想了解什么是最小生成树可以参考网址:网址
这个题就是运用并查集进行筛选;
先排序;
然后就筛选
#pragma GCC optimize(2)
#include
#define maxn 200005
typedef long long ll;
using namespace std;
ll b[maxn];
struct node
{
ll from;
ll to;
ll len;
}
a[maxn];
bool cmp(node a,node b)
{
return a.len < b.len;
}
ll find(ll x)
{
return b[x] == x ? x : b[x] = find(b[x]);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
ll n,m;
cin >> n >> m;
for(int i = 1; i <= n; i ++)
{
b[i] = i;
}
for(int i = 1; i <= m; i ++)
{
cin >> a[i].from >> a[i].to >> a[i].len;
}
sort(a+1,a+m+1,cmp);
ll sum = 0,total = 0;
for(int i = 1; i <= m; i ++)
{
ll fx = find(a[i].from);
ll fy = find(a[i].to);
if(total == n - 1)break;
if(fx == fy)continue;
else
{
b[fx] = fy;
sum += a[i].len;
total++;
}
}
if(total == n - 1)cout << sum << endl;
else cout << "orz" << endl;
return 0;
}