树状数组的求和及最大值

树状数组的求和及求区间最大值的模板

 

i的父子之间相差lowbit(i)

每一个C[i]都是由c[i-1],c[i-2],c[i-4],……c[i-lowbit(i)]组成,例如c[8] = c[8-1] + c[8-2] + c[8-4]组成

区间求和模板

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

const int N = 5e5+50;
int num[N];
int c[N];
int n;

int lowbit(int t)
{
    return t&(-t);
}

void build(int n){
    for(int i = 1; i <= n; ++i)
    {
        c[i] += num[i];
        for(int j = 1; j <lowbit(i); j<<=1)
            c[i] += c[i-j];
    }
}

void update(int x, int y)
{
    for(int i = x; i <= n; i+=lowbit(i))
        c[i] += y;
}

int query(int x)
{
    int sum = 0;
    for(int i = x; i > 0; i-=lowbit(i) )
        sum += c[i];
    return sum;

}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; ++i)
        cin >> num[i];
    build(n);
    int temp1, temp2;
    cin >> temp1 >> temp2;
    update(temp1, temp2-num[temp1]);
    int x, y;
    cin >> x >> y;
    cout << query(y)-query(x-1) << endl;
    return 0;
}

 

区间最值模板

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

const int N = 1e5+50;
int num[N];
int c[N];
int n;

int lowbit(int x)
{
    return x&(-x);
}

void build()
{
    for(int i = 1; i <= n; ++i)
    {
        c[i] = num[i];
        for(int j = 1; j < lowbit(i); j<<=1)
            c[i] = max(c[i], c[i-j]);
    }
}

void update(int x)
{
    for(int i = x; i <= n; i+=lowbit(i))
    {
        c[i] = num[i];
        for(int j = 1; j < lowbit(i); j<<=1)//每一个C[i]都由i-j组成
            c[i] = max(c[i], c[i-j]);
    }
}

int query(int s, int e)
{
    if(s == e)
        return num[s];
    else
    {
        if((e-lowbit(e)+1) == s)
            return c[e];
        if((e-lowbit(e)+1) > s)
            return max(c[e], query(s, e-lowbit(e)));
        if((e-lowbit(e)+1) < s)
            return max(num[e], query(s, e-1));
    }
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; ++i)
        cin >> num[i];
    build();
    int temp1, temp2;
    cin >> temp1 >> temp2;
    num[temp1] = temp2;
    update(temp1);
    cin >> temp1 >> temp2;
    cout << query(temp1, temp2) << endl;
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值