标签:
都是生成最小生成树,库鲁斯卡尔算法与普里姆算法的不同之处在于——库鲁斯卡尔算法的思想是以边为主,找权值最小的边生成最小生成树。
同样的题目:最小生成树
1
6
0 6 1 5 0 0
6 0 5 0 3 0
1 5 0 5 6 4
5 0 5 0 0 2
0 3 6 0 0 6
0 0 4 2 6 0
15
#include <cstdio> #include <cstring> #include <algorithm> #define MAXN 22 using namespace std; int map[MAXN][MAXN], n; int p[MAXN]; struct Edge { int begin, end, weight; bool operator < (const Edge& a) const { return weight < a.weight; } }edges[MAXN]; int Find(int *p, int f) { while ( p[f] > 0 ) f = p[f]; return f; } void Dijkstra() { int tim = 0; for (int i = 0; i < n; i ++) for (int j = i+1; j < n; j ++) { if ( map[i][j] ) { edges[tim].begin = i; edges[tim].end = j; edges[tim].weight = map[i][j]; ++ tim; } } sort(edges, edges+tim); memset(p, 0, sizeof(p)); int sum = 0; for (int i = 0; i < tim; i ++) { int x = Find(p, edges[i].begin); int y = Find(p, edges[i].end); if ( x != y ) { p[x] = y; sum += edges[i].weight; } } printf("%d\n", sum); } int main(void) { int T; scanf("%d", &T); while ( T -- ) { scanf("%d", &n); for (int i = 0; i < n; i ++) for (int j = 0; j < n; j ++) scanf("%d", &map[i][j]); Dijkstra(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/Asimple/p/5551307.html