hdoj-1028-Ignatius and the Princess III

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

本题的意思是:整数划分问题是将一个正整数n拆成一组数连加并等于n的形式,且这组数中的最大加数不大于n。
下面看一看m 和 n的关系。它们有三种关系
(1) m > n
在整数划分中实际上最大加数不能大于n,因此在这种情况可以等价为judge(n, n);
可用程序表示为if(m > n) return judge(n, n);
(2) m = n
这种情况可用递归表示为judge(n, m - 1) + 1,从以上例子中可以看出,就是最大加
数为6和小于6的划分之和
用程序表示为if(m == n) return (judge(n, m - 1) + 1);
(3) m < n
这是最一般的情况,在划分的大多数时都是这种情况。
从上例可以看出,设m = 4,那judge(6, 4)的值是最大加数小于4划分数和整数2的划分数的和。
因此,judge(n, m)可表示为judge(n, m - 1) + judge(n - m, m)

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

int dp[125][125];

int judge(int n,int m)
{
    if(dp[n][m]!=-1) return dp[n][m];
    if(n<1||m<1) return dp[n][m]=0;
    if(n==1||m==1) return dp[n][m]=1;
    if(n<m) return dp[n][m]=judge(n,n);
    if(n==m) return dp[n][m]=judge(n,m-1)+1;
    return dp[n][m]=judge(n,m-1)+judge(n-m,m);
}

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        memset(dp,-1,sizeof(dp));
        printf("%d\n",judge(n,n));
    }
    return 0;
}

你可能感兴趣的:(hdoj-1028-Ignatius and the Princess III)