Allowance - poj3040 - 贪心

Allowance

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5604   Accepted: 2195

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

USACO 2005 October Silver

思路:

好题啊~

为了能提供更多的天数,我们肯定从面值大的钱开始(题中也说了大的面值是小面值的倍数,所以我们选大的,若换成小的则需要更多钱币)

从大面值开始一直凑到小于等于C,然后从小面值的凑够大于等于C,因为超出的钱越少,越好,所以从小面值开始。

还有一点要注意的:

比如C=20,现在大面值的凑到了16,小面值的有2、4,则选4不选两张2,也就是说,大面值凑的时候已经是最接近C的了,小面值应选1张让其满足就行了,若选两张2的话是有点浪费钱币张数了

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue> 
 
using namespace std;
const int INF=0x3f3f3f3f;
struct A{
	int val,num;
}money[25];

int tmp[25];

bool cmp(A a,A b){
	return a.val>b.val;
}

int main(){
	int n,c,x,y;
	scanf("%d%d",&n,&c);	
	int ans=0,m=0;
	for(int i=0;i<n;i++){
		scanf("%d%d",&x,&y);
		if(x>=c)ans+=y;
		else {
			money[m].val=x;
			money[m++].num=y;
		}
	}
	
	sort(money,money+m,cmp);
	//用tmp[i]数组临时记录,数i组成c,需要多少个 
	while(1){
		memset(tmp,0,sizeof(tmp));
		int s=c;
		//这一轮凑够小于等于c需要的每个数多少 
		for(int i=0;i<m;i++){
			tmp[i]=min(money[i].num,s/money[i].val);
			s-=tmp[i]*money[i].val;
		}
	
		//在小于c的情况下,再从小的往大凑
		if(s>0){
			for(int i=m-1;i>=0;i--){
				if(money[i].num>=1&&money[i].val>=s){
					tmp[i]++;
					s-=money[i].val;
					break;
				}
			}
		}

		if(s>0)break;//如果怎么都凑不够一个c那就结束
		int mymin=INF; 
		for(int i=0;i<m;i++){
			if(tmp[i])mymin=min(mymin,money[i].num/tmp[i]);
		}
		
		ans+=mymin;
		int flag=0;
		for(int i=0;i<m;i++){
			if(tmp[i]){
				money[i].num-=(mymin*tmp[i]);
			}
			if(money[i].num)flag=1;
		}
		if(!flag)break;
	} 
	printf("%d\n",ans);
}

猜你喜欢

转载自blog.csdn.net/m0_37579232/article/details/81408442