难道我少算了一步(28pts)

P3366 【模板】最小生成树

glass_goldfish @ 2024-07-04 15:23:22

#include<bits/stdc++.h>
using namespace std;
struct bian{long long fir,las,qz;}a[1000001];
long long n,x;
bool cmp(bian a,bian b){return a.qz<b.qz;}
long long cnt,ans;
long long fa[1000001];
long long fi(long long p){if(p==fa[p])return p;else return fi(fa[p]);}
int main()
{
    cin>>n>>x;
    for(long long i=1;i<=n;i++)
        fa[i]=i;
    for(long long i=1;i<=x;i++)
        cin>>a[i].fir>>a[i].las>>a[i].qz;
    sort(a+1,a+x+1,cmp);
    for(long long i=1;;i++){
        if(cnt==n-1)break;
        long long fa_fir=fi(a[i].fir);
        long long fa_las=fi(a[i].las);
        if(fa_fir==fa_las)continue;
        fa[a[i].las]=a[i].fir;
        ans+=a[i].qz;
        cnt++;
    }
    cout<<ans;
    return 0;
}//你回答我却不关注你我是狗

by glass_goldfish @ 2024-07-04 16:03:24

@aCssen AC了,感谢!

\tiny {广告}

上一页 |