分块易想难调。
大BUG:
. 块数可能为(blockSize + 1)
. 边界为(max{n, block[x] * blockSize})
. 有时块内不行了,就不能去块外,要灵活应对,因题而定
话说这是道平衡树模板题来着
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long
#define ON_DEBUG
#ifdef ON_DEBUG
#define D_e_Line printf("
----------
")
#define D_e(x) cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);
#else
#define D_e_Line ;
#define D_e(x) ;
#define Pause() ;
#define FileOpen() ;
#endif
struct ios{
template<typename ATP>ios& operator >> (ATP &x){
x = 0; int f = 1; char c;
for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
x*= f;
return *this;
}
}io;
using namespace std;
const int N = 50007;
int n;
int vis[N];
int sta[N], top;
int block[N], blockSize;
int ans[N], peace[N];
inline void Destroy(int x){
vis[x] = true;
--ans[block[x]];
}
inline void Rescue(int x){
vis[x] = false;
++ans[block[x]];
}
inline int Query(int x){
if(vis[x] == true) return 0;
int sum = 0;
int flagLeft = 0, flagRight = 0;
int maxx = Min(block[x] * blockSize, n);
R(i,x + 1,maxx){
if(vis[i] == true){
flagRight = 1;
break;
}
++sum;
}
nR(i,x - 1, (block[x] - 1) * blockSize + 1){
if(vis[i] == true){
flagLeft = 1;
break;
}
++sum;
}
if(flagLeft == 1 && flagRight == 1) return sum + 1;
int flag = 0;
if(flagRight == 0){
R(i,block[x] + 1, block[n]){
if(flag) break;
if(ans[i] == peace[i]){
sum += ans[i];
continue;
}
flag = 1;
int maxx = Min(i * blockSize, n);
R(j,(i - 1) * blockSize + 1, maxx){
if(vis[j] == true) break;
++sum;
}
}
}
if(flagLeft == 0){
flag = 0;
nR(i,block[x] - 1, 1){
if(flag) break;
if(ans[i] == peace[i]){
sum += ans[i];
continue;
}
flag = 1;
nR(j,i * blockSize, (i - 1) * blockSize + 1){
if(vis[j] == true){
break;
}
++sum;
}
}
}
return sum + 1;
}
int main(){
//FileOpen();
int m;
io >> n >> m;
blockSize = sqrt(n) + 1;
R(i,1,n){
block[i] = (i - 1) / blockSize + 1;
++ans[block[i]];
}
R(i,1,blockSize) peace[i] = ans[i];
while(m--){
char ch = getchar();
while(ch != 'D' && ch != 'R' && ch != 'Q') ch = getchar();
if(ch == 'D'){
int x;
io >> x;
Destroy(x);
sta[++top] = x;
}
else if (ch == 'R'){
if(!top) continue;
Rescue(sta[top]);
--top;
}
else{
int x;
io >> x;
printf("%d
", Query(x));
}
}
return 0;
}
/*
$1 belong to 1
$2 belong to 1
$3 belong to 2
$4 belong to 2
$5 belong to 3
$6 belong to 3
$7 belong to 4
*/