POJ1251

//最近在跟着kuangbin大佬疯狂水题 (ORZ)

//Prime算法求最小生成树
#include<iostream>
#include<cstdio>
#include<cstring>
#define inf (0x3f3f3f3f)
using namespace std;
const int maxn = 35;
int Grape[maxn][maxn],d[maxn];
bool vis[maxn];
int n;//节点个数
int pre[maxn];
int Prime()
{
    memset(d,inf,sizeof(d));
    memset(pre,-1,sizeof(pre));
    d[0] = 0;
    while(true)
    {
        int mincost = inf,u = -1;
        for(int v=0;v!=n;++v)
        {
            if(!vis[v]&&d[v]<mincost)//d[v] < inf 则证明有边到达v
            {
                mincost = d[v];
                u = v;
            }
        }
        if(mincost==inf)
            break;
        vis[u] = true;//用 u 节点更新 相邻节点
        for(int v=0;v!=n;++v)
        {
            if(Grape[u][v]!=-1&&!vis[v]&&Grape[u][v]<d[v])
            {
                d[v] = Grape[u][v];
                pre[v] = u;
            }
        }
    }
    int sum = 0;
    for(int v=0;v!=n;++v)
        if(pre[v]!=-1)
            sum += Grape[v][pre[v]];
    return sum;
}
int main()
{
    while(cin>>n&&n)
    {
        memset(Grape,-1,sizeof(Grape));// u ~ v -1表示 不存在边
        memset(vis,false,sizeof(vis));
        char u,v; int num,weight,sum = 0;//权值
        for(int i=0;i!=n-1;++i)
        {
            cin>>u>>num;
            while(num--)
            {
                cin>>v>>weight;
                Grape[u-'A'][v-'A'] = Grape[v-'A'][u-'A'] = weight;
                sum += weight;
            }
        }//建图
        cout<<Prime()<<endl;
    }
}

  

posted on 2019-09-27 23:07  chengyulala  阅读(111)  评论(0编辑  收藏  举报

导航