Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

s = input()
q = int(input())
z = 0
F = ""
R = ""
for i in range(q):
    a = tuple(input().split())
    if a[0] == "1":
        z += 1
        z %= 2
    else:
        if (int(a[1]) + z) % 2 == 0:
            R = "".join([R, a[2]])
        else:
            F = "".join([a[2], F])

ans = "".join([F, s, R])
if z % 2 == 0:
    print(ans)
else:
    print(ans[::-1])


### FIXED CODE ###

from collections import deque
d = deque()
d.extend(list(input()))
q = int(input())
z = 0
F = ""
R = ""
for i in range(q):
    a = tuple(input().split())
    if a[0] == "1":
        z += 1
        z %= 2
    else:
        if (int(a[1]) + z) % 2 == 0:
            d.append(a[2])
        else:
            d.appendleft(a[2])

ans = "".join(d)
if z % 2 == 0:
    print(ans)
else:
    print(ans[::-1])
### BUGGY CODE ###

a=input()
def ip(a):
    i=2
    while i**2<=a:
        if a%i==0:return False
    return True
b=0
for i in range(a):
    c=input()
    if ip(c):b+=1
print(str(b))

### FIXED CODE ###

a=input()
def ip(a):
    i=2
    while i**2<=a:
        if a%i==0:return False
        i+=1
    return True
b=0
for i in range(int(a)):
    c=input()
    if ip(int(c)):b+=1
print(str(b))
### BUGGY CODE ###

import math
import copy
# import numpy as np

# ===FUNCTION===

def getInputNum():
    inputNum = int(input())
    return inputNum

def getInputListInt():
    outputoData = []
    inputData = input().split()
    outputData = [int(n) for n in inputData]

    return outputData

def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList

def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList

# ===CODE===

a = getInputListInt()
min = a[0]
max = a[1]

ans_max = 2019
ans = ans_max

flg = False

for i in range(min, max):
    for j in range(i+1, max+1):
        tmp = (i*j) % ans_max

        if ans > tmp:
            ans = tmp

        if ans == 0:
            flg = True
    
    if flg:
        break

print(ans)

### FIXED CODE ###

import math
import copy
# import numpy as np

# ===FUNCTION===

def getInputNum():
    inputNum = int(input())
    return inputNum

def getInputListInt():
    outputoData = []
    inputData = input().split()
    outputData = [int(n) for n in inputData]

    return outputData

def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList

def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList

# ===CODE===

a = getInputListInt()
min = a[0]
max = a[1]

ans_max = 2019
ans = ans_max

flg = False

for i in range(min, max):
    for j in range(i+1, max+1):
        tmp = (i*j) % ans_max

        if ans > tmp:
            ans = tmp

        if ans == 0:
            flg = True
            break

    if flg:
        break

print(ans)
### BUGGY CODE ###

import numpy as np

# Calculate intensity
N, K = [int(v) for v in input().split(" ")]
A_arr = np.array([int(v) for v in input().split(" ")])
step = np.arange(len(A_arr))
if K > N-1:
  print(" ".join([str(N)]*N))
  exit()

def Luminate(A_arr, i):
  isLuminated = np.abs(step - i) < A_arr
  return isLuminated

def get_Intensity(A_arr):
  return np.array([np.sum(Luminate(A_arr, i)) for i in range(len(A_arr))])
Intensity = A_arr
for i in range(K):
  Intensity = get_Intensity(Intensity+1)
  if np.sum(Intensity) == N**2:
    break
print(" ".join([str(v) for v in Intensity]))

### FIXED CODE ###

import numpy as np
 
N, K = map(int, input().split(' '))
A = tuple(map(int, input().split(' ')))
indexes = np.arange(0, N)
 
dp = np.zeros(shape=N + 1, dtype=np.int64)
 
for k in range(K):
    np.add.at(dp, np.maximum(0, indexes - A), 1)
    np.add.at(dp, np.minimum(N, indexes + A + 1), -1)
    A = dp.cumsum()[:-1]
    if np.all(A == N):
        break
    dp *= 0
 
