建立一张hash表,将所有的顶点加入该表
枚举正方形相邻两个顶点,求出另外两个顶点的坐标,判断这两个顶点是否在hash表中。
#include <iostream>
#include <cstdio>
using namespace std;
#define TABLE_SIZE 2003
int p[1005][2];
struct Node {
int x, y;
Node *next;
} table[TABLE_SIZE];
int hash (int x, int y)
{
return (x * x + y * y) % TABLE_SIZE;
}
void insert (int x, int y) {
int key = hash(x, y);
Node * newNode = new Node;
newNode->x = x;
newNode->y = y;
newNode->next = table[key].next;
table[key].next = newNode;
}
bool search (int x, int y) {
Node * cur = table[hash(x, y)].next;
while (cur != NULL) {
if (cur->x == x && cur->y == y) return true;
cur = cur->next;
}
return false;
}
int main()
{
int n, i, j;
while (scanf ("%d", &n) && n) {
for (i = 0; i < TABLE_SIZE; i++) table[i].next = NULL;
for (i = 0; i < n; i++) {
scanf ("%d %d", &p[i][0], &p[i][1]);
insert (p[i][0], p[i][1]);
}
int x1, y1, x2, y2, ans = 0;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (i == j) continue;
x1 = p[i][0] + p[i][1] - p[j][1];
y1 = p[i][1] - p[i][0] + p[j][0];
x2 = p[j][0] + p[i][1] - p[j][1];
y2 = p[j][1] - p[i][0] + p[j][0];
if (search(x1, y1) && search(x2, y2)) ans++;
x1 = p[i][0] - p[i][1] + p[j][1];
y1 = p[i][1] + p[i][0] - p[j][0];
x2 = p[j][0] - p[i][1] + p[j][1];
y2 = p[j][1] + p[i][0] - p[j][0];
if (search(x1, y1) && search(x2, y2)) ans++;
}
}
printf ("%d\n", ans / 4);
for (i = 0; i < TABLE_SIZE; i++) {
while (table[i].next != NULL) {
Node * tmp = table[i].next;
table[i].next = tmp->next;
delete tmp;
}
}
}
return 0;
}