L3-002 特殊堆栈 (30分)(四种方法)

本文介绍了如何在堆栈中实现中值查询,提供了四种不同的解决方案:双顶堆、树状数组、有序向量和线段树。每种方法都详细解释了其实现原理和操作过程,包括入栈、出栈和取中值操作。通过这些方法,可以在保证效率的同时,实现在不断变化的堆栈中快速获取中值。
摘要由CSDN通过智能技术生成

堆栈是一种经典的后进先出的线性结构,相关的操作主要有“入栈”(在堆栈顶插入一个元素)和“出栈”(将栈顶元素返回并从堆栈中删除)。本题要求你实现另一个附加的操作:“取中值”——即返回所有堆栈中元素键值的中值。给定 N 个元素,如果 N 是偶数,则中值定义为第 N/2 小元;若是奇数,则为第 (N+1)/2 小元。
输入格式:

输入的第一行是正整数 N(≤10​5​​)。随后 N 行,每行给出一句指令,为以下 3 种之一:

Push key
Pop
PeekMedian

其中 key 是不超过 10​5​​ 的正整数;Push 表示“入栈”;Pop 表示“出栈”;PeekMedian 表示“取中值”。
输出格式:

对每个 Push 操作,将 key 插入堆栈,无需输出;对每个 Pop 或 PeekMedian 操作,在一行中输出相应的返回值。若操作非法,则对应输出 Invalid。
输入样例:

17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop

输出样例:

Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid

思路:此处是的难点在与查询区间的中第n/2大的数, 且该区间还要实现删除和增加新元素, 大致有这四种方法实现
1.构建两个堆,形成双顶堆, 其中顶堆中的数都大于底堆中的数
且底堆中的size永远比顶堆的size大1;
每当有新的元素

#include <iostream>
#include <cstring>
#include <set>
#include <stack>

using namespace std;

stack<int> stk;
multiset<int> up, down;//允许有重复元素的两个小顶堆, 且up中每个元素都大于down中的元素

