結果

問題 No.1865 Make Cycle
ユーザー roaris
提出日時 2022-03-04 22:33:53
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,155 ms / 3,000 ms
コード長 1,019 bytes
コンパイル時間 187 ms
コンパイル使用メモリ 81,792 KB
実行使用メモリ 117,120 KB
最終ジャッジ日時 2024-07-18 21:06:07
合計ジャッジ時間 18,862 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 20
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5+10)
from collections import *

def dfs(v, pv, t):
    global pos
    
    seen[v] = True
    hist.append(v)
    
    for i, nv in G[v]:
        if t<i:
            continue
        
        if finished[nv]:
            continue
        
        if seen[nv] and not finished[nv]:
            pos = nv
            return
        
        dfs(nv, v, t)
        
        if pos!=-1:
            return
    
    hist.pop()
    finished[v] = True

N, Q = map(int, input().split())
G = [[] for _ in range(N)]

for i in range(Q):
    A, B = map(int, input().split())
    G[A-1].append((i+1, B-1))

l, r = 0, Q

while l<=r:
    m = (l+r)//2
    seen = [False]*N
    finished = [False]*N
    pos = -1
    hist = []
    
    for v in range(N):
        if not seen[v]:
            dfs(v, -1, m)
            
            if len(hist)>0:
                r = m-1
                break
    else:
        l = m+1

ans = l

if ans==Q+1:
    print(-1)
else:
    print(ans)
0