标签:
Time Limit: 1000MS | Memory Limit: 131072K | |
Total Submissions: 7749 | Accepted: 3195 |
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:
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
题意:三种操作
D x 摧毁城市x
R 修复最后被摧毁的城市
Q x 问 x 所在最长未被摧毁的区间长度是多少
题解:对于询问Q x 二分枚举左右边界,利用树状数组进行维护
满足条件的区间满足此式子 SUM(r) - SUM(l-1) = r-l+1(SUM[i]代表前i个城市未被摧毁的城市数量,SUM(r) - SUM(l-1)代表[l,r]内城市的存留数量)
二分的时候注意一下下边界,初始值要在最小的基础上减一。
/** 题意:三种操作 D x 摧毁城市x R 修复最后被摧毁的城市 Q x 问 x 所在最长未被摧毁的区间长度是多少 题解:对于询问Q x 二分枚举左右边界,利用树状数组进行维护 满足条件的区间满足此式子 SUM(r) - SUM(l-1) = r-l+1(SUM[i]代表前i个城市未被摧毁的城市数量,SUM(r) - SUM(l-1)代表[l,r]内城市的存留数量) */ #include <iostream> #include <stdio.h> #include <string.h> #include <stack> using namespace std; const int N = 50005; int c[N]; bool destory[N]; stack<int> stk; int n,q; int lowbit(int x){ return x&(-x); } void update(int idx,int v){ for(int i=idx;i<=n;i+=lowbit(i)){ c[i]+=v; } } int getsum(int idx){ int v=0; for(int i=idx;i>=1;i-=lowbit(i)){ v+=c[i]; } return v; } int main() { while(scanf("%d%d",&n,&q)!=EOF){ while(!stk.empty()) stk.pop(); memset(c,0,sizeof(c)); memset(destory,false,sizeof(destory)); for(int i=1;i<=n;i++){ update(i,1); } while(q--){ char s[5]; int x; scanf("%s",s); if(s[0]==‘D‘){ scanf("%d",&x); if(destory[x]) continue; destory[x] = true; update(x,-1); stk.push(x); }else if(s[0]==‘R‘){ if(stk.empty()) continue; x = stk.top(); stk.pop(); update(x,1); destory[x] = false; }else{ scanf("%d",&x); if(destory[x]){ printf("0\n"); continue; } int l=x,r=x; int low = 0,high = x; while(low<=high){ int mid = (low+high)>>1; if(getsum(x)-getsum(mid)==x-mid){ l = mid+1; high = mid-1; }else low = mid+1; } low = x-1,high = n; while(low<=high){ int mid = (low+high)>>1; if(getsum(mid)-getsum(x-1)==mid-x+1){ r = mid; low = mid+1; }else high = mid-1; } printf("%d\n",r-l+1); } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5654970.html