Title Description:
N Point M edge of the forward connected graph, each edge has a weighted value, the minimum 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 digits per line s E W, respectively, representing the 2 vertices and weights of the M-bar. (1 <= S, E <= n,1 <= W <= 10000)
OutPut
Outputs the sum of weights for all edges of the minimum spanning tree.
Input Example
9 141 2 42 3 83 4 74 5 95 6 106 7 27 8 18 9 72 8 113 9 27 9 63 6 44 6 141 8 8
Output Example
37 Topic Analysis: The prim algorithm, selects the shortest segment each time, and will produce the shortest segment point, pulls into the smallest spanning tree sequence, until all n points enter the sequence. AC Code:/** * 1, minimum spanning tree prim algorithm (2015.1.1) * 2, Kruskal algorithm */#include <iostream> #include <cstdio> #include <map># include<cstring> #include <string> #include <algorithm> #include <queue> #include <vector > #include <stack> #include <cstdlib> #include <cctype> #include <cstring> #include <cmath >using namespace Std;const int inf=0x3f3f3f3f;int g[1001][1001];//adjacency matrix int vis[1001],lowc[1001];int Prim (int G[][ 1001],int n) {int i,j,p,minc,res=0; memset (vis,0,sizeof (VIS)); vis[1]=1;//from 1 access for (i=2;i<=n;i++) lowc[i]=g[1][i]; for (i=2;i<=n;i++) {minc=inf; p=-1; for (j=1;j<=n;j++) {if (vis[j]==0&&lowc[j]<minc) {minc=lowc[j]; p=j; }}//cout<<minc<<endl; if (inf==minc) return-1;//original image is not connected to res+=minc; Vis[p]=1; for (j=1;j<=n;j++) {//update lowc[] if (Vis[j]==0&&lowc[j]>g[p][j]) {lowc[j]=g[p][j];}}} return res;} int main () {int n,m; while (cin>>n>>m) {int x,y,w; memset (g,inf,sizeof (G));//The right to record all edges first is INF for (int i=1;i<=m;i++) {cin>>x>>y>>w; G[x][y]=g[y][x]=w; cout<<g[x][y]<<endl; }//int Res=prim (n); Cout<<prim (g,n) <<endl; }return 0;}
51nod1212 Graph minimum Spanning tree (Prim)