Cod sursa(job #1197199)

Utilizator howsiweiHow Si Wei howsiwei Data 11 iunie 2014 07:07:12
Problema Arbori de intervale Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;

class SegTree
{
	int n;
	vector<int> t;
public:
	SegTree(const vector<int> & a)
	{
		n = a.size();
		t.resize(2*n);
		for (int i = 0; i < n; ++i) {
			t[n+i] = a[i];
		}
		for (int i = n-1; i >= 1; --i) {
			t[i] = max(t[2*i], t[2*i+1]);
		}
	}
	void update(int idx, int val)
	{
		idx += n;
		t[idx] = val;
		while (idx > 1) {
			int tmp = max(t[idx], t[idx^1]);
			idx /= 2;
			if (t[idx] == tmp) {
				break;
			}
			else {
				t[idx] = tmp;
			}
		}
	}
	int getmax(int lo, int hi)
	{
		lo += n;
		hi += n;
		int res = 0;
		bool lohaschild = false;
		bool hihaschild = false;
		while (lo <= hi) {
			if (lo%2 == 0) {
				lo /= 2;
				lohaschild = true;
			}
			else {
				res = max(res, t[lo]);
				lo = lo/2+1;
				lohaschild = false;
			}
			if (hi%2 == 1) {
				hi /= 2;
				hihaschild = true;
			}
			else {
				res = max(res, t[hi]);
				hi = hi/2-1;
				hihaschild = false;
			}
		}
		if (lohaschild) {
			res = max(res, t[2*lo]);
		}
		if (hihaschild) {
			res = max(res, t[2*hi+1]);
		}
		return res;
	}
};

int main() {
	ifstream fin("arbint.in");
	ofstream fout("arbint.out");
	int n, m;
	fin >> n >> m;
	vector<int> a(n);
	for (int i = 0; i < n; ++i) {
		fin >> a[i];
	}
	SegTree seg(a);
	for (int i = 0; i < m; ++i) {
		int op;
		fin >> op;
		if (op == 0) {
			int lo, hi;
			fin >> lo >> hi;
			fout << seg.getmax(--lo, --hi) << '\n';
		}
		else {
			int idx, val;
			fin >> idx >> val;
			seg.update(--idx, val);
		}
	}
	return 0;
}