您的位置:首页 > 其它

POJ 2002 Squares

2015-02-25 12:08 337 查看
这道题思路还是挺简单的,枚举两个点,然后根据这两个点可以求出第三个点和第四个点,再根据hash判断那两个点是否存在

难的就是hash不知道怎么弄,看了别人的解题报告,才发现hash还可以这样用,用一个mod取模把key值都变为比mod小的值,至于正负值的问题用平方和解决。

具体参考:優YoU http://user.qzone.qq.com/289065406/blog/1304779855

里面讲得超详细

最后结果还要除以2,因为每个正方形算了两次(两条对角线)

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int mod=2000;
struct Point {
int x,y;
};

struct Hash{
int x,y;
Hash* next;
Hash(){
next=NULL;
}
};
int n;
Point p[1005];
Hash* hash[mod];
void Insert(Point a){
int key=(a.x*a.x+a.y*a.y)%mod;
if (!hash[key]) {
Hash* temp=new Hash;
temp->x=a.x;
temp->y=a.y;
hash[key]=temp;
}
else{
Hash* tmp=hash[key];
while(tmp->next){
tmp=tmp->next;
}
tmp->next=new Hash;
tmp->next->x=a.x;
tmp->next->y=a.y;
}
}
void init(){
for(int i=0;i<mod;i++) hash[i]=NULL;
}
int find(int x,int y){
int key=(x*x+y*y)%mod;
if (!hash[key]) return 0;
else{

if(hash[key]->x==x &&hash[key]->y==y) return 1;
Hash* tmp=hash[key];
while(tmp->next){
tmp=tmp->next;
if( tmp->x==x && tmp->y==y) return 1;
}
return 0;
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif // ONLINE_JUDGE

while(scanf("%d",&n),n){
int key;
init();
for(int i=0;i<n;i++) {
scanf("%d%d",&p[i].x,&p[i].y);
Insert(p[i]);
}

int ans=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){//根据对角线上两个点用向量求出另两个点
Point t;
int x3,y3,x4,y4;
t.x=p[j].x-p[i].x;  t.y=p[j].y-p[i].y;
x3=p[j].x+p[i].x+p[j].y-p[i].y;
y3=p[j].y+p[i].y+p[i].x-p[j].x;
x4=p[j].x+p[i].x+p[i].y-p[j].y;
y4=p[j].y+p[i].y+p[j].x-p[i].x;
if (x3%2 || y3%2 || x4%2 ||y4%2) continue;//因为给出的点都是整数,若不为整数则必不是
x3/=2;  y3/=2;  x4/=2;  y4/=2;
if (find(x3,y3) && find(x4,y4)) ans++;
}
}
printf("%d\n",ans/2);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: