您的位置:首页 > 其它

hdu1598 find the most comfortable road

2013-08-26 19:01 375 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1598

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define INF 9999999
#define MAXN 1002

struct 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");
else
printf("%d\n",min);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: