数据结构 - 树状数组

数据结构 - 树状数组

模板1 题目链接:https://www.luogu.org/problem/P3374

模板2 题目链接:https://www.luogu.org/problem/P3368

模板1 单点修改、区间查询代码:

#include <bits/stdc++.h>

using namespace std;

const int N = 5e5 + 10;	

int n, m, tree[N];

void update(int x, int val) {
	for (int i = x; i <= n; i += i & (-i)) {
		tree[i] += val;
	}
}

int query(int x) {
	int ret = 0;
	for (int i = x; i; i -= i & (-i)) {
		ret += tree[i];
	}
	return ret;
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i ++ ) {
		int x;
		scanf("%d", &x);
		update(i, x);
	}
	for (int i = 1; i <= m; i ++ ) {
		int opt, a, b;
		scanf("%d%d%d", &opt, &a, &b);
		if (opt == 1) {
			update(a, b);
		}
		else {
			int ans = query(b) - query(a - 1);
			printf("%d\n", ans);
		}
	}	
	return 0;
}

模板2 区间修改、单点查询代码:

#include <bits/stdc++.h>

using namespace std;

const int N = 5e5 + 10;	

int n, m, tree[N], num[N];

void update(int x, int val) {
	for (int i = x; i <= n; i += i & (-i)) {
		tree[i] += val;
	}
}

int query(int x) {
	int ret = 0;
	for (int i = x; i; i -= i & (-i)) {
		ret += tree[i];
	}
	return ret;
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i ++ ) {
		scanf("%d", &num[i]);
		update(i, num[i] - num[i - 1]);
	}
	for (int i = 1; i <= m; i ++ ) {
		int opt, a, b, c;
		scanf("%d", &opt);
		if (opt == 1) {
			scanf("%d%d%d", &a, &b, &c);
			update(a, c);
			update(b + 1, -c);
		}
		else {
			scanf("%d", &a);
			printf("%d\n", query(a));
		}
	}	
	return 0;
}
posted @ 2019-11-15 01:22  筱柒_Littleseven  阅读(85)  评论(0编辑  收藏  举报