PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: nikhil_010309
Tester: raysh07
Editorialist: iceknight1093
DIFFICULTY:
TBD
PREREQUISITES:
None
PROBLEM:
There are N rooms arranged in a line, each room is either dangerous or safe; denoted by a binary string S.
Placing an alarm in room p protects all rooms in the range [\max(1, p-K), p].
Find the minimum number of alarms needed to make every room safe.
EXPLANATION:
Let the dangerous rooms be at positions x_1 \lt x_2 \lt\ldots\lt x_m
Looking at room x_m, we see that the only way to make it safe is to place an alarm at one of the rooms \{x_m, x_m+1, \ldots, x_m+K\}.
Of these, it’s easy to see that it’s optimal to place an alarm at x_m, since this will cover more earlier dangerous rooms than if we placed the alarm to the right.
After placing the alarm at x_m, several previously dangerous rooms will become safe; so we can ignore these rooms and then apply the exact same strategy.
That is, the solution is to simply repeatedly place an alarm at the rightmost dangerous room.
This can be easily implemented in \mathcal{O}(N^2) time, but it’s also possible to do in linear time by just iterating through the string in reverse and remembering the position of the latest placed alarm.
TIME COMPLEXITY:
\mathcal{O}(N) per testcase.
CODE:
Editorialist's code (PyPy3)
for _ in range(int(input())):
n, k = map(int, input().split())
s = input()
lst = 300
ans = 0
for i in reversed(range(n)):
if s[i] == '1' and i+k < lst:
ans += 1
lst = i
print(ans)