Prim
void add(int u, int v, int w)
{
e[++cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt;
}
int prim()
{
for (int i = 2; i <= n; ++i)
{
dis[i] = inf;
}
for(int i=1;i<=n;i++)
{
int minn = inf;
for (int i = 1; i <= n; ++i)
{
if (!vis[i] && minn > dis[i])
{
minn = dis[i];
now = i;
}
}
vis[now] = 1;
ans += minn;
for (int i = head[now]; i; i = e[i].next)
{
int v = e[i].v;
if (!vis[v] && dis[v] > e[i].w)
{
dis[v] = e[i].w;
}
}
}
return ans;
}
Kruskal
int find(int x)//并查集
{
while(x!=fa[x]) x=fa[x]=fa[fa[x]];
return x;
}
void kruskal()
{
sort(edge,edge+m,cmp);
for(re int i=0;i<m;i++)
{
eu=find(edge[i].u), ev=find(edge[i].v);
if(eu==ev)
{
continue;
}
ans+=edge[i].w;
fa[ev]=eu;
if(++cnt==n-1)
{
break;
}
}
}