题意:求该图节点可连成中有多少个正方形。
分析:2000个点每次选两个点连边然后构造正方形,但时间复杂度2000*2000*t(判断是否存在点),如果用map来判断点是否存在,O(logn)=45的时间复杂度也会超时(本人超过),看了别人的做法,才知道是hash来做,试了下,果然,hashO(1)的时间复杂度果然名不虚传,直接AC。
其实,hash结构简单挺好学的,关键是hash函数,不多说,上代码.
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
struct node
{
int x,y;
bool operator<(const node &a)const
{
if(x==a.x)return y<a.y;
return x<a.x;
}
}da[2005];
int nex[2005],hash[20005];
bool _search(node &tmp)
{
int key=abs(tmp.x+tmp.y);
for(int e=hash[key];~e;e=nex[e])
{
if(da[e].x==tmp.x&&da[e].y==tmp.y)
return 1;
}
return 0;
}
int main()
{
int n,i,j;
while(~scanf("%d",&n))
{
memset(hash,-1,sizeof hash);
for(i=0;i<n;i++)
scanf("%d%d",&da[i].x,&da[i].y);
sort(da,da+n);
for(i=0;i<n;i++)
{
int key=abs(da[i].x+da[i].y);
nex[i]=hash[key];
hash[key]=i;
}
int ans=0;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
node tmp;
tmp.x=da[i].x+da[i].y-da[j].y;
tmp.y=da[i].y-da[i].x+da[j].x;
if(!_search(tmp))continue;
tmp.x=da[j].x+da[i].y-da[j].y;
tmp.y=da[j].y-da[i].x+da[j].x;
if(!_search(tmp))continue;
ans++;
}
printf("%d\n",ans/2);
}
return 0;
}