Home PAT 1057 Stack
Post
Cancel

PAT 1057 Stack

Link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <stack>
using namespace std;
#define lowbit(i) ((i)&(-i))
const int maxn=100010;
int n,a,tree[maxn];
stack<int>st;
void update(int x,int v){
    for(int i=x;i<maxn;i+=lowbit(i))
        tree[i]+=v;
}
int getsum(int x){
    int sum=0;
    for(int i=x;i>=1;i-=lowbit(i))
        sum+=tree[i];
    return sum;
}
void PeekMedian(){
    int target=(st.size()+1)>>1;
    int low=1,high=maxn;
    while(low<high){
        int mid=(low+high)>>1;
        if(getsum(mid)>=target)
            high=mid;
        else low=mid+1;
    }
    printf("%d\n",low);
}
int main() {
    scanf("%d",&n);
    while(n--){
        char s[15];
        scanf("%s",s);
        if(s[1]=='u'){
            scanf("%d",&a);
            update(a,1);
            st.push(a);
        }else if(s[1]=='o'){
            if(st.empty()){
                printf("Invalid\n");
                continue;
            }
            a=st.top();
            st.pop();
            update(a,-1);
            printf("%d\n",a);
        }else{
            if(st.empty()){
                printf("Invalid\n");
                continue;
            }
            PeekMedian();
        }
    }
    return 0;
}
This post is licensed under CC BY 4.0 by the author.