Code:
#include<bits/stdc++.h> #define ll long long #define maxn 200004 using namespace std; void setIO(string s) { string in=s+".in"; freopen(in.c_str(),"r",stdin); } int n,m; int p[maxn],tag[maxn]; void init() { for(int i=0;i<maxn;++i) p[i]=i; } int find(int x) { return p[x]==x?x:p[x]=find(p[x]); } struct Edge { int u,v,c; }ed[maxn]; bool cmp(Edge a,Edge b) { return a.c>b.c; } int main() { // setIO("input"); init(); scanf("%d%d",&n,&m); for(int i=1;i<=m;++i) scanf("%d%d%d",&ed[i].u,&ed[i].v,&ed[i].c); sort(ed+1,ed+1+m,cmp); ll ans=0; for(int i=1;i<=m;++i) { int a=find(ed[i].u), b=find(ed[i].v); if(a!=b&&(!tag[a]||!tag[b])) ans+=1ll*ed[i].c, tag[a]|=tag[b], p[b]=a; else if(a==b && !tag[a]) ans+=1ll*ed[i].c, tag[a]=1; } printf("%I64d\n",ans); return 0; }
原文地址:https://www.cnblogs.com/guangheli/p/11263392.html
时间: 2024-11-03 02:04:12