86pts Kruskal求调,悬棺QAQ

P3366 【模板】最小生成树

icebear233 @ 2024-07-29 22:10:55

#include<bits/stdc++.h>
using namespace std;
int n,m,b,ans;
int fa[50005];
struct node{
    int u,v,w;
}e[200005];
bool cmp(node x,node y){
    return x.w<y.w;
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        fa[i]=i;
    }
    for(int i=1,x,y;i<=m;i++){
        cin>>e[i].u>>e[i].v>>e[i].w;    
    }
    sort(e+1,e+1+m,cmp);
    for(int i=1;i<=m;i++){
        if(b==n-1){
            cout<<ans;
            return 0;
        }
        int x=e[i].u,y=e[i].v,w=e[i].w;
        while(fa[x]!=x){
            x=fa[x];
        }
        while(fa[y]!=y){
            y=fa[y];
        }
        if(x==y){
            continue;
        }
        else{
            fa[y]=x;
            ans+=w;
            b++;
        }
    }
    cout<<"orz";
    return 0;
}

by icebear233 @ 2024-07-29 22:13:39

wa测试点样例

5 4

4 5 1

3 4 2

3 2 3

1 2 4

输出:10


by icebear233 @ 2024-07-29 22:18:19

Cao,为甚吗我一发讨论区求条自己就调好了,把b==n-1放在循环最后就好了。。。。

此贴结


by WaTleZero_pt @ 2024-07-29 22:20:40

《悬棺》


|