最小生成樹 kruskal算法 codevs 1638 修復公路

1638 修復公路

 

 時間限制: 1 s
 空間限制: 256000 KB
 題目等級 : 鑽石 Diamond
 
 
 
題目描述  Description

A地區在地震事後,鏈接全部村莊的公路都形成了損壞而沒法通車。政府派人修復這些公路。ios

給出A地區的村莊數N,和公路數M,公路是雙向的。並告訴你每條公路的連着哪兩個村莊,並告訴你何時能修完這條公路。問最先何時任意兩個村莊可以通車,即最先何時任意兩條村莊都存在至少一條修復完成的道路(能夠由多條公路連成一條道路)flask

輸入描述  Input Description

第1行兩個正整數N,M(N<=1000,M<=100000)app

下面M行,每行3個正整數x, y, t,告訴你這條公路連着x,y兩個村莊,在時間t時能修復完成這條公路。(x<=N,y<=N,t<=100000)spa

輸出描述  Output Description

若是所有公路修復完畢仍然存在兩個村莊沒法通車,則輸出-1,不然輸出最先何時任意兩個村莊可以通車。code

樣例輸入  Sample Input

4 4blog

1 2 6ip

1 3 4get

1 4 5input

4 2 3it

樣例輸出  Sample Output

5

 1 /*
 2 題目的意思很容易就得出:這個題是求一張圖的最小生成樹的最大邊的。
 3 寫程序的時候,沒注意把father[x1]=y1;寫成了father[x1]==y1;結果只有20分啊!
 4 */
 5 #define N 1005
 6 #define M 100010
 7 #include<iostream>
 8 using namespace std;
 9 #include<cstdio>
10 #include<algorithm>
11 int n,m;
12 struct Edge{
13     int u,v,w;
14     bool operator <(Edge P)
15     const{return w<P.w;}
16 }edge[M];
17 int father[N];
18 void input()
19 {
20     scanf("%d%d",&n,&m);
21     for(int i=1;i<=m;++i)
22       scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
23     sort(edge+1,edge+m+1);
24 }
25 int find1(int x)
26 {
27     return (father[x]==x)?x:father[x]=find1(father[x]);
28 }
29 int kruskal()
30 {
31     for(int i=1;i<=n;++i)
32       father[i]=i;
33     int sum=0;
34     for(int i=1;i<=m;++i)
35     {
36         int x1=find1(edge[i].u);
37         int y1=find1(edge[i].v);
38         if(x1!=y1)
39         {
40             sum++;
41             father[x1]=y1;
42             if(sum==n-1)
43               return edge[i].w;
44         }
45     }
46     return -1;
47 }
48 int main()
49 {
50     input();
51     printf("%d\n",kruskal());
52     return 0;
53 }
相關文章
相關標籤/搜索