Question 1 : Nearest Meeting Cells

mail@pastecode.io avatar
unknown
python
a year ago
921 B
4
Indexable
Never
# 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)