LITE - Light Switching
Farmer John tries to keep the cows sharp by letting them play with intellectual toys. One of the larger toys is the lights in the barn. Each of the N (2 <= N <= 100,000) cow stalls conveniently numbered 1..N has a colorful light above it.
At the beginning of the evening, all the lights are off. The cows control the lights with a set of N pushbutton switches that toggle the lights; pushing switch i changes the state of light i from off to on or from on to off.
The cows read and execute a list of M (1 <= M <= 100,000) operations expressed as one of two integers (0 <= operation <= 1).
The first kind of operation (denoted by a 0 command) includes two subsequent integers S_i and E_i (1 <= S_i <= E_i <= N) that indicate a starting switch and ending switch. They execute the operation by pushing each pushbutton from S_i through E_i inclusive exactly once.
The second kind of operation (denoted by a 1 command) asks the cows to count how many lights are on in the range given by two integers S_i and E_i (1 <= S_i <= E_i <= N) which specify the inclusive range in which the cows should count the number of lights that are on.
Help FJ ensure the cows are getting the correct answer by processing the list and producing the proper counts.
Input
Line 1: Two space-separated integers: N and M
Lines 2..M+1: Each line represents an operation with three space-separated integers: operation, S_i, and E_i
Output
Lines 1..number of queries: For each output query, print the count as an integer by itself on a single line.
Example
Input:
4 5
0 1 2
0 2 4
1 2 3
0 2 4
1 1 4
Output:
1
2
#include<bits/stdc++.h> #define MAXN 100005 struct node{ int l,r,val; }tree[4*MAXN]; int add[4*MAXN]; void pushdown(int id) { if(add[id]) { add[id*2]=1-add[id*2]; tree[id*2].val=tree[id*2].r-tree[id*2].l+1-tree[id*2].val; add[id*2+1]=1-add[id*2+1]; tree[id*2+1].val=tree[id*2+1].r-tree[id*2+1].l+1-tree[id*2+1].val; add[id]=0; } } void build(int id,int l,int r) { tree[id].l=l; tree[id].r=r; if(l==r) { tree[id].val=0; return; } else { int mid=(l+r)/2; build(id*2,l,mid); build(id*2+1,mid+1,r); tree[id].val=0; } } void update(int id,int l,int r) { if(r<tree[id].l||l>tree[id].r) return; if(tree[id].l==l&&tree[id].r==r) { tree[id].val=r-l+1-tree[id].val; add[id]=1-add[id]; return; } pushdown(id); int mid=(tree[id].l+tree[id].r)/2; if(r<=mid) update(id*2,l,r); else if(l>mid) update(id*2+1,l,r); else { update(id*2,l,mid); update(id*2+1,mid+1,r); } tree[id].val=tree[id*2].val+tree[id*2+1].val; } int query(int id,int l,int r) { if(l==tree[id].l&&r==tree[id].r) return tree[id].val; pushdown(id); int mid=(tree[id].l+tree[id].r)/2; if(r<=mid) return query(id*2,l,r); else if(l>mid) return query(id*2+1,l,r); else return query(id*2,l,mid)+query(id*2+1,mid+1,r); } int main() { memset(add,0,sizeof(add)); int n,m,op,s,e; scanf("%d%d",&n,&m); build(1,1,n); for(int i=0;i<m;i++) { scanf("%d%d%d",&op,&s,&e); if(op==0) update(1,s,e); else printf("%d\n",query(1,s,e)); } return 0; }