1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| 第一行输出最小生成树最大的边,第二行输出用到的电缆数量。,剩下的就是输出每条电 缆。
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; #define MAXN 15010
int n, m; int father[MAXN]; int ranks[MAXN]; int num[MAXN];
struct Edge{ int from; int to; int cost; }edge[MAXN];
bool cmp(Edge e1, Edge e2) { return e1.cost < e2.cost; }
void init_set() { for(int i = 0; i < MAXN; i++){ father[i] = i; ranks[i] = 1; } }
int find_set(int x) { return father[x] == x ? father[x] : father[x] = find_set(father[x]); }
void union_set(int x, int y) { if(ranks[x] >= ranks[y]){ ranks[x] += ranks[y]; father[y] = x; } else{ ranks[y] += ranks[x]; father[x] = y; } }
void kruskal() { init_set(); sort(edge, edge + m, cmp); int index = 0; for(int i = 0; i < m; i++){ int root_x = find_set(edge[i].from); int root_y = find_set(edge[i].to); if(root_x != root_y){ num[index++] = i; union_set(root_x, root_y); } } printf("%d\n%d\n" , edge[num[index - 1]].cost , index); for(int i = 0 ; i < index ; i++) printf("%d %d\n" , edge[num[i]].from , edge[num[i]].to); }
int main() { freopen("input.txt", "r", stdin); while(scanf("%d%d", &n, &m) != EOF){ for(int i = 0; i < m; i++){ scanf("%d%d%d", &edge[i].from, &edge[i].to, &edge[i].cost); } kruskal(); } return 0; }
|