AcWing 859. Kruskal算法求最小生成树(稀疏图)
Posted MangataTS
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AcWing 859. Kruskal算法求最小生成树(稀疏图)相关的知识,希望对你有一定的参考价值。
题面连接
https://www.acwing.com/problem/content/861/
思路
没啥好说的,就是贪心+破圈法,然后不断将最短的边加入集合中,可以参考我这篇博客
https://acmer.blog.csdn.net/article/details/118560004
代码
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 100010
struct node
int from,to;
long long cost;
E[N*2];
int fa[N],n,m;
bool cmp(node a,node b)
return a.cost<b.cost;
int find(int x)
int k = x;
while(k != fa[k])
k = fa[k];
while(x != fa[x])
int t =fa[x];
fa[x] = k;
x = t;
return x;
void init()
for(int i = 1; i <= n; ++i)
fa[i] = i;
int same(int x,int y)
return find(x) == find(y);
void merge(int a,int b)
a = find(a);
b = find(b);
if(a != b)
fa[b] = a;
long long kruskal()
long long ans = 0;
sort(E+1,E+m+1,cmp);
for(int i = 1; i <= m; ++i)
if(same(E[i].from,E[i].to))
continue;
merge(E[i].from,E[i].to);
ans += E[i].cost;
return ans;//返回的是最小生成树的代价
int main()
int u,v,w;
scanf("%d%d",&n,&m);
init();
for(int i = 1; i <= m; ++i)
scanf("%d%d%d",&u,&v,&w);
E[i].from = u,E[i].to = v,E[i].cost = w;
long long k = kruskal();
int loc = find(1);
for(int i = 2; i <= n; ++i)
if(find(i) != loc)
k = -1;
break;
if(k == -1)
puts("impossible");
else
printf("%lld\\n",k);
return 0;
以上是关于AcWing 859. Kruskal算法求最小生成树(稀疏图)的主要内容,如果未能解决你的问题,请参考以下文章