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.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Wrong Answer

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def input():
    return sys.stdin.readline().strip()

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

def main():
    INF = 999999999999999999999999
    MOD = 10**9+7

    n,k = get_nums_l()
    P = [None] + get_nums_l()
    C = [None] + get_nums_l()

    # log(P)
    # log(C)

    ans = -INF

    for start_cell in range(1, n+1):
        # log("start_cell:", start_cell)
        now = start_cell
        count = 0
        score = 0
        history = set()

        # ループの検出
        while now not in history:
            # log(now, count)
            history.add(now)
            now = P[now]
            count += 1
            score += C[now]
        loop_start = now

        # log(score)
        
        # log("loop検出.")

        # ループ突入までの長さを検出
        # ループ突入までのスコアを計算
        init_len = 0
        init_score = 0
        now = start_cell
        while now != loop_start:
            now = P[now]
            init_len += 1
            init_score += C[now]
        loop_len = count - init_len
        
        # 1ループのスコアを計算
        loop_score = score - init_score

        # log(init_len, loop_len)

        if loop_score <= 0:
            # ループでスコアが稼げない場合
            # log("A")
            # 最大n回まで移動してみる
            score2 = 0
            now = start_cell
            for _ in range(min(k, n+1)):
                now = P[now]
                score2 = C[now]
                ans = max(ans, score2)
        else:
            # ループでスコアが稼げる場合
            if k <= init_len:
                # ループ突入以前までしか行けない場合
                # log("B1")
                score2 = 0
                now = start_cell
                for _ in range(k):
                    now = P[now]
                    score2 += C[now]
                    ans = max(ans, score2)
            else:
                # ループしきったあとの端数だけ調整する
                # log("B2")
                loops = (k-init_len)//loop_len

                score2 = init_score + loops * loop_score
                if init_len>0 or loops>0:
                    ans = max(ans, score2)
                hasuu = (k-init_len) % loop_len
                # log(loops, score2, hasuu)
                now = loop_start
                for _ in range(hasuu):
                    now = P[now]
                    score2 += C[now]
                    ans = max(ans, score2)
    print(ans)


main()

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
# from numba import njit

# 公式解説を見てからやった
# 複数サイクルでき、1-K回移動可能
# N < 5000?多分、O(N * 2N)くらいで行けそうに見えるが。。。

# @njit(cache=False)
def main(N,K,P,C): #,ans):


	# XeXは、Float?
	# numbaの場合、intでないとまずいのかもしれないので、そのまま1e9はヤバそう
	# ans = -1e9
	ans = int(1e9)
	# ans = -10 ** 9	# これはOK

	# 一度計算したサイクル情報を一応キャッシュしておく。。。
	# あんまり意味なさそう
	cycleIDs = np.full( N, -1, dtype=np.int64 )
	cycleInfs = []


	# print(P)

	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			currentCycleItemCnt, currentCycleTotal = cycleInfs[ cycleIDs[v] ]
			# print(currentCycleItemCnt, currentCycleTotal)
		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:

			# 頂点vにコマが置かれた時の最高スコアを計算し、
			# これまでの最高スコアを上回ったら、これまでの最高スコアを更新する
			procCnt += 1
			currentCycleSumTmp += C[v]
			if K < procCnt:
				break

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

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, procCnt)
			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 import njit
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','void(i8,i8,i8[:],i8[:])')(main)
	# main=njit(main, cache=True)
	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) #,ans)
	#print(ans)

Submission status: Wrong Answer

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def input():
    return sys.stdin.readline().strip()

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

def main():
    INF = 999999999999999999999999
    MOD = 10**9+7

    n,k = get_nums_l()
    P = [None] + get_nums_l()
    C = [None] + get_nums_l()

    # log(P)
    # log(C)

    ans = -INF

    for start_cell in range(1, n+1):
        # log("start_cell:", start_cell)
        now = start_cell
        count = 0
        score = 0
        history = set()

        # ループの検出
        while now not in history:
            # log(now, count)
            history.add(now)
            now = P[now]
            count += 1
            score += C[now]
        loop_start = now

        # log(score)
        
        # log("loop検出.")

        # ループ突入までの長さを検出
        init_len = 0
        now = start_cell
        while now != loop_start:
            now = P[now]
            init_len += 1
        loop_len = count - init_len

        # log("loop前長さ.")

        # ループ突入までのスコアを計算
        init_score = 0
        now = start_cell
        while now != loop_start:
            now = P[now]
            init_score += C[now]
        
        # log("loop前スコア.")
        
        # 1ループのスコアを計算
        loop_score = score - init_score

        # log(init_len, loop_len)

        if loop_score <= 0:
            # ループでスコアが稼げない場合
            # log("A")
            # 最大n回まで移動してみる
            score2 = 0
            now = start_cell
            for _ in range(min(k, n+1)):
                now = P[now]
                score2 = C[now]
                ans = max(ans, score2)
        else:
            # ループでスコアが稼げる場合
            if k <= init_len:
                # ループ突入以前までしか行けない場合
                # log("B1")
                score2 = 0
                now = start_cell
                for _ in range(k):
                    now = P[now]
                    score2 += C[now]
                    ans = max(ans, score2)
            else:
                # ループしきったあとの端数だけ調整する
                # log("B2")
                loops = (k-init_len)//loop_len

                score2 = init_score + loops * loop_score
                ans = max(ans, score2)
                hasuu = (k-init_len) % loop_len
                # log(loops, score2, hasuu)
                now = loop_start
                for _ in range(hasuu):
                    now = P[now]
                    score2 += C[now]
                    ans = max(ans, score2)
    print(ans)


main()

Submission status: Wrong Answer

