标签:
用了Kruskal算法来生成最小生成树
当然也可以用Prim算法来做
#include <iostream> using namespace std; typedef struct{ int start; int end; int length; }road; int* father; road* map; int n, m; int countRoad = 0, sum = 0; int roadCompare(const void* a, const void* b); int findFather(int i); int main() { cin >> n >> m; map = (road *)malloc((m + 1)*sizeof(road)); father = (int*)malloc((n + 1)*sizeof(int)); for (int i = 1; i <= m; i++){ cin >> map[i].start >> map[i].end >> map[i].length; } for (int i = 1; i <= n; i++){ father[i] = i; } qsort(map + 1, m, sizeof(road), roadCompare); //Kruskal核心算法 for (int i = 1; i <= m; i++){ if (findFather(map[i].start) != findFather(map[i].end)){ countRoad++; sum += map[i].length; father[findFather(map[i].start)] = findFather(map[i].end); } if (countRoad == n - 1){ break; } } if (countRoad != n - 1){ cout << -1 << endl; } else{ cout << sum << endl; } return 0; } int roadCompare(const void* a, const void* b) { int c = (*(road*)a).length - (*(road*)b).length; if (c > 0){ return 1; } else if (c == 0){ return 0; } else return -1; } int findFather(int i) { if (father[i] == i){ return i; } else{ return father[i] = findFather(father[i]); } }
标签:
原文地址:http://www.cnblogs.com/zhouyiji/p/4572283.html