Cod sursa(job #2941304)

Utilizator IanisBelu Ianis Ianis Data 17 noiembrie 2022 16:57:42
Problema Radiatie Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>

using namespace std;

#ifdef LOCAL
ifstream fin("input.txt");
#define fout cout
#else
ifstream fin("radiatie.in");
ofstream fout("radiatie.out");
#endif

const int NMAX = 15005;

struct Edge {
	int x, y, c;
};

int n, m, k;
Edge e[2 * NMAX];
int r[NMAX];
vector<pair<int, int>> tree[NMAX];
bool viz[NMAX];
int parent[NMAX], parent_dist[NMAX];
int depth[NMAX];

bool cmp(const Edge &a, const Edge &b) {
	return a.c < b.c;
}

int root(int x) {
	if (r[x] == x)
		return x;
	return r[x] = root(r[x]);
}

bool merge(const Edge &e) {
	int rx = root(e.x);
	int ry = root(e.y);
	if (rx == ry)
		return false;
	r[rx] = ry;
	return true;
}

void dsu() {
	for (int i = 1; i <= n; i++)
		r[i] = i;
	sort(e + 1,  e + m + 1, cmp);
	for (int i = 1; i <= m; i++) {
		if (merge(e[i])) {
			tree[e[i].x].push_back({e[i].y, e[i].c});
			tree[e[i].y].push_back({e[i].x, e[i].c});
		}
	}
}

void dfs(int x) {
	viz[x] = true;
	for (auto &v : tree[x]) {
		int u = v.first;
		int c = v.second;
		if (!viz[u]) {
			depth[u] = depth[x] + 1;
			parent[u] = x;
			parent_dist[u] = c;
			dfs(u);
		}
	}
}

int solve(int a, int b) {
	if (a == b)
		return 0;
	if (depth[a] < depth[b])
		return max(parent_dist[b], solve(a, parent[b]));
	if (depth[a] > depth[b])
		return max(parent_dist[a], solve(parent[a], b));
	return max(max(parent_dist[a], parent_dist[b]), solve(parent[a], parent[b]));
}

int32_t main() {
	fin >> n >> m >> k;
	for (int i = 1; i <= m; i++)
		fin >> e[i].x >> e[i].y >> e[i].c;
	dsu();
	dfs(1);
	while (k--) {
		int a, b;
		fin >> a >> b;
		fout << solve(a, b) << '\n';
	}
	return 0;
}