线段树 POJ 3468 A Simple Problem with Integers 线段树 成段更新入门

来源:互联网 发布:unity3d ongui 编辑:程序博客网 时间:2024/05/17 21:47

做法:基本的成段更新,记住成段更新的原则啊,懒惰更新就是:每一次所加入的影响总有一个范围,现在只要求更新到影响范围的子区间即可,然而,对原状态的影响必须原封不动的体现出来,这样一来,必须开一个标识数组,这个数组是来保存是否受影响,受了什么样的影响,在割裂区间时,可以方便把影响下方到他的子区间上,但原区间的影响必须在加入影响是就已经作用了,而不是equry时在加上去,这就不违背了上面那个原则了,一时感想,勿喷...

#include <iostream>#include <cstdio>#include <cstring>#define left l,m,x<<1#define right m+1,r,x<<1|1#define LL long long#define LMT 100004//成段更新原则:一定要有表现出每一次改变的所有影响//在看题的一开始就要确定使用数值的类型using namespace std;LL add[LMT<<2],sum[LMT<<2];void build(int l,int r,int x){    if(l==r)    {        scanf("%I64d",&sum[x]);        return;    }    int m=(l+r)>>1;    build(left);    build(right);    sum[x]=sum[x<<1]+sum[x<<1|1];}void cut(int x,int have){    if(add[x])    {        add[x<<1]+=add[x];        add[x<<1|1]+=add[x];        sum[x<<1]+=add[x]*(have-(have>>1));//把add 的影响直接体现出来,方便体现影响        sum[x<<1|1]+=add[x]*(have>>1);        add[x]=0;    }}void update(LL key,int L,int R,int l,int r,int x){    if(L<=l&&r<=R)    {        add[x]+=key;        sum[x]+=(r-l+1)*key;        return;    }    int m=(l+r)>>1;    cut(x,r-l+1);    if(L<=m)update(key,L,R,left);    if(R>m)update(key,L,R,right);    sum[x]=sum[x<<1]+sum[x<<1|1];}LL query(int L,int R,int l,int r,int x){    if(L<=l&&r<=R)return sum[x];    int m=(l+r)>>1;    LL ret=0;    cut(x,r-l+1);    if(L<=m)ret+=query(L,R,left);    if(R>m)ret+=query(L,R,right);    return ret;}int main(){    int n,q,a,b;    LL k;    char ord[3];    while(~scanf("%d%d",&n,&q))    {        memset(add,0,sizeof(add));        build(1,n,1);        while(q--)        {            scanf("%s",ord);            if(strcmp(ord,"Q")==0)            {                scanf("%d%d",&a,&b);                printf("%I64d\n",query(a,b,1,n,1));            }            else            {                scanf("%d%d%I64d",&a,&b,&k);                update(k,a,b,1,n,1);            }        }    }    return 0;}


原创粉丝点击