poj 3468 A Simple Problem with Integers 線段樹

來源:互聯網
上載者:User

標籤:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;struct node{    int l,r;    long long sum,c;}t[400000+5];void build(int root,int l,int r){    t[root].l=l;    t[root].r=r;    t[root].sum=0;    t[root].c=0;    if(l==r) return ;    build(2*root+1,l,(l+r)/2);    build(2*root+2,(l+r)/2+1,r);}void update(int root,int i,int v){    if(t[root].l==i&&t[root].r==i)    {        t[root].sum=v;        return ;    }    t[root].sum+=v;    int mid=(t[root].l+t[root].r)/2;    if(i<=mid)        update(2*root+1,i,v);    else        update(2*root+2,i,v);}void add(int root,int l,int r,long long c){    if(t[root].l==l&&t[root].r==r)    {        t[root].c+=c;        return ;    }    t[root].sum+=c*(r-l+1);    int mid=(t[root].l+t[root].r)/2;    if(r<=mid)        add(2*root+1,l,r,c);    else if(l>mid)        add(2*root+2,l,r,c);    else    {        add(2*root+1,l,mid,c);        add(2*root+2,mid+1,r,c);    }}long long query(int root,int l,int r){    if(t[root].l==l&&t[root].r==r)    {        return t[root].sum+(r-l+1)*t[root].c;    }    t[root].sum+=(t[root].r-t[root].l+1)*t[root].c;    int mid=(t[root].r+t[root].l)/2;    add(2*root+1,t[root].l,mid,t[root].c);    add(2*root+2,mid+1,t[root].r,t[root].c);    t[root].c=0;    if(r<=mid)        return query(2*root+1,l,r);    else if(l>=mid+1)        return query(2*root+2,l,r);    else    {        return (query(2*root+1,l,mid)+query(2*root+2,mid+1,r));    }}int main(){    int i,n,q,v,a,b;    long long c;    char s[10];    while(~scanf("%d%d",&n,&q))    {        build(0,1,n);        for(i=1;i<=n;i++)        {            scanf("%d",&v);            update(0,i,v);        }        for(i=0;i<q;i++)        {            scanf("%s",s);            if(s[0]==‘C‘)            {                scanf("%d %d %lld",&a,&b,&c);                add(0,a,b,c);            }            else if(s[0]==‘Q‘)            {                scanf("%d%d",&a,&b);                long long ans=query(0,a,b);                printf("%lld\n",ans);            }        }    }    return 0;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

poj 3468 A Simple Problem with Integers 線段樹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.