[POJ3040] 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
題解:
貪心
貪心策略(分三步):
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;
}
總結
以上是生活随笔為你收集整理的[POJ3040] Allowance的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: this关键字+super关键字
- 下一篇: final+static