POJ 3468 A Simple Problem with Integers

线段树区间更新求和

#include <map>
#include <set>
#include <list>
#include <cmath>
#include<cctype>
#include <ctime>
#include <deque>
#include <stack>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define PI 3.1415926535897932626
using namespace std;
int gcd(int a, int b)
{
	return a % b == 0 ? b : gcd(b, a % b);
}
#define MAXN  100003
struct node
{
    int l,r;
    LL sum;
    LL mark;//延时标记
}tree[MAXN*4];
LL src[MAXN];
void buildtree(int id,int l ,int r)
{
    tree[id].l=l;tree[id].r=r;
    tree[id].mark=0;
    if (l==r)
    {
        tree[id].sum=src[l];
        return ;
    }
    int m=(l+r)/2;
    buildtree(id*2,l,m);
    buildtree(id*2+1,m+1,r);
    tree[id].sum=tree[id*2].sum+tree[id*2+1].sum;
}
void update(int id ,int l ,int r,LL val)
{
    if (tree[id].l==l && tree[id].r==r)
    {
        tree[id].mark+=val;
        return ;
    }
    tree[id].sum+=(r-l+1)*val;
    int m=(tree[id].l+tree[id].r)/2;
    if (l>m)
        update(id*2+1,l,r,val);
    else if (r<=m)
        update(id*2,l,r,val);
    else
    {
        update(id*2,l,m,val);
        update(id*2+1,m+1,r,val);
    }
}
LL query(int id ,int l ,int r)
{
    if (tree[id].l==l && tree[id].r==r)
    {
        return  tree[id].sum+tree[id].mark*(r-l+1);//这里不更新这个节点的sum,延时标记也不变
    }
    if (tree[id].mark!=0)
    {
        tree[id*2].mark+=tree[id].mark;
        tree[id*2+1].mark+=tree[id].mark;
        tree[id].sum+=tree[id].mark*(tree[id].r-tree[id].l+1);
        tree[id].mark=0;//清空延时标记,
    }
    int m=(tree[id].l+tree[id].r)/2;
    if (l>m)
        return query(id*2+1,l,r);
    else if (r<=m)
        return query(id*2,l,r);
    else
        return query(id*2,l,m)+query(id*2+1,m+1,r);
}
int main()
{
    int N,M;
    scanf("%d%d",&N,&M);
    for (int i=1;i<=N;i++)
        scanf("%lld",&src[i]);
    buildtree(1,1,N);
    char input[3];int a,b;LL c;
    for (int i=0;i<M;i++)
    {
        scanf("%s",input);
        if (input[0]=='Q')
        {
            scanf("%d%d%*c",&a,&b);
            //printf("%d %d\n",a,b);
            printf("%lld\n",query(1,a,b));
        }
        else
        {
            scanf("%d%d%lld%*c",&a,&b,&c);
            update(1,a,b,c);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值