Hdu 1102 - Constructing Roads

Prim算法,简单的 最小生成树

 

题意:在n个村庄里修路,使得任意两个村庄都连通,求最少几条路能完成。

 

 

 

AC代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int map[105][105], v[105];
int n, min, sum, flag;
const int max = 0x7ffffff;

int MinTree(int n)
{
    int i,j;
    memset(v, 0, sizeof(v));
    v[0] = 1;
    sum = 0;
    for(i=1; i<n; i++)
    {
        min = max;
        //find the min vertex in whole graph
        for(j=0; j<n; j++)
        {
            if(!v[j] && map[0][j]<min)
            {
                min = map[0][j];
                flag = j;
            }
        }
        sum+=min;
        v[flag] = 1;
        for(j=0; j<n; j++)
        {
            if(!v[j] && map[flag][j]<map[0][j])
            {
                map[0][j] = map[flag][j];
            }
        }
    }
    return sum;
}

int main()
{
    int i,j,k,x,y,ans;
    while(~scanf("%d",&n))
    {
        memset(map, 0, sizeof(map));
        for(i=0; i<n; i++)
        {
            for(j=0; j<n; j++)
            {
                scanf("%d",&map[i][j]);
                if(i==j) map[i][j] = 0;
            }
        }
        scanf("%d",&k);
        for(i=0; i<k; i++)
        {
            scanf("%d %d",&x,&y);
            map[x-1][y-1] = map[y-1][x-1] = 0;
        }

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


 

 

 

你可能感兴趣的:(Hdu 1102 - Constructing Roads)