kruskalRE4个点求解

P3366 【模板】最小生成树

Respects_H @ 2022-07-24 22:12:38

#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define AM 100000000
#define MOD 8011200
int n,m,t[AM];
struct Edge{
    int u,v,w;
    bool operator<(const Edge& b) const{
        return w<=b.w;
    }
};
std::vector<Edge> edges;
void add(int u,int v,int w){
    edges.push_back({u,v,w});
}
int f[AM],cnt;
void init(int x){
    for(int i=1;i<=x;i++)
        f[i]=i;
}
int find(int x){
    return (f[x]==x?x:f[x]=find(f[x]));
}
void merge(int x,int y){
    f[find(x)]=find(y);
}
bool judge(int x,int y){
    return find(x)==find(y);
}
int id[AM],od[AM];
int kruskal(){
    int res=0;
    std::sort(edges.begin(),edges.end());
    for(Edge e:edges){
        if(!judge(e.u,e.v)){
            merge(e.u,e.v);
            cnt++;
            res+=e.w;

        }
    }
    return res;
}
int main(){
    scanf("%d %d",&n,&m);
    init(n);
    int u,v,w;
    for(int i=1;i<=m;i++){
        scanf("%d %d %d",&u,&v,&w);
        add(u,v,w);
    }
    int ans=kruskal();
    if(cnt==n-1)
        printf("%d",ans);
    else
        printf("orz");
    return 0;
}

by Respects_H @ 2022-07-24 22:14:12

在#4,#8,#9,#10RE了


by TheSky233 @ 2022-07-24 22:15:45

struct Edge{
    int u,v,w;
    bool operator<(const Edge& b) const{
        return w<=b.w;
    }
};

重载运算符不能写 <=,应该是 <


by Respects_H @ 2022-07-24 22:20:27

谢谢大佬


by WHAT??? @ 2023-04-06 16:43:28

我也是这个原因 我吐了


|