给定n个数字,问能否使这些数字相加得到h【折半查找/DFS】

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

Source

第九届北京化工大学程序设计竞赛

DFS:

#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int a[N],s[N], n, flag, h;
void dfs(int sum, int now)//sum是当前累加和,now是当前累加了几个数 
{
    if(sum == h){
        flag = 1; return ;
    }
    /*
    1. flag==1 当前累加和为h,标记后直接退出 
    2. now == n + 1 不管能不能凑到h,累加的数次已经用完了 
    3. s[n] - s[now - 1] + sum < h 当前累加和+之前区间和也达不到h 
    4. sum > h 当还没到头当前累加和超过了h ,之后也只能超过 h,米有再搜索的必要了 
    */
    if(flag || now == n + 1 || s[n] - s[now - 1] + sum < h || sum > h){
        return ;
    }
    dfs(sum+a[now],now+1);//加当前这个数 
    dfs(sum,now+1);//不加当前的数 
}
int main()
{
    while(cin >> n >> h)
    {
        for(int i=1; i<=n; i++){
            cin >> a[i];
            s[i] = s[i-1] + a[i];
        }
        flag = 0;
        dfs(0,1);
        puts(flag?"Yes":"No");
    }
    return 0;
}

 折半查找:

/*
给定n个数字,问能否使这些数字相加得到h?
*/
/*
折半查找,先将前半部分的和算出来存在数组中,再将后半部分的数ans进行计算,然后在前半部分进行查找h-ans
这一题用到了一种新的写法,位运算。
用二进制来表示哪些数取了,哪些数没取。
比如,算前5个数字,2^5的二进制就是100000 那么可以把前面五个数的组合情况全部都表示出来
每一个二进制位表示第几个数,比如取第一和第三个数,那么二进制就是000101。
*/
#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int a[N],sum[N];
int main()
{
    int n, h, s;
    while(cin >> n >> h)
    {
        for(int i=0; i<n; i++)
            cin >> a[i];
        int k = 0, mid =( n >> 1);
        for(int i=0; i<(1<<mid); i++)
        {
            s = 0;
            for(int j=0; j<mid; j++)
            {
                if(i&(1<<j)){
                    s += a[j];
                }
            }
            if(s <= h) sum[k++] = s;//将前半部分的和算出来存在数组
        }
        
        sort(sum, sum+k);
        
        int res = n - mid;
        int f = 0;
        
        for(int i=0; i<(1<<res); i++)
        {
            s = 0;
            for(int j=0; j<res; j++)
            {
                if(i&(1<<j)) s += a[mid + j]; //进行计算后半部分的数s
            }
            if(s > h) continue;
            if(sum[lower_bound(sum,sum+k,h-s)-sum] == h - s) //将后半部分的数s进行计算,然后在前半部分进行查找h-s
            {
                f = 1;
                break;
            }
        }
        puts(f?"Yes":"No");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Roni-i/p/8782017.html