poj1251

裸求最小生成树

#include<iostream>
#define M 102
using namespace std;
int judge[M];
int temp[M];
int map[M][M];
int prim(int n,int v)
{
	
	int i,j,k,min,record,sum;
	sum = 0;
	memset(judge,0,sizeof(judge));
	judge[v] = 1;
	for(i=1; i<=n; i++)
	{
		temp[i] = map[1][i];
	}
	for(i=1; i<n; i++)
	{	
		min = M;
		for(j=1; j<=n; j++)
		{
			if ((min > temp[j]) &&! judge[j])
			{
				min = temp[j];
				v = j;
			}
		}	
		sum += min;
		judge[v] = 1;
		for (j=1; j<=n; j++)
		{
			if ((map[v][j]<temp[j])&&!judge[j])
			{
				temp[j] = map[v][j];
			}
		}
		
	}
	return sum;
	
}
int main(){
	int num,degree,cost,i,j;
	char vertex;
	while(cin>>num){
		if(num == 0)break;
		for(i=1; i<=num; i++) judge[i] = 0;
		for(i=1; i<=num; i++){
			for(int j=1; j<=num; j++){
				map[i][j] = M;
			}
		}
		for(i=1; i<num; i++){
			cin>>vertex>>degree;
			for( j=1; j<=degree; j++){
				cin>>vertex>>cost;
				map[i][vertex-'A'+1] = cost;
				map[vertex-'A'+1][i] = cost;
			}
		}
		cout<<prim(num,1)<<endl;
	}
	return 0;
}

 

你可能感兴趣的:(J#)