[C++] 백준 1197 : 최소 스패닝 트리

Updated:

1 minute read

백준 1197번 문제를 풀어보았다.

image-20210117214118065


1. 문제 설명

image

  • MST를 사용하여 푸는 문제.
  • 그래프가 주어졌을 때, 그 그래프의 최소 스패닝 트리를 구하는 프로그램
    • 가중치를 구한다.


2. 문제 풀이

2.1 사용 변수

typedef pair<int, int> cities;
typedef pair<int, cities> info;
int* group;
priority_queue<info, vector<info>, greater<info> > pq;

int find_p(int c);
  • cities
    • 두 도시 묶음
  • info
    • <가중치, 두 도시> 묶음
  • group
    • index의 parent node를 저장하는 배열
    • ex. group[1]=2 → 1노드의 parent node는 2노드
  • pq
    • 작은 가중치를 가진 것이 먼저 나옴.
  • find_p
    • parent를 찾는 함수
    • parent(group[c])와 c가 동일하다면 root node이기 때문에 c를 반환.


2.2 Solution

  • 가장 작은 가중치부터 순서대로 꺼내며 경로를 연결함.
  • 모든 정점들이 연결되었는지 여부를 찾기 위해서 find_p함수를 사용
    • 함께 연결되어 있다면 Parent Node도 동일하기 때문.


2.3 전체 코드

/*MST problem*/
#include <iostream>
#include <queue>
#include <functional>
using namespace std;

typedef pair<int, int> cities;
typedef pair<int, cities> info;
int* group;

void union_group(int a, int b) {
	group[a] = b;
}

int find_p(int c) {
	if (group[c] != c) {
		group[c] = group[group[c]];
		return find_p(group[c]);
	}
	else return group[c];
}

int main() {
	priority_queue<info, vector<info>, greater<info> > pq; //less: 내림차순, greater: 오름차순
	int c_num, e_num;
	info temp;
	int count = 0;
	int total = 0;
	int p1, p2;

	cin >> c_num >> e_num;

	group = new int[c_num+1]; //make each group
	for (int i = 1; i < c_num + 1; i++) 
		group[i] = i;

	for (int i = 0; i < e_num; i++) {//put data into heap
		cin >> temp.second.first >> temp.second.second >> temp.first;
		pq.push(temp);
	}

	while(count<c_num-1) {
		temp = pq.top();
		pq.pop();
		p1 = find_p(temp.second.first);
		p2 = find_p(temp.second.second);
		if (p1 != p2) {
			count++;
			total += temp.first;
			union_group(p1, p2);
		}
	}
	cout << total << endl;

	return 0;
}


3. Review

오랜만에 풀 때마다 MST 정의를 까먹음..


4. 실패한 접근 방법

  • 없음.

Leave a comment