PAT-A 1057 Stack (30)

  使用分桶法,平方分割解决超时问题。

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

1
2
3
4
5
6
7
8
9
10
11
12
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid

Analysis

  题目大意:在栈操作的基础上,添加获取中位数的操作。

  起初用哈希表统计每个数字出现的次数,利用 map 的自动排序特性,从小到大累加至中位数。然鹅超时,然后在网上学了分桶法,即把大桶的数据分到一个个小桶中进行管理;平方分割,即把 $N$ 个元素分割为 $\sqrt{N}$ 部分。也就是每个桶的大小为 $\sqrt{N}$ ,在查找数据时先找到数据所在的桶,然后再在该桶内找具体数据。详情见代码。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <bits/stdc++.h>
using namespace std;
const int mxN = 1e5 + 10;
const int sqrN = 317;

stack<int> stk;
vector<int> blk(sqrN), tb(mxN);

int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N, p = 0;
cin >> N;
for (int i = 0; i < N; i++) {
string cmd;
cin >> cmd;
if (cmd[1] == 'u') {
int num;
cin >> num;
stk.push(num);
blk[num / sqrN]++;
tb[num]++;
} else {
if (stk.empty()) {
printf("Invalid\n");
} else {
if (cmd[1] == 'e') {
int mid, cnt = 0, idx = 0, len = stk.size();
if (len & 1) mid = (len + 1) / 2;
else mid = len / 2;

while (cnt + blk[idx] < mid) {
cnt += blk[idx++];
}

idx *= sqrN;
while (cnt + tb[idx] < mid) {
cnt += tb[idx++];
}
printf("%d\n", idx);
} else {
int t = stk.top();
stk.pop();
printf("%d\n", t);
blk[t / sqrN]--;
tb[t]--;
}
}
}
}
}

Tsukkomi

  这道题还有好多解法,有空补上。


#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×