PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000027. Tổ tiên chung trên cây nhị phân (Lowest Common Ancestor of a Binary Tree)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổ tiên chung trên cây nhị phân (Lowest Common Ancestor of a Binary Tree)

Lowest Common Ancestor of a Binary Tree

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A binary tree has nn vertices indexed 11 through nn. Each vertex has at most one left and one right child, without the BST ordering restriction. Given two existing vertices p,qp,q, find their lowest common ancestor: the deepest vertex lying on both root-to-vertex paths. A vertex counts as its own ancestor.

The original LeetCode function interface is converted into an indexed-tree input/output interface for PHOJ.

Input

  • First line: n,rn,r, number of vertices and root index.
  • For each vertex ii, the next line contains its left and right child indices; 0 means absent.
  • Last line gives vertex indices p,qp,q.

Output

Print the lowest common ancestor vertex index.

Subtasks

General constraints (all subtasks): 2≤n≤1052\le n\le 10^5; 1≤p,q,r≤n1\le p,q,r\le n; p≠qp\ne q.

  • Subtask 1 (20 points): 2≤n≤302\le n\le 30; p≠qp\ne q.
  • Subtask 2 (30 points): 2≤n≤10002\le n\le 1000; p≠qp\ne q.
  • Subtask 3 (50 points): 2≤n≤1000002\le n\le 100000; p≠qp\ne q.

Examples

Input

5 1
2 3
4 5
0 0
0 0
0 0
4 5

Output

2

Explanation

Vertices 44 and 55 share parent 22, so their lowest common ancestor is 22.