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

def sol():
    h,w,d=map(int,input().split())
    a=[[int(i) for i in input().split()] for i in range(h)]
    t,ans={},{}
    for i in range(h):
        for j in range(w):
            t[a[i][j]]=(i,j)
    for i in t:
        o,p=t[i]
        if i+d in t: ans[i]=abs(o-t[i+d][0])+abs(p-t[i+d][1])
    q=int(input())
    for i in range(q):
        chk=0
        l,r=map(int,input().split())
        for j in range(300*300):
            if l==r: break
            chk+=ans[l]
            l+=d
        print(chk)

if __name__=="__main__":
    sol()


### FIXED CODE ###

def sol():
    h,w,d=map(int,input().split())
    a=[[int(i) for i in input().split()] for i in range(h)]
    t={}
    for i in range(h):
        for j in range(w):
            t[a[i][j]]=(i,j)
    ans=[0]*(h*w+1)
    for i in range(h*w,d,-1):
        o,p=t[i]
        ans[i-d]=ans[i]+abs(o-t[i-d][0])+abs(p-t[i-d][1])
    q=int(input())
    for i in range(q):
        l,r=map(int,input().split())
        print(ans[l]-ans[r])

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

import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=998244353
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n,p=LI()
  s=S()

  ans=0
  if p==2 or p==5:
    for i,x in enumerate(s):
      if int(x)%p==0:
        ans+=i+1
    return ans

  _s=list(s)
  _s.reverse()

  a=[]
  i=1
  for x in _s:
    b=(i*int(x))%p
    a.append(b)
    i*=10

  b=[0]*p
  b[a[0]%p]=1
  for i in range(n-1):
    a[i+1]+=a[i]
    a[i+1]%=p
    b[a[i+1]]+=1

  for i,x in enumerate(b):
    if i==0:
      ans+=x
    if x>1:
      ans+=x*(x-1)//2

  return ans

# main()
print(main())


### FIXED CODE ###

import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=998244353
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n,p=LI()
  s=S()

  ans=0
  if p==2 or p==5:
    for i,x in enumerate(s):
      if int(x)%p==0:
        ans+=i+1
    return ans

  _s=list(s)
  _s.reverse()

  a=[]
  i=1
  for x in _s:
    b=(i*int(x))%p
    a.append(b)
    i*=10
    i%=p

  b=[0]*p
  b[a[0]%p]=1
  for i in range(n-1):
    a[i+1]+=a[i]
    a[i+1]%=p
    b[a[i+1]]+=1

  for i,x in enumerate(b):
    if i==0:
      ans+=x
    if x>1:
      ans+=x*(x-1)//2

  return ans

# main()
print(main())
### BUGGY CODE ###

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

S = input()
Q = int(input())

input_val = []
for i in range(Q):
  q = input().split(" ")
  input_val.append(q)
  
#print(input_val)
output = ""
for q in input_val:
  if len(q)==1:
    #print("T=1, S=",S)
    # T=1のときは文字列を反転する
    S = S[::-1]
    #print(S)
  if len(q)==3:
    #print("T=2, S=",S)
    # T=2のときは
    # F=1なら先頭に文字列Cを追加
    if int(q[1])==1:
      #print("F=1, S:",S,"q[2]:",q[2])
      S = q[2] + S 
      #print(S)
    # F=2なら最後に文字列を追加
    if int(q[1])==2:
      #print("F=2, S:",S,"q[2]:",q[2])
      S = S + q[2]
      #print(S)
  #print(q)
  
print(S)

### FIXED CODE ###

# -*- coding: utf-8 -*-
import sys
from collections import deque

S = input()
Q = int(input())
rev_flg = False

output = deque()
output.append(S)

for i in range(Q):
  q = input().split(" ")
  if len(q)==1:
    # T=1のときは文字列を反転する
    rev_flg = not(rev_flg)
    # print(rev_flg)
  if len(q)==3:
    # print("T=2, S=",S)
    # T=2のときは
    # F=1なら先頭に文字列Cを追加
    if int(q[1])==1:
      if rev_flg==False:
        output.appendleft(q[2])
      else:
        output.append(q[2])
    # F=2なら最後に文字列を追加
    if int(q[1])==2:
      if rev_flg==False:
        # S = S + q[2]
        output.append(q[2])
      else:
        # S = q[2] + S
        output.appendleft(q[2])
  