void adjust() //使底堆元素个数比顶堆多一
{
    while (up.size() > down.size()) //如果顶堆的元素个数大于底堆
    {
        down.insert(*up.begin());
        up.erase(up.begin());
    }

    while (down.size() > up.size() + 1)
    {
        auto it = down.end();
        it -- ;
        up.insert(*it);
        down.erase(it);
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    char op[20];
    while (n -- )
    {
        scanf("%s", op);
        if (strcmp(op, "Push") == 0)
        {
            int x;
            scanf("%d", &x);
            stk.push(x);
            if (up.empty() || x < *up.begin()) down.insert(x);// 如果up为空或者其小于up中最小的元素则插入down中
            else up.insert(x);
            adjust();//调整
        }
        else if (strcmp(op, "Pop") == 0)
        {
            if (stk.empty()) puts("Invalid");
            else
            {
                int x = stk.top();
                stk.pop();
                printf("%d\n", x);
                auto it = down.end(); //底堆中的的最后一个指针
                //值得注意的是, 在set中end()存放的是set中元素的个数
                //end() - 1才是最后一个元素
                it -- ;
                if (x <= *it) down.erase(down.find(x));//set中也有find
                else up.erase(up.find(x));

                adjust();
            }
        }
        else
        {
            if (stk.empty()) puts("Invalid");
            else
            {
                auto it = down.end();
                it -- ;
                printf("%d\n", *it);
            }
        }
    }

    return 0;
}

第二种方法,用树状数组加二分查找第n/2大即可

#include<bits/stdc++.h>

using namespace std;
#define lowbit(x) x&-x
const int N = 1e5 + 10;

int s[N], top, pre;
int t[N];

void update(int x, int num)
{
	for(int i = x; i < N; i += lowbit(i))
	{
		t[i] += num;
	}
}

int getsum(int x)
{
	int sum = 0;
	for(int i = x; i; i -= lowbit(i))
		sum += t[i];
	return sum;
}

int query(int x)
{
	x -= 1;
	if(x % 2 == 1)
		x += 1;
	x /= 2;
	int l = 1, r = N - 1;
	while(l < r)
	{
		int mid = l + r >> 1;
		if(getsum(mid) >= x)
			r = mid;
		else
			l = mid + 1;
	}
	return l;
}
int main()
{
	int t;
	cin >> t;
	pre = top = 1;
	while(t --)
	{
		string s1;
		cin >> s1;
		if(s1 == "Pop")
		{
			if(top == 1)
				cout << "Invalid" << endl;
			else
			{
				top --;
				update(s[top], -1);
				cout << s[top] << endl;
			}
		}
		else if(s1 == "PeekMedian")
		{
			if(top == 1)
			{
				cout << "Invalid" << endl;
			}
			else
			{
				int x = top;
				cout << query(x) << endl;
			}
		}
		else
		{
			int x;
			cin >> x;
			s[top ++] = x;
			update(x, 1);
		}
	}
	return 0;
}

第三种就是用vetor插入,每次插入时二分区间找到该插入的位置insert, 删除时也同样二分并erase(), 查询mid时直接输出即可效率较高
此处的二分查询可以直接用low_bound

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
//Constant area
const int MAXN=1000000;
const int MIN_INF=0x80000000;
const int MAX_INF=0x7fffffff;
//Variable area
vector<int> v;
stack<int> s;
int n,tmp;
//Initialization area
void init(){
	v.clear();
    return;
}
//Function area

int main(){
    ios::sync_with_stdio(false);
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    init();
	cin>>n;
	while(n--){
		string ask;
		cin>>ask;
		if(ask[2]=='p'){
			if(v.size()==0){
				cout<<"Invalid"<<endl;
				continue;
			}
			auto i=lower_bound(v.begin(),v.end(),s.top());
			cout<<*i<<endl;
			v.erase(i);
			s.pop();
		}else if(ask[2]=='e'){
			if(v.size()==0){
				cout<<"Invalid"<<endl;
				continue;
			}
			int mid=v.size()%2? v.size()/2:v.size()/2-1;
			cout<<v[mid]<<endl;
		}else if(ask[2]=='s'){
			cin>>tmp;
			auto i=lower_bound(v.begin(),v.end(),tmp);
			v.insert(i,tmp);
			s.push(tmp);
		}
	}
}

第四种便是用线段树查询区间第k打也很简单,

#include<bits/stdc++.h>

using namespace std;
#define lowbit(x) x&-x
const int N = 1e5 + 10;

int s[N], top, pre;
int t[N << 2];

void update(int l, int r, int x, int num, int pos)
{
	if(l == r)
	{
		t[pos] += num;
		return;
	}
	int mid = l + r >> 1;
	if(mid >= x) update(l, mid, x, num, pos<<1);
	else update(mid + 1, r, x, num, pos<<1|1);
	t[pos] = t[pos<<1] + t[pos<<1|1];
}

int query(int l, int r, int y, int pos)
{
	if(l == r)
		return l;
	int mid = l + r >> 1;
	if(y <= t[pos<<1])
		return query(l, mid, y, pos<<1);
	else
		return query(mid + 1, r, y - t[pos<<1], pos<<1|1);
}
int main()
{
	int t;
	cin >> t;
	pre = top = 1;
	while(t --)
	{
		string s1;
		cin >> s1;
		if(s1 == "Pop")
		{
			if(top == 1)
				cout << "Invalid" << endl;
			else
			{
				top --;
				update(1, N - 1, s[top], -1, 1);
				cout << s[top] << endl;
			}
		}
		else if(s1 == "PeekMedian")
		{
			if(top == 1)
			{
				cout << "Invalid" << endl;
			}
			else
			{
				int x = top;
				x -= 1;
				if(x % 2 == 1)	x += 1;
				x /= 2;
				cout << query(1, N - 1, x, 1) << endl;
			}
		}
		else
		{
			int x;
			cin >> x;
			s[top ++] = x;
			update(1, N - 1, x, 1, 1);
		}
	}
	return 0;
}

  • 15
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
题目描述 本题要求实现一个特殊堆栈,除了常规的入栈和出栈操作外,还需要支持以下操作: peek:取出栈顶元素,但是不弹出; min:返回当前栈中的最小值; max:返回当前栈中的最大值。 输入格式 输入第一行给出一个正整数 N(≤10^5),是操作数。以下 N 行每行包含一个操作指令,格式如下: push key:将 key 插入堆栈; pop:弹出栈顶元素; peek:取出栈顶元素,但是不弹出; min:返回当前栈中的最小值; max:返回当前栈中的最大值。 这里假设堆栈中没有重复元素,且输入保证不会出现不合法的操作。 输出格式 对于每个 min 和 max 操作,输出该操作返回的值,如果堆栈为空则输出 ERROR。 输入样例 10 push 3 push 2 push 1 max pop max pop max pop max 输出样例 3 2 3 1 ERROR 算法1 (单调栈) $O(n)$ 首先,我们需要一个普通的栈来实现入栈和出栈操作。 然后,我们需要维护一个单调递减的栈,来实现最小值的查询。每次入栈时,如果当前元素小于等于栈顶元素,就将其入栈。否则,我们需要将栈顶元素弹出,直到栈顶元素小于等于当前元素,再将当前元素入栈。 同理,我们也需要维护一个单调递增的栈,来实现最大值的查询。 对于 peek 操作,我们只需要返回栈顶元素即可。 时间复杂度 每个元素最多入栈一次,出栈一次,查询一次最小值和最大值,因此总时间复杂度为 $O(n)$。 C++ 代码 算法2 (双向队列) $O(n)$ 我们可以使用双向队列来维护最小值和最大值。队列中的元素是一个二元组,第一个元素是值,第二个元素是该值在栈中的出现次数。 每次入栈时,我们需要将该元素插入到双向队列中。同时,我们需要维护队列的单调性。对于最小值队列,我们需要保证队列中的元素是单调递增的。对于最大值队列,我们需要保证队列中的元素是单调递减的。 每次出栈时,我们需要将该元素从双向队列中删除。同时,我们也需要更新队列的单调性。 对于 min 和 max 操作,我们只需要返回最小值队列和最大值队列的队首元素即可。 时间复杂度 每个元素最多入队一次,出队一次,查询一次最小值和最大值,因此总时间复杂度为 $O(n)$。 C++ 代码
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值