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 |
| 31 |
Tags
- 11286번
- BFS
- dx12
- C++
- 24779
- 2075번
- 뱀과사다리게임
- 다음소수
- dx12 정리
- 2565번
- WinAPI
- 백준 c++ 24479번
- 루트서명
- 랜더링 파이프라인
- 그리기 연산
- 바이토닉 수열
- directx12 그리기 연산2
- 백준 1260 c++
- 드래곤플라이트 모작
- 백준 24444 c++
- Perforce
- lis응용
- 백준
- unrealengine
- 4134번
- Unreal
- 애니메이션
- 다익스트라
- DirectX12
- 2d 박스충돌
Archives
- Today
- Total
game-1 님의 블로그
[백준] 11725번 C++ 트리의 부모 찾기 본문



연결 노드들을 그려보면 다음과 같은 그림이 나옵니다.

풀이)
2번부터 n번까지의 노드들의 부모들을 찾아야합니다.
이때 저는 트리를 인접리스트로 구현하였으며 BFS가 익숙하기 때문에 노드들을 찾는 과정은 bfs를 사용하였으며,
다음 노드를 찾고 해당 노드의 부모를 배열에 저장해 주는 방식으로 구현하였습니다.
코드)
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int MAX = 100'001;
vector<int>tree[MAX];
bool visited[MAX]{};
int arr[MAX]{};
void bfs(int start) {
queue<int> q;
q.push(start);
visited[start] = true;
while (not q.empty()) {
int nx = q.front();
q.pop();
for (int node : tree[nx]) {
if (not visited[node]) {
q.push(node);
visited[node] = true;
arr[node] = nx;
}
}
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n-1; ++i) {
int u, v;
cin >> u >> v;
tree[u].push_back(v);
tree[v].push_back(u);
}
bfs(1);
for (int i = 2; i <= n; ++i) {
cout << arr[i] << '\n';
}
}

'백준 문제풀이' 카테고리의 다른 글
| [백준] 12865번 c++ 평범한 배낭 (0) | 2025.01.23 |
|---|---|
| [백준]9251번 C++ , LCS(최장 공통 부분 수열) (0) | 2025.01.22 |
| [백준] 3273번 두 수의 합 C++ (1) | 2025.01.18 |
| [백준] 2565번 C++ 전깃줄 (1) | 2025.01.17 |
| [백준] C++ 16928번 뱀과 사다리 게임 (1) | 2025.01.16 |