242. 一个简单的整数问题 树状数组 实现 区间加法 差分 前缀和

题目

在这里插入图片描述

题解思路

我们把原数组保存,把树状数组看成原数组要加的数的差分数组 , 对要加减的区间只需在首部加上目标值,在尾部的后一位减去目标值。

由差分可以知道,对差分数组求前缀和就是原数组的值。

而快速求前缀和正好是树状数组的性质之一。

求这部分的前缀和,就可以得出要加多少数,然后加上原数就行了。

AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
#include <unordered_map>

using namespace std;

const  int  INF =  0x3f3f3f3f;

long long tre[100010] ;
long long a[100010] ;

int n , m ;
int  lowbit( int x )
{
    return x & (-x) ;
}
void add1(int x , int  y )
{
    for (int i = x ; i <= n ; i += lowbit(i) )
        tre[i] += y ;
}

long long sum( int x  )
{
    long long res = a[x] ;

    for (int i = x ; i ; i -= lowbit(i) )
        res += tre[i] ;

    return res ;
}
int main ()
{
    ios::sync_with_stdio(false);
    cin >> n >> m ;
    for (int i = 1 ; i <= n ; i++ )
        cin>>a[i];

    for (int i = 1 ; i <= m ; i++ )
    {
        string t1 ;
        int t2 , t3 , t4 ;
        cin>>t1;
        if ( t1[0] == 'Q')
        {
            cin >> t2 ;
            cout << sum(t2) <<"\n";
        }else
        {
            cin >> t2 >> t3 >> t4 ;
            add1( t2 , t4 );
            add1( t3 + 1 , -t4 );
        }
    }
    return 0 ;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值