ABC291 F - Teleporter and Closed off
https://atcoder.jp/contests/abc291/tasks/abc291_f (opens in a new tab)
ๆฐด่ฒไธไฝใDPใ
keywords ้ ็นใ้ใใชใใ้ ็น k ใ้ใใชใใ็นๅฎใฎ้ ็นใ้ใใชใใใใ้ ็นใ้ใใชใใใใ้ฝๅธใ้ใใชใใ k ใ้ใใชใ
# dp0[i] := v(0) ~ v(i)ใธใฎๆ็ญ่ท้ข
# dp1[i] := v(i) ~ v(N - 1)ใธใฎๆ็ญ่ท้ข
2 ใคใฎ DP ้
ๅใ็จๆใใใใจใงไปปๆใฎ่พบใ้ใใใใชๆ็ญ่ท้ขใๆฑใใใใจใๅบๆฅใใ
ไปๅใฎๅถ็ดใงใฏใๅ้ ็นใซ้ฃๆฅใใ้ ็นใ้ซใ
10 ๅใใค้ฃ็ถใใ้ ็น็ชๅทไธใซๅญๅจใใใใใk
ใ้ใใชใใใใช่พบใๅ
จๆข็ดขใใใฐใใใใจใจใชใใ
่บใใ็นใฏ
dp0
,dp1
ใฎ่จ็ฎใๆๅ DFS ้ ใงใใฃใฆใใ
TLE๏ผ้ ็นi
ใซๅฏพใใฆ้ ็นi+1~i+m
ใ้ฃๆฅใใฆใใใใใชใฐใฉใใซใใใฆใ่จ็ฎ้ใฏ ๏ผ
dp1
ใใฉใๅใใใ
ๆๅน่พบใฎ้่พบใ็ฎก็ใใใใฎๆ
ๅ ฑใซๅบใฅใใฆdp1
ใ้้ ใซๅใใใใจ่ฉฆใฟใใ WA ใใ
for i in range(n)[::-1]: for j in graph[j] ...
ใจใใฆใใใใจใซๅพใ
ๆฐใฅใ
ๅฎใฏๆๅน่พบใฎ้่พบใไฟๅญใใฆใใชใใฆใใใใจใฎๆๅน่พบใฎใฟใงdp1
ใๅใใใใจใใงใใ๏ผๅฎ่ฃ
ไพๅ็
ง๏ผ
INF = float("inf")
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
edges = set()
for i in range(n):
s = input()
for j in range(m):
if s[j] == "1":
graph[i].append(i + j + 1)
edges.add((i, i + j + 1))
# dp0[i] := v(0) ~ v(i)ใธใฎๆ็ญ่ท้ข
dp0 = [INF] * n
# dp1[i] := v(i) ~ v(N - 1)ใธใฎๆ็ญ่ท้ข
dp1 = [INF] * n
dp0[0] = 0
for u in range(n):
for v in graph[u]:
dp0[v] = min(dp0[v], dp0[u] + 1)
dp1[-1] = 0
for u in range(n)[::-1]:
for v in graph[u]:
dp1[u] = min(dp1[u], dp1[v] + 1)
for k in range(1, n - 1):
ans = INF
for via in range(k - m, k):
for exit in range(k + 1, k + m + 1):
if (via, exit) in edges:
ans = min(ans, dp0[via] + dp1[exit] + 1)
if ans is INF:
print(-1)
else:
print(ans)