题目:https://dsa.cs.tsinghua.edu.cn/oj/problem.shtml?id=1145
比较简单的题目,其实就是判断是否是一个合法的栈混洗。而判断的最快方法就是直接模拟入栈出栈的过程。
#include <stdio.h>
#define MAX 1600001
int B[MAX];
int S[MAX];
int result[2*MAX];
int main()
{
int topS = 0;
int topR = 0;
int n, m ;
int key = 1;
scanf("%d %d", &n, &m);
for (int i = 0 ; i < n; i++)
{
scanf("%d", &B[i]);
}
for (int i = 1, j = 0; i <= n; i++)
{
if (topS<m)
{
S[topS++] = i;
result[topR++] = 0;
}
else
{
key = 0;
break;
}
if (i==B[j])
{
j++;
S[--topS] = 0;
result[topR++] = 1;
}
while (topS>0&&B[j]==S[topS-1])
{
j++;
S[--topS] = 0;
result[topR++] = 1;
}
}
if (topS != 0|| key == 0)
{
printf("No\n");
}
else
{
for (int i = 0; i < topR; i++)
{
if (result[i] == 1)
{
printf("pop\n");
}
else if (result[i] == 0)
{
printf("push\n");
}
}
}
}