hdu1301 Jungle Roads (prim)

#include <stdio.h>
#define INF 0x7ffffff
#define MAX 50
//最小生成树,prim算法
int map[MAX][MAX];
int visit[MAX],dist[MAX];

int prim(int n)
{
	int i,j,min,u,sum=0;
	for(i=1;i<=n;i++)
	{
		dist[i]=map[1][i];
		visit[i]=0;
	}
	visit[1]=1;
	dist[1]=0;
	for (i=2;i<=n;i++)
	{
		min=INF;
		u=i;
		for(j=1;j<=n;j++)
			if(!visit[j]&&dist[j]<min)
			{
				min=dist[j];
				u=j;
			}
		visit[u]=1;
		sum+=min;
		for(j=1;j<=n;j++)
			if(!visit[j]&&dist[j]>map[u][j])
				dist[j]=map[u][j];
	}
	return sum;
}

int main()
{
	int n,i,j,x,y,val,num;
	char ch1,ch2;
	while(scanf("%d",&n)&&n)
	{
		for (i=1;i<=n;i++)
		{
			for(j=1;j<=n;j++)
				map[i][j]=map[j][i]=INF;
		}
		for(i=1;i<n;i++)
		{
			getchar();
			scanf("%c %d",&ch1,&num);
			for(j=1;j<=num;j++)
			{
				getchar();
				scanf("%c %d",&ch2,&val);
				x=ch1-'A'+1;//村子序号1--26
				y=ch2-'A'+1;
				map[x][y]=map[y][x]=val;
			}
		}
		printf("%d\n",prim(n));
	}
	return 0;
}

你可能感兴趣的:(hdu1301 Jungle Roads (prim))