【codevs 1690】题解

#include<cstdio>
#include<iostream> 
using namespace std;
int n,m;
struct data{
       int l,r,v;
       bool lazy;
       }tr[2000001];
void build(int k,int s,int t)
{
     tr[k].l=s;tr[k].r=t;
     if(s==t)return;
     int mid=(s+t)>>1;
     build(k<<1,s,mid);
     build(k<<1|1,mid+1,t);
 }
void pushdown(int k)
{   
     if(!tr[k].lazy)return;
     tr[k<<1].lazy=!tr[k<<1].lazy;
     tr[k<<1|1].lazy=!tr[k<<1|1].lazy;
     tr[k<<1].v=tr[k<<1].r-tr[k<<1].l+1-tr[k<<1].v;
     tr[k<<1|1].v=tr[k<<1|1].r-tr[k<<1|1].l+1-tr[k<<1|1].v;
     tr[k].lazy=0;
 }
void change(int k,int x,int y)
{
	pushdown(k);
     int l=tr[k].l,r=tr[k].r;
     if(l==x&&r==y)
     {
          tr[k].v=y-x+1-tr[k].v;
          if(l!=r)tr[k].lazy=1;
          return;
          }
     int mid=(l+r)>>1;
     if(mid>=y)change(k<<1,x,y);
     else if(mid<x)change(k<<1|1,x,y);
     else {change(k<<1,x,mid);change(k<<1|1,mid+1,y);}
     tr[k].v=tr[k<<1].v+tr[k<<1|1].v;
 }
int ask(int k,int x,int y)	
{
	pushdown(k);
    int l=tr[k].l,r=tr[k].r;
    if(l==x&&y==r)return tr[k].v;
    int mid=(l+r)>>1;
    if(mid>=y)return ask(k<<1,x,y);
    else if(mid<x)return ask(k<<1|1,x,y);
    else return (ask(k<<1,x,mid)+ask(k<<1|1,mid+1,y));
}
int main()
{
    scanf("%d%d",&n,&m);
    build(1,1,n);
    for(int i=1;i<=m;i++)
    {
            int flag,x,y;
            scanf("%d%d%d",&flag,&x,&y);
            if(flag)printf("%d\n",ask(1,x,y));
            else change(1,x,y);
            }
    return 0;
}

你可能感兴趣的:(算法)