整数划分
2016-12-01 01:12
232 查看
/** *@author StormMaybin *@date 2016-11-30 */
生命不息,奋斗不止。
各种整数划分问题
将n划分成不大于m的划分法:1. 若是划分多个整数可以存在相同的:
dp
[m]= dp
[m-1]+ dp[n-m][m] dp
[m]表示整数 n 的划分中,每个数不大于 m 的划分,则划分数可以分为两种情况:
a. 划分中每个数都小于 m,相当于每个数不大于 m- 1, 故划分数为 dp
[m-1].
b. 划分中有一个数为 m. 那就在 n中减去 m ,剩下的就相当于把 n-m 进行划分, 故划分数为 dp[n-m][m];
2. 若是划分多个不同的整数:
dp
[m]= dp
[m-1]+ dp[n-m][m-1] dp
[m]表示整数 n 的划分中,每个数不大于 m 的划分,同样划分情况分为两种情况:
a.划分中每个数都小于m,相当于每个数不大于 m-1,划分数为 dp
[m-1].
b.划分中有一个数为 m.在n中减去m,剩下相当对n-m进行划分,并且每一个数不大于m-1,故划分数为 dp[n-m][m-1];
将n划分成k个数的划分法:
dp
[k]= dp[n-k][k]+ dp[n-1][k-1];
方法可以分为两类:
第一类: n 份中不包含 1 的分法,为保证每份都 >= 2,可以先拿出 k 个 1 分到每一份,然后再把剩下的 n- k 分成 k 份即可,分法有: dp[n-k][k];
第二类: n 份中至少有一份为 1 的分法,可以先拿出一个 1 作为单独的1份,剩下的 n- 1 再分成 k- 1 份即可,分法有:dp[n-1][k-1];
将n划分成若干奇数的划分法:
g[i][j]:将i划分为j个偶数
f[i][j]:将i划分为j个奇数
g[i][j] = f[i - j][j];
f[i][j] = f[i - 1][j - 1] + g[i - j][j];
练习
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
package com.stormma.dp; import java.util.Scanner; public class Main1028 { public Main1028() { Scanner scan = new Scanner(System.in); while (scan.hasNext()) { // 对n进行不大于n的划分 // dp [m]表示n的不大于m的划分 int n = scan.nextInt(); int[][] dp = new int[n + 1][n + 1]; init(dp, n + 1); for (int i = 2; i < n + 1; i++) { for (int j = 2; j < n + 1; j++) { if (j <= i) dp[i][j] = dp[i][j - 1] + dp[i - j][j]; else dp[i][j] = dp[i][i]; } } System.out.println(dp ); } } private void init(int[][] dp, int n) { // TODO Auto-generated method stub for (int i = 1; i < n; i++) { dp[i][1] = dp[1][i] = dp[0][i] = 1; } } public static void main(String[] args) { new Main1028(); } }
相关文章推荐