题目描述
Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.
输入
Each input file contains one test case. For each case, the first line contains a positive integer N
(
≤
1
0
5
)
(≤10^5)
(≤105). Then N lines follow, each contains a command in one of the following 3 formats:
Push key
Pop
PeekMedian
where key is a positive integer no more than
1
0
5
10^5
105.
输出
For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print Invalid instead.
思路
先分析复杂度,N为
1
0
5
10^5
105因此简单分析最后只能O(n)或者O(nlogn)。但每次找中间的数字至少为O(n),普通方法会超时。
这里采用的是线段树,插入删除复杂度以及查询都是logn这样就够了。
代码
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<stack>
using namespace std;
#define MAXN1 1000000
#define MAXN 100000
int ans[4 * MAXN1 + 1000] = { 0 };
stack<int> s;
void update1(int L, int R, int idx, int res, int q)
{
if (L == R)
{
ans[idx] += q;
return;
}
int mid = (L + R) / 2;
if (res <= mid)
{
update1(L, mid, idx * 2, res, q);
}
else
{
update1(mid+1, R, idx * 2 + 1 , res, q);
}
ans[idx] = ans[idx * 2] + ans[idx * 2 + 1];
}
int query(int L, int R, int idx, int pos)
{
if (L == R)
{
return L;
}
int mid = (L + R) / 2;
if (pos <= ans[idx * 2])
{
return query(L, mid, idx * 2, pos);
}
else
{
return query(mid+1, R, idx * 2 + 1, pos-ans[idx*2]);
}
}
int main()
{
int N;
cin >> N;
while (N--)
{
string str;
cin >> str;
if (str == "Pop")
{
if (s.empty())
{
printf("Invalid\n");
}
else
{
int t = s.top();
cout<<t<<endl;
s.pop();
update1(1, 4 * MAXN, 1, t, -1);
}
}
else if (str == "Push")
{
int t;
cin >> t;
s.push(t);
update1(1, 4 * MAXN, 1, t, 1);
}
else
{
if (s.empty())
{
printf("Invalid\n");
}
else
{
int mid = s.size() / 2;
if (s.size() % 2 != 0)
{
mid++;
}
cout << query(1, 4 * MAXN, 1, mid) << endl;
}
}
}
}