0/1背包问题

Smiling & Weeping

                ----就算将仙人掌的刺全部拔光,也成为不了你想要的花

Problem Description:

  Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?

Input:

The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output:

One integer per line representing the maximum of the total value (this number will be less than 231).

Sample Input:

1 5 10 1 2 3 4 5 5 4 3 2 1

Sample Output:

14

详细判题通道:

Problem - 2602 (hdu.edu.cn)

对于这道题目的理解:

  1.DP状态的设计:dp[i][j]代表前i个装进容量为j的背包

  2.DP状态的转移:(1).如果bone[i]的体积大于背包容量,直接dp[i][j] = dp[i-1][j]

  (2).如果bone[i][j]的体积小于背包容量,判断所承受的最大价值

  dp[i][j] = max(dp[i-1][j-bone[i].volume] + bone[i].value , dp[i-1][j])

 

 1 #include<iostream>
 2 #include<stdlib.h>
 3 #include<cmath>
 4 #include<cstring>
 5 using namespace std;
 6 typedef long long ll;
 7 ll dp[1010][1010];     //把前i个bone放入空间为j的背包
 8 struct data
 9 {
10     ll value , volume;
11 }bone[10000];
12 int main()
13 {
14     int T , N , V;
15     scanf("%d",&T);
16     while(T--)
17     {
18         memset(dp , 0  , sizeof(dp));
19         scanf("%d%d",&N,&V);
20         for(int i = 1; i <= N; i++) scanf("%lld",&bone[i].value);
21         for(int i = 1; i <= N; i++) scanf("%lld",&bone[i].volume);
22         for(int i = 1; i <= N; i++)
23             for(int j = 0; j <= V; j++)  //注意背包体积要从0开始
24             {
25                 if(bone[i].volume 》 j) dp[i][j] = dp[i-1][j];
26                 else
27                     dp[i][j] = max(dp[i-1][j-bone[i].volume] + bone[i].value, dp[i-1][j]);
28             }
29         printf("%lld\n",dp[N][V]);
30     }
31     return 0;
32 }

 

posted @ 2023-06-30 14:49  smiling&weeping  阅读(41)  评论(0)    收藏  举报