#include #include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; template vector> vec2d(int n, int m, T v){ return vector>(n, vector(m, v)); } template vector>> vec3d(int n, int m, int k, T v){ return vector>>(n, vector>(m, vector(k, v))); } template void print_vector(vector v, char delimiter=' '){ if(v.empty()) { cout << endl; return; } for(int i = 0; i+1 < v.size(); i++) cout << v[i] << delimiter; cout << v.back() << endl; } bool topological_sort(vector> g, vector &order){ int n = g.size(); order.clear(); vector used(n, false); function dfs = [&](int v){ used[v] = true; for(int to : g[v]){ if(!used[to]) dfs(to); } order.push_back(v); }; for(int v = 0; v < n; v++){ if(!used[v]) dfs(v); } reverse(order.begin(), order.end()); vector inv_order(n); for(int i = 0; i < n; i++) inv_order[order[i]] = i; for(int v = 0; v < n; v++){ for(int u : g[v]){ if(inv_order[v] > inv_order[u]) return false; } } return true; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int n, q; cin >> n >> q; vector a(q), b(q); for(int i = 0; i < q; i++){ cin >> a[i] >> b[i]; a[i]--; b[i]--; } auto judge = [&](int x){ vector> g(n); for(int i = 0; i < x; i++){ g[a[i]].push_back(b[i]); } vector ord; return !topological_sort(g, ord); }; if(!judge(q)){ cout << -1 << endl; return 0; } int l = 0, r = q; while(r-l > 1){ int x = (l+r)/2; if(judge(x)) r = x; else l = x; } cout << r << endl; }