首页 > 其他 > 详细

[HDU - 1301]Jungle Roads

时间:2019-08-20 22:17:04      阅读:78      评论:0      收藏:0      [点我收藏+]

建图+最小生成树

#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;
}

 

[HDU - 1301]Jungle Roads

原文:https://www.cnblogs.com/Vikyanite/p/11385462.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!