P2245 星际导航

模版题

代码
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


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
#define mk make_pair
const int N = 1e6 + 10;
const int mod = 1e9 + 7;

struct Edge
{
int u, v, w;

bool operator<(const Edge &b) const
{
return w < b.w;
}
};
namespace KruskalTree
{
int fa[N];
int f[N][20];
int dep[N], a[N];
vector<int> g[N];
int find(int x)
{
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void addedge(int u, int v)
{
g[u].push_back(v);
g[v].push_back(u);
}
void dfs1(int x, int ff)
{
f[x][0] = ff;
dep[x] = dep[ff] + 1;
for (int i = 1; i <= 18; i++)
f[x][i] = f[f[x][i - 1]][i - 1];
for (int to : g[x])
{
if (to == ff)
continue;
dfs1(to, x);
}
}
int lca(int u, int v)
{
if (dep[u] < dep[v])
swap(u, v);
for (int i = 18; i >= 0; i--)
{
if (dep[f[u][i]] >= dep[v])
u = f[u][i];
}
if (u == v)
return u;
for (int i = 18; i >= 0; i--)
{
if (f[u][i] != f[v][i])
u = f[u][i], v = f[v][i];
}

return f[u][0];
}
void init(int n, vector<Edge> e)
{
for (int i = 0; i <= n << 1; i++)
fa[i] = i;
int cnt = n;
sort(e.begin(), e.end());
for (Edge now : e)
{
int u = now.u, v = now.v, w = now.w;
int x = find(u), y = find(v);
if (x == y)
continue;
cnt++;
fa[x] = fa[y] = cnt;
addedge(x, cnt);
addedge(y, cnt);
a[cnt] = w;
}

for (int i = cnt; i >= 1; i--)
if (!dep[i])
{

dfs1(i, 0);
}
}

} // namespace KruskalTree

int read()
{
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9')
{
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0', c = getchar();
return x * f;
}

using namespace KruskalTree;
int main()
{
int n = read(), m = read();
vector<Edge> e;
for (int i = 1; i <= m; i++)
{
int u = read(), v = read(), w = read();
e.push_back((Edge){u, v, w});
}
init(n, e);
int q = read();
for (int i = 1; i <= q; i++)
{
int u = read(), v = read();
if (find(u) != find(v))
puts("impossible");
else
printf("%d\n", a[lca(u, v)]);
}
}