[백준 알고리즘]/[C++]
11725번 트리의 부모 찾기 | BFS, DFS | Baekjoon BOJ 백준 11725 C++ 코드, 해설, 풀이
말하는펭귄
2021. 2. 9. 19:31
728x90
반응형
이번 포스팅은 백준 11725번 트리의 부모 찾기입니다.
아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.
11725번: 트리의 부모 찾기
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
www.acmicpc.net
기본 알고리즘
BFS 너비 우선 탐색
DFS 깊이 우선 탐색
더보기
답안 출력 시 (line 48)
cout << parent[i] << endl; //시간 초과
printf("%d\n", parent[i]); //해결
전체 코드
BFS 너비 우선 탐색
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
//백준11725 트리의부모찾기
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n;
const int MAX = 100001;
vector<int> map[MAX];
bool visited[MAX];
int parent[MAX];
queue<int> q;
void BFS(int v) {
visited[v] = true;
q.push(v);
while (!q.empty()) {
v = q.front();
q.pop();
for (vector<int>::iterator iter = map[v].begin(); iter != map[v].end(); ++iter){
int w = *iter;
if (visited[w] == 0) {
parent[w] = v;
visited[w] = true;
q.push(w);
}
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
map[x].push_back(y);
map[y].push_back(x);
}
BFS(1);
for (int i = 2; i <= n; i++) {
printf("%d\n", parent[i]);
}
}
|
cs |
DFS 깊이 우선 탐색
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
32
33
34
35
36
37
38
39
40
|
//백준11725 트리의부모찾기
#include <iostream>
#include <vector>
using namespace std;
int n;
const int MAX = 100001;
vector<int> map[MAX];
bool visited[MAX];
int parent[MAX];
void DFS(int v) {
visited[v] = true;
for (vector<int>::iterator iter = map[v].begin(); iter != map[v].end(); ++iter) {
int w = *iter;
if (visited[w] == 0) {
parent[w] = v;
DFS(w);
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
map[x].push_back(y);
map[y].push_back(x);
}
DFS(1);
for (int i = 2; i <= n; i++) {
printf("%d\n", parent[i]);
}
}
|
cs |
728x90
반응형