首页 > ACM题库 > HDU-杭电 > Hdu 1165 Eddy’s research II-递推-[解题报告] C++
2013
12-03

Hdu 1165 Eddy’s research II-递推-[解题报告] C++

Eddy’s research II

问题描述 :

As is known, Ackermann function plays an important role in the sphere of theoretical computer science. However, in the other hand, the dramatic fast increasing pace of the function caused the value of Ackermann function hard to calcuate.Ackermann function can be defined recursively as follows:

Now Eddy Gives you two numbers: m and n, your task is to compute the value of A(m,n) .This is so easy problem,If you slove this problem,you will receive a prize(Eddy will invite you to hdu restaurant to have supper).

输入:

Each line of the input will have two integers, namely m, n, where 0 < m < =3.
Note that when m<3, n can be any integer less than 1000000, while m=3, the value of n is restricted within 24.
Input is terminated by end of file.

输出:

For each value of m,n, print out the value of A(m,n).

样例输入:

1 3
2 4

样例输出:

5
11

递推关系的简化+递归终止条件要注意

我居然不进行任何的变形,而去直接的暴力。。。果断暴栈了。。。囧
正确的想法应该是考虑到 m<=3 这个条件,我们可以计算出 m 在各个值的时候对应的递推公式
 
A(1,n)=A(0,A(1,n-1))=A(1,n-1)+1 那么可以发现,这个其实是一个等差数列
而且很明显有 A(1,0)=A(0,1)=2,A(1,1)=A(0,A(1,0))=A(1,0)+1=3
那么就可以推出 A(1,n)=n+2
同理可以推出 A(2,n)=2*n+3
A(3,n)=2*A(3,n-1)+3
 
用这个递推关系去递归的话,还是OK的
#include<iostream>
using namespace std;

int dp(int m,int n)
{    if(m==1) return n+2;
     if(n==0) return dp(m-1,1); //这句话不写,递归出不来
     if(m==2) return 2*n+3;
     if(m==3) return 2*dp(3,n-1)+3; //这里在递减,上面那句不写的话,就没有递归终止条件
}

int main()
{    int m,n;
     while(scanf("%d%d",&m,&n)!=EOF)
     {   if(m==1)  printf("%d\n",n+2); 
         else  if(m==2) printf("%d\n",2*n+3);
         else printf("%d\n",dp(3,n));
     }
return 0;
}

直接暴力的想法以及代码如下:

记忆化搜索
#include<iostream>
using namespace std;

int dp[4][1000010];

int DP(int m,int n)
{    if(dp[m][n]) return dp[m][n];
     if(m==0) return dp[m][n]=n+1;
     if(m>0&&n==0) return dp[m][n]=DP(m-1,n);
     if(m>0&&n>0) return dp[m][n]=DP(m-1,DP(m,n-1));
}

int main()
{
    DP(3,1000000);
    int n,m;
    while(scanf("%d%d",&m,&n)!=EOF)
    {   printf("%d\n",dp[m][n]);
    }
return 0;
}

 


  1. 学算法中的数据结构学到一定程度会乐此不疲的,比如其中的2-3树,类似的红黑树,我甚至可以自己写个逻辑文件系统结构来。