码迷,mamicode.com
首页 > 编程语言 > 详细

区间维护区间查询(树状数组)

时间:2019-04-29 21:23:46      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:lse   stdout   http   cti   ack   long   sdi   ++   dig   

传送门:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <functional>
using namespace std;
#define ll long long
#define re register
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define P pair<int,int>
const int N=1e6+10;
void read(ll &a)
{
    int d=1;
    char ch;
    a=0;
    while(ch=getchar(),!isdigit(ch))
        if(ch==-)
            d=-1;
    a=ch^48;
    while(ch=getchar(),isdigit(ch))
        a=(a<<3)+(a<<1)+(ch^48);
    a*=d;
}
void write(ll x)
{
    if(x<0)
        putchar(45),x=-x;
    if(x>9)
        write(x/10);
    putchar(x%10+0);
}
ll tree1[N],tree2[N];
ll n,T;
ll lowbit(ll x){return x&-x;}
void add(ll *x,ll i,ll c)
{
    while(i<=n)
    {
        x[i]+=c;
        i+=lowbit(i);
    }
}
ll sum(ll *x,ll i)
{
    ll ans=0;
    while(i>0)
    {
        ans+=x[i];
        i-=lowbit(i);
    }
    return ans;
}
int main()
{
    //freopen("out.txt","w",stdout);
    read(n);
    read(T);
    for(re ll i=1;i<=n;i++)
    {
        ll x;
        read(x);
        add(tree1,i,x);
    }
    while(T--)
    {
        ll f;
        read(f);
        if(f==1)
        {
            ll l,r,x;
            read(l);
            read(r);
            read(x);
            add(tree1,l,-(l-1)*x);///在l的位置减去(l-1)*x是因为l之前的没有加x,而后面在r+1位置加的r*x包含(l-1)段,所以此处减去(l-1)*x
            add(tree1,r+1,r*x);
            add(tree2,l,x);///记录在该位置加了个x.
            add(tree2,r+1,-x);
        }
        else
        {
            ll l,r;
            read(l);
            read(r);
            ll ans=0;
            ans+=sum(tree1,r)+sum(tree2,r)*r;
            ans-=sum(tree1,l-1)+sum(tree2,l-1)*(l-1);
            write(ans);
            putchar(\n);
        }
    }
    return 0;
}

 

区间维护区间查询(树状数组)

标签:lse   stdout   http   cti   ack   long   sdi   ++   dig   

原文地址:https://www.cnblogs.com/acm1ruoji/p/10792639.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!