A telecom crew is building a binary relay network shaped like a complete binary tree: a single master tower sits at the top (level 0), and every tower below has at most two child relays, a left one and a right one. The crew always finishes an entire level before starting the next, and within the deepest level (the one still being built) they always install relays strictly left to right — once a position in that level is skipped, no later position in that same level may be installed.
You are told that levels 0 through h-1 are already fully deployed (so h is the number of fully completed levels above the deepest one), and you are given the deepest level's installation record as a string of length 2^h: one character per possible position in that level, read left to right, where 1 means a relay is installed there and 0 means it is not.
Determine whether this record is consistent with left-to-right installation. If it is, report the total number of relays installed across the whole network (the fully deployed levels plus the deepest level). If it is not (some position is installed after an earlier position was skipped), report that the record is invalid.
Line 1: an integer h.
Line 2: a string s of length exactly 2^h, consisting only of the characters 0 and 1.
If the record is consistent with left-to-right installation, print a single integer: the total number of relays installed, equal to (2^h - 1) plus the number of 1 characters in s. Otherwise, print exactly INVALID.
s has length exactly 2^h and contains only 0 and 1Example 1
Input
2 1101
Expected
INVALID
Explanation
h=2 so the deepest level has 2^2=4 positions, record '1101'. Reading left to right: position 0 is '1', position 1 is '1', position 2 is '0' (skipped), position 3 is '1' — but a relay is installed at position 3 after position 2 was skipped, which breaks the left-to-right rule. The record is INVALID.
Example 2
Input
3 11100000
Expected
10
Explanation
h=3 so the deepest level has 2^3=8 positions, record '11100000'. The first 3 positions are '1' and the remaining 5 are '0' — a clean prefix of installed relays, so the record is valid. Total relays = (2^3 - 1) + 3 = 7 + 3 = 10.
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 →