poj 2785 4 Values whose Sum is 0 (hash表的方法)

这是做过的几乎唯一的能用hash的题
记得当初写这个hash 貌似写出死循环了。



#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=4005;
const int key=1357;
const int Max =1000000000;
const int size=20345677;
int a[maxn],b[maxn],c[maxn],d[maxn];
int hash[size];
int sum[size];

void Insert(int num)
{
    int t=num;
    num=num%size;
    while(hash[num]!=Max&&hash[num]!=t)
        num=(num+key)%size;
    hash[num]=t;
    sum[num]++;
}
int Find(int num)
{
    int t=num;
    num=num%size;
    while(hash[num]!=Max && hash[num]!=t)
        num=(num+key)%size;
    if(hash[num]==Max) return 0;
    else return sum[num];
}
int main()
{
    int i,j,n,ans;
    while(~scanf("%d",&n))
    {
        ans=0;
        for(i=0; i<n; ++i)
            scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
        for(i=0; i<size; ++i)
        {
            hash[i]=Max;
            sum[i]=0;
        }
        for(i=0; i<n; ++i)
            for(j=0; j<n; ++j)
                Insert(a[i]+b[j]);
        for(i=0; i<n; ++i)
            for(j=0; j<n; ++j)
                ans+=Find(-(c[i]+d[j]));
        printf("%d\n",ans);
    }
    return 0;
}
#include <iostream>
#include<stdio.h>
using namespace std;
const int size=20345677;
const int M=1000000000;
const int key=1357;
int hash[size];
int mark[size];
void in(int n)
{
    int t=n;
    n=(n+M)%size;
    while(hash[n]!=M&&hash[n]!=t)
    {
        n=(n+key)%size;
    }
    hash[n]=t;
    mark[n]++;
}
int find(int n)
{
    int t=n;
    n=(n+M)%size;
    while(hash[n]!=M&&hash[n]!=t)
    {
        n=(n+key)%size;
    }
    if(hash[n]==M) return 0;
    else return mark[n];
}

int main()
{
    int n;
    int i,j;
    int a[4005],b[4005],c[4005],d[4005];

    scanf("%d",&n);
    int z=0;
    for(i=0; i<n; i++)
    {
        scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
    }
    for(i=0; i<size; i++)
    {
        hash[i]=M;
        mark[0]=0;
    }
    for(i=0; i<n; i++)
        for(j=0; j<n; j++)
        {
            in(a[i]+b[j]);
        }
    for(i=0; i<n; i++)
        for(j=0; j<n; j++)
        {
            z+=find(-(c[i]+d[j]));
        }
    printf("%d\n",z);
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值