Flip and Shift

This puzzle consists of a random sequence of m black disks and n white disks on an oval-shaped track, with a turnstile capable of flipping (i.e., reversing) three consecutive disks. In Figure 1, there are 8 black disks and 10 white disks on the track. You may spin the turnstile to flip the three disks in it or shift one position clockwise for each of the disks on the track (Figure 1).





Figure 1. A flip and a shift



The goal of this puzzle is to gather the disks of the same color in adjacent positions using flips and shifts. (Figure 2)





Figure 2. A goal sequence



You are to write a program which decides whether a given sequence can reach a goal or not. If a goal is reachable, then write a message ��YES��; otherwise, write a message ��NO��.


Input

The input consists of T test cases. The number of test cases ) (T is given in the first line of the input. Each of the next T lines gives a test case. A test case consists of an integer, representing the sum of m and n, and a sequence of m+n 0s and 1s, representing an initial sequence. A 0 denotes a white disk and a 1 denotes a black disk. The sum of m and n is at least 10 and does not exceed 30. There is a space between numbers.


Output

The output should print either ��YES�� or ��NO�� for each test case, one per line.


Sample 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


Output for the Sample Input

YES
NO

题意:给你一个黑白的盘组成的环,盘i可以和i-2或i+2交换位置,求能否使得最后分为黑白两条带

思路:很明显i可以可i-2和i+2交换,也就是说交换后i的奇偶性并为改变,而目标是使得黑白的都是奇偶相连

则有当n(黑白盘的总数)奇数时,可以发现任何奇偶的位置都是可以交换的,所以输出YES

例如:n=8;从1开始1->>3->>5->>8->>2

而当n为偶数时,可以想像当以黑白排一排时是奇偶相间的,也就是说黑白盘的奇偶数的差值在不大于1的情况下是可以满足的,

也就是说假设黑盘数为偶数,则要要求它位置的奇偶数是相等的,而当黑盘数为奇数时则要求奇偶数的差的绝对值为1则可

#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
	int t;
	scanf("%d", &t);
	while(t--){
		int n;
		scanf("%d", &n);
		int s1=0,s2=0;
		int a; 
		for(int i = 1; i <= n; i++){
			scanf("%d",&a);
			if(n%2==1)//奇数直接一直跳过就行 
				continue;
			if(a==0 && i%2==1)//记录白色的盘的位置(奇数的个数) 
				s1 ++;
			else if(a==0 && i%2==0)//记录白色的盘的位置(偶数的个数) 
				s2 ++;
		}
		if(n%2==1){
			printf("YES\n");
			continue;
		}
		if(s1-s2<=1 && s1-s2>=-1)
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/doublekillyeye/article/details/81077262