import java.io.PrintWriter import java.util.* fun PrintWriter.solve() { val n = nextInt() val m = nextInt() val adj = Array(n) { mutableListOf() } val set = mutableSetOf>() for (i in 0 until m) { val v1 = nextInt() - 1 val v2 = nextInt() - 1 if (v1 == v2 || set.contains(v2 to v1)) { println(-1) return } adj[v1].add(v2) set.add(v1 to v2) } if (findCycle(adj).isNotEmpty()) { println(-1) } else { val lst = topologicalSort(adj) val dp = IntArray(n) { -1 } fun dfs(v: Int): Int { if (dp[v] != -1) return dp[v] var max = 0 for (w in adj[v]) { max = maxOf(max, dfs(w)) } dp[v] = max + 1 return dp[v] } lst.forEach { dfs(it) } println(dp.maxOrNull()!!) } } fun findCycle(adj: Array>): List { val n = adj.size val seen = BooleanArray(n) { false } val finished = BooleanArray(n) { false } var pos = -1 val hist = Stack() fun dfs(v: Int, p: Int) { seen[v] = true hist.push(v) for (w in adj[v]) { if (w == p) continue if (finished[w]) continue if (seen[w] && !finished[w]) { pos = w return } dfs(w, v) if (pos != -1) return } hist.pop() finished[v] = true } for (i in 0 until n) { if (!finished[i]) { dfs(i, -1) if (pos != -1) break } } val cycle = mutableListOf() while (hist.isNotEmpty()) { val t = hist.pop() cycle.add(t) if (t == pos) break } return cycle } fun topologicalSort(adj: Array>): List { val ans = mutableListOf() val n = adj.size val ind = IntArray(n) { 0 } for (i in 0 until n) { for (v in adj[i]) ind[v]++ } val que: Queue = ArrayDeque() for (i in 0 until n) { if (ind[i] == 0) que.add(i) } while (que.isNotEmpty()) { val now = que.poll() ans.add(now) for (v in adj[now]) { ind[v]-- if (ind[v] == 0) que.add(v) } } return ans } fun main() { val writer = PrintWriter(System.out, false) writer.solve() writer.flush() } // region Scanner private var st = StringTokenizer("") private val br = System.`in`.bufferedReader() fun next(): String { while (!st.hasMoreTokens()) st = StringTokenizer(br.readLine()) return st.nextToken() } fun nextInt() = next().toInt() fun nextLong() = next().toLong() fun nextLine() = br.readLine()!! fun nextDouble() = next().toDouble() // endregion