importcollectionsimportsysfromtypingimportListdefsolution(N:int,tree:List[List[int]],A:int,B:int)->int:# A부터 부모 노드까지의 경로 지정 후
# B부터 부모 노드까지 탐색하며 A 경로와 겹치는 노드를 찾으면 됨
graph=collections.defaultdict(list)fortintree:a,b=tgraph[b]=a# A의 부모 노드들 배열 생성
A_parent=[]whileAingraph:A_parent.append(A)A=graph[A]# B의 부모 노드로 올라가면서
# A의 부모 노드 배열에 있는지 확인
whileBingraph:ifBinA_parent:breakB=graph[B]returnBT=int(sys.stdin.readline().rstrip())for_inrange(T):N=int(sys.stdin.readline().rstrip())tree=[]for_inrange(N-1):A_B=list(map(int,sys.stdin.readline().rstrip().split()))tree.append(A_B)A,B=map(int,sys.stdin.readline().rstrip().split())print(solution(N,tree,A,B))
Leave a comment