栈
stack又叫后进先出即 LIFO(last in first out)
火车进站经典问题
1 #include <stdio.h> 2 #include <iostream> 3 #include <stack> 4 using namespace std; 5 const int maxn = 1e4; 6 int n,a[maxn]; 7 int main(){ 8 while(scanf("%d", &n) == 1){ 9 string str1, str2, str3[maxn]; 10 cin>>str1>>str2; 11 stack<char> s; 12 int A = 0,B = 0, t = 0, flag = 1; 13 while(B < n){ 14 if(str1[A] == str2[B]) str3[t++] = "in", str3[t++] = "out",A++,B++; 15 else if(!s.empty() && s.top() == str2[B]) str3[t++] = "out",s.pop(), B++; 16 else if(A < n) s.push(str1[A++]), str3[t++] = "in"; 17 else { flag = 0; break; } 18 } 19 if(flag){ 20 cout<<"Yes."<<endl; 21 for(int i = 0; i < t; i++){ 22 cout<<str3[i]<<endl; 23 } 24 } 25 else cout<<"No."<<endl; 26 cout<<"FINISH"<<endl; 27 } 28 return 0; 29 }
只有不断学习才能进步!