线段树板子C++
1 struct node 2 { 3 int l,r,sum,lazy; 4 node *lson,*rson; 5 node() 6 { 7 l = r = sum = lazy = 0; 8 lson = rson = NULL; 9 } 10 }; 11 12 node* build(vector<int> &v,int l,int r) 13 { 14 node *k = new node; 15 k->l = l; 16 k->r = r; 17 18 if(l == r) 19 { 20 k->sum = v[l]; 21 return k; 22 } 23 24 int mid = (l+r)/2; 25 k->lson = build(v,l,mid); 26 k->rson = build(v,mid+1,r); 27 update(k); 28 29 return k; 30 } 31 32 void update(node* k) 33 { 34 k->sum = 0; 35 36 if(k->lson) 37 k->sum += k->lson->sum; 38 if(k->rson) 39 k->sum += k->rson->sum; 40 } 41 42 //同范围加上一个相同的数 43 void changeSegment(node *k,int l,int r) 44 { 45 if(k->lazy) 46 pushdown(k); 47 48 if(k->l==l && k->r==r) 49 { 50 k->sum = (r-l+1)-k->sum; 51 k->lazy = (k->lazy+1)%2; 52 return; 53 } 54 55 int mid = (k->l+k->r)/2; 56 57 if(r <= mid) 58 changeSegment(k->lson,l,r); 59 else if(l > mid) 60 changeSegment(k->rson,l,r); 61 else 62 { 63 changeSegment(k->lson,l,mid); 64 changeSegment(k->rson,mid+1,r); 65 } 66 67 update(k); 68 } 69 70 void pushdown(node *k) 71 { 72 if(k->l == k->r) 73 { 74 k->lazy = 0; 75 return; 76 } 77 78 if(k->lazy) 79 k->lson->sum = (k->lson->r-k->lson->l+1) - k->lson->sum; 80 if(k->lazy) 81 k->rson->sum = (k->rson->r-k->rson->l+1) - k->rson->sum; 82 83 k->lson->lazy = (k->lson->lazy + k->lazy)%2; 84 k->rson->lazy = (k->rson->lazy + k->lazy)%2; 85 86 k->lazy = 0; 87 } 88 89 int query(node *k,int l,int r) 90 { 91 if(k->lazy) 92 pushdown(k); 93 94 if(k->l==l && k->r==r) 95 return k->sum; 96 97 int mid = (k->l+k->r)/2; 98 99 if(r <= mid) 100 return query(k->lson,l,r); 101 else if(l > mid) 102 return query(k->rson,l,r); 103 else 104 return query(k->lson,l,mid)+query(k->rson,mid+1,r); 105 }