文章
454
粉丝
0
获赞
1
访问
10.6k
按 1..n 的顺序进栈,任意时刻可弹栈,给定一个出栈序列,判断能否得到;能则输出完整操作序列(PUSH x / POP x),不能输出 NO。
先判定可行性:目标元素不在栈顶就继续压栈,压到 n 还没出现就说明不可行。
判定通过后再模拟一遍,边压边把操作打印出来。分两遍是为了避免不可行时已经打印了半截过程。
每次弹栈后立刻比对下一个目标元素。
O(n)。
C:
#include <stdio.h>
int a[1005], st[1005], opx[2005], opk[2005];
int main(){
int n, i, next, top, ok, pass;
scanf("%d", &n);
for(i = 0; i < n; i++) scanf("%d", &a[i]);
for(pass = 0; pass < 2; pass++){
next = 1; top = 0; ok = 1;
for(i = 0; i < n && ok; i++){
while(next <= n && (top == 0 || st[top - 1] != a[i])){
st[top++] = next;
if(pass) printf("PUSH %d\n", next);
next++;
}
if(top > 0 && st[top - 1] == a[i]){
top--;
if(pass) printf("POP %d\n", a[i]);
} else ok = 0;
}
if(!ok){
if(!pass){ printf("NO\n"); return 0; }
}
}
...
登录后发布评论
暂无评论,来抢沙发