1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include<iostream> #include<cstdio> #include<algorithm>
using namespace std;
const int N = 100010, M = 200010;
struct Edge { int x, y, c;
bool operator< (const Edge &obj) const { return c < obj.c; } }edges[M];
int p[N];
int n, m, cnt, res;
int find(int x) { if(x != p[x]) p[x] = find(p[x]); return p[x]; }
bool kruskal() { sort(edges, edges + m);
for(int i = 1; i <= n; i++) p[i] = i;
for(int i = 0; i < m; i++) { int x = edges[i].x, y = edges[i].y, c = edges[i].c; int a = find(x), b = find(y); if(a != b) { p[a] = b; res += c; cnt++; } } if(cnt < n - 1) return false; return true; }
int main() { scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++) { int x, y, c; scanf("%d%d%d", &x, &y, &c); edges[i].x = x; edges[i].y = y; edges[i].c = c; }
if(kruskal()) cout << res << endl; else puts("impossible"); return 0; }
|