最小生成树 prim算法

#include"Graph.h"
#include<assert.h>
#include<iostream>
#include<fstream>
#include<limits>

const int MAX=std::numeric_limits<int>::max();
template<class T,class E>

void prim(int vetex_num,Graph<T,E> &myGraph)
{
	int *visited=new int[vetex_num];
	visited[0]=-1;
	for(int i=1;i<vetex_num;i++)
	{
		visited[i]=myGraph.getWeight(0,i);
	}
	cout<<0<<endl;
	for(int i=1;i<vetex_num;i++)
	{
		int min_index;
		int min_weight=MAX;
		for(int j=0;j<vetex_num;j++)
		{
			if(visited[j]>0&&visited[j]<MAX&&min_weight>visited[j])
			{
				min_index=j;
				min_weight=visited[j];
			}
		}
		 
		if(min_weight==MAX)
			{
				cerr<<"此图不是连通图!"<<endl;
				cerr<<i<<endl;
		}
		else
		{
			cout<<min_index<<endl;
			visited[min_index]=-1;
			for(int k=0;k<vetex_num;k++)
			{
				if(visited[k]!=-1)
				{
				      int temp_weight=myGraph.getWeight(k,min_index);
				      if(temp_weight>0&&temp_weight<visited[k])
					     visited[k]=temp_weight;
				}
			}
		}
	}
}
int main()
{
	ifstream cin("input.txt");
	int vetex_num=100;
	Graph<char,int> myGraph(vetex_num);
	//myGraph.Init(cin);
	myGraph.RandInit();
	
	prim(vetex_num,myGraph);
	return 0;
}

你可能感兴趣的:(最小生成树 prim算法)