Cod sursa(job #1809050)

Utilizator StefansebiStefan Sebastian Stefansebi Data 18 noiembrie 2016 16:51:20
Problema Datorii Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.53 kb
#include<fstream>
using namespace std;
ifstream fin("datorii.in");
ofstream fout("datorii.out");

int arb[40000];

/*
updates the position, with the given value
n - the current node, (l, r) the corresponding interval 
calculates the sum
*/
void update(int n, int l, int r, int pos, int value) {
	if (l == r) {
		arb[n] = value;
		return;
	}
	int m = (l + r) / 2;
	if (pos <= m) {
		update(n * 2, l, m, pos, value);
	}
	if (m < pos) {
		update(n * 2 + 1, m + 1, r, pos, value);
	}
	arb[n] = arb[n * 2] + arb[n * 2 + 1];
}

/*
achitare suma 
*/
void achitare(int n, int l, int r, int pos, int value) {
	if (l == r) {
		arb[n] -= value;
		return;
	}
	int m = (l + r) / 2;
	if (pos <= m) {
		achitare(n * 2, l, m, pos, value);
	}
	if (m < pos) {
		achitare(n * 2 + 1, m + 1, r, pos, value);
	}
	arb[n] = arb[n * 2] + arb[n * 2 + 1];
}

/*
queries the interval (ql, qr)
calculates the sum
*/
void query(int n, int l, int r, int ql, int qr, int& sum) {
	if (ql <= l && r <= qr) {
		sum = sum + arb[n];
		return;
	}
	int m = (l + r) / 2;
	if (ql <= m) {
		query(n * 2, l, m, ql, qr, sum);
	}
	if (m < qr) {
		query(n * 2 + 1, m + 1, r, ql, qr, sum);
	}
}

int main() {
	int n, m;
	fin >> n >> m;
	for (int i = 1; i <= n; i++) {
		int elem;
		fin >> elem;
		update(1, 1, n, i, elem);
	}
	for (int i = 1; i <= m; i++) {
		int c, a, b;
		fin >> c >> a >> b;
		if (c == 0) {
			achitare(1, 1, n, a, b);
		}
		else {
			int suma = 0;
			query(1, 1, n, a, b, suma);
			fout << suma << "\n";
		}
	}
}