poj 2002 :Squares(hash 不解释)

题意:求该图节点可连成中有多少个正方形。

分析:2000个点每次选两个点连边然后构造正方形,但时间复杂度2000*2000*t(判断是否存在点),如果用map来判断点是否存在,O(logn)=45的时间复杂度也会超时(本人超过),看了别人的做法,才知道是hash来做,试了下,果然,hashO(1)的时间复杂度果然名不虚传,直接AC。

其实,hash结构简单挺好学的,关键是hash函数,不多说,上代码.

代码:

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

struct node
{
    int x,y;
    bool operator<(const node &a)const
    {
        if(x==a.x)return y<a.y;
        return x<a.x;
    }
}da[2005];
int nex[2005],hash[20005];

bool _search(node &tmp)
{
    int key=abs(tmp.x+tmp.y);
    for(int e=hash[key];~e;e=nex[e])
    {
        if(da[e].x==tmp.x&&da[e].y==tmp.y)
            return 1;
    }
    return 0;
}
int main()
{
    int n,i,j;
    while(~scanf("%d",&n))
    {
        memset(hash,-1,sizeof hash);
        for(i=0;i<n;i++)
            scanf("%d%d",&da[i].x,&da[i].y);
        sort(da,da+n);
        for(i=0;i<n;i++)
        {
            int key=abs(da[i].x+da[i].y);
            nex[i]=hash[key];
            hash[key]=i;
        }
        int ans=0;
        for(i=0;i<n;i++)
            for(j=i+1;j<n;j++)
            {
                node tmp;
                tmp.x=da[i].x+da[i].y-da[j].y;
                tmp.y=da[i].y-da[i].x+da[j].x;
                if(!_search(tmp))continue;
                tmp.x=da[j].x+da[i].y-da[j].y;
                tmp.y=da[j].y-da[i].x+da[j].x;
                if(!_search(tmp))continue;
                ans++;
            }
        printf("%d\n",ans/2);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值