Ignatius and the Princess III(杭电1028(动态规划))

Ignatius and the Princess III(杭电1028(动态规划))

Ignatius and the Princess III

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3088    Accepted Submission(s): 2133


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





 1 // 动归是自下而上
 2 #include < iostream >
 3 using   namespace  std;
 4 int  f[ 121 ][ 121 ];
 5 int  dp( int  n, int  k) // f[5][1]=f[4][1]+f[3][2]+f[2][3]+f[1][4]+f[0][5]
 6 {
 7      if (n == 0 return   1 ; // 所以f[0][5]=1,就是代表的是5=5
 8      if (n < k)  return   0 ; // 就是f[1][4]一不能分了=0
 9      if (n == k) return   1 ; // 相当与f[2][2]=1,就是2+2一种
10      if (f[n][k] !=- 1 ) return  f[n][k]; // 不用重复计算
11     f[n][k] = 0 ; // 没有初始化的就先赋值为0;
12      for ( int  i = k;i <= n;i ++ ) // 以k为最小开始将n分开
13         f[n][k] += dp(n - i,i); // f[5][1]=f[4][1]+f[3][2]+f[2][3]+f[1][4]+f[0][5]
14      return  f[n][k];    
15 }

16 int  main()
17 {
18      int  n;
19     memset(f, - 1 , sizeof (f)); // 初始化将f[][]数组的值全部赋值为-1
20      while (cin >> n)
21         cout << dp(n, 1 ) << endl; // 假设n=5,则就是f(5,1)
22      return   0 ;
23 }

你可能感兴趣的:(Ignatius and the Princess III(杭电1028(动态规划)))