Pagini recente » Info Oltenia 2018 Proba pe Echipe Clasele 9 - 10 | Cod sursa (job #828755) | Cod sursa (job #1597060) | Cod sursa (job #2030835) | Cod sursa (job #3290980)
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("radiatie.in");
ofstream fout("radiatie.out");
const int LMAX = 15005;
const int MOD = 1000000007;
int n, father[LMAX], str[20][LMAX], medg[20][LMAX], depth[LMAX];
vector<pair<int, int>> L[LMAX];
bool ok;
struct info {
int x, y, c;
bool operator < (const info &a) {
return c < a.c;
}
};
vector<info> edges;
int find_root(int x) {
if (father[x] < 0) return x;
father[x] = find_root(father[x]);
return father[x];
}
bool unite(int x, int y) {
int rx, ry;
rx = find_root(x);
ry = find_root(y);
if (rx == ry) return 0;
if (father[rx] < father[ry]) swap(rx, ry);
father[ry] += father[rx];
father[rx] = ry;
if (father[ry] == -n) ok = 1;
return 1;
}
void init() {
for (int i = 1; i <= n; i++) father[i] = -1;
}
void dfs(int node, int father, int cost) {
str[0][node] = father;
medg[0][node] = cost;
for (auto vec : L[node]) {
if (vec.first != father) {
depth[vec.first] = depth[node] + 1;
dfs(vec.first, node, vec.second);
}
}
}
void build_lca() {
int i, j;
for (i = 1; i < 20; i++) {
for (j = 1; j <= n; j++) {
str[i][j] = str[i - 1][str[i - 1][j]];
medg[i][j] = max(medg[i - 1][j], medg[i - 1][str[i - 1][j]]);
}
}
}
int lca(int x, int y) {
if (depth[x] < depth[y]) swap(x, y);
int p = depth[x] - depth[y], i, maxi = 0;
for (i = 0; (1<<i) <= p; i++) {
if (p&(1<<i)) {
maxi = max(maxi, medg[i][x]);
x = str[i][x];
}
}
//x si y sunt pe acelasi nivel
while (x != y) {
p = 19;
while (p && str[p][x] == str[p][y]) {
p--;
}
maxi = max(maxi, max(medg[p][x], medg[p][y]));
x = str[p][x];
y = str[p][y];
}
// fout<<x<<endl;
return maxi;
}
int main() {
int m, q, i;
fin>>n>>m>>q;
for (i = 0; i < m; i++) {
int x, y, c;
fin>>x>>y>>c;
edges.push_back({x, y, c});
}
sort(edges.begin(), edges.end());
init();
i = 0;
while (i < m && !ok) {
if (unite(edges[i].x, edges[i].y)) {
L[edges[i].x].push_back({edges[i].y, edges[i].c});
L[edges[i].y].push_back({edges[i].x, edges[i].c});
}
i++;
}
dfs(1, 0, 0);
build_lca();
int x, y;
while (q--) {
fin>>x>>y;
fout<<lca(x, y)<<"\n";
}
fin.close();
fout.close();
return 0;
}