zoukankan      html  css  js  c++  java
  • [HDU

    建图+最小生成树

    #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
    ", j, mincost);
                }
            }
           // printf("%d
    ", minid);
            vis[minid] = 1;
            ans += mincost;
            //printf ("%d
    ", ans);
            for (int j = 1; j <= n; j++)
            {
                //printf ("%d %d %d
    ", 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
    ", 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
    ", ans);
    
        }
        return 0;
    }
  • 相关阅读:
    java基础
    HDOJ(HDU).2266 How Many Equations Can You Find (DFS)
    POJ.1416 Shredding Company (DFS)
    HDOJ(HDU).2044-2049 递推专题
    HDOJ(HDU).1045 Fire Net (DFS)
    HDOJ(HDU).1258 Sum It Up (DFS)
    HDOJ(HDU).1241 Oil Deposits(DFS)
    我的ACM参赛故事
    HDOJ(HDU).1035 Robot Motion (DFS)
    HDOJ(HDU).1016 Prime Ring Problem (DFS)
  • 原文地址:https://www.cnblogs.com/Vikyanite/p/11385462.html
Copyright © 2011-2022 走看看