已知Ackerman函数定义如下:
使用递归函数可以非常简单的实现:
int Akm(int m, int n)
{
if(!m)
return n+1;
else if(m && !n)
return Akm(m - 1, 1);
else
return Akm(m - 1, Akm(m, n - 1));
}
我们知道递归程序其实是隐式的使用了堆栈,这就表示所有的递归程序都可以使用堆栈来实现。
使用C++中STL的stack来实现上面的递归函数。
需要用到两个堆栈s1, s2,分别保存递归函数中的两个参数。
代码如下:模拟堆栈的操作
#include <stack>
#include <cstdio>
#include <iostream>
#define x 10000
using namespace std;
int main()
{
stack<int> s1, s2;
int m, n;
int res;
int flag = 0;
scanf("%d%d", &m, &n);
while(1)
{
while(m&&n)
{
s1.push(m - 1);
s2.push(x);
s1.push(m);
s2.push(--n);
}
while(m&&!n)
{
n = 1;
s1.push(--m);
s2.push(n);
}
while(!m)
{
res = s2.top() + 1;
while(!s1.empty()&&s2.top()!=x)
{
s1.pop();
s2.pop();
}
if(s2.empty())
{
flag = 1;
break;
}
s2.pop();
s2.push(res);
m = s1.top();
n = s2.top();
}
if(flag)
break;
}
printf("%d\n", res);
return 0;
}