1. 程式人生 > >HDU 1598 find the most comfortable road

HDU 1598 find the most comfortable road

改進 sort using problem clu spa mes span nbsp

https://vjudge.net/problem/HDU-1598

思路:
一開始想了很久才想通,先把邊進行排序,然後枚舉邊的起點和終點,但是這樣就是三重循環,t了。
之後的改進,大概就是,只用枚舉起點,當循環到兩點聯通的時候,就可以break了,這樣就改進成了二重循環。
一開始就是卡在,如何判斷兩點聯通,這裏用到的主要是克魯斯卡爾算法的思想。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 int par[205];
7 8 struct node 9 { 10 int a,b; 11 int d; 12 } r[1005]; 13 14 void init(int n) 15 { 16 for (int i = 1;i <= n;i++) 17 par[i] = i; 18 } 19 20 int fin(int x) 21 { 22 if (x == par[x]) return x; 23 else return par[x] = fin(par[x]); 24 } 25 26 void unit(int x,int y) 27 {
28 x = fin(x); 29 y = fin(y); 30 31 if (x != y) par[x] = y; 32 } 33 34 bool cmp(node p,node q) 35 { 36 return p.d < q.d; 37 } 38 39 int main() 40 { 41 int n,m; 42 43 while (scanf("%d%d",&n,&m) != EOF) 44 { 45 for (int i = 0;i < m;i++) 46 { 47
scanf("%d%d%d",&r[i].a,&r[i].b,&r[i].d); 48 } 49 50 sort(r,r+m,cmp); 51 52 int q; 53 54 scanf("%d",&q); 55 56 for (int i = 0;i < q;i++) 57 { 58 int st,en; 59 60 int minn = 100000000; 61 62 scanf("%d%d",&st,&en); 63 64 for (int j = 0;j < m;j++) 65 { 66 init(n); 67 bool f = 0; 68 for (int k = j;k < m;k++) 69 { 70 bool ff = 0; 71 72 unit(r[k].a,r[k].b); 73 74 if (fin(st) == fin(en)) ff = 1; 75 76 if (ff && r[k].d - r[j].d < minn) 77 { 78 minn = r[k].d - r[j].d; 79 f = 1; 80 } 81 82 if (f) break; 83 } 84 } 85 86 87 if (minn == 100000000) printf("-1\n"); 88 else printf("%d\n",minn); 89 } 90 } 91 92 93 return 0; 94 }

HDU 1598 find the most comfortable road