POJ 2002 Squares (Hash)

题意:给你二维平面点集 让你找出其中能组成多少个正方形

思路:对每一个点进行哈希 枚举两个点做为正方形的一条边 然后再求另外两个点 看看原点集中是否存在这两个点 由于枚举的是每条边 则一个正方形会被枚举四次 结果要除以四

#include <cstdio>
#include <cstring>
using namespace std;

#define REP( i, a, b ) for( int i = a; i < b; i++ )
#define CLR( a, x ) memset( a, x, sizeof a )

const int maxn = 1000 + 10;
const int MOD = 1007;

struct Point{
          int x, y;
          Point(int x = 0, int y = 0) : x(x), y(y) {}
          void read() { scanf("%d%d", &x, &y); }
          int Hash(){ return (x * x + y * y) % MOD; }
}p[maxn];

struct HashTable{
          int x, y;
          HashTable *next;
          HashTable(){ next = NULL; }
} *Hashtable[maxn];

int n;

void Insert(Point P){
          int key = P.Hash();
          if(!Hashtable[key]){
                    HashTable *tmp = new HashTable;
                    tmp -> x = P.x;
                    tmp -> y = P.y;
                    Hashtable[key] = tmp;
          }
          else{
                    HashTable *tmp = Hashtable[key];
                    while(tmp -> next) tmp = tmp -> next;
                    tmp -> next = new HashTable;
                    tmp -> next -> x = P.x;
                    tmp -> next -> y = P.y;
          }
}

bool Find(Point P){
          int key = P.Hash();
          if(Hashtable[key]){
                    HashTable *tmp = Hashtable[key];
                    while(tmp){
                              if(tmp -> x == P.x && tmp -> y == P.y) return true;
                              tmp = tmp -> next;
                    }
          }
          return false;
}

void Creat(const Point &p1, const Point &p2, Point &p3, Point &p4, Point &p5, Point &p6){
          int X = p2.x - p1.x;
          int Y = p2.y - p1.y;
          p3 = Point(p1.x + Y, p1.y - X);
          p4 = Point(p2.x + Y, p2.y - X);
          p5 = Point(p1.x - Y, p1.y + X);
          p6 = Point(p2.x - Y, p2.y + X);
}

void solve(){
          int ans = 0;
          CLR(Hashtable, 0);
          REP(i, 0, n) p[i].read(), Insert(p[i]);
          REP(i, 0, n) REP(j, i+1, n){
                    Point p1, p2, p3, p4;
                    Creat(p[i], p[j], p1, p2, p3, p4);
                    if(Find(p1) && Find(p2)) ans++;
                    if(Find(p3) && Find(p4)) ans++;
          }
          printf("%d\n", ans / 4);
}

int main()
{
          //freopen("in.txt", "r", stdin);
          while(~scanf("%d", &n) && n) solve();
          return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值