D - Rectangles
题目
Time Limit: 4 sec
Memory Limit: 1024 MB
大意:
从给的N个二维点坐标,找到能以坐标点为矩形顶点的最多矩形个数
Sample Input 1:
6
0 0
0 1
1 0
1 1
2 0
2 1
Sample Output 1:
3
There are three such rectangles:
the rectangle whose vertices are Points 1, 2, 3, 4,
the rectangle whose vertices are Points 1, 2, 5, 6,
and the rectangle whose vertices are Points 3, 4, 5, 6.
另外一个例子answer为 1
STL
make_pair
Constructs a pair object with its first element set to x and its second element set to y.
The template types can be implicitly deduced from the arguments passed to make_pair.
pair objects can be constructed from other pair objects containing different types, if the respective types are implicitly convertible.
即 pair模板类型可以从传递给 make_pair
binary_search
模板:binary_search(a[],a[]+size , x)
参数:
a[]: 数组首地址
size:数组元素个数
x:需要查找的值
功能: 在数组中以二分法检索的方式查找,若在数组(要求数组元素非递减)中查找到indx元素则真,若查找不到则返回值为假。
分析
本题给的数据量少且给的时间多(4 sec), 所以本题可以搜索得到结果,即可以采用O(N^2 log N)来实现。
我们先根据矩阵实现的唯一性,先确定左下和右上两个点的坐标,然后就可以查找是否有满足的其他两个点可以实现矩阵。当然查找的过程肯定要采用二分查找O(log N)的方式,使用二分要先进行排序,而因为本题点二维点有x,y两个坐标,所以用pair的类型更加方便。
Also If we compress the coordinates beforehand, we can find it in an O(1) time.
Editorial by en_translator
code:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector< pair<int,int> > v(n);
for(int i=0;i<n;i++)
cin >> v[i].first >> v[i].second;
sort(v.begin(),v.end());
int ans = 0;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
if(v[i].first < v[j].first && v[i].second < v[j].second){ // 满足左下和右上的条件
if(binary_search(v.begin(), v.end(), make_pair(v[i].first, v[j].second))
&& binary_search(v.begin(), v.end(), make_pair(v[j].first, v[i].second)))
// 二分查找是否存在左上和右下的点
ans++;
}
cout << ans << endl;
}