結果

問題 No.1865 Make Cycle
ユーザー titan23titan23
提出日時 2022-06-28 02:40:52
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,177 ms / 3,000 ms
コード長 1,103 bytes
コンパイル時間 168 ms
コンパイル使用メモリ 82,900 KB
実行使用メモリ 272,976 KB
最終ジャッジ日時 2024-04-30 15:59:52
合計ジャッジ時間 16,618 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 677 ms
178,532 KB
testcase_01 AC 479 ms
157,416 KB
testcase_02 AC 847 ms
213,488 KB
testcase_03 AC 325 ms
149,312 KB
testcase_04 AC 594 ms
202,076 KB
testcase_05 AC 727 ms
221,764 KB
testcase_06 AC 686 ms
192,408 KB
testcase_07 AC 661 ms
197,656 KB
testcase_08 AC 838 ms
220,840 KB
testcase_09 AC 699 ms
202,124 KB
testcase_10 AC 777 ms
216,680 KB
testcase_11 AC 732 ms
198,020 KB
testcase_12 AC 634 ms
188,400 KB
testcase_13 AC 700 ms
185,812 KB
testcase_14 AC 477 ms
152,940 KB
testcase_15 AC 869 ms
218,740 KB
testcase_16 AC 961 ms
250,724 KB
testcase_17 AC 622 ms
178,396 KB
testcase_18 AC 753 ms
235,412 KB
testcase_19 AC 1,177 ms
272,976 KB
testcase_20 AC 44 ms
54,588 KB
testcase_21 AC 43 ms
55,464 KB
testcase_22 AC 44 ms
55,300 KB
testcase_23 AC 43 ms
55,776 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque
input = lambda: sys.stdin.readline().rstrip()

def topological_sort(G: list) -> list:
  "Return topological_sort. / O(|V|+|E|)"
  # 0-indexed
  # len(toposo) != n: 閉路が存在
  n = len(G)
  in_cnt = [0] * n
  outs = [[] for _ in range(n)]
  for v in range(n):
    for x in G[v]:
      in_cnt[x] += 1
      outs[v].append(x)
  res = []
  todo = deque([i for i in range(n) if in_cnt[i] == 0])
  while todo:
    v = todo.popleft()
    res.append(v)
    for x in outs[v]:
      in_cnt[x] -= 1
      if in_cnt[x] == 0:
        todo.append(x)
  return res

#  -----------------------  #

n, q = map(int, input().split())
AB = [list(map(lambda x: int(x)-1, input().split())) for _ in range(q)]

def isok(mid):
  G = [[] for _ in range(n)]
  for i in range(mid):
    a = AB[i][0]
    b = AB[i][1]
    G[a].append(b)
  toposo = topological_sort(G)
  if len(toposo) != n:
    return True
  else:
    return False

ok, ng = q+1, -1
while ok - ng > 1:
  mid = (ok + ng) // 2
  if isok(mid):
    ok = mid
  else:
    ng = mid
if ok == q+1:
  print(-1)
else:
  print(ok)
0