51nod 1403 有趣的堆栈

来源:互联网 发布:后期修图软件 编辑:程序博客网 时间:2024/06/06 04:17
大家都熟悉堆栈操作。一个堆栈一般有两种操作,push和pop。假设所有操作都是合法的并且最终堆栈为空。我们可以有很多方法记录堆栈的操作,
(1) 对每个pop操作,我们记录它之前一共有多少个push操作。

(2) 对每个pop操作,我们记录这个被Pop的元素曾经被压上了几个。

对于第二种记录方式,上面压的个数,即为该元素的push和pop操作之间,另外push和pop的元素个数。也就是说,如果该元素pop的操作序列号为x,上面压了a个元素,那么其push的操作序列号为 x-a*2-1。所以从后往前扫一遍就行了。

另外,要用stdio.h,cstdio会超时。

//#include<bits/stdc++.h>#include<stdio.h>#include<cstring>using namespace std;const int MAXN=1000100;int a[MAXN],ans[MAXN<<1];void read(int&a){    char ch;while(!((ch=getchar())>='0')&&(ch<='9'));    a=ch-'0';while(((ch=getchar())>='0')&&(ch<='9'))a*=10,a+=ch-'0';}inline void prin_d(int x){    if (x > 9)    {        prin_d(x / 10);    }    putchar(x % 10 + '0');    return ;}int main(){int n,i,now,cnt;while(~scanf("%d",&n)){for(i=1;i<=n;i++)read(a[i]);cnt=n;memset(ans,-1,sizeof(ans));for(i=n+n;i>=1;i--){if(~ans[i])continue;ans[i]=0;ans[i-(a[cnt]<<1)-1]=1;cnt--;} now=0;for(i=1;i<=n+n;i++){if(ans[i])now++;else{prin_d(now);printf(" ");}}printf("\n");}}


0 0
原创粉丝点击