D - Switch
ZOJ - 1622
There are N lights in a line. Given the states (on/off) of the lights, your task is to determine at least how many lights should be switched (from on to off, or from off to on), in order to make the lights on and off alternatively.
Input
One line for each testcase.
The integer N (1 <= N <= 10000) comes first and is followed by N integers representing the states of the lights ("1" for on and "0" for off).
Process to the end-of-file.
Output
For each testcase output a line consists of only the least times of switches.
Sample Input
3 1 1 1
3 1 0 1
Sample Output
1
0
題意:燈開關(guān)分別用0 1表示瑟俭,求最少開或關(guān)幾盞燈使燈成為01交替的序列萍恕。
解法:水題鞋屈,兩種情況咖祭,0開始或1開始瓢剿,一趟遍歷册踩,分別用x工闺,y記錄每種情況要動幾盞燈桥氏,最后取xy中最小值温峭。
代碼:
#include<iostream>
using namespace std;
int a[10005];
int main()
{
int num;
while(cin>>num){
for(int i=0;i<num;i++)
cin>>a[i];
int x=0,y=0;
for(int i=0;i<num;i++)
i%2?(a[i]?x++:y++):(!a[i]?x++:y++);
cout<<min(x,y)<<endl;
}
return 0;
}