This page is still under construction.

Parts of this page are still being built. What you see may change.

Flip and Shift

Time limit1sMemory limit128 MB

Summary
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.

fns.png

fns2.png

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 TT.

Each test case is given on a single line. The first number on the line is the length of the sequence m+nm+n (10≤m+n<3010 \le m+n < 30), followed by m+nm+n numbers describing the disks. Each number is the color of a disk: 00 is a white disk and 11 is a black disk. Here mm is the number of white (00) disks and nn is the number of black (11) 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.

Examples1

  1. Example 1

    Input
    2
    18 0 0 1 0 1 1 1 1 0 1 0 0 1 0 0 0 0 1
    14 1 1 0 0 1 1 1 0 0 1 1 0 1 0
    
    Expected output
    YES
    NO