您的位置:首页 > 其它

FZU - 2214 C - Knapsack problem 超大背包

2018-01-29 19:51 155 查看
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
<= 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背包问题,但是他有个问题,就是他的体积特别大,我们正常的做法是dp【j】,j代表的是体积。体积为j时的价值为

多少,我们计算后直接输出dp【M】;

但是这个不可以,因为体积太大了,同时价值有特别小。所以我们反着想。dp【j】表示价值为j时的体积为多少。我们

计算完之后,因为要求最大价值嘛。我们倒着for循环,对于价值j,如果我们所需体积满足要求,那么直接输出j。

所以核心代码为

dp 1-n 设为INF。 表示当前想达到这个价值需要无限大的体积。

for(int i=0;i<n;i++)//对于当前货品

for(int j=V;j>=val[i];j--)//最大价值到最小价值

dp[j]=min(dp[j],dp[j-val[i]]-w[i]);

#include <iostream>

#include <algorithm>

#include <cstdio>

#include <cstring>

#include <vector>

#include <queue>

#include <stack>

using namespace std;

int dp[5500];

int w[1100];

int v[1100],V;

int INF=0x3f3f3f3f;

int n,m;

int main()

{

    int t;

    cin>>t;

    while(t--)

    {

        cin>>n>>m;

        V=0;

        for(int i=0;i<n;i++)

        {

            cin>>w[i]>>v[i];

            V=V+v[i];

        }

        memset(dp,INF,sizeof(dp));

        dp[0]=0;

        for(int i=0;i<n;i++)

        {

            for(int j=V;j>=v[i];j--)

            {

                dp[j]=min(dp[j],dp[j-v[i]]+w[i]);

            }

        }

        for(int j=V;j>=0;j--)

        {

            if(dp[j]<=m)

            {

                cout<<j<<endl;

                break;

            }

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: