2016寒假个人赛(1)C(背包)

来源:互联网 发布:java如何解压rar文件 编辑:程序博客网 时间:2024/05/16 08:54
C - C
Time Limit:3000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

Given a set of n items, each with a weight w[i] and a value v[i], determine a way to choose the items into a knapsack so that the total weight is less than or equal to a given limit B and the total value is as large as possible. Find the maximum total value. (Note that each item can be only chosen once).

Input

The first line contains the integer T indicating to the number of test cases.

For each test case, the first line contains the integers n and B.

Following n lines provide the information of each item.

The i-th line contains the weight w[i] and the value v[i] of the i-th item respectively.

1 <= number of test cases <= 100

1 <= n <= 500

1 <= B, w[i] <= 1000000000

1 <= v[1]+v[2]+...+v[n] <= 5000

All the inputs are integers.

Output

For each test case, output the maximum value.

Sample Input

1
5 15
12 4
2 2
1 1
4 10
1 2

Sample Output

15


题意:
给你一个背包,要你装的价值最大。

思路:
这题就是将质量固定求最大价值转化为价值固定求质量最小。
所以动态转移方程就是dp[j] = min(dp[j],dp[j-v]+u);u-质量,v-价值。

AC代码:

#include<iostream>#include<algorithm>#include<cstring>#include<string>#include<cstdio>#include<cmath>#include<ctime>#include<cstdlib>#include<queue>#include<vector>#include<set>using namespace std;const int T=5500;#define inf 0x3f3f3f3fL#define mod 1000000000typedef long long ll;typedef unsigned long long LL;int dp[T];int main(){#ifdef zsc    freopen("input.txt","r",stdin);#endifint N,i,j,k,n,m,u,v;scanf("%d",&N);while(N--){memset(dp,inf,sizeof(dp));dp[0] = 0;scanf("%d%d",&n,&m);for(i=0;i<n;++i){scanf("%d%d",&u,&v);for(j=5000;j>=v;--j){if(dp[j-v]+u<=m&&dp[j]>dp[j-v]+u){dp[j] = dp[j-v]+u;}}}bool flag = false;for(j=5000;j>=0;--j){if(dp[j]<=m){flag = true;break;}}if(flag){printf("%d\n",j);}else{printf("0\n");}}    return 0;}


0 0
原创粉丝点击