2019年9月PAT - 练习笔记——13.1
以下页码标注的是阅读器中实际页码,而不是书本身自印的页码。
第13章 提高篇(6)——专题扩展
13.1 分块思想
目录
- A1057 Stack
-
A1057 Stack
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, insertkey
into the stack and output nothing. For eachPop
orPeekMedian
command, print in a line the corresponding returned value. If the command is invalid, printInvalid
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 <string> #include <set> #include <stack> using namespace std; int main(void) { int n = 0; scanf("%d", &n); getchar(); stack<int> s; multiset<int> former, latter; string input = ""; for (int i = 0;i < n;++i) { getline(cin, input); if (input[1] == 'e') { if (former.empty()) printf("Invalid\n"); else printf("%d\n", *former.rbegin()); } else if (input[1] == 'o') { if (former.empty()) printf("Invalid\n"); else { int num = s.top(); printf("%d\n", num); s.pop(); if (former.size() == latter.size()) { if (num > *former.rbegin()) latter.erase(latter.find(num)); else { former.erase(former.find(num)); former.insert(*latter.begin()); latter.erase(latter.begin()); } } else { if (num > *former.rbegin()) { latter.erase(latter.find(num)); latter.insert(*former.rbegin()); former.erase(former.find(*former.rbegin())); } else former.erase(former.find(num)); } } } else { int num = atoi(input.substr(5, input.size() - 5).c_str()); s.push(num); if (former.size() == latter.size()) { if (former.empty() || num > *former.rbegin()) { latter.insert(num); former.insert(*latter.begin()); latter.erase(latter.begin()); } else former.insert(num); } else { if (num > *former.rbegin()) latter.insert(num); else { former.insert(num); latter.insert(*former.rbegin()); former.erase(former.find(*former.rbegin())); } } } } return 0; }
当初是直接做然后超时了,后来看的牛客网题解,感恩!https://www.nowcoder.com/discuss/422
思路记得很清楚,这次写起来没什么难度,就是multiset用的不多,对它的函数不太熟,要多练
-
《算法笔记》P411
-