Solution code:
import itertools
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()))

	# 計算済み
	used = [ False for _ in range(N) ]

	# print(P)

	ans = -10 ** 9
	cycleID = 0

	for n in range(N):

		v = n

		if used[v]:
			# 枝刈り
			continue

		currentCycleItemCnt = 0
		currentCycleCosts = []
		currentCycleTotalScore = 0

		while True:
			# 全頂点について、属するサイクルを計算する
			currentCycleItemCnt += 1
			currentCycleCosts.append( C[v] )
			currentCycleTotalScore += C[v]

			# 実際には少し↓で計算するが、スコアmax値計算済みとみなす
			used[v] = True
			v = P[v]
			if v == n:
				# サイクル発見
				break

		# ループを含めない最大の処理回数
		procCnt = K % currentCycleItemCnt
		# ただし、割り切れる場合も、1サイクル分は処理するものとする
		# (1回以上はやらなければならないのを考慮？)
		if procCnt == 0:
			procCnt = currentCycleItemCnt
		# procCnt = min( K, procCnt )

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		cycleLoopCnt = 0
		if currentCycleTotalScore > 0:
			# その時、ループが発生した方がスコアが高くなる場合
			# ループ回数を計算
			cycleLoopCnt =  ( K - procCnt ) // currentCycleItemCnt
			# print("K - procCnt=", K - procCnt, "currentCycleItemCnt=", currentCycleItemCnt)
			# print("cycleLoopCnt=", cycleLoopCnt)


		# このサイクル内での最大スコア
		currentCycleMaxScore = -10 ** 9

		# このサイクルに属する全頂点分をまとめて計算する
		# まず、ループが発生しない分まで計算
		npCosts = np.array( currentCycleCosts )

		for i in range(currentCycleItemCnt):
			# 累積和
			acc = list(itertools.accumulate( np.roll( npCosts, i )[:procCnt] ) )

			# print(i, acc)#[:procCnt])
			currentCycleMaxScore = max( currentCycleMaxScore, max( acc ) )
		# print("currentCycleMaxScore=",currentCycleMaxScore)


		currentCycleMaxScore += cycleLoopCnt * currentCycleTotalScore
		# print("v=", v, "currentCycleItemCnt=", currentCycleItemCnt, "procCnt, cycleLoopCnt, currentCycleMaxScore,currentCycleTotalScore=", procCnt, cycleLoopCnt, currentCycleMaxScore,currentCycleTotalScore)

		ans = max( ans, currentCycleMaxScore )

	print(ans)

Submission status: Wrong Answer

Solution code:
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:
        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)

Submission status: Wrong Answer

Solution code:
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
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

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
        break
        pos = p[pos]
        if path[pos]: break # found closure
#    st = steps.index(pos) # start of closure
    st = 0
    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)

Submission status: Wrong Answer

Solution code:
#TLE and WA

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

dp=[[ -mod for i in range(k)]for j in range(n)]

for i in range (n):
    dp[p[i]-1][k-1]=c[p[i]-1]

ans=-mod

for i in range (n):
    for j in range(k-1,0,-1):
        np=p[i]-1
        dp[np][j-1]=dp[i][j]+c[np]
        ans=max(ans,dp[i][j],dp[np][j-1])
        
print (ans)

Submission status: Wrong Answer

Solution code:

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 = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

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
        break
        path[pos] = True
        pos = p[pos]
        cnt += 1
        if path[pos]: break # found closure
    st = steps.index(pos) # start of closure
    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)

Submission status: Wrong Answer

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

ans = -1e9
for i in range(N):
    town = list()
    town.append(i)

    nxt = P[i] - 1
    score = 0
    while nxt != i:
        town.append(nxt)
        score += C[nxt]
        nxt = P[nxt] - 1
    score += C[i]
    
    loop_len = len(town)
    for j in range(loop_len):
        ans_tmp = 0

        if score > 0:
            if K % loop_len >= j:
                ans_tmp += (K//loop_len)*score 

                ind = 0
                now = i
                while ind < j:
                    ans_tmp += C[P[now] - 1]
                    now = P[now] - 1
                    ind += 1
            else:
                loop_times = K // loop_len - 1
                ans_tmp += loop_times * score 
                last_loop = K - loop_times * loop_len

                ind = 0
                now = i
                while ind < j:
                    if ind > last_loop:
                        ans_tmp = -1e9
                        break

                    ans_tmp += C[P[now] - 1]
                    now = P[now] - 1
                    ind += 1
        else:
            ind = 0
            now = i
            fin = j
            if fin == 0:
                fin = loop_len
            while ind < fin:
                if ind > K:
                    ans_tmp = -1e9
                    break

                ans_tmp += C[P[now] - 1]
                now = P[now] - 1
                ind += 1
        
        # print(i, j, town, score, ans_tmp)
        ans = max(ans, ans_tmp)

print(ans)

Submission status: Wrong Answer

Solution code:

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 = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

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
#        pos = p[pos]
#        cnt += 1
#        if path[pos]:
#            break # found closure
#        else:
#            path[pos] = True
#    st = steps.index(pos)-1 # start of closure
    st = 3
    return [steps[:st], steps[st:cnt-1]]


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)

Submission status: Wrong Answer

Solution code:

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 = 1000
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

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
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        pos = p[pos]
        cnt += 1
        if path[pos]:
            break # found closure
        else:
            path[pos] = True
    st = steps.index(pos)-1 # start of closure
    return [steps[:st], steps[st:cnt-1]]

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)

Submission status: Wrong Answer

Solution code:
#import random
#import itertools

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 = 1000
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

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
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        pos = p[pos]
        cnt += 1
        if path[pos]:
            break # found closure
        else:
            path[pos] = True
    st = steps.index(pos)-1 # start of closure
    return [steps[:st], steps[st:cnt-1]]

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)