图论-kruskal算法-稀疏图

#include
#include
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;ii;
    sort(E,E+m,cmp);
    for(int i=0;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"%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
 */

 

转载于:https://www.cnblogs.com/zuimeiyujianni/p/8848677.html

你可能感兴趣的:(图论-kruskal算法-稀疏图)