题目还是挺简单的,一次就AC了
1057 Stack (30 point(s))
题目原文
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, 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
题目大意
本题要求实现一个栈,只需具备入栈,出栈与返回中位数的功能。
解题思路
入栈出栈只需STL实现,如何找到中位数?此处可以采用分块法,将数据范围分成若干个块,该题数据范围为105,故可以分成 1 0 5 \sqrt{10^5} 105 = 317块,每块元素个数为316。设置两个数组,分别代表每块元素的个数和每个元素的出现次数。再累加每块的元素个数直到大于sta.size()/2,再从该块从头开始累加元素的出现次数直至大于sta.size()/2,该元素即为所求。
代码
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stack>
#include <string>
using namespace std;
stack<int> sta;
const int maxn = 100005;
int block[maxn] = { 0 }, table[maxn] = { 0 };//分别代表每块拥有元素个数及每个元素出现次数
int findMid(int K) {//返回中位数
int sum = 0, i = 0;
while (sum + block[i] < K) {//累加每块元素个数
sum += block[i];
++i;
}
int j = i * 316;
while (sum < K) {
sum += table[j];//累加元素出现次数
++j;
}
--j;
return j;
}
int main()
{
int N, data;
string operation;
int ret = scanf("%d", &N);
getchar();
for (int i = 0; i < N; ++i) {
getline(cin, operation);
string op = operation.substr(0, 2);
if (op == "Pu") {
data = stoi(operation.substr(5));
sta.push(data);
++table[data];
++block[data / 316];
}
else if (op == "Po") {
if (sta.empty()) {
printf("Invalid\n");
continue;
}
data = sta.top();
sta.pop();
--table[data];
--block[data / 316];
printf("%d\n", data);
}
else {
if (sta.empty()) {
printf("Invalid\n");
continue;
}
if (sta.size() % 2 == 0) {
printf("%d\n", findMid(sta.size() / 2));
}
else printf("%d\n", findMid(sta.size() / 2 + 1));
}
}
return 0;
}