树状数组C++

这两篇博客介绍了使用C++实现的动态数据结构,包括使用LLLOOOWWWBBBIIITTT函数优化的区间修改和查询功能。第一篇展示了如何在数组中进行区间加法,第二篇则扩展到区间减法并提供整体查询。适合学习和理解区间树或段树的应用。
摘要由CSDN通过智能技术生成

思路没什么好说的
直接上模版
P3374:

#include<bits/stdc++.h>

using namespace std;
const int N = 5e5 + 10;
int n, m;
int a[N];
int s[N];
int LLLOOOWWWBBBIIITTT (int x) {
	return x & (-x);
}
void Jia (int x, int y) {
	for (; x <= n; x += LLLOOOWWWBBBIIITTT (x)) s[x] += y;
}
int HE (int x) {
	int ans = 0;
	for (; x; x -= LLLOOOWWWBBBIIITTT (x)) ans += s[x];
	return ans;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) cin >> a[i], Jia (i, a[i]);
	while (m--) {
		int x, y, z;
		cin >> x >> y >> z;
		if (x == 1) Jia (y, z);
		else cout << HE (z) - HE (y - 1) << endl;
	}
	return 0;
}

P3368:

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const int N = 5e5 + 10;
LL n, m;
LL a[N];
LL s[N];
LL LLLOOOWWWBBBIIITTT (LL x) {
	return x & (-x);
}
void Jia (LL x, LL y, LL z) {
	for (; x <= y; x += LLLOOOWWWBBBIIITTT (x)) s[x] += z;
}
LL HE (LL x) {
	LL ans = 0;
	for (; x; x -= LLLOOOWWWBBBIIITTT (x)) ans += s[x];
	return ans;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m;
	for (LL i = 1; i <= n; i++) cin >> a[i], s[i] = a[i];
	while (m--) {
		LL x;
		cin >> x;
		if (x == 1) {
			LL y, z, asdf;
			cin >> y >> z >> asdf;
			Jia (y, n, asdf);
			Jia (z + 1, n, -asdf);
		}
		else {
			LL y;
			cin >> y;
			cout << HE (y) << endl;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值