- 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
- 62 lines of Python from the credited upstream file abc291_f.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- 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.
12 3 4def main():5 import sys6 7 input = sys.stdin.readline8 9 n, m = map(int, input().split())10 s = [input().rstrip() for _ in range(n)]11 12 13 inf = 10**1214 dist_1v = [inf] * n15 dist_vn = [inf] * n16 dist_1v[0], dist_vn[n - 1] = 0, 017 18 for i in range(n):19 for j in range(m):20 if s[i][j] == "0":21 continue22 23 dist_1v[i + j + 1] = min(dist_1v[i + j + 1], dist_1v[i] + 1)24 25 for i in range(n - 1, -1, -1):26 for j in range(m):27 if s[i][j] == "0":28 continue29 30 dist_vn[i] = min(dist_vn[i], dist_vn[i + j + 1] + 1)31 32 ans = list()33 34 35 36 for k in range(1, n - 1):37 candidate = inf38 39 for left in range(k - m, k):40 if left < 0:41 continue42 43 for right in range(k + 1, k + 1 + m):44 if right >= n or (right - left) > m:45 break46 47 if s[left][right - left - 1] == "0":48 continue49 50 candidate = min(candidate, dist_1v[left] + dist_vn[right] + 1)51 52 if candidate == inf:53 candidate = -154 55 ans.append(candidate)56 57 print(*ans)58 59 60if __name__ == "__main__":61 main()62