ACdreamOJ 1726 hash

http://acdream.info/problem?pid=1726

Problem Description
Recently, Losanto find an interesting Math game. The rule is simple: Tell you a number  H, and you can choose some numbers from a set {a[1],a[2],......,a[n]}.If the sum of the number you choose is  H, then you win. Losanto just want to know whether he can win the game.
Input
There are several cases.
In each case, there are two numbers in the first line  n (the size of the set) and  H. The second line has n numbers {a[1],a[2],......,a[n]}. 0<n<=40, 0<=H<10^9, 0<=a[i]<10^9,All the numbers are integers.
Output
If Losanto could win the game, output "Yes" in a line. Else output "No" in a line.
Sample Input
10 87
2 3 4 5 7 9 10 11 12 13
10 38
2 3 4 5 7 9 10 11 12 13
Sample Output
No
Yes
/**
ACdreamOJ  1726 hash
题目大意:给定n个数,问这些数的部分和是否可以组成m
解题思路:由于n的最大值只有40,因此我们把所有的数分成均等的两部分,利用哈希查寻一下就可以了
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
using namespace std;
typedef long long LL;
const int MAXN=1<<20;
const int HASH = 1000007;

struct hashmap//建立哈希表
{
    LL a[MAXN];
    int head[HASH],next[MAXN],size;
    void init() //初始化
    {
        memset(head,-1,sizeof(head));
        size=0;
    }
    bool find(LL val) //查找一个元素是否在哈希表内
    {
        int tmp = (val%HASH + HASH)%HASH;
        for(int i = head[tmp]; i!=-1; i=next[i])
            if(val==a[i]) return true;
        return false;
    }
    void add(LL val) //添加元素到哈希表中
    {
        int tmp =(val%HASH+HASH)%HASH;
        if(find(val)) return;
        a[size]=val;
        next[size]=head[tmp];
        head[tmp]=size++;
    }
} h1;
int n,m,num[55];
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        h1.init();
        for(int i=0; i<n; i++)
        {
            scanf("%d",&num[i]);
        }
        int t=n/2;
        for(int i=0; i<(1<<t); i++)
        {
            LL sum=0;
            for(int j=0; j<t; j++)
            {
                if(i&(1<<j))
                {
                    sum+=num[j];
                }
            }
            if(sum>m)continue;
            h1.add(sum);
        }
        int tt=n-t;
        int flag=0;
        for(int i=0; i<(1<<tt); i++)
        {
            LL sum=0;
            for(int j=0; j<tt; j++)
            {
                if(i&(1<<j))
                {
                    sum+=num[t+j];
                }
            }
            if(sum>m)continue;
            if(h1.find(m-sum))
            {
                flag=1;
                break;
            }
        }
        if(flag)
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值