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 sys
import numpy as np
# from numba import njit

# @njit(cache=True)
def calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			continue
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleIDs[v] = cycleID
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID


def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e19

	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		procCnt = 0
		currentCycleSumTmp = 0

		for _ in range(currentCycleItemCnt):
			# 頂点vにコマが置かれた時の最高スコアを計算し、
			# これまでの最高スコアを上回ったら、これまでの最高スコアを更新する
			# numbaにするとこの辺の処理の値が変になってるきがする。。。？
			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, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( int(ans), int(tmp) )

			# if P[v] == n:
				# サイクル終了
				# break
			# NOTES: (多分)通常のpythonだとこの取得だけでTLEする模様。。。
			# v = P[v]

	print(int(ans))

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



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 )

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

	calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)

	# print(cycleItemCnts)


	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#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()))


ans = -1e18

for i in range(n):
    now = i
    score = []
    while True:
        now = p[now] - 1
        score.append(c[now])
        if now == i:
            break
    print(score)
    loopsum = sum(score)
    if loopsum <= 0:
        point = 0
        for j in range(len(score)):
            if j > k - 1:
                break 
            point = point + score[j]
            ans = max(ans,point)
    else:
        point = 0      
        for j in range(len(score)-1):
            if j > k - 1:
                break
            point = point + score[j]
            loopnum = (k - (j + 1))//len(score)
            ans = max(ans,point+loopnum*loopsum)
print(ans)

Submission status: Wrong Answer

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

# @njit(cache=True)
def calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			continue
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleIDs[v] = cycleID
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID


def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e19

	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		procCnt = 0
		currentCycleSumTmp = 0

		while True:
		
			# 頂点vにコマが置かれた時の最高スコアを計算し、
			# これまでの最高スコアを上回ったら、これまでの最高スコアを更新する
			# numbaにするとこの辺の処理の値が変になってるきがする。。。？
			# 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, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
			# tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			# ans = max( int(ans), int(tmp) )

			# NOTES: (多分)通常のpythonだとこの取得だけでTLEする模様。。。
			if P[v] == n:
				# サイクル終了
				break
			v = P[v]

	print(int(ans))

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



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 )

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

	calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)

	# print(cycleItemCnts)


	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#print(ans)

Submission status: Wrong Answer

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

# @njit(cache=True)
def calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			continue
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleIDs[v] = cycleID
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID


def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e19

	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		procCnt = 0
		currentCycleSumTmp = 0

		for _ in range(N):
			pass
		# while True:
			# NOTES: (多分)通常のpythonだとこのループだけでTLEする模様。。。

			# 頂点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, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
			# 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('calcCycle','void(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:])')(calcCycle)
	# cc.export('main','void(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:])')(main)
	# main=njit(main, cache=True)
	cc.compile()
	exit(0)
# from my_module import main,calcCycle
from my_module import calcCycle



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 )

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

	calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)

	# print(cycleItemCnts)


	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#print(ans)

Submission status: Wrong Answer

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

# @njit(cache=True)
def calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			continue
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleIDs[v] = cycleID
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID


def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e19

	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		procCnt = 0
		currentCycleSumTmp = 0

		# while True:
		# 	# NOTES: (多分)通常のpythonだとこのループだけでTLEする模様。。。

		# 	# 頂点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, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
		# 	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('calcCycle','void(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:])')(calcCycle)
	# cc.export('main','void(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:])')(main)
	# main=njit(main, cache=True)
	cc.compile()
	exit(0)
# from my_module import main,calcCycle
from my_module import calcCycle



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 )

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

	calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)

	# print(cycleItemCnts)


	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#print(ans)

Submission status: Wrong Answer

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

# @njit(cache=True)
def calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			continue
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleIDs[v] = cycleID
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID


def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e19

	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		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, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
			# 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('calcCycle','void(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:])')(calcCycle)
	# cc.export('main','void(i8,i8,i8[:],i8[:],i8[:],i8[:],i8[:])')(main)
	# main=njit(main, cache=True)
	cc.compile()
	exit(0)
from my_module import calcCycle



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 )

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

	calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)

	# print(cycleItemCnts)


	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#print(ans)

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=True)
def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e19

	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		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, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
			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[:],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 )

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

	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			continue
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleIDs[v] = cycleID
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID


	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#print(ans)

Submission status: Wrong Answer

Solution code:
import sys

