}
三、利用栈来实现Ackerman函数:
我们可以使用栈来模拟递归函数的过程,下列代码中,使用栈st来保存每个递归函数的参数m,tmp用来保存每个递归函数的返回值:
1 /*Sample Input:
2 0 1
3 1 1
5 Sample Output:
8 */
10 #include<bits/stdc++.h>
11 using namespace std;
13 int akm(int m, int n){
14 stack<int>st;
15 int tmp;
16 while(true){
17 while(m > 0){
18 if(n == 0){
19 m--;
20 n = 1;
21 }
22 else{
23 st.push(m - 1);
24 n--;
25 }
26 }
27 tmp = n + 1;
28 if(st.empty())break;
29 else{
30 m = st.top();
31 n = tmp;
32 }
33 st.pop();
34 }
36 return tmp;
37 }
39 int main(){
40 int m, n;
41 while(cin >> m >> n){
42 cout << akm(m ,n) << endl;
43 }