Cod sursa(job #2371357)

Utilizator EdyOnuEdy Onu EdyOnu Data 6 martie 2019 17:19:12
Problema Datorii Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.45 kb
// datorii.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

//#include "pch.h"
#include <iostream>

#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <cstdio>
#include <exception>

using std::cout;
using std::for_each;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::runtime_error;

template <typename T> class FenwickTree {
public:

	explicit FenwickTree(vector<T>& elements)
		: elements{ elements } {

		__build();
	}

	T prefixSum(int position) {

		T sum = 0;
		for (int start = position; start > 0; start = getParent(start)) {
			sum += tree[start];
		}

		return sum;
	}

	T intervalSum(int first, int second) {
		return prefixSum(second) - prefixSum(first) + elements[first - 1];
	}

	void update(int position, const T& value) {

		for (int next = position; next < static_cast<int>(tree.size()); next = getNext(next)) {
			tree[next] += value;
		}

		elements[position - 1] += value;
	}

private:

	void __build() {
		tree.resize(elements.size() + 1);

		for (int i = 1; i < static_cast<int>(tree.size()); ++i) {
			__propagateToNext(i);
		}
	}

	void __propagateToNext(int i) {
		const T& val = elements[i - 1];

		for (int next = i; next < static_cast<int>(tree.size()); next = getNext(next)) {
			tree[next] += val;
		}
	}

	int getNext(int x) {
		return	x + ((~x + 1) & x);
	}

	int getParent(int x) {
		return x - ((~x + 1) & x);
	}

	vector<T>& elements;
	vector<T> tree;
};


void answer(FenwickTree<int>& bit, int M, FILE* fin, FILE* fout) {

	while (M-- > 0) {

		int type, a, b;
		if (fscanf(fin, "%d %d %d",&type, &a, &b) < 0) {
			throw runtime_error("Cannot read line!");
		}

		if (type == 1) {

			if (fprintf(fout, "%d\n", bit.intervalSum(a, b)) < 0) {
				throw runtime_error("Cannot write value!");
			}

			continue;
		}

		bit.update(a, -b);
	}

}

void solve() {

	int N, M;

	FILE* fin = fopen("datorii.in", "r");
	FILE* fout = fopen("datorii.out", "w");

	if (fscanf(fin, "%d %d", &N, &M) < 0) {
		throw runtime_error("Cannot read N and M!");
	}

	vector<int> vect;
	int x;
	while(N-- > 0) {
		if (fscanf(fin, "%d", &x) < 0) {
			throw runtime_error("Cannot read X!");
		}
		vect.push_back(x);
	}

	FenwickTree<int> bit{ vect };

	answer(
		bit,
		M,
		fin,
		fout
	);

	fclose(fin), fclose(fout);
}


int main(){
	solve();
}