const int MAXN = 110;//点
const int MAXM = 10000;//边
int f[MAXN];//并查集使用
struct Edge
{
int u, v, w;
}edge[MAXN];
int tol;//边数 初始化 0
void addedge(int u,int v,int w)
{
edge[tol].u = u;
edge[tol].v = v;
edge[tol++].w = w;
}
bool cmp(Edge a,Edge b)
{
return a.w < b.w;
}
int find(int x)
{
if (f[x] == -1)
return x;
else
return f[x] = find(f[x]);
}
int kruskal(int n)
{
memset(f,-1,sizeof(f));
sort(edge, edge+tol, cmp);
int cnt = 0;
int ans = 0;
for (int i = 0; i < tol; i++)
{
int u = edge[i].u;
int v = edge[i].v;
int w = edge[i].w;
int t1 = find(u);
int t2 = find(v);
if (t1 != t2)
{
ans += w;
f[t1] = t2;
cnt++;
}
if (cnt == n - 1)
break;
}
if (cnt < n - 1) return -1;//不连通
else return ans;
}
时间: 2024-10-25 05:43:18