您的位置:首页 > 其它

hdu 1598 find the most comfortable road

2017-09-22 16:06 405 查看
路径从小到大排序,然后开始枚举边,构建最小生成树,如果包含了要求的起点和终点,即  father【u】==father【v】 ,求得此时的差值,取个最小值就是了

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#define inf 999999999
using namespace std;

struct edge{
int u,v,w;
}e[1100];

int father[500000];
int n,m;

bool cmp(const edge &a,const edge &b){
return a.w<b.w;
};
int findroot(int p){
if(father[p]!=p)
father[p]=findroot(father[p]);
return father[p];
}
void unionset(int p,int q){
father[q]=p;
}

int main(){
while(scanf("%d%d",&n,&m)!=EOF){
int i,j;
for(i=0;i<m;i++){
scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
}
sort(e,e+m,cmp);
int q;
scanf("%d",&q);
while(q--){
int u,v;
int ans=inf;
scanf("%d%d",&u,&v);
for(i=0;i<m;i++){
for(j=0;j<=n;j++)father[j]=j;
for(j=i;j<m;j++){
int a=findroot(e[j].u);
int b=findroot(e[j].v);
if(a!=b)father[b]=a;
if(findroot(u)==findroot(v)){
ans=min(ans,e[j].w-e[i].w);
}
}
}
if(ans==inf)printf("-1\n");
else printf("%d\n",ans);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: