Pagini recente » Cod sursa (job #962310) | Cod sursa (job #544514) | Cod sursa (job #2185185) | tsaojisim | Cod sursa (job #2578782)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("radiatie.in");
ofstream fout("radiatie.out");
struct elem
{
int node, dest, cost;
}v[30005];
vector <int> g[15005];
int n, m, q, dads[15005], maxi[15005], rang[15005], poz, nivel[15005];
inline bool cmp(const elem &a, const elem &b)
{
return a.cost < b.cost;
}
int root(int x)
{
int nodinit = x, father = dads[x];
while(x != father)
{
x = dads[x];
father = dads[x];
}
//dads[nodinit] = father;
return x;
}
void join(int x, int y, int i)
{
x = root(x);
y = root(y);
if(rang[x] < rang[y])
{
dads[x] = y;
poz = y;
g[y].push_back(x);
maxi[x] = v[i].cost;
}
else
if(rang[x] > rang[y])
{
dads[y] = x;
poz = x;
g[x].push_back(y);
maxi[y] = v[i].cost;
}
else
{
dads[x] = y;
poz = y;
g[y].push_back(x);
maxi[x] = v[i].cost;
rang[y] ++;
}
}
void kruskal()
{
for(int i = 1; i <= m; i++)
if(root(v[i].node) != root (v[i].dest))
join(v[i].node, v[i].dest, i);
}
void dfs(int node)
{
for(int i = 0; i < g[node].size(); i++)
{
int vecin = g[node][i];
nivel[vecin] = nivel[node] + 1;
dfs(vecin);
}
}
int lca(int x, int y)
{
int ans = 0;
while(nivel[x] > nivel[y])
{
ans = max(ans, maxi[x]);
x = dads[x];
}
while(x != y)
{
ans = max(ans, max(maxi[x], maxi[y]));
x = dads[x];
y = dads[y];
}
return ans;
}
int main()
{
fin >> n >> m >> q;
for(int i = 1; i <= m; i++)
fin >> v[i].node >> v[i].dest >> v[i].cost;
for(int i = 1; i <= n; i++)
dads[i] = i;
sort(v + 1, v + m + 1, cmp);
kruskal();
dfs(poz);
for(int i = 1; i <= q; i++)
{
int x, y;
fin >> x >> y;
if(nivel[x] < nivel[y])
fout << lca(y, x) << '\n';
else
fout << lca(x, y) << '\n';
}
return 0;
}