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
题意
给定n个点,求平行于坐标轴的矩形的最小面积,如果没有就输出-1。
思路
需要枚举对角线的两点,判断其他两点是否存在即可。复杂度为O(n2)
代码
#include<iostream>
#include<cstdio>
#include<map>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int MAXN=1e3+5;
const ll INF=(ll)(1<<30)*(1<<30);
pair<int,int> p[MAXN];
ll min(ll a,ll b){
return a<b?a:b;
}
int main(){
int n;
scanf("%d",&n);
map<pair<int,int>,bool> mp;
for(int i=0;i<n;i++){
scanf("%d%d",&p[i].first,&p[i].second);
mp[p[i]]=true;
}
ll dx=0,dy=0,ans=INF;
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(mp[{p[i].first,p[j].second}] && mp[{p[j].first,p[i].second}]){
dx=abs(p[i].first-p[j].first);
dy=abs(p[i].second-p[j].second);
ans=min(ans,dx*dy);
}
}
}
if(ans==INF) puts("-1");
else printf("%lld\n",ans);
return 0;
}