Cod sursa(job #2902163)

Utilizator stefanliciuLiciu Vasile-Stefan stefanliciu Data 15 mai 2022 19:17:42
Problema Datorii Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.47 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("datorii.in");
ofstream fout("datorii.out");
const int  NMAX = 15001;
int v[4 * NMAX];
void build_segm_tree(int arr[], int nod, int L, int R)
{
	if (L == R)
	{
		v[nod] = arr[L - 1];
	}
	else
	{
      build_segm_tree(arr, 2 * nod, L, (L + R) / 2);
	  build_segm_tree(arr, 2 * nod + 1, (L + R) / 2 + 1, R);
	  v[nod] = v[2 * nod] + v[2 * nod + 1];
	}
}

void update(int nod, int L, int R, int poz, int val)
{
	if (poz < L || poz > R) return;

	if (L == R) { v[nod] -= val; return; }
	if (poz <= (L + R) / 2)
		update(2 * nod, L, (L + R) / 2, poz, val);
	else
		update(2 * nod + 1, (L + R) / 2 + 1, R, poz, val);
	v[nod] = v[nod * 2] + v[nod * 2 + 1];
}

int datorie(int nod, int L, int R, int i, int j)
{
	if (j < L || i > R) return 0;
	if (i <= L && R <= j) return v[nod];
	else return datorie(2 * nod, L, (L + R) / 2, i, j) + datorie(2 * nod + 1, (L + R) / 2 + 1, R, i, j);
}

int main()
{
	int N, M, tip_operatie, poz1, poz2, poz, val;
	int datorii[NMAX];
	fin >> N >> M;
	for (int i = 0; i < N; ++i)
	{
		fin >> datorii[i];
	}
	build_segm_tree(datorii, 1, 1, N);
	for (int i = 0; i < M; ++i)
	{
		fin >> tip_operatie;
		switch (tip_operatie)
		{
		 case 0:
		 {
			 fin >> poz >> val;
			 update(1, 1, N, poz, val);
		 }
		 break;
		 case 1:
		 {
			 fin >> poz1 >> poz2;
			 fout << datorie(1, 1, N, poz1, poz2) << '\n';
		 }
		 break;
		}
	}
	return 0;
}