蓝桥杯才发现图论好久不碰了,果然全忘了。。。毕竟当时可能学得不精。。。现在来补一下。。。
const int N = 100+5; int n,m; int fa[N];///保存各个节点的根节点 struct edge{ int u,v;///边的两端 int w;///边的权值 }e[N*N]; bool cmp(edge a,edge b){ return a.w<b.w; } ///找父节点 int find(int x){ if(fa[x]==x) return x; else return find(fa[x]); } ll Kruskal(){ ll ans = 0; sort(e,e+m,cmp); ///边的排序 for(int i=0;i<n;i++) fa[i] = i; ///初始化父节点(联通区)///注意:节点是从 0 开始的还是从 1 开始的 for(int i=0;i<m;i++){ int u = e[i].u,v = e[i].v,w = e[i].w; int x= find(u),y = find(v); if(x == y) continue; ans += w; fa[y] = x; } return ans; }