Cod sursa(job #2886116)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 7 aprilie 2022 00:13:42
Problema Heavy Path Decomposition Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.78 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define dbg(x) cout << #x <<": " << x << "\n";
#define sz(x) ((int)x.size())

using ll = long long;

const string fn = "heavypath";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

const int mxn = 100005;

int n, qs;
int posac;


int pos[mxn];
int head[mxn];
int heavy[mxn];
int depth[mxn];
int value[mxn];
int parent[mxn];

int subarbSz[mxn];

vector<int> g[mxn];

int a[4 * mxn];
int valAtPos[mxn];
void build(int nod, int st, int dr) {
	if (st == dr) {
		a[nod] = valAtPos[st];
	}
	else {
		int mid = (st + dr) >> 1;
		build(nod << 1, st, mid);
		build(nod << 1 | 1, mid + 1, dr);
		a[nod] = max(a[nod << 1], a[nod << 1 | 1]);
	}

}

void upd(int nod, int st, int dr, int p, int val) {

	if (st == dr) {
		a[nod] = val;
	}
	else {
		int mid = (st + dr) >> 1;
		if (p <= mid)
			upd(nod << 1, st, mid, p, val);
		else
			upd(nod << 1 | 1, mid + 1, dr, p, val);
		a[nod] = max(a[nod << 1], a[nod << 1 | 1]);
	}

}

int qry(int nod, int st, int dr, int x, int y) {
	if (st > dr || st > y || dr < x)
		return -1;
	if (st >= x && dr <= y)
		return a[nod];
	int mid = (st + dr) >> 1;
	int q1 = qry(nod << 1, st, mid, x, y);
	int q2 = qry(nod << 1 | 1, mid + 1, dr, x, y);
	return max(q1, q2);
}

int aintQry(int x, int y) {
	return qry(1, 1, n, x, y);
}



void dfs(int nod) {

	int nodsz = 1;
	int mxSonSize = 0;
	for (int i : g[nod]) {
		if (i != parent[nod]) {
			parent[i] = nod;
			depth[i] = depth[nod] + 1;

			dfs(i);


			int acSonSize = subarbSz[i];
			nodsz += acSonSize;
			if (acSonSize > mxSonSize) {
				mxSonSize = acSonSize;
				heavy[nod] = i;
			}
		}
	}
	subarbSz[nod] = nodsz;
}

void decompose(int nod, int best) {
	head[nod] = best;
	pos[nod] = ++posac;
	if (heavy[nod] != -1)
		decompose(heavy[nod], best);
	for (int i : g[nod]) {
		if (i != parent[nod] && i != heavy[nod])
			decompose(i, i);
	}
}

int qryDecomp(int x, int y) {
	int ans = value[x];
	while (head[x] != head[y]) {
		if (depth[head[x]] > depth[head[y]])
			swap(x, y);
		ans = max(ans, aintQry(pos[head[y]], pos[y]));
		y = parent[head[y]];
	}
	if (depth[x] > depth[y])
		swap(x, y);
	ans = max(ans, aintQry(pos[x], pos[y]));
	return ans;
}

int main() {

	fin >> n >> qs;

	for (int i = 1; i <= n; ++i) {
		fin >> value[i];
		heavy[i] = -1;
	}
	for (int i = 1; i < n; ++i) {
		int x, y;
		fin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}
	parent[1] = 1;
	dfs(1);
	decompose(1, 1);

	for (int i = 1; i <= n; ++i)
		valAtPos[pos[i]] = value[i];
	build(1, 1, n);

	while (qs--) {
		int op, x, y;
		fin >> op >> x >> y;
		if (op == 0) {
			upd(1, 1, n, pos[x], y);
		}
		else {
			fout << qryDecomp(x, y) << '\n';
		}
	}

	return 0;
}