UVA10125 Sumsets

链接

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1066

题解

哈希链表
预处理所有的 a + b ,存到哈希链表里面去
然后枚举 d , c ,求出 d c ,哈希一下,然后到链表中对比那些哈希值相等的数对,如果恰好是四个不相同的元素而且满足 a + b = d c ,即找到了答案

代码

//哈希链表
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cctype>
#define maxn 1010
#define mod 4894651
#define base 1000000007
#define ll long long
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
ll n, a[maxn], head[mod+10];
struct hash
{
    ll fir, sec;
    hash *next;
}pool[maxn*maxn];
void add_hash(ll a, ll b, ll h)
{
    ++*head;
    pool[*head]=(hash){a,b,pool+head[h]};
    head[h]=*head;
}
ll read(ll x=0)
{
    char c, f=1;
    for(c=getchar();!isdigit(c) and c^-1;c=getchar())if(c=='-')f=-1;
    for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+c-48;
    return f*x;
}
void init()
{
    ll i, j, s;
    for(i=1;i<=n;i++)a[i]=read();
    sort(a+1,a+n+1);
    cl(head);
    for(i=1;i<=n;i++)for(j=i+1;j<=n;j++)
        if(i<j)
        {
            s=a[i]+a[j];
            s=(s%mod+mod)%mod;
            add_hash(i,j,s);
        }
}
void work()
{
    ll d, c, h;
    hash *p;
    for(d=n;d;d--)for(c=1;c<=n;c++)
        if(d!=c)
        {
            h=a[d]-a[c];
            h=(h%mod+mod)%mod;
            for(p=pool+head[h];p;p=p->next)
                if(d!=p->fir and d!=p->sec and c!=p->fir and c!=p->sec and a[p->fir]+a[p->sec]+a[c]==a[d])
                {
                    printf("%d\n",a[d]);
                    return;
                }
        }
    printf("no solution\n");
}
int main()
{
    for(n=read();n;n=read())
    {
        init();
        work();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/FSAHFGSADHSAKNDAS/article/details/81213059