题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1022
As the new term comes, the Ignatius Train Station is very busy nowadays. A lot of student want to get back to school by train(because the trains in the Ignatius Train Station is the fastest all over the world ^v^). But here comes a problem, there is only one railway where all the trains stop. So all the trains come in from one side and get out from the other side. For this problem, if train A gets into the railway first, and then train B gets into the railway before train A leaves, train A can't leave until train B leaves. The pictures below figure out the problem. Now the problem for you is, there are at most 9 trains in the station, all the trains has an ID(numbered from 1 to n), the trains get into the railway in an order O1, your task is to determine whether the trains can get out in an order O2.
3 123 321 3 123 312
Yes. in in in out out out FINISH No. FINISH
题目大意:火车进出站。给出两个序列,序列一为火车进站顺序,问是否能以序列二顺序出站。
思路:栈处理。遍历序列一与序列二元素,序列一元素进栈,当栈顶元素与序列二当前元素一致,则出栈。同时,开一个数组存储每一步操作(in或out)。
代码如下:
#include<iostream>
#include<cstring>
#include<stack>
#include<sstream>
using namespace std;
int main()
{
int n,i,j,k;
int a[20];
string s1,s2;
stack<char> rai;
while (cin>>n>>s1>>s2)
{
while (rai.size()!=0) rai.pop();
i=j=k=0;
while (i<n)
{
rai.push(s1[i]);
a[++k]=1;
i++;
while (!rai.empty() && rai.top()==s2[j])
{
rai.pop();
a[++k]=-1;
j++;
}
}
if (j<n) cout<<"No."<<endl;
else
{
cout<<"Yes."<<endl;
for (i=1;i<=k;i++)
if (a[i]==1) cout<<"in"<<endl;
else if (a[i]==-1) cout<<"out"<<endl;
}
cout<<"FINISH"<<endl;
}
return 0;
}