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 parent[b][iq] = true 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 pi, _u in pairs(parent[src]) do local p = ea[pi] ccnt[p] = ccnt[p] - 1 if ccnt[p] == 0 then table.insert(tasks, p) end end parent[src] = {} 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] if parent[b][iq] then parent[b][iq] = nil ccnt[a] = ccnt[a] - 1 if ccnt[a] == 0 then table.insert(tasks, a) rm() end end if done == n then print(iq) break end end