【线段树延迟更新】Codeforces Round #104 (Div. 1) E

本文深入探讨了C++编程中优化代码性能的方法,包括利用位操作提高效率、构建高效的数据结构如堆和平衡树,以及实现复杂算法如快速幂运算。同时,文章详细解释了如何使用数据结构来解决实际问题,例如字符串匹配和动态规划问题。
#define N 1000005
int c4[N*5],c7[N*5];
int c47[N*5],c74[N*5];
bool mark[N*5];
char str[N];
void up(int id){
    c4[id] = c4[id<<1] + c4[id<<1|1];
    c7[id] = c7[id<<1] + c7[id<<1|1];
    c47[id] = max(c47[id<<1] + c7[id<<1|1] , c4[id<<1] + c47[id<<1|1]);
    c74[id] = max(c74[id<<1] + c4[id<<1|1] , c7[id<<1] + c74[id<<1|1]);
}
void build(int s,int t,int id){
    if(s>t)return ;
    mark[id] = 0;
    if(s == t){
        if(str[s] == '4'){
            c4[id] = 1;
            c7[id] = 0;
        } else {
            c4[id] = 0;
            c7[id] = 1;
        }
        c47[id] = c74[id] = 1;
        return ;
    }
    int mid = (s + t)>>1;
    build(s,mid,id<<1);
    build(mid+1,t,id<<1|1);
    up(id);
}
void rev(int id){
    mark[id] = !mark[id];
    swap(c47[id],c74[id]);
    swap(c4[id],c7[id]);
}
void down(int id){
    if(mark[id]){
        mark[id] = 0;
        rev(id<<1);
        rev(id<<1|1);
    }
}
void sw(int s,int t,int id,int l,int r){
    if(s<=l && r<=t){
        rev(id);
        return ;
    }
    down(id);
    int mid = (l+r)>>1;
    if(s<=mid)sw(s,t,id<<1,l,mid);
    if(mid+1<=t)sw(s,t,id<<1|1,mid+1,r);
    up(id);
}
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m) != -1){
        int i,j;
        scanf("%s",str+1);
        build(1,n,1);
        while(m--){
            char op[10];
            scanf("%s",op);
            if(op[0] == 'c'){
                printf("%d\n",c47[1]);
            }else {
                int x,y;
                scanf("%d%d",&x,&y);
                sw(x,y,1,1,n);
            }
        }
    }
    return 0;
}


http://codeforces.com/contest/145/problem/E


















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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值