树状数组的一些应用

树状数组

能在 nlogn 时间内进行 修改某个数查询前缀和
它有如下几个应用

(1)对序列区间修改(加减一个值) & 点单查询

利用差分数组的思想
我们让 树状数组作为差分数组 就可以做到 O(1) 的区间修改 在 nlogn 时间内查询序列中某个位置的值

For(i,1,n) update(i,w[i] - w[i-1]); //初始化差分数组

update(l,v);  update(r+1,-v); //区间修改

sum(i) //求出序列中i号元素的值

参考题目acwing248

(2)对序列的区间修改 & 某段区间(和)查询

由(1)可知 对树状差分数组求前缀和 为 原序列某点的值
设 原序列为A 差分序列为B
A1 = B1
A2 = B1 + B2
A3 = B1 + B2 + B3

An = B1 + B2 + B3 +…+B(n-1) + Bn
如果求[1,n]这一段A的和 就会有n个B1 ,n-1个B2 … 这是不容易直接求出的
此时需要转化为 求 (n+1)An - (1B1 + 2B2 +…+nBn) 利用两个树状数组 一个是差分数组求Ai 令一个差分树状数组存放iBi 以便直接求出(1B1 + 2B2 +…+iBi)

参考题目acwing243

#include<bits/stdc++.h>
using namespace std;
#define For(i,a,b) for(int i = a;i<=b;++i)
#define For_(i,a,b) for(int i = a;i>=b;--i)
typedef long long LL;
inline int read(){
    int r = 0,f = 1;
    char c = getchar();
    while(c<'0' || c >'9'){
        if(c =='-') f = -1;
        c = getchar();
    }
    while(c>='0' && c<='9'){
        r = (r<<1) + (r<<3) + c - '0';
        c = getchar();
    }
    return r * f;
}
typedef pair<int,int> P;
#define fi first
#define se second
const int N = 100000+ 5 , M = N * 2+ 5 ,INF = 0x3f3f3f3f,Mod = 1e9 + 7;
int n,m;
int a[N];
LL c1[N];
LL c2[N];
int lowbit(int x){
    return -x&x;
}
void updata(LL c[],int x,LL v){
    for(int i = x;i<=n;i += lowbit(i)) c[i] += v;
}
LL sum(LL c[],int x){
    LL res = 0;
    for(;x;x -= lowbit(x)) res += c[x];
    return res; 
}
LL SUM(int x){
    return (x + 1)*sum(c1,x) - sum(c2,x);
}
int main(){
    n = read();m = read();
    For(i,1,n){
        a[i] = read();
        int y = a[i] - a[i-1];
        updata(c1,i,y);
        updata(c2,i,(LL)y * i);
    }
    For(i,1,m){
        char str;
        int l,r,z;
        cin>>str>>l>>r;
        if(str == 'Q'){
            cout<<SUM(r) - SUM(l-1)<<endl;
        }
        else{
            z = read();
            updata(c1,l,z);updata(c1,r+1,(-z));
            updata(c2,l,(LL)(l * z));updata(c2,r+1,(LL)(r+1)*-z);
        }
    }
    system("pause");
    return 0;
}

(3)求一个序列第k小的值

让树状数组作为一个集合 ,c[2] = 1,表示集合中存在2 。
一段序列为 2,4,1,7,5。
sum(7) = 5 就说明7是这里面第5小的
sum(4) = 3 就说明4是这里吗第3小的

参考题目acwing244

就写这些吧~

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值