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;
}
#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;
}
相关文章推荐
- hdu 1598 find the most comfortable road
- hdu 1598 find the most comfortable road
- AYIT2017暑假集训第二周周三赛 E - find the most comfortable road HDU - 1598
- HDU-1598-find the most comfortable road
- hdu 1598 find the most comfortable road(并查集判断图联通)
- hdu-1598-find the most comfortable road( 并查集&贪心)
- hdu 1598 find the most comfortable road
- HDU 1598 find the most comfortable road
- HDU 1598 find the most comfortable road
- HDU 1598 find the most comfortable road 【枚举+(并查集)最小生成树Kruskal】
- hdu 1598 find the most comfortable road (并查集+枚举)
- hdu 1598 find the most comfortable road
- HDU 1598 find the most comfortable road (MST)
- HDU 1598 find the most comfortable road(枚举+并查集,类似于最小生成树)
- hdu 1598 find the most comfortable road(枚举+并查集)
- find the most comfortable road HDU - 1598
- HDU 1598 find the most comfortable road
- hdu 1598 find the most comfortable road(并查集+枚举)
- hdu 1598 find the most comfortable road
- HDU-1598 find the most comfortable road