求21pts

P3366 【模板】最小生成树

c_y_y @ 2023-10-19 13:15:04

#include<bits/stdc++.h>
using namespace std;
const int N=510;
int k[N][N];
struct node{
    int l,r;
    long long num;
}a[N*N];
int fa[N*N];
inline long long read(){
    long long x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();
    return x*f;
}
bool cmp(node x,node y){
    return x.num<y.num;
}
int find(int x){
    if(fa[x]!=x) fa[x]=find(fa[x]);
    return fa[x];
}
void merge(int x,int y){
    int fx=find(x),fy=find(y);
    if(fx!=fy) fa[fx]=fy;
}
int main(){
    ios::sync_with_stdio(false),cout.tie(0);
    int n=read(),m=read();
    for(int i=1;i<=m;i++) a[i].l=read(),a[i].r=read(),a[i].num=read();
    sort(a+1,a+m+1,cmp);
    for(int i=1;i<=n;i++) fa[i]=i;
    int cnt=0;
    long long ans=0;
    for(int i=1;i<=n;i++){
        if(find(a[i].l)==find(a[i].r)) continue;
        ans+=a[i].num;
        merge(a[i].l,a[i].r);
        cnt++;
        if(cnt==n-1) break;
    }
    cout<<ans;
    return 0;
}

by Infinity_Fantasy @ 2023-10-19 13:50:52

for(int i=1;i<=n;i++){
        if(find(a[i].l)==find(a[i].r)) continue;
        ans+=a[i].num;
        merge(a[i].l,a[i].r);
        cnt++;
        if(cnt==n-1) break;
    }

这个循环改成到m,然后判断图不联通就好了


by Infinity_Fantasy @ 2023-10-19 20:13:46

@c_y_y


|