/* -*- coding: utf-8 -*- * * 1660.cc: No.1660 Matrix Exponentiation - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 100000; /* typedef */ typedef long long ll; typedef vector vi; typedef queue qi; typedef pair pii; /* global variables */ vi nbrs[MAX_N]; int pns[MAX_N], ds[MAX_N]; /* subroutines */ /* main */ int main() { int n, k; scanf("%d%d", &n, &k); for (int i = 0; i < k; i++) { int ri, ci; scanf("%d%d", &ri, &ci); ri--, ci--; nbrs[ri].push_back(ci); pns[ci]++; } int m = 0, maxd = 0; qi q; for (int u = 0; u < n; u++) if (pns[u] == 0) ds[u] = maxd = 1, q.push(u), m++; while (! q.empty()) { int u = q.front(); q.pop(); for (auto v: nbrs[u]) { ds[v] = max(ds[v], ds[u] + 1); maxd = max(maxd, ds[v]); if (--pns[v] == 0) q.push(v), m++; } } printf("%d\n", (m == n) ? maxd: -1); return 0; }