hdu1598 find the most comfortable road

来源:互联网 发布:舒客牙膏知乎 编辑:程序博客网 时间:2024/06/07 18:19

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1598


#include <stdio.h>#include <string.h>#include <stdlib.h>#define INF 9999999#define MAXN 1002struct node {int st,end,val;}edge[MAXN];int father[202];int cmp(const void *x,const void *y){struct node *a=(struct node *)x;struct node *b=(struct node *)y;return a->val-b->val;}int find(int x)  {//带路径压缩的查找算法  int i,j,r=x;  while(r!=father[r])//循环结束,则找到根节点  r=father[r];  i=x;  while(i!=r)//本循环修改查找路径中所有节点  {  j=father[i];  father[i]=r;  i=j;  }  return r; }void Union(int x,int y){int fx=find(x);int fy=find(y);if(fx!=fy)father[fx]=fy;}int main(){int n,m,q,start,end,i,j,min,temp;while(scanf("%d %d",&n,&m)!=EOF){for(i=0;i<m;++i)scanf("%d %d %d",&edge[i].st,&edge[i].end,&edge[i].val);qsort(edge,m,sizeof(edge[0]),cmp);scanf("%d",&q);while(q--){min=INF;scanf("%d %d",&start,&end);for(i=0;i<m;++i)//枚举每一条边{for(j=0;j<=n;++j)father[j]=j;for(j=i;j<m;++j){Union(edge[j].st,edge[j].end);if(find(start)==find(end)){//直到找到一条可以使起点到达终点的边temp=edge[j].val-edge[i].val;if(min>temp)min=temp;break;}}if(j==m)break;}if(min==INF)printf("-1\n");elseprintf("%d\n",min);}}return 0;}


原创粉丝点击