Toy Vending Machine
Time limit1sMemory limit1024 MB
Coins travel a tree of tubes, choosing the wider tube (left on ties) and reducing its width by 1; count the coins needed for a coin to first reach node v.
- Level
Hard8 of 10
- Topics
- Tree, Simulation, Greedy, Dynamic programming
- Solved
- No attempts yet
Problem
An arcade in city E installed a new generation game machine. You can drop a coin into the machine and watch it travel from top to bottom through a branching maze of tubes. The maze has nodes, numbered from 1 to . When a coin is dropped, it enters the first node. Every node except the first has exactly one tube entering from above, through which a coin can reach it. Each node has at most two tubes going down, one leading left and the other leading right. Each tube has a width. A coin falls into the wider tube, and if the two tubes have equal width, it falls into the left one.
After a coin passes through a tube, that tube's width decreases by 1. A coin cannot pass through a tube of width 0. If a coin reaches a node from which it cannot move further down, the machine stops and waits for the next coin to be dropped.
Initially, each node of the maze holds one toy. When a coin enters a node for the first time, the toy in that node is taken by the player who dropped that coin.
Pankrat likes the toy in the node numbered .
Write a program that determines how many coins Pankrat must drop into the machine to get the toy from node .
Input
The first line contains the number , the number of nodes in the maze. The next lines describe all the nodes; the -th of these lines describes the node numbered .
The description of node consists of four integers: , , , . If node has a left tube, then is the number of the node it leads to () and is its width. If there is no left tube, then . If node has a right tube, then is the number of the node it leads to () and is its width. If there is no right tube, then .
The last line contains the integer (), the number of the node holding the toy Pankrat likes.
Every node except the first has exactly one tube entering it.
Output
Print one number: the number of coins Pankrat must drop into the machine to get the toy in node . If the chosen toy cannot be obtained, print .
Constraints
Notes
In the first example, the first coin travels the maze along the following path, and the player gets the toys from nodes 1, 3, and 4:

The second coin travels the maze along the following path, and the player gets the toys from nodes 2 and 6: 
The third coin travels the maze along the following path, and the player gets the toys from nodes 5 and 7:
