hdu1301Jungle Roads

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1301

最小生成树模板题。

代码:

#include <cstdio>
#include <cstring>

#define inf 0x3f3f3f3f
int a[50][50];
int n;
int d[50];
char s[10];
char s1[10];
int ans;
int v[50];

void prim()

{
    for(int i = 1; i <= n; ++i)
        d[i] = a[1][i];
    int cnt = 1;
    v[1] = 1;
    while(cnt < n)
    {
        int Min = inf;
        int k;
        for(int i = 1; i <= n; ++i)
        {
            if(!v[i] && d[i] < Min)
            {
                Min = d[i];
                k = i;
            }


        }
        v[k] = 1;
        ans += d[k];
        ++cnt;
        for(int i = 1; i <= n; ++i)
        {
            if(!v[i] && d[i] > a[k][i])
                d[i] = a[k][i];
        }

    }
}
int main()

{
    while(~scanf("%d",&n),n)
    {
        memset(d,0,sizeof(d));
        memset(v,0,sizeof(v));
        for(int i = 1; i <= n; ++i)
            for(int j = 1; j <= n; ++j)
                a[i][j] = (i == j ? 0 : inf);
        for(int i = 0; i < n - 1; ++i)
        {
            scanf("%s",s);
            int k;
            scanf("%d",&k);
            while(k--)
            {
                scanf("%s",s1);
                int w;
                scanf("%d",&w);
                a[s[0] - 'A' + 1][s1[0] - 'A' + 1] = w;
                a[s1[0] - 'A' + 1][s[0] - 'A' + 1] = w;
            }

        }
        ans = 0;
        prim();
        printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(ACM,Prim)