Kruskal14分求助

P3366 【模板】最小生成树

zhuxinlei @ 2024-03-17 08:41:58

#include<bits/stdc++.h>
using namespace std;
int n,m,fa[5001],i,ans=-1;
bool f=false;
struct node{
    int x,y,z;
}b[200001];
bool cmp(node aa,node bb){
    if(aa.z!=bb.z) return aa.z<bb.z;
}
int find(int x){
    if(fa[x]==x) return x;
    else return find(fa[x]);
}
int main(){
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++){
        fa[i]=i;
    }
    for(i=1;i<=m;i++){
        scanf("%d%d%d",&b[i].x,&b[i].y,&b[i].z);
    }
    sort(b+1,b+m+1,cmp);
    i=1;
    while(i<=m){
        if(i==n){
            break;
        }
        if(find(b[i].x)!=find(b[i].y)){
            fa[b[i].y]=find(b[i].x);
            ans+=b[i].z;
            i++;
        }
    }
    if(ans<0) printf("org");
    else printf("%d",ans+1);
    return 0;
}

记录


by QWQ_HY_DFX @ 2024-03-17 09:13:45

首先,\text{cmp}不是这么写的,把你的\text{if}删了

其次,ans可以设为0,用i判断...

最后,你\text{while}循环的判断条件是什么鬼,没猜错的话你是\LARGE\text{TLE}吧,下标和数量要分开存...你这样子直接结束不了循环


by QWQ_HY_DFX @ 2024-03-17 09:14:34

@zhuxinlei


by springisnotcoming @ 2024-07-14 14:17:48

《cout << "org"》

@zhuxinlei


|