Problem:
 Score : 400 points    Problem Statement Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N . Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N : P_1, P_2, \cdots, P_N .  Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):   In one move, if the piece is now on Square i  (1 \leq i \leq N) , move it to Square P_i . Here, his score increases by C_{P_i} .   Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)      Constraints  2 \leq N \leq 5000  1 \leq K \leq 10^9  1 \leq P_i \leq N  P_i \neq i  P_1, P_2, \cdots, P_N are all different.  -10^9 \leq C_i \leq 10^9  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  K  P_1  P_2  \cdots  P_N  C_1  C_2  \cdots  C_N       Output Print the maximum possible score at the end of the game.        Sample Input 1 5 2
2 4 5 1 3
3 4 -10 -8 8      Sample Output 1 8  When we start at some square of our choice and make at most two moves, we have the following options:   If we start at Square 1 , making one move sends the piece to Square 2 , after which the score is 4 . Making another move sends the piece to Square 4 , after which the score is 4 + (-8) = -4 .  If we start at Square 2 , making one move sends the piece to Square 4 , after which the score is -8 . Making another move sends the piece to Square 1 , after which the score is -8 + 3 = -5 .  If we start at Square 3 , making one move sends the piece to Square 5 , after which the score is 8 . Making another move sends the piece to Square 3 , after which the score is 8 + (-10) = -2 .  If we start at Square 4 , making one move sends the piece to Square 1 , after which the score is 3 . Making another move sends the piece to Square 2 , after which the score is 3 + 4 = 7 .  If we start at Square 5 , making one move sends the piece to Square 3 , after which the score is -10 . Making another move sends the piece to Square 5 , after which the score is -10 + 8 = -2 .   The maximum score achieved is 8 .       Sample Input 2 2 3
2 1
10 -7      Sample Output 2 13       Sample Input 3 3 3
3 1 2
-1000 -2000 -3000      Sample Output 3 -1000  We have to make at least one move.       Sample Input 4 10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719      Sample Output 4 29507023469  The absolute value of the answer may be enormous.

Solution (Python):
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
now=-100000000000
for i in range(1,n+1):
    retu=[]
    sum1=0
    sum2=0
    sum3=0
    max1=-1000000000000
    max2=-1000000000000
    flag=0
    x=i
    while(flag==0):
        x=p[x-1]
        sum1+=c[x-1]
        retu.append(c[x-1])
        if x==i:
            flag=1
    if len(retu)>=k: 
        for j in range(k):
            sum2+=retu[j]
            if sum2>max1:
                max1=sum2
        ans=max1
    elif sum1<=0: 
        for j in range(len(retu)):
            sum3+=retu[j]
            if sum3>max2:
                max2=sum3
        ans=max2
    else:
        w=k%len(retu)
        
        if w==0:
            w=len(retu)
        for j in range(w):
            sum2+=retu[j]
            if sum2>max1:
                max1=sum2
        for j in range(len(retu)):
            sum3+=retu[j]
            if sum3>max2:
                max2=sum3
        if max1+sum1>max2:
            ans=sum1*(k-w)//len(retu)+max1
        else:
            ans=sum1*((k-w)//len(retu)-1)+max2
    now=max(now,ans)
print(now)

Solution (Python):
from collections import defaultdict
def f(s):
  return int(s) - 1

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

loop = []

first = -1
x = -1
loop_mem = []
cnt = 0
score = 0

rem = set(range(N))

while len(rem) > 0:
  if first < 0:
    first = rem.pop()
    x = first
  loop_mem.append(x)
  if x != first:
    rem.remove(x)
  cnt += 1
  score += C[x]
  if first != P[x]:
    x = P[x]
  else:
    loop.append((loop_mem, cnt, score))
    first = -1
    loop_mem = []
    cnt = 0
    score = 0

ans = -1e10
for loop_mem, cnt, score in loop:
  imax = [-1e10 for _ in range(cnt)]
  imax[0] = 0
  for x in loop_mem:
    tmp = 0
    for j in range(1, cnt):
      tmp += C[x]
      imax[j] = max(imax[j], tmp)
      x = P[x]
  for j in range(2, cnt):
    imax[j] = max(imax[j-1], imax[j])
  if score <= 0:
    ans = max(ans, imax[-1])
  else:
    M = K // cnt
    m = K % cnt
    if M >= 1:
      tmp = max(score * M + max(imax[m], 0), score * (M-1) + imax[-1])
    else:
      tmp = imax[m]
    ans = max(ans, tmp)

print(ans)

Solution (Python):
from math import inf
n,k=map(int,input().split())
arr=[0]+list(map(int,input().split()))
cost=[0]+list(map(int,input().split()))
ma=-inf
for i in range(1,n+1):
    se=set()
    cur=i
    pref=[0]
    f=0
    while(cur not in se and f<k):
        se.add(cur)
        cur=arr[cur]
        co = cost[cur]
        pref.append(pref[-1]+co)
        ma=max(ma,pref[-1])
        f+=1

    if pref[-1]>0 and k>=f:
        ans=pref[-1]*(k//f)
        for j in range(k%f+1):
            ma=max(ma,ans+pref[j])
        ma=max(ma,pref[-1]*(k//f-1)+max(pref))
print(ma)

Solution (Python):

import itertools

if __name__ == "__main__":

	N,K = map(int,input().split())
	P = [ int(p)-1 for p in input().split() ]
	C = list(map(int,input().split()))

	
	
	
	cycleIDs = [ -1 for _ in range(N)]
	cycleInfs = []
	cycleID = 0
	procCnt = 0

	for n in range(N):
		v = n

		if cycleIDs[v] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					
					
					procCnt = K % len( currentCycleCosts )
					
					
					
					
					
					
					
					
					
					
					
					
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

					cycleInfs.append( ( procCnt, len(currentCycleCosts), currentCycleCosts * 3 ) )
					cycleID += 1
					break



	
	
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

		
		loopScore = 0
		if sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleSize
			loopScore = cycleLoopCnt * sum(currentCycleCosts[:currentCycleSize])
			

		
		for i in range(currentCycleSize):
			
			score = max( itertools.accumulate( currentCycleCosts[i:i+procCnt] ) )
			if ans < score + loopScore:
				ans = score + loopScore
			


	print(ans)

Solution (Python):

import itertools

if __name__ == "__main__":

	N,K = map(int,input().split())
	P = [ int(p)-1 for p in input().split() ]
	C = list(map(int,input().split()))

	
	
	
	cycleIDs = [ -1 for _ in range(N)]
	cycleInfs = []
	cycleID = 0
	procCnt = 0

	for n in range(N):
		v = n

		if cycleIDs[v] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					
					
					procCnt = K % len( currentCycleCosts )
					
					
					
					
					
					
					
					
					
					
					
					
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

					cycleInfs.append( ( procCnt, len(currentCycleCosts), currentCycleCosts * 3 ) )
					cycleID += 1
					break



	
	
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

		
		loopScore = 0
		if sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleSize
			loopScore = cycleLoopCnt * sum(currentCycleCosts[:currentCycleSize])
			

		
		for i in range(currentCycleSize):
			
			ans = max( ans, max( itertools.accumulate( currentCycleCosts[i:i+procCnt] ) ) + loopScore )


	print(ans)

Solution (Python):
from itertools import accumulate

n, k = map(int, input().split())
p = [int(x) - 1 for x in input().split()]
c = list(map(int, input().split()))
ans = -(10 ** 18)

for i in range(n):
    pos = i
    scores = []
    while True:
        pos = p[pos]
        scores.append(c[pos])
        if pos == i:
            break
    m = len(scores)
    s = list(accumulate(scores))
    for j in range(min(m, k)):
        x = (k - j - 1) // m
        ans = max(ans, s[j], s[j] + s[-1] * x)

print(ans)

Solution (Python):
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
for i in range(n):
    p[i]-=1
ans=max(c)
for i in range(n):
    f=i
    r=0
    l=[]
    while True:
        f=p[f]
        l.append(c[f])
        r+=c[f]
        if f==i:
            break
    t=0
    for j in range(len(l)):
        t+=l[j]
        if j+1>k:
            break
        ret=t
        if r>0:
            e=(k-j-1)//len(l)
            ret+=r*e
        ans=max(ans,ret)
print(ans)

Solution (Python):

import itertools

if __name__ == "__main__":

	N,K = map(int,input().split())
	P = [ int(p)-1 for p in input().split() ]
	C = list(map(int,input().split()))

	
	
	
	cycleIDs = [ -1 for _ in range(N)]
	cycleInfs = []
	cycleID = 0
	procCnt = 0

	for n in range(N):
		v = n

		if cycleIDs[v] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					
					
					procCnt = K % len( currentCycleCosts )
					
					
					
					
					
					
					
					
					
					
					
					
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

					cycleInfs.append( ( procCnt, len(currentCycleCosts), currentCycleCosts * 3 ) )
					cycleID += 1
					break



	
	
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

		
		loopScore = 0
		if sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleSize
			loopScore = cycleLoopCnt * sum(currentCycleCosts[:currentCycleSize])
			

		
		for i in range(currentCycleSize):
			
			ans = max( ans, max( list( itertools.accumulate( currentCycleCosts[i:i+procCnt] ) ) ) + loopScore )


	print(ans)

Solution (Python):

import itertools

if __name__ == "__main__":

	N,K = map(int,input().split())
	P = [ int(p)-1 for p in input().split() ]
	C = list(map(int,input().split()))

	
	
	
	cycleIDs = [ -1 for _ in range(N)]
	cycleInfs = []
	cycleID = 0
	procCnt = 0

	for n in range(N):
		v = n

		if cycleIDs[v] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					
					
					procCnt = K % len( currentCycleCosts )
					
					
					
					
					
					
					
					
					
					
					
					
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

					cycleInfs.append( ( procCnt, len(currentCycleCosts), currentCycleCosts * 3 ) )
					cycleID += 1
					break



	
	
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

		
		loopScore = 0
		if sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleSize
			loopScore = cycleLoopCnt * sum(currentCycleCosts[:currentCycleSize])
			

		
		for i in range(currentCycleSize):
			
			ans = max( ans, max( list( itertools.accumulate( currentCycleCosts[i:i+procCnt] ) ) ) + loopScore )


	print(ans)

Solution (Python):
import numpy as np

if __name__ == "__main__":
	N,K = map(int,input().split())
	P = [ int(p)-1 for p in input().split() ]
	C = list(map(int,input().split()))
	cycleIDs = np.full( N, -1, np.int64 )
	cycleInfs = []
	cycleID = 0
	procCnt = 0
	for n in range(N):
		v = n
		if cycleIDs[v] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					procCnt = K % len( currentCycleCosts )
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )
					cycleInfs.append( ( procCnt, len(currentCycleCosts), np.array( currentCycleCosts + currentCycleCosts ) ) )
					cycleID += 1
					break
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:
		loopScore = 0
		if np.sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleSize
			loopScore = cycleLoopCnt * np.sum(currentCycleCosts[:currentCycleSize])

		for i in range(currentCycleSize):
			ans = max( ans, np.roll( currentCycleCosts, i ).cumsum()[:procCnt].max() + loopScore )

	print(ans)

Solution (Python):
n,k=map(int,input().split())
*p,=map(int,input().split())
*c,=map(int,input().split())

ans=-10**20
for i in range(n):
    loop=1
    j=p[i]-1
    acm=[c[j]]
    while j!=i:
        j=p[j]-1
        acm.append(acm[-1]+c[j])
        loop+=1
    
    if acm[-1]>0:
        if k<=loop:
            cur=max(acm[:k])
        else:
            cur=(k//loop)*acm[-1]
            if k%loop>0:
                cur=max(cur,cur+max(acm[:k%loop]))
            else:
                cur-=acm[-1]
                cur+=max(acm)
    else:
        cur=max(acm[:min(k,loop)])
    
    ans=max(cur,ans)
    
print(ans)

Solution (Python):
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]

max_score = max(C[1:])
for init in range(1, N + 1):   
    score = [0]  
    i = init
    for k in range(1, K + 1):
        i = P[i]  
        score.append(score[-1] + C[i])
        max_score = max(max_score, score[k])
        if i == init:  
            loop_score = score[-1]
            loop_len = k
            if loop_score > 0:
                max_score = max(max_score, max(score[j] + loop_score * ((K - j) // loop_len) for j in range(1, loop_len + 1)))
            break

print(max_score)

Solution (Python):
import numpy as np

if __name__ == "__main__":

	N,K = map(int,input().split())
	P = [ int(p)-1 for p in input().split() ]
	C = list(map(int,input().split()))

	
	
	cycleIDs = np.full( N, -1, np.int64 )
	cycleInfs = []
	cycleID = 0
	procCnt = 0

	for n in range(N):
		v = n

		if cycleIDs[v] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					
					
					procCnt = K % len( currentCycleCosts )
					
					
					
					
					
					
					
					
					
					
					
					
					
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

					cycleInfs.append( ( procCnt, len(currentCycleCosts), np.array( currentCycleCosts + currentCycleCosts ) ) )
					cycleID += 1
					break



	
	
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

		
		loopScore = 0
		fullMinus1CntLoopScore = 0
		if np.sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleSize
			loopScore = cycleLoopCnt * np.sum(currentCycleCosts[:currentCycleSize])
			

		
		for i in range(currentCycleSize):
			
			
			ans = max( ans, np.roll( currentCycleCosts, i ).cumsum()[:procCnt].max() + loopScore )


	print(ans)

Solution (Python):
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]

max_score = max(C[1:])
for init in range(1, N + 1):   
    score = [0]  
    i = init
    for k in range(1, K + 1):
        i = P[i]  
        score.append(score[-1] + C[i])
        max_score = max(max_score, score[k])
        if i == init:  
            loop_score = score[-1]
            loop_len = k
            if loop_score < 0:
                max_score = max(max_score, max(score[1:]))
            else:
                max_score = max(max_score, max(score[j] + loop_score * ((K - j) // loop_len) for j in range(1, loop_len + 1)))
            break

print(max_score)

Solution (Python):
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

ans = -1*float('inf')

for i in range(N):
    k = i
    Cc = []
    Ct = 0
    while 1:
        k = P[k]-1
        Cc.append(C[k])
        if i == k:
            break
    l = len(Cc)
    Ct = sum(Cc)
    t = 0
    for j in range(l):
        t += Cc[j]
        if j >= K:break
        now = t
        if Ct > 0:
            e = (K-j-1)//l
            now +=  Ct*e
        ans = max(ans,now)
print(ans)

Solution (Python):
N, K = map(int, input().split())
P_L = [int(x)-1 for x in input().split()]
C_L = [int(x) for x in input().split()]

ans = float("-Inf")
for s in range(N):
    _s_l = []
    _v = s
    _cumsum = 0
    _ans = float("-Inf")
    while True:
        _nextv = P_L[_v]
        _cumsum += C_L[_nextv]
        _s_l.append(_cumsum)
        _v = _nextv
        if _nextv == s:
            break
    if K <= len(_s_l):
        _ans = max(_s_l[:K])
    else:
        if _s_l[-1] < 0:
            _ans = max(_s_l)
        else:
            _l = len(_s_l)
            if K % _l == 0:
                _ans = max(_s_l[-1] * (K // _l),
                           _s_l[-1] * (K // _l - 1) + max(_s_l))
            else:
                _ans = max(_s_l[-1] * (K // _l) + max(_s_l[:K % _l]),
                           _s_l[-1] * (K // _l - 1) + max(_s_l))
    ans = max(ans, _ans)

print(ans)

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

ans=-float('inf')
for i in range(n):
  T=1
  index=p[i]-1
  T_score=c[index]
  flag=True
  while flag:
    T+=1
    index=p[index]-1
    T_score+=c[index]
    if index==i:
      flag=False
  
  if T>=k:
    score_list=[c[p[i]-1]]+[0]*(k-1)
    index=p[i]-1
    for s in range(1,k):
      index=p[index]-1
      score_list[s]=score_list[s-1]+c[index]
    score=max(score_list)
  else:
    if T_score<=0:
      score_list=[c[p[i]-1]]+[0]*(T-1)
      index=p[i]-1
      for s in range(1,T):       
        index=p[index]-1
        score_list[s]=score_list[s-1]+c[index]        
      score=max(score_list)
    else:
      m1=k//T
      m2=k%T
      score_list=[c[p[i]-1]]+[0]*(T+m2-1)
      index=p[i]-1
      for s in range(1,T+m2):
        index=p[index]-1
        score_list[s]=score_list[s-1]+c[index]
      score=max(score_list)+T_score*(m1-1)
  ans=max(ans,score)
print(ans)

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

def check(start):
    global k
    i = start
    cnt = 0
    score = 0
    cand = []
    while True:
        i = p[i] - 1
        score += c[i]
        cand.append(score)
        cnt += 1
        if i == start:
            break
    res = - 10 ** 10
    if score >= 0:
        for j, candj in enumerate(cand):
            if k - j - 1 >= 0:
                res = max(res, ((k - j - 1) // cnt) * score + candj)
    else:
        for j, candj in enumerate(cand):
            if k - j - 1 >= 0:
                res = max(res, candj)
    return res

ans = - 10 ** 10

for i in range(n):
    ans = max(ans, check(i))

print(ans)

Solution (Python):
n, k = map(int, input().split())
p = list(map(int, input().split()))
p = [_p-1 for _p in p]
c = list(map(int, input().split()))

ans = -float('inf')

visited = [False] * n
ss = []
for i in range(n):
    if visited[i]: continue
    cur = i
    s = []
    while not visited[cur]:
        visited[cur] = True
        s.append(c[cur])
        cur = p[cur]
    ss.append(s)

for s in ss:
    m = len(s)
    cumsum = [0] * (m*2+1)
    for i in range(2*m):
        cumsum[i+1] = cumsum[i] + s[i%m]
    
    amari = [-float('inf')] * m
    for i in range(m):
        for j in range(m):
            amari[j] = max(amari[j], cumsum[i+j] - cumsum[i])
    
    for r in range(0, m):
        if r > k: continue
        q = (k-r)//m
        if r==0 and q==0:
            continue
        
        if cumsum[m] > 0:
            ans = max(ans, amari[r] + cumsum[m]*q)
        elif r > 0:
            ans = max(ans, amari[r])

print(ans)

Solution (Python):
import sys
import numpy as np







def main(N,K,P,C): 


	
	
	
	ans = int(-1e9)		
	

	
	
	cycleIDs = np.full( N, -1, dtype=np.int64 )
	cycleInfs = []


	

	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			currentCycleItemCnt, currentCycleTotal = cycleInfs[ cycleIDs[v] ]
			
		else:
			while True:
				
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					
					cycleInfs.append( (currentCycleItemCnt, currentCycleTotal) )
					cycleID += 1
					break

				
				
				cycleIDs[v] = cycleID

		procCnt = 0
		currentCycleSumTmp = 0

		while True:

			
			
			procCnt += 1
			currentCycleSumTmp += C[v]
			if K < procCnt:
				break

			cycleLoopCnt = 0
			if procCnt < K and 0 < currentCycleTotal:
				cycleLoopCnt = int(( K - procCnt ) // currentCycleItemCnt)

			
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( int(ans), int(tmp) )

			v = P[v]
			if v == n:
				
				break

	print(int(ans))

if sys.argv[-1]=='ONLINE_JUDGE':
	
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','void(i8,i8,i8[:],i8[:])')(main)
	
	cc.compile()
	exit(0)
from my_module import main



if __name__ == "__main__":
	N,K = map(int,input().split())
	P = np.array( input().split(), np.int64 )
	P -= 1
	C = np.array( input().split(), np.int64 )

	main(N,K,P,C)

Solution (Python):
import sys
import numpy as np







def main(N,K,P,C): 


	
	
	ans = -10 ** 9

	
	
	cycleIDs = np.full( N, -1, dtype=np.int64 )
	cycleInfs = []


	

	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			currentCycleItemCnt, currentCycleTotal = cycleInfs[ cycleIDs[v] ]
			
		else:
			while True:
				
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					
					cycleInfs.append( (currentCycleItemCnt, currentCycleTotal) )
					cycleID += 1
					break

				
				
				cycleIDs[v] = cycleID

		procCnt = 0
		currentCycleSumTmp = 0

		while True:

			
			
			procCnt += 1
			currentCycleSumTmp += C[v]
			if K < procCnt:
				break

			cycleLoopCnt = 0
			if procCnt < K and 0 < currentCycleTotal:
				cycleLoopCnt = int(( K - procCnt ) // currentCycleItemCnt)

			
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( int(ans), int(tmp) )

			v = P[v]
			if v == n:
				
				break

	print(int(ans))

if sys.argv[-1]=='ONLINE_JUDGE':
	
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','void(i8,i8,i8[:],i8[:])')(main)
	
	cc.compile()
	exit(0)
from my_module import main



if __name__ == "__main__":
	N,K = map(int,input().split())
	P = np.array( input().split(), np.int64 )
	P -= 1
	C = np.array( input().split(), np.int64 )

	
	main(N,K,P,C)

Solution (Python):
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
A=[]
S=[]
p=2**N-1
for i in range(N):
  if p>>i&1:
    s=i+1
    tmp=[C[i]]
    while s!=P[i]:
      i=P[i]-1
      tmp.append(C[i])
      p^=1<<i
    A.append(tmp)
    S.append(sum(tmp))
ans=-1*(10**9)-1
for i in range(len(A)):
  a=A[i]
  n=len(a)
  s=S[i]
  for j in range(n):
    t=0
    k=n
    if K>n:
      if s > 0:
        k=K%n
        if k==0:
          k=n
          t=s*(K//n-1)
        else:
          k=K%n
          t=s*(K//n)
    else:
      k=K
    for jj in range(j,k+j):
      if jj>=n:
        jj-=n
      t+=a[jj]
      ans=max(ans,t)
    ans=max(ans,t)
print(ans)

Solution (Python):
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
ans = -float('inf')
for i in range(N):
    piece = i+1
    temp = 0
    hoge = []
    
    key = 0
    for j in range(N):
        if j+1 > K:
            key = 1
            break
        piece = P[piece-1]
        temp += C[piece-1]
        
        hoge.append(temp)
        if piece == i+1:
            break
    if key == 1:
        ans = max(ans,max(hoge))
    elif hoge[-1]<=0:
        ans = max(ans,max(hoge))
    else:
        d = K//len(hoge)
        r = K%len(hoge)
        if r != 0:
            peak = max(hoge[-1]*(d-1)+max(hoge[r:]),hoge[-1]*d+max(hoge[:r]))
        else:
            peak = hoge[-1]*(d-1)+max(hoge)
        ans = max(ans,peak)
print(ans)

Solution (Python):

IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
MAX_N = 45000





verbose = False

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

def find_cycle(p, pos):
    cnt = 0
    steps = [0] * (MAX_N+1)
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        path[pos] = True
        cnt += 1
        pos = p[pos]
        if path[pos]: break 
    st = steps.index(pos) 
    return [steps[:st], steps[st:cnt]]


def score(steps, c):
    ret = [0]*len(steps)
    for i in range(len(steps)): ret[i] = c[steps[i]]
    return ret

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    [preclosure_path, closure_path] = find_cycle(P, i)
    if verbose: print('closure found:', closure_path)
    closure_scores = score(closure_path, C)
    preclosure_scores = score(preclosure_path, C)
    closure_score = sum(closure_scores)
    preclosure_len, closure_len = len(preclosure_path), len(closure_path)

    cycles = (K-preclosure_len)//closure_len
    resid = (K-preclosure_len)%closure_len
    if cycles>=1: cycles -= 1
    abbrev = closure_score * cycles
   
    trail = preclosure_scores + closure_scores * 3
    path = preclosure_path + closure_path*3
    if verbose: print('score trail:', trail)
    if verbose: print('path:', preclosure_path + closure_path*3)
    if verbose: print('mark:', mark)
    mark = min(K, len(preclosure_path+closure_path)+resid)
    localmax = max(cumsum(trail[0:mark])) + max(0, closure_score*cycles)
    if verbose: print('localmax:', localmax, 'cycles:', cycles)
    maxsc = max(localmax, maxsc)

    if verbose: print('going greedy')
    for j in range(1, closure_len):
        if K<=mark+j: break
        target = path[j]
        if done[target]: continue
        localmax = max(cumsum(trail[j:mark+j])) + max(0, closure_score*cycles)
        maxsc = max(localmax, maxsc)
        done[target] = True
        if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Solution (Python):
n,k=map(int,input().split())

p=[i-1 for i in list(map(int,input().split()))]
c=list(map(int,input().split()))

ansF=-1000000000000000000
for i in range(n):
    
    check=[False]*n
    
    turns=[]
    
    now=i
    while check[now]==False:
        check[now]=True
        turns.append(now)
        now=p[now]
    
    ans=0
    
    
    spare=turns.index(now)
    if spare>=k:
        for j in range(k):
            ans+=c[turns[j]]
            ansF=max(ans,ansF)
        continue
    for j in range(spare):
        ans+=c[turns[j]]
        ansF=max(ans,ansF)
    turns=turns[spare:]
    spare=k-spare
    
    l=len(turns)
    
    
    x=0
    for j in range(l):
        x+=c[turns[j]]
    
    if spare<=l:
        for j in range(spare):
            ans+=c[turns[j]]
            ansF=max(ans,ansF)
        continue
    
    
    if x>=0:
        ans+=(x*(spare//l-1))
        ansF=max(ans,ansF)
        for j in range(l):
            ans+=c[turns[j]]
            ansF=max(ans,ansF)
        for j in range(spare%l):
            ans+=c[turns[j]]
            ansF=max(ans,ansF)
    
    else:
        for j in range(l):
            ans+=c[turns[j]]
            ansF=max(ans,ansF)
print(ansF)

Solution (Python):
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

ans = -float('inf')
v = []
for n in range(N):
    loop, score = 0, 0
    t = n
    for i in range(min(N, K)):
        n = P[n]-1
        score += C[n]
        ans = max(ans, score)
        if n == t:
            loop = i+1
            break
    v.append((loop, score))

for n in range(N):
    loop, score = v[n]
    if loop > 0 and score > 0:
        r = (K-1)//loop
        nscore = r*score
        for i in range(K-r*loop):
            n = P[n]-1
            nscore += C[n]
            ans = max(nscore, ans)
print(ans)

Solution (Python):
N, K = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
K = K-1
ans = -10**9-1
for h in range(N):
   i = h+1
   start = i
   circle = [c[i-1]]
   i = p[i-1]
   while i != start:
      score = circle[-1] + c[i-1]
      circle.append(score)
      i = p[i-1]
   l=len(circle)
   for j in range(min(l, K+1)):
      if circle[l-1] > 0:
         score = circle[j] + ((K - j)//l)*circle[l-1]
      else:
         score = circle[j]
      ans = max(score, ans)      
print(ans)

Solution (Python):
n,k=map(int,input().split())

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

group_score=[]
checked=[0]*n

for i in range(n):
    if checked[i]==0:
        tmp_group=[]
        tmp=i
        while checked[tmp]==0:
            checked[tmp]=1
            tmp_group.append(score[tmp])
            tmp=p[tmp]-1
        group_score.append(tmp_group)




def calc(k):
    if k==0:
        return 0
    global group
    ans="INF"
    for i in range(len(group)):
        tmp=0
        for j in range(k):
            tmp+=group[(i+j)%len(group)]
            if ans=="INF":
                ans=tmp
            else:
                if ans<tmp:
                    ans=tmp
    return ans

ans=score[0]
for group in group_score:
    
    if len(group)<k:
        cycle=sum(group)
        if cycle>0:
            cycle_sum=cycle*(k//len(group))
            tmp=calc(k%len(group))
            ans=max(ans,cycle_sum+tmp)

            if k//len(group)>=2:
                cycle_sum=cycle*(k//len(group)-1)
                tmp=calc(len(group))
                ans=max(ans,cycle_sum+tmp)
          

        tmp=calc(len(group))
        ans=max(ans,tmp)



    
    else:
        tmp=calc(k)
        ans=max(ans,tmp)

print(ans)