Description
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
Output
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
Source
当总的个数n为odd时,任何一个球都能到达圆圈中的每一个位置,所以就是YES。
当总的个数n为even时,那么如果这个球的位置在odd位置上,那么它能到任意一个odd位置,若在even位置上,则能到任意一个even位置。
那么不妨把黑球全部移到一起,不去管白球,那么如果偶数位置的黑球更多一些,中间就夹着少一个的奇数的空位,把剩下的那些奇数个黑球放进去,如果 even - odd = 0 or 1 ,那么这个时候是可以把空位放满的,否则就放不满,即NO;类似的如果odd位置的黑球更多一点,就判断odd - even = 0 or 1是否为真即可。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int even,odd;
int i,n,disk[30],T;scanf("%d",&T);
while(T){
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%d",&disk[i]);
if( n%2 == 1 ) printf("YES\n"); //n为odd,必然YES
else{
even=0,odd=0; //初始化even位和odd位的黑球数
for(i=0;i<n;i++){
if( disk[i]==1 && i%2==1 ) odd++; //odd位黑球计数
if( disk[i]==1 && i%2==0 ) even++; //even位黑球计数
}
if(abs(odd-even)>1) printf("NO\n"); //判断"|odd - even| = 0 or 1"是否成立
else printf("YES\n");
}
T--;
}
}