fufengyiye @ 2024-01-21 21:12:31
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
struct edge {
int u, v, w;
bool operator < (const edge& t)
{
return w < t.w;
}
}e[200003];
int N, M;
const int inf = 10003;
int ans = 0;
int cnt = 0;
int fa[5003];
int find(int x)
{
while (x != fa[x])
{
x = fa[x] = fa[fa[x]];
}
return x;
}
void Kru()
{
for (int i = 1; i <= M; i++)
{
int x = find(e[i].u);
int y = find(e[i].v);
if (x != y)
{
fa[x] = y;
ans += e[i].w;
cnt++;
}
if (cnt == N- 1)
{
break;
}
}
}
int main()
{
cin >> N >> M;
for (int i = 1; i <= M; i++)
{
int _u, _v, _w;
cin >> _u >> _v >> _w;
e[i].u = _u;
e[i].v = _v;
e[i].w = _w;
}
sort(e, e + M);
for (int i = 1; i <= M; i++)
{
fa[i] = i;
}
Kru();
if (cnt == N - 1)
cout << ans << endl;
else
cout << "orz" << endl;
return 0;
}
by aCssen @ 2024-01-21 21:39:35
并查集的 fa
要初始化到
by fufengyiye @ 2024-01-22 10:24:00
@aCssen 太厉害了,我看了个把小时都没看出来,