output_s = "".join(list(output))

if rev_flg==True:
  print(output_s[::-1])
  #print(S[::-1])
else:
  #print(S)
  print(output_s)
### BUGGY CODE ###

from collections import deque
E = lambda x: (x+1)*(x/2)/x
N, K = map(int, input().split())
sums = deque([0]*K)
ans = 0
for pi in map(int, input().split()):
  sums.popleft(); sums.append(E(pi))
  ans = max(ans, sum(sums))
print(ans)

### FIXED CODE ###

from itertools import accumulate
N, K = map(int, input().split())
ans = [0] + list(accumulate(map(lambda x: (int(x)+1)/2., input().split())))
print(max([y-x for x,y in zip(ans, ans[K:])]))
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**6)

N,M=map( int, raw_input().split() )
S="z"+raw_input()
num=[ [ 0 for i in range(2) ] for j in range(N+1) ] 

nl= [ [] for j in range(N+1) ] 


deleted=[ 0 for j in range(N+1) ] 

for i in range(M):
	a,b=map( int, raw_input().split() )
	if not b in nl[a]:
		nl[a].append(b)
		nl[b].append(a)
		if S[b]=="A":  num[a][0]+=1
		elif S[b]=="B":  num[a][1]+=1
		if S[a]=="A":  num[b][0]+=1
		elif S[a]=="B":  num[b][1]+=1


def delete(x):
	if deleted[x]==1: return
	if num[x][0]==0 or num[x][1]==0:

		deleted[x]=1
		for u in nl[x]:
			if deleted[u]==0:
				if S[x]=="A": num[u][0]-=1						
				elif S[x]=="B": num[u][1]-=1
			
			if ( num[u][0]==0 or num[u][1]==0 ) and deleted[u]==0:
				delete(u)


for i in range(1,N+1):
	delete(i)


				

if sum(deleted[1:])==N:
	print "No"
else:
	print "Yes"



### FIXED CODE ###

from heapq  import heappush, heappop

N,M=map( int, raw_input().split() )
S="z"+raw_input()
num=[ [ 0 for i in range(2) ] for j in range(N+1) ] 

nl= [ [] for j in range(N+1) ] 

deleted=[ 0 for j in range(N+1) ] 

for i in range(M):
	a,b=map( int, raw_input().split() )
	if not b in nl[a]:
		nl[a].append(b)
		nl[b].append(a)
		if S[b]=="A":  num[a][0]+=1
		elif S[b]=="B":  num[a][1]+=1
		if S[a]=="A":  num[b][0]+=1
		elif S[a]=="B":  num[b][1]+=1

hq=[]

for i in range(1,N+1):
	if num[i][0]==0 or num[i][1]==0:
		heappush(hq,i)



while hq:
	x=heappop(hq)
	if deleted[x]==1: continue
	if num[x][0]==0 or num[x][1]==0:

		deleted[x]=1
		for u in nl[x]:
			if deleted[u]==0:
				if S[x]=="A": num[u][0]-=1						
				elif S[x]=="B": num[u][1]-=1
			
		#	print "x,u,num:::",x,u,num
			if ( num[u][0]==0 or num[u][1]==0 ) and deleted[u]==0:
				heappush(hq,u)
			#	print "x,u,hq:::",x,u,hq

				

	

#print "num:::",num
#print "deleted:::",deleted
#print "nl:::",nl

if sum(deleted[1:])==N:
	print "No"
else:
	print "Yes"
### BUGGY CODE ###

n,k=map(int,input().split())
h=list(map(int,input().split()))
c=[0]*n
for i in range(1,n):
    x=h[i]
    c[i]=min([c[j]+abs(x-h[j]) for j in range(max(0,i-k),i)])
print(c[n-1])


### FIXED CODE ###

n, k = map(int, input().split())
h = list(map(int, input().split()))
c = [0] * n
for i in range(1, n):
    x=h[i]
    c[i] = min([c[j]+abs(x-h[j]) for j in range(max(0, i-k), i)])
print(c[n-1])
### BUGGY CODE ###

