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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133 | #include <bits/stdc++.h>
using namespace std;
const int N = 50010;
const int INF = 1e9;
const int LOG = 25;
struct Edge
{
int s, t, w;
Edge(){};
Edge(int _s, int _t, int _w) : s(_s), t(_t), w(_w) {}
bool operator<(const Edge &rhs) const { return w < rhs.w; }
};
int n, m, djs[N], depth[N], par[N][LOG], maxcost[N][LOG];
vector<Edge> edges;
vector<int> G[N];
int query(int x) { return (x == djs[x] ? x : djs[x] = query(djs[x])); }
void init()
{
memset(par, -1, sizeof(par));
memset(maxcost, -1, sizeof(maxcost));
edges.clear();
for (int i = 0; i < N; i++)
{
djs[i] = i;
G[i].clear();
}
}
void MST()
{
for (int i = 0; i < m; i++)
{
int fa = query(edges[i].s), fb = query(edges[i].t);
if (fa != fb)
{
djs[fa] = fb;
G[edges[i].s].push_back(i);
G[edges[i].t].push_back(i);
}
}
}
void dfs(int s, int f)
{
depth[s] = depth[f] + 1;
par[s][0] = f;
for (auto i : G[s])
{
int t = edges[i].s ^ edges[i].t ^ s;
if (t != f)
{
maxcost[t][0] = edges[i].w;
dfs(t, s);
}
}
}
void preprocess()
{
for (int i = 1; i <= LOG; i++)
{
for (int j = 1; j <= n; j++)
{
if (par[j][i - 1] == -1 || par[par[j][i - 1]][i - 1] == -1)
continue;
par[j][i] = par[par[j][i - 1]][i - 1];
maxcost[j][i] =
max(maxcost[j][i - 1], maxcost[par[j][i - 1]][i - 1]);
}
}
}
int solve(int p, int q)
{
if (depth[p] < depth[q])
swap(p, q);
int hibit, ans = -INF;
for (hibit = 1; (1 << hibit) <= depth[p]; ++hibit)
;
for (int i = hibit - 1; i >= 0; i--)
{
if (depth[p] - (1 << i) >= depth[q])
{
ans = max(ans, maxcost[p][i]);
p = par[p][i];
}
}
if (p == q)
{
return ans;
}
for (int i = hibit - 1; i >= 0; i--)
{
if (par[p][i] == -1 || par[p][i] == par[q][i])
continue;
ans = max({ans, maxcost[p][i], maxcost[q][i]});
p = par[p][i];
q = par[q][i];
}
return max({ans, maxcost[p][0], maxcost[q][0]});
}
int main()
{
for (int ti = 0; cin >> n >> m; ++ti)
{
if (ti)
cout << '\n';
init();
for (int i = 0; i < m; i++)
{
int s, t, w;
cin >> s >> t >> w;
edges.emplace_back(s, t, w);
}
sort(edges.begin(), edges.end());
MST();
dfs(1, -1);
preprocess();
int q;
cin >> q;
for (int i = 0; i < q; i++)
{
int x, y;
cin >> x >> y;
cout << solve(x, y) << '\n';
}
}
}
|