1057 Stack (30 分)

本文介绍了一种特殊的数据结构——栈,它不仅具备基本的Push和Pop操作,还实现了PeekMedian功能,即返回栈中所有元素的中位数。通过使用树状数组结合二分查找或两个multiset数据结构,可以高效地完成这一任务。

 

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++:

树状数组+二分查找:

/*
 @Date    : 2018-01-31 13:18:19
 @Author  : 酸饺子 (changzheng300@foxmail.com)
 @Link    : https://github.com/SourDumplings
 @Version : $Id$
*/

/*
https://www.patest.cn/contests/pat-a-practise/1057
利用树状数组实现了PeekMedian的要求,即利用树状数组实现了快速查找中位数的功能
 */

#include <iostream>
#include <cstring>

using namespace std;

const int MAX = 100001;
int c[MAX]; // 树状数组,下标对应key(在栈中存的值),
// 每个元素记录的是其叶子节点这个值(下标)在栈中的总数

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

int sum(int pos)
{
    int result = 0;
    while (pos)
    {
        result += c[pos];
        pos -= lowbit(pos);
    }
    return result;
}

void add(int pos, int value)
{
    while (pos <= MAX)
    {
        c[pos] += value;
        pos += lowbit(pos);
    }
    return;
}

// 传给find的value是所需中位数在所有数中是第几个
int find(int value)
{
    int l = 0, r = MAX - 1, median, res;
    while (l < r - 1)
    {
        if ((l + r) & 1)
            median = (l + r - 1) / 2;
        else
            median = (l + r) / 2;
        // res即为median(树状数组的元素下标)这个数在栈中是第几个(按最后一个key计数)
        res = sum(median);
        // printf("l = %d r = %d median = %d res = %d value = %d\n", l, r, median, res, value);
        // 判断二分查找区间缩小的够不够
        // 刚开始肯定是res >= value的,一旦res小于了value就意味着median这个数小于所需的中位数了
        // 即最终要找到想要的中位数-1的那个数的最后一个是第几个,再加一即为所需的结果中位数
        if (res < value)
            l = median;
        else
            r = median;
    }
    return l + 1;
}

int main(int argc, char const *argv[])
{
    memset(c, 0, sizeof(c));
    char order[10];
    int stack[MAX], top = 0, N, pos;
    scanf("%d\n", &N);
    while (N--)
    {
        scanf("%s", order);
        if (order[1] == 'u')
        {
            scanf("%d", &pos);
            stack[top++] = pos;
            add(pos, 1);
        }
        else if (order[1] == 'o')
        {
            if (top)
            {
                int out = stack[--top];
                add(out, -1);
                printf("%d\n", out);
            }
            else
                printf("Invalid\n");
        }
        else if (order[1] == 'e')
        {
            if (!top)
                printf("Invalid\n");
            else
            {
                int res;
                if (top & 1)
                    res = find((top+1)/2);
                else
                    res = find(top/2);
                printf("%d\n", res);
            }
        }
    }
    return 0;
}

两个multiset:

/*
 @Date    : 2018-08-28 21:34:24
 @Author  : 酸饺子 (changzheng300@foxmail.com)
 @Link    : https://github.com/SourDumplings
 @Version : $Id$
*/

/*
https://pintia.cn/problem-sets/994805342720868352/problems/994805417945710592
 */


//两个multiset的思路:
//来自:https://blog.youkuaiyun.com/kakitgogogo/article/details/51926600
//模拟stack,不过这里的stack加多一个功能,就是输出中位数。用一个stack数据结构来模拟栈的功能,
//而为了方便得到中位数,要同时维护两个multiset数据结构(因为值可以重复,所以要用multiset)。
//一个set储存前一半的数(设为s1),一个set储存后一半的数(设为s2),
//这里s1的大小要和s2的大小一样或比s2的大小大1。同时更新中位数值mid,mid就是s1的最后一个数。
//在push的时候,把值push到stack中,同时,如果push的值小于等于mid就插入到s1,否则插入到s2,
//最后为了使他们的大小符合上面的描述,所以要调整一下,更新s1,s2和mid。
//pop的时候,对stack进行pop操作,同时,如果pop出来的值小于等于mid,
//就在s1中找出该值然后删除,否则在s2中找出该值然后删除,当前最后也要调整一下,更新s1,
//s2和mid。最后找中位数就直接找就行了。这里要注意的是multiset删除操作中,不能用实值作为参数,
//因为这样会把所有的这个值都删去,这里要先用find函数找出其中一个然后再删除。


#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <set>

using namespace std;

int N;
multiset<int> s1, s2;
int mid = 100005;
stack<int> S;

void adjust()
{
    if (s2.size() + 1 < s1.size())
    {
        s1.erase(s1.find(mid));
        s2.insert(mid);
    }
    else if (s1.size() < s2.size())
    {
        s1.insert(*s2.begin());
        s2.erase(s2.begin());
    }
    if (s1.empty())
        mid = 100005;
    else
        mid = *s1.rbegin();
    return;
}

int main()
{
    scanf("%d", &N);
    while (N--)
    {
        string order;
        cin >> order;
        switch (order[1])
        {
        case 'o':
            {
                if (S.empty())
                {
                    printf("Invalid\n");
                }
                else
                {
                    int p = S.top();
                    printf("%d\n", p);
                    S.pop();
                    if (p <= mid)
                    {
                        auto it = s1.find(p);
                        if (it != s1.end())
                        {
                            s1.erase(it);
                            adjust();
                        }
                    }
                    else
                    {
                        auto it = s2.find(p);
                        if (it != s2.end())
                        {
                            s2.erase(it);
                            adjust();
                        }
                    }
                }
                break;
            }
        case 'e':
            {
                if (S.empty())
                    printf("Invalid\n");
                else
                    printf("%d\n", mid);
                break;
            }
        case 'u':
            {
                int p;
                scanf("%d", &p);
                S.push(p);
                if (p <= mid)
                {
                    s1.insert(p);
                    adjust();
                }
                else
                {
                    s2.insert(p);
                    adjust();
                }
                break;
            }
        }
    }

    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值