Ignatius and the Princess III
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 13635 Accepted Submission(s): 9634
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!"
"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数组,dp[n][m]代表着将整数n分为小于m的数。
那么接下来将要分情况进行讨论。
先将dp的数组的值用memset函数进行初始化为-1.
假设当dp的值不为-1时,那么我们可以知道这种情况已经进行过讨论,则可以返回dp的值了。
我们可以显然的看出来,当n=1或者m=1时,分离的方法都只有1中
即:if(n==1||m==1)
return dp[n][m]=1;
而且当n<1或者m<1时,该dp数组表示的值应该为0,即此时没有任何意义。
第一种情况:
当n<m时,则dp[n][m]的值和dp[n][n]的值应该相同。
第二种情况:
当n==m时,则我们可以选择是否将m这个数分离。
如果选择分离的话,则只有一种分法,
若果选择不进行分离的话,则将n分为小于m-1的几个值,即其值为dp[n][m-1]。
则dp[n][m]=1+dp[n][m-1];
第三种情况:
当n>m时,也进行是否将m进行分离的选择。
将m进行分离时,返回的值应该为dp[n-m][m];
不将m进行分离的时候,返回的值应该为dp[n][m-1];
注意dp[n][m]要包含所有的分离方法,所以要将所讨论的情况全部加起来。
#include <iostream>
#include<cstring>
using namespace std;
const int Max=130;
int dp[Max][Max];
//进行动态规划的循环
int dyx(int n,int m)
{
//dp[n][m]代表着将n分解成不大于m的数。
if(dp[n][m]!=-1)
return dp[n][m];
//接下来分为多种情况进行讨论。
//当n,m都等于-1时,dp的数组值为0;
if(n==m==-1)
return dp[n][m]=0;
//当n,m的值均为1时,dp的数组值为1;
if(n==1||m==1)
return dp[n][m]=1;
//当n<m时
if(n<m)
return dp[n][m]=dyx(n,n);
//当n==m时,又分为两种情况进行说明,
if(n==m)
return dp[n][m]=1+dyx(n,m-1);
else
return dp[n][m]=dyx(n,m-1)+dyx(n-m,m);
}
int main()
{
int N;//定义输入的一个整数,N<120;
int c;
memset(dp,-1,sizeof(dp));
while(cin>>N)
{
c=dyx(N,N);
cout<<c<<endl;
}
return 0;
}