1258

来源:互联网 发布:win7 32位 tensorflow 编辑:程序博客网 时间:2024/05/29 18:45
#include <cstdio>#include <algorithm>using namespace std;class disjset{public:disjset(){memset(mem, -1, sizeof(mem));}int find(const int x){if(mem[x] < 0){return x;}else{mem[x] = find(mem[x]);return mem[x];}}void unionset(const int root1, const int root2){if(mem[root2] < mem[root1]){mem[root1] = root2;}else{if(mem[root1] == mem[root2]){--mem[root1];}mem[root2] = root1;}}private:int mem[100];};struct edge{int u, v, heavy;void set(const int _u, const int _v, const int _h){u = _u;v = _v;heavy = _h;}friend bool operator < (const edge &x, const edge &y);};inline bool operator < (const edge &x, const edge &y){return x.heavy < y.heavy;}int n, g[100][100], ans;edge edges[4500];int edge_num;void matrix2edges(){edge_num = 0;for(int i = 0; i < n; ++i){for(int j = i + 1; j < n; ++j){edges[edge_num].set(i, j, g[i][j]);++edge_num;}}}bool input(){if(EOF == scanf("%d", &n)){return false;}for(int i = 0; i < n; ++i){for(int j = 0; j < n; ++j){scanf("%d", &g[i][j]);}}matrix2edges();return true;}void kruskal(){ans = 0;disjset us;sort(edges, edges + edge_num);for(int i = 0; i < edge_num; ++i){const int uset = us.find(edges[i].u), vset = us.find(edges[i].v);if(uset == vset){continue;}ans += edges[i].heavy;us.unionset(uset, vset);}}int main(){while(input()){kruskal();printf("%d\n", ans);}return 0;}