Ignatius and the Princess III 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.
Examples
Sample Input
4
10
20
Sample Output
5
42
627
Hint
题意:
给出N, 求出N的所有可能划分组.
题解:
经典的划分数问题, 在此简单总结一下划分数问题
dp[i][j]称为 j的 i划分数, 即将j 分为不超过 i组的最大划分数量, 我们考虑如何建立状态转移方程
对于j 的i 划分, 划分情况分为两种情况:
- 划分中每个数都小于 i,相当于每个数不大于 i - 1, 故划分数为 dp[ i -1][ j ].
- 划分中有一个数为 i . 那就在 j 中减去 i ,剩下的就相当于把 j - i 进行划分, 故划分数为 dp[ i ][j - i];
举个例子来说, dp[3][4], 4划分为不超过3组
我们先考虑组成数不超过3的情况, 也就是dp[2][4], 共1+1+1, 2+1+1, 2+2三组
再来考虑存在3以上的可能, 只有3+1这一组, 相当于dp[3][1], 也就是dp[1][1]
说明一下, dp[0][0]一定要初始化为1, 表示为这个数它自身那一组, j 一定要从0开始循环, 考虑边界问题
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const LL maxn = 125;
int dp[maxn][maxn];
int main()
{
int n;
while(cin >> n){
ms(dp, 0);
dp[0][0] = 1;
for(int i = 1; i <= n; i++)
for(int j = 0; j <= n; j++){
if(j >= i)
dp[i][j] = dp[i-1][j]+dp[i][j-i];
else
dp[i][j] = dp[i-1][j];
}
cout << dp[n][n] << endl;
}
return 0;
}
参考博客: https://blog.csdn.net/codingdd/article/details/61414550