#include<iostream>
using namespace std;
const static int MAX = 100;
const static int INFIT = 1000;
const static int WHITE = 0;
const static int GRAY = 1;
const static int BLACK = 2;
int graph[MAX][MAX];
int n;
int prim() {
int color[MAX], p[MAX], d[MAX];
int u;
int minv;
int sum = 0;
for(int i=0; i<n; i++){
color[i] = WHITE;
d[i] = INFIT;
p[i] = -1;
}
d[0] = 0;
color[0] = GRAY;
while(1) {
minv =INFIT;
u = -1;
for(int i=0; i<n; i++) {
if(color[i] != BLACK && d[i] < minv) {
minv = d[i];
u = i;
}
}
if(u == -1) break;
color[u] = BLACK;
for(int i=0; i<n; i++) {
if(color[i] != BLACK && graph[u][i] != INFIT ) {
if(graph[u][i] < d[i]) {
d[i] = graph[u][i];
p[i] = u;
}
}
}
}
for(int i=0; i<n; i++) {
if(p[i] != -1){
sum += graph[p[i]][i];
}
}
return sum;
}
int main() {
cin >> n;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
int e;
cin >> e;
graph[i][j] = (e == -1) ? INFIT : e;
}
}
int s = prim();
cout << s << endl;
return 0;
}
最小生成树(Minimum Spanning Tree)
最新推荐文章于 2022-09-26 23:33:27 发布