POJ 2377 Bad Cowtractors

http://poj.org/problem?id=2377

裸求最大生成树

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <queue>
 5 #include <algorithm>
 6 #define READ() freopen("in.txt", "r", stdin);
 7 #define MAXV 10007
 8 #define MAXE 40007
 9 #define INF 0x3f3f3f3f
10 using namespace std;
11 
12 int N,M, num = 0;
13 struct Edge
14 {
15     int from, to, cost;
16     Edge () {}
17     Edge (int from, int to, int cost) : from(from), to(to), cost(cost) {}
18 }edge[MAXE];
19 
20 int par[MAXV];
21 
22 int find(int x)
23 {
24     if (par[x] == x) return x;
25     else return par[x] = find(par[x]);
26 }
27 
28 void unite(int x, int y)
29 {
30     int px = find(x), py = find(y);
31     if (px == py) return ;
32     par[py] = px;
33 }
34 
35 bool same(int x, int y)
36 {
37     int px = find(x), py = find(y);
38     return px == py;
39 }
40 
41 bool cmp(Edge e1, Edge e2)
42 {
43     return e1.cost > e2.cost;
44 }
45 int Kruskal()
46 {
47     int res = 0;
48     for (int i = 1; i <= N; i++) par[i] = i;
49     sort(edge, edge+num, cmp);
50     for (int i = 0; i < num; i++)
51     {
52         Edge e = edge[i];
53         if (!same(e.from, e.to))
54         {
55             res += e.cost;
56             unite(e.from, e.to);
57         }
58     }
59     for (int i = 1; i <= N; i++)//判断一下是否都连通
60     {
61         for (int j = 1; j <= N; j++)
62         {
63             if (!same(i,j)) return -1;
64         }
65     }
66     return res;
67 }
68 
69 
70 int main()
71 {
72     READ()
73     scanf("%d%d", &N, &M);
74     for (int i = 0; i < M; i++)
75     {
76         int from, to, cost;
77         scanf("%d%d%d", &from, &to, &cost);
78         edge[num++] = Edge(from, to, cost);
79         edge[num++] = Edge(to, from, cost);
80     }
81     int ans = Kruskal();
82     cout << ans << endl;
83 }
原文地址:https://www.cnblogs.com/oscar-cnblogs/p/6403913.html