PAT-1057 Stack (树状数组 + 二分查找)

主宰稳场 提交于 2020-03-27 10:07:34

1057. Stack


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

题目大意:要求实现一个栈,除了基础的push和pop操作外,还要拥有查找中间数的操作 (PeekMedian),即n个栈中元素在排序后,该元素的大小排行为 (n+1)/2。因为可能存在大量的查找中间数的操作,所以必须找到快速的解决方法。


主要思想:解此题的过程可谓是一波三折。开始的想法很天真,在每次需要PeekMedian的时候,将栈中元素全部拷贝到一个辅助数组,然后对该数组进行排序,很容易找到中间值,时间复杂度为 O((n^2) lgn),很显然最后超时了。

由于题目说明数据范围为 1~100000,想到了用一个count[]数组来储存每一个数在栈中的个数,然后每一次通过遍历数组累积,当 S[i] = count[1] + count[2] + ... + count[i] >= (n+1)/2 的时候则找到中间值i,时间复杂度为 O(n^2)。

这样显然还会超时,在这个想法的基础上利用树状数组,这种数据结构可以很快的得出前 i 项和,从而可以利用二分查找来找到中间数。于是,push和pop操作时间复杂度为 O(lgn),PeekMedian的复杂度为 O(n (lgn)^2),问题解决。

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string.h>
#define MAXN 100005
using namespace std;
int stack[MAXN];            //array of stack
int c[MAXN];                //BIT
int n = 0;
/*
    functions of Binary Index Tree (BIT)
    */
int lowbit(int x) {
    return x & (-x);
}
int get_sum(int x) {
    int sum = 0;
    for (int i = x; i > 0; i -= lowbit(i)) 
        sum += c[i];
    return sum;
}
void update(int x, int t) {
    for (int i = x; i <= MAXN; i += lowbit(i)) 
        c[i] += t;
}

/*
    operations of stack
    */
bool isEmpty() {
    return n == 0;
}
void push(int key) {
    stack[n++] = key;
    update(key, 1);
}
int pop() {
    int k = stack[--n];
    update(k, -1);
    return k;
}
int peek_median() {
    int lo = 1, hi = MAXN;   
    int median = (n + 1) / 2;
	
	//use the binary search
    while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (median > get_sum(mid))
            lo = mid + 1;
        else								// median <= get_sum(mid)
            hi = mid - 1;
    }   
    return lo;
}


int main(void) {
    int m;
    char comment[11];
    
	scanf("%d", &m);
	getchar();
    for (int i = 0; i < m; i++) {
        gets(comment);
        if (comment[1] == 'u') {			//push 
            int key = atoi(comment+5);
            push(key);
        }       
        else if (comment[1] == 'o') {		//pop
            if(isEmpty()) {
                printf("Invalid\n");
                continue;
            }
            int t = pop();
            printf("%d\n", t);
        }			
        else {								//peek median
            if (isEmpty()) {
                printf("Invalid\n");
                continue;
            }
            int m = peek_median();
            printf("%d\n", m);
        }
    }
    
    return 0;
}


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!