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

from collections import defaultdict
import sys

sys.setrecursionlimit(10**6)

N, Q = map(int, input().split())
e = [[] for _ in range(N + 1)]
for i in range(N - 1):
    a, b = map(int, input().split())
    e[a].append(b)

q = defaultdict(int)
for i in range(Q):
    p, x = map(int, input().split())
    q[p] += x

seen = [False] * (N + 1)
ans = [0] * (N + 1)


def dfs(e, v, x):
    seen[v] = True
    ans[v] += x
    for next_v in e[v]:
        if seen[next_v]:
            continue
        else:
            dfs(e, next_v, x + q[next_v])


dfs(e, 1, q[1])
print(*ans[1:])


### FIXED CODE ###

from collections import defaultdict
import sys
input = sys.stdin.readline

sys.setrecursionlimit(10**6)

N, Q = map(int, input().split())
e = [[] for _ in range(N + 1)]
for i in range(N - 1):
    a, b = map(int, input().split())
    e[a].append(b)

q = defaultdict(int)
for i in range(Q):
    p, x = map(int, input().split())
    q[p] += x

seen = [False] * (N + 1)
ans = [0] * (N + 1)


def dfs(e, v, x):
    seen[v] = True
    ans[v] += x
    for next_v in e[v]:
        if seen[next_v]:
            continue
        else:
            dfs(e, next_v, x + q[next_v])


dfs(e, 1, q[1])
print(*ans[1:])
### BUGGY CODE ###

import sys
input = sys.stdin.readline

S=tuple(input().strip())
N=len(S)+1
x = [0]

for i in range(1,N):
    if S[i-1] == '<':
        x.append(x[i-1] + 1)
    else:
        x.append(0)
        for j in range(i):
            if x[i-1-j] == x[i-j]:
                x[i-1-j] += 1
            else:
                break

print(sum(x))


### FIXED CODE ###

import sys
input = sys.stdin.readline

S=tuple(input().strip())
N=len(S)+1
sets = []
count = 0

for c in S:
    d = 1 if c == '<' else -1
    if count * d < 0:
        sets.append(count)
        count = d
    else:
        count += d
sets.append(count)

sum = 0
for i in range(len(sets)):
    k=sets[i]
    if k > 0:
        sum += (k*(k+1))//2
    else:
        sum += (k*(k-1))//2
        if i > 0:
            sum -= min(sets[i-1], -k)

print(sum)
### BUGGY CODE ###

import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

R, C, K = rl()
I = {}
for i in range(K):
	r, c, v = rl()
	I[(r-1, c-1)] = v

#dist = [[[-float('inf')]*3 for _ in range(C)] for _ in range(R)]
dist = defaultdict(lambda: -float('inf'))
dist[(0, 0, 0, 0)] = 0
heap = []
heappush(heap, (-0, (0, 0, 0, 0)))
ans = 0
while heap:
	d, n = heappop(heap)
	d = -d
	r, c, m, f = n
	#print('rcm', r, c, m, d, f)
	if r == R-1 and c == C-1:
		#print(dist)
		if m < 3 and f == 0:
			if (r, c) in I:
				d += I[(r,c)]
		ans = max(ans, d)
		#break
		continue
	if dist[n] != d:
		continue
	for i, j, k in [[0, 1, m], [1, 0, 0]]:
		ni, nj = r+i, c+j
		if ni >= R or nj >= C: continue
		nn = (ni, nj, k, 0)
		if dist[nn] < d:
			dist[nn] = d
			heappush(heap, (-d, nn))
	if m < 3 and f == 0:
		if (r, c) in I:
			nn = (r, c, m+1, 1)
			nd = d + I[(r,c)]
			if dist[nn] < nd:
				dist[nn] = nd
				heappush(heap, (-nd, nn))
print(ans)


### FIXED CODE ###

import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)
 
R, C, K = rl()
I = [[0]*(C+2) for _ in range(R+2)]
for i in range(K):
	r, c, v = rl()
	I[r][c] = v
 
dp = [[0]*4 for _ in range(C+2)]
dp2 = [[0]*4 for _ in range(C+2)]
 
for i in range(R+1):
	for j in range(C+1):
		for m in range(4):
			ni, nj = i, j+1
			dp[nj][m] = max(dp[nj][m], dp[j][m])
			if m < 3:
				dp[nj][m+1] = max(dp[nj][m+1], dp[j][m]+I[ni][nj])
			ni, nj = i+1, j
			dp2[nj][0] = max(dp2[nj][0], dp[j][m])
			dp2[nj][1] = max(dp2[nj][1], dp[j][m]+I[ni][nj])
	dp = dp2
	dp2 = [[0]*4 for _ in range(C+2)]
