PAT甲级 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 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

题目大意:
模拟一个有取出中位数功能的栈

分析
要找到中位数,即第k个数
【树状数组,最快】
在树状数组中,存储了数的个数的前缀和:ask(x)表示小于等于x的数的个数
我们二分找一个位置pos,或者说找一个数,满足ask(pos)>=k即可
【线段树,比树状数组稍微慢些】
线段树的每个结点存储当前区间的数出现的个数
【vector+lower_bound】
最慢

树状数组:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 100010;
int c[maxn];
int n;
stack<int> stk;

inline int lowbit(int x) {return x & (-x);}

void add(int x, int v)
{
    for (; x < maxn; x += lowbit(x))
        c[x] += v;
}

int ask(int x)
{
    int ret = 0;
    for (; x; x -= lowbit(x))
        ret += c[x];
    return ret;
}

void mypop()
{
    if (stk.empty()) 
    {
        puts("Invalid");
        return;
    }
    int x = stk.top();
    printf("%d\n", x);
    add(x, -1);
    stk.pop();
}

void mypush()
{
    int x;
    scanf("%d", &x);
    stk.push(x);
    add(x, 1);
}

// 找到中位数,即第k个数
// 在树状数组中,存储了数的个数的前缀和:ask(x)表示小于等于x的数的个数
// 我们二分找一个位置pos,或者说找一个数,满足ask(pos)>=k即可
void peekMedian()
{
    if (stk.empty())
    {
        puts("Invalid");
        return;
    }

    int k = (stk.size()+1)/2;

    int l = 1, r = maxn;
    while (l < r)
    {
        int mid = (l + r) >> 1;
        if (ask(mid) >= k) r = mid;
        else l = mid + 1;
    }
    printf("%d\n", l);
}

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i ++)
    {
        char ops[15];
        scanf("%s", ops);
        if (ops[1] == 'o') mypop();
        else if (ops[1] == 'u') mypush();
        else peekMedian();
    }
    return 0;
}

线段树:

#include <iostream>
#include <stack>
using namespace std;

const int maxn = 100010;
int n;
stack<int> stk;
struct SegmentTree
{
    int l, r, v, add;
}tree[maxn<<2];

void build(int p, int l, int r)
{
    tree[p].l = l, tree[p].r = r;
    if (l == r) return;
    int mid = (l + r) >> 1;
    build(p<<1, l, mid);
    build(p<<1|1, mid+1, r);
}

void pushup(int p)
{
    tree[p].v = tree[p<<1].v + tree[p<<1|1].v;
}

void change(int p, int x, int v)
{
    if (tree[p].l == tree[p].r)
    {
        tree[p].v += v;
        return;
    }
    int mid = (tree[p].l + tree[p].r) >> 1;
    if (x <= mid) change(p<<1, x, v);
    else change(p<<1|1, x, v);
    pushup(p);
}

int ask(int p, int x)
{
    if (tree[p].l == tree[p].r) return tree[p].l;
    if (tree[p<<1].v >= x) return ask(p<<1, x);
    else return ask(p<<1|1, x-tree[p<<1].v);
}

void mypop()
{
    if (stk.empty()) 
    {
        puts("Invalid");
        return;
    }
    int x = stk.top();
    printf("%d\n", x);
    change(1, x, -1);
    stk.pop();
}

void mypush()
{
    int x;
    scanf("%d", &x);
    stk.push(x);
    change(1, x, 1);
}

void peekMedian()
{
    if (stk.empty())
    {
        puts("Invalid");
        return;
    }

    int k = ((int)stk.size()+1)/2;
    printf("%d\n", ask(1, k));
}

int main()
{
    // freopen("/Users/zhbink/Documents/C++/C++/in.txt","r",stdin);
    scanf("%d", &n);
    build(1, 1, maxn);
    for (int i = 0; i < n; i ++)
    {
        char ops[15];
        scanf("%s", ops);
        if (ops[1] == 'o') mypop();
        else if (ops[1] == 'u') mypush();
        else peekMedian();
    }
    return 0;
}


vector维护:

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

stack<int> sta;
vector<int> v;

void push(int k)
{
    sta.push(k);
    auto it = lower_bound(v.begin(), v.end(), k);
    v.insert(it, k);
}

void pop()
{
    if (sta.empty())
        cout << "Invalid" << endl;
    else
    {
        cout << sta.top() << endl;
        auto it = lower_bound(v.begin(), v.end(), sta.top());
        v.erase(it);
        sta.pop();
    }
}
void peekmedian()
{
    if (sta.empty())
        cout << "Invalid" << endl;
    else
    {
        int tot = v.size();
        if (tot % 2 == 0)
            cout << v[tot / 2 - 1] << endl;
        else
            cout << v[tot / 2] << endl;
    }
}
int main()
{
    int T;
    cin >> T;
    while (T--)
    {
        char ops[15];
        scanf("%s", ops);
        if (ops[1] == 'u')
        {
            int key;
            cin >> key;
            push(key);
        }
        else if (ops[1] == 'o')
            pop();
        else
            peekmedian();
    }
    return 0;
}
发布了673 篇原创文章 · 获赞 644 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/90452872