题目链接:http://poj.org/problem?id=2892
题意:n个城市连成一条链 除了城市1与城市n 每个城市i左右都分别连接了城市i-1 i+1
有m次操作 操作分为三种
D x 表示摧毁城市x 所有途径该城市的路均被摧毁
R 表示修复上一次摧毁的城市
Q x 表示询问与x直接或间接连接的城市数目(包括城市x)也就是以x为中心连续的未被摧毁的最长区间长度。
题解:
用树状数组或者线段树来维护区间内没有被摧毁(或者已经被摧毁)的城市数量。
用一个栈来维护摧毁顺序,用于修复。
对于每次查询二分来求最大长度。注意二分边界。
线段树的写法以后再写。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>
#include <cstdlib>
using namespace std;
const int MAX=50000+5;
typedef long long LL;
int vis[MAX];
int bit[MAX];
int N;
int sum(int x)
{
int s=0;
while(x>0)
{
s+=bit[x];
x-=(x&(-x));
}
return s;
}
void add(int x,int v)
{
while(x<=N)
{
bit[x]+=v;
x+=(x&(-x));
}
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)==2)
{
N=n;
memset(bit,0,sizeof(bit));
stack<int> st;
for(int i=0;i<m;i++)
{
getchar();
char op;
int pos;
scanf("%c",&op);
if(op=='D')
{
scanf(" %d",&pos);
if(vis[pos]==0)
{
st.push(pos);
add(pos,1);
vis[pos]=1;
}
}
else if(op=='R')
{
pos=st.top();
st.pop();
if(vis[pos]==1)
{
add(pos,-1);
vis[pos]=0;
}
}
else if(op=='Q')
{
scanf(" %d",&pos);
if(vis[pos]==1)
{
printf("0\n");
continue;
}
int l=pos,r=pos;
int low=0,high=pos,mid;
while(low<=high)
{
mid=(low+high)/2;
if(sum(pos)-sum(mid)>0)
low=mid+1;
else
{
high=mid-1;
l=mid+1;
}
}
low=pos-1;high=n;
while(low<=high)
{
mid=(low+high)/2;
if(sum(mid)-sum(pos-1)>0)
high=mid-1;
else
{
low=mid+1;
r=mid;
}
}
printf("%d\n",r-l+1);
}
}
}
return 0;
}