An archive stores n records in a fixed filing chain, numbered 1 to n. Each record has an integer value, a filing pointer to the next record in sequence (or none, at the end of a chain), and, independently, a single waypoint pointer to any other record in the archive used for quick cross-referencing (or none). Starting from a given record, you must execute a route: a sequence of moves, each either 'F' (follow the current record's filing pointer) or 'W' (follow the current record's waypoint pointer), in order. If, at some move, the current record has no pointer of the required kind, the route breaks and cannot be completed. Otherwise, after successfully executing every move in the route, report the value of the record you end on.
Line 1: an integer n, the number of records. Line 2: n integers, the values of records 1..n. Line 3: n integers, the filing-pointer target of records 1..n (0 means no filing pointer). Line 4: n integers, the waypoint-pointer target of records 1..n (0 means no waypoint pointer). Line 5: an integer start, the starting record. Line 6: a string of length L over the characters 'F' and 'W', the route to execute (this line may be empty when L = 0).
If the route completes all L moves, print the value of the final record reached. If the route breaks before completing (some required move has no target), print "BROKEN" instead.
Example 1
Input
4 10 20 30 40 2 3 4 0 3 0 0 0 1 FF
Expected
30
Explanation
Starting at record 1 (value 10), the route "FF" means: follow the filing pointer to record 2 (value 20), then follow the filing pointer again to record 3 (value 30). Both moves succeed, so the answer is the value of record 3, which is 30.
Example 2
Input
3 5 15 25 2 3 0 0 0 0 1 FW
Expected
BROKEN
Explanation
Starting at record 1, the first move 'F' follows the filing pointer to record 2 (value 15). The second move 'W' requires record 2's waypoint pointer, but record 2's waypoint pointer is 0 (none), so the route breaks before completing, and the output is "BROKEN".
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →