HDU 1028 Ignatius and the Princess III(母函数或完全背包)

Ignatius and the Princess III

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 22682    Accepted Submission(s): 15839


Problem Description
"Well, it seems the first problem is too easy. I will let you know how foolish you are later." feng5166 says.

"The second problem is, given an positive integer N, we define an equation like this:
  N=a[1]+a[2]+a[3]+...+a[m];
  a[i]>0,1<=m<=N;
My question is how many different equations you can find for a given N.
For example, assume N is 4, we can find:
  4 = 4;
  4 = 3 + 1;
  4 = 2 + 2;
  4 = 2 + 1 + 1;
  4 = 1 + 1 + 1 + 1;
so the result is 5 when N is 4. Note that "4 = 3 + 1" and "4 = 1 + 3" is the same in this problem. Now, you do it!"
 

 

Input
The input contains several test cases. Each test case contains a positive integer N(1<=N<=120) which is mentioned above. The input is terminated by the end of file.
 

 

Output
For each test case, you have to output a line contains an integer P which indicate the different equations you have found.
 

 

Sample Input
4 10 20
 

 

Sample Output
5 42 627
 

 

Author
Ignatius.L
 

 

Recommend
We have carefully selected several similar problems for you:  1171 1085 1398 2152 1709 
 
 

分析:

   第一种解法,可以看作一个完全背包问题,一共有1到120的硬币,每种硬币无数个,问要得到需要的金额,有多少种硬币组合方式

    代码如下:

 

#include <cstdio>
#include <iostream>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
typedef long long ll;
int n;
int dp[130]={1};
int main()
{
    for(int i=1;i<=120;i++)
       for(int j=i;j<=120;j++)
        dp[j]+=dp[j-i];
     int n;
     while(scanf("%d",&n)!=EOF)
     {
         printf("%d\n",dp[n]);
     }
    return 0;
}

    第二种解法  母函数 

代码如下:

#include<iostream>
using namespace std;
#define M 1000
#define MAXN 130      //MAXN为最大有多少项相乘
int a[M],b[M];//a[M]中存最终项系数;b[M]中存取中间变量;
int main()
{
    int m,n;
    int i,j,k;
    m=MAXN;
    while(scanf("%d",&n)!=EOF)
    {
        //可以加一个跳出循环的条件
        //n为所求的指数的值: ";
        //因为只求指数为n的系数的值:所以循环只到n就结束
        for(i=0;i<=n;i++)//初始化第一个式子:(1+X^2+X^3+...) 所以将其系数分别存到a[n]
        {
            a[i]=1;
            b[i]=0;
        }
        for(i=2;i<=m;i++)//从第2项式子一直到第n项式子与原来累乘项的和继续相乘
        {
            for(j=0;j<=n;j++)//从所累乘得到的式子中指数为0遍历到指数为n 分别与第i个多项式的每一项相乘
                 for(k=0;k+j<=n;k+=i)//第i个多项式的指数从0开始,后面的每项指数依次比前面的多i,比如当i=3时,第3项的表达式为(1+x^3+x^6+x^9+……),直到所得指数的值i+j>=n退出
                 {
                     b[j+k]+=a[j];//比如前面指数为1,系数为3,即a[1]=3 的一项和下一个表达式的指数为k=3的相乘,则得到的式子的系数为,b[j+k]=b[4]+=a[1],又a[1]=3,所以指数为4的系数为b[4]=3;
                 }

             for(j=0;j<=n;j++)//  然后将中间变量b数组中的值依次赋给数组a,然后将数组b清零,继续接收乘以下一个表达式所得的值
              {
                  a[j]=b[j];
                  b[j]=0;
              }
        }
        printf("%d\n",a[n]);  // 指数为n的项的系数为:
    }

    return 0;
}

 

posted @ 2017-09-14 20:57  hinata_hajime  阅读(191)  评论(0编辑  收藏  举报