More than 2019 cattle off summer school camp (ninth field) Knapsack Cryptosystem-- hash table && binary enumeration

The meaning of problems

Having a length of $ n $ ($ 1 \ leq n \ leq 36 $) of the series, is given $ s $, is the sum of $ s $ subset, the subset to ensure the existence and uniqueness.

analysis

The answer is definitely from about half of the two-part.

If we keep a hash table half, the other half of the calculated value of $ v $, then find $ sv $ in the hash table, so in size from $ 2 ^ {36} $ to $ 2 ^ {18} $, in fact, binary search for.

#include<bits/stdc++.h>
using namespace std;

typedef  long long ll;
ll n, s, a[40];
ll A[1 << 20];
unordered_map<ll, int>mp;

int main()
{
    scanf("%lld%lld", &n, &s);
    for(int i = 0;i < n;i++)  scanf("%lld", &a[i]);

    int l = n / 2;  //左边的长度
    for(int i = 0;i < (1 << l);i++)
        for(int j = 0;j < l;j++)
        {
            if((i >> j) & 1)
                A[i] += a[j];
        }

    int r = n - l;  //右边的长度
    for(int i = 0;i < (1 << r);i++)
    {
        ll tmp = 0;
        for(int j = 0;j < r;j++)
        {
            if((i >> j) & 1)
                tmp += a[j+l];
        }
        mp[tmp] = i;
    }

    //查找
    for(int i = 0;i < (1 << l);i++)
    {
        ll cha = s - A[i];
        if(mp.count(cha))
        {
            for(int j = 0;j < l;j++)
            {
                if((i >> j) & 1)  printf("1");
                else printf("0");
            }
            for(int j = 0;j < r;j++)
            {
                if((mp[cha] >> j) & 1)  printf("1");
                else  printf("0");
            }
            printf("\n");
            break;
        }
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/lfri/p/11360824.html