線段樹模板

來源:互聯網
上載者:User

標籤:gif   down   show   title   scanf   分享圖片   www   alt   hide   

直接上題目連結:https://www.luogu.org/problemnew/show/P3372

 1 #include<cstdio> 2 using namespace std; 3 #define maxn 1000001 4 long long sum[maxn<<2],add[maxn<<2],a[maxn]; 5 int n,m,kind,x,y,w; 6 void Build(int l,int r,int s){ 7     if (l==r){ 8         sum[s]=a[l]; 9         return ;10     }11     int mid=(l+r)>>1;12     Build(l,mid,s<<1);13     Build(mid+1,r,s<<1|1);14     sum[s]=sum[s<<1]+sum[s<<1|1];15 }16 void PushDown(int s,int ln,int rn){17     if (add[s]){18         add[s<<1]+=add[s],sum[s<<1]+=add[s]*ln;19         add[s<<1|1]+=add[s],sum[s<<1|1]+=add[s]*rn;20         add[s]=0;21     }22 }23 void Update(int L,int R,int c,int l,int r,int s){24     if (L<=l&&r<=R){25         add[s]+=c,sum[s]+=c*(r-l+1);26         return ;27     }28     int mid=(l+r)>>1;29     PushDown(s,mid-l+1,r-mid);30     if (L<=mid) Update(L,R,c,l,mid,s<<1);31     if (R>mid) Update(L,R,c,mid+1,r,s<<1|1);32     sum[s]=sum[s<<1]+sum[s<<1|1];33 }34 long long Query(int L,int R,int l,int r,int s){35     if (L<=l&&r<=R) return sum[s];36     int m=(l+r)>>1;37     PushDown(s,m-l+1,r-m);38     long long ans=0;39     if (L<=m) ans+=Query(L,R,l,m,s<<1);40     if (R>m) ans+=Query(L,R,m+1,r,s<<1|1);41     return ans;42 }43 int main(){44     scanf("%d%d",&n,&m);45     for (int i=1;i<=n;i++) scanf("%lld",&a[i]);46     Build(1,n,1);47     for (int i=1;i<=m;i++){48         scanf("%d",&kind);49         if (kind==1){50             scanf("%d%d%d",&x,&y,&w);51             Update(x,y,w,1,n,1);52         }else{53             scanf("%d%d",&x,&y);54             printf("%lld\n",Query(x,y,1,n,1));55         }56     }57 }
線段樹

 

線段樹模板

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.