Tunnel Warfare
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9770 Accepted Submission(s): 3820
Frequently the invaders launched attack on some of the villages and destroyed the parts of tunnels in them. The Eighth Route Army commanders requested the latest connection state of the tunnels and villages. If some villages are severely isolated, restoration of connection must be done immediately!
There are three different events described in different format shown below:
D x: The x-th village was destroyed.
Q x: The Army commands requested the number of villages that x-th village was directly or indirectly connected with including itself.
R: The village destroyed last was rebuilt.
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m;
struct xx{
int l, r;
int ls, rs, ms;
} T[N<<2];
void Build(int l, int r, int k){
T[k].l = l, T[k].r = r;
T[k].ls = T[k].rs = T[k].ms = r-l+1;
if(l == r) return;
int mid = (l+r)>>1;
Build(l, mid, k<<1);
Build(mid+1, r, k<<1|1);
}
void Update(int c, int k, int f){
if(T[k].l == T[k].r){
if(f){
T[k].ls = T[k].rs = T[k].ms = 1;
}
else{
T[k].ls = T[k].rs = T[k].ms = 0;
}
return;
}
int mid = (T[k].l+T[k].r)>>1;
if(c <= mid) Update(c, k<<1, f);
else Update(c, k<<1|1, f);
T[k].ls = T[k<<1].ls, T[k].rs = T[k<<1|1].rs;
T[k].ms = max(max(T[k<<1].ms, T[k<<1|1].ms), T[k<<1].rs+T[k<<1|1].ls);
if(T[k<<1].ls == T[k<<1].r-T[k<<1].l+1) T[k].ls += T[k<<1|1].ls;
if(T[k<<1|1].rs == T[k<<1|1].r-T[k<<1|1].l+1) T[k].rs += T[k<<1].rs;
}
int Query(int c, int k){
if(T[k].l == T[k].r || !T[k].ms || T[k].r-T[k].l+1 == T[k].ms) return T[k].ms;
int mid = (T[k].l+T[k].r)>>1;
if(c <= mid){
if(c >= T[k<<1].r-T[k<<1].rs+1){
return Query(c, k<<1) + Query(mid+1, k<<1|1);
}
else return Query(c, k<<1);
}
else{
if(c <= T[k<<1|1].l+T[k<<1|1].ls-1){
return Query(c, k<<1|1) + Query(mid, k<<1);
}
else return Query(c, k<<1|1);
}
}
int main(){
while(scanf("%d%d", &n, &m) == 2){
Build(1, n, 1);
stack<int> k;
for(int i = 0; i < m; i++){
char op[3];
scanf("%s", op);
if(op[0] == 'D'){
int x;
scanf("%d", &x);
k.push(x);
Update(x, 1, 0);
}
else if(op[0] == 'Q'){
int x;
scanf("%d", &x);
printf("%d\n", Query(x, 1));
}
else{
Update(k.top(), 1, 1);
k.pop();
}
}
}
}