PAT (Advanced Level) Practice 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 N N elements, the median value is defined to be the ( N / 2 ) (N/2) (N/2)-th smallest element if N N N is even, or ( ( N + 1 ) / 2 ) ((N+1)/2) ((N+1)/2)-th if N N N is odd.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N ( ≤ 1 0 5 ) N (≤10^5) N(105). Then N N 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 1 0 5 10^5 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

题意

实现一个栈,这个栈有输出中值的功能。

思路

树状数组。

代码

#include 
#include 
#include 

using namespace std;

#define lowbit(i) ((i) & -(i)) // xxx100...

const int MAX_N = 100010;
stack<int> s;
int c[MAX_N]; // 树状数组

void update(int x, int v) { // 更新操作,将位置x的元素加上v
    for (int i = x; i < MAX_N; i += lowbit(i))
        c[i] += v; // 依次向上更新
}

int getSum(int x) { // 求和操作,返回位置1~x的元素之和
    int sum = 0;
    for (int i = x; i > 0; i -= lowbit(i))
        sum += c[i];
    return sum;
}

void peekMedia() { // 二分法求第K大
    int l = 1, r = MAX_N, mid, k = (s.size() + 1) / 2;
    while (l < r) {
        mid = (l + r) / 2;
        if (getSum(mid) >= k)
            r = mid;
        else
            l = mid + 1;
    }
    printf("%d\n", l);
}

int main() {
    int n, x;
    char str[12];
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%s", str);
        if (strcmp(str, "Push") == 0) {
            scanf("%d", &x);
            s.push(x);    // 入栈
            update(x, 1); // 将位置x加1
        } else if (strcmp(str, "Pop") == 0) {
            if (s.empty())
                printf("Invalid\n");
            else {
                printf("%d\n", s.top());
                update(s.top(), -1); // 将栈顶元素所在位置减1
                s.pop();             // 出栈
            }
        } else if (strcmp(str, "PeekMedian") == 0) {
            if (s.empty())
                printf("Invalid\n");
            else
                peekMedia();
        }
    }
}

你可能感兴趣的:(PAT)