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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <bits/stdc++.h> using namespace std; struct Kurskal{ struct Edge{ int u,v,len; bool operator < (const Edge &e) const{ return len<e.len; } }; int n,m; vector<Edge> edges; vector<int> fa; Kurskal(int n,int m) : n(n),m(m),fa(n+1) { for(int i=1;i<=n;++i) fa[i]=i; } void addEdge(int u,int v,int len){ edges.push_back({u,v,len}); } int fnd(int x){ if(fa[x]!=x) fa[x]=fnd(fa[x]); return fa[x]; } bool merge(int x,int y){ int fx=fnd(x),fy=fnd(y); if(fx==fy) return false; fa[fy]=fx; return true; } int run(){ sort(edges.begin(),edges.end()); int ans=0,cnt=0; for(int i=0;i<m;++i){ if(merge(edges[i].u,edges[i].v)){ ans+=edges[i].len; cnt++; } if(cnt==n-1) break; } if(cnt==n-1) return ans; return -1; } }; int main(){ ios::sync_with_stdio(false); cin.tie(0); int n,m; cin>>n>>m; Kurskal kurs(n,m); for(int i=0;i<m;++i){ int u,v,w; cin>>u>>v>>w; kurs.addEdge(u,v,w); } int ans=kurs.run(); if(ans!=-1) cout<<ans; else cout<<"orz"; return 0; }
|