Files
Data-Structure/Algorithm/Graph/Kruskal最小生成树.cpp
2025-09-21 12:21:50 +08:00

73 lines
1.5 KiB
C++

#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> parent;
struct edge{
int from;
int to;
int weight;
edge() : from(-1), to(-1), weight(-1){}
edge(int from_, int to_, int weight_): from(from_), to(to_), weight(weight_){}
};
struct cmp{
bool operator()(const edge& a, const edge& b){
return a.weight < b.weight;
}
};
int find(int x){
if(parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void merge(int x, int y){
int rootX = find(x);
int rootY = find(y);
if(rootX != rootY) parent[rootY] = rootX;
return;
}
int main(){
//用adj的方式
int n;
cin >> n;
//vector<vector<pair<int,int>>> adj(n, vector<pair<int,int>>());//可能没用
parent.resize(n);
for(int i = 0; i < n; i++){
parent[i] = i;
}
vector<pair<int, int>> result(n, {-1, -1});
int path = 0;
int edge_num;
cin >> edge_num;
vector<edge> arr(edge_num);
for(int i = 0; i < edge_num; i++){
int a, b, w;
cin >> a >> b >> w;
arr[i] = edge(a, b, w);//反着再来一遍就行
}
if(edge_num < n - 1) {
cout << "Not Valid Full Graph" << endl;
return ;
}
sort(arr.begin(), arr.end(), cmp());
for(auto x : arr){
if(find(x.from) == find(x.to)){
continue;
}
merge(x.from, x.to);
result.push_back({x.from, x.to});
path += x.weight;
}
cout << path << endl;
for(auto x : result){
if(x.first != -1 && x.second != -1) cout << "{" << x.first << ", " << x.second << "}" << " ";
}
cout << endl;
return 0;
}