While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.

Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.


-----Input-----

The first line of the input consists of two integers, the number of robots n (2 ≤ n ≤ 100 000) and the number of rap battles m ($1 \leq m \leq \operatorname{min}(100000, \frac{n(n - 1)}{2})$).

The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}), indicating that robot u_{i} beat robot v_{i} in the i-th rap battle. No two rap battles involve the same pair of robots.

It is guaranteed that at least one ordering of the robots satisfies all m relations.


-----Output-----

Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.


-----Examples-----
Input
4 5
2 1
1 3
2 3
4 2
4 3

Output
4

Input
3 2
1 2
3 2

Output
-1



-----Note-----

In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.

In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.

Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Sorting

Graph algorithms
Skill types: Dynamic programming

Sorting

Starter code:

Solutions:
from sys import stdin, stdout
import sys
import bisect
import heapq
input = sys.stdin.readline

def solve(n, m, edges):
	lo = 0
	hi = m
	curr_k = -1
	while lo <= hi:
		mid = lo + (hi - lo) // 2
		can_do = True
		adj_list = {x: [] for x in range(0, n)}
		in_degree = [0] * n
		for ed in range(min(mid, len(edges))):
			edge = edges[ed]
			adj_list[edge[0]].append(edge[1])
			in_degree[edge[1]] += 1
		candidates = []
		for i in range(len(in_degree)):
			if in_degree[i] == 0:
				candidates.append(i)
		res = []
		while candidates:
			ele = candidates.pop(0)
			if len(candidates) > 0:
				can_do = False
				break
			res.append(ele)
			for i in adj_list[ele]:
				in_degree[i] -= 1
				if in_degree[i] == 0:
					candidates.append(i)
		if len(res) < n:
			can_do = False
		if can_do:
			curr_k = mid
			hi = mid - 1
		else:
			lo = mid + 1
	return curr_k

def main():
	(n, m) = map(int, input().split())
	edges = []
	for i in range(m):
		(a, b) = map(int, input().split())
		edges.append([a - 1, b - 1])
	stdout.write(str(solve(n, m, edges)))
	stdout.write('\n')
main()


from sys import stdin

def main():

	def f(k):
		(g, cnt) = ([[] for _ in range(n)], [0] * n)
		for (u, v) in data[:k]:
			g[u].append(v)
			cnt[v] += 1
		if cnt.count(0) > 1:
			return False
		(w, u) = (cnt.index(0), -1)
		while u != w:
			u = w
			for v in g[u]:
				cnt[v] -= 1
				if not cnt[v]:
					if u != w:
						return False
					w = v
		return True
	(n, m) = map(int, input().split())
	data = stdin.read().splitlines()
	for (i, s) in enumerate(data):
		(u, v) = map(int, s.split())
		data[i] = (u - 1, v - 1)
	(lo, hi) = (n - 1, m + 1)
	while lo < hi:
		mid = (lo + hi) // 2
		if f(mid):
			hi = mid
		else:
			lo = mid + 1
	print(-1 if hi > m else lo)
main()


(n, m) = [int(i) for i in input().split()]
n += 1
A = [[int(i) for i in input().split()] for j in range(m)]
m += 1

def check(upper):
	p = [[] for i in range(n)]
	d = [0] * n
	for (u, v) in A[:upper]:
		p[u].append(v)
		d[v] += 1
	if d.count(0) > 2:
		return False
	x = d.index(0, 1)
	while x:
		(q, x) = (p[x], 0)
		for y in q:
			d[y] -= 1
			if d[y] == 0:
				if x:
					return False
				x = y
	return True
(left, right) = (1, m)
while left < right:
	mid = (left + right) // 2
	if check(mid):
		right = mid
	else:
		left = mid + 1
if check(left):
	print(left)
else:
	print(-1)


from heapq import heappop, heappush
(n, m) = map(int, input().split())
C = [[] for _ in range(n)]
indeg = [0] * n

def toposort():
	S = [i for i in range(n) if indeg[i] == 0]
	nparent = indeg[:]
	topo = []
	while S:
		cur = S.pop()
		topo.append(cur)
		for (neigh, _) in C[cur]:
			nparent[neigh] -= 1
			if nparent[neigh] == 0:
				S.append(neigh)
	return topo

def solve():
	topo = toposort()
	D = [(0, 0)] * n
	for cur in topo:
		for (neigh, t) in C[cur]:
			(cd, ct) = D[cur]
			(nd, _) = D[neigh]
			if nd <= cd + 1:
				D[neigh] = (cd + 1, max(ct, t))
	(d, t) = max(D)
	return t + 1 if d == n - 1 else -1
for _ in range(m):
	(a, b) = map(int, input().split())
	C[a - 1].append((b - 1, _))
	indeg[b - 1] += 1
print(solve())


