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

mod = 10**9 + 7
n = int(input())
A = [int(i) for i in input().split()]
for i in range(1,n+1):
	l = 0
	if A.count(i) > 1:
		l = i
		p = []
		for j in range(n+1):
			if A[j] == l:
				p.append(j)
		break
	if l:
		break

t = 1
d = 1
for k in range(n+1):

	#t *= (n+1-k)%mod*pow(k+1,mod-2,mod)
	t *= (n+1-k)%mod*(k+1)**(mod-2)%mod
	t %= mod
	if not k:
		print(n)
	elif k <= n+p[0]-p[1]:
		#d *= (n+p[0]-p[1]-k+1)%mod*pow(k,mod-2,mod)
		d *= (n+p[0]-p[1]-k+1)%mod*(k)**(mod-2)%mod
		d %= mod
		print((t - d)%mod)
	else:
		print(t%mod)



### FIXED CODE ###

from collections import Counter
mod = 10**9 + 7
n = int(input())
A = [int(i) for i in input().split()]
C = Counter(A)
l = 0
for i in range(1,n+1):
	if C[i] > 1:
		l = i
		p = []
		for j in range(n+1):
			if A[j] == l:
				p.append(j)
				if len(p) > 1:
					break
		break
	if l:
		break

t = 1
d = 1
for k in range(n+1):

	t *= (n+1-k)%mod
	t %= mod
	t *= pow(k+1,mod-2,mod)
	t %= mod
	if not k:
		print(n)
	elif k <= n+p[0]-p[1]:
		d *= (n+p[0]-p[1]-k+1)%mod
		d %= mod
		d *= pow(k,mod-2,mod)
		d %= mod
		print((t - d)%mod)
	else:
		print(t%mod)
### BUGGY CODE ###

import numpy as np
N, M = map(int, input().split())
Alist = np.array(list(map(int, input().split())), dtype=np.int64)
for _ in range(M):
    Alist[np.argmax(Alist)] //= 2
print(np.sum(Alist))


### FIXED CODE ###

import heapq


def int_and_reverse(num):
    return int(num) * -1


N, M = map(int, input().split())
Alist = list(map(int_and_reverse, input().split()))
heapq.heapify(Alist)
for _ in range(M):
    x = (heapq.heappop(Alist) * -1) // 2
    heapq.heappush(Alist, -x)
print(-sum(Alist))
### BUGGY CODE ###

N,Q = map(int, input().split())
S = input()
def judge_letter(letter, r, l):
    j_letter = letter[r-1 : l]
    return j_letter.count("AC")
num = []
for i in range(Q):
    l, r = map(int, input().split())
    num.append(judge_letter(S, l,r))
for j in num:
    print(j)

### FIXED CODE ###

import time
N,Q = map(int, input().split())
S = input()
AC = [0]*(N+1)

for i in range(N):
    if S[i:i+2] == "AC":
        AC[i+1] = AC[i] + 1
    else:
        AC[i+1] = AC[i]

for i in range(Q):
    l, r = map(int, input().split())
    print(AC[r-1] - AC[l-1])
### BUGGY CODE ###

import sys, re
input = sys.stdin.readline

n = int(input())
a = [int(input()) for x in range(n)]

# a[0]の場合
temp_list = a[1:]
temp_list.sort()
print(temp_list[-1])

# それ以外の場合
for i in range(1, n):
  temp_list = a[:i] + a[i+1:]
  temp_list.sort()
  print(temp_list[-1])


### FIXED CODE ###

import sys, re
input = sys.stdin.readline

n = int(input())
a = [int(input()) for x in range(n)]

# a をソートして、一番大きい要素を取り出す
temp_list = sorted(a)
m = temp_list[::-1][0]


# 最も大きな数が複数あった場合
if temp_list[::-1][1] == m:
    m_dash = m
else:
    m_dash =temp_list[::-1][1]

for a_i in a:
  if a_i == m:
    print(m_dash)
  else:
    print(m)
### BUGGY CODE ###

#!/usr/bin/env python3
import sys


def solve(N: int, P: "List[int]"):
    cnt = 0
    for i in range(0, N):
        flag=True
        for j in range(0, i+1):
            if P[i] > P[j]:
                flag=False
        if flag:
            cnt+=1
    return cnt


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    print(solve(N, P))

if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
import sys


def solve(N: int, P: "List[int]"):
    cnt = 1
    min = P[0]
    for i in range(1, N):
        if P[i] <= min:
            cnt+=1
            min = P[i]
    return cnt


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    print(solve(N, P))

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

