码迷,mamicode.com
首页 > 其他好文 > 详细

题解报告:hdu 1028 Ignatius and the Princess III(母函数orDP)

时间:2018-05-20 10:45:53      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:else   rip   整数划分   mil   集合   content   eve   return   ESS   

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
解题思路:这题既可以用动态规划,也可以用母函数。
DP原先是递归而来的,这里就直接讲递推吧!
首先定义dp[i][j]记录将整数i划分成所有元素都不大于j(即小于或等于j)的所有情况数,下面举个栗子:
当i=4,j=1时,要求划分得到的所有元素都不大于j,所以划分法只有1种:{1,1,1,1};
当i=4,j=2时,。。。。。。。。。。。。。。。。。。。。。只有2种:{1,1,1,1},{2,1,1},{2,2};
当i=4,j=3时,。。。。。。。。。。。。。。。。。。。。。只有3种:{1,1,1,1},{2,1,1},{2,2},{3,1};
当i=4,j=4时,。。。。。。。。。。。。。。。。。。。。。只有4种:{1,1,1,1},{2,1,1},{2,2},{3,1},{4};
当i=4,j=5,6.....n(n为自然数)时,。。。。。。。。。。只有4种:{1,1,1,1},{2,1,1},{2,2},{3,1},{4};
从以上规律可以推出结论:当i==1||j==1,只有一种划分法;
当i<j时,由于发法不可能出现负数,所以dp[i][j]=dp[i][i];
当i==j时,分两种情况:①如果要分出j这一个数,那么情况只有1种:{j};②如果不分,那么就将i分成所有元素不大于j-1的若干份,dp[i][j]=dp[i][j-1]。所以总的情况数为dp[i][j]=dp[i][j-1]+1;
当i>j时,也分两种情况:①如果要分出j这一个数,注意此时的j<i,说明其剩下的(i-j)划分成的所有元素都在这个集合{j,a1,a2...}里,那么此时的dp[i][j]为把剩下的(i-j)这个整数划分成所有元素都不大于j时的情况数,即dp[i][j]=dp[i-j][j];②如果不分,那么就将i分成所有元素不大于j-1的若干份,dp[i][j]=dp[i][j-1]。所以总的情况数为dp[i][j]=dp[i-j][j]+dp[i][j-1]。
AC代码之DP:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 const int maxn = 125;
 5 LL dp[maxn][maxn];int n;//dp[i][j]记录将整数i划分成所有元素不大于j的所有情况数
 6 int main()
 7 {//打表
 8     for(int i=0;i<maxn;i++)//将整数i划分成所有元素不大于1的分法和将整数1划分成所有元素不大于i(其实只有1本身)的分法都为1种
 9         dp[i][1]=dp[1][i]=1;
10     for(int i=2;i<maxn;i++){//从2开始
11         for(int j=2;j<maxn;j++){
12             if(i<j)dp[i][j]=dp[i][i];
13             else if(i==j)dp[i][j]=dp[i][j-1]+1;
14             else dp[i][j]=dp[i][j-1]+dp[i-j][j];
15         }
16     }
17     while(cin>>n){
18         cout<<dp[n][n]<<endl;//最后输出总的情况数,即将整数n划分成不大于n的所有情况数
19     }
20     return 0;
21 }

 

题解报告:hdu 1028 Ignatius and the Princess III(母函数orDP)

标签:else   rip   整数划分   mil   集合   content   eve   return   ESS   

原文地址:https://www.cnblogs.com/acgoto/p/9062446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!