POJ 2002 Squares

本文介绍了一种通过枚举两个点并计算剩余两个点的方法来找出由n个点构成的所有可能的正方形。提供了完整的C++代码实现,包括点的结构定义、哈希表的使用、点的存在性检查等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出n个点,求出用这n个点可构成的正方形的个数。可以枚举两个点,求出正方形的另两个点。

然后判断这两个是否存在。我的hash公式写得比较烂,跑了1s多。

下面是求正方形剩下两点的公式:

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

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

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

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

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

/*Accepted    1724K    1047MS    C++    1713B    2012-08-24 11:46:05*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

const int MAXN = 1 << 10;
const int prime = 99991;
int n, ans;

struct point
{
    int x, y;
}t[MAXN];

struct Hash
{
    point p;
    struct Hash *next;
}h[prime + 10];

int hash(point a)
{
    return (a.x * a.x + a.y * a.y) % prime + 1;
}

void insert(point a)
{
    Hash *temp = new Hash();
    int key = hash(a);
    temp->p.x = a.x;
    temp->p.y = a.y;
    temp->next = h[key].next;
    h[key].next = temp;
}

bool exist(point a)
{
    Hash *temp = h[hash(a)].next;

    while(temp)
    {
        if(temp->p.x == a.x && temp->p.y == a.y)
            return true;
        temp = temp->next;
    }
    return false;
}

void Read()
{
    int i;
    for(i = 0; i < n; i ++)
    {
        scanf("%d%d", &t[i].x, &t[i].y);
        insert(t[i]);
    }
}

void cal()
{
    point a, b;
    int i, j;
    ans = 0;
    for(i = 0; i < n - 1; i ++)
        for(j = i + 1; j < n; j ++)
        {
            a.x = t[i].y - t[j].y + t[i].x;
            a.y = t[i].y - (t[i].x - t[j].x);
            b.x = t[j].x + t[i].y - t[j].y;
            b.y = t[j].y - (t[i].x - t[j].x);
            if(exist(a) && exist(b))
                ans ++;

            a.x = t[i].x - (t[i].y - t[j].y);
            a.y = t[i].y + t[i].x - t[j].x;
            b.x = t[j].x - (t[i].y - t[j].y);
            b.y = t[j].y + t[i].x - t[j].x;
            if(exist(a) && exist(b))
                ans ++;
        }
    ans /= 4;
}

int main()
{
    while(scanf("%d", &n), n)
    {
        memset(h, 0, sizeof h);
        Read();
        cal();
        printf("%d\n", ans);

    }
    return 0;
}

 

 

转载于:https://www.cnblogs.com/Yu2012/archive/2012/08/24/2653950.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值