问题描述:
We all know that Bin-Laden is a notorious terrorist, and he has disappeared for a long time. But recently, it is reported that he hides in Hang Zhou of China!
“Oh, God! How terrible! ”
Don’t be so afraid, guys. Although he hides in a cave of Hang Zhou, he dares not to go out. Laden is so bored recent years that he fling himself into some math problems, and he said that if anyone can solve his problem, he will give himself up!
Ha-ha! Obviously, Laden is too proud of his intelligence! But, what is his problem?
“Given some Chinese Coins (硬币) (three kinds-- 1, 2, 5), and their number is num_1, num_2 and num_5 respectively, please output the minimum value that you cannot pay with given coins.”
You, super ACMer, should solve the problem easily, and don’t forget to take $25000000 from Bush!
输入:
Input contains multiple test cases. Each test case contains 3 positive integers num_1, num_2 and num_5 (0<=num_i<=1000). A test case containing 0 0 0 terminates the input and this test case is not to be processed.
输出:
Output the minimum positive value that one cannot pay with given coins, one line for one case.
Sample Input
1 1 3
0 0 0
Sample Output
4
代码:
#include<iostream>
using namespace std;
const int _max=8001;
int main()
{
int c1[_max],c2[_max];
int num[3];
int a[3]={1,2,5};
int i,j,k,s,n;
while(cin>>num[0]>>num[1]>>num[2] && !(num[0]==0 && num[1]==0 && num[2]==0))
{
//1、注意这里n要重新初始化为0,之前没有这一步,总是报错
n=0;
for(i=0;i<3;i++)
{
n+=num[i]*a[i];
}
//注意这里是初始化为0
for(i=0;i<=n+1;i++)
{
c1[i]=c2[i]=0;
}
//这里设置的是底层,第一个式子系数初始化为1,主要是因为第一个式子的系数决定了
//后面计算的结果,所以这个底层很重要
for(i=0;i<=num[0];i++)
{
c1[i]=1;
}
for(i=1;i<=2;i++)
{
for(j=0;j<=n;j++)//这里是前面累乘的系数,都要有
{
//这里continue的使用使算法优化很多
if(c1[j]==0)
{
continue;
}
//这里的处理是核心,注意到限制次数的是num[i],依据每个式子的情况而定
//j+k<=n 其实也可以省略
for(k=0,s=0;j+k<=n && s<=num[i];s++,k+=a[i])
{
c2[j+k]+=c1[j];
}
}
for(j=0;j<=n;j++)
{
c1[j]=c2[j];
c2[j]=0;
}
}
//这里用了break语句,它的使用使式子简洁了很多
for(i=1;i<=n+1;i++)
{
if(c1[i]==0)
break;
}
cout<<i<<endl;
}
return 0;
}//窍门就是代码的思路和自己计算的思路其实是一样的