POJ 1258 (典型Kruskal算法)

本文详细介绍了使用最小生成树算法解决特定问题的过程。通过具体的代码实现,展示了如何通过比较节点间权重来构建一棵树,确保这棵树包含图中的所有顶点且没有环,并且总权重最小。特别关注了如何避免形成环路以及如何找到连接所有顶点的最小代价路径。

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

样例错了

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<cstdlib>
#include<list>
#include<queue>
#define mm(a,b) memset(a,b,sizeof(a))
#define ACCELERATE (ios::sync_with_stdio(false),cin.tie(0))
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define MAXNL 0x3fffffff
#define MAXN 0x3f3f3f3f
using namespace std;

//#define debug

struct node{
    int u,v,w;
};

bool cmp(const node& a,const node& b){
    return a.w<b.w;
}

int fa[1005];

int get_father(int x){
    return fa[x]=fa[x]==x?x:get_father(fa[x]);
}

int main()
{
    #ifdef debug
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif // debug

    node mmp[15005];
    node p[15005];
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=0;i<m;i++){
            scanf("%d%d%d",&mmp[i].u,&mmp[i].v,&mmp[i].w);
        }
        sort(mmp,mmp+m,cmp);
        int maxn=-1;
        int ans=0;
        for(int i=1;i<=n;i++) fa[i]=i;
        int cnt=0;
        for(int i=0;i<m;i++){
            if(get_father(mmp[i].u)!=get_father(mmp[i].v)){
                ans+=mmp[i].w;
                fa[fa[mmp[i].u]]=fa[mmp[i].v];
                p[cnt].u=mmp[i].u,p[cnt].v=mmp[i].v;
                cnt++;
                if(cnt==n-1){
                    maxn=mmp[i].w;
                    break;
                }
            }
        }
        printf("%d\n",maxn);
        printf("%d\n",cnt);
        for(int i=0;i<cnt;i++){
            printf("%d %d\n",p[i].u,p[i].v);
        }
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值