您的位置:首页 > 其它

hdu 4046 树状数组

2013-08-19 18:44 274 查看



View Code

#include<stdio.h>
#include<string.h>
int c[50010];
char str[50010];
int n,m;
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int d)
{
while(x<=n)
{
c[x]+=d;
x+=lowbit(x);
}
}
int sum(int x)
{
int ans=0;
while(x>0)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
int sum(int l,int r) {
if (l > r) return 0;
if (l == 0) return sum(r);
return sum(r) - sum(l - 1);
}
int main()
{
int i,j,type,L,R,pos;
int t,cases=1;
char s[5];
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(c,0,sizeof(c));
scanf("%s",str+1);
printf("Case %d:\n",cases++);
for(i=1;i<=n-2;i++)
{
if(str[i]=='w'&&str[i+1]=='b'&&str[i+2]=='w')
update(i,1);
}
while(m--)
{
int ret;
scanf("%d",&type);
if(type==0)
{
scanf("%d%d",&L,&R);
ret=sum(L+1,R-1);
printf("%d\n",ret);
}
else
{
scanf("%d%s",&pos,s);
pos++;
char ch=str[pos];
str[pos]=s[0];
if(pos-2>=1)
{
if(str[pos-2]=='w'&&str[pos-1]=='b'&&ch=='w')
{
if(str[pos]=='b')
update(pos-2,-1);
}
else
{
if(str[pos-2]=='w'&&str[pos-1]=='b'&&str[pos]=='w')
update(pos-2,1);
}
}
if(pos-1>=1&&pos+1<=n)
{
if(str[pos-1]=='w'&&ch=='b'&&str[pos+1]=='w')
{
if(str[pos]=='w')
update(pos-1,-1);
}
else
{
if(str[pos-1]=='w'&&str[pos]=='b'&&str[pos+1]=='w')
update(pos-1,1);
}
}
if(pos+2<=n)
{
if(ch=='w'&&str[pos+1]=='b'&&str[pos+2]=='w')
{
if(str[pos]=='b')
update(pos,-1);
}
else
{
if(str[pos]=='w'&&str[pos+1]=='b'&&str[pos+2]=='w')
update(pos,1);
}
}
}
}
}

}


最后更新的部分可能写烦了*_*,思想才是最重要的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: