- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 112 lines of Python from the credited upstream file ccc11s5.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 59 60INF = 100000061 62file = open("s5.6.in", 'r')63K = eval(file.readline())64lights = []65for i in range(0,K):66 lights.append(eval(file.readline()))67group = []68N = 069group.append ([0, 0])70 71for i in range (0, K):72 if lights[i] == 1:73 if group[N][1] == 0:74 group[N][0] = i75 group[N][1] = i76 group[N][1] = group[N][1] + 177 elif group[N][1] != 0:78 N = N + 179 group.append ([0, 0])80 81if group[N][1] == 0:82 N = N - 183 group.pop()84 85N = N + 186minimumSwitches = []87for i in range(0,N+1):88 minimumSwitches.append (0)89 90numL = 091 92for i in range(N-1, -1, -1):93 minimumSwitches[i] = INF;94 numOnes = 0;95 96 j = i97 while j < N and ((group[j][1] - group[i][0]) <= 7):98 numOnes = numOnes + group[j][1] - group[j][0]99 len = max(4, group[j][1] - group[i][0]);100 t = len - numOnes101 102 103 if len == 6 and lights[group[i][0] + 2] == 1 and lights[group[i][0] + 3] == 1:104 t = INF105 elif len == 7 and lights[group[i][0] + 3] == 1:106 t = INF107 108 minimumSwitches[i] = min(minimumSwitches[i], t + minimumSwitches[j+1])109 110 j = j + 1111 112print minimumSwitches[0]