백준 16398번 행성연결
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 | #include <iostream> #include <string> #include <vector> #include<queue> #include <algorithm> using namespace std; int n; int parent[1001]; vector<pair <pair<int,int>,int> > edge; int cost[1001][1001]; int findParent(int node) { if (node == parent[node]) return node; else return parent[node] = findParent(parent[node]); } void merge(int node1, int node2) { node1= findParent(node1); node2= findParent(node2); parent[node2] = node1; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; for (int i = 1; i <= n; i++) { parent[i] = i; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) cin >> cost[i][j]; } for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { edge.push_back(make_pair(make_pair(cost[i][j],i),j)); } } sort(edge.begin(), edge.end()); long long ret = 0; for (int i = 0; i < edge.size(); i++) { if (findParent(edge[i].first.second) != findParent(edge[i].second)) { ret += edge[i].first.first; merge(edge[i].first.second, edge[i].second); } } cout << ret; return 0; } | cs |
출처:https://www.acmicpc.net/problem/16398
저도 모르게 합병한 node들의 뭉치의 size들 까지 계산해서 풀고 있었는데 그렇게 복잡하게 구현할 필요가 없네요....
문제를 푸는 핵심은 간선들의 가중치를 오름차순으로 정렬시킨뒤 최대한 낮은수부터 확인하면서
합병할수있으면 합병하고 ret+=가중치 를 해주면 간단하게 풀 수 있는 문제였습니다.
'알고리즘 > BAEKJOON' 카테고리의 다른 글
| 백준 16770번 The Bucket List (0) | 2019.04.01 |
|---|---|
| 백준 16769번 Mixing Milk (0) | 2019.04.01 |
| 백준 7569번 토마토 (0) | 2019.03.27 |
| 백준 11049번 행렬 곱셈 순서 (0) | 2019.03.27 |
| 백준 13700번 완전 범죄 (0) | 2019.03.26 |