시작 정점에서부터 출발하여 신장트리 집합을 단계적으로 확장해나가는 방법
Prim 알고리즘을 이용하여 MST를 만드는 과정
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
#define NODE 7
#define EDGE 9
class Edge {
public:
int node[2]; //양 끝 정점
int distance;
Edge(int x, int y, int distance) {
this->node[0] = x;
this->node[1] = y;
this->distance = distance;
}
bool operator <(Edge &edge) {
return this->distance < edge.distance;
}
bool operator >(Edge &edge) {
return this->distance > edge.distance;
}
};
vector<Edge> v;
int visit[10001];
priority_queue<Edge, vector<Edge>, greater<>> pq;
int sum;
void prim(int start) {
visit[start] = 1;
for (int i = 0; i < v.size(); i++) {
if (v[i].node[0] == start) {
if (!visit[v[i].node[1]]) {
pq.push(v[i]); //정점 start와 연결된 간선을 큐에 담는다
}
}
}
while (!pq.empty()) {
Edge w = pq.top();
pq.pop();
if (!visit[w.node[1]]) {
sum += w.distance;
prim(w.node[1]);
return;
}
}
}
int main(int argc, char *argv[]) {
v.push_back(Edge(0, 1, 28));
v.push_back(Edge(0, 5, 10));
v.push_back(Edge(1, 0, 28)); //
v.push_back(Edge(1, 2, 16));
v.push_back(Edge(1, 6, 14));
v.push_back(Edge(2, 1, 16)); //
v.push_back(Edge(2, 3, 12));
v.push_back(Edge(3, 2, 12)); //
v.push_back(Edge(3, 4, 22));
v.push_back(Edge(3, 6, 18));
v.push_back(Edge(4, 3, 22)); //
v.push_back(Edge(4, 5, 25));
v.push_back(Edge(4, 6, 24));
v.push_back(Edge(5, 0, 10));//
v.push_back(Edge(5, 4, 25));//
v.push_back(Edge(6, 1, 14)); //
v.push_back(Edge(6, 3, 18));
v.push_back(Edge(6, 4, 24));
prim(0);
cout << sum << endl;
return 0;
}