使用分桶法,平方分割解决超时问题。
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.
Problem: PAT-A 1057 Stack
Input Specification
Each input file contains one test case. For each case, the first line contains a positive integer $N(≤10^5)$. 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 $10^5$.
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
1 | 17 |
Sample Output
1 | Invalid |
Analysis
题目大意:在栈操作的基础上,添加获取中位数的操作。
起初用哈希表统计每个数字出现的次数,利用 map 的自动排序特性,从小到大累加至中位数。然鹅超时,然后在网上学了分桶法,即把大桶的数据分到一个个小桶中进行管理;平方分割,即把 $N$ 个元素分割为 $\sqrt{N}$ 部分。也就是每个桶的大小为 $\sqrt{N}$ ,在查找数据时先找到数据所在的桶,然后再在该桶内找具体数据。详情见代码。
Code
1 |
|
Tsukkomi
这道题还有好多解法,有空补上。