hihocoder-Week219-Smallest Rectangle

hihocoder-Week219-Smallest Rectangle 

题目1 : Smallest Rectangle

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

You are given N 2D points P1, P2, ... PN. If there is a rectangle satisfying that its 4 vertices are in the given point set and its 4 sides are parallel to the axis we say the rectange exists.

Find the smallest exsisting rectange and output its area.

输入

The first line contains an integer N. (1 <= N <= 1000)

The following N lines each contain 2 integers Xi and Yi denoting a point (Xi, Yi). (0 <= Xi, Yi <= 1000000)

输出

Output the smallest area. If no rectangle exsists output -1.

样例输入
9  
0 0  
0 1   
0 4  
1 0  
1 1  
1 4  
4 0  
4 1  
4 4
样例输出
1

题解:

  采用Hash的方式,针对每两个P1(x1, y1), P2(x2, y2),查找P(x1, y2), P(x2, y1)是否存在即可。 

  时间复杂度:O(N^2), 

#include <cstdio> 
#include <iostream> 
#include <set>  
#include <cmath> 
using namespace std;   

const int MAXN = 1000 + 10; 
const int MAXM = 1000001; 

int x[MAXN]; 
int y[MAXN]; 

int main(){  

    int cnt;  
    scanf("%d", &cnt);   

    set<long long> mp; 
    for(int i=0; i<cnt; ++i)
    {
        scanf("%d %d", &x[i], &y[i]);  
        mp.insert(x[i]*MAXM + y[i]); 
    }  

    long long ans = (long long)MAXM * MAXM;  

    for(int i=0; i<cnt; ++i)
    {
        for(int j=i+1; j<cnt; ++j)
        {
            if(x[i] != x[j] && y[i] != y[j])
            {
                if(mp.count(x[i]*MAXM + y[j]) != 0 && 
                   mp.count(x[j]*MAXM + y[i]) != 0)
                { 
                    long long area = (long long)abs(x[i] - x[j]) * abs(y[i] - y[j]); 
                    if(ans > area)
                    {
                        ans =area; 
                    }
                }
            }
        }
    }
    if (ans == (long long)MAXM*MAXM)
    {
        ans = -1; 
    }
    printf("%lld
", ans);

    return 0; 
} 

  

原文地址:https://www.cnblogs.com/zhang-yd/p/9614844.html