voidjoin(int x, int y)//并查集的合并操作 { int fx = find(x), fy = find(y); if (fx != fy) pre[fx] = fy; }
boolcmp(node x, node y) { return x.w < y.w; }
intmain() { cin >> n >> m; //输入边的信息 for (int i = 0; i < m; i++) cin >> edge[i].from >> edge[i].to >> edge[i].w; //并查集的初始化 for (int i = 0; i <= n; i++) pre[i] = i; sort(edge, edge + m, cmp); //按边的权值排序 for (int i = 0; i < m; i++) //从小到大遍历每条边 { if (used == n - 1) //n个节点的树有n-1条边 break; if (find(edge[i].from) != find(edge[i].to)) { join(edge[i].from, edge[i].to); total += edge[i].w; used++; } } cout << total << endl; //输出生成树的最小权值 return0; }
python实现:
n, m = map(int, input().split()) edge = [] used = 0 total = 0 pre = [i for i inrange(n+1)]
defmyfind(x): if pre[x] == x: return x pre[x] = myfind(pre[x]) return pre[x]
defmyjoin(x, y): fx, fy = myfind(x), myfind(y) if fx != fy: pre[fx] = fy
for i inrange(m): dic = {} dic['from'], dic['to'], dic['w'] = map(int, input().split()) edge.append(dic)
edge.sort(key=lambda x: x['w'])
for elem in edge: if used == n-1: break if myfind(elem['from']) != myfind(elem['to']): myjoin(elem['from'], elem['to']) total += elem['w'] used += 1 print(total) ''' for i in edge: print(i) '''