MST with Ali
unknown
c_cpp
10 months ago
1.0 kB
9
Indexable
// Alir3za.Zar3 -> Shiraz , Iran
#include <bits/stdc++.h>
using namespace std;
#define loop(i,l,r) for (int i=l; i<=r; i+=1)
#define arc(i,r,l) for (int i=r; i>=l; i-=1)
#define Turbo_In_Out ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N = 2e5+10;
int n,m,K[N],rnk[N]; // Kruskal's MST
vector<int> q;
int e_id[N][2]; vector<pair<int,int>> e;
int root (int v)
{ return (K[v]==v ? v : (K[v]=root(K[v]))); }
bool Union (int v , int u)
{ if ((v=root(v)) == (u=root(u))){ return false; }
if (rnk[v]<rnk[u]){ swap(v,u); }
rnk[v]+=(rnk[u]==rnk[v]); K[u]=v;
return true;
}
signed main()
{ Turbo_In_Out
cin >> n >> m;
loop(v,1,n){ rnk[v]=0; K[v]=v; }
loop(i,1,m){ int u,v,w;
cin >> u >> v >> w;
e_id[i][0]=v; e_id[i][1]=u;
e.push_back({w,i});
} sort(e.begin(),e.end());
long long out = 0;
for (auto [w,id] : e){
int u=e_id[id][0] , v=e_id[id][1];
if (Union(u,v)){ out += w; }
} cout << out << endl;
}Editor is loading...
Leave a Comment