题意:问n个点中可以组成多少个正方形,n<1000
思路:一开始TLE了,是hash的边,后来看网上是hash的点,hash函数是(x*x+y*y)%prime
已知正方形的两个点,求另外两个坐标:(x1,y1) 、(x2,y2)
则: x3=x1+(y1-y2) y3=y1-(x1-x2)
x4=x2+(y1-y2) y4=y2-(x1-x2)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<stdio.h> 2 #include<vector> 3 #include<string.h> 4 #include<iostream> 5 using namespace std; 6 7 const int N=1005; 8 const int prime=2003; 9 10 int x[N],y[N]; 11 vector<int> hash[prime]; 12 13 bool search(int _x,int _y){ 14 int key=(_x*_x+_y*_y)%prime; 15 int len=hash[key].size(); 16 for(int i=0;i<len;i++){ 17 int v=hash[key][i]; 18 if(x[v]==_x&&y[v]==_y) return 1; 19 } 20 return 0; 21 } 22 23 int main(){ 24 int i,j,k; 25 int n; 26 while(scanf("%d",&n)!=EOF&&n){ 27 for(i=0;i<prime;i++) hash[i].clear(); 28 for(i=0;i<n;i++){ 29 scanf("%d%d",&x[i],&y[i]); 30 int key=(x[i]*x[i]+y[i]*y[i])%prime; 31 hash[key].push_back(i); 32 } 33 int ans=0; 34 int x1,y1,x2,y2; 35 for(i=0;i<n;i++) 36 for(j=i+1;j<n;j++){ 37 if (i == j) continue; 38 x1=x[i]+y[i]-y[j]; 39 y1=y[i]-x[i]+x[j]; 40 x2=x[j]+y[i]-y[j]; 41 y2=y[j]-x[i]+x[j]; 42 if (search(x1, y1) && search(x2, y2)) ans++; 43 x1=x[i]-y[i]+y[j]; 44 y1=y[i]+x[i]-x[j]; 45 x2=x[j]-y[i]+y[j]; 46 y2=y[j]+x[i]-x[j]; 47 if (search(x1, y1) && search(x2, y2)) ans++; 48 } 49 printf("%d\n",ans/4); 50 } 51 return 0; 52 }