树状数组

· · 个人记录

一、基本概念

树状数组是一种用于处理前缀和的数据结构,核心操作:

二、实现步骤

1. lowbit(x)函数

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

2. 单点修改

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

3. 区间查询

int query(int x) {
    int ans = 0;
    while (x > 0) {
        ans += c[x];
        x -= lowbit(x);
    }
    return ans;
}
...
cout << query(r) - query(l - 1) << '\n';

三、例题解析

1. U438237

2. U438249

3. P2759 (数学+二分)

4. P3368

5. P5057

四、离散化

// 假设原始数组 a[] 有 n 个元素,需要离散化

// 1. 复制到临时数组
sort(tmp + 1, tmp + 1 + n);
// 对临时数组排序,为了去重和二分查找

// 2. 去重
int cnt = unique(tmp + 1, tmp + 1 + n) - tmp - 1;

// 3. 离散化
for (int i = 1; i <= n; i++) {
  // 在有序唯一值数组中查找 a[i] 的位置
  a[i] = lower_bound(tmp + 1, tmp + 1 + cnt, a[i]) - tmp;

  // 原本第1小变为第cnt大,原本第2小变为第cnt - 1大,以此类推
  a[i] = cnt - a[i] + 1;
}