Ackerman函数----递归的堆栈实现

已知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;

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值