/*Kruskal 算法
*注意:点是从1到n编号
*Ecnt = 0
*/
typedef int weight_t;
const int SIZE_V =
const int SIZE_E =
int Father[SIZE_V];
int Ecnt = 0;
//int n; // 此处写点的全局变量
//并查集算法
void init(int vn){
for(int i = 0;i <= vn;++i)
Father[i] = i;
}
int find(int x){
return (Father[x] == x) ? x :
Father[x] = find(Father[x]);
}
inline void unite(int x,int y){
Father[find(y)] = Father[find(x)];
}
struct edge_t{
int s,e;
weight_t w;
friend bool operator < (edge_t const&a,edge_t const&b){
if (a.w != b.w) return a.w < b.w;
if (a.s != b.s) return a.s < b.s;
return a.e < b.e;
}
}Edge[SIZE_E];
inline void mkEdge(int a,int b,weight_t w){
if (a > b)swap(a,b);
Edge[Ecnt].s = a;
Edge[Ecnt].e = b;
Edge[Ecnt++].w = w;
}
weight_t Kruskal(int vn,int en){
init(vn);
sort(Edge,Edge+en);
weight_t ret = 0;
for (int i = 0;i < en; ++i){
if ( find(Edge[i].s) == find(Edge[i].e))
continue;
ret += Edge[i].w;
unite(Edge[i].s,Edge[i].e);
--vn;
if (1 == vn)break;
}
return ret;
}
最小生成树 Kruskal 算法模板
最新推荐文章于 2021-07-29 09:20:13 发布