Holding Bin-Laden Captive!(母函数或多重背包)

来源:互联网 发布:大数据精准营销案例 编辑:程序博客网 时间:2024/05/16 18:04

HDOJ1085:

    

Problem Description
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
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
Output the minimum positive value that one cannot pay with given coins, one line for one case.
 

Sample Input
1 1 30 0 0
 

Sample Output
4
 

#include <iostream>using namespace std;int main(){    int num_1,num_2,num_5;    int c1[10000],c2[10000];    while(cin>>num_1>>num_2>>num_5&&(num_1||num_2||num_5))    {        int maxn=num_1+num_2*2+num_5*5;        for(int i=0;i<=maxn;i++)//初始化;            c1[i]=c2[i]=0;        for(int i=0;i<=num_1;i++)//定义(1+x+x^2+...+x^num_1);        {            c1[i]=1;            c2[i]=0;        }        for(int i=0;i<=num_1;i++)//(1+x+x^2+...+x^num_1)(1+x^2+x^4+...+x^(num2*2));            for(int j=0;j<=num_2*2;j+=2)                c2[i+j]+=c1[i];        for(int i=0;i<=num_1+num_2*2;i++)        {            c1[i]=c2[i];            c2[i]=0;        }        for(int i=0;i<=num_1+num_2*2;i++)//(1+x+x^2+...+x^(num_1+num_2*2))(1+x^5+x^10+...+x^(num5*5));            for(int j=0;j<=num_5*5;j+=5)                c2[i+j]+=c1[i];        for(int i=0;i<=num_1+num_2*2+num_5*5;i++)            c1[i]=c2[i];        int i;        for(i=1;i<=maxn;i++)            if(c1[i]==0)            {                cout<<i<<endl;                break;            }        if(i>maxn)            cout<<i<<endl;    }    return 0;}

多重背包:#include <iostream>using namespace std;int main(int argc, char **argv){int  num[3],f[10000];int  a[3]={1,2,5};f[0]=0;while(cin>>num[0]>>num[1]>>num[2]&&(num[0]||num[1]||num[2])){int sum=num[0]+num[1]*2+num[2]*5;for(int i=1;i<=sum;i++)f[i]=-0xfffffff;for(int i=0;i<3;i++)for(int j=0;j<num[i];j++)for(int k=sum;k>=a[i];k--)f[k]=max(f[k],f[k-a[i]]+a[i]);int i;for(i=1;i<=sum;i++)if(f[i]<0){cout<<i<<endl;break;}if(i>sum)cout<<i<<endl;}return 0;}