【数据结构】树状数组总结

知识概览

树状数组有两个作用:

  1. 快速求前缀和 时间复杂度O(log(n))
  2. 修改某一个数 时间复杂度O(log(n))

例题展示

  1. 单点修改,区间查询

题目链接

活动 - AcWing本活动组织刷《算法竞赛进阶指南》,系统学习各种编程算法。主要面向有一定编程基础的同学。https://www.acwing.com/problem/content/description/243/

题解

涉及单点修改和求前缀和,并且要求时间复杂度小,可以用树状数组。

代码

cpp 复制代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

const int N = 200010;

int n;
int a[N];
int tr[N];
int Greater[N], lower[N];

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

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

int sum(int x)
{
    int res = 0;
    for (int i = x; i; i -= lowbit(i)) res += tr[i];
    return res;
}

int main()
{
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);

    for (int i = 1; i <= n; i++)
    {
        int y = a[i];
        Greater[i] = sum(n) - sum(y);
        lower[i] = sum(y - 1);
        add(y, 1);  //将y加入树状数组,即数字y出现1次
    }

    memset(tr, 0, sizeof tr);
    LL res1 = 0, res2 = 0;
    for (int i = n; i; i--)
    {
        int y = a[i];
        res1 += Greater[i] * (LL)(sum(n) - sum(y));
        res2 += lower[i] * (LL)(sum(y - 1));
        add(y, 1);  //将y加入树状数组,即数字y出现1次
    }

    printf("%lld %lld\n", res1, res2);

    return 0;
}

2.区间修改,单点查询

题目链接

活动 - AcWing本活动组织刷《算法竞赛进阶指南》,系统学习各种编程算法。主要面向有一定编程基础的同学。https://www.acwing.com/problem/content/248/

题解

需要用到差分数组,区间修改可以转化成对差分数组的单点修改,单点查询可以转化成对差分数组求前缀和,这样就可以转化成经典的树状数组操作。

代码

cpp 复制代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

const int N = 100010;

int n, m;
int a[N];
LL tr[N];

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

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

LL sum(int x)
{
    LL res = 0;
    for (int i = x; i; i -= lowbit(i)) res += tr[i];
    return res;
}

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    
    for (int i = 1; i <= n; i++) add(i, a[i] - a[i - 1]);
    
    while (m--)
    {
        char op[2];
        int l, r, d;
        scanf("%s%d", op, &l);
        if (*op == 'C')
        {
            scanf("%d%d", &r, &d);
            add(l, d), add(r + 1, -d);
        }
        else
        {
            printf("%lld\n", sum(l));
        }
    }
    
    return 0;
}

参考资料

  1. AcWing算法提高课
相关推荐
野生的编程萌新36 分钟前
从冒泡到快速排序:探索经典排序算法的奥秘(二)
c语言·开发语言·数据结构·c++·算法·排序算法
花开富贵ii2 小时前
代码随想录算法训练营四十三天|图论part01
java·数据结构·算法·深度优先·图论
code小毛孩3 小时前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
艾伦~耶格尔10 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
闪电麦坤9512 小时前
数据结构:N个节点的二叉树有多少种(Number of Binary Trees Using N Nodes)
数据结构·二叉树·
快去睡觉~13 小时前
力扣400:第N位数字
数据结构·算法·leetcode
汤永红15 小时前
week1-[循环嵌套]画正方形
数据结构·c++·算法
pusue_the_sun15 小时前
数据结构——顺序表&&单链表oj详解
c语言·数据结构·算法·链表·顺序表
yi.Ist16 小时前
图论——Djikstra最短路
数据结构·学习·算法·图论·好难
数据爬坡ing16 小时前
过程设计工具深度解析-软件工程之详细设计(补充篇)
大数据·数据结构·算法·apache·软件工程·软件构建·设计语言