洛谷P3870 [TJOI2009]开关(洛谷P2846)(BZOJ1230)

线段树

洛谷P3870
洛谷P2846
BZOJ1230

线段树不解释。

代码:

#include
#include
#include
#include
#define N 100005
#define F inline
using namespace std;
struct tree{ int l,r,s0,s1,f; }t[N<<2];
int n,m;
F char readc(){
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    if (l==r) return EOF; return *l++;
}
F int _read(){
    int x=0; char ch=readc();
    while (!isdigit(ch)) ch=readc();
    while(isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x;
}
F void writec(int x){ if (x>9) writec(x/10); putchar(x%10+48); }
F void _write(int x){ writec(x),putchar('\n'); }
void build(int x,int l,int r){
    t[x]=(tree){l,r,r-l+1,0,0};
    if (l==r) return; int mid=l+r>>1;
    build(x<<1,l,mid),build(x<<1|1,mid+1,r);
}
F void pshd(int x){
    swap(t[x<<1].s0,t[x<<1].s1);
    swap(t[x<<1|1].s0,t[x<<1|1].s1);
    t[x].f^=1,t[x<<1].f^=1,t[x<<1|1].f^=1;
}
void mdfy(int x,int l,int r){
    if (t[x].l>r||t[x].rreturn;
    if (t[x].l>=l&&t[x].r<=r){
        t[x].f^=1,swap(t[x].s0,t[x].s1);
        return;
    }
    if (t[x].f) pshd(x);
    mdfy(x<<1,l,r),mdfy(x<<1|1,l,r);
    t[x].s0=t[x<<1].s0+t[x<<1|1].s0;
    t[x].s1=t[x<<1].s1+t[x<<1|1].s1;
}
int srch(int x,int l,int r){
    if (t[x].l>r||t[x].rreturn 0;
    if (t[x].l>=l&&t[x].r<=r) return t[x].s1;
    if (t[x].f) pshd(x);
    return srch(x<<1,l,r)+srch(x<<1|1,l,r);
}
int main(){
    n=_read(),m=_read(),build(1,1,n);
    while (m--){
        int f=_read(),l=_read(),r=_read();
        if (f) _write(srch(1,l,r));
        else mdfy(1,l,r);
    }
    return 0;
}

你可能感兴趣的:(BZOJ,数据结构---线段树,洛谷,蒟蒻zxl的Blog专栏)