반응형
https://www.acmicpc.net/problem/16398
16398번: 행성 연결
홍익 제국의 중심은 행성 T이다. 제국의 황제 윤석이는 행성 T에서 제국을 효과적으로 통치하기 위해서, N개의 행성 간에 플로우를 설치하려고 한다. 두 행성 간에 플로우를 설치하면 제국의 함
www.acmicpc.net
[ 문제풀이 ]
1. arr[ 1001 ][ 1001 ]배열에 값을 입력 받고, i < j일 때 값을 priority_queue에 넣습니다.
2. Union-Find를 이용하여 부모가 같지 않다면 두 노드를 합치고, ans에 cost를 더해줍니다.
3. ans를 출력합니다.
[ 소스코드 ]
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #include<iostream> #include<queue> #define ll long long using namespace std; int N; int vect[1001]; ll arr[1001][1001]; struct node { int from; int to; ll cost; }; struct cmp { bool operator()(node right, node left) { return left.cost < right.cost; } }; int Find(int num) { if (vect[num] == num) return num; return vect[num] = Find(vect[num]); } void Union(int a, int b) { int pa = Find(a); int pb = Find(b); vect[pb] = pa; } int main() { scanf("%d", &N); priority_queue<node, vector<node>, cmp> pq; for (int i = 1; i <= N; i++) { vect[i] = i; } for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { scanf("%lld", &arr[i][j]); if (i < j) { pq.push({ i,j,arr[i][j] }); } } } ll ans = 0; while (!pq.empty()) { const int a = pq.top().from; const int b = pq.top().to; const int cost = pq.top().cost; pq.pop(); if (Find(a) != Find(b)) { Union(a, b); ans += cost; } } printf("%lld", ans); } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 1175번 - 배달 (C++) (0) | 2023.01.30 |
---|---|
[ 백준 ] 13418번 - 학교 탐방하기 (C++) (0) | 2023.01.29 |
[ 백준 ] 17090번 - 미로 탈출하기 (C++) (0) | 2023.01.27 |
[ 백준 ] 14923번 - 미로 탈출 (C++) (0) | 2023.01.26 |
[ 백준 ] 5558번 - チーズ (Cheese) (C++) (0) | 2023.01.25 |