题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1022
题目大意:一列序列为s1的车厢是否能通过车站的中转以序列s2出站。白皮上有。
关键思想:栈的应用。如果待入站车厢是s2对应位置上的就进了再出,再看前面是否有符合要求的;否则只进不出。
代码如下:
//栈。知道什么时候应该进出站
#include <iostream>
#include <stack>
using namespace std;
bool ans[10010];//保存进出顺序,true为"in",false为"out"
string in,out;
bool judge(int n){
stack<int>st;
int cnt=0;
for(int i=0,j=0;i<n;i++){
if(in[i]!=out[j]){//不是要的号码,进去
st.push(in[i]);
ans[cnt++]=true;
}
else {
ans[cnt++]=true,ans[cnt++]=false;//是要的号码进去直接出来
while(!st.empty()&&st.top()==out[++j]){//看前面有没有合适的号码
st.pop();
ans[cnt++]=false;
}
if(st.empty())j++;//修复的BUG
}
}
if(cnt==2*n)return true;//每车都经过一进一出
else return false;
}
int main(){
int n;
while(cin>>n>>in>>out){
if(judge(n)){
cout<<"Yes."<<endl;
for(int i=0;i<2*n;i++)
cout<<(ans[i]?"in":"out")<<endl;
}else cout<<"No."<<endl;
cout<<"FINISH"<<endl;
}
return 0;
}
HDU 1022[Train Problem I] 栈的应用
原文:http://www.cnblogs.com/G-M-WuJieMatrix/p/6407153.html