1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #include <iostream> #include <cstdio> #include <queue> #include <algorithm> using namespace std; const int N = 400005;
int n, m, Q; struct node{ int x, y, z; }edge[N]; int fa[N];
int Next[N], head[N], ver[N], w[N], tot;
bool cmp(node a, node b){ return a.z < b.z; }
int find(int x){ return fa[x] != x ? fa[x] = find(fa[x]) : x; }
void add(int x, int y, int z){ ver[++tot] = y; w[tot] = z; Next[tot] = head[x]; head[x] = tot; }
void Kruskal(){ sort(edge + 1, edge + m + 1, cmp); for(int i = 1; i <= n; i++) fa[i] = i; for(int i = 1; i <= m; i++){ int fx = find(edge[i].x); int fy = find(edge[i].y); if(fx == fy) continue; fa[fx] = fy; add(edge[i].x, edge[i].y, edge[i].z); add(edge[i].y, edge[i].x, edge[i].z); } }
queue <int> q; int f[50005][25], d[N], mx[50005][25]; void bfs(){ q.push(1); d[1] = 1; while(q.size()){ int x = q.front(); q.pop(); for(int i = head[x]; i; i = Next[i]){ int y = ver[i]; if(d[y]) continue; q.push(y); d[y] = d[x] + 1; f[y][0] = x; mx[y][0] = w[i]; for(int j = 1; j <= 20; j++){ f[y][j] = f[f[y][j-1]][j-1]; mx[y][j] = max(mx[y][j-1], mx[f[y][j-1]][j-1]); } } } }
int lca(int x, int y){ int ans = 0; if(d[x] > d[y]) swap(x, y); for(int i = 20; i >= 0; i--){ if(d[f[y][i]] >= d[x]) { ans = max(ans, mx[y][i]); y = f[y][i]; } } if(x == y) return ans; for(int i = 20; i >= 0; i--){ if(f[x][i] != f[y][i]){ ans = max(ans, mx[x][i]); ans = max(ans, mx[y][i]); x = f[x][i]; y = f[y][i]; } } ans = max(ans, mx[x][0]); ans = max(ans, mx[y][0]); return ans; }
int main(){ scanf("%d%d%d", &n, &m, &Q); for(int i = 1; i <= m; i++){ scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].z); }
Kruskal(); bfs(); for(int i = 1; i <= Q; i++){ int x, y; scanf("%d%d", &x, &y); if(find(x) == find(y)) printf("%d\n", lca(x, y)); else printf("-1\n"); } return 0; }
|