크루스칼 알고리즘은 최소 신장 트리(Minimum Spanning Tree, MST)를 구하는 대표적인 그리디 알고리즘입니다.
더 자세한 내용은 아래 블로그에서도 보실 수 있습니다.
https://wisdom-and-record.tistory.com/124

https://school.programmers.co.kr/learn/courses/30/lessons/42861
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct DisjointSet
{
vector<int> parent;
DisjointSet(int n): parent(n)
{
for(int i = 0; i < n; ++i) parent[i] = i;
}
int find(int x)
{
if(parent[x] == x) return x;
return parent[x] = find(parent[x]);
}
bool unite(int a, int b)
{
a = find(a);
b = find(b);
if(a == b) return false;
parent[b] = a;
return true;
}
};
int solution(int n, vector<vector<int>> costs)
{
int answer = 0;
sort(costs.begin(), costs.end(), [](auto& a, auto& b){ return a[2] < b[2]; });
DisjointSet dsu(n);
for(auto& edge: costs)
{
int u = edge[0];
int v = edge[1];
int w = edge[2];
if(dsu.unite(u, v))
{
answer += w;
}
}
return answer;
}