測試題目:P3372 【模板】線段樹 1 https://www.luogu.org/problemnew/show/P3372
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define lson l,m,rt << 1
#define rson m+1,r,rt << 1|1
using namespace std;
inline void fast(){ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);}
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+10;
const int mod = 1000;
int n,m,T;
ll sum[maxn << 2];//記錄區間和
ll add[maxn << 2];//記錄區間標記
struct Node{
int l,r;
int mid(){
return (l + r) >> 1;
}
}tree[maxn << 2]; //每個數組都要開4倍空間
void PushUp(int rt){
sum[rt] = sum[rt << 1] + sum[rt << 1|1];//父節點等於兩個子節點的和
}
void PushDown(int rt,int len){
if(add[rt]){ //如果存在標記
add[rt << 1] += add[rt]; //把標記向下傳遞
add[rt << 1|1] += add[rt];
sum[rt << 1] += (ll)add[rt]*(len - (len >> 1)); //此處要開ll 不然可能回炸int,乘上區間長度
sum[rt << 1|1] += (ll)add[rt]*(len >> 1);
add[rt] = 0; //標記歸零
}
}
void BuildTree(int l,int r,int rt){
tree[rt].l = l; tree[rt].r = r; //對區間進行初始化
if(l == r){ //如果左右區間相等,到達了最終節點,此時這個節點的和就是它本身,直接輸入
cin >> sum[rt];
return ;
}
int m = tree[rt].mid();
BuildTree(lson); //分別向左右建樹
BuildTree(rson);
PushUp(rt);//向上傳遞他們的和
}
void UpdataTree(int c,int l,int r,int rt){
if(tree[rt].l == l && tree[rt].r == r){ //如果找到了我們需要修改的區間
add[rt] += c; //打上標記
sum[rt] += (ll)c*(r - l + 1); //增加區間長度 ,還是要開ll
return ;
}
PushDown(rt,tree[rt].r - tree[rt].l + 1); //每次更改都向下把這個延遲標記傳遞下去
int m = tree[rt].mid();
if(r <= m) //如果我要查詢的右區間比我的標準中值要小,我需要向左查詢
UpdataTree(c,l,r,rt << 1);
else if(l > m) //反之,如果我的左區間比標準區間大,我向右查詢
UpdataTree(c,l,r,rt << 1|1);
else {
UpdataTree(c,lson); //如果再中間,要向兩邊查詢
UpdataTree(c,rson);
}
PushUp(rt);
}
ll Query(int l,int r,int rt){
if(tree[rt].l == l && tree[rt].r == r)
return sum[rt];
int m = tree[rt].mid();
PushDown(rt,tree[rt].r - tree[rt].l + 1);
ll res = 0;
if(r <= m)
res += Query(l,r,rt << 1);
else if(l > m)
res += Query(l,r,rt << 1|1);
else {
res += Query(lson) + Query(rson);
}
return res;
}
int main()
{
fast();
while(cin >> n >> m){
memset(sum,0,sizeof(sum));
memset(add,0,sizeof(add));
BuildTree(1,n,1);
while(m--){
int op,x,y,k;
cin >> op;
if(op == 1){
cin >> x >> y >> k;
UpdataTree(k,x,y,1);
} else {
cin >> x >> y;
printf("%lld\n",Query(x,y,1));
}
}
}
return 0;
}