NYIST 860 又见01背包

又见01背包
时间限制:1000 ms | 内存限制:65535 KB
难度:3


描述
有n个重量和价值分别为wi 和 vi 的 物品,从这些物品中选择总重量不超过 W
的物品,求所有挑选方案中物品价值总和的最大值。
  1 <= n <=100
  1 <= wi <= 10^7
  1 <= vi <= 100
  1 <= W <= 10^9
输入
多组测试数据。


每组测试数据第一行输入,n 和 W ,接下来有n行,每行输入两个数,代表第i个物品的wi 和 vi。


输出
满足题意的最大价值,每组测试数据占一行。
样例输入
4 5
2 3
1 2
3 4
2 2


样例输出
7


来源
飘谊系列


上传者
TC_张友谊

 

解题:用价值换重量,尽可能多的价值换取尽可能少的重量。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <climits>
 7 #include <vector>
 8 #include <queue>
 9 #include <cstdlib>
10 #include <string>
11 #include <set>
12 #include <stack>
13 #define LL long long
14 #define pii pair<int,int>
15 #define INF 0x3f3f3f3f
16 using namespace std;
17 const int maxn = 200;
18 int dp[maxn*maxn],v[maxn],w[maxn],n,W,V;
19 int main() {
20     while(~scanf("%d %d",&n,&W)) {
21         V = 0;
22         for(int i = 1; i <= n; ++i) {
23             scanf("%d %d",w+i,v+i);
24             V += v[i];
25         }
26         memset(dp,0x3f,sizeof(dp));
27         dp[0] = 0;
28         for(int i = 1; i <= n; ++i) {
29             for(int j = V; j >= v[i]; --j)
30                 dp[j] = min(dp[j],dp[j-v[i]]+w[i]);
31         }
32         for(int i = V; i >= 0; --i)
33             if(dp[i] <= W) {
34                 printf("%d\n",i);
35                 break;
36             }
37     }
38     return 0;
39 }
View Code

 

posted @ 2014-10-23 21:58  狂徒归来  阅读(164)  评论(0编辑  收藏  举报