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 |
Tags
- 자료구조
- 트리
- XR Interaction Toolkit
- 백트래킹
- Unreal Engine 5
- DFS
- BFS
- 유니티
- Team Fortress 2
- 유니온 파인드
- c++
- 브루트포스
- 그리디 알고리즘
- 다이나믹 프로그래밍
- 다익스트라
- 재귀
- 그래프
- 문자열
- ue5
- 정렬
- 구현
- 누적 합
- 알고리즘
- 수학
- VR
- 스택
- 시뮬레이션
- 투 포인터
- 우선순위 큐
- 백준
Archives
- Today
- Total
1일1알
백준 16398번 행성 연결 C++ 본문
https://www.acmicpc.net/problem/16398
16398번: 행성 연결
홍익 제국의 중심은 행성 T이다. 제국의 황제 윤석이는 행성 T에서 제국을 효과적으로 통치하기 위해서, N개의 행성 간에 플로우를 설치하려고 한다. 두 행성 간에 플로우를 설치하면 제국의 함
www.acmicpc.net
유니온 파인드 자료구조를이용해서 최소 스패닝 트리를 구한다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
struct Info {
int s;
int e;
int cost;
bool operator<(const Info& other) const {
return cost < other.cost;
}
};
int n;
vector<vector<int>> board;
vector<Info> v;
vector<int> parent;
vector<int> height;
int GetParent(int a) {
if (a == parent[a]) return a;
return GetParent(parent[a]);
}
void Merge(int u, int v) {
u = GetParent(u);
v = GetParent(v);
if (u == v) return;
if (height[u] > height[v])
::swap(u, v);
parent[u] = v;
if (height[u] == height[v])
height[v]++;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int64 ans = 0;
cin >> n;
board = vector<vector<int>>(n, vector<int>(n));
parent = vector<int>(n);
height = vector<int>(n, 1);
for (int i = 0; i < n; i++) parent[i] = i;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> board[i][j];
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
v.push_back({ i,j,board[i][j] });
}
}
sort(v.begin(), v.end());
for (auto a : v) {
if (GetParent(a.s) == GetParent(a.e)) continue;
Merge(a.s, a.e);
ans += a.cost;
}
cout << ans;
}
'알고리즘' 카테고리의 다른 글
백준 1935번 후위 표기식2 C++ (0) | 2023.03.11 |
---|---|
백준 16168번 퍼레이드 C++ (0) | 2023.03.08 |
백준 1411번 비슷한 단어 C++ (0) | 2023.03.05 |
백준 7795번 먹을 것인가 먹힐 것인가 C++ (0) | 2023.03.04 |
백준 22233번 가희와 키워드 C++ (0) | 2023.03.03 |