Luo Gu P1441 weights weighing (search, dfs + bitset optimization)

Los weight weighing Valley P1441

\ (n-\) range is \ (n-\ Le 20 is \) , \ (m \) in the range of \ (m \ Le. 4 \) .

Violence removing weights traversing each case, a total of \ (n ^ m \) case.

Solving for the remaining number of weights may be combined weight species. Bitset solved using the optimization, the \ (I \) bit \ (1 \) represents a weight \ (I \) may be combined with it. \ (1 \) digit is the final answer.

The initial \ (the bitset [0] =. 1 \) , for the newly added weight \ (I \) , weight \ (A [I] \) , is updated to \ (bitset = bitset \ | \ (bitset << a [ i]) \) .

Time complexity is \ (O (n ^ m \ times n \ times \ text {bitset single operation time}) \) .

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<bitset>

using namespace std;

const int maxn = 25;
const int maxm = 2005;
int n, m, ans, sum;
int vis[maxn], a[maxn], f[maxm];

void solve()
{
    bitset<maxm> cnt;
    cnt[0] = 1;
    for(int i = 1; i <= n; i++){
        if(vis[i] == 1) continue;
        cnt = cnt | (cnt << a[i]);
    }
    int ret = cnt.count();
    ans = max(ans, ret - 1);
}
void dfs(int now, int step)
{
    if(step == m + 1){
        solve();
        return;
    }
    for(int i = now; i <= n; i++){
        vis[i] = 1;
        dfs(i + 1, step + 1);
        vis[i] = 0;
    }
}
int main()
{
    scanf("%d%d", &n, &m);
    sum = 0;
    for(int i = 1; i <= n; i++){
        scanf("%d", &a[i]);
        sum += a[i];
    }
    ans = 0;
    dfs(1, 1);
    printf("%d\n", ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/solvit/p/11390156.html