-
[백준/BOJ] 9934번 완전 이진 트리알고리즘 문제풀이/백준 2022. 6. 9. 17:18
https://www.acmicpc.net/problem/9934
9934번: 완전 이진 트리
상근이는 슬로베니아의 도시 Donji Andrijevci를 여행하고 있다. 이 도시의 도로는 깊이가 K인 완전 이진 트리를 이루고 있다. 깊이가 K인 완전 이진 트리는 총 2K-1개의 노드로 이루어져 있다. (아래
www.acmicpc.net
중위 탐색의 결과를 완전 이진 트리로 바꿔야 하는 문제다.
특정 depth까지 left와 right을 설정해 루트 노드를 탐색하는 방법을 반복하면서 문제를 해결하는데, 이분 탐색을 재귀로 구현하는 것과 비슷하다.
#include<bits/stdc++.h> #define f first #define s second #define lp1(i, x, n) for(int i = x; i <= n; i++) using namespace std; typedef long long ll; const int dx[] = {-1, 0, 1, 0}; const int dy[] = {0, 1, 0, -1}; int t, n, m, k, sx, sy, ex, ey, x, y, z, answer, L, R, _x1, _x2, _y1, _y2, flag; int a[2000], visited[2000]; vector<int> res[10]; void DFS(int depth, int left, int right) { if(depth >= n) return; int root = (left + right) / 2; if((root >= 0 && root < k) && !visited[root]) { visited[root] = 1; res[depth].push_back(a[root]); DFS(depth + 1, left, root - 1); DFS(depth + 1, root + 1, right); } } int main() { //freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; k = (1 << n) - 1; for(int i = 0; i < k; i++) { cin >> a[i]; } if(n == 1) { cout << a[0]; return 0; } DFS(0, 0, k - 1); for(int i = 0; i < n; i++) { for(int j = 0; j < res[i].size(); j++) { cout << res[i][j] << " "; } cout << "\n"; } }
'알고리즘 문제풀이 > 백준' 카테고리의 다른 글
[백준/BOJ] N과 M (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11) (1) 2022.09.22 [백준/BOJ] 14620번 꽃길 (0) 2022.06.21 [백준/BOJ] 2529번 부등호 (0) 2022.05.29 [백준/BOJ] 14497번 주난의 난 (0) 2022.05.22 [백준/BOJ] 2589번 보물섬 (0) 2022.05.05