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
| void Prim(vector<vector<int>> & A, int v) { int n = A.size(); vector<int> U(n, 0); vector<int> closest(n); vector<int> lowcost(n, INT_MAX); int mincost; for (int i = 0; i < n; i++) { closest[i] = v; lowcost[i] = A[v][i]; } U[v] = 1; for (int i = 1; i < n; i++) { mincost = INT_MAX; int u = -1; for (int j = 0; j < n; j++) { if (U[j] == 0 && lowcost[j] < mincost) { mincost = lowcost[j]; u = j; } } if (u == -1 || mincost == INT_MAX) { cout << "图不连通!" << endl; return; } cout << "选择边 (" << closest[u] << ", " << u << ") 权重: " << mincost << endl; U[u] = 1; for (int j = 0; j < n; j++) { if (U[j] == 0 && A[u][j] < lowcost[j]) { lowcost[j] = A[u][j]; closest[j] = u; } } } }
|