hdu 4046 树状数组

本文介绍了一种使用树状数组统计字符串中特定模式的方法。针对包含'wbw'模式的字符串,通过树状数组记录并更新每个字符变化对模式计数的影响。支持区间查询和字符修改操作。

用树状数组统计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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值