int p[N]; // 并查集 father 数组 intfind(int x){ if (p[x] != x) p[x] = find(p[x]); return p[x]; }
voidkruskal(){ sort(edge, edge + m); for (int i = 1; i <= n; i ++) p[i] = i; // 初始化并查集 int res = 0, cnt = 0; // res 存储最小生成树中边权之和 // cnt 存储最小生成树中边数 for (int i = 0; i < m; ++ i) { int a = edge[i].a, b = edge[i].b, w = edge[i].w;
a = find(a), b = find(b); if (a != b){ p[a] = b; res += w; cnt ++; } } if (cnt < n - 1) puts("impossible"); else cout << res << endl; }