1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| bool cmp(Edge a, Edge b) { return a.weight<b.weight; }
int fa[maxn]; int findroot(int x) { return fa[x] == x ? x : fa[x] = findroot(fa[x]); } void Merge(int x, int y) { x = findroot(x); y = findroot(y); fa[x] = y; }
int main() { int n,m; cin>>n>>m; for(int i=1;i<=n;i++){ fa[i]=i; } for(int i=1,u,v,w;i<=m;i++) { cin>>u>>v>>w; addEdge(u,v,w); addEdge(v,u,w); } sort(edge, edge+m*2, cmp); int ans=0; for(int i=0;i<m*2;i++) { if(findroot(edge[i].from)!=findroot(edge[i].to)) { Merge(edge[i].from,edge[i].to); ans+=edge[i].weight; } } cout<<ans; return 0; }
|