Algo-Trian
This commit is contained in:
72
Algorithm/Graph/Kruskal最小生成树.cpp
Normal file
72
Algorithm/Graph/Kruskal最小生成树.cpp
Normal file
@@ -0,0 +1,72 @@
|
||||
#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(){
|
||||
//<2F><>adj<64>ķ<EFBFBD>ʽ
|
||||
int n;
|
||||
cin >> n;
|
||||
//vector<vector<pair<int,int>>> adj(n, vector<pair<int,int>>());//<2F><><EFBFBD><EFBFBD>û<EFBFBD><C3BB>
|
||||
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);//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
}
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user