#include<bits/stdc++.h>
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl "\n"
#define fir first
#define sec second
#define pb push_back
#define pii pair<int,int>
using namespace std;
const int N=1e5+5;
int t,n,k;
int s[N];
struct segtreenode {
int val,lazy;
} segtree[N<<2];
void pushup(int rt) {
segtree[rt].val=segtree[rt<<1].val+segtree[rt<<1|1].val;
}
void pushdown(int rt,int ln,int rn) {
if(segtree[rt].lazy) {
segtree[rt<<1].lazy+=segtree[rt].lazy ;
segtree[rt<<1|1].lazy+=segtree[rt].lazy ;
segtree[rt<<1].val+=segtree[rt].lazy*ln;
segtree[rt<<1|1].val+=segtree[rt].lazy*rn;
segtree[rt].lazy=0;
}
}
void build(int l,int r,int rt) {
segtree[rt].lazy=0;
if(l==r) {
segtree[rt].val=s[l];
return ;
}
int mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
pushup(rt);
}
//单点更新
void update(int L,int c,int l,int r,int rt) {
if(l==r) {
// cout<<rt<<endl;
segtree[rt].val+=c;
return ;
}
int mid=(l+r)>>1;
if(L<=mid)update(L,c,l,mid,rt<<1);
else update(L,c,mid+1,r,rt<<1|1);
pushup(rt);
}
//区间查询
int qury(int L,int R,int l,int r,int rt) {
if(L<=l&&r<=R) {
return segtree[rt].val;
}
if(L>r||R<l) {
return 0;
}
int mid=(l+r)>>1;
pushdown(rt,mid-l+1,r-mid);
int ans=0;
if(L<=mid)ans+=qury(L,R,l,mid,rt<<1);
if(R>mid)ans+=qury(L,R,mid+1,r,rt<<1|1);
return ans;
}
//区间更新
void up_date(int L,int R,int c,int l,int r,int rt) {
if(L<=l&&r<=R) {
segtree[rt].val+=c*(r-l+1);
segtree[rt].lazy+=c;
return ;
}
int mid=(l+r)>>1;
pushdown(rt,mid-l+1,r-mid);
if(L<=mid)up_date(L,R,c,l,mid,rt<<1);
if(R>mid)up_date(L,R,c,mid+1,r,rt<<1|1);
pushup(rt);
}
signed main() {
IOS
cin>>t;
int id=1;
while(t--) {
cin>>n;
for(int i=1; i<=n; i++) {
cin>>s[i];
}
build(1,n,1);
}
}
return 0;
}
线段树模版
最新推荐文章于 2024-09-13 17:05:05 发布