[level 3] Title: 섬 연결하기, Time: 0.05 ms, Memory: 10.2 MB -BaekjoonHub

This commit is contained in:
SSUM
2025-03-07 22:08:12 +09:00
parent a923a2aacd
commit 5137936552
2 changed files with 91 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
# [level 3] 섬 연결하기 - 42861
[문제 링크](https://school.programmers.co.kr/learn/courses/30/lessons/42861)
### 성능 요약
메모리: 10.2 MB, 시간: 0.05 ms
### 구분
코딩테스트 연습 > 탐욕법Greedy
### 채점결과
정확성: 100.0<br/>합계: 100.0 / 100.0
### 제출 일자
2025년 03월 07일 22:08:10
### 문제 설명
<p>n개의 섬 사이에 다리를 건설하는 비용(costs)이 주어질 때, 최소의 비용으로 모든 섬이 서로 통행 가능하도록 만들 때 필요한 최소 비용을 return 하도록 solution을 완성하세요.</p>
<p>다리를 여러 번 건너더라도, 도달할 수만 있으면 통행 가능하다고 봅니다. 예를 들어 A 섬과 B 섬 사이에 다리가 있고, B 섬과 C 섬 사이에 다리가 있으면 A 섬과 C 섬은 서로 통행 가능합니다.</p>
<p><strong>제한사항</strong></p>
<ul>
<li>섬의 개수 n은 1 이상 100 이하입니다.</li>
<li>costs의 길이는 <code>((n-1) * n) / 2</code>이하입니다.</li>
<li>임의의 i에 대해, costs[i][0] 와 costs[i] [1]에는 다리가 연결되는 두 섬의 번호가 들어있고, costs[i] [2]에는 이 두 섬을 연결하는 다리를 건설할 때 드는 비용입니다.</li>
<li>같은 연결은 두 번 주어지지 않습니다. 또한 순서가 바뀌더라도 같은 연결로 봅니다. 즉 0과 1 사이를 연결하는 비용이 주어졌을 때, 1과 0의 비용이 주어지지 않습니다.</li>
<li>모든 섬 사이의 다리 건설 비용이 주어지지 않습니다. 이 경우, 두 섬 사이의 건설이 불가능한 것으로 봅니다.</li>
<li>연결할 수 없는 섬은 주어지지 않습니다.</li>
</ul>
<p><strong>입출력 예</strong></p>
<table class="table">
<thead><tr>
<th>n</th>
<th>costs</th>
<th>return</th>
</tr>
</thead>
<tbody><tr>
<td>4</td>
<td>[[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]]</td>
<td>4</td>
</tr>
</tbody>
</table>
<p><strong>입출력 예 설명</strong></p>
<p>costs를 그림으로 표현하면 다음과 같으며, 이때 초록색 경로로 연결하는 것이 가장 적은 비용으로 모두를 통행할 수 있도록 만드는 방법입니다.</p>
<p><img src="https://grepp-programmers.s3.amazonaws.com/files/production/13e2952057/f2746a8c-527c-4451-9a73-42129911fe17.png" title="" alt="image.png"></p>
> 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges

View File

@@ -0,0 +1,31 @@
def solution(n, costs):
# Union-Find 초기화: 각 섬은 자기 자신을 부모로 갖는다.
parent = list(range(n))
# find 함수: 경로 압축을 적용하여 부모를 찾는다.
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
# union 함수: 두 노드가 다른 집합에 속하면 합치고 True 반환
def union(x, y):
root_x = find(x)
root_y = find(y)
if root_x != root_y:
parent[root_y] = root_x
return True
return False
# 비용 오름차순으로 정렬
costs.sort(key=lambda x: x[2])
total_cost = 0
edges_used = 0
for start, end, cost in costs:
if union(start, end):
total_cost += cost
edges_used += 1
if edges_used == n - 1:
break
return total_cost