【hihoCoder 1442 --- Smallest Rectangle】

【hihoCoder 1442 --- Smallest Rectangle】

题目来源:点击进入【hihoCoder 1442 — Smallest Rectangle】

Description

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.

Input

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

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

Sample Input

9
0 0
0 1
0 4
1 0
1 1
1 4
4 0
4 1
4 4

Sample Output

1

解题思路

根据题意需要找的是边与轴平行的矩形,那么我们只需要遍历对角的两个点。
又因为四个点的坐标实际上都和对角两个点相关。所以当我们知道对角两个点时,就可以得到其他两个点,然后判断是否存在,以及标记面积。

AC代码(C++):

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int MAXN = 1e3+5;
const int MOD = 1e9+7;
pair<int,int> p[MAXN];

int main(){
    SIS;
    ll n,x,y,ans=INF;
    map<pair<int,int>,bool> m;
    cin >> n;
    for(int i=0;i<n;i++){
        cin >> p[i].first >> p[i].second;
        m[p[i]]=true;
    }
    for(int i=0;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(p[i].first==p[j].first || p[i].second==p[j].second) continue;
            if(m[{p[i].first,p[j].second}] && m[{p[j].first,p[i].second}]){
                x=abs(p[i].first-p[j].first);
                y=abs(p[i].second-p[j].second);
                ans=min(ans,x*y);
            }
        }
    }
    if(ans == INF) cout << -1 << endl;
    else cout << ans << endl;
    return 0;
}

你可能感兴趣的:(ACM)