很巧妙的用了差分建树,解决区间修改的问题
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int maxn=5e5+5; 5 6 int n,m; 7 int a[maxn]; 8 ll tree[maxn]; 9 10 int lowbit(int x){ 11 return x&(-x); 12 } 13 14 void add(int idx,int v){ 15 for(int i=idx;i<=n;i+=lowbit(i)) 16 tree[i]+=v; 17 } 18 19 ll sum(int x){ 20 ll ans=0; 21 while(x!=0){ 22 ans+=tree[x]; 23 x-=lowbit(x); 24 } 25 return ans; 26 27 } 28 int main(){ 29 std::ios::sync_with_stdio(false); 30 cin>>n>>m; 31 for(int i=1;i<=n;i++) cin>>a[i],add(i,a[i]-a[i-1]); 32 for(int i=1;i<=m;i++){ 33 //cout <<i<<"i=="<<endl; 34 int op,x,y,z;cin>>op; 35 if(op==1) { 36 cin>>x>>y>>z;add(x,z);add(y+1,-z);} 37 else { 38 cin>>x;cout <<sum(x)<<"\n";} 39 } 40 41 return 0; 42 }
原文地址:https://www.cnblogs.com/Msmw/p/11468767.html
时间: 2024-11-06 10:04:53