1057 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 (≤10^5^). Then N lines follow, each contains a command in one of the following 3 formats:

1
2
3
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

浅析

Q:在普通栈的基础上加上查询中位数的功能。

普通栈用 stack 头文件可快速实现。考虑到数字比较多,中位数用哈希表实现,重写 Push 和 Pop 来实现出入栈的同时哈希表的维护。

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
52
53
54
55
56
57
58
59
60
61
#include 
#include
#include
using namespace std;

const int maxn = 100010;
const int sqrN = 316;

int table[maxn] = {0}; //哈希表
int block[sqrN] = {0}; //哈希表每块元素的个数
stack<int> st;
void Push(int a){
st.push(a);
table[a]++;
block[a/sqrN]++;
}
void Pop(){
int a = st.top();
st.pop();
table[a]--;
block[a/sqrN]--;
printf("%d\n", a);
}
void PeekMedian(){
int k = st.size();
if(k%2 == 1)
k = (k + 1) / 2;
else
k = k / 2;
int sum = 0;
int idx = 0; //找到中位数所在块号
while(sum+block[idx]
sum += block[idx++];
int num = idx * sqrN;
while(sum+table[num]
sum += table[num++];
printf("%d\n", num);
}
int main(){
int x,query;
scanf("%d", &query);
char cmd[15];
for (int i = 0; i < query;i++){
scanf("%s", cmd);
if(strcmp(cmd,"Push")==0){
scanf("%d", &x);
Push(x);
}
else{
if(st.empty())
printf("Invalid\n");
else{
if(strcmp(cmd,"Pop")==0)
Pop();
else
PeekMedian();
}
}
}
return 0;
}
丨fengche丨 wechat
来找我聊天吧~
-------------本文结束感谢您的阅读-------------