1 #include <cstdio> 2 #include <cstring> 3 #include <vector> 4 #include <algorithm> 5 using namespace std; 6 7 const int maxn = 100005; 8 int n, m; 9 struct node 10 { 11 int u, v, c; 12 }g[maxn]; 13 long long ans; 14 int fa[maxn]; 15 int ff[maxn]; 16 int ee[maxn]; 17 18 bool cmp(node a, node b){ 19 return a.c > b.c; 20 } 21 22 void init(){ 23 memset(ff, false, sizeof(ff)); 24 memset(ee, false, sizeof(ee)); 25 for (int i = 0; i < n; i++){ 26 fa[i] = i; 27 } 28 } 29 30 int find(int x){ 31 if (x == fa[x]) 32 return x; 33 else 34 return fa[x] = find(fa[x]); 35 } 36 37 void Union(int x, int y, int z){ 38 int a = find(x); 39 int b = find(y); 40 if (a == b){ 41 if (ff[a]) 42 return; 43 ans += z; 44 ff[a] = true; 45 } 46 else{ 47 if (ff[a] && ff[b]) 48 return; 49 ans += z; 50 fa[b] = a; 51 if (ff[a] || ff[b]) 52 ff[a] = true; 53 } 54 } 55 56 int main(){ 57 while (~scanf("%d%d", &n, &m)){ 58 if (n == 0 && m == 0) 59 break; 60 init(); 61 int u, v, c; 62 for (int i = 0; i < m; i++){ 63 scanf("%d%d%d", &u, &v, &c); 64 g[i].u = u; 65 g[i].v = v; 66 g[i].c = c; 67 } 68 //克鲁斯卡尔 69 sort(g, g + m, cmp); //按边从小到大排列 70 ans = 0; 71 for (int i = 0; i < m; i++){ 72 Union(g[i].u, g[i].v, g[i].c); 73 } 74 printf("%lld\n", ans); 75 } 76 //system("pause"); 77 return 0; 78 }
时间: 2024-10-03 20:16:31