POJ - 2421Constructing Roads prim

已连接的两条边权值更新为0,直接prim就可以了。

#include 
#include 
#include 
#include
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define INF 0x3f3f3f3f
#define mem(arr,a) memset(arr,a,sizeof(arr))
#define V 2000+5
#define LL long long int
#define E 320000
#define pow(a) ((a)*(a))
int n, m;
int cost[V][V];
int minCost[V];
int vis[V];
int sum;
void prim(){
    for (int i = 1; i <= n; i++){
        minCost[i] = cost[1][i];
        vis[i] = 0;
    }
    while (1){
        int v = -1;
        for (int i = 1; i <= n; i++){
            if (!vis[i] && (v == -1 || minCost[i] < minCost[v]))v = i;
        }
        if (v == -1)break;
        vis[v] = 1;
        sum += minCost[v];
        for (int i = 1; i <= n; i++){
            if (minCost[i]>cost[v][i])minCost[i] = cost[v][i];
        }
    }
    cout << sum << endl;

}
int main(){
    cin >> n;
    sum = 0;
    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= n; j++){
            cin >> cost[i][j];
        }
    }
    cin >> m;
    for (int i = 1; i <= m; i++){
        int a, b; cin >> a >> b;
        cost[a][b] = cost[b][a] = 0;
    }
    prim();
}

你可能感兴趣的:(最小生成树)