以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 计算机考研交流 』   (http://bbs.xml.org.cn/list.asp?boardid=67)
----  [讨论]DS第二章补充习题Ackermann函数  (http://bbs.xml.org.cn/dispbbs.asp?boardid=67&rootid=&id=56979)


--  作者:chenminyi
--  发布时间:12/20/2007 1:53:00 AM

--  [讨论]DS第二章补充习题Ackermann函数
非递归实现了Ackermann函数,供大家参考。用Dev C++验证了Ackermann(3,n)。也希望大家能帮我顶一下这个求助的帖子
http://ieee.org.cn/dispbbs.asp?boardID=67&ID=56974

#include<iostream>
#include<stack>

long Ackerman1(long m, long n)
{   
    if(m==0) return n+1;
    if(n==0) return Ackerman1(m-1,1);
    else     return Ackerman1(m-1,Ackerman1(m,n-1));
}
    
long Ackerman2(long m, long n)
{   
    std::stack<long> s;
    long operand1,operand2;
    s.push(m);    
    s.push(n);
    while(s.size()>1){
        operand2 = s.top();    s.pop();
        operand1 = s.top();    s.pop();
        if(operand1==0)
            s.push(operand2+1);
        else if(operand2==0){
            s.push(operand1-1);
            s.push(1);
        }
        else{
             s.push(operand1-1);
             s.push(operand1);
             s.push(operand2-1);
        }
    }
    return s.top();                     
}

int main()
{
     long m,n;
     std::cout << "intput the m and n!" << std::endl;
     std::cin >> m >> n;
     std::cout << "result of function1: " << Ackerman1(m,n) << std::endl;
     std::cout << "result of function2: " << Ackerman2(m,n) << std::endl;
     system("pause");
}
     


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
31.250ms