문제) 백준 - 트리/DFS - 가장 가까운 공통 조상
https://www.acmicpc.net/problem/3584
3584번: 가장 가까운 공통 조상
루트가 있는 트리(rooted tree)가 주어지고, 그 트리 상의 두 정점이 주어질 때 그들의 가장 가까운 공통 조상(Nearest Common Anscestor)은 다음과 같이 정의됩니다. 두 노드의 가장 가까운 공통 조상은, 두
www.acmicpc.net
DFS를 통해 한 노드에 대하여 조상으로 올라가 트리를 순회하여 Set에 모든 조상을 저장합니다. 그 후, 공통 조상을 탐색할 다음 노드에 대하여 마찬가지로 트리를 순회합니다. 이때 탐색한 조상이 Set에 있을 경우, 그 조상을 반환하여 출력합니다.
C++ 소스코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void dfs(int now){ | |
visited[now] = true; | |
st.insert(now); | |
for(int next:graph[now]) | |
if(!visited[next]) | |
dfs(next); | |
} | |
int dfs2(int now){ | |
visited[now] = true; | |
if(st.find(now) != st.end()) | |
return now; | |
for(int next: graph[now]) | |
if(!visited[next]) | |
return dfs2(next); | |
} | |
int solve(int a, int b){ | |
st.clear(); | |
memset(visited, false, sizeof(visited)); | |
dfs(a); | |
memset(visited, false, sizeof(visited)); | |
return dfs2(b); | |
} |
Full Code)
GitHub - Chocochip101/BOJ_Solution: BOJ Solutions
BOJ Solutions. Contribute to Chocochip101/BOJ_Solution development by creating an account on GitHub.
github.com
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 21922번 - 학부 연구생 민상 (C++) 문제 및 풀이 (0) | 2022.02.21 |
---|---|
[백준] 5618번 - 공약수 (C++) 문제 및 풀이 (0) | 2022.02.21 |
[백준] 6118번 - 숨바꼭질 (C++) 문제 및 풀이 (0) | 2022.02.19 |
[백준] 2302번 - 극장 좌석 (C++) 문제 및 풀이 (0) | 2022.02.18 |
[백준] 21919번 - 소수 최소 공배수 (C++) 문제 및 풀이 (0) | 2022.02.18 |
댓글