树状数组【模板题】三连

基础版

题目链接

  1. 单点更新
  2. 求区间

注意

  • 数组大小:20000
  • 数据范围:用long long
  • 格式:每个结果输出后加换行符
#include <iostream>
#include <cstring>
using namespace std;
// 前缀和 差分 二分 树状数组 
const int N = 2e5+6;
int n, m;
typedef long long LL;
LL a[N], 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]);
		add(i, a[i]);
	}
	int op, x, c, y;
	while(m--){
    
    
		scanf("%d", &op);
		if(op == 1){
    
    
			scanf("%d%d", &x, &c);
			add(x, c);
		}else{
    
    
			scanf("%d%d", &x, &y);
			printf("%lld\n", sum(y)-sum(x-1));
		}
	}
	return 0;
} 

进阶版

题目链接

  1. 区间更新
  2. 求单点
  • 差分思想
#include <iostream>
#include <cstring>
using namespace std;
// 前缀和 差分 二分 树状数组 
const int N = 2e5+6;
int n, m;
typedef long long LL;
LL a[N], 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);
	memset(a, 0, sizeof a);
	for(int i = 1; i <= n; i++) {
    
    
		scanf("%d", &a[i]);
		add(i, a[i]-a[i-1]);
	}
	int op, x, c, y;
	while(m--){
    
    
		scanf("%d", &op);
		if(op == 1){
    
    
			scanf("%d%d%d", &x, &y, &c);
			add(x, c);
			add(y+1, -c);
		}else{
    
    
			scanf("%d", &x);
			printf("%lld\n", sum(x));
		}
	}
	return 0;
} 

高阶版

题目链接

  1. 区间更新
  2. 查区间
  • 差分双数组
  1. tr1[]差分数组 a[i]-a[i-1]
  2. tr2[]差分数组i*a[i] - (i-1)*a[i-1]
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
int n, m;
const int N = 1e5+5;
typedef long long LL;

LL a[N], tr1[N], tr2[N];
int lowbit(int x)  // 返回末尾的1
{
    
    
    return x & -x;
}

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

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

Guess you like

Origin blog.csdn.net/SYaoJun/article/details/119283609