어떤 그래프로부터 최소 신장 트리(Minimum Spanning Tree)를 도출해낼 때 사용하는 알고리즘
위의 프로세스는 Greedy Method 방식으로 진행이 된다.
O(ElogV)
두 트리를 연결하는 과정에서 union-find 알고리즘을 사용하면 쉽게 구현할 수 있다.
#define MAX_SIZE 100000
typedef struct Edge{
int from, to, cost;
}Edge;
bool cmp(const Edges &e1, const Edge &e2){
return e1.cost < e2.cost;
}
//index 0 is not used
int Set[MAX_SIZE + 1]; //소속한 집합의 루트값
vector<Edge> edges;
int find(int n){
if(Set[n] = n) return n;
return Set[n] = find(Set[n]); //path compression
}
void union(int a, int b){
int A(find(a));
int b(find(b));
if(A != B){
Set[A] = B;
}
}
int kruskal(int v, int e){
int mstCost = 0;
int selectCnt = 0;
for(int i = 1; i <= MAX_SIZE; i++) Set[i] = i;
sort(edges.begin(), edges.end(), cmp);
for(int i = 0; i < e; i++){
if(find(edges[i].from) != find(edges[i].to)){
mstCost += edges[i].cost;
selectCnt++;
union(edges[i].from, edges[i].to);
}
}
if(selectCnt == v - 1) return mstCost;
else return -1;
}