[Luogu 3372] [TEMPLATE] Line Segment tree 1, luogu3372
Description
For example, if you know a sequence, you need to perform the following two operations:
1. Add x to each number in a certain range
2. Obtain the sum of each number in a certain range.
Input/Output Format
Input Format:
The first line contains two integers N and M, indicating the number of numbers in the series and the total number of operations respectively.
The second row contains N integers separated by spaces. the I-th digit indicates the initial value of the I-th Column.
Each row in the next M row contains 3 or 4 integers, indicating an operation, as shown below:
Operation 1: Format: 1 x y k meaning: Add k to each number in the range [x, y]
Operation 2: Format: 2 x y Meaning: Sum of each number in the output range [x, y]
Output Format:
The output contains several integer rows, that is, the result of all operation 2.
Input and Output sample input sample #1:
5 51 5 4 2 32 2 41 2 3 22 3 41 1 5 12 1 4
Output sample #1:
11820
Description
Time-Space limit: 1000 ms, 128 M
Data scale:
For 30% of data: N <= 8, M <= 10
For 70% of data: N <= 1000, M <= 10000
For 100% of data: N <= 100000, M <= 100000
(The data has been enhanced ^ _ ^ to ensure that it is within the range of int64/long data)
Example:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<algorithm> 5 #define ll l,mid,rt<<1 6 #define rr mid+1,r,rt<<1|1 7 #define LL long long 8 #define maxn 100005 9 using namespace std;10 LL add[maxn<<2],sum[maxn<<2];11 void pushdown(int rt,int m){12 if(add[rt]){13 add[rt<<1]+=add[rt];14 add[rt<<1|1]+=add[rt];15 sum[rt<<1]+=add[rt]*(m-(m>>1));16 sum[rt<<1|1]+=add[rt]*(m>>1);17 add[rt]=0;18 }19 }20 void build(int l,int r,int rt){21 add[rt]=0;22 if(l==r){23 scanf("%lld",&sum[rt]);24 return ;25 }26 int mid=(l+r)>>1;27 build(ll);build(rr);28 sum[rt]=sum[rt<<1]+sum[rt<<1|1];29 }30 void update(int ql,int qr,int c,int l,int r,int rt){31 if(ql<=l&&r<=qr){32 add[rt]+=c;33 sum[rt]+=(LL)c*(r-l+1);34 return ;35 }36 pushdown(rt,r-l+1);37 int mid=(l+r)>>1;38 if(ql<=mid) update(ql,qr,c,ll);39 if(mid<qr) update(ql,qr,c,rr);40 sum[rt]=sum[rt<<1]+sum[rt<<1|1];41 }42 LL query(int ql,int qr,int l,int r,int rt){43 if(ql<=l&&r<=qr) return sum[rt];44 pushdown(rt,r-l+1);45 int mid=(l+r)>>1;46 LL ret=0;47 if(ql<=mid) ret+=query(ql,qr,ll);48 if(mid<qr) ret+=query(ql,qr,rr);49 return ret;50 }51 int main(){52 int n,q;53 scanf("%d%d",&n,&q);54 build(1,n,1);55 while(q--){56 int Q;57 int a,b,c;58 scanf("%d",&Q);59 if(Q==2){60 scanf("%d%d",&a,&b);61 printf("%lld\n",query(a,b,1,n,1));62 }63 else{64 scanf("%d%d%d",&a,&b,&c);65 update(a,b,c,1,n,1);66 }67 }68 return 0;69 }