[C++] 백준 1922 : 네트워크 연결

Updated:

1 minute read

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

image-20210117222056815


1. 문제 설명

image-20210117222041035

  • MST를 사용하여 푸는 문제.
  • 모든 컴퓨터를 연결하는데 필요한 최소비용을 출력


2. 문제 풀이

2.1 사용 변수

typedef pair<int, pair<int, int> > info;
bool union_group(int a, int b, int * group);
priority_queue<info, vector<info>, greater<info> > pq;
  • info
    • <가중치, 두 도시> 묶음
  • group
    • index의 parent node를 저장하는 배열
    • ex. group[1]=2 → 1노드의 parent node는 2노드
  • bool union_group(int a, int b, int * group)
    • parent를 찾는 함수
    • parent(group[c])와 c가 동일하다면 root node이기 때문에 c를 반환.
    • a의 parent node와 b의 parent node를 찾은 후 두 parent node가 같은지 확인.
      • 다르다면 더 height가 작은 쪽을 큰 쪽에 붙임.
  • pq
    • 작은 가중치를 가진 것이 먼저 나옴.


2.2 Solution

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


2.3 전체 코드

#include <iostream>
#include <queue>
#include <functional>

using namespace std;

typedef pair<int, pair<int, int> > info; //information(cost, (com1,com2))

int edge = 0;

bool union_group(int a, int b, int * group) {
	int p_a = group[a], p_b = group[b];
	int size_a = 0, size_b = 0;

	while (p_a != a) { //find final parent of a
		group[a] = group[p_a]; // reduce height of a's tree
		a = group[a];
		p_a = group[a];
		size_a++;
	}
	while (p_b != b) { //find final parent of b
		group[b] = group[p_b]; // reduce height of b's tree
		b = group[b];
		p_b = group[b];
		size_b++;
	}
	if (p_a != p_b) {
		if (size_a > size_b) group[b] = a; //compare heights of a and b
		else group[a] = b;
		edge++;
		return true;
	}
	return false;
}

int main() {
	int com_num, net_num;
	int weight = 0;
	info temp;
	priority_queue<info, vector<info>, greater<info> > pq; //**Put greater**//

	cin >> com_num;
	cin >> net_num;

	int * group;
	group = new int[com_num + 1];
	for (int i = 1; i < com_num + 1; i++)
		group[i] = i;

	for (int i = 0; i < net_num; i++) {
		cin >> temp.second.first >> temp.second.second >> temp.first;
		pq.push(temp);
	}

	
	while (edge < com_num - 1) {
		temp = pq.top();
		pq.pop();
		if (union_group(temp.second.first, temp.second.second, group))
			weight += temp.first;
	}

	cout << weight << endl;
}


3. Review

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


4. 실패한 접근 방법

  • 없음.

Leave a comment