A remote monitoring network is organized as a rooted binary tree of stations. Every leaf station is a raw sensor that independently reports either all-clear (encoded as 0) or alert (encoded as 1). Every non-leaf station is a fusion relay with exactly two child stations, and combines their reports using one of two fixed rules built into the relay:
2 ("escalate-any"): the relay reports alert if at least one child reports alert (logical OR).3 ("escalate-both"): the relay reports alert if both children report alert (logical AND).Given the full structure of the tree, determine what the root station ultimately reports.
The first line contains a single integer n, the number of stations. Stations are numbered 1 to n, and station 1 is always the root.
Each of the next n lines describes one station with three integers val left right:
val is 0 or 1, the station is a leaf and left = right = 0.val is 2 or 3, the station is a relay and left and right are the (distinct, non-zero) indices of its two child stations.Print a single integer: 1 if the root ultimately reports alert, 0 if it reports all-clear.
1 <= n <= 10^4n is always odd, and the described structure always forms a valid full binary tree (every station has exactly 0 or 2 children) rooted at station 1.Example 1
Input
3 3 2 3 1 0 0 0 0 0
Expected
0
Explanation
Station 1 is an escalate-both (AND) relay with children station 2 and station 3. Station 2 is a leaf reporting alert (1) and station 3 is a leaf reporting all-clear (0). AND requires both children to alert, and station 3 does not, so the root reports all-clear: 0.
Example 2
Input
5 2 2 5 3 3 4 1 0 0 0 0 0 1 0 0
Expected
1
Explanation
Station 1 is an escalate-any (OR) relay with children station 2 and station 5. Station 5 is a leaf reporting alert (1), so the OR is already satisfied by that branch alone (station 2 is itself an AND relay over leaf station 3 = alert and leaf station 4 = all-clear, which evaluates to all-clear, but that does not change the outcome). The root reports alert: 1.
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 →