poj 2002 Squares
题意:
给定N个点,求出这些点一共可以构成多少个正方形。
分析:
若正方形为ABCD,A坐标为(x1, y1),B坐标为(x2, y2),则很容易可以推出C和D的坐标;
对于特定的A和B坐标,C和D可以在线段AB的左边或者右边,即有两种情况;
因此只需要枚举点A和点B,然后计算出两种对应的C和D的坐标,判断是否存在即可;
这样计算完之后得到的答案是正确答案的4倍,因为正方形的4条边都枚举了,所以答案要右移两位。
特别注意对hash的处理,这里用 平方求余法 标记散点值。
代码:
hash 做法:
const int N = 1010;
const int H = 10007;
int ptx[N], pty[N];
struct Node
{
int x;
int y;
int next;
};
Node node[N];
int cur;
int n;
long ans;
int hashTable[H];
void initHash()
{
for (int i = 0; i < H; ++i) hashTable[i] = -1;
cur = 0;
ans = 0;
}
void insertHash(int x, int y)
{
int h = (x * x + y * y) % H;
node[cur].x = x;
node[cur].y = y;
node[cur].next = hashTable[h];
hashTable[h] = cur;
++cur;
}
bool searchHash(int x, int y)
{
int h = (x * x + y * y) % H;
int next;
next = hashTable[h];
while (next != -1)
{
if (x == node[next].x && y == node[next].y) return true;
next = node[next].next;
}
return false;
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
initHash();
for (int i = 0; i < n; ++i)
{
scanf("%d%d", &ptx[i], &pty[i]);
insertHash(ptx[i], pty[i]);
}
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
int x1 = ptx[i] - (pty[i] - pty[j]);
int y1 = pty[i] + (ptx[i] - ptx[j]);
int x2 = ptx[j] - (pty[i] - pty[j]);
int y2 = pty[j] + (ptx[i] - ptx[j]);
if (searchHash(x1, y1) && searchHash(x2, y2)) ++ans;
}
}
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
int x1 = ptx[i] + (pty[i] - pty[j]);
int y1 = pty[i] - (ptx[i] - ptx[j]);
int x2 = ptx[j] + (pty[i] - pty[j]);
int y2 = pty[j] - (ptx[i] - ptx[j]);
if (searchHash(x1, y1) && searchHash(x2, y2)) ++ans;
}
}
ans >>= 2;
printf("%ld\n", ans);
}
return 0;
}
二分做法:
#define N 1000
struct Point {
int x;
int y;
};
struct Point point[N];
int n; /* 点的个数 */
/* 由于点已经按照坐标排序过,所以采用二分查找
* 搜索点(x,y)是否存在,存在返回1,否则返回0
*/
int bsearch(int x, int y)
{
int m, s, t;
s = 0;
t = n-1;
while (s <= t) {
m = (s+t)/2;
if (point[m].x == x && point[m].y == y) return 1;
if (point[m].x > x || (point[m].x == x && point[m].y > y)) {
t = m-1;
}
else {
s = m+1;
}
}
return 0;
}
int main()
{
int x, y, i, j, count;
while (scanf("%d", &n), n) {
count = 0;
for (i = 0; i < n; i++) {
scanf("%d %d", &x, &y);
//插入法对点排序,按照x从小到大,y从小到大,且x优先排列的方式
for (j = i-1; j >= 0; j--) {
if (point[j].x > x || (point[j].x == x && point[j].y > y)) {
point[j+1] = point[j];
} else {
break;
}
}
point[j+1].x = x;
point[j+1].y = y;
}
/* 枚举所有边,对每条边的两个顶点可以
* 确定一个唯一的正方形,并求出另外两个顶点的坐标
*/
for (i = 0; i < n; i++) {
for (j = (i+1); j < n; j++) {
//计算第三个点的坐标,搜索其是否存在
x = point[i].y-point[j].y+point[i].x;
y = point[j].x-point[i].x+point[i].y;
if (bsearch(x,y) == 0) {
continue;
}
//计算第四个点的坐标,搜索其是否存在
x = point[i].y-point[j].y+point[j].x;
y = point[j].x-point[i].x+point[j].y;
if (bsearch(x, y)) {
count++;
}
}
}
printf("%d\n", count/2);
}
return 0;
}