Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
Tags
- 후니의 쉽게 쓴 시스코 네트워킹
- CS
- 이분탐색
- 구현
- 알고리즘
- 에라토스테네스의 체
- 플로이드-와샬
- java
- BFS
- 스택
- 완전탐색
- dfs
- JUnit 5
- Effective Java
- 유니온 파인드
- 그리디
- 동적계획법
- 프로그래머스
- 시뮬레이션
- mst
- 백준
- 수학
- 투 포인터
- Network
- 문자열
- 백트래킹
- 위상정렬
- Kotlin
- 세그먼트 트리
- swea
Archives
반갑습니다!
[프로그래머스] 섬 연결하기 본문
풀이
모든 섬을 연결하라는 의미는 결국 MST를 만들라는 말과 같다.
아래의 코드에서는 입력으로 들어온 costs
벡터를 edges
벡터에 저장하고 kruskal 알고리즘을 사용해 MST를 생성해서 해결했다.
코드
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
int parent[101]; | |
vector<pair<int, pair<int, int>>> edges; | |
int find(int x) { | |
if (x == parent[x]) return x; | |
return parent[x] = find(parent[x]); | |
} | |
void merge(int a, int b) { | |
a = find(a); | |
b = find(b); | |
if (a < b) parent[b] = a; | |
else parent[a] = b; | |
} | |
int kruskal() { | |
sort(edges.begin(), edges.end()); | |
int sum = 0; | |
for (int i = 0; i < edges.size(); i++) { | |
int a = edges[i].second.first; | |
int b = edges[i].second.second; | |
int cost = edges[i].first; | |
if (find(a) == find(b)) continue; | |
merge(a, b); | |
sum += cost; | |
} | |
return sum; | |
} | |
int solution(int n, vector<vector<int>> costs) { | |
int answer = 0; | |
for (auto i : costs) { | |
edges.push_back({ i[2], {i[0], i[1]} }); | |
} | |
for (int i = 1; i <= n; i++) parent[i] = i; | |
answer = kruskal(); | |
return answer; | |
} |
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 2631줄 세우기 (0) | 2020.10.22 |
---|---|
[프로그래머스] 최고의 집합 (0) | 2020.10.22 |
[백준] 1915 가장 큰 정사각형 (0) | 2020.10.20 |
[백준] 17472 다리 만들기 2 (0) | 2020.10.19 |
[백준] 6497 전력난 (0) | 2020.10.19 |