题意简洁,最小生成树问题。通过Prim算法求解,数据的处理有点困难。

CODE:

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

const int SIZE = 110;
const int INF = 0x0fffffff;

int w[SIZE][SIZE];
int v[SIZE], d[SIZE];
int n;


int Prim(int src)
{
    int i, j;
    int tot = 0;
    memset(v, 0sizeof(v));
    for(i = 1; i <= n ; i++) d[i] = (i == src)? 0:INF;
    for(i = 1; i <= n; i++)              //一次循环找出一条边。第一次不算。
    {
        int x, m = INF;
        for(int y = 1; y <= n; y++) if(!v[y] && m >= d[y]) m = d[x=y];
        v[x] = 1;
        tot += m;
        for(int y = 1; y <= n; y++) if(!v[y]) d[y] <?= w[x][y];
    }
    return tot;
}

void init()
{
    int i, j;
    for(i = 1; i <= SIZE; i++)
    {
        for(j = 1; j <= SIZE; j++)
        {
            w[i][j] = w[j][i] = INF;
        }
    }
    return ;
}


int main()
{
    int i, j;
    int road, cost;
    char beg, link;
    while(~scanf("%d", &n), n)
    {
        init();
        for(i = 1; i < n; i++)
        {
            getchar();
            scanf("%c %d", &beg, &road);
            while(road--)
            {
                scanf(" %c %d", &link, &cost);   //输入的数据处理,%c前面有空格。 
                w[i][link-'A'+1] = w[link-'A'+1][i] = cost;
            }
        }
        printf("%d\n", Prim(1));
    }
    return 0;
}

 

posted on 2012-08-27 16:21  有间博客  阅读(143)  评论(0编辑  收藏  举报