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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include<iostream> #include<stdio.h> #include<string> #include<queue> #include<cstring> #include<vector> #include<algorithm> #define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0) typedef long long ll; using namespace std; ll n,m; ll f[100020]; ll f2[100020]; struct Edge{ ll u,v,w; }e[200020]; inline int cmp(Edge a,Edge b){ return a.w<b.w; } inline int cmp2(Edge a,Edge b){ return a.w>b.w; } inline ll find(ll x){ return f[x]==0?x:f[x]=find(f[x]); } inline ll find2(ll x){ return f2[x]==0?x:f2[x]=find2(f2[x]); } inline void read(ll &x) { x=0;ll f=0;char ch=getchar(); while(ch<'0'||ch>'9') {f|=(ch=='-');ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} x=f?-x:x; return; } int main(){ read(n);read(m); ll x,y,z; for(int i=1;i<=m;i++){ read(x); read(y);read(z); e[i]=(Edge){x,y,z}; } sort(e+1,e+1+m,cmp); ll cnt=0,sum=0,mx=0; for(int i=1;i<=m;i++){ ll x=find(e[i].u),y=find(e[i].v); if(x!=y){ f[x]=y; cnt++; mx=max(mx,e[i].w); } if(cnt==n-1){ break; } } cnt=0; sort(e+1,e+1+m,cmp2); for(int i=1;i<=m;i++){ ll x=find2(e[i].u),y=find2(e[i].v); if(x!=y&&e[i].w<=mx){ f2[x]=y; cnt++; sum+=e[i].w; } if(cnt==n-1){ printf("%lld\n",sum); break; } } return 0; }
|