poj 1258 农场网络 最小生成树

地址 http://poj.org/problem?id=1258

 

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output

28

解答


根据题目的输入格式 还是使用prim比较好

 

#include <iostream>
#include <algorithm>
#include <vector>
#include <memory.h>
using namespace std;

/*
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
*/

const int N = 510;
const int INF = 0x3f3f3f3f;
int g[N][N];
int dist[N];
int st[N];

int n;

int prim()
{
    memset(dist, 0x3f, sizeof dist);
    int res = 0;
    for (int i = 0; i < n; i++) {
        int t = -1;
        for (int j = 1; j <= n; j++) {
            if (st[j] == 0 && (-1 == t || dist[t] > dist[j])) {
                t = j;
            }
        }

        if (i && dist[t] == INF) return INF;
        if (i) res += dist[t];
        st[t] = true;

        for (int j = 1; j <= n; j++) dist[j] = min(dist[j], g[t][j]);
    }

    return res;
}


int main()
{
    while (scanf("%d", &n) != EOF)
    {
        memset(g, 0x3f, sizeof g);
        memset(st, 0, sizeof(st));
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                scanf("%d",&g[i][j]);
            }
        }

        printf("%d\n", prim());
    }


    return 0;
}

 

posted on 2020-06-19 12:14  itdef  阅读(196)  评论(0编辑  收藏  举报

导航