Road Reparation(Cses Problem Set)

problelm Statement

const ll nxm = 200000 + 2;vector<pair<ll, pair<ll, ll>>> e;ll par[nxm], _rank[nxm];void disjoinSet(ll n){for (ll i = 1; i <= n; i++)par[i] = i, _rank[i] = 0;}ll findPar(ll x){if (par[x] == x){return x;}return par[x] = findPar(par[x]);}void make_union(ll u, ll v){ll pu = findPar(u);ll pv = findPar(v);if (pu != pv){if (_rank[pu] > _rank[pv]){par[pv] = pu;}else if (_rank[pu] < _rank[pv]){par[pu] = pv;}else{par[pu] = pv;_rank[pv]++;}}}void solve(){ll n, m;cin >> n >> m;REP(i, 0, m){ll x, y, z;cin >> x >> y >> z;e.push_back(mp(z, mp(x, y)));}sort(e.begin(), e.end());ll ans = 0;disjoinSet(n);for (auto i : e){if (findPar(i.ss.ff) != findPar(i.ss.ss)){make_union(i.ss.ff, i.ss.ss);ans += i.ff;}}ll grandParent = findPar(1);REP(i, 2, n + 1){if (findPar(i) != grandParent){cout << "IMPOSSIBLE";return;}}cout << ans;}