Problem 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:
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
区间合并经典例题
这题唯一的难点在query函数,4种情况,详情见代码。
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ls i<<1
#define rs i<<1|1
#define lson ls,l,m
#define rson rs,m+1,r
const int maxn=1e5+7;
const int mod=1e9+7;
int T,n,m,a[maxn],x;
int lc[maxn<<2],rc[maxn<<2],num[maxn<<2];
char ch;
int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+ch-'0';
ch=getchar();
}
return x*f;
}
void pushup(int i,int l,int r){
lc[i]=lc[ls]; rc[i]=rc[rs];
num[i]=max(num[ls],num[rs]);
int m=l+r>>1;
if(lc[i]==m-l+1) lc[i]+=lc[rs];
if(rc[i]==r-m) rc[i]+=rc[ls];
num[i]=max(num[i],rc[ls]+lc[rs]);
}
void build(int i,int l,int r){
if(l==r){
lc[i]=rc[i]=num[i]=1;
return;
}
int m=l+r>>1;
build(lson); build(rson);
pushup(i,l,r);
}
void update(int i,int l,int r,int k,int x){
if(l==r&&l==k){
lc[i]=rc[i]=num[i]=x;
return;
}
int m=l+r>>1;
if(k<=m) update(lson,k,x);
else update(rson,k,x);
pushup(i,l,r);
}
int query(int i,int l,int r,int x){
if(num[i]==0||num[i]==r-l+1||l==r) return num[i];
int m=l+r>>1;
//将x的位置在4种情况下分类讨论,
//左儿子的右区间前
if(x<(m-rc[ls]+1)) return query(lson,x);
//左儿子的右区间中
else if(x<=m) return query(lson,x)+query(rson,m+1);
//右儿子的左区间中
else if(x<=m+lc[rs]) return query(rson,x)+query(lson,m);
//右儿子的左区间后
else return query(rson,x);
}
int main(){
while(~scanf("%d%d",&n,&m)){
stack<int>st;
build(1,1,n);
while(m--){
cin>>ch;
if(ch=='D'){
x=read();
update(1,1,n,x,0);
st.push(x);
}
else if(ch=='Q'){
x=read();
printf("%d\n",query(1,1,n,x));
}
else{
if(st.size()){
x=st.top(); st.pop();
update(1,1,n,x,1);
}
}
}
}
return 0;
}
/*
7 9
D 3
D 6
D 5
Q 4
Q 5
R
Q 4
R
Q 4
1
0
2
4
*/