用树状数组统计wbw。如果出现,我们在后面那个w的位置插上1.统计[x,y]的区间的话,从x+2统计到y。
/*
Pro: 0
Sol:
date:
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <set>
#include <vector>
#define maxn 50009
using namespace std;
int Q,n,t,c[maxn],x,y,op,len;
char a[maxn],ch;
void modify(int pos, int val){
while(pos <= n){
c[pos] += val;
pos += (pos & -pos);
}
}
int getsum(int pos){
int sum = 0;
while(pos){
sum += c[pos];
pos -= (pos & -pos);
}return sum;
}
int main(){
scanf("%d",&t);
for(int ca = 1; ca <= t; ca ++){
printf("Case %d:\n",ca);
memset(c,0,sizeof(c));
scanf("%d%d",&n,&Q);
scanf("%s",a);
for(int i = 2; i < n; i ++){
if(a[i] == 'w' && a[i - 1] == 'b' && a[i - 2] == 'w'){
modify(i + 1,1);
}
}
for(int i = 1; i <= Q; i ++){
scanf("%d%d",&op,&x);
if(op == 0){
scanf("%d",&y); x ++; y ++;
if(y - x <= 1)
puts("0");
else
printf("%d\n",getsum(y) - getsum(x + 1));
}else{
cin >> ch;
if(a[x] == ch) continue;
else{
if(ch == 'w'){//原来是b
if(x - 2 >= 0 && a[x - 1] == 'b' && a[x - 2] == 'w')
modify(x + 1, 1);
if(x - 1 >= 0 && x + 1 <= n - 1 && a[x - 1] == 'w' && a[x + 1] == 'w')
modify(x + 2, -1);
if(x + 2 < n && a[x + 1] == 'b' && a[x + 2] == 'w')
modify(x + 3, 1);
}else{
if(x + 1 < n && x - 1 >= 0 && a[x - 1] == 'w' && a[x + 1] == 'w')
modify(x + 2, 1);
if(x - 2 >= 0 && a[x - 1] == 'b' && a[x - 2] == 'w')
modify(x + 1, -1);
if(x + 2 < n && a[x + 1] == 'b' && a[x + 2] == 'w')
modify(x + 3, -1);
}
}
a[x] = ch;
}
}
}
return 0;
}
本文介绍了一种使用树状数组统计字符串中特定模式的方法。针对包含'wbw'模式的字符串,通过树状数组记录并更新每个字符变化对模式计数的影响。支持区间查询和字符修改操作。
918

被折叠的 条评论
为什么被折叠?



