Tunnel WarfareTime Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 12163 Accepted Submission(s): 4765 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.
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.
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
Source |
题意:
有三种操作 D X 毁灭X村庄,R 恢复最后毁灭的村庄 ,Q X 查询与X村庄直接或间接相连的村庄有多少。
关于线段树区间合并介绍,可看转载博客:https://blog.youkuaiyun.com/no_O_ac/article/details/81211453.
///注意:左右子树对于区间来说,中间那一段是连续上的,即如左子树右端点为7, 则右子树左端点为8
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
using namespace std;
const int maxn = 50000+50;
struct xx{
int ll,rl,sum;
}tree[maxn * 4];
void build(int l,int r,int root){
tree[root].ll = tree[root].rl = tree[root].sum = r - l + 1;
if(l == r) return ;
int mid = (l + r) / 2;
build(l,mid,root * 2);
build(mid + 1,r,root * 2 + 1);
}
void update(int l,int r,int p,int root,int key){
if(l == r){
tree[root].ll = tree[root].rl = tree[root].sum = key;
return ;
}
int mid = (l + r) / 2;
if(p <= mid)
update(l,mid,p,root * 2,key);
else
update(mid + 1,r,p,root * 2 + 1,key);
tree[root].sum = max(max(tree[root*2].sum,tree[root*2+1].sum),tree[root*2].rl + tree[root*2+1].ll);
tree[root].ll = tree[root*2].ll;
tree[root].rl = tree[root*2+1].rl;
if(tree[root*2].ll == mid - l + 1)
tree[root].ll += tree[root*2+1].ll;
if(tree[root*2+1].rl == r - mid)
tree[root].rl += tree[root*2].rl;
}
int query(int l,int r,int p,int root){
if(l == r || tree[root].sum == r - l + 1 || tree[root].sum == 0)
return tree[root].sum;
int mid = (l + r) / 2;
if(p <= mid){
if(mid - tree[root*2].rl < p) ///显然,如果p位于tree[root*2].rl 之中,不仅要算位于左子树的部分,还要算位于右子树的部分
return query(l,mid,p,root * 2) + query(mid + 1,r,mid + 1,root * 2 + 1);
else
return query(l,mid,p,root * 2);
}
else {
if(mid + 1 + tree[root*2+1].ll > p) ///与上同理
return query(l,mid,mid,root * 2) + query(mid + 1,r,p,root * 2 + 1);
else
return query(mid + 1,r,p,root * 2 + 1);
}
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m)){
build(1,n,1);
char ch; int x;
stack<int> s;
while(m --){
scanf(" %c",&ch);
if(ch == 'D'){
scanf("%d",&x);
s.push(x);
update(1,n,x,1,0);
} else if(ch == 'R'){
x = s.top(); s.pop();
update(1,n,x,1,1);
} else {
scanf("%d",&x);
printf("%d\n",query(1,n,x,1));
}
}
}
return 0;
}