PAT (Advanced Level) Practise 1057 Stack (30)
2016-03-16 16:52
501 查看
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<cstdio> #include<stack> #include<cstring> #include<algorithm> using namespace std; const int maxn = 1e5 + 10; int n, x; char s[maxn]; struct Tree { int f[maxn*4]; void insert(int x, int l, int r, int u, int v) { if (l == r) { f[x] += v; return; } int mid = l + r >> 1; if (u <= mid) insert(x << 1, l, mid, u, v); else insert(x << 1 | 1, mid + 1, r, u, v); f[x] = f[x << 1] + f[x << 1 | 1]; } int find(int x, int l, int r, int k) { if (l == r) return l; int mid = l + r >> 1; if (f[x << 1] >= k) return find(x << 1, l, mid, k); else return find(x << 1 | 1, mid + 1, r, k - f[x << 1]); } }solve; int main() { scanf("%d", &n); stack<int> p; while (n--) { scanf("%s", s); if (s[1] == 'o') { if (p.empty()) printf("Invalid\n"); else { solve.insert(1, 1, 1e5, p.top(), -1); printf("%d\n", p.top()); p.pop(); } } if (s[1] == 'u') { scanf("%d", &x); p.push(x); solve.insert(1, 1, 1e5, x, 1); } if (s[1] == 'e') { if (p.empty()) printf("Invalid\n"); else printf("%d\n", solve.find(1, 1, 1e5, (p.size() + 1) / 2)); } } return 0; }
相关文章推荐
- libdvbpsi源码分析(四)PAT表解析/重建
- PAT配置
- 什么是端口复用动态地址转换(PAT) 介绍配置实例
- MikroTik layer7-protocol
- PAT是如何工作的
- PAT 乙级题:1002. 写出这个数 (20)
- PAT (Advanced Level) Practise 1001-1010
- 数据结构学习与实验指导(一)
- PAT Basic Level 1001-1010解题报告
- 1001. 害死人不偿命的(3n+1)猜想
- 1002. 写出这个数
- 1032. 挖掘机技术哪家强
- 1001. 害死人不偿命的(3n+1)猜想 (PAT basic)
- 1002. 写出这个数(PAT Basic)
- 1004. 成绩排名(PAT Basic)
- 1006. 换个格式输出整数(PAT Basic)
- 1007. 素数对猜想(PAT Basic)
- 1008. 数组元素循环右移问题
- 1009. 说反话(PAT Basic)
- 1011. A+B和C(PAT Basic)