An excavation crew has mapped a sealed vault as a network of corridors branching outward, in the shape of a binary tree, from a single entrance chamber. At every junction along the way, restorers found a stone tablet stamped with a single digit, 0 or 1. Junctions with no further corridors are dead-end doors, each locked behind a dial that opens only to the correct passphrase. The passphrase for a given door is the binary number obtained by reading the stamped digits in order from the entrance chamber down to that door, with the entrance chamber's digit as the most significant bit.
You are given the full corridor map. Compute the sum, over every dead-end door, of its passphrase's numeric value.
The first line contains a single integer n, the number of junctions (numbered 0 to n-1; junction 0 is the entrance chamber).
Each of the next n lines describes junction i (for i from 0 to n-1) with three integers bit_i left_i right_i, where bit_i is the digit (0 or 1) stamped at that junction, and left_i/right_i are the indices of its two corridor branches, or -1 if that branch does not exist.
Print a single integer: the sum of the passphrases of all dead-end doors (junctions with no branches).
1 <= n <= 1000bit_i is 0 or 10; every junction other than 0 is reachable from exactly one other junction, and there are no cycles.Example 1
Input
7 1 1 2 0 3 4 1 5 6 0 -1 -1 1 -1 -1 0 -1 -1 1 -1 -1
Expected
22
Explanation
The entrance chamber (junction 0, digit 1) branches to junction 1 (digit 0) and junction 2 (digit 1). Junction 1 branches to leaves 3 (digit 0) and 4 (digit 1); junction 2 branches to leaves 5 (digit 0) and 6 (digit 1). Reading from the entrance: leaf 3's passphrase is 1,0,0 = binary 100 = 4; leaf 4 is 1,0,1 = 101 = 5; leaf 5 is 1,1,0 = 110 = 6; leaf 6 is 1,1,1 = 111 = 7. The sum is 4+5+6+7 = 22.
Example 2
Input
1 0 -1 -1
Expected
0
Explanation
The vault has only the entrance chamber, which is itself a dead-end door stamped with digit 0, giving a passphrase of 0 (binary "0"). The sum is 0.
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 →