PAT-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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值