做法:克鲁斯卡尔+倍增LCA
#include<cstdio>
#include<algorithm>
using namespace std;
struct street {int u,v,z;}a[50010];
struct node {int v,fr,z;}e[20010];
int tail[10010],fa[10010],dep[10010];
int f[10010][14],g[10010][14];
int cnt=0,n,m,p,minn;
inline int read()
{
int x=0;char c=getchar();
while (c<'0' || c>'9') c=getchar();
while (c>='0' && c<='9') x=x*10+c-48,c=getchar();
return x;
}
void add(int u,int v,int z) {e[++cnt]=(node){v,tail[u],z}; tail[u]=cnt;}
int cmp(street x,street y) {return x.z>y.z;}
int gf(int x) {return !fa[x] ? x:fa[x]=gf(fa[x]);}
void dfs(int x)
{
for (int p=tail[x];p;p=e[p].fr)
if (!f[e[p].v][0])
{
dep[e[p].v]=dep[x]+1;
f[e[p].v][0]=x;
g[e[p].v][0]=e[p].z;
dfs(e[p].v);
}
}
int LCA(int x,int y)
{
minn=100010;
if (dep[x]<dep[y]) swap(x,y);
for (int i=13;i>=0;i--)
if (dep[x]-dep[y]>=(1<<i))
minn=min(minn,g[x][i]),x=f[x][i];
if (x==y) return x;
for (int i=13;i>=0;i--)
if (f[x][i]!=f[y][i])
{
minn=min(minn,min(g[x][i],g[y][i]));
x=f[x][i],y=f[y][i];
}
if (f[x][0]!=f[y][0]) return 0;
else
{
minn=min(minn,min(g[x][0],g[y][0]));
return f[x][0];
}
}
int main()
{
// freopen("truck.in","r",stdin);
// freopen("truck.out","w",stdout);
n=read(),m=read();
for (int i=1;i<=m;i++)
a[i]=(street){read(),read(),read()};
sort(a+1,a+m+1,cmp);
for (int i=1;i<=m;i++)
if (gf(a[i].u)!=gf(a[i].v))
{
fa[gf(a[i].u)]=gf(a[i].v);
add(a[i].u,a[i].v,a[i].z);
add(a[i].v,a[i].u,a[i].z);
}
dfs(1);
for (int j=1;j<=13;j++)
for (int i=1;i<=n;i++)
{
f[i][j]=f[f[i][j-1]][j-1];
g[i][j]=min(g[i][j-1],g[f[i][j-1]][j-1]);
}
p=read();
for (int i=1,lca;i<=p;i++)
{
lca=LCA(read(),read());
if (!lca || minn==100010) puts("-1");
else printf("%d
",minn);
}
return 0;
}