import sys
input=lambda: sys.stdin.readline().rstrip()
k=int(input())
S=input()
mod=10**9+7
n=len(S)
n_max=2*(10**6+1)
F,FI=[0]*(n_max+1),[0]*(n_max+1)
F[0],FI[0]=1,1
for i in range(n_max):
  F[i+1]=(F[i]*(i+1))%mod
FI[n_max-1]=pow(F[n_max-1],mod-2,mod)
for i in reversed(range(n_max-1)):
  FI[i]=(FI[i+1]*(i+1))%mod
def comb(x,y):
  return (F[x]*FI[x-y]*FI[y])%mod

P1,P2=[1],[1]
for _ in range(10**6):
  P1.append((P1[-1]*26)%mod)
  P2.append((P2[-1]*25)%mod)

ans=0
for i in range(n,n+k+1):
  ans+=comb(i-1,n-1)*P2[i-n]*P1[n+k-i]
  ans%=mod
print(ans)


### FIXED CODE ###

import sys
input=lambda: sys.stdin.readline().rstrip()
k=int(input())
S=input()
mod=10**9+7
n=len(S)
n_max=2*(10**6+1)
F,FI=[0]*(n_max+1),[0]*(n_max+1)
F[0],FI[0]=1,1
for i in range(n_max):
  F[i+1]=(F[i]*(i+1))%mod
FI[n_max-1]=pow(F[n_max-1],mod-2,mod)
for i in reversed(range(n_max-1)):
  FI[i]=(FI[i+1]*(i+1))%mod
def comb(x,y):
  return (F[x]*FI[x-y]*FI[y])%mod

P1,P2=[1],[1]
for _ in range(10**6):
  P1.append((P1[-1]*26)%mod)
  P2.append((P2[-1]*25)%mod)

ans=0
for i in range(n,n+k+1):
  ans+=comb(i-1,n-1)*P2[i-n]*P1[n+k-i]
  ans%=mod
print(ans)
### BUGGY CODE ###

import sys
from numpy import*
def main(n,q,c,z):
  a=zeros(q,int64)
  t=zeros(9**6,int64)
  b=zeros(9**6,int64)
  j=0
  for i in argsort(z[:,1]):
    l,r=z[i,0],z[i,1]
    while j<r:
      d=c[j]
      j+=1
      x,y,b[d]=b[d]+1,j+1,j
      while x<=n:
        t[x]+=1
        x+=x&-x
      while y<=n:
        t[y]-=1
        y+=y&-y
    while l:
      a[i]+=t[l]
      l-=l&-l
  return a

(n,q),c,*z=[int_(t.split())for t in open(0)]
print('\n'.join(map(str,main(n,q,c,int_(z)).tolist())))

### FIXED CODE ###

def main(N,Q,C,LR,A):
    data = [0]*(N+1)
    def add(i,x):
        i+=1
        while i <= N:
            data[i]+= x
            i+=i&-i 
            #下桁から最初に1が出現するところまで拾う
            #111 -> 1 , 1100 -> 100 , 1010 -> 1
    def sum(a,b):
        r=0
        i=b
        while i>0:
            r+=data[i]
            i-=i&-i
        i=a
        while i>0:
            r-=data[i]
            i-=i&-i
        return r
    p=[-1]*N
    q=0
    a=[0]*Q
    for i in range(N):
        if p[C[i]-1]>=0:
            add(p[C[i]-1],-1)
        p[C[i]-1]=i
        add(i,1)
        while q<Q and LR[A[q]][1]==i+1:
            a[A[q]]=sum(LR[A[q]][0]-1,LR[A[q]][1])
            q+=1
    return a

import sys
if sys.argv[-1]=='ONLINE_JUDGE':
    from numba import*
    from numba.pycc import CC
    cc = CC('my_module')
  
    def cc_export(f, signature):
        cc.export(f.__name__, signature)(f)
        return njit(f)
  
    main=cc_export(main,(i8,i8,i8[:],i8[:,:],i8[:]))
    cc.compile()
    exit()
  
def input(): return sys.stdin.buffer.readline()
N,Q=map(int, input().split())
import numpy as np
C=np.array(input().split(),dtype=np.int64)
#print(C)
LR_ = [0] * (Q*2)
for i in range(Q):
    LR_[i*2],LR_[i*2+1] = input().split()
LR=np.array(LR_, dtype=np.int64).reshape(Q,2)
#print(LR)
A=np.argsort(LR[:,1])

