題目大意:給你一堆點,問你能組成幾個正方形。
思路:一開始想的是用對角線的長度來當哈希的key,但判斷正方形會太複雜,然後就去找了一下正方形的判斷方法,發現
已知: (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)
就是枚舉兩個點,然後算出另外兩個點。在哈希表中看看能不能找到這兩個點。如果只採取其中一個公式的話,切記點的座標要排序再哈希(具體原因我也不知道,但自己舉了很多樣例確實是這樣),你也可以把兩個公式都用上,兩個if得到答案。
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<bitset>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#define INF 0x3f3f3f3f
#define CLR(x,y) memset(x,y,sizeof(x))
#define LC(x) (x<<1)
#define RC(x) ((x<<1)+1)
#define MID(x,y) ((x+y)>>1)
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
const double PI=acos(-1.0);
int fact[10]= {1,1,2,6,24,120,720,5040,40320,362880};
const int maxn= 1010;
const int mod = 100019;
int n;
struct dian {
int x,y;
} a[maxn];
int hash[mod+10];
int next[maxn];
int gethash(int i) {
return (a[i].x*a[i].x%mod+a[i].y*a[i].y%mod)%mod;
}
bool find(int x,int y){
int hashval=(x*x%mod+y*y%mod)%mod;
for(int i=hash[hashval];i!=-1;i=next[i])
{
if(a[i].x==x&&a[i].y==y)return true;
}
return false;
}
bool cmp(dian aa,dian bb){
if(aa.x!=bb.x)
return aa.x<bb.x;
return aa.y<bb.y;
}
int main(){
while(scanf("%d",&n),n)
{
int ans=0;
memset(hash,-1,sizeof(hash));
for(int i=1;i<=n;i++)
{
scanf("%d%d",&a[i].x,&a[i].y);
}
sort(a+1,a+1+n,cmp);//非常重要 沒有則wa
for(int i=1;i<=n;i++)
{
int hashval=gethash(i);//映射到哈希表裏
next[i]=hash[hashval];
hash[hashval]=i;
}
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
int x=a[i].x-a[j].y+a[i].y;//算出第一個點
int y=a[i].y+a[j].x-a[i].x;
if(!find(x,y))continue;//查找
x=a[j].x-a[j].y+a[i].y;//第二個點
y=a[j].y+a[j].x-a[i].x;
if(!find(x,y))continue;//查找
ans++;
}
}
printf("%d\n",ans/2);//由於有重複計算 所以要除以二
}
}
Time Limit: 3500MS | Memory Limit: 65536K | |
Total Submissions: 21208 | Accepted: 8136 |
Description
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
Output
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