题意:给定n个相异整数点,求能构成多少个正方形。
其实这题挺简单的,经过思考可以发现,我们可以通过枚举两个点(或者说一条边),然后求出可能构成正方形的另外两个点,然后判断是不是在给你的点集中就行了。求点问题是一个数学问题,判断要用到hash表。用开散列法(拉链法).
#include<stdio.h>
#include<string.h>
#include <iostream>
using namespace std;
#define MAXHASH 1000003
#define NN 1004
typedef struct node{
int x, y;
struct node *nxt;
}NODE;
NODE po[NN];
NODE *head[MAXHASH];
int n;
int hash(NODE p){
int h = p.x * 20000 + p.y;
h %= MAXHASH;
if(h < 0) h += MAXHASH;
return h;
}
void Init(){
int i, h;
memset(head, 0, sizeof(head));
for (i = 1; i <= n; i++){
h = hash(po[i]);
po[i].nxt = head[h];
head[h] = po + i;
}
}
int find(NODE p1){
int h = hash(p1);
for (NODE *p = head[h]; p; p = p->nxt){
if(p->x == p1.x && p->y == p1.y){
return 1;
}
}
return 0;
}
void Solve(){
NODE p1, p2, p3, p4;
int i, j;
int cnt = 0;
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
if(i == j) continue;
//公式:x3=x1+(y1-y2);y3=y1-(x1-x2); x4=x2+(y1-y2);y4=y2-(x1-x2)(在直线AB上方)
// 或x3=x1-(y1-y2);y3=y1+(x1-x2); x4=x2-(y1-y2);y4=y2+(x1-x2)(在直线AB下方)
p1 = po[i];
p2 = po[j];
p3.x = p1.x + (p1.y - p2.y);
p3.y = p1.y - (p1.x - p2.x);
p4.x = p2.x + (p1.y - p2.y);
p4.y = p2.y - (p1.x - p2.x);
if(find(p3) && find(p4)) cnt++;
}
}
printf("%d\n", cnt / 4);
}
int main() {
int i;
while(scanf("%d", &n)!= EOF){
if(n == 0) break;
for (i = 1; i <= n; i++){
scanf("%d%d", &po[i].x, &po[i].y);
}
Init();
Solve();
}
return 0;
}