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.
思路:对硬币按照面值降序排列,制定支付方法时,首先从大到小找,不能够等于C时从小到大找,这样就能够找达到当前最优 的支付方式,进行支付,然后再次寻找支付方式直到硬币不足以支付C
#include<iostream>
#include<cstdio>
#include<fstream>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#include<cstring>
#define MAX 25
#define INF 10000000
using namespace std;
struct coin{
int den;
int num;
};
bool cmp(coin x, coin y){
return x.den >y.den;
}
int N, C;
coin c[MAX];
int use[MAX];
void Solve(){
int ans = 0;
while(true){
memset(use,0,sizeof(use));
int rest = C;
//先从大到小取
for(int i=0; i<N; i++){
use[i] = min(rest/c[i].den, c[i].num);
rest -= c[i].den * use[i];
}
//钱不能够正好凑到C的话从小到大取
if(rest){
for(int i=N-1; i>=0; i--)
if(c[i].num && c[i].den>=rest){
use[i]++;
rest = 0;
break;
}
}
//所有的钱都凑上去还不够
if(rest)break;
int minx = INF;
//求出剩下的钱还能这样付几周
for(int i=0; i<N; i++){
if(use[i])
minx = min(c[i].num/use[i], minx);
}
ans += minx;
//更新硬币数量
for(int i=0; i<N; i++){
if(use[i]){
c[i].num -= use[i] * minx;
}
}
}
cout << ans << endl;
}
//测试函数
int main(){
ifstream in ("D:\\钢铁程序员\\程序数据\\040贝西的零花钱.txt");//从文件读取数据流,省去手动输入的麻烦
if(!in){//读取如果失败
cout << "ERROR" << endl;
}
in >> N >> C;
for(int i=0; i<N; i++)
in >> c[i].den >> c[i].num;
sort(c,c+N,cmp);
Solve();
in.close();//打开文件以后要关闭
return 0;
}