POJ 1258 Agri-Net

很普通的一道关于最小生成树的题,回顾了下kruskal算法的写法。

 

/*Accepted 332K 16MS C++ 987B 2012-07-23 23:03:38 */

#include<cstdio>

#include<cstring>

#include<cstdlib>

#include<algorithm>

using namespace std;

const int MAXN = 105;

int p[MAXN], r[MAXN * MAXN], u[MAXN * MAXN], v[MAXN * MAXN], w[MAXN * MAXN];

int n, m;



int find( int x)

{

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

}



void init()

{

    m = 0;

    int c, i, j;

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

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

        {

            scanf( "%d", &c);

            if( i == j) continue;

            u[m] = i, v[m] = j; w[m ++] = c;

        }

}



int cmp( const int i, const int j)

{

    return w[i] < w[j];

}



int kruskal()

{

    int i, j, e, ans = 0;

    int nx, ny;

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

        p[i] = i;

    for( i = 0; i < m; i ++)

        r[i] = i;

    sort( r, r + m, cmp);

    for( i = 0; i < m; i ++)

    {

        e = r[i];

        nx = find(u[e]), ny = find(v[e]);

        if( nx != ny) {

            p[nx] = ny;

            ans += w[e];

        }

    }

    return ans;

}



int main()

{

    while( scanf( "%d", &n) == 1)

    {

        init();

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

    }

    return 0;

}

 

 

 

你可能感兴趣的:(poj)