线段树
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #define MAX 50010 7 #define inf 100000000 8 using namespace std; 9 int a[MAX]; 10 struct tree{ 11 int l,r,sum,mx,mi,lazy; 12 }f[MAX*4]; 13 14 void pushup(int i){ 15 f[i].sum=(f[i*2+1].sum+f[i*2].sum); 16 f[i].mx=max(f[i*2+1].mx,f[i*2].mx); 17 f[i].mi=min(f[i*2+1].mi,f[i*2].mi); 18 } 19 20 void update(int i,int x) 21 { 22 f[i].sum+=x*(f[i].r-f[i].l+1); 23 f[i].mi+=x; 24 f[i].mx+=x; 25 f[i].lazy+=x; 26 return; 27 } 28 29 void pushdown(int i){ 30 if(f[i].lazy!=0){ 31 update(i*2,f[i].lazy); 32 update(i*2+1,f[i].lazy); 33 f[i].lazy=0; 34 return; 35 } 36 else return; 37 } 38 39 void build(int i,int left,int right){ 40 int mid=(left+right)/2; 41 f[i].lazy=0;f[i].mx=0;f[i].mi=inf; 42 f[i].l=left;f[i].r=right; 43 if(left==right){ 44 f[i].sum=a[left]; 45 f[i].mx=a[left]; 46 f[i].mi=a[left]; 47 return; 48 } 49 build(i*2,left,mid); 50 build(i*2+1,mid+1,right); 51 pushup(i); 52 } 53 54 void add(int i,int left,int right,int v){ 55 int mid=(f[i].l+f[i].r)/2; 56 if(f[i].l==left&&f[i].r==right){ 57 update(i,v); 58 return; 59 } 60 pushdown(i); 61 if(mid>=right)add(i*2,left,right,v); 62 else if(mid<left)add(i*2+1,left,right,v); 63 else add(i*2,left,mid,v),add(i*2+1,mid+1,right,v); 64 pushup(i); 65 } 66 67 int query(int i,int left,int right) { 68 int mid=(f[i].l+f[i].r)/2; 69 if(f[i].l==left&&f[i].r==right) return f[i].sum; 70 pushdown(i); 71 if(mid>=right) return query(i*2,left,right); 72 if(mid<left) return query(i*2+1,left,right); 73 return (query(i*2,left,mid)+query(i*2+1,mid+1,right)); 74 } 75 76 int qmax(int i,int left,int right){ 77 int mid=(f[i].l+f[i].r)/2; 78 if(f[i].l==left&&f[i].r==right) return f[i].mx; 79 pushdown(i); 80 if(mid>=right) return qmax(i*2,left,right); 81 if(mid<left) return qmax(i*2+1,left,right); 82 return max(qmax(i*2,left,mid),qmax(i*2+1,mid+1,right)); 83 } 84 85 int qmin(int i,int left,int right){ 86 int mid=(f[i].l+f[i].r)/2; 87 if(f[i].l==left&&f[i].r==right) return f[i].mi; 88 pushdown(i); 89 if(mid>=right) return qmin(i*2,left,right); 90 if(mid<left) return qmin(i*2+1,left,right); 91 return min(qmin(i*2,left,mid),qmin(i*2+1,mid+1,right)); 92 }