Dynamic Programming: The Knapsack Problem

Backpack problem: There are M jewels with different values, and the time for the thief to steal each jewel is also different. It is necessary to put as many jewels into the backpack as possible before the security finds out, and at the same time, it must ensure that the total value of the jewels in the backpack is the largest

Suppose: the size of the backpack is M[][], the value of stolen jewels at time t is V[100], and the time for each jewel stolen is time[t]

Steal the i-th jewel at time t, and the current time is t, then judge the current jewel,

Let the value in the backpack after the last theft plus the value v[i] of this jewel be: m[i-1][ t-time[i] ],

If the jewel is not stolen, then: m[i-1][t]

State transition equation: M[i] [j]= max{ v[i]+m[i-1][j-time[i] , m[i-1][t]}

#include<stdio.h>

int TotalTime, num;    //设置总时间和珠宝数量
int value[100],time[100],m[1000][1000];
int main(){
    printf("输入总时间和珠宝数量\n")
    scanf("%d,%d",&TotalTime,&num);
    printf("输入每个珠宝的时间和珠宝价值\n")
    for(int i = 0; i<num; i++){
        scanf("%d,%d",&time[i],&value[i]);
        printf("\n");
    }
    for(int i = 0; i<num; i++){
        for(int t=TotalTime;t>0;t--){    //剩余时间
            if(time[t]<t){    //当前珠宝偷窃时间足够
                int value1 = m[i-1][t-time[t]+v[i];
                int value2 = m[i-1][t];    //如果不采集,时间不变
                m[i][t] = (value1>value2 : value1?value2);
            }
        }        
    }
    printf("偷窃总价值为:%d",m[num][TotalTime]);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_37504771/article/details/124003621