結果

問題 No.468 役に立つ競技プログラミング実践編
ユーザー kanetai
提出日時 2025-06-23 17:56:18
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 932 ms / 2,000 ms
コード長 2,157 bytes
コンパイル時間 334 ms
コンパイル使用メモリ 82,404 KB
実行使用メモリ 173,604 KB
最終ジャッジ日時 2025-06-23 17:56:33
合計ジャッジ時間 14,487 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 31
other AC * 6
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
#from typing import TypeVar
Weight = int #TypeVar('W')
Edge = tuple[int, int, Weight]

# adjList[u] = {(u, v, c)∈E | u,v∈V }, u: sorce node, v: target node, c: edge cost
def topological_sort(adjList: list[list[Edge]]) -> list[Weight]:
  result: list[int] = []
  V = len(adjList)
  E = 0
  indeg = [0 for _ in range(V)]
  q: deque[int] = deque()
  for i in range(V):
    E += len(adjList[i])
    for (s, t, c) in adjList[i]:
      indeg[t] += 1
  for i in range(V):
    if indeg[i] == 0:
      q.append(i)
  
  while len(q) != 0:
    t = q.popleft()
    result.append(t)
    for (u, v, c) in adjList[t]:
      E -= 1
      indeg[v] -= 1
      if indeg[v] == 0:
        q.append(v)
 
  if E != 0:
    raise ValueError('G is cyclic, not DAG.')
  
  return result

# edges[u] = {(u, v, c)∈E | u,v∈V }
def calc_EST(sortedNodes: list[int], adjList: list[list[Edge]]) -> list[Weight]:
  N = len(sortedNodes)
  EST: list[Weight] = [0] * N
  for u in sortedNodes:
    for (u, v, c) in adjList[u]:
      EST[v] = max(EST[v], EST[u] + c)
  return EST

# revEdges[v] = {(u, v, c)∈E | u,v∈V }
def calc_LST(revSortedNodes: list[int], revAdjList: list[list[Edge]], totalTime) -> list[Weight]:
  N = len(revSortedNodes)
  INF: Weight = 1 << 60
  LST: list[Weight] = [INF] * N
  LST[revSortedNodes[0]] = totalTime # index of end node = N-1 = revSortedNodes[0]
  for v in revSortedNodes:
    for (u, v, c) in revAdjList[v]:
      LST[u] = min(LST[u], LST[v]-c)
  return LST

# yukicoder No.468 <https://yukicoder.me/problems/no/468>
(N, M) = map(int, input().split())
adjList = [[] for _ in range(N)]
revAdjList = [[] for _ in range(N)]
for _ in range(M):
  (u, v, c) = map(int, input().split())
  adjList[u].append((u, v, c))
  revAdjList[v].append((u, v, c))

nodes = topological_sort(adjList=adjList)
EST = calc_EST(sortedNodes=nodes, adjList=adjList)
revNodes = list(reversed(nodes))
T = EST[revNodes[0]] # index of end node = N-1 = nodes[N-1] = revNodes[0]
LST = calc_LST(revSortedNodes=revNodes, revAdjList=revAdjList, totalTime=T)
count = sum(1 for i in range(N) if LST[i]-EST[i] > 0) #Slack[i] != 0

print(f"{T} {count}/{N}")
0