SWITCH
題目描述如下:
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
分析:該題看似簡單但卻隱藏著陷阱,題目要求尋找的是最少的切換數(shù),故從第二盞燈開始判斷處理得出的結(jié)論是不一定正確的。通過分析可以發(fā)現(xiàn)該題其實(shí)只存在兩種情況:奇數(shù)位置的燈開著或者偶數(shù)位置的燈開著。這樣可以直觀的處理該題:取奇數(shù)位置燈開著需要切換燈狀態(tài)數(shù)與偶數(shù)位置燈開著需切換燈狀態(tài)數(shù)的較小值。這樣的話需要掃描兩邊燈的狀態(tài)數(shù)組,開銷較大。進(jìn)一步分析,設(shè)a為奇數(shù)位置的燈開著需要切換的燈數(shù),b為偶數(shù)位置燈開著需要切換的燈數(shù)。其實(shí)a+b=n。這樣本題就只需要掃描一遍數(shù)組,且進(jìn)一步優(yōu)化后存儲(chǔ)燈狀態(tài)的數(shù)組也可以省了。具體代碼如下:

2

3

4

5



6

7

8

9

10

11

12



13

14

15

16

17



18

19

20



21

22



23

24

25

26



27

28

29

30

31

32

33

34

35

36

37

38

39

posted @ 2010-09-20 09:31 李東亮 閱讀(331) | 評(píng)論 (0) | 編輯 收藏