1 //克鲁斯卡尔 2 #include<iostream> 3 #include<algorithm> 4 using namespace std; 5 const int maxn = 10005; 6 struct node 7 { 8 int begin, end, len; 9 }cun[maxn]; 10 int n, fa[maxn], ans, m; 11 12 bool cmp(node a, node b) 13 { 14 return a.len<b.len; //按长度有小到大排序 15 } 16 17 void init() 18 { 19 for (int i = 0; i <= n; i++) 20 { 21 fa[i] = i; 22 } 23 } 24 25 int find(int x) 26 { 27 if (x == fa[x]) 28 return fa[x]; 29 else 30 return fa[x] = find(fa[x]); 31 } 32 33 void join(int a, int b) 34 { 35 a = find(a); 36 b = find(b); 37 if (a != b) 38 fa[b] = a; 39 } 40 41 int kruskal() 42 { 43 sort(cun, cun + m, cmp); 44 init(); //初始化并查集 45 ans = 0; 46 for (int i = 0; i<m; i++) 47 { 48 if (find(cun[i].begin) != find(cun[i].end)) //一条边的两个端点不在同一个集合,则选他,并合并 49 { 50 join(cun[i].begin, cun[i].end); 51 ans += cun[i].len; 52 } 53 } 54 return ans; 55 } 56 57 int main() 58 { 59 while (cin >> n) 60 { 61 if (n == 0) break; 62 m = n*(n - 1) / 2; 63 for (int i = 0; i<m; i++) 64 cin >> cun[i].begin >> cun[i].end >> cun[i].len; 65 cout << kruskal() << endl; 66 } 67 return 0; 68 }
1 //prim 2 #include<iostream> 3 #include<cstdio> 4 #include<cstdlib> 5 #include<cstring> 6 #include<algorithm> 7 using namespace std; 8 9 #define INF 0x7fffffff 10 # define MAXN 120 11 typedef long long int LL; 12 13 LL n, m; 14 LL cmpa[MAXN][MAXN], book[MAXN], dis[MAXN]; 15 16 int main() 17 { 18 LL a, b, weight, ans, p, q, f1, f2, minn, mark; 19 while (scanf("%I64d", &n) && n) 20 { 21 //初始化 这题prime算法合适,边那摩多,都是完全图了 22 for (LL i = 0; i<MAXN; i++) 23 { 24 dis[i] = INF; 25 for (LL j = 0; j<MAXN; ++j) 26 cmpa[i][j] = INF; 27 } 28 29 memset(book, 0, sizeof(book)); 30 ans = 0; 31 32 for (LL i = 0; i<n*(n - 1) / 2; ++i) 33 { 34 scanf("%I64d %I64d %I64d", &a, &b, &weight); 35 cmpa[a][b] = cmpa[b][a] = weight; 36 } 37 38 //连通图 39 book[1] = 1; 40 dis[1] = -1; 41 42 for (LL t = 1; t<n; ++t) 43 { 44 for (LL i = 2; i <= n; ++i) 45 {//更新dis中的值 46 for (LL j = 1; j <= n; ++j) 47 { 48 if (book[j] && dis[i]>cmpa[i][j]) 49 { //j在树中 50 dis[i] = cmpa[i][j]; 51 } 52 } 53 } 54 55 //选点建树 56 minn = INF, mark = 0; 57 for (LL i = 2; i <= n; ++i) 58 { 59 if (book[i]) 60 continue; 61 else 62 { 63 if (dis[i] < minn) 64 { 65 minn = dis[i]; 66 mark = i; 67 } 68 } 69 } 70 71 if (minn != INF) 72 { 73 ans += minn; 74 book[mark] = 1; 75 dis[mark] = -1; 76 } 77 78 } 79 cout << ans << endl; 80 81 } 82 return 0; 83 }
时间: 2024-10-06 17:20:09