HDU (动规路) Ignatius and the Princess III

来源:互联网 发布:淘宝退款申请介入处理 编辑:程序博客网 时间:2024/06/13 12:58

杭电1028:http://acm.hdu.edu.cn/showproblem.php?pid=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.
 


 

Sample Input
41020
 


 

Sample Output
542627
 


 

Author
Ignatius.L

 

这个题目一块是递归里面的整数划分问题,不过用的是动规的知识而已罢了!!!

 开始是把书上的代码敲上去,那三个简单的测试数据过了,提交了~~超时~~~

超时代码:

#include<iostream>
using namespace std;

int n,m,t;

int dp(int n,int m)//按书上原原本本打的,没有优化。
{
    if((n<1)||(m<1)) return 0;
    if((n==1)||(m==1)) return 1;
    if((n<m)) return dp(n,n);
    if((n==m) ) return dp(n,m-1)+1;
    return dp(n,m-1)+dp(n-m,m);
}

int main()
{
    while(~scanf("%d",&t))
    {
        printf("%d\n",dp(t,t));
    }
    return 0;
}

 

后来去百度了,一下需要在工程中有点优化

AC代码:

#include<iostream>
#include<string.h>
using namespace std;

int t,i;
int dp[128][128];

int mm(int n,int m)
{
 if(dp[n][m]!=-1) return dp[n][m];//可以省略很多时间,对于那些不必要处理可以跳过
 if((n<1)||(m<1)) return dp[n][m]=0;
 if((n==1)||(m==1)) return dp[n][m]=1;
 if((n<m)) return dp[n][m]=mm(n,n);
 if((n==m) ) return dp[n][m]=mm(n,m-1)+1;
 return dp[n][m]=mm(n,m-1)+mm(n-m,m);
}

int main()
{
 memset(dp,-1,sizeof(dp));
 while(~scanf("%d",&t))
 {
  printf("%d\n",mm(t,t));
 }
 return 0;
}

 

继续中。。。。。
原创粉丝点击