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

import numpy as np
n = int(input())
a =np.array([int(x) for x in input().split()])
q = int(input())
bc = [map(int, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]

sum1 = np.sum(a[a>10**5])
a = a[a<=10**5]
for i in range(q):
    a = np.sort(a)
    ans = 0
    for j in range(len(a)):
        if a[j] == b[i]:
            a[j] = c[i]
        ans += a[j]
    print(ans+sum1)

### FIXED CODE ###

import numpy as np
import collections

n = int(input())
a =np.array([int(x) for x in input().split()])
q = int(input())
bc = [map(int, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]

count_dict = collections.Counter(a)
ans = np.sum(a)
for i in range(q):
    if count_dict[b[i]] > 0:
        ans += count_dict[b[i]]*(c[i]-b[i])
        count_dict[c[i]] += count_dict[b[i]]
        count_dict[b[i]] = 0
    print(ans)
### BUGGY CODE ###

n=int(input())
a=list(map(int,input().split()))
x=0
for i in range(n):
  x+=a[i]
#print(x)
m=[]
for i in range(n):
  m+=[(a[(i+1)%n]-a[i])*2]
#print(m)
for i in range(n):
  x-=m[2*i%n]*(n-i-1)
#print(x)
ans=[0 for _ in range(n)]
ans[0]=x//n
for i in range(1,n):
  ans[2*i%n]=ans[2*(i-1)%n]+m[2*(i-1)%n]
#print(ans)
s=""
for i in range(n-1):
  s+=str(ans[i])+" "
s+=str(ans[n-1])
print(s)

### FIXED CODE ###

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

m=[]
for i in range(n):
  m+=[(a[(i+1)%n]-a[i])*2]
#print(x)
#print(m)

ans=[0 for _ in range(n)]
for i in range(1,n):
  ans[2*i%n]=+m[2*(i-1)%n]
for i in range(n-1):
  m[2*(i+1)%n]+=m[2*i%n]
#print(m)
for i in range(n):
  x+=a[i]
  x-=m[2*i%n]
#print(x)
ans[0]=x//n
for i in range(1,n):
  ans[2*i%n]+=ans[2*(i-1)%n]
#print(ans)
for i in range(n-1):
  print(ans[i],end=" ")
print(ans[n-1])
### BUGGY CODE ###

from bisect import bisect_right
from bisect import bisect_left

n = int(input())
lengths = map(int, input().split())

res = 0
sorted_lengths = sorted(lengths)
for i in range(n):
	l1 = sorted_lengths[i]
	for j in range(i + 1, n - 1):
		l2 = sorted_lengths[j]
		rem = sorted_lengths[j + 1:]
		res += bisect_left(rem, l1 + l2) - bisect_left(rem, l2 - l1)

print(res)


### FIXED CODE ###

from bisect import bisect_left

n = int(input())
lengths = sorted(map(int, input().split()))

res = 0
for i in range(n):
	l1 = lengths[i]
	for j in range(i + 1, n - 1):
		l2 = lengths[j]
		res += bisect_left(lengths, l1 + l2, j + 1) - j - 1

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

S = input()

MOD = 10 ** 9 + 7
N = 13

DP = [0] * N

# 初期値
DP[0] = 1
digit = 1

# 0 -> 5 -> ?5 -> ??5 -> ...に対する余りがどこになるかを更新していく
for i in range(len(S) - 1, -1, -1):
    nextDP = [0] * N

    if S[i] == "?":
        for k in range(10):
            for j in range(N):
                nextDP[(k * digit + j) % N] += DP[j]
                nextDP[(k * digit + j) % N] %= MOD
    else:
        k = int(S[i])
        for j in range(N):
            nextDP[(k * digit + j) % N] += DP[j]
            nextDP[(k * digit + j) % N] %= MOD

    digit *= 10
    digit %= N
    DP = nextDP[:]

print(DP[5])





### FIXED CODE ###

S = input()
 
MOD = 10 ** 9 + 7
N = 13
 
DP = [0] * N
 
# 初期値
DP[0] = 1
digit = 1
 
# 0 -> 5 -> ?5 -> ??5 -> ...に対する余りがどこになるかを更新していく
for i in range(len(S) - 1, -1, -1):
    nextDP = [0] * N
 
    if S[i] == "?":
        for k in range(10):
            for j in range(N):
                nextDP[(k * digit + j) % N] += DP[j]
                nextDP[(k * digit + j) % N] %= MOD
    else:
        k = int(S[i])
        for j in range(N):
            nextDP[(k * digit + j) % N] += DP[j]
            nextDP[(k * digit + j) % N] %= MOD
 
    digit *= 10
    digit %= N
    DP = nextDP[:]
 
print(DP[5])
 
"""
??2??5

"""
### BUGGY CODE ###

#!/usr/bin/env python
import numpy as np
N = int(input())
alphabets = list('abcdefghijklmnopqrstuvwxyz')
A = np.zeros((N, N))
for i in range(N):
    for j, c in enumerate(input()):
        A[i,j] = alphabets.index(c)

B = np.concatenate([A, A], axis=0)
B = np.concatenate([B, B], axis=1)
cnt = 0
for i in range(N):
    for j in range(N):
        C = B[i:i+N, j:j+N]
        if (C==C.T).all():
            cnt += 1
print(cnt)

### FIXED CODE ###

#!/usr/bin/env python
import numpy as np
N = int(input())
alphabets = list('abcdefghijklmnopqrstuvwxyz')
A = np.zeros((N, N), dtype=int)
for i in range(N):
    for j, c in enumerate(input()):
        A[i,j] = alphabets.index(c)

B = np.concatenate([A, A], axis=0)
cnt = 0
for i in range(N):
    C = B[i:i+N, :]
    if (C==C.T).all():
        cnt += 1
print(cnt*N)
### BUGGY CODE ###

n, k, q = map(int, input().split())
a = list()
for i in range(0, q):
    a.append(int(input()))

score = [k]*n

for i in a:
    score[i-1] += 1
    for x in range(len(score)):
         score[x] = score[x] - 1

for x in score:
    if x > 0:
        print("Yes")
    else:
        print("No")


### FIXED CODE ###

n, k, q = map(int, input().split())
a = list()
for i in range(0, q):
    a.append(int(input()))

score = [k - q]*n

for i in a:
    score[i-1] += 1

for x in score:
    if x > 0:
        print("Yes")
    else:
        print("No")
### BUGGY CODE ###

import sys

#sys.stdin = open('input3.txt', 'r')

H, W, N = map(int, raw_input().split())
points = []
for _ in range(N):
	a, b = map(int, raw_input().split())
	points.append((a,b))

points.sort(key=lambda x:x[0])
searched = {}
for p in points:
	searched[p] = 0
results = {}
for x in range(10):
	results[x] = 0

def get_points(h, w):
	if ((h + 2 >  H) or (w + 2 > W) or (h < 1) or (w < 1)):
		return 0
	else:
		count = 0
		for x in range(3):
			for y in range(3):
				if ( (h + x, w + y) in searched ):
					if searched[(h + x, w + y)] == 0:
						count = count + 1
					else:
						return 0
		return count

def search_three_by_three_square(pt):
	h, w = pt[0], pt[1]
	results[get_points(h, w)] = results[get_points(h, w)] + 1
	results[get_points(h - 1, w)] = results[get_points(h - 1, w)] + 1
	results[get_points(h - 2, w)] = results[get_points(h - 2, w)] + 1

	results[get_points(h, w - 1)] = results[get_points(h, w - 1)] + 1
	results[get_points(h - 1, w - 1)] = results[get_points(h - 1, w - 1)] + 1
	results[get_points(h - 2, w - 1)] = results[get_points(h - 2, w - 1)] + 1

	results[get_points(h, w - 2)] = results[get_points(h, w - 2)] + 1
	results[get_points(h - 1, w - 2)] = results[get_points(h - 1, w - 2)] + 1
	results[get_points(h - 2, w - 2)] = results[get_points(h - 2, w - 2)] + 1

	searched[pt] = 1

for p in points:
	search_three_by_three_square(p)

zero = (W - 2) * (H - 2)
for x in range(1, 10, 1):
	zero = zero - results[x]
results[0] = zero
for x in range(10):
	print str(results[x])


### FIXED CODE ###

import sys

#sys.stdin = open('input1.txt', 'r')

H, W , N = map(int, raw_input().split())
squares = {}
results = [0 for _ in range(10)]
for _ in range(N):
	h, w = map(int, raw_input().split())
	for x in [(0, 0), (0, -1), (0, -2), (-1, 0), (-1, -1), (-1, -2), (-2, 0), (-2, -1), (-2, -2)]:
		nh, nw = h + x[0], w + x[1]
		if ((nh < 1) or (nw < 1) or (nh + 2 > H) or (nw + 2 > W)):
			pass
		else:
			if (nh, nw) in squares:
				squares[(nh, nw)] += 1
			else:
				squares[(nh, nw)] = 1

for v in squares.values():
	results[v] += 1

results[0] = (H - 2) * (W - 2) - sum(results[1:])

for x in range(10):
	print str(results[x])
### BUGGY CODE ###



import numpy as np

a,b,k=map(int,input().split())
for i in range(a,b+1):
    if(i-a<k or b-i<k):
        print(i)
        

### FIXED CODE ###

a,b,k=map(int,input().split())
se=set(set(range(a,a+k))|set(range(b-k+1,b+1)))
li=[x for x in se if a<=x<=b]
li=sorted(li)
print(*li,sep="\n")
### BUGGY CODE ###

s=input()
query=int(input())

li_q = []
for _ in range(query):
    li_q.append(input().split())

rev = False
li_str = [s]
for q in li_q:
    if q[0] == '1':
        rev = not rev
    else:
        if q[1] == '1':
            if rev:
                li_str.append(q[2])
            else:
                li_str.insert(0, q[2])
        else:
            if rev:
                li_str.insert(0, q[2])
            else:
                li_str.append(q[2])
                
ans = ''.join(li_str)
if rev:
    ans = ans[::-1]
    
print(ans)

### FIXED CODE ###

from collections import deque

s=input()
query=int(input())

li_q = []
for _ in range(query):
    li_q.append(input().split())

rev = False
q_str = deque([s])
for q in li_q:
    if q[0] == '1':
        rev = not rev
    else:
        if q[1] == '1':
            if rev:
                q_str.append(q[2])
            else:
                q_str.appendleft(q[2])
        else:
            if rev:
                q_str.appendleft(q[2])
            else:
                q_str.append(q[2])

li_str = list(q_str)
ans = ''.join(li_str)
if rev:
    ans = ans[::-1]
    
print(ans)
### BUGGY CODE ###

n = int(input())
string = input()

r=g=b=0

for idx, s in enumerate(string):
    if s == 'R':
        r+=1
    elif s == 'B':
        b+=1
    elif s == 'G':
        g+=1

ans = r*g*b

for i in range(n):
    for j in range(i+1, n):
        k = 2*j - i
        if k < n and len(set([string[i],string[j], string[k]])) == 3:
            ans -= 1

print(ans)
            



### FIXED CODE ###

n = int(input())
string = input()
r = 0
g = 0
b = 0
for c in string:
    if c == 'R':
        r += 1
    elif c == 'G':
        g += 1
    else:
        b += 1
ans = r*g*b
for i in range(n):
    for j in range(i+1, n):
        if 2*j - i >= n:
            break
        
        if string[i] != string[j] and string[i] != string[2*j-i] and string[j] != string[2*j-i]:
            ans -= 1
print(ans)
### BUGGY CODE ###

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

for i in range(n):
    if a[i] in d:
        d[a[i]] += 1
    else:
        d[a[i]] = 1

for i in range(n):
    b = a[i]
    d[b] = d[b]-1
    count = 0
    for j in d:
        temp_count = d[j]*(d[j]-1)//2
        count += temp_count
    d[b] = d[b] + 1
    print(count)

### FIXED CODE ###

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

for i in range(n):
    if a[i] in d:
        d[a[i]] += 1
    else:
        d[a[i]] = 1

count = 0
for i in d:
    count += d[i] * (d[i] - 1) // 2


for i in range(n):
    b = d[a[i]]
    print(count-b+1)
### BUGGY CODE ###

import numpy as np

N, M = map(int, input().split())

A_list = list(map(int, input().split()))

R_list = []

for _ in range(M):
  B, C = map(int, input().split())
  BC_list = [C]*B
  R_list.extend(BC_list)

R_list = np.array(R_list)
R_list = np.sort(R_list)
R_list = R_list[::-1]
R_list = R_list[:N]

A_list = np.array(A_list)
A_list = np.sort(A_list)

short_len = N - len(R_list)

if short_len > 0:
  R_list = np.append(R_list, [0]*short_len)

print(np.sum(np.maximum(A_list,R_list)))

### FIXED CODE ###

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
from operator import itemgetter
 
N,M = map(int,readline().split())
A = list(map(int,readline().split()))
m = map(int,read().split())
BC = list(zip(m,m))
 
BC.sort(key = itemgetter(1),reverse=True)
 
BC.append((N,-1))
 
change = []
for b,c in BC:
    change += [c] * b
    if len(change) > N:
        break
 
A += change
A.sort()
answer = sum(A[-N:])
print(answer)
### BUGGY CODE ###

N = int(input())
A = [int(i) for i in input().split()]


def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors


ans = []
c = 0
for i in range(N, 0, -1):
    if A[i-1] % 2 == 1:
        c += 1
        ans.append(i)
        for j in make_divisors(i):
            A[j-1] += 1
print(c)
if c != 0:
    print(*ans[::-1])


### FIXED CODE ###



from collections import defaultdict
N = int(input())
a = [int(i) for i in input().split()]

d = defaultdict(int)
# balls = [0 for _ in range(N)]

ans = 0
for n in range(N, 0, -1):
    a_i = a[n-1]
    cnt = 0
    n2 = n*2
    while n2 <= N:
        cnt += d[n2]
        n2 += n
    if cnt % 2 != a_i:
        d[n] = 1
        ans += 1

print(ans)
if ans >= 1:
    for k, v in d.items():
        if v == 1:
            print(k)
### BUGGY CODE ###

import itertools
N, K = map(int,input().split())
A = list(map(int,input().split()))
K = min(41,K)
#A = [0] * N

for k in range(K):
    imos = [0] * (N+1)
    for n in range(N):
        a = n - A[n]
        b = n + A[n]
        a = max(0,a)
        b = min(N-1,b)
        imos[a] += 1
        imos[b+1] -= 1
    csum = list(itertools.accumulate(imos))
    A = csum[:-1]
A = [str(a) for a in A]
print (' '.join(A))


### FIXED CODE ###

import itertools
N, K = map(int,input().split())
A = list(map(int,input().split()))
K = min(41,K)
#A = [0] * N

for k in range(K):
    imos = [0] * (N+1)
    for n in range(N):
        a = n - A[n]
        b = n + A[n]
        a = max(0,a)
        b = min(N-1,b)
        imos[a] += 1
        imos[b+1] -= 1
    csum = list(itertools.accumulate(imos))
    A = csum[:-1]
A = [str(a) for a in A]
print (' '.join(A))
### BUGGY CODE ###

n = int(input())
A = list(map(int, input().split()))
q = int(input())
M = list(map(int, input().split()))


def solve(i, m, A): 
    if m == 0:
        return True
    elif i >= n:
        return False
    res = solve(i + 1, m, A) or solve(i + 1, m - A[i], A)
    return res
 
for m in M:
    if solve(0, m, A):
        print('yes')
    else:
        print('no')

### FIXED CODE ###

n = int(input())
A = list(map(int, input().split()))
q = int(input())
M = list(map(int, input().split()))

table = [[-1 for i in range(max(M)+1)] for j in range(n)]

def solve(i, m):
    if m == 0:
        return True
    elif i >= n:
        return False
    elif table[i][m] != -1:
        return table[i][m]
    elif m - A[i] >= 0:
        res = solve(i + 1, m) or solve(i + 1, m - A[i])
        table[i][m] = res
        return res
    else:
        res = solve(i + 1, m)
        table[i][m] = res
        return res

for m in M:
    if solve(0, m):
        print('yes')
    else:
        print('no')
### BUGGY CODE ###


s = input()
# s = 'ABCABC'

count = 0

while True:
    idx = s.find('ABC')
    if idx == -1:
        break
    s = s[:idx] + 'BCA' + s[idx+3:]
    count += 1
    # print(s)


print(count)
# print(idx)
# print(s)

### FIXED CODE ###

def test(s):

	res = 0
	aAdd = 0
	last = ''
	tmp = ''
	for i in xrange(len(s)):
		if tmp and tmp > i:
			continue
		if s[i] == 'A':
			aAdd += 1
		elif s[i:i+2] == 'BC':
			# print aAdd
			res = res + aAdd
			tmp = i + 2
		else:
			aAdd = 0
			last = s[i]


	return res
s=raw_input()
print test(s)
### BUGGY CODE ###

#import numpy as np
#from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix

from collections import* #defaultdict Counter deque appendleft
from fractions import gcd
from functools import* #reduce
from itertools import* #permutations("AB",repeat=2) combinations("AB",2) product("AB",2) groupby accumulate
from operator import mul,itemgetter
from bisect import* #bisect_left bisect_right
from heapq import* #heapify heappop heappushpop
from math import factorial,pi
from copy import deepcopy
import sys
sys.setrecursionlimit(10**8)
#input=sys.stdin.readline  #危険！基本オフにしろ！

def main():
    MOD=10**9+7
    s="0"+input()
    dp=[[0]*len(s)for i in range(13)]
    dp[0][0]=1
    for k,j in enumerate(s[1:]):
        for i in range(13):
            if dp[i][k]:
                if j=="?":
                    for r in range(10):
                        dp[int(str(i)+str(r))%13][k+1]+=dp[i][k]%MOD
                else:
                    dp[int(str(i)+j)%13][k+1]+=dp[i][k]%MOD
    print(dp[5][-1]%MOD)
    
if __name__ == '__main__':
    main()
    

### FIXED CODE ###

def main():
    MOD=10**9+7
    s="0"+input()
    dp=[[0]*len(s)for i in range(13)]
    dp[0][0]=1
    for k,j in enumerate(s[1:]):
        for i in range(13):
            if dp[i][k]:
                if j=="?":
                    for r in range(10):
                        dp[(10*i+r)%13][k+1]+=dp[i][k]%MOD
                else:
                    dp[int(str(i)+j)%13][k+1]+=dp[i][k]%MOD
    print(dp[5][-1]%MOD)
if __name__ == '__main__':
    main()
### BUGGY CODE ###

import queue
import copy
def dfs(L,start,end):
    stack = [start]

    visited = []

    #path[node] : shortest path of node from start to
    path =[ 0 for i in range((len(L)+1))]

    while stack:
        node = stack.pop()
        if node == end:
            return path[end]
        for n in L[node]:
            if n[0] not in visited:

                path[n[0]] = path[node]  + n[1]

                stack.append(n[0])
                visited.append(n[0])


N = int(input())
p = []
for i in range(N-1):
    l = list(map(int,input().split()))
    p.append(l)

Q,K = map(int,input().split())
xy = []
for i in range(Q):
    xy.append(list(map(int,input().split())))


L = [ [] for i in range(N+1)]
for l in p:
    L[l[0]].append([l[1],l[2]])
    L[l[1]].append([l[0],l[2]])

pp = []
for i in range(len(p)):
    pp.append([p[i][1],p[i][0],p[i][2]])
p.extend(pp)
for i in range(Q):
    v1 = dfs(L,xy[i][0],K)
    v2 = dfs(L,K,xy[i][1])
    print(v1+v2)



### FIXED CODE ###

import sys
def dfs(L,start):
    stack = [start]

    path =[-1]*len(L)
    path[start] = 0
    while stack:
        node = stack.pop()
        for n in L[node]:
            if path[n[0]] < 0:
                path[n[0]] = path[node]  + n[1]
                stack.append(n[0])

    return path

#input
input = sys.stdin.readline
N = int(input())
p = []
for i in range(N-1):
    l = list(map(int,input().split()))
    p.append(l)

Q,K = map(int,input().split())
xy = []
for i in range(Q):
    xy.append(list(map(int,input().split())))

#neigher list
L = [ [] for i in range(N+1)]
for l in p:
    L[l[0]].append([l[1],l[2]])
    L[l[1]].append([l[0],l[2]])

d = dfs(L,K)

for i in range(Q):
    print(d[xy[i][0]]+ d[xy[i][1]])
### BUGGY CODE ###

# -*- coding: utf-8 -*-

from math import sqrt
from itertools import permutations, combinations_with_replacement
import numpy as np

def num_div_set2(N):
    # 1とその数はデフォで入れとく
    s = {1, N}
    # 終点はルート切り捨て+1
    end = int(sqrt(N)) + 1
    for i in range(2, end+1):
        # 割り切れるなら、iとN/iを追加
        if N % i == 0:
            s.add(i)
            s.add(N // i)
    return s

N, M = map(int, input().split())
MOD = 10 ** 9 + 7

ans = 0
for comb in combinations_with_replacement(num_div_set2(M), N):
    if np.prod(comb) == M:
        ans = (ans + len(set(permutations(comb)))) % MOD
print(ans)


### FIXED CODE ###

# -*- coding: utf-8 -*-

"""
参考：http://drken1215.hatenablog.com/entry/2018/09/23/224100
　　　http://tutuz.hateblo.jp/entry/2018/09/24/121248
・素因数分解と重複組み合わせ
・毎回階乗やると死ぬから階乗と逆元のテーブル作る(忘れてた)
"""

from collections import defaultdict
from math import sqrt

MOD = 10 ** 9 + 7

def fact_prime(num):
    d = defaultdict(int)
    # 終点はルート切り捨て+1
    end = int(sqrt(num)) + 1
    for i in range(2, end+1):
        cnt = 0
        # 素因数分解：小さい方から割れるだけ割って素数をカウント
        while num % i == 0:
            num //= i
            d[i] += 1
        # 1まで来たら終了
        if num == 1:
            break
    # 最後までそのまま来たやつはnumが素数(ただし1^1は1^0なので数に入れない)
    if num != 1:
        d[num] += 1
    return d

# とりあえずv+N-1が収まればいいはず
MAX = 10 ** 5 * 2
# 予め組み合わせ計算に必要な階乗と逆元のテーブルを作っておく
factorial = [1] * (MAX)
factorial[0] = factorial[1] = 1
for i in range(2, MAX):
    factorial[i] = factorial[i-1] * i % MOD

inverse = [1] * (MAX)
# powに第三引数入れると冪乗のmod付計算を高速にやってくれる
inverse[MAX-1] = pow(factorial[MAX-1], MOD-2, MOD)
for i in range(MAX-2, 0, -1):
    # 最後から戻っていくこのループならH+W回powするより処理が速い
    inverse[i] = inverse[i+1] * (i+1) % MOD

# 組み合わせの数
def nCr(n, r):
    # 10C7 = 10C3
    r = min(r, n-r)
    # 分子の計算
    numerator = factorial[n]
    # 分母の計算
    denominator = inverse[r] * inverse[n-r] % MOD
    return numerator * denominator % MOD

N, M = map(int, input().split())

# d = fact_prime(M)
# print(d)
ans = 1
for k, v in fact_prime(M).items():
    # 重複組み合わせ
    # v個のkとN-1個の仕切りから、v個を並べる(v+N-1個のマスからv個を選び出す組み合わせ)
    ans = (ans * nCr(v+N-1, v)) % MOD
print(ans)
### BUGGY CODE ###

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

e_list = [[] for i in range(N)]

for i in range(M):
    a,b = list(map(int,input().split()))
    a,b = a-1,b-1
    e_list[a].append((b,1))

import heapq
flag=False
min_d = 10**27
for vg in range(N):
    for vi,_ in e_list[vg]:
        #dijkstra
        #you need to prepare e_list = [[orient,dist]]
        
        min_d_list = [10**27 for i in range(N)]
        min_d_list[vi] = 0
        prev_list = [-1 for i in range(N)]
        q = []
        for i in range(N):
            heapq.heappush(q,[min_d_list[i],i])
        
        while len(q)>0:
            d,v = heapq.heappop(q)
            for e in e_list[v]:
                v1,d1=e
                if v!=vg or v1!=vi:
                    if min_d_list[v1]>d+d1:
                        min_d_list[v1]=d+d1
                        prev_list[v1]=v
                        heapq.heappush(q,[d+d1,v1])
        if min_d_list[vg]<min_d:
            flag=True
            min_vi = vi
            min_vg = vg
            min_d = min_d_list[vg]
            min_prev = prev_list
            
#print(min_d_list)
if flag:
    ans = []
    v = min_vg
    while v!=min_vi:
        ans.append(v+1)
        v=min_prev[v]
    ans.append(min_vi+1)
    ans = ans[::-1]
    
    print(len(ans))
    for a in ans:
        print(a)
else:
    print(-1)

### FIXED CODE ###

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

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

from collections import deque
flag=False
min_d = 10**27
for vg,vi in es:
    Q = deque([vi])
    checked_list = [False for i in range(N)]
    checked_list[vi]=True
    min_path_list = [10**27 for i in range(N)] #問題によりここを変える
    min_path_list[vi] = 0
    prev_list = [-1]*N
    while len(Q)>0:
        v = Q.pop()
        for v1 in e_list[v]:
            if v!=vg or v1!=vi:
                if not checked_list[v1]:
                    checked_list[v1]=True
                    Q.appendleft(v1)
                    prev_list[v1]=v
                    min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1) #問題によりここを変える
    if min_path_list[vg]<min_d:
        flag=True
        min_vi = vi
        min_vg = vg
        min_d = min_path_list[vg]
        min_prev = prev_list
            
#print(min_d_list)
if flag:
    ans = []
    v = min_vg
    while v!=min_vi:
        ans.append(v+1)
        v=min_prev[v]
    ans.append(min_vi+1)
    ans = ans[::-1]
    
    print(len(ans))
    for a in ans:
        print(a)
else:
    print(-1)
### BUGGY CODE ###

number,money=input().rstrip().split()
number=int(number)
money=int(money)
bill=[0,0,0]

for i in range(number+1):
    bill=[0,0,0]
    mass=money-10000*i
    bill[0]=i
    if mass==0 and sum(bill)==number:
        break
    elif mass<0:
        break
    else:
        for j in range(number+1):
            if j!=0:
                mass=mass-5000
            bill[1]=j
            if mass==0 and sum(bill)==number:
                break
            elif mass<0:
                break
            else:
                k=int(mass/1000)
                bill[2]=k
                if sum(bill)==number:
                    break
    if sum(bill)==number:
        mass=0
        break
                
if mass==0:
    print(str(bill[0])+' '+str(bill[1])+' '+str(bill[2]))
else:
    print(str(-1)+' '+str(-1)+' '+str(-1))


### FIXED CODE ###

number,money=input().rstrip().split()
number=int(number)
money=int(money)
bill=[0,0,0]

for i in range(number+1):
    bill=[0,0,0]
    mass=money-10000*i
    bill[0]=i
    if mass==0 and sum(bill)==number:
        break
    elif mass<0:
        break
    else:
        for j in range(number+1-i):
            if j!=0:
                mass=mass-5000
            bill[1]=j
            if mass==0 and sum(bill)==number:
                break
            elif mass<0:
                break
            else:
                k=int(mass/1000)
                bill[2]=k
                if sum(bill)==number:
                    break
    if sum(bill)==number:
        mass=0
        break
                
if mass==0:
    print(str(bill[0])+' '+str(bill[1])+' '+str(bill[2]))
else:
    print(str(-1)+' '+str(-1)+' '+str(-1))