print(' '.join(map(str, A)))
### BUGGY CODE ###

s = input()
t = input()
dp = [[0] * (len(t) + 1) for _ in range(len(s) + 1)]
for i in range(1, len(s) + 1):
  for j in range(1, len(t) + 1):
    k = dp[i - 1][j]
    if dp[i][j - 1] > k:
      k = dp[i][j - 1]
    if (s[i - 1] == t[j - 1]) and (dp[i - 1][j - 1] + 1 > k):
      k = dp[i - 1][j - 1] + 1
    dp[i][j] = k
u = []
while i > 0 and j > 0:
  if dp[i - 1][j] == dp[i][j]:
    i -= 1
  elif dp[i][j - 1] == dp[i][j]:
    j -= 1
  else:
    u.append(s[i - 1])
    i -= 1
    j -= 1
print(''.join(u[::-1]))


### FIXED CODE ###

s = input()
t = input()
slen = len(s)
tlen = len(t)
dp = [[0 for j in range(tlen + 1)] for i in range(slen + 1)]
for i in range(slen):
  for j in range(tlen):
    if s[i] == t[j]:
      dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1)
    dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i + 1][j])
    dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j + 1])
result = ''
i = slen
j = tlen
while i > 0 and j > 0:
  if dp[i - 1][j] == dp[i][j]:
    i -= 1
  elif dp[i][j - 1] == dp[i][j]:
    j -= 1
  else:
    result = s[i - 1] + result
    i -= 1
    j -= 1
print(result)
### BUGGY CODE ###

k,s =map(int,input().split())
cnt = 0
for x in range(0,s+1):
  for y in range(0,s+1-x):
    z = s-x-y
    if x<=k and y<=k and z <=k:
      cnt += 1
print(cnt)

### FIXED CODE ###

k,s =map(int,input().split())
cnt = 0
for x in range(0,s+1):
  for y in range(0,s+1-x):
    z = s-x-y
    if x<=k and y<=k and z <=k:
      cnt += 1
print(cnt)
### BUGGY CODE ###

#N, X, Y = map(int, input().split())
#l = [0 for _ in range(N-1)]
#for i in range(1, N+1):
#    for j in range(i+1,N+1):
#        n = min(j-i, abs(i-X)+1 + abs(j-Y))
#        l[n-1] +=1
#for m in l:
#    print(m)
inf = 100000
N, X, Y = map(int, input().split())
X -= 1
Y -= 1
ans = [0 for _ in range(N)]
for i in range(N):
    queue = []
    dist = [inf for _ in range(N)]
    def push(n, d):
        if dist[n] == inf:
            dist[n] = d
            queue.append(n)
    push(i, 0)
    while len(queue) > 0:
        q = queue.pop(0)
        if q-1 >=0:
            push(q-1, dist[q] + 1)
        if q+1 <N:
            push(q+1, dist[q] + 1)
        if q == X:
            push(Y, dist[q] + 1)
        if q == Y:
            push(X, dist[q] + 1)
    for d in dist:
        ans[d] += 1
for i in range(1, N):
    print(int(ans[i]/2))


### FIXED CODE ###

N, X, Y = map(int, input().split())
l = [0 for _ in range(N-1)]
for i in range(1, N+1):
    for j in range(i+1,N+1):
        n = min(j-i, abs(i-X)+1 + abs(j-Y))
        l[n-1] +=1
for m in l:
    print(m)
### BUGGY CODE ###

import bisect

N, M, Q = map(int, input().split())
tmp = [list(map(int, input().split())) for _ in range(M)]
tmp.sort(key=lambda x: x[0])
L, R = [], []
for i in range(M):
    L.append(tmp[i][0])
    R.append(tmp[i][1])

for _ in range(Q):
    p, q = map(int, input().split())
    ans = 0
    INDEX_1 = bisect.bisect_left(L, p)
    INDEX_2 = bisect.bisect_right(L, q)
    for i in range(INDEX_1, INDEX_2):
        if R[i] <= q:
            ans += 1
    print(ans)

### FIXED CODE ###

N, M, Q = map(int, input().split())
matrix = [[0]*(N+1) for _ in range(N)]

for _ in range(M):
    l, r = map(int, input().split())
    matrix[l-1][r] += 1

for i in range(N):
    for j in range(1, N+1):
        matrix[i][j] += matrix[i][j-1]

for _ in range(Q):
    p, q = map(int, input().split())
    ans = 0
    for i in range(p-1, q):
        ans += matrix[i][q]-matrix[i][p-1]
    print(ans)
### BUGGY CODE ###

from itertools import permutations

N, C = list(map(int, input().split()))

D = []
for i in range(C):
    D.append(list(map(int, input().split())))

remains = {0: [], 1: [], 2: []}

for i in range(1, N+1):
    line = list(map(int, input().split()))
    for j in range(N):
        remains[(i+j+1)%3].append(line[j])

INF = 65535

def recolor(x, y):
    return D[x-1][y-1]

memo = {0: {}, 1: {}, 2: {}}

answer = INF
for choice in permutations(list(range(1, C+1)), 3):
    _answer = 0
    for i in range(3):
        total = memo[i].get(
            choice[i],
            sum([recolor(r, choice[i]) for r in remains[i] if choice[i] != r])
        ) 
        memo[i][choice[i]] = total
        _answer += total 
    answer = min(answer, _answer)

print(answer)

### FIXED CODE ###

from itertools import permutations
from collections import defaultdict

N, C = list(map(int, input().split()))
D =[list(map(int, input().split())) for _ in range(C)]

remains = {0: defaultdict(int), 1: defaultdict(int), 2: defaultdict(int)}
for i in range(1, N+1):
    line = list(map(int, input().split()))
    for j in range(N):
        remains[(i+j+1)%3][line[j]] += 1

INF = float('inf')

def recolor(x, y, count):
    return D[x-1][y-1] * count

answer = INF
for choice in permutations(range(1, C+1), 3):
    _answer = 0
    for i, c in enumerate(choice):
        _answer += sum([recolor(r, c, remains[i][r]) for r in remains[i] if c != r])
    answer = min(answer, _answer)

print(answer)
### BUGGY CODE ###

import re
S = str(input())
count = 0;
while('BW'in S):
  count=count+S.count('BW');
  S = re.sub('BW','WB',S);
print(count)


### FIXED CODE ###

S = input()
ans = 0
tmp = 0
for i in range(len(S)):
  if S[i] == 'W':
    ans+=i-tmp
    tmp+=1
print(ans)
### BUGGY CODE ###

import bisect
import sys
input = sys.stdin.readline


def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    C = list(map(int, input().split()))
    A.sort()
    B.sort()
    C.sort(reverse=True)
    # print(A)
    # print(B)
    # print(C)

    ans = 0
    last_b = N
    for c in C:
        last_b = bisect.bisect_left(B, c, hi=last_b)
        if last_b==0:
            break
        last_a = N
        for b in reversed(B[:last_b]):
            last_a = bisect.bisect_left(A, b, hi=last_a)
            if last_a==0:
                break
            ans += last_a
            # print(b)
            # print("last_b: "+str(last_b))
            # print("last_a: "+str(last_a))
    
    print(ans)


if __name__ == '__main__':
    main()

### FIXED CODE ###

import bisect
import sys
input = sys.stdin.readline


def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    C = list(map(int, input().split()))
    A.sort()
    C.sort()

    ans = 0
    for b in B:
        cnt_a = bisect.bisect_left(A, b)
        cnt_c = N - bisect.bisect_right(C, b)
        ans += cnt_a * cnt_c
        # print(str(cnt_a) + "*" + str(cnt_c))
    
    print(ans)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

n = int(input())
s = []
for i in range(n):
    s.append(input())

u = set(s)
m = 0
ans = []

for i in u:
    if s.count(i) > m:
        ans = [i]
        m = s.count(i)
    elif s.count(i) == m:
        ans.append(i)

ans.sort()

print('\n'.join(map(str, ans)))
#for i in range(len(ans)):
#    print(ans[i])

        


### FIXED CODE ###

import collections

n = int(input())
s = [input() for i in range(n)]

c = collections.Counter(s)
common = c.most_common()

count = common[0][1]
ans = []
for i in common:
  if i[1] == count:
    ans.append(i[0])
  else:
    break
ans.sort()
print(*ans,sep='\n')
### BUGGY CODE ###

import sys
from collections import defaultdict, deque
import bisect
from heapq import *
from math import factorial
sys.setrecursionlimit(200000)
input = sys.stdin.readline

N, = map(int, input().split())
# N = int(input())
# L = [int(v) for v in input().split()]
# L = [[int(v) for v in input().split()] for _ in range(N)]
# L = [int(input()) for _ in range(N)]
# L = [list(input().strip())  for _ in range(N)]
# S = input().strip()

L = [[int(v) for v in input().split()] for _ in range(N - 1)]
Q, K = map(int, input().split())
QL = [[int(v) for v in input().split()] for _ in range(Q)]

m = {}
for a, b, c in L:
    if m.get(a) == None:
        m[a] = {}
    if m.get(b) == None:
        m[b] = {}

    m[a][b] = c
    m[b][a] = c

def dfs(now, a, l, al):
    ans = 10 ** 18
    if now == a:
        return l
    for k, v in m[now].items():
        if k in al:
            continue
        re = dfs(k, a, l + v, al + [k])
        ans = min(ans, re)
    return ans

for i in range(N):
    a = dfs(K, i + 1, 0, [])
    m[K][i + 1] = a

for x, y in QL:
    print(m[K][x] + m[K][y])

### FIXED CODE ###

import sys
from collections import defaultdict
sys.setrecursionlimit(200000)
input = sys.stdin.readline

N, = map(int, input().split())
L = [[int(v) for v in input().split()] for _ in range(N - 1)]
Q, K = map(int, input().split())
QL = [[int(v) - 1 for v in input().split()] for _ in range(Q)]

m = [set() for _ in range(N)]
c = {}
for x, y, z in L:
    m[x - 1].add(y - 1)
    m[y - 1].add(x - 1)

    if c.get(x - 1) == None:
        c[x - 1] = {}

    if c.get(y - 1) == None:
        c[y - 1] = {}

    c[x - 1][y - 1] = z
    c[y - 1][x - 1] = z

s = [None] * N
s[K - 1] = 0

def f(index, b):
    for v in m[index]:
        if s[v] == None:
            s[v] = b + c[index][v]
            f(v, s[v])
        else:
            if s[v] > b + c[index][v]:
                s[v] = b + c[index][v]
                f(v, s[v])

f(K - 1, 0)

for x, y in QL:
    print(s[x] + s[y])
### BUGGY CODE ###

n = int(input())
a = list(map(int,input().split()))


ans=0
for i in range(n-1):
    a2=0
    for j in range(i+1,n):
        a2 = (a2+a[j]) % (10**9+7)
    ans = ( ans + (a[i]*a2) )%(10**9+7)
print(ans)


### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))

a2=[a[n-1]]
for i in range(n-1,0,-1):
    a2.append(a2[-1]+a[i-1])
ans=0
for i in range(n-1):
    ans = ( ans + (a[i]*a2[-i-2]) )%(10**9+7)
print(ans)
### BUGGY CODE ###

x,y = list(map(lambda x: int(x), input().split(" ")))
c = 2
while x % y == 0:
  x *= c
  c += 1
print(x)

### FIXED CODE ###

x,y = map(int, input().split(" "))
if x % y == 0:
  print(-1)
else:
  print(x)
### BUGGY CODE ###

class UF():
  def __init__(self, N):
    self.parents = [ i for i in range(N+1) ]

  def union(self, f, t):
    p1 = self.find(f)
    p2 = self.find(t)
    if p1 == p2:
      return
    self.parents[p2] = p1

  def find(self, node):
    # if self.parents[node] == node:
    #   return node
    # else:
    #   return self.find(self.parents[node])
    while self.parents[node] != node:
      node = self.parents[node]
    return node

N,M = map(int, input().split())
p = list(map(int, input().split()))
uf = UF(N)
xy = [ list(map(int, input().split())) for _ in range(M) ]

# for _ in range(M):
#   x,y = map(int, input().split())
#   uf.union(x,y)
for x,y in xy:
  uf.union(x,y)

res = 0
for i in range(N):
  if i+1 == p[i]:
    res += 1
  elif uf.parents[i+1] == uf.parents[p[i]]:
    res += 1
  elif uf.find(i+1) == uf.find(p[i]):
    res += 1

print(res)


### FIXED CODE ###

class UF():
  def __init__(self, N):
    self.parents = [-1] * (N+1)

  def union(self, f, t):
    p1 = self.find(f)
    p2 = self.find(t)
    if p1 == p2:
      return

    if self.parents[p1] > self.parents[p2]:
      p1,p2 = p2,p1
    self.parents[p1] += self.parents[p2]
    self.parents[p2] = p1

  def find(self, node):
    if self.parents[node] < 0:
      return node
    else:
      self.parents[node] = self.find(self.parents[node])
      return self.parents[node]

  def same(self, n1, n2):
    return self.find(n1) == self.find(n2)

N,M = map(int, input().split())
p = list(map(int, input().split()))
uf = UF(N)
xy = [ list(map(int, input().split())) for _ in range(M) ]

# for _ in range(M):
#   x,y = map(int, input().split())
#   uf.union(x,y)
for x,y in xy:
  uf.union(x,y)

res = 0
for i in range(N):
  if i+1 == p[i] or uf.same(i+1, p[i]):
    res += 1

print(res)
### BUGGY CODE ###

import sys
from operator import itemgetter
inputs = sys.stdin.readline
N, Q= map(int,inputs().split())
def main():
	E = [None]*2*N
	for n in range(N):
		a,b,c = map(int,inputs().split())
		E[2*n] = (a - c, 1, c)
		E[2*n + 1] = (b - c, -1, c)
	E.sort(key=itemgetter(0))
	tuple(tuple(E))
	mini = 1000000001
	kouho = {1000000001}
	my_add = kouho.add
	my_discard = kouho.discard
	q = 0
	d = int(inputs())
	flag = False
	cont = False
	for e in E:
		while(e[0] > d):
			if cont == True:
				if mini < 1000000001:
					print(mini)
				else:
					print(-1)
			else:
				mini = min(kouho)
				if mini < 1000000001:
					print(mini)
				else:
					print(-1)
			cont = True
			if q < Q-1:
				q = q + 1
				d = int(inputs())
			else:
				flag = True
				q = q + 1
				break
		if flag == True:
			break
		if e[1] == 1:
			my_add(e[2])
			if mini > e[2]:
				mini = e[2]
		elif e[1] == -1:
			my_discard(e[2])
			cont = False
	for t in [None]*(Q-q):
		print(-1)
		
def sub():
	V = [list(map(int,inputs().split())) for p in [0]*N]
	M = [int(inputs()) for p in [0]*Q]
	V.sort(key = lambda x:(x[2],x[0],x[1]))
	for v in V:
		v[0] -= v[2]
		v[1] -= v[2] + 1
	for m in M:
		for n in range(N):
			if V[n][0] <=m and m <= V[n][1]:
				print(V[n][2])
				break
		else:
			print(-1)


if N>1000000:
	sub()
else:
	main()

### FIXED CODE ###

