Skip to content

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

Description

@hwangJi-dev

💬 문제

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


💬 Idea

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

💬 풀이

import Foundation
func solution3584(){lett=Int(readLine()!)!
for_in1...t {letn=Int(readLine()!)!
varnodes=Array(repeating:0, count: n +1)for_in1..<n {letnode=readLine()!.components(separatedBy:.whitespaces).map({Int($0)! })nodes[node[1]]=node[0]}func dfs(_ start:Int)->[Int]{varvisitedQueue:[Int]=[]varneedToVisitNode= start
while needToVisitNode !=0{
visitedQueue.append(needToVisitNode)
needToVisitNode =nodes[needToVisitNode]}return visitedQueue
}lettc=readLine()!.components(separatedBy:.whitespaces).map({Int($0)! })func getCommonAncestor(_ n1:Int, _ n2:Int)->Int{letqueue1=dfs(n1)letqueue2=dfs(n2)return queue1.filter({ queue2.contains($0)}).first!
}print(getCommonAncestor(tc[0],tc[1]))}}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions