hdu3911 Black And White 【線段樹+區間異或操作】

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <stdlib.h>
#include <time.h>
using namespace std;
using namespace std;
const int N=2e5+10;
int ans,num[4*N],L1[4*N],L0[4*N],R1[4*N],R0[4*N],M1[4*N],M0[4*N],f[4*N];

void pushup(int o,int s)
{
    L1[o]=L1[o*2];
    R1[o]=R1[o*2+1];
    if(L1[o]==s-s/2)
        L1[o]+=L1[o*2+1];
    if(R1[o]==s/2)
        R1[o]+=R1[o*2];
    M1[o]=max(max(M1[o*2],M1[o*2+1]),R1[o*2]+L1[o*2+1]);

    L0[o]=L0[o*2];
    R0[o]=R0[o*2+1];
    if(L0[o]==s-s/2)
        L0[o]+=L0[o*2+1];
    if(R0[o]==s/2)
        R0[o]+=R0[o*2];
    M0[o]=max(max(M0[o*2],M0[o*2+1]),R0[o*2]+L0[o*2+1]);
}

void pushdw(int o)
{
    if(f[o])
    {
        f[o*2]^=1;
        f[o*2+1]^=1;
        swap(M1[o*2],M0[o*2]);
        swap(L1[o*2],L0[o*2]);
        swap(R1[o*2],R0[o*2]);
        swap(M1[o*2+1],M0[o*2+1]);
        swap(L1[o*2+1],L0[o*2+1]);
        swap(R1[o*2+1],R0[o*2+1]);
        f[o]=0;
    }
}

void build(int o,int l,int r)
{
    f[o]=0;
    L0[o]=R0[o]=M0[o]=L1[o]=R1[o]=M1[o]=0;
    if(l==r)
    {
        if(num[l]==1)
            L1[o]=R1[o]=M1[o]=1;
        else
            L0[o]=R0[o]=M0[o]=1;
    }
    else
    {
        int m=(l+r)/2;
        build(o*2,l,m);
        build(o*2+1,m+1,r);
        pushup(o,r-l+1);
    }
}

int query(int o,int l,int r,int x,int y)
{
    if(x<=l&&r<=y)
    {
        return M1[o];
    }
    else
    {
        pushdw(o);
        int m=(l+r)/2;
        if(y<=m)
        {
            return query(o*2,l,m,x,y);
        }
        else if(x>m)
        {
            return query(o*2+1,m+1,r,x,y);
        }
        else
        {
            int lson=min(m-x+1,R1[o*2]);
            int rson=min(y-m,L1[o*2+1]);
            int t1=query(o*2,l,m,x,y);
            int t2=query(o*2+1,m+1,r,x,y);
            return max(lson+rson,max(t1,t2));
        }
    }

}
void update(int o,int l,int r,int x,int y)
{
    if(x<=l&&r<=y)
    {
        f[o]^=1;
        swap(M1[o],M0[o]);
        swap(L1[o],L0[o]);
        swap(R1[o],R0[o]);
    }
    else
    {
        pushdw(o);
        int m=(l+r)/2;
        if(x<=m) update(o*2,l,m,x,y);
        if(y>m) update(o*2+1,m+1,r,x,y);
        pushup(o,r-l+1);
    }
}

int main()
{
    int n,m,a,b,k;
    while(~scanf("%d",&n))
    {
        for(int i=1; i<=n; i++)
            scanf("%d",&num[i]);
        build(1,1,n);
        scanf("%d",&m);
        for(int i=1; i<=m; i++)
        {
            scanf("%d%d%d",&k,&a,&b);
            if(k==0)
            {
                ans=query(1,1,n,a,b);
                printf("%d\n",ans);
            }
            else
            {
                update(1,1,n,a,b);
            }
        }
    }
    return 0;
}
發佈了613 篇原創文章 · 獲贊 12 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章