MST pku 1258 Agri-Net

# include <cstdio>

# include <algorithm>



using namespace std;



# define N 100 + 5

# define M 5000 + 5



int n, m;

int p[N];

int u[M], v[M], w[M], r[M];



void read_graph(void)

{

    int tmp;

    m = 0;

    for (int i = 1; i <= n; ++i)

    for (int j = 1; j <= n; ++j)

    {

        scanf("%d", &tmp);

        if (i <= j) continue;

        ++m;

        u[m] = i, v[m] = j, w[m] = tmp;

    }

}



int cmp(int x, int y) {return w[x]<w[y];}

int find(int x) {return x==p[x] ? x:(p[x]=find(p[x]));}

int kruskal(int n, int m)

{

    int ret = 0;

    for (int i = 1; i <= n; ++i) p[i] = i;

    for (int i = 1; i <= m; ++i) r[i] = i;

    sort(r+1, r+1+m, cmp);

    for (int i = 1; i <= m; ++i)

    {

        int e = r[i];

        int x = find(u[e]);

        int y = find(v[e]);

        if (x != y)

        {

            ret += w[e];

            p[y] = x;

        }

    }

    return ret;

}



int main()

{    

    while (~scanf("%d", &n))

    {

        read_graph();

        printf("%d\n", kruskal(n, m));

    }

    

    return 0;

}

你可能感兴趣的:(net)