Codeforces145 E. Lucky Queries(线段树)

题意:

给定长度为n的字符串S,只包含字符4和7,
现在要进行m次操作,操作有两种:
(switch l,r):将[l,r]内的4变成7,7变成4
(count):计算串中的最长非递增子序列,输出长度

数据范围:n<=1e6,m<=3e5

解法:
可以用01替换47,这样好写一点.
因为答案一定是:
1.0
2.1
3.一段0一段1
那么线段树维护这三种情况的最大值,
因为存在交换操作,再维护一下(一段1一段0)的情况
遇到交换操作的时候直接交换即可

ps:
每个节点用二维矩阵[2][2]表示00,1101,10的情况,这样超好写!
code:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxm=1e6+5;
char s[maxm];
int b[maxm];
int n,m;
struct Node{
    int a[maxm<<2];
    int laz[maxm<<2];
    int ma[maxm<<2][2][2];
    void chg(int node){
        swap(ma[node][0][0],ma[node][1][1]);
        swap(ma[node][0][1],ma[node][1][0]);
    }
    void pushup(int node,int l,int r){
        ma[node][0][0]=ma[node*2][0][0]+ma[node*2+1][0][0];
        ma[node][1][1]=ma[node*2][1][1]+ma[node*2+1][1][1];
        ma[node][0][1]=max(ma[node*2][0][1]+ma[node*2+1][1][1],ma[node*2][0][0]+ma[node*2+1][0][1]);
        ma[node][1][0]=max(ma[node*2][1][0]+ma[node*2+1][0][0],ma[node*2][1][1]+ma[node*2+1][1][0]);
    }
    void pushdown(int node){
        if(laz[node]){
            chg(node*2);
            chg(node*2+1);
            laz[node*2]^=1;
            laz[node*2+1]^=1;
            laz[node]=0;
        }
    }
    void build(int l,int r,int node){
        if(l==r){
            ma[node][b[l]][b[l]]=1;
            ma[node][0][1]=ma[node][1][0]=1;
            return ;
        }
        int mid=(l+r)/2;
        build(l,mid,node*2);
        build(mid+1,r,node*2+1);
        pushup(node,l,r);
    }
    void update(int st,int ed,int l,int r,int node){
        if(st<=l&&ed>=r){
            chg(node);
            laz[node]^=1;
            return ;
        }
        pushdown(node);
        int mid=(l+r)/2;
        if(st<=mid)update(st,ed,l,mid,node*2);
        if(ed>mid)update(st,ed,mid+1,r,node*2+1);
        pushup(node,l,r);
    }
    int ask(){
        return ma[1][0][1];
    }
}t;
signed main(){
    cin>>n>>m;
    scanf("%s",s+1);
    for(int i=1;i<=n;i++){
        b[i]=(s[i]=='4'?0:1);
    }
    t.build(1,n,1);
    while(m--){
        scanf("%s",s+1);
        if(s[1]=='s'){
            int l,r;scanf("%d%d",&l,&r);
            t.update(l,r,1,n,1);
        }else{
            int ans=t.ask();
            printf("%d\n",ans);
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值