问题描述
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
问题分析
整数划分问题是将一个正整数n拆成一组数连加并等于n的形式,且这组数中的最大加数不大于n。
如6的整数划分为
6
5 + 1
4 + 2, 4 + 1 + 1
3 + 3, 3 + 2 + 1, 3 + 1 + 1 + 1
2 + 2 + 2, 2 + 2 + 1 + 1, 2 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1
共11种。
主要是通过递归来实现,递归函数为int split(int n,int m) ,其中n是待划分的正整数,m是划分中最大的加数。返回值即为划分的种数。
(1)当n=1或者m=1,split(n,m)=1;
(2)当m>n,最大加数不可能比要划分的正整数大,所以,split(n,m)=split(n,n)
(3)当n=m,split(n,m)=split(n,m-1)+1。比如说:split(6,6)=1+split(6,5)。也就是说整数6的划分可以分为6和最大加数为5的两部分。
(4)当n>m,split(n,m)=split(n,m-1)+split(n-m,m)。比如说split(6,4)=split(6,3)+split(2,4)
其中:
split(6,3) :
3 + 3, 3 + 2 + 1, 3 + 1 + 1 + 1
2 + 2 + 2, 2 + 2 + 1 + 1, 2 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1
split(2,4):
4 + 2, 4 + 1 + 1
这些划分方法有相同的整数m(这里是4)。所以,把所有划分都减去4,就相当于求正整数n-m的划分种类数。
AC代码
# include<stdio.h>
# include<string.h>
#define MAX 125
int num[MAX][MAX];//使用数组将已经计算过的值保存起来,免得递归重复计算
int split(int n,int m);
int main()
{
memset(num,0,sizeof(num));
int N;
while(scanf("%d",&N)!=EOF)
{
printf("%d\n",split(N,N));
}
return 0;
}
int split(int n,int m)
{
if(num[n][m])
return num[n][m];
else if(n==1||m==1)
num[n][m]=1;
else if(n>m)
num[n][m]=split(n,m-1)+split(n-m,m);
else if(n<m)
num[n][m]=split(n,n);
else if(n==m)
num[n][m]=split(n,m-1)+1;
return num[n][m];
}