※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 1922번 문제인 네트워크 연결이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/1922 

 

1922번: 네트워크 연결

이 경우에 1-3, 2-3, 3-4, 4-5, 4-6을 연결하면 주어진 output이 나오게 된다.

www.acmicpc.net

이 문제는 주어진 그래프에서 MST(최소신장트리)를 구하는 문제이다. MST는 문제에서 요구하는 조건을 모두 만족시키기 때문이다.

 

아래는 제출한 소스코드이다.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int arr[1001];

int findf(int x) {
	if (x == arr[x]) return x;
	return arr[x] = findf(arr[x]);
}

vector<pair<int, pair<int, int>>> edges;

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int N; cin >> N;
	for (int i = 1; i <= N; i++) {
		arr[i] = i;
	}

	int M; cin >> M;
	while (M--) {
		int x, y, c; cin >> x >> y >> c;
		edges.push_back({ c,{x,y} });
	}

	sort(edges.begin(), edges.end());

	int ans = 0;
	for (auto edge : edges) {
		int x = findf(edge.second.first), y = findf(edge.second.second);
		if (x == y) continue;
		ans += edge.first;
		arr[y] = x;
	}

	cout << ans;
}

 

728x90

'BOJ' 카테고리의 다른 글

[BOJ 5569 // C++] 출근 경로  (0) 2022.06.12
[BOJ 17843 // C++] 시계  (0) 2022.06.12
[BOJ 1495 // C++] 기타리스트  (0) 2022.06.10
[BOJ 1965 // C++] 상자넣기  (0) 2022.06.09
[BOJ 1051 // C++] 숫자 정사각형  (0) 2022.06.08

+ Recent posts