Pagini recente » Cod sursa (job #295217) | Cod sursa (job #2170951) | Cod sursa (job #581660) | Cod sursa (job #2112717) | Cod sursa (job #2896845)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 15000;
const int MMAX = 50000;
const int LOGMAX = 14;
struct edge {
int x;
int y;
int c;
} edges[MMAX + 1];
int depth[NMAX + 1];
int cost[LOGMAX][NMAX + 1];
int parent[LOGMAX][NMAX + 1];
vector <edge> mst[NMAX + 1];
bool cmp( edge a, edge b ) {
return a.c < b.c;
}
int father[NMAX + 1];
int root( int x ) {
if ( x == father[x] ) return x;
return ( father[x] = root( father[x] ) );
}
bool unire( int a, int b ) {
int ra = root( a ), rb = root( b );
if ( ra == rb ) return 0;
father[ra] = rb;
return 1;
}
void build_mst( int n, int m ) {
for ( int i = 1; i <= n; i ++ ) father[i] = i;
sort( edges, edges + m, cmp );
for ( int i = 0; i < m; i ++ ) {
if ( unire( edges[i].x, edges[i].y ) ) {
mst[edges[i].x].push_back( edges[i] );
swap( edges[i].x, edges[i].y );
mst[edges[i].x].push_back( edges[i] );
}
}
}
void dfs( int node, int p, int cp, int d ) {
depth[node] = d;
if ( d >= 1 ) {
cost[0][node] = cp;
parent[0][node] = p;
for ( int i = 1; ( 1 << i ) <= d; i ++ ) {
cost[i][node] = max( cost[i - 1][node], cost[i - 1][parent[i - 1][node]] );
parent[i][node] = parent[i - 1][parent[i - 1][node]];
}
}
for ( auto it : mst[node] ) {
if ( it.y != p )
dfs( it.y, node, it.c, d + 1 );
}
}
int query( int a, int b ) {
int ans = 0;
for ( int i = LOGMAX - 1; i >= 0; i -- ) {
if ( depth[a] <= depth[b] - ( 1 << i ) ) {
ans = max( ans, cost[i][b] );
b = parent[i][b];
} else if ( depth[b] <= depth[a] - ( 1 << i ) ) {
ans = max( ans, cost[i][a] );
a = parent[i][a];
}
}
for ( int i = LOGMAX - 1; i >= 0; i -- ) {
if ( ( 1 << i ) > depth[a] ) continue;
if ( parent[i][a] != parent[i][b] ) {
ans = max( ans, max( cost[i][a], cost[i][b] ) );
a = parent[i][a];
b = parent[i][b];
}
}
return ans;
}
int main() {
ifstream fin( "radiatie.in" );
ofstream fout( "radiatie.out" );
int n, m, q;
fin >> n >> m >> q;
for ( int i = 0; i < m; i ++ ) {
fin >> edges[i].x >> edges[i].y >> edges[i].c;
}
build_mst( n, m );
dfs( 1, -1, 0, 0 );
while ( q-- ) {
int a, b;
fin >> a >> b;
fout << query( a, b ) << '\n';
}
return 0;
}