车厢调度

http://ybt.ssoier.cn:8088/problem_show.php?pid=1357

题目描述
有一个栈,入栈序列为 1~n,给定一个出栈序列,问该序列是否合法。
合法输出"YES",不合法输出 "NO"。
数据范围: n≤1000。

输入样例

5
5 4 3 2 1

输出样例

YES
  • 参考程序
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+10;
int n,m,a[N],st[N], h=0;

int main(){
    scanf("%d", &n);
    for(int i=1; i<=n; i++) scanf("%d",&a[i]);
    for(int i=1,p=1; i<=n; i++){
        st[++h] = i;
        while(h && st[h]==a[p]) h--, p++;
    }
    printf("%s", h==0 ? "YES" :"NO");
    return 0;
}

火车编组

题目描述
火车通过进入一个类似栈的空间进行重新编组。

比如,有 4 辆火车,初始的顺序是 1 2 3 4,最后编组的结果是 3 2 4 1,那么只需要准备一个栈,让这4辆火车按照:进栈、进栈、进栈、出站、出站、进栈、出站、出站的顺序进行栈的操作就可以得到 3 2 4 1 的编组结果。

输入格式
第1行1个正整数 n, n<=100,列车进入顺序为 1~n;
第2行n个小于或等于n的正整数,表示列车经过编组后的车厢编号顺序;

输出格式
一行编组时进栈出栈的操作序列,A表示进栈,B表示出栈。

输入样例

4
3 2 4 1

输出样例

AAABBABB
  • 参考程序
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+10;
int n,m,a[N],st[N], h=0;

int main(){
    scanf("%d", &n);
    for(int i=1; i<=n; i++) scanf("%d",&a[i]);
    string s;
    for(int i=1,p=1; i<=n; i++){
        st[++h] = i, s.append(1,'A');
        while(h && st[h]==a[p]) h--, p++, s.append(1,'B');
    }
    printf("%s",s.c_str());
    return 0;
}
posted @ 2023-01-12 10:23  HelloHeBin  阅读(77)  评论(0)    收藏  举报