hdu find the most comfortable road(贪心+并查集)

这题用到了并查集,并且还用到了贪心思想。

就是先把每条路上的speedSARS从小到大排序,然后通过并查集判断两个城市是否有路联通,如果有的话,从所有路中找出最舒适的一条。

代码:

 1 #include<stdio.h>
2 #include<Stdlib.h>
3 #include<string.h>
4 struct node
5 {
6 int x,y;
7 int cost;
8 }p[10002];
9 int f[102];
10 int cmp(const void *a,const void *b)
11 {
12 return (*(struct node *)a).cost - (*(struct node *)b).cost;
13 }
14 int find(int x)
15 {
16 if(f[x]!=x)
17 f[x]=find(f[x]);
18 return f[x];
19 }
20 int main()
21 {
22 int n,m,i,j,k,a,b,t,min;
23 while(scanf("%d%d",&n,&m)!=EOF)
24 {
25 for(i=0;i<m;i++)
26 scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].cost);
27 qsort(p,m,sizeof(p[0]),cmp);
28 scanf("%d",&t);
29 while(t--)
30 {
31 scanf("%d%d",&a,&b);
32 min=999999999;
33 for(i=0;i<m;i++)
34 {
35 for(k=0;k<=n;k++)
36 f[k]=k;
37 j=i;
38 while(j<m)
39 {
40 int t1=find(p[j].x);
41 int t2=find(p[j].y);
42 if(t1!=t2)
43 {
44 f[t1]=t2;
45 }
46 if(find(a)==find(b))
47 break;
48 j++;
49 }
50 if(j>=m)
51 break;
52 if(min>(p[j].cost-p[i].cost))
53 min=p[j].cost-p[i].cost;
54 }
55 if(min==999999999)
56 min=-1;
57 printf("%d\n",min);
58 }
59 }
60 return 0;
61 }



原文地址:https://www.cnblogs.com/misty1/p/2264226.html