Link to this code: https://cses.fi/paste/a159913dfaae3e06681a7b/
#include<iostream>
#include<array>
#include<vector>
#include<algorithm>
using namespace std;
class DSU{
   int numCities;
   vector<int>parent,weight;
    int find(int city){
       if(parent[city]==city)return city;
       return parent[city]=find(parent[city]);
    }
  public:
    DSU(int n){
      numCities=n-1;
      parent.resize(n);
      weight.resize(n,1);
      for(int i=1;i<n;i++)parent[i]=i;
    } 
    bool Union(int a,int b){
    a=find(a);
    b=find(b);
    if(a==b)return false;
    if(weight[a]>weight[b])swap(a,b);
    weight[b]+=weight[a];
    parent[a]=b;
    return true;
    }
    bool isPossible(){
    return numCities==weight[find(1)];
    }
};
int main(){  
  int n,m;
  long long cost=0;
  cin>>n>>m;
  DSU dsu(n+1);
  vector<array<long long,3>>cities(m);
  for(auto &city:cities){
    m=3;
    while(m--)cin>>city[m]; 
  }
  sort(cities.begin(),cities.end());
  for(auto &city:cities){
   if(dsu.Union(city[2],city[1])){
      cost+=city[0];
   }
  }
  if(dsu.isPossible()){
    cout<<cost<<"\n";
  }else{
  cout<<"IMPOSSIBLE\n";
  }
  return 0;
}