Akm函数递归和非递归

#include <iostream>
#include <cstdio>
#include <stack>
#include <ctime>

using namespace std;

/*int akm_1(int m, int n) {   //递归
    if (m == 0)
        return n + 1;
    else if (m != 0 && n == 0)
        return akm_1(m - 1, 1);
    else
        return akm_1(m - 1, akm_1(m, n - 1));
}*/

int akm_2(int m, int n) {   //非递归用两个stack来存放m,n如果m!=0&&n!=0,n暂时存放-1
    stack<int> x , y;
    int ans = 0 , _x , _y;
    x.push(m), y.push(n);
    while ((!x.empty()) && (!y.empty())) {
        if (x.top() != 0) {
            if (y.top() == 0) {
                _x = x.top(), _y = y.top();
                x.pop(); y.pop();
                x.push(_x - 1), y.push(1);
            }
            else {
                while (x.top()!= 0 &&y.top()!= 0) {
                    _x = x.top(), _y = y.top() - 1;
                    x.pop(), y.pop();
                    x.push(_x - 1), y.push(-1);
                    x.push(_x), y.push(_y);
                }
            }
        }
        else {
            _y = y.top();
            x.pop();
            if (x.empty())
                return y.top() + 1;
            else {
                y.pop(), y.pop(), y.push(_y + 1);
            }
        }
    }
    return -1;
}

int main() {
    int ans;
    clock_t startTime, endTime;
    /*startTime = clock();//计时开始
    ans = akm_1(4, 1);
    endTime = clock(); //计时结束
    cout << ans << endl << "Time : " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;*/
    startTime = clock();//计时开始
    ans = akm_2(3, 2);
    endTime = clock(); //计时结束
    cout << ans << endl << "Time : " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值