const LL mod=1e9+7; const LL INF=(LL)1e18; using namespace std; struct edge{ int u,v,w; edge(int u,int v,int w):u(u),v(v),w(w){} bool operator < (const edge& x) const{ return w<x.w; } }; int n,m; int p[maxn]; vector<edge>e; int find(int x){ return x==p[x]?x:p[x]=find(p[x]); } int kruskal(){ int ans=0; int cnt=0; sort(e.begin(),e.end()); for(int i=0;i<=n;i++) p[i]=i; for(int i=0;i<m;i++){ int x=find(e[i].u),y=find(e[i].v); if(x!=y){ ans+=e[i].w; p[x]=y; cnt++; } if(cnt==n-1) break; } return ans; } int main(){ // freopen("input.txt","r",stdin); // freopen("ouput.txt","w",sdout); ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); cin>>n>>m; for(int i=1;i<=m;i++){ int u,v,w; cin>>u>>v>>w; e.pb(edge(u,v,w)); } cout<<kruskal()<<endl; return 0; } // 6 10 1 2 6 1 3 1 1 4 5 2 3 5 2 5 3 3 4 5 3 5 6 3 6 4 4 6 2 5 6 6 answer:15
|
近期评论