问题 E 栈的操作问题
时间限制: 1 Sec 内存限制: 128 MB[ 提交]
题目描述
假设入栈序列为1 2 3 4 ... n,则出栈序列是1到n的一个排列。 假设用P表示入栈操作,用Q表示出栈操作,则栈操作过程可以表示为一个由P和Q构成的序列。 对一个给定的出栈序列,应该如何操作才能得到呢?
输入
输入由若干行构成,每一行是一组由空格间隔开的整数,第一个整数是序列的长度n(n不大于1000),后面是一个1到n的排列。
输出
对每一行输入,计算对应的栈操作序列,并输出此操作序列,如果不能输出此序列,则在不能操作的位置输出"error"。
样例输入
4 1 2 3 44 4 3 2 14 4 2 1 34 3 1 2 4
样例输出
PQPQPQPQPPPPQQQQPPPPQ errorPPPQ error
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#include<math.h>
int a[100001];
int top;
int nu[100001];
int head;
int main(){
int num;
int i;
while(~scanf("%d",&num)){
top=-1;
head=1;
a[0]=0;
for(i=0;i<num;i++){
scanf("%d",&nu[i]);
}
for(i=0;i<num;i++){
int t=nu[i];
top++;
while(a[top-1]<t){
a[top]=head;
head++;
top++;
printf("P");
}
top--;
if(a[top]==t){
printf("Q");
top--;
}
else if(a[top]>t){
printf(" error");
break;
}
}
memset(a,0,sizeof(a));
memset(nu,0,sizeof(nu));
printf("\n");
}
return 0;
}