首页 > 代码库 > hdu 1102 Constructing Roads

hdu 1102 Constructing Roads

题目:

        链接:点击打开链接

题意:

        求需要修建的公路的最短长度。

算法:

思路:

        prim最小生成树

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAX 100000000
#define MAXN 110

int map[MAXN][MAXN];
int low[MAXN];
int vis[MAXN];
int n,m;

void prim()
{
    int k,pos,minn;
    int result = 0;
    memset(vis,0,sizeof(vis));
    pos = 1;
    vis[pos] = 1;
    for(int i=1; i<=n; i++)
    {
        if(i != pos)
            low[i] = map[pos][i];
    }
    for(int i=1; i<n; i++)
    {
        minn = MAX;
        for(int j=1; j<=n; j++)
        {
            if(!vis[j] && minn > low[j])
            {
                minn = low[j];
                pos = j;
            }
        }
        result += minn;
        vis[pos] = 1;
        for(int j=1; j<=n; j++)
        {
            if(!vis[j] && map[pos][j] < low[j])
                low[j] = map[pos][j];
        }
    }
    printf("%d\n",result);
}

int main()
{
    //freopen("input.txt","r",stdin);
    int a,b,c;
    while(scanf("%d",&n) != EOF)
    {
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
            {
                scanf("%d",&a);
                map[i][j] = a;
            }
        }
        scanf("%d",&m);
        for(int i=1; i<=m; i++)
        {
            scanf("%d%d",&b,&c);
            map[b][c] = map[c][b] = 0;
        }
        prim();
    }
    return 0;
}