关闭

POJ-2002 Squares解题报告

标签: eachsearchinputintegeroutputless
299人阅读 评论(0) 收藏 举报
分类:

Description

A square is a 4-sided polygon whose sides have equal length and adjacent sides form 90-degree angles. It is also a polygon such that rotating about its centre by 90 degrees gives the same polygon. It is not the only polygon with the latter property, however, as a regular octagon also has this property.

So we all know what a square looks like, but can we find all possible squares that can be formed from a set of stars in a night sky? To make the problem easier, we will assume that the night sky is a 2-dimensional plane, and each star is specified by its x and y coordinates.

Input

The input consists of a number of test cases. Each test case starts with the integer n (1 <= n <= 1000) indicating the number of points to follow. Each of the next n lines specify the x and y coordinates (two integers) of each point. You may assume that the points are distinct and the magnitudes of the coordinates are less than 20000. The input is terminated when n = 0.

Output

For each test case, print on a line the number of squares one can form from the given stars.

Sample Input

4
1 0
0 1
1 1
0 0
9
0 0
1 0
2 0
0 2
1 2
2 2
0 1
1 1
2 1
4
-2 5
3 7
0 0
5 2
0

Sample Output

1
6
1
题目大意:就是给你N个不重复的点,找出所有的不同的正方形。
题目链接:http://poj.org/problem?id=2002
方法:排序及二分查找
思路:对于点,我们可以定义一个结构体,来联系点的坐标,然后进行点升序排列,方便我们后面二分查找,我们对于每两个点来构造一个正方形的边,我们可以想象一下,在平面坐标系里面,一个正方形始终有一个边垂直X轴或者与x轴正方向成锐角,我们就把构造的边当做正方形的这种边来计算正方形的其余两点,这样就不会有重复的结果,而且不需要分情况,求其余两点坐标很好求,画图用几何算出来,求出来后进行二分查找,判断是否存在,不二分查找容易超时。
算法实现:
 
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
struct point
{
	int x;
	int y;
};
point a[1003];
int cmp(const void *a,const void *b)
{
	if( ((point*)a)->x!=((point*)b)->x )
		return ((point*)a)->x-((point*)b)->x;
	else
		return ((point*)a)->y-((point*)b)->y;
}
bool search(point p,int n)
{
	int low,high,mid;
	low=0;
	high=n-1;
	while(high-low>=0)
	{
		mid=(low+high)/2;
		if(cmp(&a[mid],&p)>0)
			high=mid-1;
		else if(cmp(&a[mid],&p)==0)
		{
			return true;
		}
		else
			low=mid+1;
	}
	return false;
}
int main()
{
	int n,i,j,sum;
	point b,c;
	while(scanf("%d",&n)!=EOF)
	{
		if(n==0)
			break;
		for(i=0;i<n;i++)
		{
			scanf("%d%d",&a[i].x,&a[i].y);
		}
		sum=0;
		qsort(a,n,sizeof(a[0]),cmp);
		for(i=0;i<n;i++)
			for(j=i+1;j<n;j++)
			{
				if(a[j].y>a[i].y)
				{
					int dx=a[j].x-a[i].x;
					int dy=a[j].y-a[i].y;
					b.x=a[i].x-dy;
					b.y=a[i].y+dx;
					c.x=a[j].x-dy;
					c.y=a[j].y+dx;
					if( search(b,n) && search(c,n))
					{
						sum++;
					}
				}	
			}
		printf("%d\n",sum);
	}
	return 0;
    
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:16557次
    • 积分:392
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:5篇
    • 译文:0篇
    • 评论:19条
    文章分类
    文章存档
    最新评论