恶心的递归,恶心的阿克马
居然根据递归写出非递归形式,有本事把汉诺塔的非递归写一个?抱歉,我是菜鸡,不会!
递归形式:(很简单啦)
1 #pragma GCC optimize(3) 2 #include<iostream> 3 using namespace std; 4 int akm(int m,int n){ 5 if(m==0) return n+1; 6 if(m>0&&n==0) return akm(m-1,1); 7 if(m>0&&n>0) return akm(m-1,akm(m,n-1)); 8 } 9 int main(){ 10 ios::sync_with_stdio(false); 11 int m,n; 12 cin>>m>>n; 13 cout<<akm(m,n)<<endl; 14 15 } 16 17 /* 18 Ack(2,1)=Ack(1,Ack(2,0)) 19 =Ack(1,Ack(1,1)) 20 =Ack(1,Ack(0,Ack(1,0))) 21 =Ack(1,Ack(0,Ack(0,1))) 22 =Ack(1,Ack(0,2)) 23 =Ack(1,3) 24 =Ack(0,Ack(1,2)) 25 =Ack(0,Ack(0,Ack(1,1))) 26 =Ack(0,Ack(0,Ack(0,Ack(1,0)))) 27 =Ack(0,Ack(0,Ack(0,Ack(0,1)))) 28 =Ack(0,Ack(0,Ack(0,2))) 29 =Ack(0,Ack(0,3)) 30 =Ack(0,4) 31 =5 32 */
非递归阿克马,纯纯牛马
:
1 #include<bits/stdc++.h>//stl大法 2 using namespace std; 3 int asker(int m, int n) 4 { 5 stack<int> s1;//STL 6 stack<int> s2;//STL 7 s1.push(m);//STL 放到栈顶 8 s2.push(n);//STL 放到栈顶 9 while (!s1.empty())//判断是否栈空 10 { 11 while (m != 0) 12 { 13 if (n == 0) 14 { 15 m = m - 1; 16 n = 1; 17 s1.push(m); 18 s2.push(n); 19 } 20 else 21 { 22 n = n - 1; 23 s1.push(m - 1); 24 s2.push(-1); 25 } 26 } 27 n = n + 1; 28 while ((!s1.empty())&& (s2.top() != -1))//top获得栈顶元素 29 { 30 s1.pop();//删除栈顶元素 31 s2.pop(); 32 } 33 if(!s1.empty()) 34 { 35 m = s1.top(); 36 s2.pop(); 37 s2.push(n); 38 } 39 } 40 return n; 41 } 42 int main() 43 { 44 ios::sync_with_stdio(false); 45 int n,m; 46 cin>>n>>m; 47 cout<<asker(m,n)<<endl; 48 }
本文来自博客园,作者:江上舟摇,转载请注明原文链接:https://www.cnblogs.com/LQS-blog/p/16014471.html