1.Kruskal算法实现
- 使用了并查集进行优化查找,使得时间复杂度降低。
- 核心代码:
class Kruskal {
public:
vector<int> father;
int findFather(int x) {
while (x != father[x]) {
x = father[x];
}
return x;
}
int miniSpanningTree(int n, int m, vector<vector<int> >& cost) {
if (cost.empty()) return 0;
int res = 0, count = 0;
sort(cost.begin(), cost.end(), [](vector<int>& u, vector<int>& v) {
return u[2] < v[2];
});
father.resize(n + 1, 0);
for (int i = 0; i <= n; i++)
father[i] = i;
for (vector<int>& vec : cost) {
int rx = findFather(vec[0]), ry = findFather(vec[1]);
if (rx == ry) continue;
father[rx] = ry;
res += vec[2];
count++;
}
return count + 1 == n ? res : -1;
}
};
2.Prim算法实现