#BST0000018. Kiểm tra cây tìm kiếm nhị phân (Validate Binary Search Tree)

Kiểm tra cây tìm kiếm nhị phân (Validate Binary Search Tree)

Validate Binary Search Tree

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A binary tree with nn nodes is given. It is a valid BST if all of the following conditions hold at every node with key vv:

  • every key in the left subtree is strictly smaller than vv;
  • every key in the right subtree is strictly greater than vv;
  • both subtrees satisfy the same definition.

The inequalities are strict, so two equal keys cannot both appear in a valid BST.

Determine whether the given tree is a valid BST.

Input

The first line contains nn and the root index rr.

Exactly nn lines follow. Line ii describes node ii as key left right. A child index of 00 means that the child is absent; any nonzero child index is in [1,n][1,n].

The input is guaranteed to describe exactly one connected, acyclic binary tree rooted at rr.

Output

Print YES if the tree is a valid BST; otherwise print NO.

Subtasks

Subtask 1 (20 points): 1≤n≤201\le n\le 20.

Subtask 2 (30 points): 1≤n≤5001\le n\le 500.

Subtask 3 (50 points): 1≤n≤1041\le n\le 10^4.

In all subtasks, −231≤key≤231−1-2^{31}\le \text{key}\le 2^{31}-1.

Examples

Input

5 1
8 2 3
3 4 5
10 0 0
1 0 0
9 0 0

Output

NO

Explanation

The node with key 99 is in the left subtree of the root with key 88. A valid BST requires every key in that entire subtree to be smaller than 88, but 9>89>8.

Therefore the tree is invalid and the output is NO.