pku 2002 Squares 二分查找 或者 hash
http://poj.org/problem?id=2002
首先枚举正方形的任意两点,然后有由这两点确定其他两点,确定后再到给定的点中做二分查找如果都存在,则找到了一个正方形。首先排序,然后查找,记住这里重复计算了,要除以2
推导过程转载自:http://blog.csdn.net/zsc09_leaf/article/details/6204705
- 公式推导 :
- // 如图所示,正方形的四个点分别为 (x1,y1),(x2,y2),(x3,y3),(x4,y4)
- // 假设一开始给出的点为 (x1,y1),(x2,y2) 且已排序
- // 根据全等三角形,可以得知2个蓝色△全等,2个红色△全等 (注:此处也可推右边的正方形)
- // 所以可以推出 x3=x2-(y2-y1);
- // y3=y2+(x2-x1);
- // x4=x1-(y2-y1);
- // y4=y1+(x2-y1);
- // 当然全体是排好序。 因为这样子做会导致边被重用,所以需除于 2 ,具体追究可自己详细思考
View Code
#include <iostream>
#include <cstdio>
#include <algorithm>
#define maxn 1007
using namespace std;
struct node
{
int x,y;
}p[maxn];
int n;
int cmp(node a,node b)
{
if (a.x == b.x) return a.y <b.y;
else return a.x < b.x;
}
bool bsearch(int x,int y,int l,int r)
{
while (l <= r)
{
int m = (l + r)/2;
if (p[m].x == x && p[m].y == y) return true;
else if (p[m].x > x)
{
r = m - 1;
}
else if (p[m].x < x)
{
l = m + 1;
}
else
{
if (p[m].y > y)
r = m -1;
else
l = m + 1;
}
}
return false;
}
int main()
{
int i,j,ans;
while (~scanf("%d",&n))
{
if (!n) break; 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)
{
int x3=p[j].x-(p[j].y-p[i].y);
int y3=p[j].y+(p[j].x-p[i].x);
if(!bsearch(x3,y3,0,n))
continue;
int x4=p[i].x-(p[j].y-p[i].y);
int y4=p[i].y+(p[j].x-p[i].x);
if(!bsearch(x4,y4,0,n))
continue;
ans++;
}
}
printf("%d\n",ans/2);
}
return 0;
}
hash开散列挂链实现:
View Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 1007
#define N 9997
using namespace std;
struct mode
{
int x,y;
}p[maxn];
struct node
{
int x,y;
node *next;
}*pp[N],H[N + 25];
int n,pos;
int cmp(mode a,mode b)
{
if (a.x == b.x) return a.y <b.y;
else return a.x < b.x;
}
bool bsearch(int x,int y)
{
int tmp = (x + y)%N;
if (tmp < 0) tmp = -tmp;
node *q;
for (q = pp[tmp]; q != NULL; q = q->next)
{
if (q->x == x && q->y == y)
return true;
}
return false;
}
int main()
{
int i,j,ans;
while (~scanf("%d",&n))
{
if (!n) break; ans = pos = 0;
memset(pp,0,sizeof(pp));
for (i = 0; i < n; ++i)
{
scanf("%d%d",&p[i].x,&p[i].y);
int tmp = p[i].x + p[i].y;
int l = tmp%N;
if (l < 0) l = -l;
node *t = &H[pos++];
t->x = p[i].x;
t->y = p[i].y;
t->next = pp[l];
pp[l] = t;
}
sort(p, p + n,cmp);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
int x3=p[j].x-(p[j].y-p[i].y);
int y3=p[j].y+(p[j].x-p[i].x);
if(!bsearch(x3,y3))
continue;
int x4=p[i].x-(p[j].y-p[i].y);
int y4=p[i].y+(p[j].x-p[i].x);
if(!bsearch(x4,y4))
continue;
ans++;
}
}
printf("%d\n",ans/2);
}
return 0;
}