POJ 2002 Squares 解题报告 哈希

POJ 2002 Squares 解题报告

题意:给出平面中的点,求用这些点最多能构成多少个正方形。
解题思路:正常思路直接暴力肯定超时,看了别人的blog,其实就是用离散化的方法极大减小了遍历时间。其他地方就没什么难的了。还发现一点:new分配的类会自动初始化,malloc只分配空间,类构造函数没用,next指针还得自己赋成NULL。
在这里插入图片描述

#include<iostream>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<iostream>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<map>
#include<stack>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<fstream>
#include<iomanip>
#pragma warning(disable:4996)
#define INF 0x3f3f3f3f
#define ll long long
#define PI acos(-1.0)
const int N = 1000010;
const int maxn = 1e9;
using namespace std;
const int prime = 1999;//2000内最大素数
struct node {
	int x, y;
};
struct square {
	int x, y;
	square* next;
	square()
	{
		next = NULL;
	}
};
node pos[1005];//放原始数据
square* ha[2005];
void in(int t)
{
	int key = (pos[t].x * pos[t].x + pos[t].y * pos[t].y) % prime + 1;//+1是为了避开哈希表下标0
	if (NULL == ha[key])
	{
		square* tem = (square*)malloc(sizeof(square));
		tem->x = pos[t].x;
		tem->y = pos[t].y;
		tem->next = NULL;
		ha[key] = tem;
	}
	else
	{
		square* tem = ha[key];
		while (tem->next)
		{
			tem = tem->next;
		}
		tem->next = (square*)malloc(sizeof(square));
		tem->next->x = pos[t].x;
		tem->next->y = pos[t].y;
		tem->next->next = NULL;
	}
}
bool judge(int x, int y)
{
	int key = (x * x + y * y) % prime + 1;
	if (NULL == ha[key])
	{
		return false;
	}
	else
	{
		square* tem = ha[key];
		while (tem != NULL)
		{
			if (x == tem->x && y == tem->y)
				return true;
			tem = tem->next;
		}
	}
	return false;
}
int main()
{
	int n;
	while (cin >> n && n)
	{
		memset(ha, 0, sizeof(ha));
		for (int i = 1; i <= n; i++)
		{
			cin >> pos[i].x >> pos[i].y;
			in(i);
		}
		int ans = 0;
		for (int i = 1; i <= n - 1; i++)
		{
			for (int j = i + 1; j <= n; j++)
			{
				int a = pos[j].x - pos[i].x;
				int b = pos[j].y - pos[i].y;
				int x3 = pos[i].x + b;
				int y3 = pos[i].y - a;
				int x4 = pos[j].x + b;
				int y4 = pos[j].y - a;
				if (judge(x3, y3) && judge(x4, y4))
					ans++;
				x3 = pos[i].x - b;
				y3 = pos[i].y + a;
				x4 = pos[j].x - b;
				y4 = pos[j].y + a;
				if (judge(x3, y3) && judge(x4, y4))
					ans++;
			}
		}
		cout << ans / 4 << endl;
	}
}



发布了64 篇原创文章 · 获赞 0 · 访问量 1452

猜你喜欢

转载自blog.csdn.net/weixin_45566331/article/details/104675708