Minimum Spanning Tree (prim)

In this problem, a read undirected graph adjacency matrix (ie, the array shown), and the establishment to establish minimum spanning tree of FIG accordance with the above description of the algorithm, and outputs the cost of the minimum spanning tree.

Input
first line of input contains a positive integer n, the total of n vertices FIG. Wherein n is not more than 50.
After each row of n rows of n integers separated by a space, for the first integer j i-th row, if not zero, it indicates the i-th and j-th vertex of vertices directly connected and consideration of the respective the value 0 indicates no direct connection. I and j are equal when the time to ensure that an integer corresponding to 0.
Adjacency matrix input guarantee a symmetric matrix, i.e., the input must FIG undirected graph, and to ensure that only one connected component of FIG.
Output
only an integer, i.e., the total cost of the minimum spanning tree. Note that the output end of the line wrap.
Sample input
. 4
0. 4 0 2
2 0. 3. 5
. 4. 3. 1 0
0 0. 1. 5
sample output
. 6
Prim (add):

#include<cstdio>
#include<cstring>
#include<iostream> 
using namespace std; 
int map[60][60],book[60],dis[60];
int main()
{
	int n;
	while(cin>>n)
	{
	 memset(book,0,sizeof(book));
	 for(int i=0;i<n;i++)
	  for(int j=0;j<n;j++)
	  {
	  	cin>>map[i][j];
	  	if(i!=j&&map[i][j]==0)
	  	 map[i][j]=0x3f3f3f3f;
	  }
	 for(int i=0;i<n;i++)
	  dis[i]=map[0][i];
	 book[0]=1;
	 int count=1,date,sum=0;
	 while(count<n)
	 {
	 	count++;
	 	int minn=0x3f3f3f3f;
	 	for(int i=0;i<n;i++)
	 	 if(book[i]==0&&dis[i]<minn)
	 	  minn=dis[i],date=i;
	 	book[date]=1;
	 	sum+=dis[date];
	 	for(int i=0;i<n;i++)
	 	 if(book[i]==0&&dis[i]>map[date][i])
	 	  dis[i]=map[date][i];
	 }
	 cout<<sum<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43540515/article/details/92073361