Skip to content

Commit 77a58af

Browse files
committed
[Silver II] Title: 트리의 부모 찾기, Time: 104 ms, Memory: 12744 KB -BaekjoonHub
1 parent 20a49c0 commit 77a58af

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# [Silver II] 트리의 부모 찾기 - 11725
2+
3+
[문제 링크](https://www.acmicpc.net/problem/11725)
4+
5+
### 성능 요약
6+
7+
메모리: 12744 KB, 시간: 104 ms
8+
9+
### 분류
10+
11+
그래프 이론, 그래프 탐색, 트리, 너비 우선 탐색, 깊이 우선 탐색
12+
13+
### 제출 일자
14+
15+
2025년 1월 21일 10:38:41
16+
17+
### 문제 설명
18+
19+
<p>루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.</p>
20+
21+
### 입력
22+
23+
<p>첫째 줄에 노드의 개수 N (2 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N-1개의 줄에 트리 상에서 연결된 두 정점이 주어진다.</p>
24+
25+
### 출력
26+
27+
<p>첫째 줄부터 N-1개의 줄에 각 노드의 부모 노드 번호를 2번 노드부터 순서대로 출력한다.</p>
28+
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
#define MAX 100001
6+
7+
int graph[MAX];
8+
int visited[MAX];
9+
vector<int> tree[MAX];
10+
11+
void dfs(int k) {
12+
visited[k] = 1;
13+
14+
for (int i = 0; i < tree[k].size(); i++) {
15+
int next = tree[k][i];
16+
17+
if (!visited[next]) {
18+
graph[next] = k;
19+
dfs(next);
20+
}
21+
}
22+
}
23+
24+
int main() {
25+
int N;
26+
cin >> N;
27+
28+
for (int i = 1; i < N; i++) {
29+
int u, v;
30+
cin >> u >> v;
31+
tree[u].push_back(v);
32+
tree[v].push_back(u);
33+
}
34+
35+
dfs(1);
36+
37+
for (int i = 2; i <= N; i++) {
38+
cout << graph[i] << "\n";
39+
}
40+
41+
return 0;
42+
}

0 commit comments

Comments
 (0)