图算法总结----Kruskal算法

版权声明:本文为博主原创文章,未经博主允许可以随便转载。 https://blog.csdn.net/liyuanshuo_nuc/article/details/63307969
//
// Created by liyuanshuo on 2017/3/13.
//

#include <bits/stdc++.h>

int r[10010]; //the rank of every side
int u[10010], v[10010], w[10010]; // u, v is the pointer of i-th side of graph, w---weight
int p[10010];  // p-array used to union-find set
int n, m; //n--numbers of nodes m--numbers of sides

//cmp -- function used to sort
int cmp (const int i, const int j )
{
    return w[i] < w[j];
}

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

int Kruskal( )
{
    int ans = 0;
    for (int i = 0; i < n; ++i)
    {
        p[i] = i;
    }
    for (int j = 0; j < m ; ++j)
    {
        r[j] = j;
    }
    std::sort( r, r+m, cmp);
    for (int k = 0; k < m ; ++k)
    {
        int e = r[k];
        int x = find (u[e]);
        int y = find (v[e]);
        if( x != y )
        {
            ans += w[e];
            p[x] = y;
        }
    }
    return ans;
}

猜你喜欢

转载自blog.csdn.net/liyuanshuo_nuc/article/details/63307969
今日推荐