PAT甲级 A1057
题目详情
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.
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:
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
解题思路
这道题乍一看是一道很简单的顺序输入操作题目。其难点在于取中位数过程中的时间复杂度。我本来采用sort默认对每次取中位数的情况进行快排,但是仍然超时,利用Hash表存储中位数进行遍历同样超时。柳婼学姐的树状数组没咋看懂,后来只能采用现在网上比较多的分块查找,选定块大小,用table和block共同索引中位数,
以下为写的比较不错的博主的代码
//利用分块的思想查询第K大的数
#include<cstring>
#include<cstdio>
#include<stack>
#include<iostream>
using namespace std;
stack<int> st;
const int maxn = 100010;
const int sqrN = 317; //每块内最大316
int block[sqrN] = { 0 };//block[i]表示块i中的元素个数
int table[maxn] = { 0 };//table[i]表示元素i的存在个数
void push(int num) {
st.push(num);
block[num / 316]++; //把元素num放到相应的块里
table[num]++;
}
void pop() {
if (!st.empty()) {
int num = st.top();
printf("%d\n", num);
st.pop();
block[num / 316]--;
table[num]--;
}
else {
printf("Invalid\n");
}
}
void peekmedian() {
if (!st.empty()) {
int k = (st.size() + 1) / 2;
int sum = 0;
int i = 0;
while (sum + block[i] < k) {
sum += block[i++];
}
int Num = i * 316;
while (sum + table[Num] < k) {
sum += table[Num++];
}
printf("%d\n", Num);
}
else {
printf("Invalid\n");
}
}
int main() {
int N;
cin >> N;
char cmd[15];
for (int i = 0; i < N; i++) {
scanf("%s", cmd);
int tmp;
if (strcmp(cmd, "Push") == 0) {
cin >> tmp;
push(tmp);
}
else if (strcmp(cmd, "Pop") == 0) {
pop();
}
else if (strcmp(cmd, "PeekMedian") == 0) {
peekmedian();
}
}
}
原文指路:原文