【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 <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <queue>
#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;
}