Loading

[HDU - 1301]Jungle Roads

建图+最小生成树

#include <cstdio>
#include <cstring>
#include <algorithm>
#define maxn 28
#define inf 100000
using namespace std;
int graph[maxn][maxn];
int vis[maxn];
int cost[maxn];
int prim(int n)
{
    int ans = 0;
    int minid = 0;
    for (int i = 1; i <= n; i++)
    {
        cost[i] = graph[1][i];
        vis[i] = 0;
    }

    vis[1] = 1;
    cost[1] = 0;
    for (int i = 1; i <= n-1; i++)
    {
        int mincost = inf;
        for (int j = 1; j <= n; j++)
        {
            if (!vis[j] && cost[j] < mincost)
            {
                mincost = cost[j];
                minid = j;
                //printf("%d %d\n", j, mincost);
            }
        }
       // printf("%d\n", minid);
        vis[minid] = 1;
        ans += mincost;
        //printf ("%d\n", ans);
        for (int j = 1; j <= n; j++)
        {
            //printf ("%d %d %d\n", j, cost[j], cost[minid] + graph[minid][j]);
            if (!vis[j] && cost[j] > graph[minid][j])
            {
                cost[j] = graph[minid][j];
                //printf ("%d", cost[i]);
            }
        }
    }
    return ans;

}

int main()
{
    int n, m;
    while(~scanf("%d", &n))
    {
        if (!n)
            break;

        fill(graph[0], graph[0] + maxn*maxn, inf);
        for (int i = 1; i <= n-1; i++)
        {
            char alpha[2];
            int num;
            scanf("%s %d", alpha, &num);
            //printf("%s %d\n", alpha, num);
            for (int j = 1; j <= num; j++)
            {
                int cost;
                char alphb[2];
                scanf("%s %d", alphb, &cost);
                graph[alpha[0]-'A'+1][alphb[0]-'A'+1] = cost;
                graph[alphb[0]-'A'+1][alpha[0]-'A'+1] = cost;
            }
        }
        int ans = prim(n);
        printf("%d\n", ans);

    }
    return 0;
}

 

posted @ 2019-08-20 20:35  ViKyanite  阅读(117)  评论(0编辑  收藏  举报