local n, q = io.read("*n", "*n") local ea, eb = {}, {} local ccnt, parent = {}, {} for i = 1, n do ccnt[i] = 0 parent[i] = {} end for iq = 1, q do local a, b = io.read("*n", "*n") ea[iq], eb[iq] = a, b ccnt[a] = ccnt[a] + 1 if parent[b][a] then parent[b][a] = parent[b][a] + 1 else parent[b][a] = 1 end end local tasks = {} for i = 1, n do if ccnt[i] == 0 then table.insert(tasks, i) end end local done = 0 local function rm() while done < #tasks do done = done + 1 local src = tasks[done] for p, c in pairs(parent[src]) do ccnt[p] = ccnt[p] - c if ccnt[p] == 0 then table.insert(tasks, p) end end end end rm() if done == n then print(-1) os.exit() end for iq = q, 1, -1 do local a, b = ea[iq], eb[iq] parent[b][a] = parent[b][a] - 1 if parent[b][a] == 0 then parent[b][a] = nil end ccnt[a] = ccnt[a] - 1 if ccnt[a] == 0 then table.insert(tasks, a) rm() end if done == n then print(iq) break end end