题意:给定一堆点,判断能构成多少个正方形
枚举前两个点,根据前两个点推算出后两个点,看后两个点在不在表中,若在,ans++,记得最后ans除以4,多算了4倍。
code:
#include <iostream>
#include <fstream>
using namespace std;
const int HASH_BASE = 1007;
int n;
int map[1000][2];
int hashTable[HASH_BASE];
int cur;
int ans;
struct HashNode{
int x;
int y;
int next;
};
HashNode node[1005];
void initHash()
{
cur = 0;
ans = 0;
for (int i = 0; i < HASH_BASE; i++)
{
hashTable[i] = -1;
}
}
void insertHash(int x, int y)
{
int value = (x*x + y*y) % HASH_BASE;
node[cur].x = x;
node[cur].y = y;
node[cur].next = hashTable[value];
hashTable[value] = cur;
cur++;
}
bool searchHash(int x, int y)
{
int value = (x*x + y*y) % HASH_BASE;
int next = hashTable[value];
while (next != -1)
{
if (x == node[next].x && y == node[next].y)
return true;
next = node[next].next;
}
return false;
}
int main()
{
//fstream in("input.txt");
while (cin >> n)
{
if (!n)
break;
initHash();
memset(map, 0, sizeof(map));
for (int i = 0; i < n; i++)
{
cin >> map[i][0] >> map[i][1];//x,y
insertHash(map[i][0],map[i][1]);
}
//direction one
/*
x3 = x1+(y1-y2)
y3 = y1-(x1-x2)
x4 = x2+(y1-y2)
y4 = y2-(x1-x2)
*/
for (int i = 0; i < n; i++)//x1,y1
{
for (int j = i+1; j < n; j++)//x2,y2
{
int x3 = map[i][0] + (map[i][1] - map[j][1]);
int y3 = map[i][1] - (map[i][0] - map[j][0]);
int x4 = map[j][0] + (map[i][1] - map[j][1]);
int y4 = map[j][1] - (map[i][0] - map[j][0]);
if (searchHash(x3, y3) && searchHash(x4, y4))
ans++;
}
}
//direction two
/*
x3 = x1-(y1-y2)
y3 = y1+(x1-x2)
x4 = x2-(y1-y2)
y4 = y2+(x1-x2)
*/
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
int x3 = map[i][0] - (map[i][1] - map[j][1]);
int y3 = map[i][1] + (map[i][0] - map[j][0]);
int x4 = map[j][0] - (map[i][1] - map[j][1]);
int y4 = map[j][1] + (map[i][0] - map[j][0]);
if (searchHash(x3, y3) && searchHash(x4, y4))
ans++;
}
}
ans >>= 2;
cout << ans << endl;
}
//system("pause");
return 0;
}