from collections import defaultdict

class RobotRapping:

	def __init__(self, n, m, battles):
		(self.n, self.m) = (n, m)
		self.battles = battles

	def generate_graph(self, k):
		edge_map = defaultdict(list)
		rev_map = defaultdict(list)
		for i in range(k):
			edge_map[self.battles[i][0] - 1].append((self.battles[i][1] - 1, i))
			rev_map[self.battles[i][1] - 1].append((self.battles[i][0] - 1, i))
		return (edge_map, rev_map)

	def check_order(self, num_battles):
		(edge_map, rev_map) = self.generate_graph(num_battles)
		outgoing_cnt = defaultdict(int)
		for k in edge_map:
			outgoing_cnt[k] = len(edge_map[k])
		s = []
		cntr = 0
		for i in range(self.n):
			if outgoing_cnt[i] == 0:
				s.append(i)
		while len(s) > cntr:
			if len(s) > cntr + 1:
				return False
			else:
				node = s[cntr]
				for v in rev_map[node]:
					outgoing_cnt[v] -= 1
					if outgoing_cnt[v] == 0:
						s.append(v)
				cntr += 1
		return True

	def min_battles(self):
		if not self.check_order(self.m):
			print(-1)
		else:
			(mn, mx) = (0, self.m)
			while mn < mx - 1:
				md = int((mn + mx) / 2)
				if self.check_order(md):
					mx = md
				else:
					mn = md
			print(mx)

	def min_battles2(self):
		(edge_map, rev_map) = self.generate_graph(self.m)
		outgoing_cnt = defaultdict(int)
		for k in edge_map:
			outgoing_cnt[k] = len(edge_map[k])
		s = []
		cntr = 0
		order = []
		for i in range(self.n):
			if outgoing_cnt[i] == 0:
				s.append(i)
		while len(s) > cntr:
			if len(s) > cntr + 1:
				print(-1)
				return
			else:
				node = s[cntr]
				order.append(node)
				for (v, _) in rev_map[node]:
					outgoing_cnt[v] -= 1
					if outgoing_cnt[v] == 0:
						s.append(v)
				cntr += 1
		mn_pos = -1
		for i in range(1, self.n):
			for (v, ind) in edge_map[order[i]]:
				if v == order[i - 1]:
					mn_pos = max(mn_pos, ind)
					break
		print(mn_pos + 1)
(n, m) = list(map(int, input().strip(' ').split(' ')))
battles = []
for i in range(m):
	(x, y) = list(map(int, input().strip(' ').split(' ')))
	battles.append((x, y))
rr = RobotRapping(n, m, battles)
rr.min_battles2()


import os, sys
from io import BytesIO, IOBase

def topsort(n, path, indeg):
	ans = []
	for i in range(n):
		if not indeg[i]:
			ans.append(i)
	i = 0
	if len(ans) > 1:
		return 0
	while i != len(ans):
		for x in path[ans[i]]:
			indeg[x] -= 1
			if not indeg[x]:
				ans.append(x)
		i += 1
		if len(ans) - i > 1:
			return 0
	return ans

def main():
	(n, m) = map(int, input().split())
	path = [[] for _ in range(n)]
	indeg = [0] * n
	edg = []
	for _ in range(m):
		(u1, v1) = map(lambda xx: int(xx) - 1, input().split())
		edg.append((u1, v1))
		path[u1].append(v1)
		indeg[v1] += 1
	top = topsort(n, path, indeg)
	if not top:
		return -1
	inde = [0] * n
	for (ind, i) in enumerate(top):
		inde[i] = ind
	ls = -1
	for i in range(m):
		(x, y) = edg[i]
		if abs(inde[x] - inde[y]) == 1:
			ls = i + 1
	return ls
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
print(main())


from collections import defaultdict, deque

def bfs(q, n, mid):
	g = defaultdict(list)
	vis = [0] * n
	for i in range(mid):
		(x, y) = q[i]
		g[x].append(y)
		vis[y] += 1
	q = deque()
	for i in range(n):
		if vis[i] == 0:
			q.append(i)
	flag = True
	cnt = 0
	while q and flag:
		if len(q) != 1:
			flag = False
		t = q.popleft()
		cnt += 1
		for i in g[t]:
			vis[i] -= 1
			if vis[i] == 0:
				q.append(i)
	return cnt == n and flag == True

def f(q, n):
	lo = 0
	hi = len(q)
	ans = -1
	while lo <= hi:
		mid = (lo + hi) // 2
		if bfs(q, n, mid):
			ans = mid
			hi = mid - 1
		else:
			lo = mid + 1
	return ans
q = []
(n, m) = map(int, input().strip().split())
for _ in range(m):
	(x, y) = map(int, input().strip().split())
	q.append((x - 1, y - 1))
print(f(q, n))