您的位置:首页 > 其它

poj——2002——Squares

2014-02-12 17:50 393 查看
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


算法过程:

1 将顶点按x坐标递增排序,若x相同,按y坐标递增排序,然后枚举所有边,对每一条由点p1和p2(根据排序p1 < p2)组成的边按照如下方式可唯一确定一个正方形:

1) 将边绕p1逆时针旋转90度得到点p3

2) 将边绕p2顺时针旋转90度得到点p4

则p1 p2 p3 p4组成一个正方形,设p1 = (x1,y1), p2 = (x2, y2),根据向量的旋转公式可以求出p3, p4的坐标为

p3 = (y1 - y2 + x1, x2 - x1 + y1)

p4 = (y1 - y2 + x2, x2 - x1 + y2)

2 然后搜索点p3和p4是否存在,若存在则找到一个正方形,计数加1,可以发现总是存在两条边确定的正方形是一样的,也就是说每个正方形会被发现2次,所以要将最后的计数结果除以2.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
struct node
{
int x;
int y;
}Node[1100];
int cmp(node a,node b)
{
if(a.x!=b.x)
return a.x<b.x;
else
return a.y<b.y;
}
int judge(int a,int b)//用二分法看所给点中是否有这两个点
{
int l=0,r=n-1,mid;
while(l<=r)
{
mid=(l+r)/2;
if(Node[mid].x==a&&Node[mid].y==b)
return 1;
else
{
if(Node[mid].x<a||(Node[mid].x==a&&Node[mid].y<b))
l=mid+1;
else
r=mid-1;
}
}
return 0;
}
int main()
{
while(scanf("%d",&n),n)
{
for(int i=0;i<n;i++)
scanf("%d%d",&Node[i].x,&Node[i].y);

sort(Node,Node+n,cmp);
int sum=0;
int x,y;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
x=Node[i].y-Node[j].y+Node[i].x;
y=Node[j].x-Node[i].x+Node[i].y;//判断第一个点是否存在,若存在继续找第二个点
if(!judge(x,y))
continue;
x=Node[i].y-Node[j].y+Node[j].x;
y=Node[j].x-Node[i].x+Node[j].y;
if(judge(x,y))
sum++;
}
}
printf("%d\n",sum/2);
}
return 0;
}



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