Minimum Spanning Tree
For a given weighted graph G=(V, find the minimum spanning tree (MST) of G
and print total weight of edges belong to the MST.
Input
In the first line, an integer n
denoting the number of vertices in G is given. In the following n lines, a n×n adjacency matrix A which represents G is given. aij denotes the weight of edge connecting vertex i and vertex j. If there is no edge between i and j, aij
is given by -1.
Output
Print the total weight of the minimum spanning tree of G
.
Constraints
- 1≤n≤100
(if aij≠−1
- is a connected graph
Sample Input 1
5 -1 2 3 1 -1 2 -1 -1 4 -1 3 -1 -1 1 1 1 4 1 -1 3 -1 -1 1 3 -1
Sample Output 1
5
Reference
Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.
1 #include<iostream> 2 using namespace std; 3 static const int MAX=100; 4 static const int INFTY=(1<<21); 5 static const int WHITE =0; 6 static const int GRAY=1; 7 static const int BLACK=2; 8 int n,M[MAX][MAX]; 9 int prim() 10 { 11 int u,minv; 12 int d[MAX],p[MAX],color[MAX]; 13 for(int i=0;i<n;i++) 14 { 15 d[i]=INFTY; 16 p[i]=-1; 17 color[i]=WHITE; 18 } 19 20 d[0]=0; 21 while(1) 22 { 23 minv=INFTY; 24 u=-1; 25 for(int i=0;i<n;i++) 26 { 27 if(minv>d[i]&&color[i]!=BLACK) 28 { 29 u=i; 30 minv=d[i]; 31 } 32 } 33 if(u==-1) 34 { 35 break; 36 } 37 color[u]=BLACK; 38 for(int v=0;v<n;v++) 39 { 40 if(color[v]!=BLACK&&M[u][v]!=INFTY) 41 { 42 if(d[v]>M[u][v]) 43 { 44 d[v]=M[u][v]; 45 p[v]=u; 46 color[v]=GRAY; 47 } 48 } 49 } 50 } 51 int sum=0; 52 for(int i=0;i<n;i++) 53 { 54 if(p[i]!=-1) 55 sum+=M[i][p[i]]; 56 57 } 58 return sum; 59 } 60 int main() 61 { 62 cin>>n; 63 for(int i=0;i<n;i++) 64 { 65 for(int j=0;j<n;j++) 66 { 67 int e; 68 cin>>e; 69 M[i][j]=(e==-1)?INFTY:e; 70 } 71 } 72 cout<<prim()<<endl; 73 return 0; 74 }
G

浙公网安备 33010602011771号