![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
int mincost[maxn]; bool used[maxn]; int MST() { _for(i,0,V) { mincost[i] = INF; used[i] = false; } mincost[0] = 0; int res = 0; while(1) { int v = -1; _for(u,0,V) if(!used[u] && (v==-1 || mincost[u] < mincost[v])) v = u; if(v==-1) break; used[v] = true; res += mincost[v]; _for(u,0,G[v].size()) mincost[G[v][u].to] = min(mincost[G[v][u].to],G[v][u].cost); } return res; }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
int par[maxn]; //父亲 int high[maxn]; //树的高度 void init(int n) { _for(i,0,n) { par[i] = i; high[i] = 0; } } int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); } void unite(int x,int y) { x = find(x);y = find(y); if(x==y) return ; if(high[x]<high[y]) par[x] = y; else { par[y] = x; if(high[x]==high[y]) high[x] ++; } } bool same(int x,int y) { return find(x) == find(y); } struct tedge { int u; int v; int cost; }; vector<tedge> es; bool cmp(const tedge& a,const tedge& b) { return a.cost < b.cost; } int MST() { _for(i,0,V) _for(j,0,G[i].size()) es.pb({i,G[i][j].to,G[i][j].cost}); sort(es.begin(),es.end(),cmp); init(V); int res = 0; //无向图 E*2 _for(i,0,E*2) { tedge e= es[i]; if(!same(e.u,e.v)) { unite(e.u,e.v); res += e.cost; } } return res; }
Prim O(|V^2|)
Kruskal O(|E|logV)