Implication: Select several numbers from n numbers so that the sum is a given value m, so that the title is guaranteed to be solvable.
Since the maximum n is 36, direct search for the 2 ^ 36 power confirms TLE, but for the half of the interval, that is 18, 2 ^ 18, it should be thought of to fold the interval in half, first calculate the sum of various combinations in the first half of the interval, enumerate the various cases in the second half of the interval and find whether m-sum exists in the first half of the interval.
Method 1: set+map
#include<cstdio> #include<cstring> #include<algorithm> #include<set> #include<map> using namespace std; typedef long long ll; ll a[50]; map<ll,int>mp; set<ll>st; int main() { int i,j; int n; ll m; scanf("%d%lld",&n,&m); for(i=0;i<n;i++) { scanf("%lld",&a[i]); } int p=n/2; int q=n-p; for(i=0;i<(1<<p);i++)//The first half interval; { ll sum=0; for(j=0;j<p;j++) { if((i>>j)&1) { sum+=a[j]; } } st.insert(sum); mp[sum]=i; } for(i=0;i<(1<<q);i++)//Second half interval; { ll sum=0; for(j=0;j<q;j++) { if((i>>j)&1) { sum+=a[j+p]; } } if(st.find(m-sum)!=st.end()) { int now=mp[m-sum]; for(j=0;j<p;j++) { printf("%d",(now>>j)&1); } for(j=0;j<q;j++) { printf("%d",(i>>j)&1); } } } return 0; }
Law 2: map+string:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <string> #include <map> using namespace std; typedef long long ll; ll a[50]; int main() { int i,j; map<ll,string>mp1; map<ll,string>mp2; int n; ll m; scanf("%d%lld",&n,&m); for(i=0;i<n;i++) { scanf("%lld",&a[i]); } int p=n/2; int q=n-p; for(i=0;i<(1<<p);i++)//The first half; { string s; ll sum=0;//Select some of them and; for(j=0;j<p;j++) { if((i>>j)&1)//This is to judge whether the jth place is chosen or not. { sum+=a[j]; s.push_back('1'); } else { s.push_back('0'); } } mp1[sum]=s; } for(i=0;i<(1<<q);i++) { string s; ll sum=0; for(j=0;j<p;j++) { if((i>>j)&1) { sum+=a[j+p]; s.push_back('1'); } else { s.push_back('0'); } } mp2[sum]=s; if(mp1.count(m-sum)) { cout<<mp1[m-sum]<<mp2[sum]<<endl; break; } } return 0; }