题目大意:车厢进站,判断给出的出战顺序是否可能。
关于这道的解法,网上有很多答案,今天我尝试了一下,怎样把所有可能的情况都输出来。废话少说,直接上代码。
//
// 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:自己测试的数据不多,觉得没问题。 如果发现问题,希望大神指正!