日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Boring data structure problem 模拟-双端队列

發(fā)布時(shí)間:2025/3/19 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Boring data structure problem 模拟-双端队列 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題意 :

  • 維護(hù)一個(gè)“雙端隊(duì)列”,1e7次操作,支持左插入,右插入,按值刪除,查找中點(diǎn)(靠右)值ceil[(m+1)/2]ceil[(m + 1) / 2]ceil[(m+1)/2],值不重復(fù)。

思路 :

  • 1e7所以所有操作都要滿足O(1)O(1)O(1)
  • deque不論是front,back,push_front,push_back,pop_front,pop_back都是O(1)O(1)O(1)
  • 查詢中間位置,因此想到用兩個(gè)雙端隊(duì)列維護(hù),由于每次只插入一個(gè)數(shù),不難維護(hù)前后者長(zhǎng)度一樣
  • 刪除操作,由于插入的值1?1e71 - 1e71?1e7,可以使用數(shù)組記錄每個(gè)數(shù)屬于哪個(gè)雙端隊(duì)列,刪除時(shí)直接將vis改為0且更新對(duì)應(yīng)雙端隊(duì)列的長(zhǎng)度即可,查詢時(shí)只要先將在右雙端隊(duì)列左端前vis == 0的值去掉即可,注意刪除后也要維護(hù)兩個(gè)雙端隊(duì)列長(zhǎng)度一致。
#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; // 記錄不用糾結(jié)vis數(shù)組的非真實(shí)情況的左右雙端隊(duì)列的長(zhǎng)度// 每次修改長(zhǎng)度后,維護(hù)lc == rc / lc + 1 == rc void del() {// 左雙端隊(duì)列比右雙端隊(duì)列大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 ++ ;}// 右雙端隊(duì)列比左雙端隊(duì)列+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; }

總結(jié)

以上是生活随笔為你收集整理的Boring data structure problem 模拟-双端队列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。