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 105 106
   | 
 
 
 
 
 
 
 
 
 
  #include <bits/stdc++.h> using namespace std;
  #define EmiliaMyWife ios::sync_with_stdio(0); cin.tie(NULL);
 
  const int N = 3e4 + 25; struct ed { 	int a, b, c; 	bool operator<(ed x) { return c < x.c; } }; int pa[N], sz[N], dep[N], lca[15][N], mx[15][N]; bool vis[N]; vector<vector<pair<int, int>>> edge;
  int fnd(int x) { return pa[x] == x ? pa[x] : pa[x] = fnd(pa[x]); } bool uni(int a, int b) { 	if((a = fnd(a)) == (b = fnd(b))) 		return false; 	if(sz[a] > sz[b]) 		swap(a, b); 	return sz[b] += sz[a], pa[a] = b, true; } void dfs(int v) { 	vis[v] = 1; 	for(auto [u, c] : edge[v]) { 		if(!vis[u]) { 			dep[u] = dep[v] + 1; 			lca[0][u] = v; 			mx[0][u] = c; 			dfs(u); 		} 	} } int solve(int a, int b) { 	if(fnd(a) != fnd(b)) 		return -1; 	int res = 0; 	if(dep[a] < dep[b]) 		swap(a, b); 	for(int i = 14; ~i; i--) 		if(dep[lca[i][a]] >= dep[b]) 			res = max(res, mx[i][a]), a = lca[i][a]; 	if(a == b) 		return res; 	for(int i = 14; ~i; i--) { 		if(lca[i][a] != lca[i][b]) { 			res = max(res, mx[i][a]); a = lca[i][a]; 			res = max(res, mx[i][b]); b = lca[i][b]; 		} 	} 	return max({res, mx[0][a], mx[0][b]}); }
  signed main() { 	EmiliaMyWife
  	int n, m; 	cin >> n >> m; 	for(int i = 1; i <= n; i++) 		pa[i] = i, sz[i] = 1; 	edge.resize(n + 1); 	vector<ed> edg(m); 	vector<bool> has(m); 	for(int i = 0; i < m; i++) 		cin >> edg[i].a >> edg[i].b >> edg[i].c; 	sort(edg.begin(), edg.end()); 	for(int i = 0; i < m; i++) { 		if(uni(edg[i].a, edg[i].b)) 			has[i] = 1; 	} 	for(int i = 0; i < m; i++) { 		if(has[i]) { 			edge[edg[i].a].push_back({edg[i].b, edg[i].c}); 			edge[edg[i].b].push_back({edg[i].a, edg[i].c}); 		} 	} 	for(int i = 1; i <= n; i++) { 		if(!vis[i]) 			dfs(i); 	} 	for(int i = 1; i < 15; i++) 		for(int j = 1; j <= n; j++) 			lca[i][j] = lca[i - 1][lca[i - 1][j]], mx[i][j] = max(mx[i - 1][j], mx[i - 1][lca[i - 1][j]]); 	int q; 	cin >> q; 	while(q--) { 		int a, b; 		cin >> a >> b; 		cout << solve(a, b) << '\n'; 	}
  	return 0; }
 
 
  |