Knapsack problem dynamic programming # 1

Luo Gu P1048 herbs

"01 backpack"

Two-dimensional array to achieve:

 

1 for(int i=1;i<=M;i++){
2     for(int j=0;j<=T;j++){
3         dp[i][j]=dp[i-1][j];
4         if(j-t[i]>=0){
5             dp[i][j]=max(dp[i-1][j-t[i]]+v[i],dp[i][j]);
6         }
7     }
8 }   
9 printf("%d",dp[T][M]);         

 

Time complexity: $ O (T * M) $

Space complexity: $ O (T * M) $

Optimization of a one-dimensional array: to optimize the spatial complexity ()

 

Luo Gu P1616 crazy herbs

Meaning of the questions:

A small herbs, there are T time, a total of M kinds of drugs, each drug herbs time t i and herbs worth v i given, each drug can be taken an unlimited number, how the value of herbs not exceed the maximum time ?

 

 

Guess you like

Origin www.cnblogs.com/liuziwen0224/p/11514833.html