Squares
Time Limit: 3500MS | Memory Limit: 65536K | |
Total Submissions: 18718 | Accepted: 7209 |
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 (坐标).
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
因为坐标有负数,所以在生成key值时要注意一下,思路很简单,先枚举两个点所有的组合,然后通过数学公式的换算来计算另外两个点,然后用哈希表查找一下那两个点是否存在。因为我们把所有点都枚举过一次,所以一个正方形被我们找过四次,把最后结果除以四就好了。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<map>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<new>
using namespace std;
const int mod = 100007;
struct node
{
int x;
int y;
}dian[1234];
node *hs[mod+6];
bool f(int xx,int yy,int xxx,int yyy)
{
long long int t;
int flag=0;
t=xx*xx+yy*yy;
t=t%mod+1;
while(hs[t])
{
if(hs[t]->x==xx&&hs[t]->y==yy)
{
flag++;
break;
}
t++;
}
t=xxx*xxx+yyy*yyy;
t=t%mod+1;
while(hs[t])
{
if(hs[t]->x==xxx&&hs[t]->y==yyy)
{
flag++;
break;
}
t++;
}
if(flag==2) return 1;
else return 0;
}
int main()
{
int n;
while(cin>>n&&n)
{
memset(hs,0,sizeof(hs));
for(int i=1;i<=n;i++)
{
scanf("%d%d",&dian[i].x,&dian[i].y);
long long int key=(dian[i].x*dian[i].x)+(dian[i].y*dian[i].y);
key=key%mod+1;
if(hs[key]) while(hs[key]) ++key;
// hs[key]=new node;
hs[key]=&dian[i];
}
int sum=0;
for(int i=2;i<=n;i++)
for(int j=1;j<i;j++)
{
int x1=dian[i].x,x2=dian[j].x,y1=dian[i].y,y2=dian[j].y,x3,x4,y3,y4;
x3=x1+(y1-y2);
x4=x2+(y1-y2);
y3=y1-(x1-x2);
y4=y2-(x1-x2);
if(f(x3,y3,x4,y4)) sum++;
x3=x1-(y1-y2);
x4=x2-(y1-y2);
y3=y1+(x1-x2);
y4=y2+(x1-x2);
if(f(x3,y3,x4,y4)) sum++;
}
cout<<sum/4<<endl;
}
return 0;
}