题目:
题解:
这里用了一个minn数组,minn[i][j]表示从i开始往上蹦2^j,经过的所有边+自己通往父亲那条边 的权值最小值。
lca解决就好了,注意lca最后返回的是使x和y的父亲相等,所以不用担心minn取到x和y的lca通往父亲的那条边
代码:
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#define sz 31
#define INF 1e9
#define M 50005
#define N 10005
using namespace std;
//minn[i][j]表示从i开始往上蹦2^j,经过的所有bian的权值最小值。
struct road{int x,y,z;}lu[M];
int tot,nxt[M*2],point[M*2],v[M*2],cc[M*2];
int fa[N],f[N][sz],minn[N][sz],mi[sz],h[N];
int cmp(road a,road b){return a.z>b.z;}
int find(int x)
{
if (fa[x]!=x) fa[x]=find(fa[x]);
return fa[x];
}
void addline(int x,int y,int cap)
{
++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; cc[tot]=cap;
++tot; nxt[tot]=point[y]; point[y]=tot; v[tot]=x; cc[tot]=cap;
}
void dfs(int x,int fa)
{
h[x]=h[fa]+1;
for (int i=1;i<sz;i++)
if (h[x]-mi[i]<1) break;
else
{
f[x][i]=f[f[x][i-1]][i-1];
minn[x][i]=min(minn[x][i-1],minn[f[x][i-1]][i-1]);
}
for (int i=point[x];i;i=nxt[i])
if (v[i]!=fa)
{
minn[v[i]][0]=cc[i];
f[v[i]][0]=x;
dfs(v[i],x);
}
}
int lcmin(int x,int y)
{
int i;
int minnn=INF;
if (h[x]<h[y]) swap(x,y);
int k=h[x]-h[y];
for (i=0;i<sz;i++)
if ((k>>i)&1) minnn=min(minnn,minn[x][i]),x=f[x][i];
if (x==y) return minnn;
for (i=sz-1;i>=0;i--)
if (f[x][i]!=f[y][i]) minnn=min(minnn,min(minn[x][i],minn[y][i])),x=f[x][i],y=f[y][i];
minnn=min(minnn,min(minn[x][0],minn[y][0]));
return minnn;
}
int main()
{
int n,m,i,q;
mi[0]=1;
for (i=1;i<sz;i++) mi[i]=mi[i-1]*2;
scanf("%d%d",&n,&m);
for (i=1;i<=m;i++) scanf("%d%d%d",&lu[i].x,&lu[i].y,&lu[i].z);
sort(lu+1,lu+m+1,cmp);
for (i=1;i<=n;i++) fa[i]=i;
for (i=1;i<=m;i++)
{
int a=find(lu[i].x),b=find(lu[i].y);
if (a!=b)
{
addline(lu[i].x,lu[i].y,lu[i].z);
fa[a]=b;
}
}
for (i=1;i<=n;i++)
if (!h[i]) dfs(i,0);
scanf("%d",&q);
for (i=1;i<=q;i++)
{
int x,y;
scanf("%d%d",&x,&y);
if (find(x)!=find(y)) printf("-1\n");
else printf("%d\n",lcmin(x,y));
}
}