Pagini recente » Cod sursa (job #1197483) | Cod sursa (job #1705625) | Cod sursa (job #935760) | Cod sursa (job #2311054) | Cod sursa (job #2038292)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 15e3;
const int MAXLOG = 15;
vector <pair <int, int>> g[MAXN + 1];
vector <pair <int, pair <int, int>>> edg;
int boss[MAXN + 1], dp[MAXLOG][MAXN + 1], anc[MAXLOG][MAXN + 1], lev[MAXN + 1] = {0, 1};
int what_boss(int node) {
if (boss[node] != node)
boss[node] = what_boss(boss[node]);
return boss[node];
}
void dfs(int node) {
for (auto it : g[node])
if (lev[it.first] == 0) {
anc[0][it.first] = node;
lev[it.first] = lev[node] + 1;
dp[0][it.first] = it.second;
dfs(it.first);
}
}
int lca_lev(int x, int y) {
if (lev[x] < lev[y])
swap(x, y);
for (int i = MAXLOG - 1; i >= 0; --i)
if (lev[anc[i][x]] >= lev[y])
x = anc[i][x];
if (x == y)
return lev[x] + 1;
for (int i = MAXLOG - 1; i >= 0; --i)
if (anc[i][x] != anc[i][y]) {
x = anc[i][x];
y = anc[i][y];
}
return lev[x];
}
int max_on_path(int node, int lvl) {
if (lvl > lev[node])
return 0;
int val = 0;
for (int i = MAXLOG - 1; i >= 0; --i)
if (lev[anc[i][node]] >= lvl) {
val = max(val, dp[i][node]);
node = anc[i][node];
}
return max(val, dp[0][node]);
}
int main()
{
int n, m, k;
ifstream fin("radiatie.in");
fin >> n >> m >> k;
edg.resize(m);
for (int i = 0; i < m; ++i) {
int a, b, c;
fin >> a >> b >> c;
edg[i] = {c, {a, b}};
}
for (int i = 1; i <= n; ++i)
boss[i] = i;
sort(edg.begin(), edg.end());
for (auto it : edg)
if (what_boss(it.second.first) != what_boss(it.second.second)) {
boss[what_boss(it.second.first)] = what_boss(it.second.second);
g[it.second.first].push_back({it.second.second, it.first});
g[it.second.second].push_back({it.second.first, it.first});
}
dfs(1);
for (int i = 1; i < MAXLOG; ++i)
for (int node = 1; node <= n; ++node) {
anc[i][node] = anc[i - 1][anc[i - 1][node]];
dp[i][node] = max(dp[i - 1][node], dp[i - 1][anc[i - 1][node]]);
}
ofstream fout("radiatie.out");
for (int i = 0; i < k; ++i) {
int a, b, lv;
fin >> a >> b;
lv = lca_lev(a, b);
fout << max(max_on_path(a, lv), max_on_path(b, lv)) << '\n';
}
fin.close();
fout.close();
return 0;
}