Hint
This is exactly an MST. Prim's algorithm from the lesson; if at the end not all n buildings are in the tree, the graph is not connected.
Solution (C++)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; i++) {
int u, v, c;
cin >> u >> v >> c;
graph[u].push_back({v, c});
graph[v].push_back({u, c});
}
vector<bool> inTree(n + 1, false);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, 1});
long long cost = 0;
int added = 0;
while (!pq.empty()) {
auto [c, v] = pq.top();
pq.pop();
if (inTree[v]) continue;
inTree[v] = true;
cost += c;
added++;
for (auto [x, w] : graph[v]) if (!inTree[x]) pq.push({w, x});
}
if (added < n) cout << "IMPOSSIBLE" << endl;
else cout << cost << endl;
return 0;
}