您的位置:首页 > 编程语言 > PHP开发

pku 2002 -- Squares(二分,几何)

2011-02-24 12:22 381 查看
 SquaresTime Limit: 3500MS Memory Limit: 65536K
Total Submissions: 8787 Accepted: 3051

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

 

 



 

//////////////////////////////////////////////////////////////////////////
//	184K	1688MS
//	公式推导 :
//	如图所示,正方形的四个点分别为 (x1,y1),(x2,y2),(x3,y3),(x4,y4)
//	假设一开始给出的点为  (x1,y1),(x2,y2) 且已排序
//	根据全等三角形,可以得知2个蓝色△全等,2个红色△全等 (注:此处也可推右边的正方形)
//	所以可以推出 x3=x2-(y2-y1);
//				 y3=y2+(x2-x1);
//				 x4=x1-(y2-y1);
//				 y4=y1+(x2-y1);
//	当然全体是排好序。 因为这样子做会导致边被重用,所以需除于 2 ,具体追究可自己详细思考
//////////////////////////////////////////////////////////////////////////
#include<iostream>
using namespace std;
struct point
{
int x,y;
point(int a,int b)
{
x=a;
y=b;
}
point(){}
}num[1010];

int n;

int cmp(const void *a,const void *b)
{
if((*(point*)a).x==(*(point*)b).x)
return (*(point*)a).y-(*(point*)b).y;
return (*(point*)a).x-(*(point*)b).x;
}
bool next(point a,point b)				//二分查找的比较函数
{
if(a.x==b.x)
return a.y<b.y;
return a.x<b.x;
}
bool mysearch(point p)					//二分查找
{
int mid,high=n,low=0;
while(low<=high)
{
mid=(low+high)/2;
if(num[mid].x==p.x&&num[mid].y==p.y)
return true;
else if(next(num[mid],p))
low=mid+1;
else
high=mid-1;
}
return false;
}
int main()
{
int i,j,x3,y3,x4,y4;
while(scanf("%d",&n)&&n)
{
for(i=0;i<n;i++)
scanf("%d%d",&num[i].x,&num[i].y);

qsort(num,n,sizeof(num[0]),cmp);

int ans=0;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
x3=num[j].x-(num[j].y-num[i].y);
y3=num[j].y+(num[j].x-num[i].x);
if(!mysearch( point(x3,y3) ))
continue;
x4=num[i].x-(num[j].y-num[i].y);
y4=num[i].y+(num[j].x-num[i].x);
if(!mysearch( point(x4,y4) ))
continue;
ans++;
}

printf("%d/n",ans/2);
}
}


 

 

 

 

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