Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

hwooo

BOJ (C/C++) 1922번: 네트워크 연결 본문

Study/Algorithm

BOJ (C/C++) 1922번: 네트워크 연결

hwooo 2022. 12. 1. 23:22

풀이

최소 스패닝 트리를 구하는 문제 -> 크루스칼 알고리즘 사용

 

크루스칼? 연결 비용을 오름차순으로 정렬하여 가장 적은 비용부터 사용함

두 노드가 같은 그룹에 속하지 않았을 때 이어주는 간선을 사용하여 비용을 증가시킴


코드

#include <stdio.h>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

vector <pair<int, pair<int, int >>> Com;
int R[1001];

int Find(int n) {
	if (R[n] == n) return n;
	return Find(R[n]);
}
void Union(int a, int b) {
	int aroot, broot;
	aroot = Find(a);
	broot = Find(b);
	R[broot] = aroot;
}

int Kruskal(int N) {
	int start, end, cost = 0;

	// asc
	sort(Com.begin(), Com.end());

	// 루트는 자기 자신으로 초기화
	for (int i = 1; i <= N; i++) R[i] = i;

	for (int i = 0; i < Com.size(); i++) {
		start = Com[i].second.first, end = Com[i].second.second;

		// 두 노드가 같은 그룹에 속하지 않았을 때
		if (Find(start) != Find(end)) {
			cost += Com[i].first;

			// 노드의 root 연결
			Union(start, end);
		}
	}
	return cost;
}

int main() {
	int N, M, a, b, c;

	scanf("%d\n%d", &N, &M);
	for (int i = 0; i < M; i++) {
		scanf("%d %d %d", &a, &b, &c);
		Com.push_back({ c,{a,b} });
	}

	printf("%d", Kruskal(N));
	return 0;
}

'Study > Algorithm' 카테고리의 다른 글

BOJ (C/C++) 1261번: 알고스팟  (0) 2022.12.02
BOJ (C/C++) 16953번: A → B  (0) 2022.12.02
BOJ (C/C++) 11403번: 경로 찾기  (0) 2022.12.01
BOJ (C/C++) 2747번: 피보나치 수  (0) 2022.12.01
BOJ (C/C++) 2312번: 수 복원하기  (0) 2022.11.30