84?

P3366 【模板】最小生成树

kevin4 @ 2023-10-07 21:18:05

#include<bits/stdc++.h>
using namespace std;
int read() {
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9') {
        if(c=='-') f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+(c^48),c=getchar();
    return x*f;
}
struct Edge {
    int u,v,w;
} edge[200005];
int fa[5005],n,m,ans,eu,ev,cnt;
bool cmp(Edge a,Edge b) {
    return a.w<b.w;
}
int find(int x) {
    while(x!=fa[x]) x=fa[x]=fa[fa[x]];
    return x;
}
void kruskal() {
    sort(edge,edge+m,cmp);
    for(int i=0; i<m; i++) {
        eu=find(edge[i].u), ev=find(edge[i].v);
        if(eu==ev) {
            continue;
        }
        ans+=edge[i].w;
        fa[ev]=eu;
        if(++cnt==n-1) {
            break;
        }
    }
}
int main() {
    n=read(),m=read();
    for(int i=1; i<=n; i++) {
        fa[i]=i;
    }
    for(int i=0; i<m; i++) {
        edge[i].u=read(),edge[i].v=read(),edge[i].w=read();
    }
    kruskal();
    printf("%d",ans);
    return 0;
}

by Jim_Franklin @ 2023-10-07 21:23:32

如果该图不连通则输出 orz


by houluyu @ 2023-10-07 21:24:22

find错了


by kevin4 @ 2023-10-07 21:29:24

@dare_ 但我while了啊


by kevin4 @ 2023-10-07 21:33:58

@Jim_Franklin 谢谢


|