您的位置:首页 > 其它

PAT (Advanced Level) Practise 1057 Stack (30)

2017-07-16 09:52 351 查看


1057. Stack (30)

时间限制

150 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<= 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 105.

Output Specification:

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.
Sample Input:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop

Sample Output:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid


题意:有三种操作,分别是向栈中压入一个数,从栈中弹出一个数,查询栈中元素的中间数

解题思路:线段树

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>

using namespace std;

#define LL long long
const int INF = 0x3f3f3f3f;

int sum[100009 << 2];
int n,x;
char ch[15];

void update(int k, int l, int r, int p, int val)
{
sum[k] += val;
if (l == r) return;
int mid = (l + r) >> 1;
if (mid >= p) update(k << 1, l, mid, p, val);
else update(k << 1 | 1, mid + 1, r, p, val);
}

int query(int k, int l, int r, int p)
{
if (l == r) return l;
int mid = (l + r) >> 1;
if (sum[k << 1] >= p) return query(k << 1, l, mid, p);
else return query(k << 1 | 1, mid + 1, r, p - sum[k << 1]);
}

int main()
{
while (~scanf("%d", &n))
{
memset(sum, 0, sizeof sum);
stack<int>s;
for (int i = 0; i < n; i++)
{
scanf("%s", &ch);
if (!strcmp(ch, "Pop"))
{
if (s.empty()) { printf("Invalid\n"); continue; }
int pre = s.top();
s.pop();
update(1, 1, 100000, pre, -1);
printf("%d\n", pre);
}
else if (!strcmp(ch, "Push"))
{
scanf("%d", &x);
s.push(x);
update(1, 1, 100000, x,1);
}
else
{
if (s.empty()) { printf("Invalid\n"); continue; }
int Size = s.size();
printf("%d\n", query(1, 1, 100000, (Size + 1) / 2));
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: