Squares
Time Limit: 3500MS | Memory Limit: 65536K | |
Total Submissions: 16948 | Accepted: 6447 |
Description
A square is a 4-sided polygon whose sides have equal length and adjacent sides form 90-degree angles. It is also a polygon such that rotating about its centre by 90 degrees gives the same polygon. It is not the only polygon with the latter property, however,
as a regular octagon also has this property.
as a regular octagon also has this property.
So we all know what a square looks like, but can we find all possible squares that can be formed from a set of stars in a night sky? To make the problem easier, we will assume that the night sky is a 2-dimensional plane, and each star is specified by its x
and y coordinates.
Input
The input consists of a number of test cases. Each test case starts with the integer n (1 <= n <= 1000) indicating the number of points to follow. Each of the next n lines specify the x and y coordinates (two integers) of each point. You may assume that the
points are distinct and the magnitudes of the coordinates are less than 20000. The input is terminated when n = 0.
points are distinct and the magnitudes of the coordinates are less than 20000. The input is terminated when n = 0.
Output
For each test case, print on a line the number of squares one can form from the given stars.
Sample Input
4 1 0 0 1 1 1 0 0 9 0 0 1 0 2 0 0 2 1 2 2 2 0 1 1 1 2 1 4 -2 5 3 7 0 0 5 2 0
Sample Output
1 6 1
Source
题目大意:
告诉你n个点的坐标,然后让你判断这n个点一共能组成多少个正方形。
解题思路:
暴力果断T,不解释,然后,我想到了枚举一条边,通过正方形的边之间的关系来枚举其他的可能情况,再到最后的,我们只需要枚举两个顶点,然后利用二分查找在这些点中寻找是不是有满足条件的另外两个顶点就行了,当然是用二分的前提肯定是这个序列是从小到大有序排列的,所以我们先对所有点的坐标sort下,然后再用STL中的 binary_search去找就可以了。。。。注意下,关于任意四点能够构成四边形的条件,我们通过:
已知: (x1,y1) (x2,y2)
则: x3=x1+(y1-y2) y3= y1-(x1-x2)
x4=x2+(y1-y2) y4= y2-(x1-x2)
便可以得到。
代码:
# include<cstdio> # include<iostream> # include<algorithm> # include<cstring> # include<string> # include<cmath> # include<queue> # include<stack> # include<set> # include<map> using namespace std; # define inf 999999999 # define MAX 1000+4 struct node { int x; int y; }a[MAX]; int cmp ( const struct node & x,const struct node & y ) { if ( x.x == y.x ) return x.y < y.y; return x.x < y.x; } int main(void) { int n; while ( cin>>n ) { if ( n==0 ) break; for ( int i = 0;i < n;i++ ) { cin>>a[i].x>>a[i].y; } sort(a,a+n,cmp); int ans = 0; for ( int i = 0;i < n-1;i++ ) { for ( int j = i+1;j < n;j++ ) { struct node temp; temp.x = a[i].x+a[i].y-a[j].y; temp.y = a[i].y-a[i].x+a[j].x; if ( !binary_search(a,a+n,temp,cmp) ) continue; temp.x = a[j].x+a[i].y-a[j].y; temp.y = a[j].y-a[i].x+a[j].x; if ( !binary_search(a,a+n,temp,cmp) ) continue; ans++; } } cout<<ans/2<<endl; } return 0; }