import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N = I()
    A = LI()
    #  print(N, A)


    # 余りを活用する
    A.sort(reverse=True)
    #  print(A)
    while len(A) > 1:
        A[0] = A[0] % A[1]
        if A[0] == 0:
            del A[0]
        A.sort(reverse=True)

    print(A[0])

main()


### FIXED CODE ###

import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools
import numpy as np

sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    N = I()
    A = LI()
    #  print(N, A)


    # 余りを活用する
    A = list(set(A))
    A.sort(reverse=True)
    if A[-1] == 0:
        del A[-1]
    #  print(A)
    while len(A) > 1:
        #  A[0] = A[0] % A[1]
        A = [a % A[idx+1] if idx < len(A) - 1 else a for idx, a in enumerate(A)]
        A = list(set(A))
        A.sort(reverse=True)
        if A[-1] == 0:
            del A[-1]

        #  if A[0] == 0:
        #      del A[0]

    print(A[0])

main()
### BUGGY CODE ###

import sys

#+++++
		
def main():
	n,m = map(int, input().split())
	if n == 1:
		return m
	
	ret = 0
	for i in range(1,m):
		a = m // i
		b = m % i
		if b == 0 and n*i <= m:
			ret = i
			
		if n*i > m:
			return ret
			
		if ret == 1 and i*i > m:
			return 1
			
	print(ret)
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

### FIXED CODE ###

import sys
import math

