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

 

 

转载于:https://www.cnblogs.com/clliff/p/4490599.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值