The most violent solution of 0 ~ 1 knapsack problem

Time:2021-12-6

Pure violence solution of 0 ~ 1 knapsack problem

analysis

When selecting items to put into the backpack, there are only two options for each item, i.e. put in and not put in. Therefore, in the case of n items, when the most violent means are used to solve, the worst time complexity should be the nth power of 2.

solve

If the number of items is 3 and the numbers are 1, 2 and 3 respectively, there are 8 situations as follows (0 means not to put in the backpack and 1 means to put in the backpack):

1    0 0 0 * 
2    1 0 0 * 
3    0 1 0
4    0 0 1
5    1 1 0 * 
6    1 0 1
7    0 1 1
8    1 1 1 *

The first row is the full arrangement of three zeros, so there is only one case;
The 2nd ~ 4th behaviors only contain a complete arrangement of 1;
The 5th ~ 7th behaviors contain the full arrangement of two 1s;
The eighth row is the full arrangement of the three 1s.

Therefore, it is natural to think of upgrading and improving the deep recursive Full Permutation Method to solve it.

However, I always feel that there should be more concise and intuitive violent means to solve the knapsack problem, and I always feel that it is written aboveanalysisAnd belowsolveIt seems that it is not the same method, but I can’t say why.
Alas, I can’t help it. I’m really too delicious. I hope to write it down as an essay first. I look forward to looking back when I’m strong one day in the future. come on.

The code is as follows:

#include
using namespace std;

const int N = 510;
int n, V;
int e[N], v[N], w[N], path[N];
int st[N], res = 0;

void dfs(int u){
    if(u == n + 1){
        int sum_v = 0, sum_w = 0;
        for(int i=1; i<=n; i++){
            sum_v += path[i] * v[i];
            sum_w += path[i] * w[i];
            // printf("%d ", path[i]);
        }
        puts("");
        if(sum_v <= V) res = max(sum_w, res);
        return;
    }

    for(int i=1; i<=n; i++){
        if(!st[i]){
            path[u] = e[i];
            st[i] = true;
            dfs(u + 1);
            st[i] = false;
        }
    }
}

int main(){
    Freopen ("0-1 knapsack problem. TXT", "R", stdin);
    scanf("%d%d", &n, &V);
    for(int i=1; i<=n; i++){
        scanf("%d%d", v+i, w+i);
    }

    for(int i=1; i<=n; i++){
        e[i] = 1;
        dfs(1);
    }
    cout << res << endl;
    return 0;
}
/*
Test sample
Input:
4 5
1 2
2 4
3 4
4 5
Output:
8
*/

Bug record

At that time, the result was always wrong after writing. After looking for it for a long time, I found that it was a defined sum_ V and sum_ W variables are not initialized and assigned, resulting in the computer randomly initializing them with a negative number.