1539.Do you like Hot Dog ?SDNUOJ1539(2018总结赛)

Description
Hot dog is a very delicious food,and Goc like it very much. The picture below shows how much does Goc like it. hhhhh…

Given a set of hot dog, each with a price and a happy value , determine a way to choose the items into a knapsack so that the total price is less than or equal to a given limit ​ and the total happy value is as large as possible. Find the maximum total happy value. (Note that each item can be only chosen once).
Input
The first line contains the integer ​ indicating to the number of test cases.

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

Following ​ lines provide the information of each item.

The line contains the price and the happy value of the ​ item respectively.

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

因为重量变化范围大,枚举背包容量易超时,换位,枚举取得一定价值时的最小重量

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
using namespace std;
#define N 2500005
int v[505];
int w[505];
int m[N];///表示当前总重量
const int INF = 0x3f3f3f3f;///表无穷大

int main()
{
    int t;
    while(~scanf("%d", &t))
    {
        while(t--)
        {
            int n;
            int p;
            int ans = 0;
            scanf("%d%d", &n, &p);
            for(int i = 1; i <= n; i++)
                scanf("%d%d", &w[i], &v[i]);
            fill(m, m + sizeof(m) / sizeof(int), INF);
            m[0] = 0;///没物品可选,重量为0
            for(int i = 1; i <= n; i++)
            {
                for(int j = 5000; j >= v[i]; --j)
                    m[j] = min(m[j], m[j-v[i]] + w[i]);///min最小重量
            }
            for(int i = 5000; i >= 0; --i)
            {
                if(m[i] <= p)///小于限制重量(背包容量)的最大价值
                {
                    ans = i;
                    break;
                }
            }
            cout << ans << '\n';
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhaobaole2018/article/details/85122136
Dog
今日推荐