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.
* 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
题解:
贪心
贪心策略(分三步):
1、显然先把大于c的全部出完
2、从大到小只要不超过c,能出就出
3、从小到大能出就出,直到刚好超过c
证明:显然每次出钱需要浪费的尽量少,这样每次出只会使得出的钱刚好等于c或大于c一点点,所以每次是最优的
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
using namespace std;
const int N =25;
struct Node {
int a,b;
bool operator < (const Node &x) const {
return a<x.a;
}
}p[N];
int gi() {
int x=0,o=1; char ch=getchar();
while(ch!='-' && (ch<'0' || ch>'9')) ch=getchar();
if(ch=='-') o=-1,ch=getchar();
while(ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
return o*x;
}
int main() {
int n=gi(),c=gi(),i,ans=0;
for(i=1; i<=n; i++) p[i].a=gi(),p[i].b=gi();
sort(p+1,p+n+1);
i=n;
while(p[i].a>c) ans+=p[i].b,i--;
n=i;
while(1) {
int now=0;
for(i=n; i>=1; i--) {
while(p[i].b && now+p[i].a<=c) {
now+=p[i].a;
p[i].b--;
}
}
for(i=1; i<=n; i++) {
while(p[i].b && now<c) {
now+=p[i].a;
p[i].b--;
}
}
if(now<c) break;
ans++;
}
printf("%d", ans);
return 0;
}