During the War of Resistance Against Japan, tunnel warfare was carried out extensively in the vast areas of north China Plain. Generally speaking, villages connected by tunnels lay in a line. Except the two at the ends, every village was directly connected with two neighboring ones.
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!
Input
The first line of the input contains two positive integers n and m (n, m ≤ 50,000) indicating the number of villages and events. Each of the next m lines describes an event.
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.
Output
Output the answer to each of the Army commanders’ request in order on a separate line.
Sample Input
7 9 D 3 D 6 D 5 Q 4 Q 5 R Q 4 R Q 4
Sample Output
1 0 2 4
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>
using namespace std;
int m,n;
int D[50010];
struct node{
int l,r;
int ll,rl,ml;
//左边开始连续的最大长度和右边开始最大的连续长度
//以及这个区间最大连续长度
}tree[50010<<2];
void Build(int l,int r,int rt){
tree[rt].l = l;
tree[rt].r = r;
tree[rt].ll =tree[rt].rl =tree[rt].ml = r-l+1;
if(l==r) return;
int m=(l+r)/2;
Build(l,m,rt*2);
Build(m+1,r,rt*2+1);
}
int Query(int rt,int x){
if(tree[rt].l==tree[rt].r||tree[rt].ml==0||tree[rt].ml==tree[rt].r-tree[rt].l+1){
return tree[rt].ml;
}
int m=(tree[rt].l+tree[rt].r)/2;
int res=0;
if(x<=m)
{
if(x>=tree[rt<<1].r-tree[rt<<1].rl+1)
return Query(rt<<1,x)+Query((rt<<1)|1,m+1);
else
return Query(rt<<1,x);
}
else
{
if(x<=tree[(rt<<1)|1].l+tree[(rt<<1)|1].ll-1)
return Query((rt<<1)|1,x)+Query(rt<<1,m);
else
return Query((rt<<1)|1,x);
}
}
void Updata(int rt,int L,int C){
if(tree[rt].l==tree[rt].r)
{
tree[rt].ll=tree[rt].rl=tree[rt].ml=C;
return;
}
int m=(tree[rt].l+tree[rt].r)/2;
if(L<=m) Updata(rt<<1,L,C);
else Updata(rt<<1|1,L,C);
tree[rt].ll=tree[rt<<1].ll;
tree[rt].rl=tree[(rt<<1)|1].rl;
tree[rt].ml=max(tree[rt<<1].ml,tree[(rt<<1)|1].ml);
tree[rt].ml=max(tree[rt].ml,tree[rt<<1].rl+tree[(rt<<1)|1].ll);
if(tree[rt<<1].ll==tree[rt<<1].r-tree[rt<<1].l+1)
tree[rt].ll+=tree[(rt<<1)|1].ll;
if(tree[(rt<<1)|1].rl==tree[(rt<<1)|1].r-tree[(rt<<1)|1].l+1)
tree[rt].rl+=tree[rt<<1].rl;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
Build(1,n,1);
char c[2];
int x,d=0;
while(m--){
scanf("%s",c);
if(c[0]=='D'){
scanf("%d",&x);
Updata(1,x,0);
D[d++]=x;
}
if(c[0]=='Q'){
scanf("%d",&x);
cout << Query(1,x) << endl;
}
if(c[0]=='R'){
Updata(1,D[--d],1);
}
}
}
//cout << "Hello world!" << endl;
return 0;
}