티스토리 뷰

백준

백준 소스코드 [C++] 2268 수들의 합

Hani_Levenshtein 2020. 11. 11. 07:19

www.acmicpc.net/problem/2268

 

2268번: 수들의 합

첫째 줄에는 N(1≤N≤1,000,000), M(1≤M≤1,000,000)이 주어진다. M은 수행한 명령의 개수이며 다음 M개의 줄에는 수행한 순서대로 함수의 목록이 주어진다. 첫 번째 숫자는 어느 함수를 사용했는지를

www.acmicpc.net

백준 소스코드 [C++] 2268 수들의 합

#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
#include <vector>
#include <math.h>
#include <stack>
#include <bitset>
#include <string>
typedef long long ll;
using namespace std;
int n, m;
vector<ll> tree, arr;
void input() {
	cin >> n >> m;
	arr.resize(n,0);
	tree.resize(4 * n);
}

ll init(int i, int S, int E) {
	if (S == E) return tree[i] = arr[S];
	else return tree[i] = init(2 * i, S, (S + E) / 2)
		+ init(2 * i + 1, (S + E) / 2 + 1, E);
}

void update(int i, int S, int E, int idx, ll gap) {
	if (idx < S || E < idx) return;
	tree[i] += gap;
	if (S != E) {
		update(2 * i, S, (S + E) / 2, idx, gap);
		update(2 * i + 1, (S + E) / 2 + 1, E, idx, gap);
	}
}
ll query(int i, int S, int E, int L, int R) {
	if (E < L || R < S) return 0;
	if (L <= S && E <= R) return tree[i];
	return query(2 * i, S, (S + E) / 2, L, R)
		+ query(2 * i + 1, (S + E) / 2 + 1, E, L, R);
}

void output() {
	int a, b, c;
	for (int i = 0;i < m;i++) {
		cin >> a >> b >> c;
		if (a == 1) {
			update(1, 0, n - 1, b - 1, c - arr[b - 1]);
			arr[b - 1] = c;
		}
		else {
			if (b > c) swap(b, c);
			cout << query(1, 0, n - 1, b - 1, c - 1) << '\n';
		}
	}
}
int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	input();
	init(1, 0, n - 1);
	output();
	return 0;
}
댓글