Ignatius and the Princess III
"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
题目大意:
对于给定一个数N要求给出所有的拆分方法,对应的如下所示
4 = 4;
4 = 3 + 1;
4 = 2 + 2;
4 = 2 + 1 + 1;
4 = 1 + 1 + 1 + 1;
并且跟顺序无关。
思路:使用生成函数
解题思路:若要划分正整数n,可分出的数有n种:1,2,……,n。这n个数相当于n种物品。每种物品可取可不取,取出数量无限制,但是这些物品(正整数)拿来求和时,贡献不一样,“物品1”1个顶1个,“物品2”1个顶2个,……所以n个原子多项式是
(1+x+x2+x3+...)
(1+x2+x4+x6+...)
(1+x3+x6+x9+...)
……
(1+xn+x2n+x3n+...)
于是,令生成函数
问题所求就是G(x)中xn项的系数。
code:
#include<iostream>
#include<cstring>
using namespace std;
int N;
const int MAXN = 130;
int c1[MAXN],c2[MAXN];
int main(){
while(~scanf("%d",&N)){
//初始化第一个 多项式
memset(c2,0,sizeof(c2));
for(int i=0;i<=N;i++) c1[i] = 1;
//第i个多项式
for(int i=2;i<=N;i++){
// 分别乘以原子多项式中的x^(ik)项,忽略ik>N的项
for(int k=0;k*i<=N;k++){
//生成函数中项的增量 就是原本的每一个项都加上 ik
for(int j=0;k*i+j<=N;j++)
c2[k*i+j] += c1[j];
}
memcpy(c1,c2,sizeof(c2));
memset(c2,0,sizeof(c2));
}
printf("%d\n",c1[N]);
}
return 0;
}