SDNU-1539. Do you like Hot Dog ?(背包问题:价值超大,重量小)

SDNU-1539. Do you like Hot Dog ?

Description

Given a set of n n n hot dog, each with a price p [ i ] p[i] p[i] and a happy value v [ i ] v[i] v[i], determine a way to choose the items into a knapsack so that the total price is less than or equal to a given limit P P P 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 T T T indicating to the number of test cases.

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

Following n n n lines provide the information of each item.

The i t h i_{th}​ ith line contains the price p [ i ] p[i]​ p[i] and the happy value v [ i ] v[i]​ v[i] of the i t h i_{th}​ ith item respectively.

1 &lt; = n u m b e r o f t e s t c a s e s &lt; = 10 1 &lt;= number of test cases &lt;= 10 1<=numberoftestcases<=10

1 &lt; = n &lt; = 500 1 &lt;= n &lt;= 500 1<=n<=500

1 &lt; = P , w [ i ] &lt; = 1000000000 1 &lt;= P, w[i] &lt;= 1000000000 1<=P,w[i]<=1000000000

1 &lt; = v [ 1 ] + v [ 2 ] + . . . + v [ n ] &lt; = 5000 1 &lt;= v[1]+v[2]+...+v[n] &lt;= 5000 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

题意就是普通背包的题意,就是给的数据范围有些大。
一开始用普通的做法,然后一直RE,后来看学长的题解,发现了他是求价值为多少时的最小体积,我用一维优化了一下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
int v[1005]/*价值*/,w[1005]/*体积*/,f[5005];//价值最大为5000
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        fill(f,f+5005,INF);//取最小要都弄成正无穷,一开始因为这个一直错。。。
        f[0]=0;
        int V,n;
        scanf("%d%d",&n,&V);
        for (int i=1;i<=n;i++)
            scanf("%d%d",&w[i],&v[i]);
        for (int i=1;i<=n;i++)
            for (int j=5001;j>=v[i];j--)
            //虽然不知道他给的价值的和最大是多少(可以求),但是给出了价值上限为5000,可以利用一下,也可以求出,提高解题的范围
                f[j]=min(f[j],f[j-v[i]]+w[i]);
               //记住在同价值下,求得体积越小,价值也就越大
        int ans=0;
        for (int i=1;i<=5000;i++)//找到最大价值&&小于V的,然后输出。
            if (f[i]<=V)
                ans=i;
        printf("%d\n",ans);
    }
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 10:56
点赞 评论 收藏
分享
05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
大方的大熊猫准备进厂:1.教育背景:你希望从事什么专业的工作你的主修课就是什么;成绩优秀是你应该做的,没什么可描述的,成绩不优秀也许人家在大学忙着创业呢?(成绩优秀不一定是好事,只能说明多元化的大学你上成了高中,没有真正上明白大学,反而体现了你死板,不爱社交,没有别的突出能力) 2.实践经历:你想表达的意思没有说清楚。你是说你会个性化服务,还是你有实习经历。如果没有带来,经济收益,表彰,更好的发展前景,那你还不如说说提升了自己哪些技能。你说有人给你送锦旗我都能明白你优秀,但是你说你会xxxx,你说这话谁信,证据呢。 3.入伍经历:你描述的就是你的工作职责或者你应该做的,并没有体现出来你把这个事情做好了,而且入伍经历并不能证明你能干好你要应聘的工作,不如只写经历其余所有内容都不写。 4.荣誉技能:重点突出一下,但不要过多描述,这些荣誉的含金量懂得都懂。 重点:你要应聘什么工作(具体岗位,实习生不具体),你的期望薪资
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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