Description
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:
1.D x: The x-th village was destroyed.
2.Q x: The Army commands requested the number of villages that x-th village was directly or indirectly connected with including itself.
3.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
Hint
An illustration of the sample input:
OOOOOOO
D 3 OOXOOOO
D 6 OOXOOXO
D 5 OOXOXXO
R OOXOOXO
R OOXOOOO
题解
==treap的简单运用,最近终于有点空了,想练练平衡树。这道题涉及到插入,删除,和找前驱后继。用treap维护被毁坏的村庄的序列即可。
#include
#include
#include
#include
#include
#include
int n,m,le,rt,root=0,size=0,ds[50005];
char c[3];
struct tree{int l,r,v,rnd;} tr[50005];
void lturn(int &w){
int p=tr[w].r; tr[w].r=tr[p].l; tr[p].l=w; w=p;
}
void rturn(int &w){
int p=tr[w].l; tr[w].l=tr[p].r; tr[p].r=w; w=p;
}
void insert(int &w,int x){
if(w==0){
size++; w=size;
tr[w].v=x; tr[w].rnd=rand();
return ;
}
if(tr[w].v>x){
insert(tr[w].l,x);
if(tr[tr[w].l].rnd<tr[w].rnd) rturn(w);
}
else{
insert(tr[w].r,x);
if(tr[tr[w].r].rnd<tr[w].rnd) lturn(w);
}
}
void findl(int &w,int x){
if(w==0) return;
if(tr[w].v>x) findl(tr[w].l,x);
else {le=tr[w].v; findl(tr[w].r,x);}
}
void findr(int &w,int x){
if(w==0) return;
if(tr[w].v<x) findr(tr[w].r,x);
else {rt=tr[w].v; findr(tr[w].l,x);}
}
void del(int &w,int x){
if(tr[w].v<x) del(tr[w].r,x);
else if(tr[w].v>x) del(tr[w].l,x);
else{
if(tr[w].l*tr[w].r==0) w=tr[w].l+tr[w].r;
else if(tr[tr[w].l].rnd<tr[tr[w].r].rnd){
rturn(w); del(w,x);
}
else {lturn(w); del(w,x);}
}
}
int main()
{
int i,j=0,x;
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++){
scanf("%s",c);
if(c[0]=='D'){
scanf("%d",&ds[++j]);
insert(root,ds[j]);
}
else if(c[0]=='Q'){
scanf("%d",&x);
le=0,rt=n+1; findl(root,x); findr(root,x);
if(rt==le) {puts("0"); continue;}
printf("%d\n",rt-le-1);
}
else {
del(root,ds[j]); j--;
}
}
return 0;
}