N bulbs are in a row from left to right,some are on, and some are off.The first bulb is the most left one. And the last one is the most right one.they are numbered from 1 to n,from left to right.
in order to save electricity, you should turn off all the lights, but you’re lazy.
coincidentally,a passing bear children paper(bear children paper means the naughty boy), who want to pass here from the first light bulb to the last one and leave.
he starts from the first light and just can get to the adjacent one at one step.
But after all,the bear children paper is just a bear children paper. after leaving a light bulb to the next one, he must touch the switch, which will change the status of the light.
your task is answer whether it’s possible or not to finishing turning off all the lights, and make bear children paper also reach the last light bulb and then leave at the same time.
Input
The first line of the input file contains an integer T, which indicates the number of test cases.
For each test case, there are 2 lines.
The first line of each test case contains 1 integers n.
In the following line contains a 01 sequence, 0 means off and 1 means on.
- 1≤T≤10
- 1≤N≤1000000
Output
There should be exactly T lines in the output file.
The i-th line should only contain “YES” or “NO” to answer if it’s possible to finish.
Sample Input
1
5
1 0 0 0 0
Sample Output
YES
Hint
Child’s path is: 123234545
all switchs are touched twice except the first one.
题意:题中给一段0和1组成的序列表示灯的初始状态,有个熊孩子他想从第一个灯泡走到最后一个灯泡,然后离开,在这过程中他可以走到任意一个相邻的灯泡上,可以折返,步数不限,每经过一个灯泡,熊孩子会按下灯泡开关,问你他有没有可能把这段灯泡都关闭。
解题思路: 如果经过1(灯泡开着)则直接走过,如果经过0,则分两种情况,第一种,如果后一个还是 0,则走到下一个,再折返回来,再到下一个时,两个灯泡还是0 0状态,符合题意;第二种,如果后一个是 1 ,则用一个变量记录这种情况出现的次数,通过例子的实验,这种情况如果是偶数次,则通过折返法就能使灯泡都关掉,否则无论怎么走都不可能使全部为 0 。
结论:只要 0 连续出现的偶数段都能用折返法使其为 0 不变,0 连续出现的奇数段的数量为偶数则可以通过0 1的折返转递最终都消为 0 。所以只要计算出 0 连续出现的奇数段的数量判段是不是偶数就可得出答案。
#include<stdio.h>
int a[1000005];
int main()
{
int t,i,j,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0; i<n; ++i)
scanf("%d",&a[i]);
int t0 = 0;
for(i=0; i<n; ++i)
{
if(a[i]==0)
{
if(i+1<n) //注意数组边界的判断
{
if(a[i+1]==1)
t0++;
else
i++;
}
else
t0++;
}
}
if(t0%2==0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}