1. 程式人生 > 其它 >噁心的遞迴,噁心的阿克馬

噁心的遞迴,噁心的阿克馬

居然根據遞迴寫出非遞迴形式,有本事把漢諾塔的非遞迴寫一個?抱歉,我是菜雞,不會!

遞迴形式:(很簡單啦)

 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 }