int father[5010], n, m;
int find(int x)//找根函数,记得进行路径压缩
{
if(father[x] == x) return x;
else return father[x] = find(father[x]);
}
int same(int x, int y)//简化代码
{
if(find(x) == find(y)) return 1;
else return 0;
}
struct edge
{
int u, v, cost;//边的两个端点,cost是边的长度
}e[200010];
int cmp(edge e1, edge e2)
{
return e1.cost < e2.cost;
}
int kruskal()
{
sort(e + 1, e + 1 + m, cmp);
int res = 0;//边权总和
int cnt = 0;//边的数量
for(int i = 1; i <= m; i++)
{
if(same(e[i].u, e[i].v) == 0)
{
cnt++;
res += e[i].cost;
father[find(e[i].u)] = find(e[i].v);
}
}
if(cnt == n - 1) return res;
else return -1;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
father[i] = i;
}
for(int i = 1; i <= m; i++)
{
cin >> e[i].u >> e[i].v >> e[i].cost;
}
int ans = kruskal();
if(ans == -1) cout << "orz\n";
else cout << ans << '\n';
return 0;
}
标签:return,int,kruskal,father,最小,cost,find,模板
From: https://www.cnblogs.com/joylz/p/18549733