01背包(模板)

 1 /*
 2  * 01背包
 3  * n种物品,没种的重量为W,价值为V,背包容量为C,求在不超过C的情况下能装入的最大价值;
 4  * 测试数据:
 5  * 5 10
 6  * 2 6
 7  * 2 3
 8  * 6 5
 9  * 5 4
10  * 4 6
11  *
12  * Answer: 15
13  */
14 #include<iostream>
15 #include<cstdio>
16 #include<cstring>
17 #include<algorithm>
18 using namespace std;
19 
20 int n,C;
21 struct node
22 {
23     int W,V;
24 }maze[10];
25 int dp[20];
26 
27 int main()
28 {
29     while(scanf("%d%d",&n,&C)!=EOF)
30     {
31         for(int i=0;i<n;i++)
32         {
33             scanf("%d%d",&maze[i].W,&maze[i].V);
34         }
35         memset(dp,0,sizeof(dp));
36         for(int i=0;i<n;i++)
37         {
38             for(int j=C;j>=maze[i].W;j--)
39                 dp[j] = max(dp[j-maze[i].W]+maze[i].V,dp[j]);
40         }
41         printf("%d",dp[C]);
42     }
43     return 0;
44 }

猜你喜欢

转载自www.cnblogs.com/youpeng/p/10071825.html