// compile: make data
// run: ./data < data.in
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#ifdef LOCAL
#include <debug/codeforces.h>
#define debug(x...) _debug_print(#x, x);
#define Debug(x...) _debug_print_format(#x, x);
#else
#define debug(x...)
#define Debug(x...)
#endif
template<typename...Args> void print_(Args...args){((cout<<args<<" "),...)<<endl;}
#define rep(i,a,b) for(int i=(a);i<(int)(b);++i)
#define sz(v) ((int)(v).size())
#define print(...) print_(__VA_ARGS__);
#define FIND(a, x) ((find(a.begin(),a.end(),(x))!=a.end())?1:0)
#define cmin(x,...) x=min({(x), __VA_ARGS__})
#define cmax(x,...) x=max({(x), __VA_ARGS__})
#define INTMAX (int)(9223372036854775807)
#define INF (int)(1152921504606846976)
#define double long double
#define int long long
#define MAXN 200010
struct graph {
struct node {
int v, w;
bool operator<(const node &other) const {
return w < other.w;
}
bool operator==(const node &other) const {
return v == other.v && w == other.w;
}
};
vector<vector<node>> e;
int n;
bool directed;
graph(int V, bool D = 0) {
n = V;
e.resize(n);
directed = D;
}
void add_edge(int u, int v, int w = 1) {
e[u].push_back(node{v, w});
}
int kruskal() {
struct DSU {
vector<int> parent, rank;
DSU(int n) {
parent.resize(n);
rank.resize(n);
rep(i, 0, n) parent[i] = i;
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void unite(int x, int y) {
int rx = find(x), ry = find(y);
if (rx == ry) return;
if (rank[rx] < rank[ry]) parent[rx] = ry;
else if (rank[rx] > rank[ry]) parent[ry] = rx;
else parent[ry] = rx, ++rank[rx];
}
};
vector<pair<int, pair<int, int>>> edges;
rep(u, 0, n) {
for (auto [v, w]: e[u]) {
edges.push_back({w, {u, v}});
}
}
sort(edges.begin(), edges.end());
int ans = 0, cnt = 0;
DSU dsu(n);
for (auto [w, p]: edges) {
auto [u, v] = p;
if (dsu.find(u) == dsu.find(v)) continue;
dsu.unite(u, v);
ans += w;
if (++cnt == n-1) break;
}
return (cnt==n-1 ? ans : INF);
}
void graphviz_dump(string filename = "graph.dot") {
ofstream gf; gf.open(filename);
gf << (directed ? "digraph" : "graph") << " {\n";
gf << " "; rep(i, 0, n) gf << i << " ;"[i==n-1]; gf << endl;
string notation = directed ? " -> " : " -- ";
bool weighted = 0;
for (auto es: e) for (auto edge: es) if (edge.w != 1) weighted = 1;
rep(u, 0, n) {
for (auto [v, w]: e[u]) {
if (!directed && u > v) continue;
gf << " " << u << notation << v << (weighted ? " ;\n" : ";\n");
}
}
gf << "}\n";
}
};
int32_t main() {
ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
int n, m; cin >> n >> m;
graph g(n);
rep(i, 0, m) {
int u, v, w; cin >> u >> v >> w;
g.add_edge(u-1, v-1, w);
}
int ans = g.kruskal();
if (ans == INF) cout << "IMPOSSIBLE\n";
else cout << ans << endl;
return 0;
}
No Comments