码迷,mamicode.com
首页 > 其他好文 > 详细

用栈来递归 模板 honoi

时间:2018-04-03 14:36:05      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:names   problem   int   class   top   clu   har   fine   define   

用栈来模拟递归的技巧

 

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<cstring>
#include<set>
#include<algorithm>
#include<stack>
#include<string>
#include<cstdio>
#define _for(i, a, b) for (int i = (a); i<(b); ++i)
using namespace std;
struct problem {
    int n;
    char scr, mid, dest;
    problem(int nn, char s, char m, char d) :n(nn), scr(s), mid(m), dest(d) {}
};
stack<problem> stk;

int main()                                  
{
    int n;
    cin >> n;
    stk.push(problem(n, A, B, C));
        while (!stk.empty()) {
            problem now = stk.top();
            stk.pop();
            if (now.n == 1) { cout << now.scr << "->" << now.dest << endl; }
            else {
                stk.push(problem(now.n - 1, now.mid, now.scr, now.dest));//先放最后一个子问题
                stk.push(problem(1, now.scr, now.mid, now.dest));
                stk.push(problem(now.n - 1, now.scr, now.dest, now.mid));
            }
        }
    
    system("pause");
} 

 

用栈来递归 模板 honoi

标签:names   problem   int   class   top   clu   har   fine   define   

原文地址:https://www.cnblogs.com/SuuT/p/8707779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!