AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
    • 吐槽
  • App
  • 登录/注册

Kruskal算法



0


题目链接 (https://www.acwing.com/problem/content/861/)

算法基础课的859题,为什么最后的测试样例过不了,大佬们看看是哪里的问题

错误的代码:

#include<bits/stdc++.h>
using namespace std;

const int N = 1e5+10;
int n,m,f[N];
struct edge{
    int u,v,cost;
}e[2*N];
bool cmp(edge a,edge b){
    return a.cost<b.cost;
}
// int find(int a){
//     if(f[a] != a) f[a] = find(f[a]);
//     return f[a];
// }
int find(int x){
    int c = x;
    while(x!=f[x]){
        x = f[x];
    }
    while(c!=f[c]){
        int t = c;
        c = f[c];
        f[t] = x;
    }
    return x;
}

int krus(){
    int ans = 0,num = 0;
    for(int i=0; i<n; i++)  f[i] = i;
    sort(e,e+m,cmp);
    for(int i=0; i<m; i++){
        int fu = find(e[i].u),fv = find(e[i].v);
        if(fu!=fv){
            f[fu] = fv;
            ans += e[i].cost;
            num++;
            if(num==n-1)    break;
        }
    }
    if(num!=n-1)    return -1;
    else    return ans;
}
int main()
{
    cin>>n>>m;
    for(int i=0; i<m; i++){
        cin>>e[i].u>>e[i].v>>e[i].cost;
    }
    int ans = krus();
    if(ans==-1) cout<<"impossible";
    else    cout<<ans;

    return 0;
}


提问于19天前
初渔
5041


1 个问答



1

显然,这道题点的标号是从1开始的。

回答于19天前
C++大蒟蒻
35293

我来回答
你确定删除吗?

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息