树状数组特训

文章介绍了如何使用树状数组和差分数组实现区间修改和单点查询的功能,通过给定的示例代码展示了在给定数据结构的基础上进行问题转换的方法。
摘要由CSDN通过智能技术生成
两个基本函数
1.单点修改
void add(int x, int k) {
  while (x <= n) {  // 不能越界
    c[x] = c[x] + k;
    x = x + lowbit(x);
  }
}
2.区间查询
int getsum(int x) {  // a[1]..a[x]的和
  int ans = 0;
  while (x > 0) {
    ans = ans + c[x];
    x = x - lowbit(x);
  }
  return ans;
}
3.初始建立树状数组
#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 10;

int n, m;
int a[N], c[N];

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

signed main() {
  cin >> n >> m;

  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    add(i, a[i]);
  }

}

例题1:https://loj.ac/p/130

#include <bits/stdc++.h>
#define int long long
using namespace std;

const int N = 1e6 + 10;
int n, m;
int a[N], c[N];

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

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

int getsum(int x) {
  int ans = 0;
  while (x > 0) {
    ans = ans + c[x];
    x -= lowbit(x);
  }
  return ans;
}

signed main() {
  cin >> n >> m;

  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    add(i, a[i]);
  }

  while (m--) {
    int a, b, c;
    cin >> a >> b >> c;

    if (a == 1) {
      add(b, c);
    } else {
      cout << getsum(c) - getsum(b - 1) << endl;
    }
  }
}

例题2:https://loj.ac/p/131

思路:我可以实现的是:区间查询,单点修改,但是这个题目要我实现:区间修改,单点查询。转换一下思维,就可以使用差分数组来实现

#include <bits/stdc++.h>
#define int long long
using namespace std;

const int N = 1e6 + 10;
int n, m;
int a[N], c[N];

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

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

int getsum(int x) {
  int ans = 0;
  while (x > 0) {
    ans = ans + c[x];
    x -= lowbit(x);
  }
  return ans;
}

signed main() {
  cin >> n >> m;

  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    add(i, a[i] - a[i - 1]);
  }

  while (m--) {
    int a, b, c, d;
    cin >> a >> b;

    if (a == 1) {
      cin >> c >> d;
      add(b, d);
      add(c + 1, -1 * d);
    } else {
      cout << getsum(b) << endl;
    }
  }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值