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 |
Tags
- Team Fortress 2
- c++
- 투 포인터
- 브루트포스
- 자료구조
- 그리디 알고리즘
- 구현
- BFS
- 다이나믹 프로그래밍
- 트리
- 시뮬레이션
- DFS
- 알고리즘
- 정렬
- Unreal Engine 5
- 유니티
- 누적 합
- 재귀
- ue5
- 백준
- 백트래킹
- 그래프
- VR
- 문자열
- 스택
- 유니온 파인드
- 수학
- XR Interaction Toolkit
- 우선순위 큐
- 다익스트라
Archives
- Today
- Total
1일1알
백준 1068번 트리 C++ 본문
1. root부터 탐색하면서 삭제할 노드의 부모 노드를 알아낸다.
2. 삭제할 노드를 dfs를 이용하여 제일 밑에있는 자식 노드부터 차례로 삭제한다.
3. 2번이 끝났으면 삭제할 노드의 자식들은 모두 삭제가 된 상태이기 때문에 1번에서 파악한 부모 노드를 이용하여 삭제할 노드를 삭제한다.
4. root부터 탐색하면서 리프 노드의 갯수를 알아낸다.
예외) 삭제할 노드가 root노드라면 부모 노드가 없기때문에 0을 출력하고 프로그램을 종료한다.
#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 <unordered_map>
#include <unordered_set>
using namespace std;
typedef long long ll;
int n, del;
int cnt = 0;
vector<vector<int>> tree(51, vector<int>());
void DeleteNode(int node) {
for (auto child : tree[node]) {
DeleteNode(child);
auto it = find(tree[node].begin(), tree[node].end(), child);
tree[node].erase(it);
}
}
void FindAndDeleteNode(int node) {
for (auto child : tree[node]) {
if (child == del) {
DeleteNode(child);
auto it = find(tree[node].begin(), tree[node].end(), child);
tree[node].erase(it);
}
FindAndDeleteNode(child);
}
}
void FindLeafNode(int node) {
for (auto child : tree[node]) {
FindLeafNode(child);
}
if (tree[node].size() == 0) cnt++;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
int parent;
int root;
for (int i = 0; i < n; i++) {
cin >> parent;
if (parent == -1) {
root = i;
continue;
}
tree[parent].push_back(i);
}
cin >> del;
if (del == root) {
cout << 0;
return 0;
}
FindAndDeleteNode(root);
FindLeafNode(root);
cout << cnt;
};
'알고리즘' 카테고리의 다른 글
백준 16922번 로마 숫자 만들기 C++ (0) | 2022.01.16 |
---|---|
백준 2210번 숫자판 점프 C++ (0) | 2022.01.16 |
백준 5014번 스타트링크 C++ (0) | 2022.01.14 |
백준 13549번 숨바꼭질 3 C++ (0) | 2022.01.13 |
백준 9019번 DSLR C++ (0) | 2022.01.12 |