Train Problem I
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 43515 Accepted Submission(s): 16310
Problem Description
Input
The input contains several test cases. Each test case consists of an integer, the number of trains, and two strings, the order of the trains come in:O1, and the order of the trains leave:O2. The input is terminated by the end of file. More details in the Sample Input.
Output
The output contains a string "No." if you can't exchange O2 to O1, or you should output a line contains "Yes.", and then output your way in exchanging the order(you should output "in" for a train getting into the railway, and "out" for a train getting out of the railway). Print a line contains "FINISH" after each test case. More details in the Sample Output.
Sample Input
3 123 321
3 123 312
Sample Output
Yes.
in
in
in
out
out
out
FINISH
No.
FINISH
For 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.".
【分析】栈的应用
题意:有一条铁路线,最多可停9辆车。现在有一个n辆车的进入和离开的序列O1和O2,且先进入的车只能在后进入的车离开后才能离开,问此序列是否符合要求?如果能,输出"Yes"及这n辆车的进出方案,否则输出"No."。
不难想到用栈模拟上述过程,但需要特别注意的是:n辆车不一定是一次性进入或离开的。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
const int maxn=15;
int n;
char O1[maxn],O2[maxn]; //n辆车的进入.离开序列
char result[2*maxn][5]; //进出方案
stack<char> st;
int main()
{
int i,j,ans;
while(scanf("%d %s %s",&n,O1,O2)!=EOF)
{
i=j=ans=0;
//开始栈为空,O1序列第一个元素入栈
st.push(O1[i]);
strcpy(result[ans++],"in");
while(i<n && j<n)
{
//栈不空 且栈顶元素与O2序列当前元素相同
if(!st.empty() && st.top()==O2[j])
{
//则将当前栈顶元素出栈,并继续考察O2序列下一元素
j++;
st.pop();
strcpy(result[ans++],"out");
}
//否则O1序列当前元素入栈
else
{
//栈顶元素与O2序列当前元素不同,且O1序列中所有元素均已入栈
//则此方案不符合要求
if(i==n)
break;
st.push(O1[++i]);
strcpy(result[ans++],"in");
}
}
if(i==n)
printf("No.\n");
else
{
printf("Yes.\n");
for(i=0;i<ans;i++)
printf("%s\n",result[i]);
}
printf("FINISH\n");
}
return 0;
}