===================================
这个是最小生成树的模板题,可以用Prim算法,也可以用Kruskal算法。这个题我用的是并查集优化的Kruskal算法。
C++代码:
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; const int maxn = 50003; struct Edge{ int a; int b; int c; }e[maxn]; bool cmp(Edge a,Edge b){ return a.c < b.c; } int n,m; int father[maxn]; void Init(int n){ for(int i = 1; i <= n; i++) father[i] = i; } int Find(int x){ while(x != father[x]){ father[x] = father[father[x]]; x = father[x]; } return x; } int Merge(int a,int b){ int ax = Find(a); int bx = Find(b); if(ax == bx) return 0; father[bx] = ax; return 1; } long long Kruskal(int n,int m){ long long ans = 0; for(int i = 1; i <= m; i++){ if(Merge(e[i].a,e[i].b)){ ans += e[i].c; n--; if(n == 1) return ans; } } return 0; } int main(){ cin>>n>>m; Init(n); for(int i = 1; i <= m; i++){ cin>>e[i].a>>e[i].b>>e[i].c; } sort(e+1,e+m+1,cmp); long long ans = Kruskal(n,m); cout<<ans<<endl; return 0; }
python题解见我的简书:https://www.jianshu.com/p/ca661b783628
转载于:https://www.cnblogs.com/Weixu-Liu/p/10901169.html