More than 2019 cattle off summer school camp (ninth field) Knapsack Cryptosystem

Time limit: C / C ++ 2 seconds and 4 seconds in other languages

Space limitations: C / C ++ 262144K, other languages 524288K
64bit IO the Format:% LLD

Title Description

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.

Enter a description:

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 Description:

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.

Entry

8 1129
295 592 301 14 28 353 120 236

Export

01100001

Entry

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

Export

111111111111111111111111111111111111

The meaning of problems: there are the number n, the number of each may be selected from the group (1) or not selected (0), find a condition such that the selected number and is s.

 

Solution: binary enumeration.

 

Code:

#include<bits/stdc++.h>
using namespace std;
long long w[50];
map<long long ,string> lmaps;
int main()
{
  long long i,j,n,sum,S;
  scanf("%lld%lld",&n,&S);
  for(i=1;i<=n;i++) scanf("%lld",&w[i]);
  for(i=0;i<(1<<(n/2));i++)
  {
    string s;sum=0;
    for(j=0;j<n/2;j++)
    {
      if((i>>j)&1) s+='1',sum+=w[j+1];
      else s+='0';
    }
    lmaps[sum]=s;
  } 
  for(i=0;i<(1<<(n/2));i++)
  {
    string s;sum=0;
    for(j=0;j<n/2;j++)
    {
      if((i>>j)&1) s+='1',sum+=w[n/2+j+1];
      else s+='0';
    }
    if(!lmaps[S-sum].empty())
     {
       cout<<lmaps[S-sum]<<s<<endl;
       break;
     }
  }
  system("pause");
  return 0;
}

Guess you like

Origin www.cnblogs.com/VividBinGo/p/11407699.html