** 최소신장트리 MST는 두가지 알고리즘으로 풀이가 가능하다
알고리즘 | 자료구조 | 특징 |
---|---|---|
크루스칼 | 간선 리스트 + 정렬 + unionFind | 간선 중심, 간선 수가 적을때 유리하다 |
prim | 우선순위큐 | 정점 중심, 간선 수가 많을 때 유리하다 |
우선순위큐 동작방법(이 형태에서 항상 변형)
PriorityQueue<Edge> pq = new PriorityQueue<>();
boolean[] visited = new boolean[N];
int mst = 0;
int connected = 0;
// 0번 정점부터 시작
visited[0] = true;
for (Edge e : graph[0]) {
pq.add(e);
}
while (!pq.isEmpty() && connected < N - 1) {
Edge cur = pq.poll();
if (visited[cur.to]) continue;
visited[cur.to] = true;
mst += cur.weight;
connected++;
for (Edge next : graph[cur.to]) {
if (!visited[next.to]) {
pq.add(next);
}
}
}