#define _USE_MATH_DEFINES #include using namespace std; //template #define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define ALL(v) (v).begin(),(v).end() typedef long long int ll; const int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12; templateinline bool chmax(T& a,T b){if(ainline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;} //end typedef pair P; int n,m; vector

g[501010]; vector res; int used[501010]; P par[501010]; bool dfs(int v){ used[v]=1; for(auto& e:g[v]){ par[v]={e.first,e.second}; if(used[e.first]==0 and dfs(e.first))return 1; else if(used[e.first]==1){ int cur=e.first; do{ res.push_back(par[cur].second); cur=par[cur].first; }while(cur!=e.first); return 1; } } used[v]=2; return 0; } bool cyclic(){ rep(i,0,n)used[i]=0,par[i]={-1,-1}; rep(i,0,n)if(used[i]==0 and dfs(i))return 1; return 0; } int main(){ scanf("%d%d",&n,&m); vector h(n); rep(i,0,m){ int x,y; scanf("%d%d",&x,&y); x--; y--; g[x].push_back({y,i}); h[y]++; } if(cyclic()){ puts("-1"); } else{ queue none; rep(i,0, n) { if (h[i] == 0) { none.push(i); } } vector tsort; while (none.size()) { int i = none.front(); none.pop(); tsort.push_back(i); for (auto& [j,tmp] : g[i]) { h[j]--; if (h[j] == 0) none.push(j); } } reverse(tsort.begin(), tsort.end()); vector dp(n, 0); int ans = 0; for (int i : tsort) { for(auto& [u,tmp]:g[i]){ dp[i] = max(dp[i], dp[u] + 1); } ans = max(ans, dp[i]); } cout << ans+1 << endl; return 0; } return 0; }