POJ 2421 Constructing Roads

本文介绍了一种使用Kruskal算法求解最小生成树(MST)的方法。通过输入边的权重并进行排序,该算法能有效地找出图中所有顶点连接起来且权重最小的树形结构。具体实现包括了并查集来避免形成环路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最小生成树,用Kruskal。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct edge
{
    int u;
    int v;
    int w;
};
edge e[10000];
int le,n,uset[110];
int root(int x)
{
    if (uset[x] == x)
        return x;
    else
    {
        uset[x]=root(uset[x]);
        return uset[x];
    }
}
bool cmp(edge a,edge b)
{
    return a.w < b.w;
}
int main()
{
    int q,t1,t2,tx,ty,i,j,ans;
    scanf("%d",&n);
    le=0;
    for (i=1; i<=n; i++)
    {
        uset[i]=i;
        for (j=1; j<=n; j++)
        {
            scanf("%d",&t1);
            if (i<j)
            {
                e[le].u=i;
                e[le].v=j;
                e[le].w=t1;
                le++;
            }
        }
    }
    scanf("%d",&q);
    while (q--)
    {
        scanf("%d%d",&t1,&t2);
        tx=root(t1);
        ty=root(t2);
        uset[tx]=ty;
    }
    sort(e,e+le,cmp);
    ans=0;
    for (i=0; i<le; i++)
    {
        tx=root(e[i].u);
        ty=root(e[i].v);
        if (tx != ty)
        {
            uset[tx]=ty;
            ans+=e[i].w;
        }
    }
    printf("%d\n",ans);
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值