from my_module import main
print(*main(N,Q,C,LR,A),sep='\n')
### BUGGY CODE ###

n = int(input())
cnt = 0
for a in range(1, n):
    for b in range(1, ((n-1)//a)+1):
        if n - a*b <= 0: break
        cnt += 1
print(cnt)


### FIXED CODE ###

n = int(input())
cnt = 0
for a in range(1, n):
    bn = (n-1) // a
    for b in range(1, bn+1):
        c = n-(a*b)
        if c<=0: break
        if a*b + c == n:
            cnt += 1
print(cnt)
### BUGGY CODE ###

def solve():
    N,K = [int(i) for i in input().split()]
    P = [int(i) for i in input().split()]
    ans = 0
    for i in range(N-K+1):
        target = P[i:i+K]
        expected_sum = sum([(num+1)/2.0 for num in target])
        ans = max(expected_sum, ans)
    print(ans)

if __name__ == "__main__":
    solve()

### FIXED CODE ###

def solve():
    N,K = [int(i) for i in input().split()]
    P = [int(i) for i in input().split()]
    prev_K_sum = max_K_sum = sum(P[:K])
    start = 0
    for i in range(N-K):
        cur_K_sum = prev_K_sum - P[i] + P[i+K]
        if cur_K_sum > max_K_sum:
            start = i + 1
            max_K_sum = cur_K_sum
        prev_K_sum = cur_K_sum
    target = P[start:start+K]
    ans = sum([(num+1)/2.0 for num in target])
    print(ans)

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

N,W = map(int,input().split())
wvs = [[int(kk) for kk in input().split()] for i in range(N)]

dp = [0]*(W+1)

for w,v in  wvs:
    for i in reversed(range(W+1)):
        #print(i)
        dp[i] = max(dp[i-w]+v,dp[i])
        if i == w:
            break

print(max(dp))



### FIXED CODE ###

N,W = map(int,input().split())
wvs = [[int(kk) for kk in input().split()] for i in range(N)]

dp = [0]*(W+1)

for w,v in  wvs:
    for i in reversed(range(W+1)):
        #print(i)
        dp[i] = max(dp[i-w]+v,dp[i])
        if i == w:
            break

print(max(dp))
### BUGGY CODE ###

N = input()
counter = 0

for i in range(1, int(N)+1):
  a = str(i)
  if '7' in a and a != '':
    a = a.replace('7', '')
    if '3' in a and a != '':
      a = a.replace('3', '')
      if a != '':
        a = a.replace('5', '')
        if a == '':
          counter += 1
print(counter)

### FIXED CODE ###

N = int(input())
 
def dfs(s):
  if int(s) > N: 
    return 0
  ret = 1 if all(s.count(c) > 0 for c in '753') else 0
  for c in '753':
    ret += dfs(s+c)
  return ret
 
print(dfs('0'))
### BUGGY CODE ###

alphabet_small = {chr(i):i-97 for i in range(97, 97+26)}
s = input()
k = int(input())
ans =""
for character in s:
    i = alphabet_small[character]
    #print(i,character)
    if i != 0 and k >= 26 - i:
        k -= 26 - i
        ans += "a"
    else:
        ans += character


if k > 0:
    k %= 26
    ans = ans[:-1] + chr((alphabet_small[ans[-1]]+k)%26+97)

print(ans)

### FIXED CODE ###

alphabet_small = {chr(i):i-97 for i in range(97, 97+26)}
s = input()
k = int(input())
ans =""
for character in s:
    i = alphabet_small[character]
    #print(i,character)
    if i != 0 and k >= 26 - i:
        k -= 26 - i
        ans += "a"
    else:
        ans += character


if k > 0:
    k %= 26
    ans = ans[:-1] + chr((alphabet_small[ans[-1]]+k)%26+97)

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

N = int(input())

s = [sorted(list(input())) for i in range(N)]

for i in range(N):
    s[i] = ''.join(s[i])

ans = 0

for i in range(N):
    for j in range(i+1, N):
        if s[i]==s[j]: ans+=1

print(ans)


### FIXED CODE ###

import collections
N = int(input())

s = [sorted(list(input())) for i in range(N)]

for i in range(N):
    s[i] = ''.join(s[i])

ans = 0

c = collections.Counter(s)
for v in c.values():
    ans += (1/2) * v * (v-1)

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

import sys
from collections import Counter

input = sys.stdin.readline

P = 2019


def main():
    S = input().rstrip()

    n = len(S)
    T = [int(S[k:]) % P for k in range(n)]
    T.append(0)  # T_{n+1} = 0

    c = Counter(T)
    ans = 0
    for v in c.values():
        ans += v*(v-1)//2  # vC2
    print(ans)


if __name__ == "__main__":
    main()


### FIXED CODE ###

import sys

input = sys.stdin.readline

P = 2019

def main():
    S = input().rstrip()

    n = len(S)
    counts = [0] * P
    counts[0] += 1
    T = 0
    d = 1
    for s in reversed(S):
        T = (T + (d * int(s)) % P) % P
        d = (d * 10) % P
        counts[T] += 1

    ans = 0
    for c in counts:
        ans += c*(c-1)//2  # cC2
    print(ans)


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

import sys
input=sys.stdin.readline
n=int(input())
a=input().split()
ans=[]
for i in range(n):
    if n%2==0:
        if i%2!=0:
            ans.insert(0,a[i])
        else:
            ans.append(a[i])
    else:
        if i%2==0:
            ans.insert(0,a[i])
        else:
            ans.append(a[i])
ans=' '.join(ans)
if n==1:
    ans=a[0]
print(ans)

### FIXED CODE ###

import sys
input=sys.stdin.readline
n=int(input())
a=input().split()
ans=[]

for i in range(n):
    if n%2==0:
        if i%2==0:
            ans.append(a[i])
    else:
        if i%2!=0:
            ans.append(a[i])
ans=ans[::-1]
for i in range(n):
    if n%2==0:
        if i%2!=0:
            ans.append(a[i])
    else:
        if i%2==0:
            ans.append(a[i]) 
ans=ans[::-1]
ans=' '.join(ans)
if n==1:
    ans=a[0]
'''
for j in range(n):
    ans.insert(0,a[j])
'''
print(ans)
### BUGGY CODE ###

n,k = [int(i) for i in input().split()]
data = [int(i) for i in input().split()]

d = 1
count = 0
loop = []
route = [1]

while count < len(data):
    d = data[d-1]
    if d in route:
        loop = route[route.index(d):]
        break
    else:
        route.append(d)
    count += 1
if len(loop) > 0:
    loop_len = len(loop)
    a = len(route) - loop_len
    if k < a:
        print(route[k])
    else:
        print(loop[(k-a)%loop_len])
else:
    print(route[k])

### FIXED CODE ###

n, k = map(int, input().split())
a = list(map(int, input().split()))
visited = [0]
for _ in range(n):
    now = a[visited[-1]]-1
    visited.append(now)

if k < n:
    print(visited[k]+1)
else:
    p = visited.index(visited[-1])
    loop = visited[::-1][1:].index(visited[-1])+1
    x = (k-p-1)%loop
    print(visited[p+x+1]+1)
### BUGGY CODE ###

from sys import stdin
from math import sqrt

a, b = [int(x) for x in stdin.readline().split()]

while b != 0:
    a, b = b, a % b

c = 1
i = 2
while a > 1:
    n = 0
    while a % i == 0:
        a //= i
        n += 1
    if n > 0:
        c += 1
    i += 1

print(c)


### FIXED CODE ###

from sys import stdin

a, b = [int(x) for x in stdin.readline().split()]

while b != 0:
    a, b = b, a % b

c = 1
lim = a ** 0.5 + 10
n = 0
i = 2
while a > 1 and i <= lim:
    n = 0
    while a % i == 0:
        a //= i
        n += 1
    if n > 0:
        c += 1
    i += 1
if a > 1:
    c += 1

print(c)
### BUGGY CODE ###

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


def main():
    from collections import deque

    h, w = map(int, input().split())
    a = [list(input()) for _ in range(h)]
    dx = [0, 0, -1, 1]
    dy = [1, -1, 0, 0]
    dist = [[float('inf') for __ in range(w)] for _ in range(h)]
    blacks = deque()

    # See:
    # http://drken1215.hatenablog.com/entry/2019/05/05/223200?_ga=2.177845805.987014750.1556545680-1855989383.1556545680
    # https://blog.kichi2004.jp/2019/05/agc033/
    for i in range(h):
        for j in range(w):
            if a[i][j] == '#':
                dist[i][j] = 0
                blacks.append((i, j))

    while blacks:
        current = blacks.popleft()
        cur_x = current[1]
        cur_y = current[0]

        for i in range(len(dx)):
            next_x = cur_x + dx[i]
            next_y = cur_y + dy[i]

            if next_x < 0 or next_x >= w or next_y < 0 or next_y >= h:
                continue

            if dist[next_y][next_x] == float('inf'):
                dist[next_y][next_x] = dist[cur_y][cur_x] + 1
                blacks.append((next_y, next_x))

    ans = 0

    for i in range(h):
        for j in range(w):
            ans = max(ans, dist[i][j])

    print(ans)


if __name__ == '__main__':
    main()


### FIXED CODE ###

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


def main():
    from collections import deque

    h, w = map(int, input().split())
    a = [list(input()) for _ in range(h)]
    dx = [0, 0, -1, 1]
    dy = [1, -1, 0, 0]
    dist = [[-1 for __ in range(w)] for _ in range(h)]
    blacks = deque()

    # See:
    # http://drken1215.hatenablog.com/entry/2019/05/05/223200?_ga=2.177845805.987014750.1556545680-1855989383.1556545680
    # https://blog.kichi2004.jp/2019/05/agc033/
    for i in range(h):
        for j in range(w):
            if a[i][j] == '#':
                dist[i][j] = 0
                blacks.append((i, j))

    while blacks:
        current = blacks.popleft()
        cur_x = current[1]
        cur_y = current[0]

        for i in range(4):
            next_x = cur_x + dx[i]
            next_y = cur_y + dy[i]

            if next_x < 0 or next_x >= w or next_y < 0 or next_y >= h:
                continue

            if dist[next_y][next_x] == -1:
                dist[next_y][next_x] = dist[cur_y][cur_x] + 1
                blacks.append((next_y, next_x))

    ans = 0

    for i in range(h):
        for j in range(w):
            ans = max(ans, dist[i][j])

    print(ans)


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

# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush
import numpy as np


def small_dp(N,A,B):
    *X, = filter(lambda c: int.__sub__(*c)<0, zip(A,B))
    k = len(X)
    if k == 0:
        return N
    if k == 1:
        return X[0][1]*(N//X[0][0]) + N%X[0][0]
    if k == 2:
        c = 0
        for i in range(N//X[0][0]+1):
            j = (N-i*X[0][0])//X[1][0]
            c = max(X[0][1]*i + X[1][1]*j + (N-i*X[0][0])%X[1][0], c)
        return c
    if k == 3:
        if (N//X[1][0]+1)*(N//X[0][0]+1) <= 10**6 :
            return max(X[0][1]*i + max(X[1][1]*j + X[2][1]*((N-i*X[0][0]-j*X[1][0])//X[2][0]) + ((N-i*X[0][0]-j*X[1][0])%X[2][0]) for j in range((N-i*X[0][0])//X[1][0]+1)) for i in range(N//X[0][0]+1))
        else:
            dp = np.zeros(N+1, dtype=int)
            for w in range(1,N+1):
                dp[w] = max(dp[w-X[i][0]]+X[i][1] if w>=X[i][0] else w for i in range(k))
            N = dp[-1]
            return N

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    res = small_dp(small_dp(N, A, B), B, A)

    return str(res)

if __name__ == '__main__':
    print(solve())


### FIXED CODE ###

# -*- coding: utf-8 -*-
from itertools import product
from heapq import heappop, heappush

def small_dp(N,A,B):
    *X, = filter(lambda c: int.__sub__(*c)<0, zip(A,B))
    k = len(X)
    if k == 0:
        return N
    if k == 1:
        return X[0][1]*(N//X[0][0]) + N%X[0][0]
    if k == 2:
        c = 0
        for i in range(N//X[0][0]+1):
            j = (N-i*X[0][0])//X[1][0]
            c = max(X[0][1]*i + X[1][1]*j + (N-i*X[0][0])%X[1][0], c)
        return c
    if k == 3:
        if (N//X[1][0]+1)*(N//X[0][0]+1) <= 10**6 :
            return max(X[0][1]*i + max(X[1][1]*j + X[2][1]*((N-i*X[0][0]-j*X[1][0])//X[2][0]) + ((N-i*X[0][0]-j*X[1][0])%X[2][0]) for j in range((N-i*X[0][0])//X[1][0]+1)) for i in range(N//X[0][0]+1))
        else:
            import numpy as np
            dp = np.zeros(N+1, dtype=int)
            for w in range(1,N+1):
                dp[w] = max(dp[w-X[i][0]]+X[i][1] if w>=X[i][0] else w for i in range(k))
            N = dp[-1]
            return N

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    res = small_dp(small_dp(N, A, B), B, A)

    return str(res)

if __name__ == '__main__':
    print(solve())
### BUGGY CODE ###

N=int(input())
A=list(map(int,input().split()))
Q=int(input())
D=dict()
for i in A:
  if i in D:
    D[i]+=1
  else:
    D[i]=1
for _ in range(Q):
  b,c=map(int,input().split())
  if b in D:
    if c in D:
      D[c]+=D[b]
    else:
      D[c]=D[b]
    del D[b]
  r=0
  for i,j in D.items():
    r+=i*j
  print(r)

### FIXED CODE ###

N=int(input())
A=list(map(int,input().split()))
Q=int(input())
D=dict()
s=0
for i in A:
  s+=i
  if i in D:
    D[i]+=1
  else:
    D[i]=1
for _ in range(Q):
  b,c=map(int,input().split())
  if b in D:
    s+=(c-b)*D[b]
    if c in D:
      D[c]+=D[b]
    else:
      D[c]=D[b]
    del D[b]
  print(s)
### BUGGY CODE ###

n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def sim(start,mx): # simulate mx step from start, returns max_score
    if mx==0:
        return 0
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]

    while True:
        nxt=p[nxt]-1
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==mx:
            break

    return max(p_lis)

visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0

for i in range(n):
    if i in visited_p:
        continue
    visited_p.add(i)
    now_p=0
    nxt=p[i]-1
    visited=set()
    while True:
        nxt=p[nxt]-1
        visited_p.add(nxt)
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]
    cycle_score.append(now_p)
    cycle_points.append(list(visited))

ans=-float('inf')

for c_num in range(len(cycle_score)):
#    print(c_num,cycle_score[c_num],cycle_points[c_num])
    cycle_len=len(cycle_points[c_num])
    for start in cycle_points[c_num]:

        if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
            score = sim(start,min(cycle_len,k))
            ans=max(ans,score)

        else: # loop as many as possible
            loop_num = k % cycle_len
            nokori=k-(loop_num*cycle_len)

            score = sim(start,nokori) + loop_num*cycle_score[c_num]
            ans=max(ans,score)

print(ans)

### FIXED CODE ###

n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def sim(start,mx): # simulate mx step from start, returns max_score
    if mx==0:
        return 0
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]

    while True:
        nxt=p[nxt]-1
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==mx:
            break

    return max(p_lis)

visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0

for i in range(n):
    if i in visited_p:
        continue
    visited_p.add(i)
    now_p=0
    nxt=p[i]-1
    visited=set()
    while True:
        nxt=p[nxt]-1
        visited_p.add(nxt)
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]
    cycle_score.append(now_p)
    cycle_points.append(list(visited))

ans=-float('inf')

for c_num in range(len(cycle_score)):
#    print(c_num,cycle_score[c_num],cycle_points[c_num])
    cycle_len=len(cycle_points[c_num])
    for start in cycle_points[c_num]:

        if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
            score = sim(start,min(cycle_len,k))
            ans=max(ans,score)

        else: # loop as many as possible
            loop_num = max(0,(k // cycle_len) - 1)
            nokori=k-loop_num*cycle_len
            score = sim(start,nokori) + loop_num*cycle_score[c_num]
            ans=max(ans,score)

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

import bisect
n, m = map(int, input().split())
A = sorted(map(int, input().split()))

for _ in range(m):
    x = A.pop()
    x //= 2
    bisect.insort_right(A, x)
print(sum(A))

### FIXED CODE ###

import sys
from math import floor
from heapq import heappush, heappop, heappushpop
input = sys.stdin.readline
sys.setrecursionlimit(10**7)


# 10**5
n, m = map(int, input().split())
# 10**9
a = sorted(map(lambda s: -int(s), input().split()))


for _ in range(m):
    x = heappop(a)
    heappush(a, x/2)

print(sum(map(lambda x: floor(-x), a)))
### BUGGY CODE ###

import sys
input = sys.stdin.readline
n,k = map(int,input().split())
h = list(map(int,input().split()))

dp = [float('inf')]*n
dp[0] = 0
for i in range(n):
    for j in range(1,k+1):
        if i-j >= 0:
            dp[i] = min(dp[i],dp[i-j]+abs(h[i]-h[i-j]))
print(dp[n-1])


### FIXED CODE ###

import sys
input = sys.stdin.readline
n,k = map(int,input().split())
h = list(map(int,input().split()))

dp = [10**9]*n
dp[0] = 0
for i in range(n):
    for j in range(1,k+1):
        if i-j >= 0:
            dp[i] = min(dp[i],dp[i-j]+abs(h[i]-h[i-j]))
print(dp[n-1])