importsysfromtypingimportListsys.setrecursionlimit(10**5)defsolution(N:int,tree1:List[List[int]],tree2:List[List[int]])->List[int]:answer=[]graph=[[]for_inrange(N+1)]visited=[False]*(N+1)parent=[iforiinrange(N+1)]depth=[0]*(N+1)fortintree1:x,y=tgraph[x].append(y)graph[y].append(x)# 방문 여부를 확인하면서
# 해당 노드(node)와 연결된 노드에 깊이(d)를 1씩 증가시키면서 depth에 기록
defdfs(node,d):visited[node]=Truedepth[node]=dforningraph[node]:ifnotvisited[n]:parent[n]=nodedfs(n,d+1)# x, y 노드 중 가장 깊이가 깊은 노드를 y로 통일
# x, y의 깊이가 같아질 때까지 y를 parent[y]로 업데이트
# 두 노드의 깊이만큼 부모를 거슬러 올라감
deflca(x,y):ifdepth[x]>depth[y]:y,x=x,ywhileTrue:ifdepth[x]==depth[y]:breaky=parent[y]for_inrange(depth[x]):ifx==y:returnxx=parent[x]y=parent[y]returnxdfs(1,0)fortintree2:x,y=tanswer.append(lca(x,y))returnanswerN=int(sys.stdin.readline().rstrip())array1=[]for_inrange(N-1):array1.append(list(map(int,sys.stdin.readline().rstrip().split())))M=int(sys.stdin.readline().rstrip())array2=[]for_inrange(M):array2.append(list(map(int,sys.stdin.readline().rstrip().split())))print(*solution(N,array1,array2),sep='\n')
Leave a comment