#include<iostream>
using namespace std;
const int N=100;
//ackerman函数,递归算法
//ackerman函数,两种非递归算法
void main()
{
//数组递推
int m=3;int n=2;
int ack[N][N];
memset(ack,0,sizeof(ack));
int i,j;
for(j=0;j<N;j++)
ack[0][j]=j+1;
for(i=1;i<N;i++)
{
ack[i][0]=ack[i-1][1];
for(j=1;j<N;j++)
ack[i][j]=ack[i-1][ack[i][j-1]];
}
cout<<ack[m][n]<<endl;
//栈结构消除递归,麻烦,仅为理解递归及栈的工作原理
struct {int mval;int nval;int ack;} s[100];
int top=0;
s[top].mval=m;s[top].nval=n;s[top].ack=-1;
while(s[0].ack==-1)
{
if(s[top].mval==0)
{
s[top].ack=s[top].nval+1;
while(s[top].ack!=-1&&top)
{
top--;
if(s[top].nval==-1)
{ s[top].nval=s[top+1].ack;
}
else
{
s[top].ack=s[top+1].ack;
}
}
}
else if(s[top].nval==0)
{
top++;
s[top].mval=s[top-1].mval-1;
s[top].nval=1;
s[top].ack=-1;
}
else
{
top++;
s[top].mval=s[top-1].mval-1;
s[top].nval=-1;
s[top].ack=-1;
top++;
s[top].mval=s[top-2].mval;
s[top].nval=s[top-2].nval-1;
s[top].ack=-1;
}
}
cout<<s[0].ack<<endl;
//递归算法
int ackm(int m,int n);
cout<<ackm(m,n)<<endl;
}
int ackm(int m,int n)
{
if(m==0)return n+1;
else if(n==0)return ackm(m-1,1);
else return ackm(m-1,ackm(m,n-1));
}
评论11
最新资源