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, insertkey
into the stack and output nothing. For eachPop
orPeekMedian
command, print in a line the corresponding returned value. If the command is invalid, printInvalid
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和strcpy部分。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100010;
int stack[maxn];
int tmp[maxn];
char op[15];
int main() {
int top = 1, op_num;
scanf("%d", &op_num);
stack[0] = -1; // [0]不放数字
for (int i = 0; i < op_num; i++) {
scanf("%s", op);
switch (op[1]) {
case 'u':
scanf("%d", &stack[top++]);
break;
case 'o':
if (top == 1)
{
printf("Invalid\n");
break;
}
else {
printf("%d\n", stack[--top]);
break;
}
case 'e':
if (top == 1)
{
printf("Invalid\n");
break;
}
else {
memcpy(tmp, stack, sizeof(int)*maxn);
sort(tmp, tmp + top);
printf("%d\n", tmp[top / 2 ]);
break;
}
}
}
return 0;
}
采用分块思想,将stack内每一个数映射到block和table里,这样可以利用范围快速查询
//利用分块的思想查询第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();
}
}
}