#P7093. Merging Blocks Game
Merging Blocks Game
Merging Blocks Game
You are given a sequence of one dimensional blocks, where each block's length is a power of two. The blocks are presented one by one. For each block, you must decide whether to attach it immediately to the left or immediately to the right of the existing sequence of blocks. Every time two adjacent blocks have the same length, they immediately merge into a single block whose length is twice as long, i.e., if two blocks of length x merge, they become one block of length 2x. This merge may trigger further adjacent merges if possible. Note that at any moment there is at most one mergeable pair.
Your goal is to determine whether there exists a sequence of left/right insertions that results in the entire sequence merging into one single block. It turns out that a necessary and sufficient condition for this is that the total sum of the blocks equals a power of two. In mathematical terms, let the sum be \(S\). You win if and only if \(S\) can be expressed as \(2^k\) for some non-negative integer \(k\). That is, \(S\) is a power of two if \(S \&\ (S-1)=0\) (with \(S>0\)).
Analyze the given sequence to decide whether the game can be won.
inputFormat
The first line contains an integer \(n\) (\(1 \le n \le 10^5\)), the number of blocks.
The second line contains \(n\) space-separated integers \(b_1, b_2, \ldots, b_n\), each representing the length of a block. It is guaranteed that each \(b_i\) is a power of two.
outputFormat
Print Yes
if there exists a sequence of insertions that results in a single block after all possible merges; otherwise, print No
.
Recall that the winning condition is equivalent to the sum of all blocks being a power of two.
sample
3
2 4 16
No