Cod sursa(job #2098431)

Utilizator sandupetrascoPetrasco Sandu sandupetrasco Data 2 ianuarie 2018 19:57:51
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.96 kb
#include <bits/stdc++.h>

#define pb push_back 
#define x first 
#define y second 
#define MOD 1000000007

using namespace std;
typedef long long ll;
typedef pair< int , int > PII;
const int dirx[] = {-2,-1,1,2, 1, -1};
const int diry[] = {0,1,1,0, -1, -1};
inline void debugMode() {
    #ifndef ONLINE_JUDGE
    freopen("input.in", "r", stdin);
    freopen("output.out", "w", stdout);
    #endif
}

struct my{
	int val;
	int x;
	int y;
};

int n, m, A[1 << 15], RMQ[17][1 << 17], F[1 << 15], H[1 << 15], cnt = 0, HB[1 << 15];
vector < int > V[1 << 15], E;
vector < my > R;
bool v[1 << 15];

void Normalize(int x){
	queue < int > Q;
	Q.push(x);
	while (Q.size()){
		int node = Q.front(); Q.pop();
		H[++cnt] = node;
		HB[node] = cnt;
		for (auto it : V[node]){
			Q.push(it);
		}
	}
}

void make_Euler(int x, int fath){
	E.pb(x);
	for (auto it : V[H[x]]){
		if (HB[it] != fath){
			make_Euler(HB[it], x);
			E.pb(x);
		}
	}
}

int main(){
	debugMode();
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) cin >> A[i];

	for (int i = 1, x, y; i < n; i++){
		cin >> x >> y;
		V[x].pb(y);
		v[y] = 1;
	}
	
	int root = 1;
	for (int i = 1; i <= n; i++)
		if (!v[i]) root = i;

	Normalize(root);

	make_Euler(1, 1);
	int n = E.size();

	for (int i = 1; i <= n; i++){
		RMQ[0][i] = E[i - 1];
		if (!F[E[i - 1]]) F[E[i - 1]] = i; 
	}

	for (int i = 1; (1 << i) <= n; i++){
		for (int j = 1; j + (1 << (i - 1)) <= n; j++){
			RMQ[i][j] = min(RMQ[i - 1][j], RMQ[i - 1][j + (1 << (i - 1))]);
		}
	}

	for (int i = 1, xx, yy, x, y; i <= m; i++){
		cin >> xx >> yy;
		x = F[HB[xx]]; y = F[HB[yy]];
		if (x > y) swap(x, y);
		int diff = (y - x + 1);
		int k = log2(diff);
		int rs = min(RMQ[k][x], RMQ[k][y - (1 << k) + 1]);
		R.pb({A[H[rs]], xx, yy});
	}

	sort(R.begin(), R.end(), [&](my a, my b){return (a.val > b.val || (a.val == b.val && a.x < b.x) || (a.val == b.val && a.x == b.x && a.y < b.y));});

	cout << R[0].val << " " << R[0].x << " " << R[0].y;
	
	return 0;
}