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. InputOne 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.OutputFor each testcase output a line consists of only the least times of switches.Sample Input3 1 1 13 1 0 1Sample Output10
分析:該題看似簡單但卻隱藏著陷阱,題目要求尋找的是最少的切換數,故從第二盞燈開始判斷處理得出的結論是不一定正確的。通過分析可以發現該題其實只存在兩種情況:奇數位置的燈開著或者偶數位置的燈開著。這樣可以直觀的處理該題:取奇數位置燈開著需要切換燈狀態數與偶數位置燈開著需切換燈狀態數的較小值。這樣的話需要掃描兩邊燈的狀態數組,開銷較大。進一步分析,設a為奇數位置的燈開著需要切換的燈數,b為偶數位置燈開著需要切換的燈數。其實a+b=n。這樣本題就只需要掃描一遍數組,且進一步優化后存儲燈狀態的數組也可以省了。具體代碼如下:
posts - 12, comments - 1, trackbacks - 0, articles - 1
Copyright © 李東亮