PAT (Advanced Level) Practise 1057 Stack (30)

来源:互联网 发布:静默卸载软件 bat 编辑:程序博客网 时间:2024/06/05 17:06

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:
17PopPeekMedianPush 3PeekMedianPush 2PeekMedianPush 1PeekMedianPopPopPush 5Push 4PeekMedianPopPopPopPop
Sample Output:
InvalidInvalid322124453Invalid

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

解题思路:线段树


#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 longconst 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;}

原创粉丝点击