Count Squares HDU 3432

題目鏈接:


Given a set of points with integer coordinates xi, yi, i = 1...N, your program must find all the squares having each of four vertices in one of these points.

Input

Input file contains integer N followed by N pairs of integers xi yi.

Constraints

-104 ≤ xi, yi ≤ 104, 1 ≤ N ≤ 2000. All points in the input are different.

Output

Output file must contain a single integer — number of squares found.

Sample Input

Sample input 1
4 0 0 4 3 -3 4 1 7
Sample input 2
9
1 1  1 2  1 3  
2 1  2 2  2 3  
3 1  3 2  3 3

Sample Output

Sample output 1
1
Sample output 2
6

Hint

Bold texts appearing in the sample sections are informative and do not form part of the actual data. 

題意:

給你 n 個點,判斷存在多少個正方形.

思路:

枚舉兩個點 || 正方形的邊, 然後根據枚舉的兩個點算出未知的兩個點,然後在給出的點中查找這兩個點是否出現,如果出現則說明存在正方形,反之說明不存在.

查找的話可以使用hash 或者 map, 但是map 我沒有試過,不知道具體能不能行.

代碼:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;

const int prime = 1999;

typedef class{
public:
    int x,y;
}node;

typedef class Hash{//手動寫hash表
public:
    int x, y;
    Hash *next;
    Hash(){
        next = 0;
    }
}Hash;

node a[2000+10];
Hash *has[prime];

void insert_hash(int pos){
//hash的對應法則,我們採用平方和
    int k = (a[pos].x * a[pos].x + a[pos].y * a[pos].y) % prime + 1;
    if(!has[k]){
        Hash *tmp = new Hash;
        tmp->x = a[pos].x;
        tmp->y = a[pos].y;
        has[k] = tmp;
    }else {
        Hash * tmp = has[k];//如果這個點出現過
        while(tmp->next)
            tmp = tmp->next;
        tmp->next = new Hash;
        tmp->next->x = a[pos].x;
        tmp->next->y = a[pos].y;
    }
}

bool Find(int x, int y){
    int  k = (x * x + y * y) % prime + 1;
    if(!has[k]) return false;
    Hash * tmp = has[k];
    while(tmp){
        if(tmp->x == x && tmp->y == y)
            return true;
        tmp = tmp->next;
    }return false;
}

int main(){
    int n;
    while(scanf("%d", &n) != EOF && n){
        memset(has,0, sizeof(has));
        for(int  i = 1; i <= n; ++i){
            scanf("%d %d", &a[i].x, &a[i].y);
            insert_hash(i);
        }int num = 0;
        for(int i = 1; i <= n; ++i)
            for(int j = i+1; j <= n; ++j){
                int x = a[j].x - a[i].x;//根據已知點算正方形未知點的座標
                int y = a[j].y - a[i].y;

                int x1 = y + a[i].x;
                int y1 = a[i].y - x;
                int x2 = y + a[j].x;
                int y2 = a[j].y - x;
                if(Find(x1,y1) && Find(x2,y2))
                    ++num;
                x1 = a[i].x - y;
                y1 = a[i].y + x;
                x2 = a[j].x - y;
                y2 = a[j].y + x;
                if (Find(x1,y1) && Find(x2,y2))
                    ++num;
            }printf("%d\n",num/4);//由於每個正方形被算了四次,所以除以4
    }return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章