标签:
USACO
YYX家门前的街上有N(2<=N<=100000)盏路灯,在晚上六点之前,这些路灯全是关着的,六点之后,会有M(2<=m<=100000)个人陆续按下开关,这些开关可以改变从第i盏灯到第j盏灯的状态,现在YYX想知道,从第x盏灯到第y盏灯中有多少是亮着的(1<=i,j,x,y<=N)
第 1..询问总次数 行:对于每一次询问,输出询问的结果
4 5
0 1 2
0 2 4
1 2 3
0 2 4
1 1 4
1 /*没什么好说的,线段树的区间修改加区间查询*/ 2 #define N 100100 3 #include<iostream> 4 using namespace std; 5 #include<cstdio> 6 #include<cstring> 7 struct Tree{ 8 int sum,delta,l,r; 9 }tree[N*4]; 10 int n,m,a,x,y; 11 void update(int k) 12 { 13 int lch=k<<1,rch=(k<<1)+1; 14 tree[k].sum=tree[lch].sum+tree[rch].sum; 15 } 16 void build_tree(int k,int l,int r) 17 { 18 tree[k].l=l;tree[k].r=r; 19 if(l==r) 20 { 21 tree[k].sum=tree[k].delta=0; 22 return ; 23 } 24 int mid=(l+r)>>1,lch=k<<1,rch=(k<<1)+1; 25 build_tree(lch,l,mid); 26 build_tree(rch,mid+1,r); 27 update(k); 28 } 29 void down(int k) 30 { 31 int lch=k<<1,rch=(k<<1)+1; 32 tree[lch].delta+=tree[k].delta; 33 tree[lch].delta%=2; 34 tree[lch].sum=(tree[lch].r-tree[lch].l+1)-tree[lch].sum; 35 tree[rch].delta+=tree[k].delta; 36 tree[rch].delta%=2; 37 tree[rch].sum=(tree[rch].r-tree[rch].l+1)-tree[rch].sum; 38 tree[k].delta=0; 39 } 40 void change(int k,int l,int r,int x,int y) 41 { 42 if(x<=l&&r<=y) 43 { 44 tree[k].delta++; 45 tree[k].delta%=2; 46 tree[k].sum=(r-l+1)-tree[k].sum; 47 return; 48 } 49 if(tree[k].delta) 50 down(k); 51 int mid=(l+r)>>1,lch=k<<1,rch=(k<<1)+1; 52 if(x<=mid) 53 change(lch,l,mid,x,y); 54 if(y>mid) 55 change(rch,mid+1,r,x,y); 56 update(k); 57 } 58 int query(int k,int l,int r,int x,int y) 59 { 60 if(x<=l&&r<=y) 61 { 62 return tree[k].sum; 63 } 64 if(tree[k].delta) 65 down(k); 66 int mid=(l+r)>>1,lch=k<<1,rch=(k<<1)+1; 67 int ans=0; 68 if(x<=mid) 69 ans+=query(lch,l,mid,x,y); 70 if(y>mid) 71 ans+=query(rch,mid+1,r,x,y); 72 return ans; 73 } 74 int main() 75 { 76 scanf("%d%d",&n,&m); 77 build_tree(1,1,n); 78 for(int i=1;i<=m;++i) 79 { 80 scanf("%d%d%d",&a,&x,&y); 81 if(a==0) 82 { 83 change(1,1,n,x,y); 84 } 85 else printf("%d\n",query(1,1,n,x,y)); 86 } 87 return 0; 88 }
标签:
原文地址:http://www.cnblogs.com/c1299401227/p/5492875.html