样例过,4RE,1WA,求调

P3366 【模板】最小生成树

Daifendexiaohu @ 2024-07-13 10:43:02

代码如下:

#include<bits/stdc++.h>
using  namespace std;
int bs[5005],n,m,ans=0;
struct edge{
    int u,v,w;
}e[200005];
bool cmp(edge x,edge y){
    return x.w<=y.w;
}
int gf(int x){
    if(bs[x]!=x){
        bs[x]=gf(bs[x]);
    }
    return bs[x];
}
void mg(int x,int y){
    int fx=gf(x),fy=gf(y);
    if(bs[fx]!=bs[fy]){
        bs[fx]=bs[fy];
    }
}
int main(){
    cin>>n>>m;
    for(int i = 1; i <= n; i++){
        bs[i]=i;
    }
    for(int i = 1; i <= m; i++){
        cin>>e[i].u>>e[i].v>>e[i].w;
    }
    sort(e+1,e+m+1,cmp);
    for(int i = 1; i <= m; i++){
        if(gf(e[i].u)!=gf(e[i].v)){
            ans+=e[i].w;
            mg(e[i].u,e[i].v);
        }
    }
    cout<<ans;
    return 0;
}

谢谢!


by Daifendexiaohu @ 2024-07-13 11:02:33

现在过了。


|