最小生成树(kruskal+并查集实现)

题目大意如下:

最小生成树(kruskal+并查集实现)_第1张图片

求上图中带权图的最小生成树?

具体实现(C++):

#include <iostream>
#include <algorithm>
#include <stdio.h>
#define  M 9999
#define N 6
using namespace std;
int set[N] = {0,1,2,3,4,5};
int edge[N][N] = {{0,6,1,5,M,M},{6,0,5,M,3,M},{1,6,0,5,6,4},{5,M,5,0,M,2},{M,3,6,M,0,6},{M,M,4,2,6,0}};

int find(int x)
{
    int r;
    r = x;
    while(r != set[r])
        r = set[r];
    return r;//x's root
}

//合并x,y所在的集合
void merge(int x, int y){
    int fx,fy;
    fx = find(x);
    fy = find(y);
    if(fx != fy)
        set[fx] = fy;
}

int main()
{
    int i,j,k,min,mini,minj,num,x,y;
    num = 0;

    while(num < N-1)
    {
        min = M, mini = 0, minj = 0;

        for(i = 0; i < N; i++)
            for(j = i+1; j < N; j++ )
            {
                x = find(i);
                y = find(j);
                if((min > edge[i][j])&&(x != y))
                {
                    min = edge[i][j];
                    mini = i;
                    minj = j;
                }
            }
        num++;
        merge(mini,minj);
        cout<<"第"<<num<<"条边:from "<<(mini+1)<<" to "<<(minj+1)<<" 边长度为:"<<min<<endl;
    }
    return 0;
}

运行结果:

你可能感兴趣的:(最小生成树(kruskal+并查集实现))