【FZU2214】Knapsack problem(经典01背包改编)

Problem 2214 Knapsack problem

Accept: 837    Submit: 3249
Time Limit: 3000 mSec    Memory Limit : 32768 KB

 Problem 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

15 1512 42 21 14 101 2

 Sample Output

15


这是一道01背包改编的经典问题,可是比赛时到最后也没搞出来,最后几分钟有了点思路,就是把v和w换一下,比赛结束百度了一下发现还真是;还是太菜了

主要思路,由于w和空间太大,数组无法存下,我们可以先用数组存价值,最后判断重量是否超过m即可。

AC 代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string.h>
using namespace std;
const int maxn = 505;  
const int INF = 0x3f3f3f3f;  
  
int w[maxn],v[maxn];  
int dp[5005]; 
int main()
{
	int n,m,t;
	scanf("%d",&t);
	while(t--)
	{
	    scanf("%d%d",&n,&m);  
        int s = 0;  
        for(int i = 1; i <= n; i++){  
            scanf("%d%d",&w[i],&v[i]);  
            s += v[i];  
        } 
		memset(dp,INF,sizeof(dp));
		dp[0]=0;
        for(int i = 1; i <= n; i++){  
            for(int j = s; j >= v[i]; j--){  
                dp[j] = min(dp[j],dp[j - v[i]] + w[i]);  
            } 
		}
	   int ans = 0;  
        for(int i = s; i >= 0; i--){  
            if(dp[i] <= m){  
                ans = i;  
                break;  
            }  
        } 
		cout<<ans<<endl;
	}
	return 0; 
 }

猜你喜欢

转载自blog.csdn.net/duanghaha/article/details/80041355
今日推荐