The undirected graph of the N-point M-edge, with a weighted value for each edge, to find the smallest spanning tree of the graph. Input
Line 1th: 2 number n,m The middle is separated by a space, N is the number of points, and M is the number of edges. (2 <= N <=, 1 <= M <= 50000)
2-m + 1 lines: 3 number s E W per line, respectively, representing 2 vertices and weights for M-bar edges. (1 <= S, E <= n,1 <= W <= 10000)
Output
Outputs the sum of weights for all edges of the minimum spanning tree.
Input example
9
1 2 4
2 3 8
3 4 7
4 5 9 5 6 6
7 2
7 8 1
8 9 7 2
8 each
3 9
2 7 9 6
3 6 4
4 6
1 8 8
Output example
37
#include <iostream> #include <stdio.h> #include <string.h> const int INF = 0X3F3F3F3F;
using namespace Std;
int map[1010][1010];
int dist[1010];
int vis[1010];
int n,m,x,y,z; void Init () {for (int i = 0;i <= n;i + +) for (int j = 0;j <= n;j + +) map[i][j] = map[j][i] = I
NF;
} int Prim (int v0) {int i,j,sum = 0;
for (int i = 1;i <= n;i + +) {Dist[i] = Map[v0][i];
Vis[i] = V0;
} Vis[v0] =-1;
for (int i = 1;i < N;i + +) {int min = Inf,v =-1;
for (int j = 1;j <= N;j + +) {if (vis[j]! =-1 && dist[j] < min) {v = j;
min = Dist[j];
}} if (v! =-1) {Vis[v] =-1;
Sum + = Dist[v]; for (int j = 1;j <= N;j + +) {if (vis[j]! =-1 && map[v][j] < dist[j]) {dis
T[J] = Map[v][j];
VIS[J] = v;
}
} }} return sum;
} int main () {while (~scanf ("%d%d", &n,&m)) {Init ();
for (int i = 0;i < M;i + +) {scanf ("%d%d%d", &x,&y,&z);
if (Map[x][y] > z) map[x][y] = map[y][x] = Z;
} printf ("%d\n", Prim (1));
} return 0; }