P3372 [template] segment tree 1
Topic links: https://www.luogu.org/problem/P3372
topic:
Title Description
If that is known to a number of columns, you need to perform the following two operations:
1. The section of each of a number of x plus
2. obtaining a number of sections and each
Input Format
The first line contains two integers N, M, respectively, represents the number of the total number of columns and number of operations.
The second line contains N integers separated by spaces, wherein the number indicates the i-th column of the item i of the initial value.
Next M lines contains an integer of 3 or 4, represents an operation, as follows:
Operation 1: Format: 1 XYK Meaning: the interval [x, y] k each number plus
Operation 2: Format: 2 XY Meaning: the number of outputs of each interval [x, y] and the
Output Format
Output contains an integer number of lines, that is, the operation results of all 2.
Sample input and output
5 5 1 5 4 2 3 2 2 4 1 2 3 2 2 3 4 1 1 5 1 2 1 4
11 8 20
Description / Tips
Constraints of time: 1000ms, 128M
Data Scale:
For 30% of the data: N <= 8, M <= 10
For 70% of the data: N <= 1000, M <= 10000
To 100% of the data: N <= 100000, M <= 100000
(Data ^ _ ^ has been strengthened to ensure that within int64 / long long range data)
Sample Description:
// // Created by hanjinyu on 19-9-2. // #include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=1e6+10; int input[maxn]; struct Node{ ll left; ll right; ll num; ll lazy; }tree[maxn*4]; void PushUp(int root) { tree[root].num=tree[root<<1].num+tree[root<<1|1].num; } void PushDown(int root) { if(tree[root].lazy>0) { tree[root<<1].lazy+=tree[root].lazy; tree[root<<1|1].lazy+=tree[root].lazy; tree[root<<1].num+=tree[root].lazy*(tree[root<<1].right-tree[root<<1].left+1); tree[root<<1|1].num+=tree[root].lazy*(tree[root<<1|1].right-tree[root<<1|1].left+1); tree[root].lazy=0; } } void Build(int root,int l,int r) { tree[root].left=l; tree[root].right=r; if(l==r) { tree[root].num=input[l]; return; } int mid=(l+r)>>1; Build(root<<1,l,mid); Build(root<<1|1,mid+1,r); PushUp(root); } void change(int root,int l,int r,int k) { if(tree[root].left>=l&&tree[root].right<=r) { tree[root].num+=k*(tree[root].right-tree[root].left+1); tree[root].lazy+=k; return; } PushDown(root); if(l<=tree[root<<1].right) change(root<<1,l,r,k); if(r>=tree[root<<1|1].left) change(root<<1|1,l,r,k); PushUp(root); } ll Q(int root,int l,int r) { ll ans=0; if(tree[root].left>=l&&tree[root].right<=r) { return tree[root].num; } PushDown(root); if(l<=tree[root<<1].right) ans+=Q(root<<1,l,r); if(r>=tree[root<<1|1].left) ans+=Q(root<<1|1,l,r); return ans; } int main() { int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { scanf("%d",&input[i]); } Build(1,1,n); int a,x,y,k; for(int i=0;i<m;i++) { scanf("%d",&a); if(a==1) { scanf("%d%d%d",&x,&y,&k); change(1,x,y,k); } else if(a==2) { scanf("%d%d",&x,&y); printf("%lld\n",Q(1, x, y)); } } Return 0 ; }