最小生成树MST
最小生成树是在一张无向连通图中,找到一棵树,使得其边的代价之和最小。
注:可能存在多个最小生成树。
两种算法
Kruskal核心思想
以边为展开,将图中的最小代价边尝试加入集合tree中,并且该边不能与集合tree中的边形成环,如此迭代,最终得到的集合tree为MST。因此可以采用并集查的方式实现Kruskal算法
Prim核心思想
以点为展开,将图中的最小代价边的终点尝试加入集合visited中,并边的起点from已在集合visited中,终点to不在集合visited中。这里,可以采用堆来存储扩展的边。
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
class MST {
private:
struct Cmp {
bool operator()(const vector<int>& left, const vector<int>& right) {
return left[2] > right[2];
}
};
int findParent(int x, vector<int>& parents) {
return x == parents[x] ? x : (parents[x] = findParent(parents[x], parents));
}
void merge(int x, int y, vector<int>& parents) {
int px = parents[x];
int py = parents[y];
if (px != py)
parents[px] = py;
}
public:
/*
Kruskal
input
edges: [[u, v, w], ...] Undirected Connected graph
n: the number of points
minCost: the minimum cost
output
the one of MST
*/
vector<vector<int>> findMST_Kruskal(vector<vector<int>> edges, int n, int& minCost) {
sort(edges.begin(), edges.end(), [](const vector<int>& left, const vector<int>& right) {
return left[2] < right[2];
});
vector<int>parents(n);
for (int i = 0; i < n; ++i)
parents[i] = i;
vector<vector<int>>tree;
minCost = 0;
for (auto& edge : edges) {
int pu = findParent(edge[0], parents);
int pv = findParent(edge[1], parents);
if (pu == pv) continue;
merge(edge[0], edge[1], parents);
tree.push_back(edge);
minCost += edge[2];
}
return tree;
}
/*
Prim
input
edges: [[u, v, w], ...] Undirected Connected graph
n: the number of points
minCost: the minimum cost
output
the one of MST
*/
vector<vector<int>> findMST_Prim(vector<vector<int>> edges, int n, int& minCost) {
unordered_map<int, vector<vector<int>>>graph;
for (auto edge : edges) {
graph[edge[0]].push_back(edge);
swap(edge[0], edge[1]);
graph[edge[0]].push_back(edge);
}
priority_queue<vector<int>, vector<vector<int>>, Cmp>queue;
unordered_set<int>visited;
vector<vector<int>>tree;
minCost = 0;
int from = 0;
visited.insert(from);
while (true) {
for (auto& edge : graph[from]) {
if (visited.find(edge[1]) != visited.end()) continue;
queue.push(edge);
}
if (queue.empty()) break;
auto edge = queue.top();
queue.pop();
if (visited.find(edge[1]) != visited.end()) continue;
minCost += edge[2];
visited.insert(edge[1]);
tree.push_back(edge);
from = edge[1];
}
return tree;
}
};
int main() {
vector<vector<int>> edges = { {0,3,4},{0,1,1},{0,2,1},{2,3,2},{1,3,1},{1,2,2} };
int n = 4;
MST mst;
int minCost = 0;
auto tree=mst.findMST_Prim(edges, n, minCost);
cout << "minCost" << minCost << endl;
for (auto& edge : tree)
cout << edge[0] << " " << edge[1] << " " << edge[2] << endl;
}