链接:https://ac.nowcoder.com/acm/contest/889/D
来源:牛客网
时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
Amy asks Mr. B problem D. Please help Mr. B to solve the following problem.
Amy wants to crack Merkle–Hellman knapsack cryptosystem. Please help it.
Given an array {ai} with length n, and the sum s.
Please find a subset of {ai}, such that the sum of the subset is s.
For more details about Merkle–Hellman knapsack cryptosystem Please read
https://en.wikipedia.org/wiki/Merkle%E2%80%93Hellman_knapsack_cryptosystem
https://blog.nowcoder.net/n/66ec16042de7421ea87619a72683f807
Because of some reason, you might not be able to open Wikipedia.
Whether you read it or not, this problem is solvable.
输入描述:
The first line contains two integers, which are n(1 <= n <= 36) and s(0 <= s < 9 * 1018)
The second line contains n integers, which are {ai}(0 < ai < 2 * 1017).
{ai} is generated like in the Merkle–Hellman knapsack cryptosystem, so there exists a solution and the solution is unique.
Also, according to the algorithm, for any subset sum s, if there exists a solution, then the solution is unique.
输出描述:
Output a 01 sequence.
If the i-th digit is 1, then ai is in the subset.
If the i-th digit is 0, then ai is not in the subset.
示例1
输入
复制
8 1129
295 592 301 14 28 353 120 236
输出
复制
01100001
说明
This is the example in Wikipedia.
示例2
输入
复制
36 68719476735
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 2147483648 4294967296 8589934592 17179869184 34359738368
输出
复制
111111111111111111111111111111111111
在n个数组成的数列中找任意个数使其和为s,组合具有唯一性。
n最大取值36,因此用递归或者枚举都会超时,学了一个新的方法叫折半枚举。即将数组a二分,前后两部分分开枚举再合在一起。
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <map>
#include <queue>
#include <string.h>
#include <algorithm>
using namespace std;
long long n,s,a[100],p[100];
int main()
{
map<long long,string>m1;
map<long long,string>m2;
scanf("%lld%lld",&n,&s);
for(int i=0;i<n;i++)
scanf("%lld",&a[i]);
for(int i=0;i<1<<(n/2);i++){
string vis;
long long sum=0;
for(int j=0;j<n/2;j++){
if((i>>j)&1){
sum+=a[j];vis.push_back('1');
}
else vis.push_back('0');
}
m1[sum]=vis;
}
for(int i=0;i<1<<(n-n/2);i++){
string vis;
long long sum=0;
for(int j=0;j<n-n/2;j++){
if((i>>j)&1){
sum+=a[j+n/2];vis.push_back('1');
}
else vis.push_back('0');
}
m2[sum]=vis;
if(m1.count(s-sum)){
cout<<m1[s-sum]<<m2[sum]<<endl;
break;
}
}
return 0;
}