Boring data structure problem 模拟-双端队列

题意 :

  • 维护一个“双端队列”,1e7次操作,支持左插入,右插入,按值删除,查找中点(靠右)值 c e i l [ ( m + 1 ) / 2 ] ceil[(m + 1) / 2] ceil[(m+1)/2],值不重复。

思路 :

  • 1e7所以所有操作都要满足 O ( 1 ) O(1) O(1)
  • deque不论是front,back,push_front,push_back,pop_front,pop_back都是 O ( 1 ) O(1) O(1)
  • 查询中间位置,因此想到用两个双端队列维护,由于每次只插入一个数,不难维护前后者长度一样
  • 删除操作,由于插入的值 1 − 1 e 7 1 - 1e7 11e7,可以使用数组记录每个数属于哪个双端队列,删除时直接将vis改为0且更新对应双端队列的长度即可,查询时只要先将在右双端队列左端前vis == 0的值去掉即可,注意删除后也要维护两个双端队列长度一致。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <ctime>
#define endl '\n'
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define lowbit(x) (x&-x)
using namespace std;
const double pi = acos(-1);
typedef long long ll;
typedef pair<int, int> PII;
typedef pair<long, long> PLL;

const int N = 1e7 + 10;

int vis[N], tot;
deque<int> lq, rq;
int lc, rc;		// 记录不用纠结vis数组的非真实情况的左右双端队列的长度

// 每次修改长度后,维护lc == rc / lc + 1 == rc
void del()
{
    // 左双端队列比右双端队列大
    while (lc > rc)
    {
        while (vis[lq.back()] == 0) lq.pop_back();
        rq.push_front(lq.back());
        lq.pop_back();
        vis[rq.front()] = 2;
        lc -- , rc ++ ;
    }
    
    // 右双端队列比左双端队列+1还大
    while (rc > lc + 1)
    {
        while (vis[rq.front()] == 0) rq.pop_front();
        lq.push_back(rq.front());
        rq.pop_front();
        vis[lq.back()] = 1;
        lc ++ , rc -- ;
    }
}

int main()
{
    IOS;
    
    int q;
    cin >> q;
    
    while (q -- )
    {
        string op;
        cin >> op;
        if (op == "L")
        {
            lq.push_front( ++ tot);
            vis[tot] = 1;
            lc ++ ;
            del();
        }
        else if (op == "R")
        {
            rq.push_back( ++ tot);
            vis[tot] = 2;
            rc ++ ;
            del();
        }
        else if (op == "G")
        {
            int x;
            cin >> x;
            if (vis[x] == 1) lc -- ;
            if (vis[x] == 2) rc -- ;
            vis[x] = 0;
            del();
        }
        else
        {
            while (vis[rq.front()] == 0) rq.pop_front();
            cout << rq.front() << endl;
        }
    }
    
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值