比赛 板子大赛 评测结果 AAAAAAAAAA
题目名称 通信线路 最终得分 100
用户昵称 秋_Water 运行时间 1.191 s
代码语言 C++ 内存使用 8.31 MiB
提交时间 2025-01-22 15:59:48
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
const int N=5e6+5;
int f[N];
int find(int x){
    if(f[x]==x){
        return x;
    }
    else{
        return find(f[x]);
    }
} 
struct node{
    int x,y,w;
}a[N];
bool cmp(node a,node b){
    return a.w<b.w;
}
int n,cnt,ans;
int main(){
    freopen("mcst.in","r",stdin);
    freopen("mcst.out","w",stdout); 
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            int w;
            cin>>w;
            if(w!=-1){
                a[++cnt].x=i;
                a[cnt].y=j;
                a[cnt].w=w;
            }
        }
    }
    for(int i=1;i<=n;i++) f[i]=i; 
    sort(a+1,a+cnt+1,cmp);
    for(int i=1;i<=cnt;i++){
        int r1=find(a[i].x),r2=find(a[i].y);
        if(r1!=r2){
            ans+=a[i].w;
            f[r2]=r1;
        }
    }
    cout<<ans;
    
    return 0;
}