A regional disaster-relief agency runs a beacon cascade: a single origin beacon tower broadcasts an alert to at most two regional relay towers, each of which forwards the alert to at most two towers of its own, and so on, so the whole network forms a strict binary cascade rooted at the origin. Every real tower in the cascade has a unique numeric identifier. Given the identifiers of two distinct towers that both exist in the cascade, determine whether they are peer towers: towers that sit the exact same number of hops from the origin but are not both fed directly by the same immediate upstream tower.
The cascade is given in breadth-first order, starting from the origin. Line 1 contains a single integer n, the number of tokens in the encoding on line 2. Line 2 contains n space-separated tokens describing the cascade: the first token is the origin tower's identifier; then, processing towers strictly in the order they were first added to the cascade (breadth-first, origin first), each tower contributes exactly two more tokens for its own two downstream slots — the left slot then the right slot — where a token of -1 means that slot is unused and any other token is the identifier of the tower placed there (that tower will itself later contribute its own two tokens once it is processed). This continues until every tower that was added has contributed its two slot tokens. Line 3 contains two integers x and y, the identifiers of the two towers to compare.
Print exactly true if towers x and y are peer towers (same hop-distance from the origin, different immediate upstream tower), otherwise print false.
-1 token is a tower identifier in the range [1, 10000], and all tower identifiers appearing in the cascade are distinctExample 1
Input
11 1 2 3 4 -1 -1 5 -1 -1 -1 -1 4 5
Expected
true
Explanation
The cascade has origin 1 with downstream towers 2 and 3 (hop 1). Tower 2 feeds only tower 4 (hop 2), and tower 3 feeds only tower 5 (hop 2). Towers 4 and 5 are both at hop-distance 2 from the origin, but their immediate upstream towers differ (2 vs 3), so they are peer towers and the answer is true.
Example 2
Input
7 10 20 30 -1 -1 -1 -1 20 30
Expected
false
Explanation
The cascade has origin 10 feeding towers 20 and 30 directly, so both are at hop-distance 1. However they share the same immediate upstream tower (10 itself), so they are not peer towers and the answer is false.
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 →