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;
}

全部评论

相关推荐

07-02 18:09
门头沟学院 Java
苍穹外卖和谷粒商城这俩是不是烂大街了,还能做吗?
想去重庆的鸽子在吐槽:你不如把这俩做完自己搞明白再优化点再来问 何必贩卖焦虑
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务