最小生成树-Kruskal算法模板

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define maxn 11
#define maxm 20
struct edge
{
    int u,v,w;
}edges[maxm];
int father[maxn];
int m,n;
void ufset()
{
    for(int i=0; i<=n; i++)
        father[i]=-1;
}
int find(int x)
{
    int s;
    for(s=x; father[s]>=0; s=father[s]);
    while(s!=x)
    {
        int tmp=father[x];
        father[x]=s;
        x=tmp;
    }
    return x;
}
void Union(int R1,int R2)
{
    int r1=find(R1),r2=find(R2);
    int tmp=father[r1]+father[r2];
    if(father[r1]>father[r2])
    {
        father[r1]=r2;
        father[r2]=tmp;
    }
    else
    {
        father[r2]=r1;
        father[r1]=tmp;
    }
}
int cmp(const void *a,const void *b)
{
    edge aa=*(const edge*)a;
    edge bb=*(const edge*)b;
    return aa.w-bb.w;
}
void kruskal()
{
    int sum=0,num=0,u,v;
    ufset();
    for(int i=0; i<m; i++)
    {
        u=edges[i].u;
        v=edges[i].v;
        if(find(u)!=find(v))
        {
            printf("%d %d %d\n",u,v,edges[i].w);
            sum+=edges[i].w;
            num++;
            Union(u,v);
        }
        if(num>=n-1)
            break;
    }
    printf("weight of MST is %d\n",sum);
}
int main()
{
    int u,v,w;
    freopen("1.txt","r",stdin);
    scanf("%d%d",&n,&m);
    for(int i=0; i<m; i++)
    {
        scanf("%d%d%d",&u,&v,&w);
        edges[i].u=u;
        edges[i].v=v;
        edges[i].w=w;
    }
    qsort(edges,m,sizeof(edges[0]),cmp);
    kruskal();
    return 0;
}

  

上一篇:【译】SQL Pivot介绍


下一篇:《数据结构与抽象:Java语言描述(原书第4版)》一2.2.1 可变大小数组