题目链接
挖沟
代码实现
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = 5e5 + 10;
struct Edge
{
int u, v, w;
bool operator < (const Edge &W)const
{
return w < W.w;
}
}edge[M];
int p[N];
int n, m;
int find(int a)
{
if (p[a] != a) p[a] = find(p[a]);
return p[a];
}
int Kruskal()
{
for (int i = 1; i <= n; i ++ ) p[i] = i;
sort(edge, edge + m);
int res = 0, cnt = 0;
for (int i = 0; i < m; i ++ )
{
auto e = edge[i];
int pu = find(e.u), pv = find(e.v);
if (pu != pv)
{
p[pv] = pu;
res += e.w;
cnt ++;
}
}
return res;
}
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 0; i < m; i ++ )
{
int a, b, c;
cin >> a >> b >> c;
edge[i] = {a, b, c};
}
int t = Kruskal();
cout << t << endl;
return 0;
}