hdu 1102 Constructing Roads(Prim最小生成树)

/* Author: ACb0y Date: 2010-9-14 Type: MST ProblemId: hdu 1102 Constructing Roads Result: AC */ #include <iostream> using namespace std; #define inf 99999999 int n; int q; int g[110][110]; int vis[110]; int d[110]; void MST() { int i, j; for (i = 1; i <= n; i++) { d[i] = g[1][i]; } memset(vis, 0, sizeof(vis)); d[1] = 0; int ans = 0; for (i = 1; i <= n; i++) { int Min = inf; int pos = -1; for (j = 1; j <= n; j++) if (!vis[j]) { if (d[j] < Min) { Min = d[j]; pos = j; } } vis[pos] = 1; ans += Min; for (j = 1; j <= n; j++) if (!vis[j]){ if (g[pos][j] < d[j]) { d[j] = g[pos][j]; } } } cout << ans << endl; } int main() { #ifndef ONLINE_JUDGE freopen("1102.txt", "r", stdin); #endif while (cin >> n) { int i, j; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { int temp; cin >> g[i][j]; } } cin >> q; for (i = 1; i <= q; i++) { int a, b; cin >> a >> b; g[a][b] = g[b][a] = 0; } MST(); } return 0; }

你可能感兴趣的:(2010)