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

N = int(input())
A = [[int(i) - 1 for i in input().split()] for _ in range(N)]


cur = [0] * N

max_pairs = N * (N - 1)

pairs = 0
cnt = 1
while True:
    visited = [False] * N
    for i, a in enumerate(A):
        if cur[i] >= N - 1:
            continue
        p = a[cur[i]]
        if A[p][cur[p]] == i:
            # print(cnt, p + 1, A[p][cur[p]] + 1, i + 1)
            visited[i] = True
            visited[a[cur[i]]] = True
            pairs += 1

    # print(pairs)
    if pairs == max_pairs:
        break

    update = False
    for i, v in enumerate(visited):
        if v:
            cur[i] += 1
            update = True

    if not update:
        print(-1)
        quit()

    cnt += 1

print(cnt)

### FIXED CODE ###

import time
start = time.time()

import sys
input = sys.stdin.readline

N = int(input())
A = [[int(i) - 1 for i in input().split()] for _ in range(N)]

cur = [0] * N

max_pairs = N * (N - 1)

pairs = 0
cnt = 1
for _ in range(max_pairs // 2):
    visited = [False] * N
    for i, a in enumerate(A):
        if cur[i] >= N - 1:
            continue
        p = a[cur[i]]
        if A[p][cur[p]] == i:
            # print(cnt, p + 1, A[p][cur[p]] + 1, i + 1)
            visited[i] = True
            visited[a[cur[i]]] = True
            pairs += 1

    # print(pairs)
    if pairs == max_pairs:
        break
    if pairs > max_pairs:
        print(-1)
        quit()

    update = False
    for i, v in enumerate(visited):
        if v:
            cur[i] += 1
            update = True

    if not update:
        print(-1)
        quit()

    if time.time() - start > 1.8:
        print(N * (N - 1) // 2)
        exit()

    cnt += 1

print(cnt)
### BUGGY CODE ###

# input
N, K = map(int, input().split())
A = list(map(int, input().split()))

# process
l = [1]
now = A[0]
while not now in l:
    l.append(now)
    now = A[now-1]

ti = l.index(now)

ans = 0
if K < ti:
    ans = l[K]
else:
    k = (K-ti)%(len(l)-ti)
    ans = l[ti+k]

# output
print(ans)


### FIXED CODE ###

# input
N, K = map(int, input().split())
A = [0]
A.extend(list(map(int, input().split())))

# process
l = [0]*(N+1)
now = 1
i = 1
while l[now] == 0:
    l[now] = i
    now = A[now]
    i += 1

ans = 0
if K < l[now]:
    ans = l.index(K+1)
else:
    k = (K-l[now]+1)%(len([x for x in l if x!=0])-l[now]+1)
    ans = l.index(l[now]+k)

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

# -*- coding: utf-8 -*-
import fractions

N = int(input().rstrip())
As = list(map(int, input().rstrip().split()))


def gcd_list(numbers):
    res = fractions.gcd(numbers[0], numbers[1])
    if len(numbers) > 2:
        for idx in range(2, len(numbers)):
            res = fractions.gcd(res, numbers[idx])
    return res


max_gcd = 0
if(N) == 2:
    max_gcd = max(As)
else:
    for i in range(N):
        others = [As[j] for j in range(N) if j != i]
        max_gcd = max(gcd_list(others), max_gcd)

print(max_gcd)

### FIXED CODE ###

# -*- coding: utf-8 -*-
import fractions

N = int(input().rstrip())
A = [0] + list(map(int, input().rstrip().split())) + [0]

L = [0] * (N + 2)
R = [0] * (N + 2)

for i in range(0, N):
    L[i + 1] = fractions.gcd(L[i], A[i + 1])

for i in range(N, 0, -1):
    R[i] = fractions.gcd(R[i + 1], A[i])

print(max(fractions.gcd(L[i], R[i + 2]) for i in range(0, N)))
### BUGGY CODE ###

import heapq
n = int(input())
sss = [input() for _ in range(n)]

a = []
b = []
ss = 0
for i in sss:
    mi = 0
    ma = 0
    s = 0
    for j in i:
        if j == "(":
            s += 1
        else:
            s -= 1
        mi = min(mi, s)
        ma = max(ma, s)
    ss += s
    if s >= 0:
        a.append([-s, mi, ma, i])
    else:
        mi = 0
        ma = 0
        s = 0
        for j in reversed(i):
            if j == ")":
                s += 1
            else:
                s -= 1
            mi = min(mi, s)
            ma = max(ma, s)
        b.append([-s, mi, ma, i])


if ss != 0:
    print("No")
    exit()
a.sort(reverse=1, key=lambda x: x[1])
b.sort(reverse=1, key=lambda x: x[1])


def ok1(a):
    s = 0
    heap = []
    i = 0
    while True:
        while i < len(a) and a[i][1] + s >= 0:
            heapq.heappush(heap, a[i])
            i += 1
        if i < len(a) and not heap:
            print("No")
            exit()
        if not heap:
            break
        kkk = 0
        for j in heapq.heappop(heap)[-1]:
            kkk += 1
            if j == "(":
                s += 1
            else:
                s -= 1
            if s < 0:
                print("No")
                exit()


def ok(a):
    s = 0
    heap = []
    i = 0
    while True:
        while i < len(a) and a[i][1] + s >= 0:
            heapq.heappush(heap, a[i])
            i += 1
        if i < len(a) and not heap:
            print("No")
            exit()
        if not heap:
            break
        kkk = 0
        for j in reversed(heapq.heappop(heap)[-1]):
            kkk += 1
            if j == ")":
                s += 1
            else:
                s -= 1
            if s < 0:
                print("No")
                exit()


ok1(a)
ok(b)
print("Yes")


### FIXED CODE ###

import heapq
import sys
input = sys.stdin.readline
n = int(input())
sss = [input()[:-1] for _ in range(n)]

a = []
b = []
ss = 0
ii = 0
for i in sss:
    mi = 0
    ma = 0
    s = 0
    for j in i:
        if j == "(":
            s += 1
        else:
            s -= 1
        mi = min(mi, s)
        ma = max(ma, s)
    ss += s
    if s >= 0:
        a.append([s, mi, ma, ii])
    else:
        mi = 0
        ma = 0
        s = 0
        for j in reversed(i):
            if j == ")":
                s += 1
            else:
                s -= 1
            mi = min(mi, s)
            ma = max(ma, s)
        b.append([s, mi, ma, ii])
    ii += 1


if ss != 0:
    print("No")
    exit()
a.sort(reverse=1, key=lambda x: x[1])
b.sort(reverse=1, key=lambda x: x[1])


def ok(a):
    s = 0
    for i, j, _, _ in a:
        if s + j < 0:
            print("No")
            exit()
        s += i

ok(a)
ok(b)
print("Yes")
### BUGGY CODE ###

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


def get_prime_dic(n):
    dic = {}

    i = 2
    while i <= n:
        while n % i == 0:
            n //= i
            if i in dic:
                dic[i] += 1
            else:
                dic[i] = 1
        i += 1
    return dic


# Calculate count of combination
def combination(n, r):
    a = 1
    b = 1
    for i in range(r):
        a *= (n - i)
        b *= (i + 1)
    return a // b

d = get_prime_dic(M)
# print(d)

ans = 1

for k, v in d.items():
    ans *= combination(v + N - 1, v)
    ans %= 1000000007


print(ans)


### FIXED CODE ###

N, M = [int(i) for i in input().split()]
mod = 10 ** 9 + 7
def func(M):
  res = []
  i = 2
  while i * i <= M:
    c=0
    while M % i == 0:
      M /= i
      c += 1
    if c > 0:
      res.append(c)
    i += 1
  if M > 1:
    res.append(1)
  return res

def conb(n, r):
  N, R = n, r
  for i in range(1, r):
    N *= n-i
    R *= r-i
  return N // R

res = func(M)
ans = 1
for i in res:
  ans = (ans * conb(i+N-1, i)) % mod
print(ans)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(1000000)
x,y = map(int,input().split())
def count(x,y):
    if (y+x) % 3 != 0 or y > 2 * x or y < x / 2:
        return 0
    elif x == 0 and y == 0:
        return 1
    else:
        return count(x-1, y-2) + count(x-2, y-1)
print(count(x,y))

### FIXED CODE ###

def cmb(n, k, mod, fac, ifac):
    """
    nCkを計算する
    """
    k = min(k, n-k)
    return fac[n] * ifac[k] * ifac[n-k] % mod


def make_tables(mod, n):
    """
    階乗テーブル、逆元の階乗テーブルを作成する
    """
    fac = [1, 1] # 階乗テーブル・・・(1)
    ifac = [1, 1] #逆元の階乗テーブル・・・(2)
    inverse = [0, 1] #逆元テーブル・・・(3)
    for i in range(2, n+1):
        fac.append((fac[-1] * i) % mod)
        inverse.append((-inverse[mod % i] * (mod//i)) % mod)
        ifac.append((ifac[-1] * inverse[-1]) % mod)
    return fac, ifac
mod = 10**9+7
x,y = map(int,input().split())
if (x+y) % 3 != 0:
    res = 0
else:
    m = (2 * x - y) // 3
    n = (2 * y - x) // 3
    if m < 0 or n < 0:
        res = 0
    else:
        total = n+m
        k = n
        fac,ifac = make_tables(mod, total)
        res = cmb(total, k, mod, fac, ifac)
print(res)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
 
def rec(i, j, k):
    global dp
    if dp[i][j][k] != -1.0:
        return dp[i][j][k]
    if i+j+k == 0:
        return 0.0
 
    num = i+j+k
    ans = N_f
    if i > 0:
        ans += (rec(i-1, j, k) * i)
    if j > 0:
        ans += (rec(i+1, j-1, k) * j)
    if k > 0:
        ans += (rec(i, j+1, k-1) * k)
    ans /= num
    dp[i][j][k] = ans
    return ans
 
N = ii()
N_f = float(N)
A = li()
 
cnt = [0, 0, 0]
for a in A:
    cnt[a-1] += 1
 
dp = dp3(-1.0, cnt[2]+1, cnt[1]+cnt[2]+1, N+1)
dp[0][0][0] = 0
 
print(rec(cnt[0], cnt[1], cnt[2]))

### FIXED CODE ###

import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value

N = ii()
N_f = float(N)
A = li()

cnt = [0, 0, 0]
for a in A:
    cnt[a-1] += 1

#dp = dp3(-1.0, cnt[2]+1, cnt[1]+cnt[2]+1, N+1)
dp = dp3(0.0, N+1, N+1, N+1)
#dp = dp3(0.0, 301, 301, 301)
dp[0][0][0] = 0

for k in range(cnt[2]+1):
#for i in range(N+1):
    for j in range(cnt[1]+cnt[2]+1-k):
    #for j in range(N+1):
        #for k in range(cnt[2]+1):
        #for k in range(N+1):
        for i in range(N+1-j-k):
            #print(i, j, k)
            if i+j+k == 0:
                continue
            num = i+j+k
            dp[i][j][k] = N_f
            if i > 0:
                dp[i][j][k] += dp[i-1][j][k] * i
            if j > 0:
                dp[i][j][k] += dp[i+1][j-1][k] * j
            if k > 0:
                dp[i][j][k] += dp[i][j+1][k-1] * k
            dp[i][j][k] /= num

print(dp[cnt[0]][cnt[1]][cnt[2]])
### BUGGY CODE ###

h,w = list(map(int, input().split()))
b = [input() + '#' for _ in range(h)]
b.append('#' * (w + 1))
ans = [[0]*w for _ in range(h)]

for r in range(h):
    c = 0
    while c < w:
        if b[r][c] == '#':
            c += 1
        else:
            st = c
            while b[r][c] == '.':
                c += 1
            for i in range(st, c):
                ans[r][i] += (c - st)

for c in range(w):
    r = 0
    while r < h:
        if b[r][c] == '#':
            r += 1
        else:
            st = r
            while b[r][c] == '.':
                r += 1
            for i in range(st, r):
                ans[i][c] += (r - st)

import itertools
print(max(itertools.chain.from_iterable(ans))-1)


### FIXED CODE ###

h,w = list(map(int, input().split()))
b = [input() + '#' for _ in range(h)]
b.append('#' * (w + 1))
ans = [[0]*w for _ in range(h)]

for r in range(h):
    c = 0
    while c < w:
        if b[r][c] == '#':
            c += 1
        else:
            st = c
            while b[r][c] == '.':
                c += 1
            for i in range(st, c):
                ans[r][i] += (c - st)

for c in range(w):
    r = 0
    while r < h:
        if b[r][c] == '#':
            r += 1
        else:
            st = r
            while b[r][c] == '.':
                r += 1
            for i in range(st, r):
                ans[i][c] += (r - st)

import itertools
print(max(itertools.chain.from_iterable(ans))-1)
### BUGGY CODE ###

N=int(input())
a=[]
for i in range(N):
  a.append(input())
b=list(set(a))
c=list(map(lambda x:a.count(x),b))
d=int(c.count(max(c)))
e=[]
for k in range(d):
  e.append(b[c.index(max(c))])
  c[c.index(max(c))]=0
for l in range(len(e)):
  print(min(e))
  e.remove(min(e))

### FIXED CODE ###

N=int(input())
a=[]
for i in range(N):
  a.append(input())
b={}
for j in range(len(a)):
  if a[j] in b:
    b[a[j]]+=1
  else:
    b[a[j]]=1
max_b=max(b.values())
c=[]
for k,l in b.items():
  if l==max_b:
    c.append(k)
c.sort()
for m in c:
  print(m)
### BUGGY CODE ###

import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from heapq import heapify, heappop, heappush

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M = MAP()
L = [LIST() for i in range(M)]
graph = defaultdict(list)
for a, b in L:
    graph[a-1].append(b-1)
ans = 0
dist = [0] * N

for i in range(N):
    q = [i]
    while q:
        a = q.pop()
        for node in graph[a]:
            if dist[a] + 1 > dist[node]:
                dist[node] = dist[a] + 1
                if ans < dist[node]:
                    ans = dist[node]
                q.append(node)
    # if ans < max(dist):
    #     ans = max(dist)
print(ans)


### FIXED CODE ###

import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from heapq import heapify, heappop, heappush

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M = MAP()
gout = [[] for i in range(N)]
deg = [0] * N

for i in range(M):
    x, y = MAP()
    gout[x-1].append(y-1)
    deg[y-1] += 1
# only no_children 
topo = [v for v in range(N) if deg[v] == 0]
path_len = [0] * N
ans = 0
q = deque(topo)
# 子を持たない子スタート
while q:
    v = q.popleft()
    for t in gout[v]:
        # 親の子，vのカウントを減らす
        deg[t] -= 1
        # それでそれ以外の子がいなくなったら，
        # トポロジカルソートではスタックに積む
        if deg[t] == 0:
            q.append(t)
            path_len[t] = path_len[v] + 1
            ans = path_len[t]
print(ans)
### BUGGY CODE ###

n,m = list(map(int, input().split()))
x = []
for i in range(m):
  x.append(list(map(str,input().split())))
  
qu = []
count = 0
AC,WA = 0,0
for i in x:
  qu.append(i[0])
  

qu_set = list(set(qu))
for i in qu_set:
  x_target = [j for j in x if j[0] == i]
  
  #ACがあるかどうか、あった場合そのインデックス
  if [i,"AC"] in x:
    index = x_target.index([i,"AC"])
    WA += index
    AC += 1
  else:
    pass
  
print(AC, WA)

### FIXED CODE ###

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

ac = [0]*n
wa = [0]*(n+1)
pena = 0

for i in range(m):
  ques, state = input().split()
  ques = int(ques)-1
  
  if (state=="AC") and (ac[ques]==0):
    ac[ques] = 1
    pena += wa[ques]
  elif (state=="WA") and (ac[ques]==0):
    wa[ques] += 1
    
print(sum(ac), pena)
### BUGGY CODE ###

import sys
import numpy as np
# input処理を高速化する
input = sys.stdin.readline

L=int(input())
div =0.001
ranges =np.arange(0.001,L+1,0.001)

V=0
for x in ranges:
    z=L-2*x
    V=max(V,x*x*z)

print(V)


# for x in np.arange(1,10+1,0.1):
#     for y in np.arange(1,10+1-x,0.1):
#         print(x,y)

### FIXED CODE ###

import sys
import numpy as np
# input処理を高速化する
input = sys.stdin.readline

L=int(input())

#forループではない
# div =0.001
# ranges =np.arange(0.001,L+1,0.01)
# V=0
# for x in ranges:
#     z=L-2*x
#     V=max(V,x*x*z)

# print(V)
#相加相乗平均を用いる
print((L/3)**3)
### BUGGY CODE ###

s = input()[::-1]
length = len(s)
a = []
d = []
for i in range(length):
    a.append(int(s[i]) * pow(10, i) % 2019)
d.append(a[0])
for i in range(length-1):
    d.append((d[i] + a[i+1]) % 2019)
print(sum(d[i] == d[j] for i in range(length-1) for j in range(i+1, length)) + d.count(0))

### FIXED CODE ###

import numpy as np

s = input()[::-1]
length = len(s)
a = np.zeros(length, dtype=int)
d = np.zeros(length, dtype=int)
ans = np.zeros(2019, dtype=int)
x = 10

a[0] = int(s[0])
d[0] = a[0]
ans[d[0]] += 1

for i in range(1, length):
    a[i] = int(s[i]) * x % 2019
    d[i] = (d[i-1] + a[i]) % 2019
    ans[d[i]] += 1
    x = x * 10 % 2019

ans_c = ans[np.nonzero(ans)]

print(int(sum([ans_c[i] * (ans_c[i]-1) for i in range(ans_c.shape[0])]) / 2) + ans[0])
### BUGGY CODE ###

def isok(t):
    cnt = 0
    for i in range(n):
        cnt += max(a[i] - t // f[i], 0)
        if cnt > k:
            return False
    return True 

n,k = map(int,input().split())
a = list(map(int,input().split()))
f = list(map(int,input().split()))
a.sort(reverse = 1)
f.sort()
ok = a[0] * f[-1]
ng = -1
bool = True
while abs(ok - ng) > 1:
    mid = (ok + ng) // 2
    if isok(mid):
        ok = mid
    else:
        ng = mid
    #print(ng,mid,ok)
print(ok)


### FIXED CODE ###

def isok(t):
    cnt = 0
    for i in range(n):
        cnt += max(a[i] - t // f[i], 0)
        if cnt > k:
            return False
    return True 

n,k = map(int,input().split())
a = list(map(int,input().split()))
f = list(map(int,input().split()))
a.sort(reverse = 1)
f.sort()
ok = a[0] * f[-1]
ng = -1
bool = True
while abs(ok - ng) > 1:
    mid = (ok + ng) // 2
    if isok(mid):
        ok = mid
    else:
        ng = mid
    #print(ng,mid,ok)
print(ok)
### BUGGY CODE ###

from bisect import bisect_left as bl
def main():
    N,K = map(int,input().split())
    A = list(map(int,input().split()))
    A.sort()
    if K > max(A):
        print("IMPOSSIBLE")
        exit()
    if K in A:
        print("POSSIBLE")
        exit()
    for a in A:
        if a-K in A:
            print("POSSIBLE")
            exit()
        elif K-a in A:
            print("POSSIBLE")
            exit()
    B = list(map(lambda x:x%2,A))
    B = set(B)
    flag = 0
    C = [A[i+1]-A[i] for i in range(N-1)]
    C = set(C)
    D = set(A)
    if C-D:
        flag = 1
    if len(B) == 2 and flag:
        print("POSSIBLE")
        exit()
    print("IMPOSSIBLE")
    

if __name__ == "__main__":
    main()

### FIXED CODE ###

def main():
    N,K = map(int,input().split())
    A = list(map(int,input().split()))
    A.sort()
    if K > max(A):
        print("IMPOSSIBLE")
        exit()
    if K in A:
        print("POSSIBLE")
        exit()

    E = list(map(lambda x:abs(x-K),A))
    E = set(E)
    C = [A[i+1]-A[i] for i in range(N-1)]
    C = set(C)
    D = set(A)
    if E&D:
        print("POSSIBLE")
        exit()

    print("IMPOSSIBLE")
    

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

k,s = map(int,input().split())

ans = 0
for x in range(k+1):
    for y in range(k+1):
        for z in range(k+1):
            if x + y + z == s:
                ans += 1

print(ans)


### FIXED CODE ###

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

K, S = map(int, raw_input().split())
cnt = 0
for i in range(0, K+1):
	if S - i <= 2 * K:
		for j in range(0, K+1):
			if S - i - j <= K:
				for k in range(0, K+1):
					if i + j + k == S:
						cnt += 1
						break

print cnt

### FIXED CODE ###

K, S = map(int, raw_input().split())
cnt = 0
for i in range(0, K+1):
	if S - i <= 2*K:
		for j in range(0, K+1):
			if 0 <= S - i - j and S - i - j <= K:
				cnt+=1
print cnt
### BUGGY CODE ###

import sys
input = sys.stdin.readline
n,q = map(int, input().split())
tree = [[] for _ in range(n)]
for _ in range(n-1):
    a,b = map(int, input().split())
    tree[a-1].append(b)
    tree[b-1].append(a)
px = [ list(map(int,input().split())) for _ in range(q) ]
# print(tree)
# print(px)
c = [0]*n
for i in range(len(px)):
    c[px[i][0]-1] += px[i][1]
# print(c)
# for i in range(1,n):
#     c[i] += c[min(tree[i])-1]
visited = [0]*n
visited[0] = 1
check = sum(visited)
while check!=n:
    for i in range(1,n):
        for j in range(len(tree[i])):
            node_tmp = tree[i][j]
            if visited[node_tmp-1]==1 and visited[i]==0:
                c[i] += c[node_tmp-1]
                visited[i] = 1
            else:
                pass
    check = sum(visited)
print(" ".join(map(str,c)))

### FIXED CODE ###

import sys
input = sys.stdin.readline
n,q = map(int, input().split())
tree = [[] for _ in range(n)]
for _ in range(n-1):
    a,b = map(int, input().split())
    tree[a-1].append(b)
    tree[b-1].append(a)
# px = [ list(map(int,input().split())) for _ in range(q) ]
c = [0]*n
# for i in range(len(px)):
for _ in range(q):
    p,x = map(int,input().split())
    c[p-1] += x  
visited = [0]*n
cnd = [1]   # current_node
while len(cnd)>0:
    nnd = []
    for j in cnd:
        visited[j-1]=1
        ko = tree[j-1]
        for k in ko:
            if visited[k-1]==0:
                c[k-1] += c[j-1]
                nnd.append(k)
    cnd = nnd
print(" ".join(map(str,c)))
### BUGGY CODE ###

def xgcd(a, b):
    x0, y0, x1, y1 = 1, 0, 0, 1
    while b != 0:
        q, a, b = a // b, b, a % b
        x0, x1 = x1, x0 - q * x1
        y0, y1 = y1, y0 - q * y1
    return a, x0, y0
def modinv(a, m):
    g, x, y = xgcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m
s=list(input())
mod=10**9+7
K=modinv(10,13)
U=[[0 for i in range(10) ]for k in range(13)]
for i in range(13):
    for j in range(10):
        U[i][j]=((i-j)*K)%13

dp=[[0 for k in range(13)] for i in range(len(s))]
#dp[i][j]=初めのindex=i番目まで見たときに、あまりがjになるような方法の総数
num=s[0]
if s[0]=="?":
    for i in range(10):
        dp[0][i]=1
else:
    number=int(s[0])
    dp[0][number]=1

for i in range(1,len(s)):
    if s[i]=="?":
        for k in range(13):
            for j in range(10):
                dp[i][k]+=dp[i-1][U[k][j]]
        dp[i][k]=dp[i][k]%mod
    else:
        number=int(s[i])
        for k in range(13):
            dp[i][k]=dp[i-1][U[k][number]]%mod
print(dp[len(s)-1][5]%mod)


### FIXED CODE ###

def xgcd(a, b):
    x0, y0, x1, y1 = 1, 0, 0, 1
    while b != 0:
        q, a, b = a // b, b, a % b
        x0, x1 = x1, x0 - q * x1
        y0, y1 = y1, y0 - q * y1
    return a, x0, y0
def modinv(a, m):
    g, x, y = xgcd(a, m)
    return x % m
def main():
    s=list(input())
    mod=10**9+7
    K=modinv(10,13)
    U=[[0 for i in range(10) ]for k in range(13)]
    for i in range(13):
        for j in range(10):
            U[i][j]=((i-j)*K)%13

    dp=[[0 for k in range(13)] for i in range(len(s))]
    #dp[i][j]=初めのindex=i番目まで見たときに、あまりがjになるような方法の総数
    num=s[0]
    if s[0]=="?":
        for i in range(10):
            dp[0][i]=1
    else:
        number=int(s[0])
        dp[0][number]=1

    for i in range(1,len(s)):
        for k in range(13):
            if s[i]=="?":
                for j in range(10):
                    dp[i][k]+=dp[i-1][U[k][j]]%mod
            else:
                number=int(s[i])
                dp[i][k]=dp[i-1][U[k][number]]%mod
    print(dp[len(s)-1][5]%mod)
if __name__ == "__main__":
    main()