L3-002. 堆棧
時間限制
200 ms
內存限制
65536 kB
代碼長度限制
8000 B
判題程序
Standard
作者
陳越
大家都知道“堆棧”是一種“先進後出”的線性結構,基本操作有“入棧”(將新元素插入棧頂)和“出棧”(將棧頂元素的值返回並從堆棧中將其刪除)。現請你實現一種特殊的堆棧,它多了一種操作叫“查中值”,即返回堆棧中所有元素的中值。對於N個元素,若N是偶數,則中值定義爲第N/2個最小元;若N是奇數,則中值定義爲第(N+1)/2個最小元。
輸入格式:
輸入第一行給出正整數N(<= 105)。隨後N行,每行給出一個操作指令,爲下列3種指令之一:
Push keyPop
PeekMedian
其中Push表示入棧,key是不超過105的正整數;Pop表示出棧;PeekMedian表示查中值。
輸出格式:
對每個入棧指令,將key入棧,並不輸出任何信息。對每個出棧或查中值的指令,在一行中打印相應的返回結果。若指令非法,就打印“Invalid”。
輸入樣例:17 Pop PeekMedian Push 3 PeekMedian Push 2 PeekMedian Push 1 PeekMedian Pop Pop Push 5 Push 4 PeekMedian Pop Pop Pop Pop輸出樣例:
Invalid Invalid 3 2 2 1 2 4 4 5 3 Invalid
#include <bits/stdc++.h>
using namespace std;
int tree[101000<<2];
stack<int> S;
void update(int l, int r, int rt, int v, int add)
{
if(l == r)
{
tree[rt] += add;
return ;
}
int mid = (l + r) / 2;
if(v <= mid) update(l, mid, rt*2, v, add);
else update(mid + 1, r, rt*2+1, v, add);
tree[rt] = tree[rt*2] + tree[rt*2+1];
}
int find(int l,int r, int rt, int v)
{
if(l == r) return l;
int mid = (l + r) / 2;
if(tree[rt*2] >= v) return find(l, mid, rt*2, v);
else return find(mid+1, r, rt*2+1, v - tree[rt*2]);
}
int main()
{
int T, t, sz;
char ch[100];
scanf("%d", &T);
while(T--)
{
scanf("%s", ch);
if(!strcmp(ch, "Pop"))
{
if(S.empty()) printf("Invalid\n");
else
{
t = S.top();
S.pop();
printf("%d\n", t);
update(0, 100000, 1, t, -1);
}
}
else if(!strcmp(ch,"PeekMedian"))
{
if(S.empty())
{
printf("Invalid\n");
continue;
}
sz = S.size();
if(sz % 2) sz = (sz+1) / 2;
else sz = sz / 2;
printf("%d\n", find(0, 100000, 1, sz));
}
else if(!strcmp(ch,"Push"))
{
scanf("%d", &t);
S.push(t);
update(0, 100000, 1, t, 1);
}
}
return 0;
}