题意 :
- 维护一个“双端队列”,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 1−1e7,可以使用数组记录每个数属于哪个双端队列,删除时直接将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;
}