您的位置:首页 > 其它

POJ 2002 Squares

2013-07-31 21:29 351 查看
题目:DescriptionA 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.InputThe 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.OutputFor 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的,但目前还不会~= =

代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;

int n;

class Point
{
public:
int x,y;
}point[1100];

bool cmp(Point a,Point b)
{
if(a.x==b.x)
return a.y<b.y;
return a.x<b.x;
}

int judge(int a,int b)
{
int left=0,right=n-1,mid;
while(left<=right)
{
mid=(left+right)/2;
if(point[mid].x==a && point[mid].y==b)
return 1;
else
if(point[mid].x<a || (point[mid].x==a && point[mid].y<b))
left=mid+1;
else
right=mid-1;
}
return 0;
}

int main()
{
int i,j;
while(scanf("%d",&n),n)
{
int sum=0,x,y,i,j;
for(i=0;i<n;i++)
scanf("%d%d",&point[i].x,&point[i].y);
sort(point,point+n,cmp);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
x=point[i].y-point[j].y+point[i].x;        //这四个求坐标的公式很重要。。。。。
y=point[j].x-point[i].x+point[i].y;
if(!judge(x,y)) continue;
x=point[i].y-point[j].y+point[j].x;
y=point[j].x-point[i].x+point[j].y;
if(judge(x,y)) sum++;
}
printf("%d\n",sum/2);
}
return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: