Problem:
 Score : 600 points    Problem Statement Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N , and the i -th edge is directed from Vertex A_i to Vertex B_i . It is guaranteed that the graph contains no self-loops or multiple edges.  Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1 . If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph.      Notes For a directed graph G = (V, E) , we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G :   V' is a (non-empty) subset of V .  E' is the set of all the edges in E that have both endpoints in V' .       Constraints  1 \leq N \leq 1000  0 \leq M \leq 2000  1 \leq A_i,B_i \leq N  A_i \neq B_i  All pairs (A_i, B_i) are distinct.  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  M  A_1  B_1  A_2  B_2  :  A_M  B_M       Output If there is no induced subgraph of G that satisfies the condition, print -1 .
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:  K  v_1  v_2 : v_K   This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\} . (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.        Sample Input 1 4 5
1 2
2 3
2 4
4 1
4 3      Sample Output 1 3
1
2
4  The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\} . The in-degree and out-degree of every vertex in this graph are both 1 .       Sample Input 2 4 5
1 2
2 3
2 4
1 4
4 3      Sample Output 2 -1  There is no induced subgraph of G that satisfies the condition.       Sample Input 3 6 9
1 2
2 3
3 4
4 5
5 6
5 1
5 2
6 1
6 2      Sample Output 3 4
2
3
4
5

Solution (Python):
import sys; input = sys.stdin.buffer.readline
from collections import defaultdict
from collections import deque
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def BFS(G, N, s, g, ans):
	Q = deque()
	Q.append(s)
	dist = [INF] * N
	dist[s] = 0
	prev = [None] * N
	jud = "No"
	while Q:
		v = Q.popleft()
		for i in G.graph[v]:
			if dist[i] == INF:
				dist[i] = dist[v] + 1
				prev[i] = v
				Q.append(i)
				if i == g:
					jud = "Yes"
					break
		if jud == "Yes":
			break

	if ans > dist[g]:
		state = g
		path = [g]
		while True:
			state = prev[state]
			path.append(state)
			if state == s:
				break
		return dist[g], path[::-1]
	else:
		return INF, []


def main():
	N, M = getlist()
	G = Graph()
	edgefrom = []
	edgeto = []
	for i in range(M):
		a, b = getlist()
		a -= 1; b -= 1
		edgefrom.append(a)
		edgeto.append(b)
		G.add_edge(a, b)

	ans = 100000
	path = None
	for i in range(M):
		predis, prepath = BFS(G, N, edgeto[i], edgefrom[i], ans)
		if predis != INF:
			ans = predis
			path = prepath

	if ans == 100000:
		print(-1)
	else:
		print(ans + 1)
		for i in path:
			print(i + 1)

if __name__ == '__main__':
	main()

Solution (Python):

from collections import defaultdict
from collections import deque
import sys

buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def slv(N, M, AB):

    g = defaultdict(list)
    for a, b in AB:
        g[a].append(b)

    def bfs(s):
        q = deque([s])
        done = {}
        done[s] = 0
        prev = {}
        goal = None
        while q:
            u = q.popleft()
            for v in g[u]:
                if v not in done:
                    done[v] = done[u] + 1
                    prev[v] = u
                    q.append(v)
                if v == s:
                    goal = u
                    break
        if goal is None:
            return None
        v = goal
        ans = [s]
        while v in prev:
            ans.append(v)
            v = prev[v]
        return ans

    ans = [0] * (2*N)
    for i in range(1, N+1):
        a = bfs(i)
        if a and len(ans) > len(a):
            ans = a
    if len(ans) == (2*N):
        print(-1)
        return
    print(len(ans))
    print(*ans, sep='\n')


def main():
    N, M = read_int_n()
    AB = [read_int_n() for _ in range(M)]
    slv(N, M, AB)


if __name__ == '__main__':
    main()

Solution (Python):

import sys

buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def slv(N, M, AB):
    from collections import defaultdict

    g = defaultdict(list)
    for a, b in AB:
        g[a].append(b)

    def bfs(s):
        q = deque([s])
        done = {}
        done[s] = 0
        prev = {}
        goal = None
        while q:
            u = q.popleft()
            for v in g[u]:
                if v not in done:
                    done[v] = done[u] + 1
                    prev[v] = u
                    q.append(v)
                if v == s:
                    goal = u
                    break
        if goal is  None:
            return None
        v = goal
        ans = [s]
        while v in prev:
            ans.append(v)
            v = prev[v]
        return ans

    from collections import deque
    ans = [0] * (2*N)
    for i in range(1, N+1):
        a = bfs(i)
        if a and len(ans) > len(a):
            ans = a
    if len(ans) == (2*N):
        print(-1)
        return
    print(len(ans))
    print(*ans, sep='\n')


def main():
    N, M = read_int_n()
    AB = [read_int_n() for _ in range(M)]
    slv(N, M, AB)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10**7)
def main():
    N, M = map(int, input().split())
    l = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        l[a-1].append(b-1)
    c = [0] * N
    loop = []
    def cyclic(n):
        if c[n] == 2:
            return False
        if c[n] == 1:
            loop.append(n)
            return True
        c[n] = 1
        for i in l[n]:
            if cyclic(i):
                loop.append(n)
                return True
        c[n] = 2
        return False
    for i in range(N):
        if cyclic(i):
            break
    if len(loop) == 0:
        print(-1)
        return
    loop.reverse()
    t = loop[-1]
    loop = loop[loop.index(t):]
    ll = set(loop)
    flag = True
    while flag:
        for i, v in enumerate(loop[:-1]):
            flag2 = False
            for j in l[v]:
                if j in ll and loop[i + 1] != j:
                    if loop.index(j) == 0:
                        loop = loop[:i+1] + [j]
                    elif loop.index(j) < i:
                        loop = loop[loop.index(j):i+1] + [j]
                    else:
                        loop = loop[:i+1] + loop[loop.index(j):]
                    ll = set(loop)
                    flag2 = True
                    break
            if flag2:
                break
        else:
            flag = False
    loop = set(loop)
    print(len(loop))
    for i in loop:
        print(i+1)
    return
main()

Solution (Python):
import sys
sys.setrecursionlimit(10**7)
def main():
    N, M = map(int, input().split())
    l = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        l[a-1].append(b-1)
    c = [0] * N
    loop = []
    def cyclic(n):
        if c[n] == 2:
            return False
        if c[n] == 1:
            loop.append(n)
            return True
        c[n] = 1
        for i in l[n]:
            if cyclic(i):
                loop.append(n)
                return True
        c[n] = 2
        return False
    for i in range(N):
        if cyclic(i):
            break
    if len(loop) == 0:
        print(-1)
        return
    print(0)
    return
main()

Solution (Python):
import sys
sys.setrecursionlimit(10**7)

def main():
    N, M = map(int, input().split())
    V = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        V[a - 1].append(b - 1)
    C = [0] * N
    def dfs(n):
        if C[n] == 2:
            return False
        if C[n] == 1:
            return True
        C[n] = 1
        for i in V[n]:
            if dfs(i):
                return True
        C[n] = 2
        return False
    for i in range(N):
        if dfs(i):
            return 0
    return -1
print(main())

Solution (Python):
import sys
sys.setrecursionlimit(10**7)

def main():
    N, M = map(int, input().split())
    V = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, input().split())
        V[a - 1].append(b - 1)
    C = [0] * N
    loop = []
    def dfs(n):
        if C[n] == 2:
            return False
        if C[n] == 1:
            loop.append(n)
            return True
        C[n] = 1
        for i in V[n]:
            if dfs(i):
                loop.append(n)
                return True
        C[n] = 2
        return False
    for i in range(N):
        if dfs(i):
            break
    if len(loop) == 0:
        print('-1')
        return
    for i in range(1, len(loop)):
        if loop[i] == loop[0]:
            break
    loop = loop[:i][::-1]

    def minimize(l):
        s = set(l)
        for i in range(len(l)):
            for j in V[l[i]]:
                if j == l[(i + 1) % len(l)]:
                    continue
                if j in s:
                    break
            else:
                continue
            break
        else:
            return l
        I = {m: k for k, m in enumerate(l)}
        j = I[j]
        if i < j:
            l = l[0:i + 1] + l[j:]
        else:
            l = l[j:i + 1]
        return l
    while True:
        t = len(loop)
        loop = minimize(loop)
        if len(loop) == t:
            break
    print(t)
    print('\n'.join(str(i + 1) for i in loop))
main()

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5)

N, M = map(int, input().split())
G = [[] for _ in range(N+1)]
for _ in range(M):
    A, B = map(int, input().split())
    G[A].append(B)

def dfs(v, o):
    for c in G[v]:
        if c == o:
            return [v]
    for c in G[v]:
        if visited[c]:
            continue
        visited[c] = True
        ret = dfs(c, o)
        if ret:
            return [v] + ret

for v in range(1, N+1):
    visited = [False] * (N+1)
    cur = dfs(v, v)
    if cur:
        break
else:
    print(-1)
    exit()

while True:
    cur_set = set(cur)
    unused = None
    for i in range(len(cur)):
        u, v = cur[i], cur[(i+1) % len(cur)]
        for c in G[u]:
            if c == v:
                continue
            elif c in cur_set:
                unused = (i, cur.index(c))
                break

    if not unused:
        break
    else:
        t, s = unused
        nxt = []
        i = s
        while i != t:
            nxt.append(cur[i])
            i = (i + 1) % len(cur)
        nxt.append(cur[t])
        cur = nxt

print(len(cur))
print(*cur, sep='\n')

Solution (Python):
n,m = map(int,input().split())
from collections import deque

links = [set() for _ in range(n+1)]
for _ in range(m):
    a,b = map(int, input().split())
    links[a].add(b)

def bfs(links, start):
    parent = [-1] * (n+1)
    selfdepth = 10**6
    d = deque()
    done = {start}
    d.append((start,0))
    while(d):
        edge,depth = d.popleft()
        for i in links[edge]:
            if(i == start):
                selfdepth = depth + 1
                parent[i] = edge
                return( selfdepth, parent )
            if(not i in done):
                parent[i] = edge
                d.append((i,depth+1))
                done.add(i)

    return ( selfdepth, parent )

k = 10**6
start = -1
for i in range(1,n+1):
    selfdepth, parent_tmp = bfs(links, i)
    if(k > selfdepth):
        k = selfdepth
        start = i
        parent_k = parent_tmp

if(start == -1):
    print(-1)
    exit()

print(k)
print(start)
now = parent_k[start]
cnt = 0
while(now != start):
    print(now)
    now = parent_k[now]

Solution (Python):
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return " ".join(map(str,x))
def max2(x): 
    return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def Topo_sort(x,y):
    co = cl.Counter(n for m in x.values() for n in m)
    S = cl.deque([i for i in range(y) if co[i] == 0])
    while S:
        n = S.popleft()
        yield n
        for i in x[n]:
            co[i] -= 1
            if co[i] <= 0:
                S.append(i)
    """
    if sum(co.values()) != 0:
        print(1)
        exit()
    else:
        print(0)
        exit()
    """
    



    







n,k = m()

g = cl.defaultdict(set)

gb = cl.defaultdict(set)
for i in range(k):
    a,b = m()
    a -= 1
    b -= 1
    g[a].add(b)
    gb[b].add(a)

ans = [None for i in range(n)]

for opt in range(n):
    for start in g[opt]:
        cost = [-1]*n
        cost[start] = 0
        de = [start]
        po = []
        fl = True

        while len(de) > 0 and fl:
            po = []
            for i in de:
                for j in g[i]:
                    if cost[j] < 0:
                        cost[j] = cost[i] + 1
                        po.append(j)
                        if j == opt:
                            fl = False
            de = po

        if cost[opt] >= 0 and cost[opt] < len(ans):
            p = opt
            ans = [p+1]
            while p != start:
                for e in gb[p]:
                    if cost[p] == cost[e] + 1:
                        p = e
                        ans.append(p+1)
                        break
if ans[0] == None:
    print(-1)
else:
    print(len(ans))
    for i in ans:
        print(i)

Solution (Python):
from collections import deque

n, m = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(m)]
INF = 10 ** 5

adj = [[] for _ in range(n)]
for a, b in ab:
    a -= 1
    b -= 1
    adj[a].append(b)

mn = INF
for s in range(n):
    dq = deque([s])
    d = [-1] * n
    p = [-1] * n
    d[s] = 0
    last = []

    while dq:
        u = dq.popleft()
        for v in adj[u]:
            if d[v] == -1:
                d[v] = d[u] + 1
                p[v] = u
                dq.append(v)

            if v == s:
                last.append(u)

    for v in last:
        route = [v]
        while p[v] != s:
            v = p[v]
            route.append(v)

        route.append(s)
        size = len(route)
        if size < mn:
            mn = size
            ans = route[::-1]

if mn != INF:
    print(mn)
    for e in ans:
        print(e + 1)
else:
    print(-1)

Solution (Python):
from collections import deque
n,m = map(int,input().split())
path = [set() for _ in range(n)]
pathr= [set() for _ in range(n)]
for _ in range(m):
    a,b = map(int,input().split())
    path[a-1].add(b-1)
    pathr[b-1].add(a-1)

def bfs(start):
    que = deque()
    d = [1e100]*n
    for i in path[start]:
        que.append(i)
        d[i] = 1
    while que:
        p = que.popleft()
        for nxt in path[p]:
            if d[nxt] == 1e100:
                que.append(nxt)
            d[nxt] = min(d[nxt], d[p] + 1)
    if d[start] == 1e100:
        return [0] * (n+1)
    ret = [0]*d[start]
    ret[-1] = start
    now = start
    for i in range(d[start] - 1)[::-1]:
        for p in pathr[now]:
            if d[p] == i+1:
                now = p
                ret[i] = now
                break
    return ret
ans = [0]*(n+1)
for i in range(n):
    tmp = bfs(i)
    if len(ans) > len(tmp):
        ans = tmp
if len(ans) > n:
  print(-1)
else:
    print(len(ans))
    for i in ans:
        print(i+1)

Solution (Python):
from collections import deque
n,m = map(int,input().split())
path = [set() for _ in range(n)]
pathr= [set() for _ in range(n)]
for _ in range(m):
    a,b = map(int,input().split())
    path[a-1].add(b-1)
    pathr[b-1].add(a-1)

def bfs(start):
    que = deque()
    d = [1e100]*n
    for i in path[start]:
        que.append(i)
        d[i] = 1
    while que:
        p = que.popleft()
        for nxt in path[p]:
            if d[nxt] == 1e100:
                que.append(nxt)
            d[nxt] = min(d[nxt], d[p] + 1)
    if d[start] == 1e100:
        return [0] * (n+1)
    ret = [0]*d[start]
    ret[-1] = start
    now = start
    for i in range(d[start] - 1)[::-1]:
        for p in pathr[now]:
            if d[p] == i+1:
                now = p
                ret[i] = now
                break
    return ret
ans = [0]*(n+1)
for i in range(n):
    tmp = bfs(i)
    if len(ans) > len(tmp):
        ans = tmp
if len(ans) > n:
  print(-1)
else:
    print(len(ans))
    for i in ans:
        print(i+1)

Solution (Python):
from collections import deque

N, M = map(int, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
    A,B = map(int, input().split())
    edge[A - 1].append(B - 1)

ans = []
for sta in range(N):
    prev = [-1] * N
    que = deque([sta])

    while que:
        v = que.popleft()
        for w in edge[v]:
            if w == sta:
                path = []
                while v != -1:
                    path.append(v+1)
                    v = prev[v]
                if (not ans) or (len(ans) > len(path)):
                    ans = path
                break

            if prev[w] != -1: continue

            prev[w] = v
            que.append(w)

if ans:
    print(len(ans))
    print(*ans, sep='\n')
else:
    print(-1)

Solution (Python):
from collections import deque

n, m = map(int, input().split())
Edge = [list(map(int, input().split())) for i in range(m)]
adj = [[] for _ in range(n)]

for u, v in Edge:
    adj[u-1].append(v-1)

adj_bit = [0]*n
for i in range(n):
    for j in adj[i]:
        adj_bit[i] += 1 << j

for i in range(n):
    que = deque([(i, 0)])
    visited_a = [0] * n

    while que:
        v, visited = que.popleft()

        for dest in adj[v]:
            if visited_a[dest]:
                continue
            if dest == i:
                ans = [i+1]
                for j in range(1001):
                    if visited & 1:
                        ans.append(j+1)
                    visited >>= 1
                print(len(ans))
                print(*ans, sep='\n')
                exit()
            if visited & adj_bit[dest]:
                
                continue
            visited_a[dest] = 1
            que.append((dest, visited + (1 << dest)))
else:
    print(-1)

Solution (Python):
from collections import deque

N, M = map(int, input().split())
edge = [[] for _ in range(N)]
for _ in range(M):
    A,B = map(int, input().split())
    edge[A - 1].append(B - 1)

ans = []
for sta in range(N):
    prev = [-1] * N
    que = deque([sta])

    while que:
        v = que.popleft()
        for w in edge[v]:
            if w == sta: 
                path = []
                while v != -1:
                    path.append(v+1)
                    v = prev[v]
                if (not ans) or (len(ans) > len(path)):
                    ans = path
                break

            if prev[w] != -1: continue

            prev[w] = v
            que.append(w)

if ans:
    print(len(ans))
    print(*ans, sep='\n')
else:
    print(-1)

Solution (Python):
N,M = map(int,input().split())
AB = [tuple(map(int,input().split())) for i in range(M)]
es = [[] for i in range(N)]
for a,b in AB:
    a,b = a-1,b-1
    es[a].append(b)

from collections import deque
mindist = N
opt = None
for g,tos in enumerate(es):
    for s in tos:
        q = deque([(s,0)])
        prev = [-1]*N
        dist = [N]*N
        dist[s] = 0
        while q:
            v,d = q.popleft()
            for to in es[v]:
                if to==g: break
                if d+1 >= dist[to]: continue
                dist[to] = d+1
                prev[to] = v
                q.append((to,d+1))
            else:
                continue
            break
        else:
            continue
        if d+1 >= mindist: continue
        mindist = d+1
        opt = [g,v]
        while prev[opt[-1]] >= 0:
            opt.append(prev[opt[-1]])
if opt:
    ans = [o+1 for o in opt]
    print(len(ans))
    print(*ans, sep='\n')
else:
    print(-1)

Solution (Python):
def dijkstra_back(s,t,n,w,cost):
    import heapq
    
    prev = [s] * n 
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    q=[]
    heapq.heapify(q)
    heapq.heappush(q,(0,s))
    while q:
        c,v=heapq.heappop(q)
        if d[v]<c:
            continue

        for i in range(len(to[v])):
            k=to[v][i]
            if d[k]>d[v]+cost[v][k]:
                d[k]=d[v]+cost[v][k]
                heapq.heappush(q,(d[k],k))
                prev[k]=v

    path = [t]
    while prev[t] != s:
        path.append(prev[t])
        prev[t] = prev[prev[t]]
    path.append(s)
    path = path[::-1]
    return path

N,M=map(int,input().split())
fr={i:[] for i in range(1,N+1)}
to={i:[] for i in range(1,N+1)}
cost=[[float('inf') for i in range(0,N+1)] for i in range(0,N+1)]
for i in range(0,M):
    a,b=map(int,input().split())
    cost[a][b]=1
    fr[b].append(a)
    to[a].append(b)



ansc=10**10
ans=[]
for i in range(1,N+1):
    for j in fr[i]:
        test=dijkstra_back(i,j,N+1,M,cost)
        if len(test)==2:
            if cost[i][j]!=float('inf'):
                ansc=2
                ans=test
        elif len(test)<ansc:
            ansc=len(test)
            ans=test

if ansc!=10**10:
    print(ansc)
    for i in range(0,ansc):
        print(ans[i])
else:
    print(-1)

Solution (Python):
def dijkstra_back(s,t,n,w,cost):
    import heapq
    
    prev = [s] * n 
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    q=[]
    heapq.heapify(q)
    heapq.heappush(q,(0,s))
    while q:
        c,v=heapq.heappop(q)
        if d[v]<c:
            continue

        for i in range(len(to[v])):
            k=to[v][i]
            if d[k]>d[v]+cost[v][k]:
                d[k]=d[v]+cost[v][k]
                heapq.heappush(q,(d[k],k))
                prev[k]=v

    path = [t]
    while prev[t] != s:
        path.append(prev[t])
        prev[t] = prev[prev[t]]
    path.append(s)
    path = path[::-1]
    return path



N,M=map(int,input().split())
fr={i:set([]) for i in range(1,N+1)}
to={i:set([]) for i in range(1,N+1)}
for i in range(0,M):
    a,b=map(int,input().split())
    fr[b].add(a)
    to[a].add(b)

delete=set([])
flag=1
while flag==1:
    flag=0
    for i in range(1,N+1):
        if (not i in delete) and (delete>=fr[i] or delete>=to[i]):
            delete.add(i)
            flag=1

node=[i for i in range(1,N+1)]
save=set(node)-delete
if save:
    hen=[]
    for i in save:
        fr[i]=fr[i]&save
        to[i]=to[i]&save
        fr[i]=list(fr[i])
        to[i]=list(to[i])

    for i in save:
        for j in fr[i]:
            hen.append((j,i))

    save=list(save)

    cost=[[float('inf') for i in range(0,N+1)] for i in range(0,N+1)]
    for i in range(0,len(hen)):
        a,b=hen[i]
        cost[a][b]=1

    ansc=10**10
    ans=[]
    for i in range(len(save)):
        for j in fr[save[i]]:
            test=dijkstra_back(save[i],j,N+1,len(hen),cost)
            if len(test)<ansc:
                ansc=len(test)
                ans=test

    print(ansc)
    for i in range(0,ansc):
        print(ans[i])

else:
    print(-1)

Solution (Python):
def examA():
    class Dijkstra(object):
        """
        construct: O(ElogV)
        """
        def __init__(self, edges, start=0):
            """
            :param list of list of list of int edges:
            :param int start=0:
            """
            self.__dist = [inf] * len(edges)
            self.__dist[start] = 0
            self.__calculate(edges, start)

        @property
        def dist(self):
            return self.__dist

        def __calculate(self, edges, start):
            Q = [(0, start)]  
            while (Q):
                dist, v = heapq.heappop(Q)
                if self.dist[v] < dist: continue  
                for u, cost in edges[v]:
                    if self.dist[u] > self.dist[v] + cost:
                        self.__dist[u] = self.dist[v] + cost
                        heapq.heappush(Q, (self.dist[u], u))
    N, L = LI()
    V, D = LI()
    X = [LI()for _ in range(N)]
    X.append([0,V,D])
    X.append([L,0,0])
    X.sort()
    V = [[]for _ in range(N+2)]
    for i in range(N+1):
        x1, v1, d1 = X[i]
        r = x1 + d1
        for j in range(i+1,N+2):
            x2, v2, d2 = X[j]
            if r<x2:
                break
            cost = (x2-x1)/v1
            V[i].append((j,cost))

    dij = Dijkstra(V, 0)
    ans = dij.dist[-1]
    if ans>=inf:
        print("impossible")
        return
    print('{:.18f}'.format(ans))
    return

def examB():
    N, K = LI()
    H = 11; W = 7
    S = [[0]*(W+1) for _ in range(H+3)]
    for h in range(H+2):
        for w in range(W):
            S[h+1][w+1] = (S[h][w+1] + S[h+1][w] - S[h][w] + (7*h+w+1))
    
    base = 0
    for h in range(H):
        for w in range(W-2):
            cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w]
            if cur%11==K:
                base += 1
                
    ans = base * ((N-2)//11)
    
    rest = (N-2)%11
    for h in range(rest):
        for w in range(W-2):
            cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w]
            if cur%11==K:
                ans += 1
                
    print(ans)
    return

