首页 > 代码库 > poj-1251 Jungle Roads

poj-1251 Jungle Roads

题目链接:http://poj.org/problem?id=1251

简单题

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stack>
#include <queue>

using namespace std;
#define INF 10000000

int n, m;
char a[5], b[5];
int c, d;

int map[100][100], dis[100], v[100];

int prim(int n)
{
	int i, j, k, min, sum = 0;
	for (i = 1; i <= n; i++)
		dis[i] = map[1][i];

	memset(v, 0, sizeof(v));
	v[1] = 1;
	dis[1] = 0;

	for (i = 2; i <= n; i++)
	{
		k = 1;
		min = INF;
		for (j = 1; j <= n; j++)
			if (!v[j] && min>dis[j])
			{
				k = j;
				min = dis[j];
			}
		sum += min;
		v[k] = 1;
		for (j = 1; j <= n; j++)
			if (!v[j] && dis[j]>map[k][j])
				dis[j] = map[k][j];
	}
	return sum;
}

int main()
{
	while (scanf("%d",&n) != EOF)
	{
		if (n == 0)
			break;

		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
            {
                if (i != j)
                    map[i][j] = INF;
                else
                    map[i][j]= 0;
            }
        m = n-1;
		while (m--)
		{
			scanf("%s %d",a,&c);
			while (c --)
            {
                scanf("%s %d",b,&d);
                if (map[a[0]-'A'+1][b[0]-'A'+1] > d)
                {
                    map[a[0]-'A'+ 1][b[0]-'A'+1] = d;
                    map[b[0]-'A'+1][a[0]-'A'+1] = d;
                }
            }
		}
		printf("%d\n",prim(n));
	}
	return 0;
}

poj-1251 Jungle Roads