#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
/*并查集start*/
struct UF{
UF * parent;
UF():parent(NULL){ }
};
UF* find(UF* c){
if(c->parent == NULL)
return c;
set<UF*> s;
while(c->parent!= NULL){
s.insert(c);
c = c->parent;
}
for(auto v : s)
v->parent = c;
return c;
}
void unionn(UF *a ,UF* b){
if(find(a) == find(b))
return;
find(a)->parent = find(b);
}
UF uf[100];
/*并查集end*/
/*边的结构*/
struct Edge{
int from,to;
int weight;
Edge(int a,int b, int c):from(a),to(b),weight(c){ }
bool operator< (const Edge& other) const{
return weight<other.weight;
}
};
vector<Edge> e; //存储所有的边
vector<Edge> g[100]; //存储生成的图 ,以邻接表表示
int N,M; //顶点个数,边的条数
bool kruskal(){
sort(e.begin(), e.end());
int cnt = 0;
for(int i=0; i<e.size();++i){
int from = e[i].from;
int to =e[i].to;
int weight = e[i].weight;
if(find(&uf[from]) == find(&uf[to]))
continue;
unionn(&uf[from],&uf[to]);
g[from].push_back(Edge(from,to,weight));
g[to].push_back(Edge(to,from,weight));
cnt++;
if(cnt == N-1)
return true;
}
return false;
}
int main()
{
cin>>N>>M;
for(int i=0; i<M; ++i)
{
int from,to,weight;
cin>>from>>to>>weight;
e.push_back(Edge(from,to,weight));
}
if(kruskal())
for(int i=1; i<=N;++i)
for(auto v : g[i])
cout<<v.from<<" "<<v.to<<" "<<v.weight<<endl; //输出生成的图的所有边
}
kruskal算法基于并查集的实现
最新推荐文章于 2022-11-13 11:15:32 发布