import sys
from operator import itemgetter
def main():
	inputs = sys.stdin.readline
	N, Q= map(int,inputs().split())
	E = [None]*2*N
	for n in range(N):
		a,b,c = map(int,inputs().split())
		E[2*n] = (a - c, 1, c)
		E[2*n + 1] = (b - c, -1, c)
	E.sort(key=itemgetter(0))
	tuple(tuple(E))
	mini = 1000000001
	kouho = {1000000001}
	my_add = kouho.add
	my_discard = kouho.discard
	q = 0
	d = int(inputs())
	flag = False
	cont = False
	for e in E:
		while e[0] > d:
			if cont == True:
				print(mini-(mini//1000000001)*1000000002)
			else:
				mini = min(kouho)
				print(mini-(mini//1000000001)*1000000002)
			cont = True
			q = q + 1
			if q > Q-1:
				flag = True
				break
			d = int(inputs())
		if flag == True:
			break
		if e[1] == 1:
			my_add(e[2])
			if mini > e[2]:
				mini = e[2]
		elif e[1] == -1:
			my_discard(e[2])
			if mini == e[2]:
				cont = False
	for t in [None]*(Q-q):
		print(-1)
main()
### BUGGY CODE ###

n= int(input())
gsb = [list(map(int,input().split())) for _ in range(2)]

def increase(num, gsb0, gsb1):
    max_num = 0
    g_max = num//gsb0[0] if (gsb0[0] < gsb1[0]) else 0
    for i in range(g_max + 1):
        remain = num - i*gsb0[0]
        s_max = remain//gsb0[1] if (gsb0[1] < gsb1[1]) else 0
        for j in range( s_max + 1 ):
            k = (remain - j*gsb0[1])//gsb0[2] if (gsb0[2] < gsb1[2]) else 0

            tmp = (num - i*gsb0[0] - j*gsb0[1] - k*gsb0[2]) + i*gsb1[0] + j*gsb1[1] + k*gsb1[2]
            max_num = max(max_num, tmp)

    return(max_num)

num = increase(n,gsb[0],gsb[1])
num = increase(num,gsb[1],gsb[0])

print(num)

### FIXED CODE ###

n= int(input())
gsb = [tuple(map(int,input().split())) for _ in range(2)]

def increase(num, gsb0, gsb1):
    dp = [ [num] * (num+1) for _ in range(3+1)]
    for i in range(1,4):
        w = gsb0[i-1]
        v = gsb1[i-1]
        for j in range(num+1):
            if(j < w):
                dp[i][j] = dp[i-1][j]
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-w] + v-w)

    return(dp[-1][-1])

num = increase(n,gsb[0],gsb[1])
num = increase(num,gsb[1],gsb[0])

print(num)
### BUGGY CODE ###

#k = int(input())
#s = input()
#a, b = map(int, input().split())
#s, t = map(str, input().split())
#l = list(map(int, input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
#a = [input() for _ in range(n)]


import itertools

n = int(input())
seq = list(map(int, input().split()))

ans = 0
a = list(itertools.combinations(seq,2))

for i in range(len(a)):
    #print(a[i][0], a[i][1])
    ans += a[i][0] * a[i][1]

ans %= 10**9+7

print(ans)



### FIXED CODE ###

#k = int(input())
#s = input()
#a, b = map(int, input().split())
#s, t = map(str, input().split())
#l = list(map(int, input().split()))
#l = [list(map(int,input().split())) for i in range(n)]
#a = [input() for _ in range(n)]


N = int(input())
seq = list(map(int, input().split()))

s = 0
for i in range(N):
    s += seq[i]

s2 =0
for i in range(N):
    s2 += seq[i]**2


s0 = (s**2 -s2)//2

print(s0%(10**9+7))
### BUGGY CODE ###

s=input()
q=int(input())
for _ in [0]*q:
	k=input()
	if k[0] == "1":
		s = s[::-1]
	else:
		if k[2] == "1":
			s = "".join([k[4:],s])
		else:
			s = "".join([s,k[4:]])
print(s)

### FIXED CODE ###

from collections import deque
s=input()
Q=int(input())
hanten = 0
mae = deque()
ushiro = deque()
for i in range(Q):
	q=input()
	if q=="1":
		hanten ^= 1
	else:
		if q[2] == "1":
			if hanten == 0:
				mae.appendleft(q[4])
			else:
				ushiro.append(q[4])
		else:
			if hanten == 0:
				ushiro.append(q[4])
			else:
				mae.appendleft(q[4])
if hanten == 0:
	print("".join(mae) + s + "".join(ushiro))
else:
	print(("".join(mae) + s + "".join(ushiro))[::-1])
### BUGGY CODE ###

def f(n):
	e=[1,0,0,1];z=[1,1,1,0]
	while n:e=[e,g(e,z)][n%2];z=g(z,z);n//=2
	return e[1]
M=998244353;g=lambda a,b:[(a[x]*b[y]+a[z]*b[w])%M for x,y,z,w in[[0,0,1,2],[0,1,1,3],[2,0,3,2],[2,1,3,3]]];n,m=map(int,input().split());I=[1,1];r=f(m+2*n-2);c=1
for i in range(2,n):I+=[(M-M//i)*I[M%i]%M]
for i in range(n-1):r=(r+c*(M-f(2*n-2-2*i)))%M;c=c*(m+i)*I[i+1]%M
print(r)

### FIXED CODE ###

M=998244353
g=lambda a,b:[(a[0]*b[0]+a[1]*b[2])%M,(a[0]*b[1]+a[1]*b[3])%M,(a[2]*b[0]+a[3]*b[2])%M,(a[2]*b[1]+a[3]*b[3])%M]
def f(n):
	e=[1,0,0,1];z=[1,1,1,0]
	while n:
		if n%2>0:e=g(e,z)
		z=g(z,z);n//=2
	return e[1]
n,m=map(int,input().split());I=[1,1];r=f(m+2*n-2);c=1
for i in range(2,n):I+=[(M-M//i)*I[M%i]%M]
for i in range(n-1):r=(r+c*(M-f(2*n-2-2*i)))%M;c=c*(m+i)*I[i+1]%M
print(r)
### BUGGY CODE ###

#!python3

import sys
sys.setrecursionlimit(10 ** 6)

LI = lambda: list(map(int, input().split()))

# input
N, M = LI()
AB = [LI() for _ in range(M)]

# params
link = [[] for _ in range(N)]
for a, b in AB:
    link[a - 1].append(b - 1)
impossible = [False] * N
n = [N]


def joint(v, visit, s):
    if impossible[v]:
        return []
    s = s | {v}
    visit = visit + [v]
    if len(visit) > n[0]:
        return []
    ans = []
    for u in link[v]:
        if u in s:
            i = visit.index(u)
            return visit[i:]
        t = joint(u, visit, s)
        if 0 < len(t):
            if ans == [] or 0 < len(t) < n[0]:
                ans = t
                n[0] = len(ans)
    if ans == []:
        impossible[v] = True
    return ans


def main():
    ans = []
    for i in range(N):
        t = joint(i, [], set())
        if 0 < len(t):
            if ans == [] or 0 < len(t) < len(ans):
                ans = t
    if ans == []:
        print(-1)
        return
    print(len(ans))
    for x in ans:
        print(x + 1)
        

if __name__ == "__main__":
    main()


### FIXED CODE ###

#!python3

import sys
sys.setrecursionlimit(10 ** 6)

LI = lambda: list(map(int, input().split()))

# input
N, M = LI()
AB = [LI() for _ in range(M)]

# params
link = [[] for _ in range(N)]
for a, b in AB:
    link[a - 1].append(b - 1)
impossible = [False] * N


def joint(v, visit):
    if impossible[v]:
        return None
    visit = visit + [v]
    for u in link[v]:
        if u in visit:
            i = visit.index(u)
            return visit[i:]
        t = joint(u, visit)
        if t is not None:
            return t
    impossible[v] = True
    return None


def solve(l):
    n = len(l)
    d = {l[i]: i for i in range(n)}
    for i in range(n):
        x = l[i]
        for y in link[x]:
            if y in d:
                j = d[y]
                if (i + 1) % n == j:
                    continue
                if j < i:
                    l = l[j : i + 1]
                else:
                    l = l[: i + 1] + l[j:]
                return solve(l)
    return l
            

def main():
    t = None
    for i in range(N):
        t = joint(i, [])
        if t is not None:
            break
    if t is None:
        print(-1)
        return
    
    ans = solve(t)
    print(len(ans))
    for x in ans:
        print(x + 1)
        

if __name__ == "__main__":
    main()