F - Virus 2 解説 by evima

Another Solution

Consider calculating the pairs \((d_i, e_i)\), where \(d_i\) represents the day room \(i\) was first infected, and \(e_i\) is the shortest distance to room \(i\) from a room that was infected on or before day \(d_i - 1\), similarly to Dijkstra’s algorithm. (See the sample implementation below.) The difficulty is when the transmission is carried over to a later day. However, if you prepare in advance so that, given \(d\) and \(w\), you can quickly find the earliest day on or after day \(d+1\) when \(X_j\) is at least \(w\), you will be in time.

Sample Implementation of the Main Part (Python. The complete code is here: https://atcoder.jp/contests/abc307/submissions/42933837)

c = [(D + 1, 0) for _ in range(N)]
for a in A:
    c[a] = 0, 0
q = [(0, 0, a) for a in A]
while len(q):
    d, e, u = heapq.heappop(q)
    if (d, e) > c[u]:
        continue
    for v, w in g[u]:
        if e + w <= X[d]:
            nd, ne = d, e + w
        else:
            nd, ne = find(d + 1, w), w
        if (nd, ne) < c[v]:
            c[v] = nd, ne
            heapq.heappush(q, (nd, ne, v))
for d, e in c:
    print(d if d <= D else -1)

投稿日時:
最終更新: