求助克鲁斯卡尔!!!

P3366 【模板】最小生成树

ko_no_lzx_da @ 2022-03-28 13:11:07

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
const long long N=10000000;
long long cnt;
long long n,m;
long long ans;
long long fa[N];
long long head[N];
struct node{
    long long from,to,v,next;
}edge[N];
void add(long long from,long long to,long long v){
    edge[++cnt].to=to;
    edge[cnt].from=from;
    edge[cnt].v=v;
}
bool cmp(node a,node b){
    return a.v<b.v;
}        
long long find(long long x){
    if(fa[x]!=x){
        return fa[x]=find(fa[x]);
    }else{
        return x;
    }
}
void with(long long x,long long y){
    if(fa[x]!=x)fa[y]=fa[find(x)];
    else fa[y]=fa[x];
}
int main(){
    cin >>n>>m;
    for(long long i=1;i<=n;i++)fa[i]=i;
    for(long long i=1;i<=m;i++){
        long long f,t,v;
        cin >>f>>t>>v;
        add(f,t,v);
        add(t,f,v);
    }
    long long num=0;
    sort(edge+1,edge+1+m,cmp);
    for(long long i=1;i<=m;i++){
        long long x=edge[i].from,y=edge[i].to;
        if(find(x)!=find(y)){
            with(x,y);
            ans+=edge[i].v;
            num++;
        }
        if(num==n-1){
            cout <<ans;
            return 0;
        }
    }
    cout <<"orz";
    return 0;   
}

by Skykguj @ 2022-03-28 13:54:06

首先只用连一次边,然后你这个 kruskal 合并集合写的不对,我给你改过来了,你可以看一下:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
const long long N=10000000;
long long cnt;
long long n,m;
long long ans;
long long fa[N];
long long head[N];
struct node{
    long long from,to,v,next;
}edge[N];
void add(long long from,long long to,long long v){
    edge[++cnt].to=to;
    edge[cnt].from=from;
    edge[cnt].v=v;
}
bool cmp(node a,node b){
    return a.v<b.v;
}        
long long find(long long x){
    if(fa[x]!=x){
        return fa[x]=find(fa[x]);
    }else{
        return x;
    }
}
void with(long long x,long long y){
    fa[x]=y;
}
int main(){
    cin >>n>>m;
    for(long long i=1;i<=n;i++)fa[i]=i;
    for(long long i=1;i<=m;i++){
        long long f,t,v;
        cin >>f>>t>>v;
        add(f,t,v);
    }
    long long num=0;
    sort(edge+1,edge+1+m,cmp);
    for(long long i=1;i<=m;i++){
        long long x=edge[i].from,y=edge[i].to;
        x=find(x),y=find(y);
        if(x!=y){
            with(x,y);
            ans+=edge[i].v;
            num++;
        }
        if(num==n-1){
            cout <<ans;
            return 0;
        }
    }
    cout <<"orz";
    return 0;   
}

by StillEmpty @ 2022-03-28 14:04:48

@Skykguj 他的合并对的,你错了


by CE_WA_TLE @ 2022-03-28 15:54:58

不用建反向边


by Skykguj @ 2022-03-28 15:59:07

@StillEmpty 确实是他错了,他这个过不了。


by ko_no_lzx_da @ 2022-03-28 16:59:20

@CE_WA_TLE 不是无向图吗


by Aa0815 @ 2022-03-29 11:03:58

@ko_no_lzx_da 确实不用,就是建有向边,然后连祖先??(大雾


by ko_no_lzx_da @ 2022-03-29 12:59:20

@Aa0815 懂了谢谢


|