ans = 0
for m in range(4):
	ans = max(ans, dp[C][m])
print(ans)
### BUGGY CODE ###

def prime(n):
    is_prime = [True] * (n + 1)
    is_prime[0] = False
    is_prime[1] = False
    for j in range(4, n+1, 2):
        is_prime[j] = False
    for i in range(3, int(n**0.5) + 1, 2):
        if not is_prime[i]:
            continue
        for j in range(i * 2, n + 1, i):
            is_prime[j] = False
    return [i for i in range(n + 1) if is_prime[i]]

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

def make_divisors2(n):
    divisors = set()
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.add(i)
            if i != n // i:
                divisors.add(n//i)
    return divisors

def main():
    n = int(input())
    a = [int(x) for x in input().split()]
    prime_list = prime(max(a))
    prime_count = dict()
    for value in prime_list:
        prime_count[value] = 0
        key = value
        for i in range(n):
            while a[i]%key == 0:
                key *= value
                prime_count[value] += 1
    
    ans = 0
    inf = pow(10, 9)+7
    
    for value in a:
        sub = 1
        for p in prime_list:
            k = prime_count[p]
            v = value
            while v%p == 0:
                v //= p
                k -= 1
            sub *= pow(p, k, inf)
            sub %= inf
        ans += sub
        ans %= inf
    print(ans)
    

if __name__ == "__main__":
    main()

### FIXED CODE ###

import sys
from collections import Counter

def prime_factorize(n):
    ans = []
    while not n%2:
        ans.append(2)
        n //= 2
    mod = 3
    while mod**2 <= n:
        if n%mod == 0:
            ans.append(mod)
            n //= mod
        else:
            mod += 2
    if n != 1:
        ans.append(n)
    counter = Counter(ans)
    return counter

def main():
    input = sys.stdin.readline
    mod = pow(10,9)+7
    n = int(input())
    a = [int(x) for x in input().split()]
    
    prime_list = dict()
    for i in range(n):
        primes = prime_factorize(a[i])
        for key, value in primes.items():
            if key in prime_list:
                if prime_list[key] < value:
                    prime_list[key] = value
            else:
                prime_list[key] = value
    
    L = 1
    for key, value in prime_list.items():
        L *= pow(key, value, mod)
        L %= mod
        
    ans = 0
    for i in range(n):
        ans += (L*pow(a[i], mod-2, mod))%mod
        ans %= mod
    
    print(ans)
            


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

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

if k==1 :
  ln=0
else:
  while 1:
    ln = n
    n = abs(n-k)
    if ln<=n:
      break
print(ln)

### FIXED CODE ###

n,k = map(int,input().split())
 
if k==1 :
  ln=0
elif k==0 :
  ln=n
elif n>=k:
  a = n%k
  n=a
  while 1:
    ln = n
    n = abs(a-k)
    if ln<=n:
      break
else:
  while 1:
    ln = n
    n = abs(n-k)
    if ln<=n:
      break
print(ln)
### BUGGY CODE ###

def main():
    s=s0=input()
    while True:
        i=s.find('01')
        if i>=0:
            s=s[:i]+s[i+2:]
            continue
        i=s.find('10')
        if i>=0:
            s=s[:i]+s[i+2:]
            continue
        break
    print(len(s0)-len(s))

main()

### FIXED CODE ###

def main():
    s=input()
    print(2*min(s.count('1'),s.count('0')))

main()
### BUGGY CODE ###

H, W = (int(i) for i in input().split())
#e = [[i for i in input().split()] for i in range(H)]
e = []
for x in range(H):
    e.append(list(input()))

maxcount = 1
for i in range(H):
    for j in range(W):
        #print("start", i, j)
        count = 1
        if e[i][j] == "#":
            continue
        for k in range(i+1, H):
            #print(e[k][j], k, j)
            if e[k][j] == "#":
                #print(k, j)
                break
            else:
                count +=1
        #print("1 ", count)
        for l in range(1, i+1):
            #print(e[i-l][j], i-l, j)
            if e[i-l][j] == "#":
                break
            else:
                count += 1
        #print("2 ", count)
        if count + W -1 < maxcount:
            continue
        for m in range(j+1, W):
            if e[i][m] == "#":
                break
            else:
                count +=1
        #print("3 ",count)
        for n in range(1, j+1):
            if e[i][j-n] == "#":
                break
            else:
                count +=1
        if maxcount < count:
            maxcount = count
        if maxcount == W+H:
            break
    else:
        continue
    break
print(maxcount)


### FIXED CODE ###

import sys
input = sys.stdin.readline

H, W = (int(i) for i in input().split())
#e = [[i for i in input().split()] for i in range(H)]
e = []
for x in range(H):
    e.append(list(input()))

L = [[0] * W for i in [1] * H]
R = [[0] * W for i in [1] * H]
D = [[0] * W for i in [1] * H]
U = [[0] * W for i in [1] * H]
totalmax = 0

for i in range(H):
    for j in range(W):
        if e[i][j] == ".":
            if j == 0:
                L[i][j] = 1
            else:
                L[i][j] = L[i][j-1] + 1
        if e[i][W-1-j] == ".":
            #print(i, W-1-j)
            if W-1-j == W-1:
                R[i][W-1-j] = 1
            else:
                R[i][W-1-j] = R[i][W-j] + 1
                #print(R[i][W-j-2])
            #print(R[i][W-j-1])
        if e[i][j] == ".":
            if i == 0:
                U[i][j] = 1
            else:
                U[i][j] = U[i-1][j] + 1
        if e[H-1-i][j] == ".":
            if H-1-i == H-1:
                D[H-1-i][j] = 1
            else:
                D[H-1-i][j] = D[H-i][j] + 1

for i in range(H):
    #print("")
    for j in range(W):
        totalmax = max(totalmax, L[i][j]+R[i][j]+D[i][j]+U[i][j]-3)
        #print(L[i][j],R[i][j], D[i][j], U[i][j], end="/")



print(totalmax)
### BUGGY CODE ###

N = int(input())
A = list(map(str, input().split()))
Q = int(input())
S = []
c = 0


for i in range(Q):
    B, C = map(str,input().split())
    if B in A:
        string = ",".join(A)
        string_new = string.replace(B,C)
        A =  string_new.split(",")


    S.append(sum(map((lambda x: int(x)), A)))



for s in S:
    print(s)

### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
S = []
c = 0
s = sum(A)
table = [0] * 100010
# A = pd.Series(A)
# for a in A:
#     print(a)

for i in A:
    table[i] += 1

for i in range(Q):
    B, C = map(int,input().split())
    # if B in A:
    # c = A.count(B)
    c = table[B]
    s += (C - B) * c
    table[C] += table[B]
    table[B] = 0
    # print(s)
        # print((C - B) * c) 
        # string = ",".join(A)
        # string_new = string.replace(B,C)
        # A =  string_new.split(",")
        # s = sum(map((lambda x: int(x)), A))
    S.append(s)

        # A.replace(B, C,c)
        # while B in A:
        #     A[A.index(B)] = C
    # for a in A:
    #     print(a)
    # else:
        # S.append(s)



for s in S:
    print(s)
### BUGGY CODE ###

# YouTube
def com(com_n, com_r):
    return fac[com_n] * inv[com_r] * inv[com_n - com_r] % md

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

# 準備
md = p
n_max = p-1
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
    k_fac_inv = k_fac_inv * i % md
    fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
    inv[i] = k_fac_inv
    k_fac_inv = k_fac_inv * i % md

b = [0] * p
for ai, ak in enumerate(a):
    if ak:
        b[0] = (b[0] + 1) % p
        s=1
        for bi in range(p-1,-1,-1):
            b[bi] = (b[bi] - s * com(p - 1, bi)) % p
            s=(-ai*s)%p
print(*b)


### FIXED CODE ###

# YouTube
def com(com_n, com_r):
    return fac[com_n] * inv[com_r] * inv[com_n - com_r] % md

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

# 準備
md = p
n_max = p-1
fac = [1]
inv = [1] * (n_max + 1)
k_fac_inv = 1
for i in range(1, n_max + 1):
    k_fac_inv = k_fac_inv * i % md
    fac.append(k_fac_inv)
k_fac_inv = pow(k_fac_inv, md - 2, md)
for i in range(n_max, 1, -1):
    inv[i] = k_fac_inv
    k_fac_inv = k_fac_inv * i % md

b = [0] * p
for ai, ak in enumerate(a):
    if ak:
        b[0] = (b[0] + 1) % p
        s=1
        for bi in range(p-1,-1,-1):
            b[bi] = (b[bi] - s * com(p - 1, bi)) % p
            s=(-ai*s)%p
print(*b)
### BUGGY CODE ###

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

# BFSで各点から到達可能な最も遠いところを探索する
# 1回探索はO(HW)なのでO(HHWW)
# BFSなのでdeque / queue使う・・・微妙に1つだけTLE残る

# 全ての地点から全ての地点への最短経路を求める

'''
3 5
...#.
.#.#.
.#...
'''


# from collections import deque
import queue

H, W = map(int, input().split())

data = [None] * H
for i in range(H):
    data[i] = input()


def judge(h, w, dist):
    if (h < 0) or (h >= H) or (w < 0) or (w >= W):
        return False
    if data[h][w] == '#' or dist[h][w] > -1:
        return False
    else:
        return True


def bfs(h, w):
    dist = [[-1] * W for i in range(H)]
    # q = deque()
    q = queue.Queue()

    max_dist = 0
    dist[h][w] = 0
    # q.append((h, w, 0))
    q.put((h, w, 0))

    # while len(q) > 0:
    while not q.empty():
        # h, w, val = q.popleft()
        h, w, val = q.get()
        dist[h][w] = val
        max_dist = max(max_dist, val)

        m = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        for dx, dy in m:
            h_new, w_new = h + dx, w + dy
            if judge(h_new, w_new, dist):
                q.put((h_new, w_new, val+1))

    return max_dist


ans = 0
for h in range(H):
    for w in range(W):
        if data[h][w] == '.':
            res = bfs(h, w)
            if ans < res:
                ans = res

print(ans)


### FIXED CODE ###

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

# BFSで各点から到達可能な最も遠いところを探索する
# 1回探索はO(HW)なのでO(HHWW)
# BFSなのでdeque / queue使う・・・微妙に1つだけTLE残る

# 全ての地点から全ての地点への最短経路を求める

'''
3 5
...#.
.#.#.
.#...
'''

import sys
from collections import deque

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

H, W = na()
# data = [ns() for _ in range(H)]

data = [list("#" * (W + 2))]
# 周りを'#'で埋めておく
for _ in range(H):
    data.append(["#"] + list(input()) + ["#"])
data += [list("#" * (W + 2))]


def bfs(h, w):
    dist = [[-1] * (W+2) for _ in range(H+2)]
    q = deque()

    max_dist = 0
    dist[h][w] = 0
    q.append((h, w, 0))

    # while len(q) > 0:
    while len(q) > 0:
        h, w, val = q.popleft()

        m = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        for dx, dy in m:
            h_new, w_new = h + dx, w + dy
            if data[h_new][w_new] == '.' and dist[h_new][w_new] == -1:
                q.append((h_new, w_new, val+1))
                dist[h_new][w_new] = val + 1
                max_dist = max(max_dist, val + 1)

    return max_dist


ans = 0
for h in range(H+2):
    for w in range(W+2):
        if data[h][w] == '.':
            res = bfs(h, w)
            if ans < res:
                ans = res

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

from bisect import bisect_right

def main():
    N, D, A = map(int, input().split())
    B = []

    for i in range(N):
        x, h = map(int, input().split())
        B.append((x,h))

    B.sort()
    X = [0] * N
    H = [0] * N
    for i in range(N):
        X[i], H[i] = B[i]
    ans = 0
    ok = [False] * N
    for i in range(N):
        if ok[i]:
            continue
        cnt = H[i] // A if H[i] % A == 0 else H[i] // A + 1
        ans += cnt
        ok[i] = True
        search_max = bisect_right(X, X[i] + 2 * D) - 1
        for j in range(min(i+1,N),min(search_max+1,N)):
            if ok[j]:
                continue
            H[j] -= cnt * A
            if H[j] <= 0:
                ok[j] = True
    
    print(ans)



if __name__ == "__main__":
    main()

### FIXED CODE ###

from bisect import bisect_right
import sys
input = sys.stdin.readline

def main():
    N, D, A = map(int, input().split())
    B = []

    for i in range(N):
        x, h = map(int, input().split())
        B.append((x,h))

    B.sort()
    X = [0] * N
    H = [0] * N
    for i in range(N):
        X[i], H[i] = B[i]
    ans = 0
    ok = [False] * N
    S = [0] * (N + 1)
    for i in range(N):
        if S[i] < H[i]:
            cnt = (H[i] - S[i]) // A if (H[i] - S[i]) % A == 0 else (H[i] - S[i]) // A + 1
            ans += cnt
            search_max = bisect_right(X, X[i] + 2 * D)
            S[i] += cnt * A
            S[search_max] -= cnt * A
        
        S[i+1] += S[i]

    print(ans)



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

#!/mnt/c/Users/moiki/bash/env/bin/python
from itertools import permutations
N,M = map(int, input().split())
cost = [0,2,5,5,4,5,6,3,7,6]
A = list(map(int, input().split()))

p = []
for a in A:
    p.append( (cost[a], a) )
costp = sorted(p)


costX = [ z[0] for z in costp]
A = [ z[1] for z in costp]

dp = [""] * (N+1)

for c,a in zip(costX,A):
    i = N 
    if i-c >= 0:
        dp[i-c] = str(a)



for i in range(N-1, 1, -1):
    if len(dp[i]) == 0:
        continue
    
    for c,a in zip(costX,A):
        for p in permutations( [dp[i], str(a)]):
            if i-c >= 0:
                if dp[i-c] == "":
                    dp[i-c] = str(int( "".join(p)))
                else:
                    dp[i-c] = str(max(int(dp[i-c]), int( "".join(p))))
    
print(dp[0])
    
    
    
    




### FIXED CODE ###

N,M = map(int, input().split())
cost = [0,2,5,5,4,5,6,3,7,6]
A = list(map(int, input().split()))

costp = sorted([ (cost[a] ,a) for a in A], key=lambda x:x[1], reverse=True)
costX = [ z[0] for z in costp]
A = [ z[1] for z in costp]
# print(A,costX)

dp = [-1] * (N+1)
dp[N] = 0

for i in range(N, 1, -1):
    if (dp[i]) == -1:
        continue

    for c,a in zip(costX,A):
        if i-c >= 0:
            dp[i-c] = dp[i] + 1


ans = ""

i = 0
while i<N:
    # print(i)
    for c,a in zip(costX,A):
        # print(c,a,i)
        # if i+c <= N:
        #     print("i: {}, dp[i]=".format(i), dp[i], ", dp[i+c]: ", dp[i+c], "c=",c, "a=",a)
        # else: print("i: {}, dp[i]=".format(i), dp[i], ",c=",c, "a=",a)
        
        if i+c <= N:
            if dp[i]-1 == dp[i+c]:
                ans += str(a)
                i = i+c
                break

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

N = int(input())
A = tuple(map(int, input().split()))
mod = 10 ** 9 + 7

U = N + 10
fact = [1] * (U + 1)
inv = [1] * (U + 1)

for i in range(1, U + 1):
    fact[i] = fact[i - 1] * i % mod

inv[U] = pow(fact[i], mod - 2, mod)
for i in range(U, 0, -1):
    inv[i - 1] = inv[i] * i % mod


def comb(N, r):
    if r < 0 or r > N:
        return 0
    res = fact[N] * inv[r] % mod
    res = res * inv[N - r] % mod
    return res


X = max(set(A), key=A.count)
left = A.index(X)
right = A[::-1].index(X)
LR = left + right

for i in range(1, N + 2):
    ans = comb(N+1, i)-comb(LR, i-1)
    ans = (ans + mod) % mod
    print(ans)


### FIXED CODE ###

from collections import Counter

N = int(input())
A = tuple(map(int, input().split()))
mod = 10 ** 9 + 7

U = N + 10
fact = [1] * (U + 1)
inv = [1] * (U + 1)

for i in range(1, U + 1):
    fact[i] = fact[i - 1] * i % mod

inv[U] = pow(fact[i], mod - 2, mod)
for i in range(U, 0, -1):
    inv[i - 1] = inv[i] * i % mod


def comb(N, r):
    if r < 0 or r > N:
        return 0
    res = fact[N] * inv[r] % mod
    res = res * inv[N - r] % mod
    return res


X = Counter(A).most_common()[0][0]
left = A.index(X)
right = A[::-1].index(X)
LR = left + right

for i in range(1, N + 2):
    ans = comb(N+1, i)-comb(LR, i-1)
    ans = (ans + mod) % mod
    print(ans)
### BUGGY CODE ###

def resolve():
	n,q=map(int,input().split())
	s=input()
	lr=[list(map(int,input().split())) for i in range(q)]
	
	for i in range(q):
		l=lr[i][0]-1
		r=lr[i][1]
		t=s[l:r]
		print(t.count('AC'))
resolve()

### FIXED CODE ###

def resolve():
	n,q=map(int,input().split())
	s=input()
	lr=[list(map(int,input().split())) for i in range(q)]

	t=[0]*(n+1)
	for i in range(n):
		t[i+1]=t[i]+(s[i:i+2]=='AC')
	
	for i in range(q):
		l=lr[i][0]
		r=lr[i][1]

		print(t[r-1]-t[l-1])
resolve()
### BUGGY CODE ###

"""
解説動画のコードを参考にしました
https://atcoder.jp/contests/abc175/submissions/15945829
"""

N,K = map(int, input().split())
*P, = map(int, input().split())
*C, = map(int, input().split())

ans = int(-1e18)

for start in P:
    pos = start
    scores = [] # スコア格納用

    while True:
        pos = P[pos-1] # 移動
        scores.append(C[pos-1]) # スコアの格納
        # 1周したかどうか
        if pos == start: break

    # 周期途中のどこでやめるか判定
    L = len(scores)
    S = sum(scores)
    period_score = 0
    for i in range(L):
        period_score += scores[i] # スコアの加算
        # 試行回数を超えていないか
        if i+1 > K: break
        total_score = period_score
        # 1周期の合計スコアが正なら、周期を重ねるごとにスコア増
        if S > 0:
            total_score += S * ((K-(i+1)) // L)
        ans = max(ans, total_score)

print(ans)


### FIXED CODE ###

"""
解説動画のコードを参考にしました
https://atcoder.jp/contests/abc175/submissions/15945829
"""

N,K = map(int, input().split())
*P, = map(int, input().split())
*C, = map(int, input().split())

ans = int(-1e18)

for start in P:
    pos = start
    scores = [] # スコア格納用

    while True:
        pos = P[pos-1] # 移動
        scores.append(C[pos-1]) # スコアの格納
        # 1周したかどうか
        if pos == start: break

    # 周期途中のどこでやめるか判定
    L = len(scores)
    S = sum(scores)
    period_score = 0
    for i in range(L):
        period_score += scores[i] # スコアの加算
        # 試行回数を超えていないか
        if i+1 > K: break
        total_score = period_score
        # 1周期の合計スコアが正なら、周期を重ねるごとにスコア増
        if S > 0:
            total_score += S * ((K-(i+1)) // L)
        ans = max(ans, total_score)

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

L,R=map(int,input().split())

x=[]
a=1
for b in (L,R):
    if b%2019==0:
        a=0
        break
    else:
        for i in range(L,R):
            for j in range(L+1,R+1):
                y=((i*j)%2019)
                x.append(y)

if a==0:
    print(a)
else:
    print(min(x))


### FIXED CODE ###

L,R=map(int,input().split())

x=[]
a=0
for i in range(L,R):
    for j in range(L+1,R+1):
        y=((i*j)%2019)
        x.append(y)
        if y==0:
            break
    if y==0:
            break

print(min(x))
### BUGGY CODE ###

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

total=0

for i in range(n-1):
  for j in range(n-i-1):
    total=total+a[i]*a[i+j+1]%1000000007
    total=total % 1000000007
    
print(total)


### FIXED CODE ###

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

total=0

for i in range(n-1):
  s=s-a[i]
  total=total+a[i]*s%1000000007
  
print(total%1000000007)
### BUGGY CODE ###

from collections import defaultdict
from operator import itemgetter

n, a, b = map(int, input().split())
ppp = list(map(int, input().split()))
qqq = list(map(itemgetter(0), sorted(enumerate(ppp, start=1), key=itemgetter(1))))

dp = {0: 0}
for i in qqq:
    ndp = defaultdict(lambda: 10 ** 18)
    for j, cost in dp.items():
        if j < i:
            ndp[i] = min(ndp[i], cost)
            ndp[j] = min(ndp[j], cost + b)
        else:
            ndp[j] = min(ndp[j], cost + a)
    dp = ndp

print(min(dp.values()))


### FIXED CODE ###

from bisect import bisect
from operator import itemgetter

n, a, b = map(int, input().split())
ppp = map(int, input().split())
qqq = [i for i, p in sorted(enumerate(ppp, start=1), key=itemgetter(1))]
INF = 10 ** 15

dp = [(0, 0)]
for i in qqq:
    ndp = []
    s = bisect(dp, (i,))
    tmp_min = INF
    for j, cost in dp[:s]:
        cost += b
        ndp.append((j, cost))
        tmp_min = cost
    stay_cost = dp[s - 1][1]
    if tmp_min > stay_cost:
        ndp.append((i, stay_cost))
        tmp_min = stay_cost
    for j, cost in dp[s:]:
        cost += a
        if tmp_min > cost:
            ndp.append((j, cost))
            tmp_min = cost
    dp = ndp

print(dp[-1][1])