ACDream 1726 A Math game (折半查找)

A Math game

Time Limit: 2000/1000MS (Java/Others) Memory Limit: 256000/128000KB (Java/Others)

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

Manager

 
题意:给定n个数字,问能否使这些数字相加得到H?
分析:折半查找,先将前半部分的和算出来存在数组中,再将后半部分的数ans进行计算,然后在前半部分进行查找H-ans
这一题用到了一种新的写法,位运算。
用二进制来表示哪些数取了,哪些数没取。
比如,算前5个数字,2^5的二进制就是100000 那么可以把前面五个数的组合情况全部都表示出来
每一个二进制位表示第几个数,比如取第一和第三个数,那么二进制就是100101。
 
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<stdlib.h>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
#define LL long long
using namespace std;
const int MAXN=2e6+7;
int n,H;
int a[MAXN],sum[MAXN];
int main()
{
    int n,H;
    while(scanf("%d %d",&n,&H)!=EOF)
    {
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        int c=0,k=n>>1;
        for(int i=0;i<(1<<k);i++)
        {
            LL s=0;
            for(int j=0;j<k;j++)
            {
                if((1<<j)&i) s+= a[j];
            }
            if(s<=H) sum[c++]=s;
        }
        sort(sum,sum+c);
        int res=n-k;
        bool ok=false;
        for (int i=0;i<(1<<res);i++)
        {
            LL s=0;
            for(int j=0;j<res;j++)
            {
                if ((1<<j)&i) s+=a[k+j];
            }
            if (s>H) continue;
            if (sum[lower_bound(sum,sum+c,H-s)-sum]==H-s) {
                ok=true;
                break;
            }
        }
        puts(ok?"Yes":"No");
    }
    return 0;
}
View Code

 

 

posted @ 2015-05-09 16:15  Cliff Chen  阅读(287)  评论(0编辑  收藏  举报