#include <bits/stdc++.h>
using namespace std;
int p[100];
typedef pair<pair<int, int>, int> P; //里面的pair是路两头的编号,外面的pair的second是权值
int cmp(P a, P b)//按照权值排序
{
return a.second < b.second;
}
//并查集
int find1(int x)
{
return p[x] == x ? x : p[x] = find1(p[x]);
}
void un(int x, int y)
{
p[find1(x)] = find1(y);
}
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)//并查集数组赋初值
{
p[i] = i;
}
vector<P> mp(m);
for (int i = 0; i < m; i++)
{
cin >> mp[i].first.first >> mp[i].first.second >> mp[i].second;
}
sort(mp.begin(), mp.end(), cmp);
int k = 0, ans = 0;
for (int i = 0; i < m; i++)
{
if (k == n - 1)//如果已经将所有点都连起来了就退出
{
break;
}
if (find1(mp[i].first.first) != find1(mp[i].first.second))
{
un(mp[i].first.first, mp[i].first.second);
k++;
cout << "The " << k << "th road is " << mp[i].first.first << " to " << mp[i].first.second << ",need cost:" << mp[i].second << ".\n";
ans += mp[i].second;
}
}
cout << "all cost:" << ans;
return 0;
}
最小生成树方法之一——Kruskal模板
最新推荐文章于 2023-11-28 13:33:13 发布