N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000) 第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Input示例
9 14 1 2 4 2 3 8 3 4 7 4 5 9 5 6 10 6 7 2 7 8 1 8 9 7 2 8 11 3 9 2 7 9 6 3 6 4 4 6 14 1 8 8
Output示例
37
<span style="font-size:14px;">#include <stdio.h>
#include <iostream>
using namespace std;
#define N 1005
#define INF 0x0f0f0f0f
#define MAX 10001
int n, m;
int vis[N], tmp[N], cost[N][N];
int Prim(){
int k, edge, min_tree = 0;
for(int i = 1; i <= n; ++i){
tmp[i] = cost[1][i];
vis[i] = 0;
}
vis[1] = 1;
for(int i = 1; i <= n - 1; i++){
edge = INF;
for(int j = 1; k <= n; j++){
if(vis[j] == 0 && tmp[j] < edge){
edge = tmp[j];
k = j;
}
}
if(edge > MAX)
return -1;
min_tree += edge;
for(int j = 1; j <= n; ++j){
if(vis[j] == 0 && tmp[j] > cost[k][j])
tmp[j] = cost[k][j];
}
}
return min_tree;
}
int main(){
int a, b, c;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
cost[i][j] = INF;
cost[i][i] = 0;
}
}
for(int i = 1; i <= m; ++i){
scanf("%d%d%d", &a, &b, &c);
cost[a][b] = cost[b][a] = c;
}
int ans = Prim();
printf("%d\n", ans);
return 0;
}</span>