01背包(递归)

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1000;
int v[maxn];
int w[maxn];
int n = 0, W1= 0;
int cou = 0;

int m(int i, int j) {
    cou++;
    printf("m(%d, %d)\n", i, j);
    if (i == n){
        return 0;
    }
    if (w[i] > j) {
        return m(i+1, j);
    }
    return max(m(i+1, j-w[i])+v[i], m(i+1, j));
}

int main() {
    while (scanf("%d%d", &n, &W1)==2) {
        for (int i = 0; i < n; i++) {
            scanf("%d", &v[i]);
        }
        for (int i = 0; i < n; i++) {
            scanf("%d", &w[i]);
        }
        int maxval = m(0, W1);
        printf("%d\n", maxval);
        printf("cou = %d\n", cou);
    }
    return 0;
}


你可能感兴趣的:(01背包(递归))