【FZU - 2214】【Knapsack problem】

版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/82746863

题目:

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

解题思路:就是很裸的01背包问题,然而 他给的体积的数据范围确实太大了,根本没办法去开大数组求解,所以 change一下思维 ,我们将价值作为下标,这样就不会因为开过大数组而爆内存,同时需要注意的一点就是,之前以体积作为下标的时候,我们是求解的固定体积能达到的最大价值,现在就是当前价值能实现的最小体积。当当前的体积是小于给出固定体积的时候,咱们就记录一下,最后直接倒着推,就能找到当前体积的最大价值了。

ac代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int  min(int a,int b)
{
	if(a<b)
		return  a;
	else
		return b;
}
typedef long long ll;
ll w[505];
int v[505];
int dp[80008];
int main()
{
	int t;
	while(scanf("%d",&t)!=EOF)
	{
		int n,B;
		while(t--)
		{
			int vv=0;
			memset(dp,0x3f3f,sizeof(dp));
			scanf("%d%d",&n,&B);
			for(int i=0;i<n;i++)
				scanf("%lld%d",&w[i],&v[i]);
			for(int i=0;i<n;i++)
				vv+=v[i];		
			dp[0]=0;
			for(int i=0;i<n;i++)
				for(int j=vv;j>=v[i];j--)
				{
					if(dp[j-v[i]]+w[i]<=B)
					{
						dp[j]=min(dp[j-v[i]]+w[i],dp[j]);
					}
				}
			int ans=-1;
			for(int j=vv;j>=0;j--)
			{
				if(dp[j]<=B)
				{
					ans=j;
					break;
				}
			}
			cout<<ans<<endl;
		}
	}
	return 0;
}

总结:不得不说,这个真的是开了一个转化思维的脑洞,之前习惯将体积做下标,价值做数值,颠倒过来其实也是很不错的操作。

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/82746863
今日推荐