Input
Output
Sample Input
3 123 321 3 123 312
Sample Output
Yes. in in in out out out FINISH No. FINISHFor the first Sample Input, we let train 1 get in, then train 2 and train 3. So now train 3 is at the top of the railway, so train 3 can leave first, then train 2 and train 1. In the second Sample input, we should let train 3 leave first, so we have to let train 1 get in, then train 2 and train 3. Now we can let train 3 leave. But after that we can't let train 1 leave before train 2, because train 2 is at the top of the railway at the moment. So we output "No.".HintHint
解题思路:该题为模拟题,知识点为栈和队列的应用,可以用数组模拟。
最多9辆火车,编号为1,2,3....9,进出站方式入图(先进后出)。给出一个n,表示要进出站得火车数,给出火车进站顺序表,给出火车出站顺序表,问按给出入站表入站的火车能否以出站表顺序出站,如果可以,输出“YES.”以及出入情况信息(in,out),否则输出“NO.”,每组测试案例输出的最后一行以“FINISH”结束。
用3个队列及1个站来模拟,分别存储,火车进站顺序,火车出站顺序,站内火车情况(出入顺序要求情况)。输入火车进、出站顺序表,用字符数组做中介存储,后存入到对应队列。依题意得,火车进出站的次数最多为2*n次(每辆火车进站一次,出站一次),开始就循环结束判断条件纠结了很久,后面才想到。因为火车最多9辆,所以,这个地方不会导致程序运行超时。每次循环,判断出来,如果站内有火车可以按照给定的顺序出站,则让其出站(用队列保存火车出入情况),否则,若有火车未入栈,则让火车入站。最后如果火车进出站情况存储队列中有2*n个数据(所有的火车都进过站并且出来了,按题目给定的顺序)则输出“YES.”和火车出入情况及顺序(直接输出出入情况存储队列),否则输出“NO.”,其余按题意输出即可。
#include<stdio.h> #include<string.h> //使用String串 #include<iostream> //使用c++输出流 #include<stack> //使用栈 #include<queue> //使用队列 using namespace std; int main() { int n,x,i; string st; //输出时内容暂存 while(scanf("%d",&n)!=EOF) { queue<int> in,out; //存储需要入站,出站的火车编号 queue<string> sign; //存储火车存储站的状态(in,out,有序) stack<int > s; //存储现在车站中火车进出顺序 char a[20]; //存储输入时,火车进、出站顺序,后面会转存到队列 scanf("%s",a); //读入火车入站顺序 for(i=0;i<n;i++)in.push(a[i]-48); //将火车入站顺序转存到入站队列 scanf("%s",a); for(i=0;i<n;i++)out.push(a[i]-48); x=in.front(); //读取第一辆进站火车的车号 s.push(x); //放入栈(站中) in.pop(); sign.push("in"); //记录有一辆火车进站 int m=2*n-1; //最多处理2*n次(进n次,出n次) while(m--) { if(!out.empty()&&!s.empty()&&out.front()==s.top()) //若站(栈)内有火车,出站队列中有火车序号,且要处理的为同一辆火车,则处理这辆火车(出战) { out.pop(); //该火车可以出站 s.pop(); //该火车出站 sign.push("out"); //记录有火车出站 } else if(!in.empty()) //若处于出站口的火车不能出站,且还有火车没有进站,则让下一辆火车进站 { x=in.front(); //提取即将进站火车信息 in.pop(); //该火车将入站 s.push(x); //火车入站 sign.push("in"); //记录有1辆火车入站 } } if(sign.size()==n*2) //若火车出入站的次数为2*n次(每辆火车进一次站,出一次站) { printf("Yes.\n"); //火车以给出顺序进站,能以给出顺序出站 for(i=0;i<2*n;i++) { st=sign.front(); cout<<st<<endl; sign.pop(); } } else printf("No.\n"); //火车以给出顺序进站,不能以给出顺序出站 printf("FINISH\n"); } return 0; }