ZOJ-1259 输出所有的出站情况

题目大意:车厢进站,判断给出的出战顺序是否可能。

关于这道的解法,网上有很多答案,今天我尝试了一下,怎样把所有可能的情况都输出来。废话少说,直接上代码。

//

//  main.cpp

//  ZOj-1259

//

//  Created by scnulpc on 2017/6/12.

//  Copyright © 2017 scnulpc. All rights reserved.

//


#include <iostream>

#include <stack>

#include <queue>

using namespace std;

struct node {

    int sin;

    int sout;

    node* left;

    node* right;

    node(){left=right=NULL;}

};


int counter=0;



//生成情况树

node *builtTree(int sin,int sout)//sin:栈内元素个数 sout:栈外元素个数

{

    

    node* temp = new node();

    temp->sin=sin;

    temp->sout=sout;

    if (sout==0) {

        return temp;

    }

    if (sout>0) {  //栈外有元素,可以入栈,生成左孩子

        temp->left=builtTree(sin+1, sout-1);

    }

    if (sin>0) {   //栈内有元素,可以出栈,生成右孩子

        temp->right=builtTree(sin-1, sout);

    }

    return temp;

}

//遍历情况树,深度遍历法,并输出可能的情况

void DFS(node* p,stack<int> path,queue<int>source,queue<int>result) //P:树根. path:站中的车厢顺序 source:未进站的车厢顺序 result:出战的车厢顺序

{

    

    if (p->sout==0) {

        counter++;

        while (!path.empty()) {

            result.push(path.top());

            path.pop();

        }

        //输出情况

        while (!result.empty()) {

            cout<<result.front()<<" ";

            result.pop();

        }//while

        return;

    }//if

    stack<int> tempPath = path;

    queue<int> tempSource = source;

    //向左走,压栈

    if (p->left!=NULL) {

        path.push(source.front());

        source.pop();

        DFS(p->left, path, source, result);

    }

    path = tempPath;

    source = tempSource;

    //向右走,出栈

    if (p->right!=NULL) {

        result.push(path.top());

        path.pop();

        DFS(p->right, path, source, result);

    }

}

int main(int argc, const char * argv[]) {

    int n=0;

    cin>>n;               //输入车厢数量

    node* boot = builtTree(0, n);

    stack<int> store;

    queue<int> source;

    queue<int> result;

    for (int i=1; i<=n; i++) {

        source.push(i);

    }

    DFS(boot, store, source, result);

    return 0;

}



ps:自己测试的数据不多,觉得没问题。 如果发现问题,希望大神指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值