def examC():
    N, K = LI()
    A = LI()
    loop = 2**N
    ans = inf
    for i in range(loop):
        cnt = 0
        need = 0
        highest = 0
        for j in range(N):
            if i&(1<<j)==0:
                if highest<A[j]:
                    need = inf
                    break
                continue
            cnt += 1
            if highest>=A[j]:
                need += (highest+1-A[j])
                highest = highest + 1
            else:
                highest = A[j]
        if cnt>=K and need<ans:
            ans = need
        
    print(ans)
    return

def examD():
    
    def cycle(neighbor, start, ring_size, node):
        visited = [False]*node
        stack = []
        stack.append([start])
        visited[start] = True
        while (stack):
            curr_path = stack.pop()
            
            
            if len(curr_path) > ring_size:
                continue
            
            last = curr_path[-1]
            for nei in neighbor[last]:
                if nei in curr_path:
                    if len(curr_path)==0:
                        continue
                    if (len(curr_path) <= ring_size) and (curr_path[0] == nei):
                        new_path = copy(curr_path)
                        return new_path
                    elif (len(curr_path) <= ring_size):
                        return cycle(neighbor,nei,ring_size-1,node)
                if visited[nei]:
                    continue
                visited[nei] = True
                new_path = copy(curr_path)
                new_path.append(nei)
                stack.append(new_path)
        return -1
    N, M = LI()
    V = [[]for _ in range(N)]
    for _ in range(M):
        a,b = LI()
        a -= 1; b -= 1
        V[a].append(b)
    
    loop = -1
    for i in range(N):
        loop = cycle(V,i,N,N)
        if loop!=-1:
            break
    if loop==-1:
        print(-1)
        return
    while(True):
        next = -1
        for k in loop:
            next = cycle(V,k,len(loop)-1,N)
            if next != -1:
                break
        if next==-1:
            break
        loop = next

    ans = loop
    print(len(ans))
    for v in ans:
        print(v+1)
    return

import sys,bisect,itertools,heapq,math,random
from copy import copy,deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    examD()

Solution (Python):
N,M = map(int,input().split())
AB = [tuple(map(int,input().split())) for i in range(M)]

es = [[] for _ in range(N)]
for a,b in AB:
    a,b = a-1,b-1
    es[a].append(b)

from collections import deque

mindist = N
ans = None
for g in range(N):
    for s in es[g]:
        q = deque([s])
        dist = [N]*N
        dist[s] = 0
        prev = [-1]*N
        while q:
            v = q.popleft()
            if v==g:
                break
            for to in es[v]:
                if dist[to] <= dist[v] + 1: continue
                dist[to] = dist[v] + 1
                prev[to] = v
                q.append(to)
        else:
            continue
        if dist[g] >= mindist: continue
        mindist = dist[g]
        v = g
        tmp = [v+1]
        while prev[v] >= 0:
            v = prev[v]
            tmp.append(v+1)
        ans = tmp

if ans:
    print(len(ans))
    print(*ans, sep='\n')
else:
    print(-1)