这道题其实和邦德市一样,只是需要多判断一下是不是在同一棵树上,这里我是用vis来标记的连通分量实现的。详见http://blog.csdn.net/qq_35546274/article/details/51888979
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=50005;
struct lu
{
int u,v,w;
};
vector<lu>g;
vector<int>ww[maxn],e[maxn];
int n,m,q,pa[maxn],fa[maxn],dist[maxn],dep[maxn],vis[maxn]={0};
bool my(lu a,lu b)
{
return a.w>b.w;
}
void init()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
g.push_back((lu){x,y,z});
}
sort(g.begin(),g.end(),my);
}
void in()
{
for(int i=1;i<=n;i++)
pa[i]=i;
}
int find(int x)
{
if(pa[x]==x) return x;
pa[x]=find(pa[x]);
return pa[x];
}
void krscr()
{
for(int i=0;i<g.size();i++)
{
int x=g[i].u,y=g[i].v,z=g[i].w;
if(find(x)==find(y)) continue;
pa[find(x)]=find(y);
e[x].push_back(y);
e[y].push_back(x);
ww[x].push_back(z);
ww[y].push_back(z);
}
}
int f(int x,int y)
{
int k=200000;
if(dep[x]<dep[y]) swap(x,y);
while(dep[x]>dep[y])
{
k=min(k,dist[x]-dist[fa[x]]);
x=fa[x];
}
while(x!=y)
{
k=min(k,dist[x]-dist[fa[x]]);
k=min(k,dist[y]-dist[fa[y]]);
y=fa[y];
x=fa[x];
}
return k;
}
void dfs(int x,int y)
{
vis[x]=y;
for(int i=0;i<e[x].size();i++)
{
int j=e[x][i];
if(vis[j]) continue;
dep[j]=dep[x]+1;
fa[j]=x;
dist[j]=dist[x]+ww[x][i];
dfs(j,y);
}
}
int main()
{
freopen("bus.in","r",stdin);
//freopen("bus.out","w",stdout);
init();
in();
krscr();
int t=0;
for(int i=1;i<=n;i++) if(vis[i]==0)
{
fa[i]=i;
dep[i]=1;
dist[i]=0;
dfs(i,++t);
}
scanf("%d",&q);
for(int i=1;i<=q;i++)
{
int x,y;
scanf("%d%d",&x,&y);
if(vis[x]!=vis[y])
{
printf("-1\n");
continue;
}
int ans=f(x,y);
printf("%d\n",ans);
}
return 0;
}