#+++++


		
def main():
	n,m = map(int, input().split())
	if m % n ==0:
		return m // n
		
	ll=1
	for i in range(1, int(math.sqrt(m))+1):
		#pa((i,ll))
		if m % i == 0:
			if i >= n:
				ll=max(ll, m // i)
			if m // i >= n:
				ll=max(ll, i)
	return ll
				

#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)
### BUGGY CODE ###

n = int(input())
a = [int(i) for i in input().split()]

def lcm(x, y):
    if x > y:
        big = x
    else:
        big = y

    while(True):
        if((big % x == 0) and (big % y == 0)):
            lcm = big
            break
        big += 1
    return lcm

ans = max(a)
for i in a:
    ans = lcm(ans, i)
    
print(ans)

### FIXED CODE ###

n = int(input())
a = [int(i) for i in input().split()]

def gcd(x, y):
    while(y):
        x, y = y, x%y
    return x

def lcm(x, y):
    lcm = (x*y)//gcd(x,y)
    return lcm

ans = 1
for i in a:
    ans = lcm(ans, i)
    
print(ans)
### BUGGY CODE ###

import sys
from collections import defaultdict
from queue import Queue

input = sys.stdin.readline
h, w = map(int, input().split())
matrix = defaultdict(lambda: -1)
queue = Queue()
for i in range(h):
    cells = list(input().rstrip("\n"))
    for j, cell in enumerate(cells):
        if cell == "#":
            matrix[str(i) + "_" + str(j)] = 0
            queue.put((i, j))
while not queue.empty():
    i, j = queue.get(block=False)
    for i_diff, j_diff in [(-1, 0), (0, -1), (0, 1), (1, 0)]:
        i_current = i + i_diff
        j_current = j + j_diff
        if (
            0 <= i_current < h
            and 0 <= j_current < w
            and matrix[str(i_current) + "_" + str(j_current)] == -1
        ):
            matrix[str(i_current) + "_" + str(j_current)] = (
                matrix[str(i) + "_" + str(j)] + 1
            )
            queue.put((i_current, j_current))

max_step = max(matrix.values())
print(max_step)

### FIXED CODE ###

import sys
from collections import deque

input = sys.stdin.readline
h, w = map(int, input().rstrip("\n").split())
matrix = [[-1 for j in range(w)] for i in range(h)]
queue = deque()
for i in range(h):
    cells = list(input().rstrip("\n"))
    for j, cell in enumerate(cells):
        if cell == "#":
            matrix[i][j] = 0
            queue.append((i, j))
while queue:
    i, j = queue.popleft()
    for i_diff, j_diff in [(-1, 0), (0, -1), (0, 1), (1, 0)]:
        i_current = i + i_diff
        j_current = j + j_diff
        if (
            0 <= i_current < h
            and 0 <= j_current < w
            and matrix[i_current][j_current] == -1
        ):
            matrix[i_current][j_current] = matrix[i][j] + 1
            queue.append((i_current, j_current))

max_step = max([max(row) for row in matrix])
print(max_step)
### BUGGY CODE ###

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

for i in range(n-1):
  if a[n-1-i]&1:
    b.add(n-i)
    for j in range(2, int((n-i)**0.5)+1):
      if (n-i)%j == 0:
        a[j-1] += 1
        if (n-i)//j != j:
          a[(n-i)//j -1] += 1
if a[0] != len(b)%2:
  b.add(1)
          
print(len(b))
if len(b)>0:
  print(*b)

### FIXED CODE ###

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

for i in range(n-1):
  if a[n-1-i]&1:
    b.add(n-i)
    for j in range(2, int((n-i)**0.5)+1):
      if (n-i)%j == 0:
        a[j-1] += 1
        if (n-i)//j != j:
          a[(n-i)//j -1] += 1
if a[0] != len(b)%2:
  b.add(1)
          
print(len(b))
if len(b)>0:
  print(*b)
### BUGGY CODE ###

n,m = map(int,input().split())
lst = [list(map(int,input().split())) for _ in range(m)]
lst.sort(key=lambda x:x[1])
res = []
for i in range(m):
    a,b = lst[i][0], lst[i][1]
    flg = False
    if i==0:
        res.append(b-1)
    else:
        for r in res:
            if a<=r<=b:
                flg=True
        if not flg:
            res.append(b-1)
print(len(res))

### FIXED CODE ###

n,m = map(int,input().split())
lst = [list(map(int,input().split())) for _ in range(m)]
lst.sort(key=lambda x:x[1])
res = []
for i in range(m):
    a,b = lst[i][0], lst[i][1]
    flg = False
    if i==0:
        res.append(b-1)
    else:
        for r in res:
            if a<=r<=b:
                flg=True
        if not flg:
            res.append(b-1)
print(len(res))
### BUGGY CODE ###

import sys,fractions
sys.setrecursionlimit(10**5)
def input():
    return sys.stdin.readline()[:-1]

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

u = 10**9+7

from functools import reduce

def gcd_list(numbers):
    return reduce(fractions.gcd, numbers)

def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)

G = l[0]
for i in range(N-1,0,-1):
    G = fractions.gcd(G,l[i])
    if G==1:
        break

def division_binary_shift(a, b):
    """
    a // b

    :param a: dividend
    :param b: divisor
    :return: quotient
    """
    if a < b:
        return 0
    if b == 0:
        raise ZeroDivisionError

    q = 0
    sq = 1
    ori_b = b
    while a >= b:
        b <<= 1
        if a >= b:
            sq <<= 1
        else:
            b >>= 1
            a -= b
            q += sq
            sq = 1
            b = ori_b

    return q

gcd = G
L = [l[i]//gcd for i in range(N)]
lcm = lcm_list(L)

# print(lcm,gcd,'aaa')
ANS = 0
for i in range(N):
    elm = L[i]
    ANS += division_binary_shift(lcm,elm)
    ANS %= u
print(ANS)

### FIXED CODE ###

import sys
from fractions import gcd
sys.setrecursionlimit(10**5)
def input():
    return sys.stdin.readline()[:-1]

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

u = 10**9+7

lcm = 1
s = 0
for i in range(N):
    k = l[i]
    g = gcd(k,lcm)
    t = k//g
    lcm = lcm*t
    s = s*t + lcm//k
print(s%u)
### BUGGY CODE ###

import itertools
X, Y, Z, K = map(int, input().split())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]
C = [int(i) for i in input().split()]

D = []
for a, b, c in itertools.product(A, B, C):
    d = a + b + c
    D.append(d)
    
D.sort(reverse = True)
for d in D[:K]:
    print(d)

### FIXED CODE ###

X, Y, Z, K = map(int, input().split())
A = sorted([int(i) for i in input().split()], reverse = True)
B = sorted([int(i) for i in input().split()], reverse = True)
C = sorted([int(i) for i in input().split()], reverse = True)

D = []
for i in range(X):
    for j in range(Y):
        if (i + 1) * (j + 1) > K:
            break
        for k in range(Z):
            if (i + 1) * (j + 1) * (k + 1) > K:
                break
            D.append(A[i] + B[j] + C[k])
            #print(A[i] + B[j] + C[k], i, j, k)
            
D.sort(reverse = True)
for d in D[:K]:
    print(d)
### BUGGY CODE ###

def main():
	L = input()
	n = len(L)
	MOD = 10**9+7
	if L == "0":
		print(1)
		return

	num_1 = 0
	pos = []
	for i in range(n-1, -1, -1):
		if L[i] == "1":
			num_1 += 1
			pos.append(n-i-1)
	pos.reverse()
	ans = 2**(num_1)%MOD

	def my_pow(x, n):
		if n == 0:
			return 1
		if n%2 == 0:
			return my_pow(x*x, n//2)
		return x * my_pow(x, n-1)

	for i, p in enumerate(pos):
		cur = (1<<i)%MOD
		cur *= my_pow(3, p)%MOD
		cur %= MOD
		ans += cur
		ans %= MOD

	print(ans)


if __name__ == '__main__':
	main()

### FIXED CODE ###

MOD = 10**9+7

memo = dict()
memo[0] = 1
def pow3(n):
	if n in memo:
		return memo[n]
	if n%2 == 0:
		tmp = pow3(n//2)
		memo[n] = tmp*tmp%MOD
		return memo[n]
	memo[n] = 3 * pow3(n-1)%MOD
	return memo[n]

def cul(i, p):
	cur = (1<<i)%MOD
	cur *= pow3(p)
	return cur % MOD

def solve(L):
	n = len(L)
	if L == "0":
		return 1
	if not "0" in L:
		return pow3(n)

	num_1 = 0
	pos = []
	for i in range(n):
		if L[i] == "1":
			num_1 += 1
			pos.append(n-i-1)

	ans = (2**num_1)%MOD
	for i, p in enumerate(pos):
		ans += cul(i, p)
		ans %= MOD

	return ans

def main():
	L = input()
	print(solve(L))


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

from collections import defaultdict
import sys
room_num,root_num = map(int,input().split())
#room_dis_dic = dict(zip(range(1,room_num+1),[0]+[sys.maxsize]*(room_num-1)))
connect_dic = defaultdict(set)
connected_list = [1]
next_connect_dic = {}
for _ in range(root_num):
    a,b = map(int,input().split())
    connect_dic[a].add(b)
    connect_dic[b].add(a)
    
for room_i in connected_list:
    #print(room_i)
    next_room_set = connect_dic[room_i]-next_connect_dic.keys()
    connected_list.extend(list(next_room_set))
    for next_room_i in next_room_set:
        next_connect_dic[next_room_i] = room_i

if len(set(range(2,room_num+1))-next_connect_dic.keys())!=0:
    print("No")
else:
    print("Yes")
    for i in range(2,room_num+1):
        print(next_connect_dic[i])

### FIXED CODE ###

from collections import defaultdict
import sys
room_num,root_num = map(int,input().split())
#room_dis_dic = dict(zip(range(1,room_num+1),[0]+[sys.maxsize]*(room_num-1)))
connect_dic = defaultdict(set)
connected_list = [1]
next_connect_dic = {}
for _ in range(root_num):
    a,b = map(int,input().split())
    connect_dic[a].add(b)
    connect_dic[b].add(a)
    
for room_i in connected_list:
    #print(room_i)
    next_room_set = {connect_to for connect_to in connect_dic[room_i] if connect_to not in next_connect_dic.keys()}
    connected_list.extend(list(next_room_set))
    for next_room_i in next_room_set:
        next_connect_dic[next_room_i] = room_i

if len(set(range(2,room_num+1))-next_connect_dic.keys())!=0:
    print("No")
else:
    print("Yes")
    for i in range(2,room_num+1):
        print(next_connect_dic[i])
### BUGGY CODE ###

N, M = map(int,input().split()) # 複数の数字を変数に格納
List = [list(map(int,input().split())) for i in range(N)] # [[1,2],[3,4],[5,6]]

List.sort(key=lambda x: x[0])
List_S = []
 
result = 0
p = 0
 
for i in range(1,M+1):
    add = 0
    for j in range(p,N):
        if List[j][0] <= i:
            List_S.append(List[j][1])
            p += 1
            add = 1
        else:
            break
    if len(List_S) != 0:
        if add == 1:
            List_S.sort()
        result += List_S.pop()
 
print(result)

### FIXED CODE ###

from operator import itemgetter
import sys
input = sys.stdin.readline

N, M = map(int,input().split()) # 複数の数字を変数に格納
List = [list(map(int,input().split())) for i in range(N)] # [[1,2],[3,4],[5,6]]

List.sort(key=itemgetter(0))
List_S = [0]
 
result = 0
p = 0

for i in range(1, M+1):
    add = 0
    add_list = []
    while p < N and List[p][0] == i:
        if List_S[len(List_S)-1] < List[p][1]:            
            List_S.append(List[p][1])
        else:
            add_list.append(List[p][1])
            add += 1
        p += 1
            
    if len(List_S) != 1:
        result += List_S.pop()
        if add > 0:
            List_S.extend(add_list)
            List_S.sort()
 
print(result)
### BUGGY CODE ###

def dfs(s, t, links):
    visited = set()
    q = [(s, 0)]
    while q:
        v, used = q.pop()
        if v == t:
            return used
        visited.add(v)
        for l, u in links[v]:
            if u in visited:
                continue
            new_used = used | (1 << l)
            q.append((u, new_used))


n = int(input())
links = [set() for _ in range(n)]
for i in range(n - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    links[a].add((i, b))
    links[b].add((i, a))
conditions = []
m = int(input())
for i in range(m):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    conditions.append(dfs(u, v, links))

ans = 0
for i in range(1 << m):
    cnd_cnt = bin(i).count('1')
    bit = 0
    k = i
    while k:
        b = k & -k
        j = b.bit_length() - 1
        bit |= conditions[j]
        k ^= b
    free_link_cnt = n - 1 - bin(bit).count('1')
    val = 2 ** free_link_cnt
    if cnd_cnt % 2:
        ans -= val
    else:
        ans += val
print(ans)


### FIXED CODE ###

def dfs(s, t, links):
    visited = set()
    q = [(s, 0)]
    while q:
        v, used = q.pop()
        if v == t:
            return used
        visited.add(v)
        for lb, u in links[v]:
            if u in visited:
                continue
            q.append((u, used | lb))


n = int(input())
links = [set() for _ in range(n)]
for i in range(n - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    lb = 1 << i
    links[a].add((lb, b))
    links[b].add((lb, a))
conditions = []
m = int(input())
for i in range(m):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    conditions.append(dfs(u, v, links))

ans = 0
for i in range(1 << m):
    cnd_cnt = bin(i).count('1')
    bit = 0
    k = i
    while k:
        b = k & -k
        j = b.bit_length() - 1
        bit |= conditions[j]
        k ^= b
    free_link_cnt = n - 1 - bin(bit).count('1')
    val = 2 ** free_link_cnt
    if cnd_cnt % 2:
        ans -= val
    else:
        ans += val
print(ans)
### BUGGY CODE ###

import numpy as np

N, K = map(int, input().split())
x = np.array(list(map(int, input().split())))

m = 0

for i in range(N-K+1):
	ans = 0
	for j in range(i, i+K):
		ans += np.mean(np.array(range(1, x[j]+1))) 

	if ans > m:
		m = ans

print(m)

### FIXED CODE ###

import numpy as np

N, K = map(int, input().split())
x = np.array(list(map(float, input().split())))

for i in range(N):
	x[i] = (1 + x[i]) / 2

data = np.sum(x[:K])
ans = data

for i in range(N-K):
	data = data + x[i+K] - x[i]
	if data > ans:
		ans = data

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

p = str(input())
s = list(p)
k = int(input())

zisyo = []
for i in range(len(s)):
    count = 0
    st = s[i]
    zisyo.append(st)
    while count <= len(s):
        count = count + 1
        try:
            st = st + s[i + count]
            zisyo.append(st)
        except:
            pass
    
zisyosort = list(sorted(list(set(zisyo))))
print(zisyosort[k-1])

### FIXED CODE ###


s = str(input())
k = int(input())
kouho = [s]

for i in range(len(s)):
    for plus in range(k+1):
        st = s[i:i + plus]
        kouho.append(st)
so = list(sorted(set(kouho)))
if '' in so:
    so.remove('')
    
print(so[k-1])