Under construction

Still being built. Things may change

Marbles on the tree

Interview

Time limit1sMemory limit128 MB

Summary
Given a rooted ordered binary tree, find the leaf where the K-th marble stops, where each marble at a two-child node goes to the left if left subtree has at most the right subtree's resting marbles, else right.
Level

Medium6 of 10

Topics
Tree, DFS, Simulation, Binary search
Solved
No attempts yet

Problem

A binary tree is a tree in which every node has at most two children. The number drawn inside each node of the picture is the node number.

The binary tree in this problem is rooted at node 1, and the order of the children matters. You cannot swap the left side and the right side of any subtree.

Put one marble on the root. The marble falls by the following process.

  1. If the node holding the marble has no child, the marble stops there.
  2. If the node has exactly one child, the marble falls to that child.
  3. If the node has two children, the marble falls to the left child when the number of marbles already resting in the left subtree is less than or equal to the number of marbles already resting in the right subtree, and to the right child otherwise.
  4. Repeat the process until the marble stops.

Every marble ends up on a leaf. Marbles are dropped one at a time, and the next marble is put on the root only after the previous one has stopped.

Dropping marbles on the tree in the picture, the first five stop on nodes 2, 4, 2, 5, 2 in that order.

When the tree is small or the marbles are few, plain simulation tells you where each marble stops. The answer has to come out quickly for a large tree with a huge number of marbles as well.

Given a binary tree and KK, find the number of the node where the KK-th marble stops.

Input

The first line contains the number of nodes NN of the binary tree. (1≤N≤2000001 \le N \le 200000)

Each of the next NN lines contains two integers UU and VV. On the ii-th of these lines, UU is the left child of node ii and VV is the right child of node ii. If UU is −1-1, node ii has no left child. If VV is −1-1, node ii has no right child. A value other than −1-1 always satisfies 2≤U,V≤N2 \le U, V \le N.

The last line contains KK. (1≤K≤10181 \le K \le 10^{18})

The given tree is always a valid binary tree, and the root is node 1.

Output

Print the number of the node where the KK-th marble stops.

Examples2

  1. Example 1

    Input
    5
    2 3
    -1 -1
    4 5
    -1 -1
    -1 -1
    5
    
    Expected output
    2
    
  2. Example 2

    Input
    5
    2 3
    -1 -1
    4 5
    -1 -1
    -1 -1
    2
    
    Expected output
    4