#define _USE_MATH_DEFINES #include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 1000000007; // constexpr int MOD = 998244353; constexpr int DY4[]{1, 0, -1, 0}, DX4[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}; constexpr int DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; std::vector detect_directed_cycle( const std::vector>& graph) { const int n = graph.size(); std::vector is_visited(n, 0), cycle; const std::function dfs = [&graph, &is_visited, &cycle, &dfs](const int ver) -> bool { is_visited[ver] = 1; cycle.emplace_back(ver); for (const int e : graph[ver]) { if (is_visited[e] == 1) { cycle.erase(cycle.begin(), std::find(cycle.begin(), cycle.end(), e)); cycle.emplace_back(e); return true; } else if (is_visited[e] == 0) { if (dfs(e)) return true; } } cycle.pop_back(); is_visited[ver] = 2; return false; }; for (int i = 0; i < n; ++i) { if (is_visited[i] == 0 && dfs(i)) break; } return cycle; } int main() { int n, q; cin >> n >> q; vector a(q), b(q); REP(i, q) cin >> a[i] >> b[i], --a[i], --b[i]; int lb = -1, ub = q; while (ub - lb > 1) { const int mid = (lb + ub) / 2; vector> graph(n); REP(i, mid + 1) graph[a[i]].emplace_back(b[i]); (detect_directed_cycle(graph).empty() ? lb : ub) = mid; } cout << (ub == q ? -1 : ub + 1) << '\n'; return 0; }