문제) 백준 - 최소 스패닝 트리(Minimum Spanning Tree) - Watering the Fields
https://www.acmicpc.net/problem/10021
10021번: Watering the Fields
Input Details There are 3 fields, at locations (0,2), (5,0), and (4,3). The contractor will only install pipes of cost at least 11. Output Details FJ cannot build a pipe between the fields at (4,3) and (5,0), since its cost would be only 10. He therefore b
www.acmicpc.net
네트워크를 이루는 것들 중 최소 비용을 구하는 문제이다. DisjointSet과 MST(Minimum Spanning Tree)를 활용하면 풀 수 있다.
C++ 소스코드)
This file contains 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
int kruskal() { | |
int ret = 0, cnt = 0; | |
vector<pair<int, p>> edges; | |
for(int u = 0; u < N; ++u ) | |
for (auto now : graph[u]) { | |
int v = now.first; int cost = now.second; | |
edges.push_back({ cost, {u, v} }); | |
} | |
sort(edges.begin(), edges.end()); | |
Disjointset ds(N + 1); | |
for (int i = 0; i < edges.size(); ++i) { | |
int cost = edges[i].first; | |
if (cost < C) continue; | |
int u = edges[i].second.first; int v = edges[i].second.second; | |
if (ds.find(u) == ds.find(v)) continue; | |
ds.merge(u, v); | |
ret += cost; | |
cnt++; | |
} | |
if (cnt != N - 1) | |
ret = -1; | |
return ret; | |
} |
Full Code)
GitHub - Chocochip101/BOJ_Solution
Contribute to Chocochip101/BOJ_Solution development by creating an account on GitHub.
github.com
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 17780번 - 새로운 게임 (C++) 문제 및 풀이 (0) | 2021.10.24 |
---|---|
[백준] 4485번 - 녹색 옷 입은 애가 젤다지? (C++) 문제 및 풀이 (0) | 2021.10.21 |
[백준] 2623번 - 음악프로그램 (C++) 문제 및 풀이 (0) | 2021.10.05 |
[백준] 2056번 - 작업 (C++) 문제 및 풀이 (0) | 2021.10.01 |
[백준] 4811번 - 알약 (C++) 문제 및 풀이 (0) | 2021.09.29 |
댓글