Allowance
Description
As a reward for record milk production, Farmer John has decided to start paying Bessie the cow a small weekly allowance. FJ has a set of coins in N (1 <= N <= 20) different denominations, where each denomination of coin evenly divides the next-larger denomination (e.g., 1 cent coins, 5 cent coins, 10 cent coins, and 50 cent coins).Using the given set of coins, he would like to pay Bessie at least some given amount of money C (1 <= C <= 100,000,000) every week.Please help him ompute the maximum number of weeks he can pay Bessie.
Input
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Each line corresponds to a denomination of coin and contains two integers: the value V (1 <= V <= 100,000,000) of the denomination, and the number of coins B (1 <= B <= 1,000,000) of this denomation in Farmer John's possession. Output
* Line 1: A single integer that is the number of weeks Farmer John can pay Bessie at least C allowance
Sample Input 3 6 10 1 1 100 5 120 Sample Output 111 Hint
INPUT DETAILS:
FJ would like to pay Bessie 6 cents per week. He has 100 1-cent coins,120 5-cent coins, and 1 10-cent coin. OUTPUT DETAILS: FJ can overpay Bessie with the one 10-cent coin for 1 week, then pay Bessie two 5-cent coins for 10 weeks and then pay Bessie one 1-cent coin and one 5-cent coin for 100 weeks. Source |
题意:
有n种面额的硬币。且面值大的一定能被面值小的整除。现告诉你每种面值硬币的个数。和一个值c。每周支出的钱必须大于等于c。问钱最多能用多少周。
思路:
贪心。大概都能想到。关键是如何寻找最优策略。对于面值大于c的硬币自然不用说。一枚用一周。
对于面值小于c的硬币。我们先考虑一个c的方案。要使用的周数最多我们应该就要使钱的利用率最大。
也就是说损失的钱最少。尽量不要超过c太多。在不超过c的情况下对于大面值和小面值的优先使用大面值的。应为小面值的组合可得到大面值的(整除关系)。留下小面值的给后面的组合最优的可能性越大。如这种策略下没凑够c的话就
找一个最小的面额。使得组合值大于c。(使损失值最小)
详细见代码:
#include <iostream>
#include<algorithm>
#include<math.h>
#include<stdio.h>
#include<string.h>
const int INF=0x3f3f3f3f;
using namespace std;
struct node
{
int val,mou;//面值和数目
} mon[25];
int n,c;
int need[25];//一种方案所需各面值的数目
bool cmp(node a,node b)
{
return a.val<b.val;
}
int main()
{
int i,ans,ti,rest,lim,mday;
while(~scanf("%d%d",&n,&c))
{
ans=0;
lim=-1;
for(i=0;i<n;i++)
scanf("%d%d",&mon[i].val,&mon[i].mou);
sort(mon,mon+n,cmp);
for(i=n-1;i>=0;i--)
if(mon[i].val>=c)//如果面值大于c直接加数目就行了
ans+=mon[i].mou;
else
{
lim=i;
break;
}
while(1)
{
memset(need,0,sizeof need);
rest=c;
for(i=lim;i>=0;i--)//尽可能用大面值凑够
{
if(!mon[i].mou||!rest)
continue;
ti=rest/mon[i].val;
ti=min(ti,mon[i].mou);
need[i]=ti;
rest-=ti*mon[i].val;
}
if(rest)//没凑够的话。只能往回找最小的面值凑够。保证损失的钱最少
{
for(i=0;i<=lim;i++)
{
if(mon[i].val>=rest&&(mon[i].mou-need[i]))
{
need[i]++;
rest=0;
break;
}
}
if(rest)
break;
}
mday=INF;
for(i=0;i<=lim;i++)
if(need[i])
mday=min(mday,mon[i].mou/need[i]);//得出该种方案能支付的最大周数
ans+=mday;
for(i=0;i<=lim;i++)
mon[i].mou-=mday*need[i];
}
printf("%d\n",ans);
}
return 0;
}
/*
11
6 1
4 1
*/