Cod sursa(job #1484426)

Utilizator howsiweiHow Si Wei howsiwei Data 11 septembrie 2015 10:28:27
Problema Arbori de intervale Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#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;
		while (t[idx] != val && idx >= 1) {
			t[idx] = val;
			val = max(t[idx], t[idx^1]);
			idx /= 2;
		}
	}
	int getmax(int lo, int hi) {
		lo += n;
		hi += n;
		int ret = 0;
		while (lo < hi) {
			if (lo%2 == 0) {
				lo /= 2;
			}
			else {
				ret = max(ret, t[lo]);
				lo = lo/2+1;
			}
			if (hi%2 == 1) {
				hi /= 2;
			}
			else {
				ret = max(ret, t[hi]);
				hi = hi/2-1;
			}
		}
		if (lo == hi) {
			ret = max(ret, t[lo]);
		}
		return ret;
	}
};

int main() {
	freopen("arbint.in", "r", stdin);
	freopen("arbint.out", "w", stdout);
	ios::sync_with_stdio(false);
	int n, m;
	cin >> n >> m;
	vector<int> a(n);
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	SegTree seg(a);
	for (int i = 0; i < m; i++) {
		int op;
		cin >> op;
		if (op == 0) {
			int lo, hi;
			cin >> lo >> hi;
			lo--, hi--;
			cout << seg.getmax(lo, hi) << '\n';
		}
		else {
			int idx, val;
			cin >> idx >> val;
			idx--;
			seg.update(idx, val);
		}
	}
	return 0;
}