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
| #include <iostream> #include <cstring> using namespace std;
const int N = 510, INF = 0x3f3f3f3f;
int n, m; int dist[N], g[N][N]; bool st[N];
int prim() { memset(dist, 0x3f, sizeof(dist)); dist[1] = 0; int res = 0; for(int i = 0; i < n; i ++ ) { int t = -1; for(int j = 1; j <= n; j ++ ) if(!st[j] && (t == -1 || dist[j] < dist[t])) t = j; res += dist[t]; st[t] = true; for(int j = 1; j <= n; j ++ ) dist[j] = min(dist[j], g[t][j]); } return res; }
int main() { cin >> n >> m; memset(g, 0x3f, sizeof(g)); while(m -- ) { int a, b, c; cin >> a >> b >> c; g[a][b] = g[b][a] = min(g[a][b], c); } int t = prim(); if(t > INF / 2) printf("impossible\n"); else printf("%d\n", t); return 0; }
|