CSES - Shared codeLink to this code:
https://cses.fi/paste/86860ae3e6481ac3405556/
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int INF = 1e9;
vector<pair<int,int>> adj[100005];
int visited[100005];
int cost = 0;
vector<int> dist(100005,INF);
void dfs(int node){
visited[node] = 1;
for(auto it: adj[node]){
if(visited[it.first]==0){
dfs(it.first);
}
}
}
void prismmsp(int node){
dist[node] = 0;
set<pair<int,int>> s;
s.insert({0,node});
while(!s.empty()){
auto x = *(s.begin());
s.erase(x);
int u = x.second;
int w = x.first;
cost += w;
visited[u] = 1;
for(auto it: adj[u]){
if(visited[it.first]==1){
continue;
}
if(dist[it.first]>it.second){
s.erase({dist[it.first],it.first});
dist[it.first] = it.second;
s.insert({dist[it.first],it.first});
}
}
}
}
signed main(){
int n,m;cin>>n>>m;
int a,b,c;
for(int i=0;i<m;i++){
cin>>a>>b>>c;
adj[a].push_back({b,c});
adj[b].push_back({a,c});
}
int ct=0;
for(int i=1;i<=n;i++){
if(visited[i]==0){
ct++;
dfs(i);
}
}
if(ct>1){
cout<<"IMPOSSIBLE"<<"\n";
return 0;
}
memset(visited,0,sizeof(visited));
prismmsp(1);
cout<<cost<<"\n";
}