Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 가장 가까운 공통 조상 #215

Closed
hwangJi-dev opened this issue Apr 26, 2023 · 0 comments
Closed

[Algorithm] 가장 가까운 공통 조상 #215

hwangJi-dev opened this issue Apr 26, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Apr 26, 2023

💬 문제

https://www.acmicpc.net/problem/3584


💬 Idea

  • 각 노드의 가장 가까운 부모 노드를 배열에 저장한다.
  • 목표 노드부터 최상단 노드까지 거꾸로 탐색한 결과를 각각 도출한다. (q1, q2)
  • q1, q2의 공통 원소를 찾아 필터링하고 그 중 첫번째 노드를 출력한다.

💬 풀이

import Foundation

func solution3584() {
    let t = Int(readLine()!)!
    
    for _ in 1...t {
        let n = Int(readLine()!)!
        var nodes = Array(repeating: 0, count: n + 1)
        
        for _ in 1..<n {
            let node = readLine()!.components(separatedBy: .whitespaces).map({ Int($0)! })
            nodes[node[1]] = node[0]
        }
        
        func dfs(_ start: Int) -> [Int] {
            var visitedQueue: [Int] = []
            var needToVisitNode = start
            
            while needToVisitNode != 0 {
                visitedQueue.append(needToVisitNode)
                needToVisitNode = nodes[needToVisitNode]
            }
            
            return visitedQueue
        }
        
        let tc = readLine()!.components(separatedBy: .whitespaces).map({ Int($0)! })
        
        func getCommonAncestor(_ n1: Int, _ n2: Int) -> Int {
            let queue1 = dfs(n1)
            let queue2 = dfs(n2)
            return queue1.filter({ queue2.contains($0) }).first!
        }
        
        print(getCommonAncestor(tc[0], tc[1]))
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant