首页 > 技术文章 > 图论-kruskal算法-稀疏图

zuimeiyujianni 2018-04-15 18:18 原文

#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXV = 1000;
const int INF = 0xFFFFFFF;
struct edge{
    int u,v,cost;
}E[MAXV];
bool cmp(edge a,edge b){ return a.cost < b.cost; }
int father[MAXV];
int findFather(int x)
{
    int a = x;
    while(x != father[x]) x=father[x];
    //路径压缩
    while(a != father[a])
    {
        int temp = a;
        a = father[a];
        father[temp]=x;    
    }    
    return x;
} 
int kruskal(int n,int m)
{
    int ans=0,numEdge=0;
    for(int i=0;i<n;i++) father[i]=i;
    sort(E,E+m,cmp);
    for(int i=0;i<m;i++)
    {
        int faU=findFather(E[i].u);
        int faV=findFather(E[i].v);
        if(faU!=faV)
        {
            father[faU]=faV;
            ans += E[i].cost; 
            numEdge++;
            if(numEdge==n-1) break;
        }
    }
    if(numEdge!=n-1) return -1;
    return ans;
}
int main(void)
{
    int m,n;
    scanf("%d%d",&n,&m);
    for(int i=0;i<m;i++) scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].cost);
    int ans = kruskal(n,m);
    printf("%d",ans); 
    return 0;
}
 /*
6 10
0 1 4
0 4 1
0 5 2 
1 2 1
1 5 3
2 3 6
2 5 5 
3 4 5
3 5 4
4 5 3
output:
11
 */

 

推荐阅读