2019牛客暑期多校训练营(第九场)D.Knapsack Cryptosystem

链接:https://ac.nowcoder.com/acm/contest/889/D
来源:牛客网
 

题目描述

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.

题目大意:现在给你N个数然后给你一个K,问你这N个数中哪几个数的加和是K,并在下面标注出来

思路:这个题目当时就想起来暴力搜索,但是想想每个2^36次方肯定是爆掉的了,后来看了过了的代码,就差不错知道了,这个题目他们是把36分成了两部分,前半段的搜索加记忆化,后半段使用记忆化,这样就是一个记忆化+2^18的复杂度了,

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#define ll long long
using namespace std;
const int maxn=40;
map<ll ,ll >mp;
ll index[maxn],a[maxn],target;
int n,mid;
ll ans;
void init()
{
    index[1]=1;
    for(int i=2;i<=maxn;i++)
        index[i]=index[i-1]*2;
}
void DFS(int pos,ll sta,ll sum,int en)
{
    if(pos==en+1)
    {
        if(pos==mid)
        {
            if(sum==target)
                ans=sta;
            mp[sum]=sta;;
        }
        else
        {
            if(mp[target-sum])
                ans=sta+mp[target-sum];
        }
        return ;
    }
    DFS(pos+1,sta,sum,en);
    DFS(pos+1,sta+index[pos],sum+a[pos],en);
}
int main()
{
    init();
    scanf("%d%lld",&n,&target);
    for(int i=1;i<=n;i++)
        scanf("%lld",&a[i]);
    mid=n/2+1;
    ans=0;
    if(target) DFS(1,0,0,n/2);
    if(!ans) DFS(n/2+1,0,0,n);
    for(int i=1;i<=n;i++)
    {
        if(ans&1)
            cout<<"1";
        else
            cout<<"0";
        ans>>=1;
    }
    cout<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值