O(mlogm)
int p[N]; //并查集
struct Edge
{
int a, b, w;
bool operator<(const Edge &W) const
{
return w < W.w;
}
} edge[M];
int find(int x) //并查集
{
if (p[x] != x)
{
p[x] = find(p[x]);
}
return p[x];
}
int kruskal() //连通时返回最小生成树边权和,否则返回INF(0x3f3f3f3f)
{
sort(edge, edge + m);
for (int i = 1; i <= n; i++)
{
p[i] = i;
}
int res = 0, cnt = 0;
for (int i = 0; i < m; i++)
{
int a = find(edge[i].a), b = find(edge[i].b);
if (a != b)
{
p[a] = b;
res += edge[i].w;
cnt++;
}
}
if (cnt < n - 1)
{
return INF;
}
return res;
}