题目链接;https://vjudge.net/problem/HDU-1028
题目:
"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
题解:
这道题可以用dp或者母函数解决。
dp: 用f[i][j]表示 整数i划分成每个数都不大于j的方案数。
1. f[i][1]=1.
2. if(j>i) f[i][j]=f[i][i] 显然成立
3. if(j==i) f[i][j]=f[i][j-1]+1 整数i划分成每个数都不大于j的方案数=整数i划分成最大值为j的方案数+整数i划分成最大值小于j的方案数。 因为i==j 整数i划分成最大值为j的方案数等于1
4 f[i][j]=f[i-j][j]+f[i][j-1]; 整数i划分成每个数都不大于j的方案数=整数i划分成最大值为j的方案数+整数i划分成最大值小于j的方案数。 f[i-j][j]表示最大值为j,那么把剩下的i-j继续划分。
母函数:
f(x)=(1+x+x2+x3+x4+...)(1+x2+x4+x6+...)(1+x3+x6+x9+...)
母函数展开后,第 X的n次幂项的系数就是数字n的划分数。
下边分别给出两种代码:
dp:
#include<bits/stdc++.h>
using namespace std;
const int maxn=125;
int f[maxn][maxn];
int n;
int main(){
f[0][0]=1;
for(int i=1;i<maxn;i++){
for(int j=1;j<maxn;j++){
if(j==1){
f[i][j]=1;
}else if(j>i){
f[i][j]=f[i][i];
}else if(j==i){
f[i][j]=f[i][j-1]+1;
}else{
f[i][j]=f[i-j][j]+f[i][j-1];
}
}
}
while(scanf("%d",&n)!=EOF){
printf("%d\n",f[n][n]);
}
return 0;
}
母函数:
#include<bits/stdc++.h>
using namespace std;
const int maxn=121;
int c[maxn+1],c2[maxn];
int n;
void init(){
for(int i=0;i<=maxn;i++){
c[i]=1;
}
for(int k=2;k<=maxn;k++){
for(int i=0;i<=maxn;i++){
for(int j=0;j+i<=maxn;j+=k){
c2[i+j]+=c[i];
}
}
for(int i=0;i<=maxn;i++){
c[i]=c2[i];c2[i]=0;
}
}
}
int main(){
init();
while(scanf("%d",&n)!=EOF){
printf("%d\n",c[n]);
}
return 0;
}