hash版本,ans/2是因为如(0,0),(0,3),(3,0),(3,3)
(0,0)(0,3)和(0,3)(3,3)都满足,但只有一个正方形:
#define N 2001
#define SUM 40005
int n;
int next[N], hash[SUM];
struct point
{
int x, y;
} p[N];
bool cmp(point a, point b)
{
if (a.x < b.x) return true;
if (a.x == b.x) return a.y < b.y;
return false;
}
bool is_exist(int x, int y)
{
int sum = MY_ABS(x + y);
int index = hash[sum];
while (index != -1) {
if ((p[index].x == x) && (p[index].y == y))
return true;
index = next[index];
}
return false;
}
int main()
{
while (scanf("%d", &n) == 1 && n) {
memset(next, -1, sizeof(next));
memset(hash, -1, sizeof(hash));
int i, j;
int ans = 0;
for (i = 0; i < n; ++i)
scanf("%d%d", &p[i].x, &p[i].y);
sort(p, p + n, cmp);
for (i = 0; i < n; ++i) {
int sum = MY_ABS(p[i].x + p[i].y);//以x和y坐标和作为hash函数
next[i] = hash[sum];
hash[sum] = i;
}
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
int x = p[i].x + (p[j].y - p[i].y);
int y = p[i].y - (p[j].x - p[i].x);
if (!is_exist(x, y)) continue;
x = p[j].x + (p[j].y - p[i].y);
y = p[j].y - (p[j].x - p[i].x);
if (!is_exist(x, y)) continue;
++ans;
}
}
printf("%d\n", ans / 2);
}
return 0;
}
/*
4
0 0
0 3
3 0
3 3
*/
二分版本:
#define N 2001
int n;
struct point
{
int x, y;
} p[N];
bool cmp(point a, point b)
{
if (a.x < b.x) return true;
if (a.x == b.x) return a.y < b.y;
return false;
}
bool binary_search(point test)
{
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = (low + high) >> 1;
if (p[mid].x == test.x && p[mid].y == test.y) return 1;
if (cmp(p[mid], test) == 1) low = mid + 1;
else high = mid - 1;
}
return false;
}
int main()
{
while (scanf("%d", &n) == 1 && n) {
int i, j;
int ans = 0;
for (i = 0; i < n; ++i)
scanf("%d%d", &p[i].x, &p[i].y);
sort(p, p + n, cmp);
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
point t;
t.x = p[i].x + (p[j].y - p[i].y);
t.y = p[i].y - (p[j].x - p[i].x);
if (!binary_search(t)) continue;
t.x = p[j].x + (p[j].y - p[i].y);
t.y = p[j].y - (p[j].x - p[i].x);
if (!binary_search(t)) continue;
++ans;
}
}
printf("%d\n", ans / 2);
}
return 0;
}
/*
4
0 0
0 3
3 0
3 3
*/