POJ-2002,3432(搜点,hash或二分)

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
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值