The ninth field title D combined sum of the binary enumeration (large backpack) more than 2019 cattle off school for the sum

https://ac.nowcoder.com/login?callBack=%2Facm%2Fcontest%2F889%2FD%3F%26headNav%3Dacm

The meaning of problems: the given length n array {a i} and the sum of the sum.

Please find {a i} of subsets, such that the sum of the subset sum, 01 to select the output of the sequence program.

Analysis: can be seen as a large backpack, as do ordinary backpack, then the time complexity of n * a [i] (max), and a [i] too, will obviously be a timeout, or a violent enumerate do, then, 2 ^ n also overtime, but only 36 n, use binary enumeration in the index binary, then it can significantly reduce the time complexity.

During the second enumeration to find, because the number is too large to use the set, and a set of find ()! = Set.end () to find out whether there is achieved, and in the output sequence of 01 selected programs, as output had first enumeration scheme, so use map to save the state and the sum for the first time enumeration.

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
using namespace std;

typedef long long ll;
int n,q,p;
ll sum;
ll a[39];
set<ll> se;
map<ll,int> ma;

int main(){
    scanf("%d%lld",&n,&sum);
    p=n>>1,q=n-(n>>1);
    for(int i=1; i<=n; i++){
        scanf("%lld",a+i);
    }
    for(int i=1; i<(1<<p); i++){
        ll res=0;
        for(int j=0; j<p; j++){
            if(i&(1<<j))
                res+=a[j+1];
        }
        se.insert(res);
        ma[res]=i;
    }
    for(int i=1; i<(1<<q); i++){
        ll res=0;
        for(int j=0; j<q; j++){
            if(i&(1<<j))
                res+=a[p+j+1];
        }
        if(se.find(sum-res)!=se.end()){
            int state=ma[sum-res];
            for(int k=0; k<p; k++){
                if(state&(1<<k)) putchar('1');
                else putchar('0');
            }
            for(int k=0; k<q; k++){
                if(i&(1<<k)) putchar('1');
                else putchar('0');
            }
            puts("");
            return 0;
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/-Zzz-/p/11416746.html