【PAT甲级】1057 Stack (30)(BIT+二分)

题目链接

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 (<= 10^5^). 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 10^5^.

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

思路:树状数组+二分;线段树

注意:不能用C++的cin,cout,否则超时

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <map>
#include <stack>
#include <cmath>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define mem(a,n) memset(a,n,sizeof(a))
#define lowbit(i) ((i)&(-i))
typedef long long ll;
typedef unsigned long long ull;
const ll INF=0x3f3f3f3f;
const int N = 1e5+5;

int c[N];
///BIT的更新
void update(int i,int val) {
    while(i<N) {
        c[i]+=val;
        i+=lowbit(i);
    }
}
///BIT的求和
int getSum(int i) {
    int sum=0;
    while(i>0) {
        sum+=c[i];
        i-=lowbit(i);
    }
    return sum;
}   
stack<int>st;
///求中值
void peekMid() {
    int lo=1,hi=N,mid;
    int k=(st.size()+1)>>1;
    while(lo<hi) {
        mid=(lo+hi)>>1;
        if(getSum(mid)>=k) hi=mid;
        else lo=mid+1;
    }
    printf("%d\n",lo);
}
int main() {
    int n;
    scanf("%d",&n);
    char str[20];
    while(n--) {
        scanf("%s",str);
        if(str[1]=='u') {
            int x;
            scanf("%d",&x);
            st.push(x);
            update(x,1);
        } else if(str[1]=='o') {
            if(st.empty()) {
                puts("Invalid");
            } else {
                int tmp=st.top();
                printf("%d\n",tmp);
                st.pop();
                update(tmp,-1);
            }
        } else {
            if(st.empty()) {
                puts("Invalid");
            } else {
                peekMid();
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/feng_zhiyu/article/details/81349179