https://www.jianshu.com/p/c57eb5b7a8ff
题目描述
某火车站只有一条铁轨供火车停靠,所有的列车都从一侧进入,从另一侧出来。如果此时,列车A首先进入铁路,然后列车B在列车A离开之前进入铁路,则列车A不能离开,直到列车B离开(如下图所示)。车站最多有9列火车,所有火车都有一个ID(编号从1到n),列车按照Order1的顺序进入铁路,你需要确定列车可以以Order2的顺序从地铁站离开。
输入
测试数据有多组
每组包含一个整数N和两个字符串O1,O2,N代表列车数量(1 <= N <= 9),O1代表进站顺序,O2代表出站顺序
输出
对于每组数据
首先输出一行"Yes.“或"No.”,代表能否由当进站顺序为O1时,出站顺序O2能否实现
若能实现,给出你的实现方法,其中"in"为列车进站,"out"为列车出站。
最后输出一行FINISH。
具体输出见样例。
样例输入
3 123 321
3 123 312
样例输出
Yes.
in
in
in
out
out
out
FINISH
No.
FINISH
思路:
先将输出的字符存在队中,
新建一个栈用于存输入字符,
若栈非空且栈顶元素跟队头元素相同,即证明此时应该将栈顶元素弹出,
否则,将输入字符压入栈中。
该过程中由vector存操作字符串,
若(栈)压入,往vector里push_back “in”,
若弹出,往vector里push_back “out”。
===================================================================
===================================================================
模拟入栈
1051 Pop Sequence (25分)
Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.
Input Specification:
Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.
Output Specification:
For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.
Sample Input:
5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2
Sample Output:
YES
NO
NO
YES
NO
#include <cstdio>
#include <stack>
using namespace std;
int main(){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
stack<int> s;
int arr[b];
while(c--){
while(!s.empty())s.pop();
for(int i=1;i<=b;i++){
scanf("%d",&arr[i]);
}
bool flag=true;
int cur=1;
for(int i=1;i<=b;i++){
s.push(i);
if(s.size()>a){
flag=false;
break;
}
while(!s.empty()&&s.top()==arr[cur]){
s.pop();
cur++;
}
}
if(flag==true&&s.empty()==true)printf("YES\n");
else printf("NO\n");
}
return 0;
}