Boj2042_구간 합 구하기

Published: by Creative Commons Licence

boj2042_구간 합 구하기

  • 펜윅트리를 이용해 문제 해결!
#include<iostream>
#include<vector>
using namespace std;

typedef long long ll;

ll sum(vector<ll> &tree, int i) {
	ll ans = 0;
	while (i > 0) {
		ans += tree[i];
		i -= (i&-i);
	}
	return ans;
}

void update(vector<ll> &tree, int i, ll diff) {
	while(i < tree.size()) {
		tree[i] += diff;
		i += (i&-i);
	}
}

int main() {
	int n, m, k;
	scanf("%d %d %d", &n, &m, &k);
	vector<ll> arr(n + 1);
	vector<ll> tree(n + 1);

	for (int i = 1; i <= n; i++) {
		scanf("%lld", &arr[i]);
		update(tree, i, arr[i]);
	}
	m += k;
	while (m--) {
		int num;
		scanf("%d", &num);
		if (num == 1) {
			int idx;
			ll val;
			scanf("%d %lld", &idx, &val);
			ll diff = val - arr[idx];
			arr[idx] = val;
			update(tree, idx, diff);
		}
		else if (num == 2) {
			int l, r;
			scanf("%d %d", &l, &r);
			printf("%lld\n", sum(tree, r) - sum(tree, l - 1));
		}
	}
	return 0;
}