比赛 板子大赛 评测结果 AAAAAAAAWA
题目名称 通信线路 最终得分 90
用户昵称 zhm 运行时间 0.646 s
代码语言 C++ 内存使用 5.27 MiB
提交时间 2025-01-22 16:26:56
显示代码纯文本
    #include <cstdio>
    #include <algorithm>
    using namespace std; 
     
    const int N = 1501;
    int n;
     
    struct edge {
        int u, v, w;
    } E[N*(N-1)/2];
    int cnt;
     
    bool cmp(edge a, edge b)
    {
        return a.w < b.w;
    }
     
    int fa[N+5];
     
    int find(int x)
    {
        if (fa[x] != x) fa[x] = find(fa[x]);
        return fa[x];
    }
     
    int main(void)
    {
    	freopen("mcst.in", "r", stdin);
    	freopen("mcst.out", "w", stdout); 
    	scanf("%d", &n);
    	for (int i = 1; i <= n; i++)
    		for (int j = 1; j <= n; j++) {
    			int x;
    			scanf("%d", &x);
    			if (x == -1) continue;
    			cnt++;
    			E[cnt].u = i;
    			E[cnt].v = j;
    			E[cnt].w = x;
    		}
    	sort(E+1, E+cnt+1, cmp);
    	for (int i = 1; i <= n; i++)
    		fa[i] = i;
    		
    	long long sum = 0;
    	for (int i = 1; i <= cnt; i++) {
    		int x = find(E[i].u), y = find(E[i].v);
    		if (x != y) {
    		   fa[x] = y;
    		   sum += E[i].w;
    		}
    	}
    	printf("%lld\n", sum);
    	fclose(stdin);
    	fclose(stdout);
        return 0;
    }