POJ 2002 Squares(簡單的二分)

Squares
Time Limit: 3500MS   Memory Limit: 65536K
Total Submissions: 16948   Accepted: 6447

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

Source


題目大意:

告訴你n個點的座標,然後讓你判斷這n個點一共能組成多少個正方形。

解題思路:

暴力果斷T,不解釋,然後,我想到了枚舉一條邊,通過正方形的邊之間的關係來枚舉其他的可能情況,再到最後的,我們只需要枚舉兩個頂點,然後利用二分查找在這些點中尋找是不是有滿足條件的另外兩個頂點就行了,當然是用二分的前提肯定是這個序列是從小到大有序排列的,所以我們先對所有點的座標sort下,然後再用STL中的 binary_search去找就可以了。。。。注意下,關於任意四點能夠構成四邊形的條件,我們通過:

已知: (x1,y1)  (x2,y2)

則:   x3=x1+(y1-y2)   y3= y1-(x1-x2)

x4=x2+(y1-y2)   y4= y2-(x1-x2)

便可以得到。

代碼:

# include<cstdio>
# include<iostream>
# include<algorithm>
# include<cstring>
# include<string>
# include<cmath>
# include<queue>
# include<stack>
# include<set>
# include<map>

using namespace std;

# define inf 999999999
# define MAX 1000+4

struct node
{
    int x;
    int y;
}a[MAX];

int cmp ( const struct node & x,const struct node & y )
{
    if ( x.x == y.x )
        return x.y < y.y;
    return x.x < y.x;
}

int main(void)
{
    int n;
    while ( cin>>n )
    {
        if ( n==0 )
            break;
        for ( int i = 0;i < n;i++ )
        {
            cin>>a[i].x>>a[i].y;
        }
        sort(a,a+n,cmp);
        int ans = 0;
        for ( int i = 0;i < n-1;i++ )
        {
            for ( int j = i+1;j < n;j++ )
            {
                struct node temp;
                temp.x = a[i].x+a[i].y-a[j].y;
                temp.y = a[i].y-a[i].x+a[j].x;

                if ( !binary_search(a,a+n,temp,cmp) )
                    continue;

                temp.x = a[j].x+a[i].y-a[j].y;
                temp.y = a[j].y-a[i].x+a[j].x;

                if ( !binary_search(a,a+n,temp,cmp) )
                    continue;

                ans++;

            }
        }
        cout<<ans/2<<endl;

    }




	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章