您的位置:首页 > 其它

PAT--1057. Stack

2017-07-17 23:34 375 查看
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

题解

主要是求栈的中位数,即栈中第
(sta.size() + 1) / 2
个元素。

排序来查询容易超时,可以利用树状数组来求中位数。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;

int n;
int sta[maxn];
int c[maxn];
int top;

int lowbit(int b) { return  b & -b; }
void update(int x, int v){
for(int i = x; i < maxn; i += lowbit(i)) c[i] += v;
}
int sum(int x){
int s = 0;
for(int i = x; i; i -= lowbit(i)) s += c[i];
return s;
}

int main(){

scanf("%d", &n);
char cmd[15];
for(int i = 0; i < n; ++i){
scanf("%s", cmd);
if(!strcmp(cmd, "Pop")){
if(top == 0) printf("Invalid\n");
else {
update(sta[top], -1);
printf("%d\n", sta[top--]);
}
}
else if(!strcmp(cmd, "PeekMedian")){
if(top == 0) printf("Invalid\n");
else{
int left = 1, right = maxn, k = (top + 1) / 2;
while(left < right){
int mid = left + (right - left) / 2;
if(sum(mid) >= k) right = mid;
else left = mid + 1;
}
printf("%d\n", left);
}
}
else{
int val;
scanf("%d", &val);
sta[++top] = val;
update(val, 1);
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pat