Algorithm 12 - Knapsack Problem (DFS)

Problem description:
  There are n items, each item has weight w[i] and value c[i]. Now it is necessary to select several items and put them into a knapsack with a capacity of V, so that under the premise that the total weight of the items selected into the knapsack must not exceed V, the sum of the values ​​of the items in the knapsack is maximized, and the maximum value is sought. (1<=n<=20)

Analysis:
  For each item, there are two choices: choose or not choose. Each item must be selected, so the DFS parameter needs to record the index of the currently processed item. The question involves the weight and value of the item, so there are also parameters to record the total weight sumW and total value sumC of the item in the backpack before processing the item

void DFS(int index , int sumW , int sumC){...}

  If you choose not to put the item with index number, then sumW and sumC will remain unchanged, and then process the item with index+1, that is, go to DFS(index+1, sumW, sumC); if you choose the item with index number, then go to DFS( index, sumW+w[index], sumC+c[index])

  Once the index increases to n, it means that all items have been processed, and the sumW and sumC recorded at this time are the total weight and total value of the selected items. In this process, set a global record maximum total value variable maxValue, and update it in real time according to the situation

code:

#include<cstdio>
const int maxn = 30;
int n,V,maxValue = 0;//物品件数n,背包容量V,最大价值maxValue
int w[maxn],c[maxn];//w[i]为每件物品的重量,c[i]为每件物品的价值

void DFS(int index , int sumW , int sumC){
    if(index == n){
        //已经完成了对n件物品的处理
        if(sumW <= V && sumC > maxValue){
            maxValue = sumC;
        }
        return ;
    }

    DFS(index+1,sumW,sumC);
    DFS(index+1,sumW+w[index],sumC+c[index]);
}

int main(){
    scanf("%d%d",&n,&V);
    for(int i = 0 ; i < n ; i++)
        scanf("%d",&w[i]);
    for(int i = 0 ; i < n ; i++)
        scanf("%d",&c[i]);
    DFS(0,0,0);
    printf("%d\n",maxValue);
    return 0;
}

insert image description here

Improve:

#include<cstdio>
const int maxn = 30;
int n,V,maxValue = 0;//物品件数n,背包容量V,最大价值maxValue
int w[maxn],c[maxn];//w[i]为每件物品的重量,c[i]为每件物品的价值

void DFS(int index , int sumW , int sumC){
    if(index == n){
        return ;
    }
    DFS(index+1,sumW,sumC);
    if(sumW+w[index] <= V){
        //满足这个情况才能够选
        if(sumC+c[index] > maxValue){
            maxValue = sumC+c[index];
        }
        DFS(index+1,sumW+w[index],sumC+c[index]);
    }
}

int main(){
    scanf("%d%d",&n,&V);
    for(int i = 0 ; i < n ; i++)
        scanf("%d",&w[i]);
    for(int i = 0 ; i < n ; i++)
        scanf("%d",&c[i]);
    DFS(0,0,0);
    printf("%d\n",maxValue);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46025531/article/details/122851421