Flip and Shift
Time limit1sMemory limit128 MB
Given a circular binary string, decide whether repeated flips (swap the two outer of three consecutive disks) can gather all 1s and all 0s into two contiguous blocks.
- Level
Medium5 of 10
- Topics
- Math, Greedy, Implementation
- Solved
- No attempts yet
Problem
Black and white disks are arranged in an arbitrary order in a single row (a circular sequence) on an oval track.
In this puzzle you may use an operation called a flip. A flip takes three consecutive disks and turns the whole group over (rotates it by 180°): the middle disk stays in place while the two outer disks swap positions. (See Figure 1.) You may apply a flip to the three disks at any position on the track.


Given the color sequence of the disks arranged in a circle, write a program that decides whether a finite number of flips can gather all black disks into one contiguous block and all white disks into another contiguous block (as in Figure 2).
Input
The first line contains the number of test cases .
Each test case is given on a single line. The first number on the line is the length of the sequence (), followed by numbers describing the disks. Each number is the color of a disk: is a white disk and is a black disk. Here is the number of white () disks and is the number of black () disks. All numbers are separated by spaces.
Output
For each test case, print YES on its own line if the white and black disks can be separated into two contiguous blocks, and NO otherwise.