Luo Gu P1441 weights weighing (search, dfs + dp)

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. Dp simple to solve. Complexity \ (O (n-\ n-Times \ Times m) \) .

Time complexity is \ (O (n-m ^ \ n-Times \ n-Times \ Times m) \) . The actual complexity should be much smaller than this, pruning effect is obvious.

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

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()
{
    for(int i = 0; i <= sum; i++) f[i] = 0;
    f[0] = 1;
    int tot = 0, ret = 0;
    for(int i = 1; i <= n; i++){
        if(vis[i] == 1) continue;
        for(int j = tot; j >= 0; j--){
            if(f[j] == 1 && f[j + a[i]] == 0){
                ret++; f[j + a[i]] = 1;
            }
        }
        tot += a[i];
    }
    ans = max(ans, ret);
}
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/11390034.html