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
题意
给定1条1到n的隧道,然后有三个操作。
Q X:查询X周围连通的隧道有多少个(包含自己)
D X:摧毁X位置的隧道。
R :恢复最近被摧毁位置的通道。
题意
处理D,R:线段树的单点修改,分别是置0置1. R用操作用数组模拟栈操作。
处理Q:借助区间求和,sum是单调递增的,可以左边走一个二分答案,右边走一个二分答案即可。
AC代码
#include<cstdio>
#include<iostream>
#include<algorithm>
#define ls (rt << 1)
#define rs (rt << 1 | 1)
using namespace std;
const int maxn = 5e4 + 5;
int sum[maxn<<2], arr[maxn];
int n, m;
void pushUp(int rt){
sum[rt] = sum[ls] + sum[rs];
}
void build(int rt, int l, int r){
if (l == r){
sum[rt] = 1;
return;
}
int m = (l + r) >> 1;
build(ls, l, m);
build(rs, m + 1, r);
pushUp(rt);
}
void update(int rt, int l, int r, int x, int C){
if (l == r){
sum[rt] = C;
return;
}
int m = (l + r) >> 1;
if (x <= m) update(ls, l, m, x, C);
else update(rs, m + 1, r, x, C);
pushUp(rt);
}
int query(int rt, int l, int r, int L, int R){
if (L <= l && r <= R){
return sum[rt];
}
int m = (l + r) >> 1;
int res = 0;
if (L <= m) res += query(ls, l, m, L, R);
if (R > m) res += query(rs, m + 1, r, L, R);
return res;
}
bool check(int l , int r){
int tot = query(1, 1, n, l, r);
return r - l + 1 == tot;
}
void solve(){
while(~scanf("%d%d", &n, &m)){
build(1, 1, n);
char handle[2];
int x, cnt = 0;
while (m--){
scanf("%s", &handle);
if (handle[0] == 'D'){
scanf("%d", &x);
update(1, 1, n, x, 0);
arr[++cnt] = x;
} else if (handle[0] == 'Q'){
scanf("%d", &x);
//最大值最小化,左开右闭
int l = 0, r = x;
while (r - l > 1){
int m = l + (r - l) / 2;
if (check(m, x)) r = m;
else l = m;
}
int ans = x - r;
//最小值最大化,左闭右开
l = x, r = n + 1;
while (r - l > 1){
int m = l + (r - l) / 2;
if (check(x, m)) l = m;
else r = m;
}
ans += l - x;
if (check(x, x)) ans++;
printf("%d\n", ans);
} else {
int y = arr[cnt--];
update(1, 1, n, y, 1);
}
}
}
}
int main(){
solve();
return 0;
}