原题链接:https://acm.hdu.edu.cn/showproblem.php?pid=7072
题意
有四个操作
- 在左端插入一个数
- 在右端插入一个数
- 删除值为x的元素(保证唯一)
- 查询第 ( m + 1 2 ) (\frac{m+1}{2}) (2m+1)个元素的值
分析
赛中一直被删除操作困扰很久,看了题解之后恍然大悟。
思路基本就是维护两个链表,我们控制两个链表的size,使得第 m + 1 2 \frac{m+1}{2} 2m+1个元素正好位于第二个链表的左端,这样第四个操作可以O(1)查询。然后插入时维护大小也基本是O(1)。
接着就是删除操作,我们可以先不删除,给这个数打上标记,并给当前所在的链表size-1,在移动链表或查询时,如果当前元素已经被删除了,我们直接略过这个元素,接着找下一个,直到满足条件为止,这样时间复杂度也基本是O(1),而删除操作最多 1.5 e 6 1.5e6 1.5e6,时间复杂度也不会超过 O ( 1 e 7 + 1.5 e 6 ) O(1e7+1.5e6) O(1e7+1.5e6)
记得手写链表,不然会RE。
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned int ul;
typedef pair<int, int> PII;
const ll inf = 2e18;
const int N = 1e7 + 10;
const int M = 1e6 + 10;
const ll mod = 1e9 + 7;
const double eps = 1e-8;
#define lowbit(i) (i & -i)
#define Debug(x) cout << (x) << endl
#define fi first
#define se second
#define mem memset
#define endl '\n'
bool vis[N];
int LSize, RSize;
int bel[N];
struct List {
int a[N<<1];
int l = 1e7, r = 1e7-1;
int back() {return a[r];}
int front() {return a[l];}
void push_front(int x) {a[--l] = x;}
void push_back(int x) {a[++r] = x;}
void pop_front() {++l;}
void pop_back() {--r;}
}L, R;
void rebuild1() {
while (LSize > RSize) {
int now = L.back();
if (!vis[now]) {
R.push_front(now), RSize++;
bel[now] = 2;
LSize--;
}
L.pop_back();
}
}
void rebuild2() {
while (LSize < RSize - 1) {
int now = R.front();
if (!vis[now]) {
L.push_back(now), RSize--;
bel[now] = 1;
LSize++;
}
R.pop_front();
}
}
int ask() {
while (1) {
int now = R.front();
if (!vis[now]) {
return now;
} else {
R.pop_front();
}
}
}
inline void solve() {
int n; cin >> n;
int cnt = 0;
while (n--) {
char op; cin >> op;
if (op == 'L') {
L.push_front(++cnt);
bel[cnt] = 1;
LSize++;
rebuild1();
} else if (op == 'R') {
R.push_back(++cnt);
bel[cnt] = 2;
RSize++;
rebuild2();
} else if (op == 'G') {
int x; cin >> x;
if (bel[x] == 1) {
LSize--;
rebuild2();
}
else {
RSize--;
rebuild1();
}
vis[x] = 1;
} else {
printf("%d\n", ask());
}
//cout << LSize << ' ' << RSize << endl;
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
signed test_index_for_debug = 1;
char acm_local_for_debug = 0;
do {
if (acm_local_for_debug == '$') exit(0);
if (test_index_for_debug > 20)
throw runtime_error("Check the stdin!!!");
auto start_clock_for_debug = clock();
solve();
auto end_clock_for_debug = clock();
cout << "Test " << test_index_for_debug << " successful" << endl;
cerr << "Test " << test_index_for_debug++ << " Run Time: "
<< double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
cout << "--------------------------------------------------" << endl;
} while (cin >> acm_local_for_debug && cin.putback(acm_local_for_debug));
#else
solve();
#endif
return 0;
}