class SWAG:
    def __init__(self):
        self.fold_l = []
        self.r = []
        self.fold_r = ~(1 << 60)
    def push(self, a):
        if self.fold_r < a:
            self.fold_r = a
        self.r.append(a)
    def pop(self):
        if not self.fold_l:
            self.r.reverse()
            self.fold_l = self.r
            self.r = []
            self.fold_r = ~(1 << 60)
            fold_l = self.fold_l
            for i in range(len(fold_l) - 1):
                if fold_l[i + 1] < fold_l[i]:
                    fold_l[i + 1] = fold_l[i]
        self.fold_l.pop()
    def get(self):
        if not self.fold_l:
            return self.fold_r
        elif not self.r:
            return self.fold_l[-1]
        else:
            return max(self.fold_l[-1], self.fold_r)

n, k = map(int, input().split())
p = [*map(int, input().split())]
c = [*map(int, input().split())]
for i in range(n):
    p[i] -= 1

if max(c) < 0:
    print(max(c))
    sys.exit()

ans = 0
used = [False] * n
for i in range(n):
    if used[i]:
        continue

    # ループを取り出す
    loop = []
    at = i
    while not used[at]:
        loop.append(c[at])
        used[at] = True
        at = p[at]

    siz = len(loop)
    cusum = [0] + loop * 3
    for i in range(siz * 3):
        cusum[i + 1] += cusum[i]
    sum = cusum[siz]

    # k % siz 回以下での最大 -> 累積和にスライド最大値
    d = k % siz
    swag = SWAG()
    for i in range(d):
        swag.push(cusum[i])
    for i in range(siz):
        swag.push(cusum[d + i])
        ans = max(ans, swag.get() - cusum[i] + sum * (k // siz))
        swag.pop()

    if k < siz:
        continue

    # k % siz + siz 回以下での最大
    d = k % siz + siz
    swag = SWAG()
    for i in range(d):
        swag.push(cusum[i])
    for i in range(siz):
        swag.push(cusum[d + i])
        ans = max(ans, swag.get() - cusum[i] + sum * (k // siz - 1))
        swag.pop()

print(ans)

Submission status: Wrong Answer

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

# @njit(cache=True)
def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e19

	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		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[:],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 )

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

	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			break
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID

	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#print(ans)

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


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


	# print(P)

	ans = -1e19
	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)
	#print(ans)

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=True)
def main(N,K,P,C):


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


	# print(P)

	ans = -1e19
	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)
	#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()))

route = {}
point = {}

for idx, p in enumerate(P):
    route[idx+1] = p
    point[p] = C[p-1]

all_max = -float('inf')
for origin_start in range(1, N+1):
    visit = set()
    visit.add(origin_start)
    now_point = 0
    max_point = -float('inf')
    start = origin_start
    for k in range(K):
        now_point += point[start]
        max_point = max(max_point, now_point)
        start = route[start]
        if start in visit:
            roup_count = k + 1
            if now_point >= 0 and K // roup_count > 0:
                now_point *= (K // roup_count)
                start = origin_start
                for _ in range(K % roup_count):
                    now_point += point[start]
                    max_point = max(max_point, now_point)
                    start = route[start]
            break
        visit.add(start)

    all_max = max(max_point, all_max)
print(all_max)

Submission status: Wrong Answer

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

route = {}
point = {}

for idx, p in enumerate(P):
    route[idx+1] = p
    point[p] = C[p-1]

all_max = -float('inf')
for origin_start in range(1, N+1):
    visit = set()
    visit.add(origin_start)
    now_point = 0
    max_point = -float('inf')
    start = origin_start
    # print(start)
    for k in range(K):
        now_point += point[start]
        max_point = max(max_point, now_point)
        start = route[start]
        if start in visit:
            roup_count = k + 1
            if now_point >= 0:
                now_point *= (K // roup_count)
                start = origin_start
                for _ in range(K % roup_count):
                    now_point += point[start]
                    max_point = max(max_point, now_point)
                    start = route[start]
            break
        visit.add(start)
    # print(k, now_point, start, K % k)
    # roup_count = k + 1
    # if now_point >= 0:
    #     now_point *= (K // roup_count)
    #     start = origin_start
    #     for k in range(K % roup_count):
    #         now_point += point[start]
    #         max_point = max(max_point, now_point)
    #         start = route[start]
    # print(k, start, now_point)

    all_max = max(max_point, all_max)
print(all_max)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

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

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


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


	# print(P)

	ans = -1e19
	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)
	#print(ans)