裸的最小生成树
输入很蓝瘦
**并查集
int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
找到x在并查集里的根结点,如果两个端点在同一个集合内,find之后两个值就相等了
每次找到权值最小的端点不在同一集合的边 把两个集合合并
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; int fa[33]; struct node { int s, e, d; }l[111]; bool cmp(node x, node y) { if(x.d != y.d) return x.d < y.d; } int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } int main() { while(1) { int n, i, j, x, val, sum = 0, cnt = 0;//cnt是边数 char c; scanf("%d", &n); if(n == 0) break; for(i = 0; i < n - 1; i++) { scanf(" %c", &c); int s = c - 'A' + 1; scanf("%d", &x); for(j = 0; j < x; j++) { scanf(" %c %d", &c, &val); int e = c - 'A' + 1; l[cnt++] = (node){s, e, val}; } } sort(l, l + cnt, cmp); for(int i = 1; i <= n; i++) fa[i] = i; for(int i = 0; i < cnt; i++) { int fs = find(l[i].s), fe = find(l[i].e); if(fs == fe) continue; sum += l[i].d; fa[fs] = fe; } printf("%d ", sum); } return 0; }