题目大意:给出一个数(车的数目),两个字符串(前一个为现有车的排序,第二个为要组成的车的排序),
Sample Input
3 123 321
3 123 312
Sample Output
Yes.
in
in
in
out
out
out
FINISH
No.
FINISH
思路:直接用stack模拟栈的顺序:
首先如果出栈序列可行,那么必定存在唯一的可行出栈方式(想想是不是)
我们需要两个指针i,j,用来指定in顺序和out顺序的位置,
如果当前栈顶元素等于out序列中j所指向的那个字符,那么就出栈并且保存com【len++】=“out”;
如果当前的字符出栈不可行时,我们就把in中i所指向的字符加入栈中即可;在判断下一个i;
注意栈操作时:
出栈:栈S不能为空 且 j不能超过出栈序列的最后一个元素 且 S.top() == j所指元素
入栈:i不能超过入栈序列的最后一个元素
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<stack>
#define maxn 33
using namespace std;
string in;
string out;
string com[maxn];
int n;
int main()
{
while(cin>>n)
{
cin>>in>>out;
int len=0;
stack<char>s;
int i=0,j=0;
while(i<n&&j<n)
{
if(in[i]==out[j]) //相同时,进~出
{
com[len++]="in";
com[len++]="out";
i++;
j++;
}
else if(s.empty()||(s.top()!=out[j]))//不满足时,进~
{
com[len++]="in";
s.push(in[i]);
i++;
}
else//出~
{
com[len++]="out";
s.pop();
j++;
}
}
while(!s.empty()&&s.top()==out[j])//判断是否可以出
{
com[len++]="out";
s.pop();
j++;
}
if(s.empty())//栈中无元素时表示恰好可以完成工作,把保存的路径输出即可
{
cout<<"Yes."<<endl;
for(int i=0;i<len;i++)
cout<<com[i]<<endl;
cout<<"FINISH"<<endl;
}
else
{
cout<<"No."<<endl;
cout<<"FINISH"<<endl;
}
}
return 0;
}