采药(0-1背包)

经典0-1背包问题分析:https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92.md#0-1-%E8%83%8C%E5%8C%85 (用谷歌浏览器打开)

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 int w[102];            // w[i]表示采第i株草药的时间 
 8 int v[102];            // v[i]表示第i株草药的价值 
 9 int dp[102][1002];    // dp[i][j]表示在总时间不超过j的情况下,前i株草药能达到的最大价值 
10 
11 int main() 
12 {
13     int T, M;
14     while(cin >> T >> M) 
15     {
16         for(int i = 1; i <= M; ++i)
17             cin >> w[i] >> v[i];
18             
19         for(int j = 0; j <= T; ++j)
20             dp[0][j] = 0;
21             
22         for(int i = 1; i <= M; ++i)
23         {
24             for(int j = 1; j <= T; ++j)
25             {
26                 if(j >= w[i])
27                     dp[i][j] = max(dp[i-1][j], dp[i-1][j-w[i]] + v[i]);
28                 else
29                     dp[i][j] = dp[i-1][j];
30             }
31         }
32         
33         cout << dp[M][T] << endl;
34     }
35             
36     return 0;
37 }

猜你喜欢

转载自www.cnblogs.com/FengZeng666/p/11107681.html