LCA+Kruskal 爆炸力qwq,我估计是LCA的DFS预处理出锅了qwq,但是没找出来哪里有问题qwq只能来求助万能的谷民了qwq
找出来的会得到我的卑微的一个关注qwq
#include<bits/stdc++.h>
using namespace std;
int n, m, k, t, ans;
int f[10010], fa[10010][20], eg[10010][20], dep[10010];
int nxt[100010], edge[100010], h[100010], ver[100010], tot;
bool fg[10010];
struct cccp
{
int s, e, edge;
}a[100010];
inline 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 << 3) + (x << 1) + (c ^ '0');
c = getchar();
}
return x * f;
}
inline void add(int x, int y, int z)
{
tot++;
nxt[tot] = h[x];
ver[tot] = y;
edge[tot] = z;
h[x] = tot;
}
bool cmp(cccp x, cccp y)
{
return x.edge > y.edge;
}
int find(int x)
{
return x == f[x] ? x : f[x] = find(f[x]);
}
int lca(int x, int y)
{
if (find(x) != find(y))
{
return -1;
}
int ans = 1145141919;
if (dep[x] > dep[y]) swap(x, y);
for (int i = t;i >= 0;--i)
{
if (dep[fa[y][i]] >= dep[x])
{
ans = min(ans, eg[y][i]);
y = fa[y][i];
}
}
if (x == y)
return ans;
for (int i = t;i >= 0;--i)
{
if (fa[x][i] != fa[y][i])
{
x = fa[x][i];
y = fa[y][i];
ans = min(ans, eg[y][i]);
ans = min(ans, eg[x][i]);
}
}
ans = min(ans, eg[x][0]);
return ans;
}
void dfs(int nw, int fr)
{
fg[nw] = 1;
dep[nw] = dep[fr] + 1;
for (int i = 0;i <= t;++i)
{
fa[nw][i] = (i == 0 ? fr : fa[fa[nw][i - 1]][i - 1]);
eg[nw][i] = (i == 0 ? eg[fr][i] : eg[eg[nw][i - 1]][i - 1]);
}
for (int i = h[nw];i != 0;i = nxt[i])
{
int y = ver[i];
if (y != fr)
{
eg[y][0] = edge[i];
dfs(y, nw);
}
}
}
int main()
{
n = read();
m = read();
t = log2(n);
for (int i = 1;i <= m;++i)
{
a[i].s = read();
a[i].e = read();
a[i].edge = read();
f[i] = i;
}
int cnt = 0;
sort(a + 1, a + m + 1, cmp);
for (int i = 1;i <= m;++i)
{
int x = find(a[i].s);
int y = find(a[i].e);
if (x != y)
{
f[x] = y;
add(a[i].s, a[i].e, a[i].edge);
add(a[i].e, a[i].s, a[i].edge);
cnt++;
}
if (cnt == n - 1) break;
}
k = read();
for (int i = 1;i <= n;++i)
{
if (fg[i] == 0)
dfs(1, 1);
}
for (int i = 1;i <= k;++i)
{
int x = read();
int y = read();
printf("%d", lca(x, y));
}
return 0;
}