백준 2042 구간 합 구하기

Posted by : at

Category : Solution


Problem2 문제풀이

#include <iostream>
#include <vector>

using namespace std;

int N, M, K, num, cmd, from, to;
int arr[1000001];

void update(vector<long long> &tree, int target, int diff);
long long sum(vector<long long>& tree, int target);

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cin >> N >> M >> K;
	vector<long long> tree(N + 1);
	for (int i = 0; i < N; i++)
	{
		cin >> arr[i];
		update(tree, i+1, arr[i]);
	}
	for (int i = 0; i < M + K; i++)
	{
		cin >> cmd >> from >> to;
		if (cmd == 1)
		{
			long long dist = to - arr[from-1];
			arr[from - 1] = to;
			update(tree, from, dist);
		}
		else
		{
			cout << sum(tree, to) - sum(tree, from - 1) << '\n';
		}
	}
	return 0;
}

void update(vector<long long>& tree, int target, int diff)
{
	while (target < tree.size())
	{
		tree[target] += diff;
		target += (target & -target);
	}
}
long long sum(vector<long long>& tree, int target)
{
	long long ans = 0;
	while (target > 0)
	{
		ans += tree[target];
		target -= (target & -target);
	}
	return ans;
}

About GJ

안녕하세요 방문해주셔서 감사합니다. 혹시 보시면서 궁금하신것 있으시면 https://open.kakao.com/o/sivaz71c로 연락주세용~

Star
Useful Links