結果

問題 No.1364 [Renaming] Road to Cherry from Zelkova
ユーザー neterukunneterukun
提出日時 2021-01-22 22:29:20
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 483 ms / 2,500 ms
コード長 2,215 bytes
コンパイル時間 317 ms
コンパイル使用メモリ 82,504 KB
実行使用メモリ 174,384 KB
最終ジャッジ日時 2024-12-29 09:07:51
合計ジャッジ時間 13,371 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 45
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.buffer.readline


def topological_sorted(digraph):
    n = len(digraph)
    indegree = [0] * n
    for v in range(n):
        for nxt_v in digraph[v]:
            indegree[nxt_v] += 1

    tp_order = [i for i in range(n) if indegree[i] == 0]
    stack = tp_order[:]
    while stack:
        v = stack.pop()
        for nxt_v in digraph[v]:
            indegree[nxt_v] -= 1
            if indegree[nxt_v] == 0:
                stack.append(nxt_v)
                tp_order.append(nxt_v)

    return len(tp_order) == n, tp_order


n, m = map(int, input().split())
edges = [list(map(int, input().split())) for i in range(m)]
MOD = 10 ** 9 + 7


graph = [[] for i in range(n + 1)]
for u, v, _, _ in edges:
    graph[u].append(v)
rev_graph = [[] for i in range(n + 1)]
for u, v, _, _ in edges:
    rev_graph[v].append(u)

root = 0
reach = [False] * (n + 1)
reach[0] = True
stack = [root]
while stack:
    v = stack.pop()
    for nxt_v in graph[v]:
        if reach[nxt_v]:
            continue
        reach[nxt_v] = True
        stack.append(nxt_v)

root = n
rev_reach = [False] * (n + 1)
rev_reach[n] = True
stack = [root]
while stack:
    v = stack.pop()
    for nxt_v in rev_graph[v]:
        if rev_reach[nxt_v]:
            continue
        rev_reach[nxt_v] = True
        stack.append(nxt_v)

if not reach[n]:
    print(0)
    exit()

for i in range(n + 1):
    reach[i] = reach[i] & rev_reach[i]

graph = [set() for i in range(n + 1)]
memo = {}
for u, v, l, a in edges:
    if reach[u] and reach[v]:
        graph[u].add(v)
        if (u, v) not in memo:
            memo[u, v] = []
        memo[u, v].append((l, a))

flag, tp_order = topological_sorted(graph)
if not flag:
    print("INF")
    exit()

    

nxt_ptn = [0] * (n + 1)
nxt_ptn[n] = 1
for v in tp_order[::-1]:
    for nxt_v in graph[v]:
        for l, a in memo[v, nxt_v]:
            nxt_ptn[v] += nxt_ptn[nxt_v] * a
            nxt_ptn[v] %= MOD

ans = 0
ptn = [0] * (n + 1)
ptn[0] = 1
for v in tp_order:
    for nxt_v in graph[v]:
        for l, a in memo[v, nxt_v]:
            ptn[nxt_v] += ptn[v] * a
            ans += ptn[v] * nxt_ptn[nxt_v] * l * a
            ptn[nxt_v] %= MOD
            ans %= MOD
print(ans)
0