码迷,mamicode.com
首页 > 其他好文 > 详细

最小生成树【模板】

时间:2015-05-03 00:51:15      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

Kruskal算法

struct Edge  
{  
    int from;  
    int to;  
    int w;  
};  

Edge Edges[200200];  

int father[200200],N,M;  

int find(int x)  
{  
    if(x != father[x])  
        father[x] = find(father[x]);  
    return father[x];  
}  

int cmp(Edge a,Edge b)  
{  
    return a.w < b.w;  
}  

int Kruskal()  
{  
    int a,b,ans = 0,k = 0;  
    for(int i = 0; i < M; i++)  
    {  
        a = find(Edges[i].from);  
        b = find(Edges[i].to);  
        if(a != b)  
        {  
            ans += Edges[i].w;  
            father[b] = a;  
            k++;  
            if(k == N-1)  
                break;  
        }  
    }  
    return ans;  
}  
//初始化
    for(int i = 0; i < N; i++)  
        father[i] = i;  
    Sum = 0;  
    for(int i = 0; i < M; i++)  
    {  
        scanf("%d%d%d",&x,&y,&w);  
        Edges[i].from = x;  
        Edges[i].to = y;  
        Edges[i].w = w;  
        Sum += w;  
    }  
    sort(Edges,Edges+M,cmp);  
    int ans = Kruskal();  

Prim算法

int G[110][110],vis[110],low[110];  

void Prim(int N)  
{  
    memset(vis,0,sizeof(vis));  
    int ans = 0;  
    vis[1] = 1;  
    int pos = 1;  
    for(int i = 1; i <= N; i++)  
    {  
        if(i != pos)  
            low[i] = G[pos][i];  
    }  

    for(int i = 1; i < N; i++)  
    {  
        int Min = 0xffffff0;  
        for(int j = 1; j <= N; j++)  
        {  
            if(!vis[j] && low[j] < Min)  
            {  
                Min = low[j];  
                pos = j;  
            }  
        }  
        ans += Min;  
        vis[pos] = 1;  
        for(int j = 1; j <= N; j++)  
        {  
            if(!vis[j] && low[j] > G[pos][j])  
                low[j] = G[pos][j];  
        }  
    }  

    printf("%d\n",ans);  

}

//初始化调用
    for(int i = 1; i <= N; i++)  
        for(int j = 1; j <= N; j++)  
            G[i][j] = 0xffffff0;  
    for(int i = 1; i <= n*(n-1)/2; i++)  
    {  
        scanf("%d%d%d",&x,&y,&d);  
        map[x][y] = map[y][x] = d;  
    } 

最小生成树【模板】

标签:

原文地址:http://blog.csdn.net/lianai911/article/details/45445659

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!