C - 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).
The goal of this puzzle is to gather the disks of the same color in adjacent positions using flips and shifts. (Figure 2)
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 file. 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
Sample Output
YES
NO
#include<stdio.h>
#include<math.h>
int main(){
int t;
scanf("%d",&t);
while(t--){
int sum;
scanf("%d",&sum);
int b[sum];
for(int i=0;i<sum;i++)
scanf("%d",&b[i]);
int x=0,y=0;
for(int i=0;i<sum;i++){
if(b[i]==0&&i%2==1) x++;
else if(b[i]==0&&i%2==0) y++;
}
if(sum%2==1)
{
printf("YES\n");
continue;
}
if(fabs(x-y)<=1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
思路:
sum为奇数时,奇数位的球可以换到偶数位上,一定能使黑白球各自连续
sum为偶数时,无论怎么换,球的位置的奇偶性不变,保证奇数位和偶数位的某颜色球数差值小于1即可