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 77 78 79 80
| #define _CRTSECURE_NOWARNINGS #pragma warning(disable:4996) #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<cctype> #include<algorithm> #include<iostream> #include<queue> #include<stack> #include<vector> #include<map> #include<set> #include<list> using namespace std; #define INF 0x3f3f3f3f #define MAXN 110
int n, m, mp[MAXN][MAXN], vis[MAXN], d[MAXN];
void Initmap(int x) { memset(mp, INF, sizeof(mp)); for (int i = 1; i <= x; i++) mp[i][i] = 0; }
void Prim(int n, int m) { memset(vis, 0, sizeof(vis)); int index = 1; int res = 0; vis[index] = 1; for (int i = 1; i <= n; i++) d[i] = mp[index][i]; for (int i = 1; i < n; i++) { int minn = INF; for (int j = 1; j <= n; j++) { if (!vis[j] && d[j] < minn) { minn = d[j]; index = j; } } if (minn == INF) { printf("Impossible\n"); return; } res += minn; vis[index] = 1; for (int j = 1; j <= n; j++) { if (!vis[j] && d[j] > mp[index][j]) d[j] = mp[index][j]; } } printf("%d\n", res); } int main() {
while (scanf("%d%d", &n, &m) != EOF) { if (!m) break; Initmap(n); for (int i = 1, u, v, w; i <= m; i++) { scanf("%d%d%d", &u, &v, &w); mp[v][u] = min(w, mp[u][v]); mp[u][v] = min(w, mp[u][v]); } Prim(n, m); } return 0; }
|