POJ1861(Network)-Kruskal

題目在這ios

Sample Inputide

4 6 1 2 1 1 3 1 1 4 2 2 3 1 3 4 1 2 4 1 

Sample Outputspa

1 4 1 2 1 3 2 3 3 4

題目意思:4個點,6個邊,每一個邊有對應的權值。最後輸出一行爲路徑中最大的邊的值,第二行爲路徑上邊的總數,code

第三行爲每條邊的始末編號。題目須要求出最小生成樹的最大邊的最小值。blog

 1 /*
 2 Problem: 1861        User: 
 3 Memory: 416K        Time: 500MS
 4 Language: C++        Result: Accepted
 5 */
 6 #include <iostream>
 7 #include <algorithm>
 8 using namespace std;
 9 
10 #define MAX 15010
11 int p[1010];//存放父親結點
12 
13 struct Edge
14 {
15     int u;
16     int v;
17     int w;
18 }map[MAX],ans[MAX];
19 
20 bool cmp(Edge a,Edge b)
21 {
22     return a.w<b.w;
23 }
24 
25 int Find(int a)
26 {
27     return a==p[a]?a:a=Find(p[a]);
28 }
29 
30 int main()
31 {
32     int N,M,i;
33     int a,b,c;
34     cin>>N>>M;
35     for(i=0;i<=N;i++)
36     {
37         p[i] = i;
38     }
39     for(i=0;i<M;i++)
40     {
41         cin>>a>>b>>c;
42         map[i].u = a;
43         map[i].v = b;
44         map[i].w = c;
45     }
46     sort(map,map+M,cmp);
47     int count = 0;
48     int maxEdge = 0;
49     for(i=0;i<M;i++){
50         int x = Find(map[i].u);
51         int y = Find(map[i].v);
52         if(x != y)
53         {
54             p[x] = y;//不在一個集合,合併
55             ans[count].u = map[i].u;
56             ans[count].v = map[i].v;
57             count ++;
58             if(map[i].w>maxEdge)
59                 maxEdge = map[i].w;
60         }
61     }
62     cout<<maxEdge<<endl;//路徑中最長的邊
63     cout<<count<<endl;//邊的總數
64     for(i=0;i<count;i++)
65         cout<<ans[i].u<<" "<<ans[i].v<<endl;/輸出每條路徑
66     return 0;
67 }
View Code
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息