Question 1 : Nearest Meeting Cells
unknown
python
2 years ago
921 B
8
Indexable
# Question 1 : Nearest Meeting Cells def check(edges, cell_1, cell_2): a1 = [cell_1] while edges[cell_1] not in a1: a1.append(edges[cell_1]) cell_1 = edges[cell_1] if cell_2 in a1: return True a2 = [cell_2] while edges[cell_2] not in a2: if edges[cell_2] in a1: return True a2.append(edges[cell_2]) cell_2 = edges[cell_2] return False def res(a, m, n): k = [False for i in range(len(a))] k[n] = True k[m] = True while not (k[a[m]] or k[a[n]]): m = a[m] n = a[n] k[n] = True k[m] = True return a[m] if k[a[m]] == True else a[n] number_of_edges = int(input()) edges = [int(i) for i in input().split()] cells = [int(i) for i in input().split()] cell_1, cell_2 = int(cells[0]), int(cells[1]) if check(edges, cell_1, cell_2): print(res(edges, cell_1, cell_2)) else: print(-1)
Editor is loading...