-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy path1057_Stack (30).cpp
78 lines (76 loc) · 1.31 KB
/
1057_Stack (30).cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <cstdio>
#include <iostream>
#include <map>
#include <cstring>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
static inline bool get(int &v)
{
int s = 1, c;
while(!isdigit(c = getchar())&&c != '-')
{
if(c == EOF)
break ;
}
if(c == EOF) return 0;
if(c == '-') s = 0 , v = 0;
else v = c^48;
for(;isdigit(c = getchar());v = (v << 1) + (v << 3) + (c ^ 48));
v = (s ? v : -v);
return 1 ;
}
/*
树状数组求第k小元素
*/
const int maxn = 100005;
int n,k;
int c[maxn];
int lowbit(int x){ return x&-x; }
void insert(int x,int t){ while(x<maxn){ c[x]+=t; x+=lowbit(x); } }
int find(int k)
{
int cnt=0,ans=0;
for(int i=20;i>=0;i--)
{
ans+=(1<<i);
if(ans>=maxn || cnt+c[ans]>=k)ans-=(1<<i);
else cnt+=c[ans];
}
return ans+1;
}
stack<int> s;
int main()
{
memset(c, 0, sizeof(c));
int n,i,val;
char str[100];
get(n);
for(i = 1; i <= n; i++)
{
gets(str);
if(!strcmp(str,"Pop"))
{
if(s.empty()) printf("Invalid\n");
else
{
printf("%d\n", s.top());
insert(s.top(), -1);
s.pop();
}
}
else if(!strcmp(str, "PeekMedian"))
{
if(s.empty()) printf("Invalid\n");
else{printf("%d\n", find((s.size()+1)>>1));}
}
else
{
sscanf(str, "Push %d", &val);
insert(val, 1);
s.push(val);
}
}
return 0;
}