POJ 2002 Squares

题目:

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. 

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.

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

要解这道题需要的数学知识:
已知:p1=(x1,y1),p2=(x2,y2)找在坐标轴上所对应的正方形的的另外两个坐标p3=(x3,y3),p4=(x4,y4)。
则有公式:
x3=x1+(y1-y2) y3=y1-(x1-x2)
x4=x2+(y1-y2) y4=y2-(x1-x2)

x3=x1-(y1-y2) y3=y1+(x1-x2)
x4=x2-(y1-y2) y4=y2+(x1-x2)

先枚举出两个点p1,p2。在通过数学公式求解出p3,p4点,再用二分法看所给点中是否有p3,p4这两个点。
看了别人的解法,还有用hash的,但目前还不会~= =

代码:
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 using namespace std;
 5 
 6 int n;
 7 
 8 class Point
 9 {
10 public:
11     int x,y;
12 }point[1100];
13 
14 bool cmp(Point a,Point b)
15 {
16     if(a.x==b.x)
17         return a.y<b.y;
18     return a.x<b.x;
19 }
20 
21 int judge(int a,int b)
22 {
23     int left=0,right=n-1,mid;
24     while(left<=right)
25     {
26         mid=(left+right)/2;
27         if(point[mid].x==a && point[mid].y==b)
28                return 1;
29         else
30             if(point[mid].x<a || (point[mid].x==a && point[mid].y<b))
31                 left=mid+1;
32             else
33                 right=mid-1;
34     }
35     return 0;
36 }
37 
38 int main()
39 {
40     int i,j;
41     while(scanf("%d",&n),n)
42     {
43         int sum=0,x,y,i,j;
44         for(i=0;i<n;i++)
45             scanf("%d%d",&point[i].x,&point[i].y);
46         sort(point,point+n,cmp);
47         for(i=0;i<n;i++)
48             for(j=i+1;j<n;j++)
49         {
50             x=point[i].y-point[j].y+point[i].x;        //这四个求坐标的公式很重要。。。。。
51             y=point[j].x-point[i].x+point[i].y;
52             if(!judge(x,y)) continue;
53             x=point[i].y-point[j].y+point[j].x;
54             y=point[j].x-point[i].x+point[j].y;
55             if(judge(x,y)) sum++;
56         }
57         printf("%d
",sum/2);
58     }
59     return 0;
60 }


原文地址:https://www.cnblogs.com/teilawll/p/3228894.html