Description
Input
* 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
Sample Input
3 6 10 1 1 100 5 120
Sample Output
111
Hint
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.
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 10000000
struct money
{
int va;//面值
int zh;//該面值錢的數目
}A[25];
typedef struct money money;
bool cmp(money a,money b)
{
return a.va>b.va;
}//按照面值從大到小來排序
int main()
{
int n,c,t;
int need[25];//用來儲存第i種方案
while(scanf("%d%d",&n,&c)!=EOF)
{
int sum=0;
int i;
int co=0;
int lim=30;//lim的初始賦值應該值得注意,由於我是尋找面值從大到小,所以把lim的值應該比最大組數大,否則後面跳不出循環。如果面值從小到大尋找又不一樣
for(i=0;i<n;i++)
scanf("%d%d",&A[i].va,&A[i].zh);
sort(A,A+n,cmp);
for(i=0;i<n;i++)
{
if(A[i].va>=c)
sum=sum+A[i].zh;
else
{
lim=i;//記錄面值小於c的i組
break;
}
}//大於c的直接加
while(1)
{
memset(need,0,sizeof(need));
t=c;//t是相當於一個c的替代品
for(i=lim;i<n;i++)
{
if(!A[i].zh||!t)
continue;
co=t/A[i].va;
co=min(co,A[i].zh);
need[i]=co;
t=t-need[i]*A[i].va;
}//面值小於c的儘量加大的,並且儘量接近或等於c而不超過c
if(t)
{
for(i=n-1;i>=lim;i--)
{
if(A[i].va>=t&&A[i].zh>need[i])
{
need[i]++;
t=0;
break;
}
}
if(t)
break;
}//從面值最小的往上找,找到就跳出
int minn=INF;
for(i=lim;i<n;i++)
if(need[i])
minn=min(minn,A[i].zh/need[i]);//第i種方案可以給多少個星期
sum+=minn;
for(i=lim;i<n;i++)
if(need[i])
A[i].zh-=minn*need[i];//當第i種方案儘量用了張數後面值i所剩下的張數,進行i+1種方案
}
printf("%d\n",sum);
}
return 0;
}