HUNNU11392:Candy Store (完全背包)

来源:互联网 发布:mac os 10.12 beta8 编辑:程序博客网 时间:2024/06/06 17:33

http://acm.hunnu.edu.cn/online/?action=problem&type=show&id=11392&courseid=0

You are walking with a friend, when you pass a candy store. You make a comment about
how unhealthy their wares are. Your friend issues an interesting challenge: who can be
the unhealthiest? Both of  you will go into the store with the same amount of money.
Whoever buys candy with the most total calories wins!
Since you're a smart computer scientist, and since you have access to the candy store's
inventory, you decide not to take any chances. You will write a program to determine
the most calories you can buy. The inventory tells you the price and calories of every
item. It also tells you that there is so much in stock that you can buy as much of any kind
of candy as you want. You can only buy whole pieces of candy.
Input
There will be multiple test cases in the input. Each test case will begin with a line with an
integer n (1≤n≤5,000), and an amount of money m ($0.01≤m≤$100.00), separated by a
single space, where n  is the number of different types of candy  for sale, and m  is the
amount of money you have to spend.  The monetary amount m will be expressed in
dollars with exactly two decimal places, and with no leading zeros unless the amount is
less than one dollar. There will be no dollar sign. Each of the next n  lines will have an
integer  c  (1≤c≤5,000)  and an amount of money  p  ($0.01≤p≤$100.00),  separated by a
single space, where c  is the number of calories in a  single piece of candy, and p  is the
price of a single piece of candy, in dollars and in the same format as m. The input will
end with a line containing '0 0.00'.
Output
For each test case, output a single integer, indicating the maximum amount of calories
you can buy with up to m dollars. Output no spaces, and do not separate answers with
blank lines.
Sample Input
2 8.00
700 7.00
199 2.00
3 8.00
700 7.00
299 3.00
499 5.00
0 0.00
Sample Output
796
798
 
 题意:给出每个食物的卡路里与价格,要求在身上钱一定的情况下能得到最大的卡路里是多少

思路:裸完全背包,将价格乘以100方便计算,但是要注意精度

 

#include <stdio.h>#include <string.h>#include <math.h>#include <algorithm>using namespace std;double ep = 1e-9;long long dp[500005];int val[5005],price[5005];int main(){    int n,i,j,s;    double sum,x;    while(~scanf("%d%lf",&n,&sum))    {        if(n+sum<ep)            break;        s = (floor)(sum*100);        memset(dp,0,sizeof(dp));        for(i = 0; i<n; i++)        {            scanf("%d%lf",&val[i],&x);            price[i] = (floor)(x*100);//保持精度,不要用强制转化        }        for(i = 0; i<n; i++)        {            for(j = price[i]; j<=s;j++)            {                dp[j] = max(dp[j],dp[j-price[i]]+val[i]);            }        }        printf("%lld\n",dp[s]);    }    return 0;}


 

原创粉丝点击