SET解法(此法在POJ会TLE,哈希解法在后面)
题目的意思是
给n个点,让在n个点中找四个点为正方形的方案数,同四个点旋转,反转什么的只能算一个
一共有1000个点
如果直接枚举是
1000×1000×1000×1000的复杂度
每次枚举两个点,再用两个点算出另两个点的坐标,看这两个点的坐标存不存在
这样的复杂度就是1000×1000×log(1000)因为我是用set 实现查找的
已知1,2点的坐标,这里我们确认1,2是相邻的两点
这样一个正方形会被计算四次
已知: (x1,y1) (x2,y2)
则: 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)
接下来上代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<set>
class coordinate
{
public:
int x,y;
};
using namespace std;
coordinate a[1010];
bool operator<(coordinate a,coordinate b)
{
if(a.x==b.x)
{
return a.y<b.y;
}
return a.x<b.x;
}
int main()
{
int n;
while (scanf("%d",&n),n)
{
set<coordinate>mySet;
for (int i = 0; i < n; i++)
{
coordinate tt;
scanf("%d %d",&tt.x,&tt.y);
a[i]=tt;
mySet.insert(tt);
}
int counter=0;
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
//coordinate[i] coordinate[j]
coordinate t1,t2;
t1.x=a[i].x+a[i].y-a[j].y;
t1.y=a[i].y-a[i].x+a[j].x;
t2.x=a[j].x+a[i].y-a[j].y;
t2.y=a[j].y-a[i].x+a[j].x;
if(mySet.count(t1)&&mySet.count(t2))
{
/*cout<<a[i].x<<' '<<a[i].y<<endl;
cout<<a[j].x<<' '<<a[j].y<<endl;
cout<<t1.x<<' '<<t1.y<<endl;
cout<<t2.x<<' '<<t2.y<<endl;
cout<<endl;*/
counter++;
}
t1.x=a[i].x-a[i].y+a[j].y;
t1.y=a[i].y+a[i].x-a[j].x;
t2.x=a[j].x-a[i].y+a[j].y;
t2.y=a[j].y+a[i].x-a[j].x;
if(mySet.count(t1)&&mySet.count(t2))
{
/*cout<<a[i].x<<' '<<a[i].y<<endl;
cout<<a[j].x<<' '<<a[j].y<<endl;
cout<<t1.x<<' '<<t1.y<<endl;
cout<<t2.x<<' '<<t2.y<<endl;
cout<<endl;*/
counter++;
}
}
}
printf("%d\n",counter/4);
}
return 0;
}
HASH解法:
用哈希表替换掉set,就可以在poj过了
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<list>
using namespace std;
class coordinate
{
public:
int x,y;
};
class T
{
public:
list<coordinate>Hash[60000];//2*x+y
void Insert(coordinate t)
{
Hash[(t.x*2+t.y+60000)%60000].push_back(t);
}
void Clear()
{
for(int i=0;i<60000;i++)
{
Hash[i].clear();
}
}
bool Count(coordinate t)
{
int HashNum=(t.x*2+t.y+60000)%60000;
for(list<coordinate>::iterator i=Hash[HashNum].begin();i!=Hash[HashNum].end();i++)
{
if(i->x==t.x&&i->y==t.y)
{
return true;
}
}
return false;
}
}MySet;
coordinate a[1010];
bool operator<(coordinate a,coordinate b)
{
if(a.x==b.x)
{
return a.y<b.y;
}
return a.x<b.x;
}
int main()
{
int n;
while (scanf("%d",&n),n)
{
MySet.Clear();
for (int i = 0; i < n; i++)
{
coordinate tt;
scanf("%d %d",&tt.x,&tt.y);
a[i]=tt;
MySet.Insert(tt);
}
int counter=0;
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
coordinate t1,t2;
t1.x=a[i].x+a[i].y-a[j].y;
t1.y=a[i].y-a[i].x+a[j].x;
t2.x=a[j].x+a[i].y-a[j].y;
t2.y=a[j].y-a[i].x+a[j].x;
if(MySet.Count(t1)&&MySet.Count(t2))
{
counter++;
}
t1.x=a[i].x-a[i].y+a[j].y;
t1.y=a[i].y+a[i].x-a[j].x;
t2.x=a[j].x-a[i].y+a[j].y;
t2.y=a[j].y+a[i].x-a[j].x;
if(MySet.Count(t1)&&MySet.Count(t2))
{
counter++;
}
}
}
printf("%d\n",counter/4);
}
return 0;
}