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

# 公式解説を見てからやった
# 複数サイクルでき、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 = ( K - procCnt ) // currentCycleItemCnt

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, procCnt)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( ans, 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

# 公式解説を見てからやった
# 複数サイクルでき、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 = ( K - procCnt ) // currentCycleItemCnt

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, procCnt)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( ans, tmp )

			v = P[v]
			if v == n:
				# サイクル終了
				break

	return ans
	# print(ans)

if sys.argv[-1]=='ONLINE_JUDGE':
	# from numba import njit
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','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 )

	ans=main(N,K,P,C)
	print(ans)

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

	# print(P)

	ans = -1e10
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

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

			v = P[v]
			if v == n:
				# サイクル発見
				break

		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 = ( K - procCnt ) // currentCycleItemCnt

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, procCnt)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( ans, tmp )

			v = P[v]
			if v == n:
				# サイクル終了
				break

	return ans
	# print(ans)

if sys.argv[-1]=='ONLINE_JUDGE':
	# from numba import njit
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','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 )

	ans=main(N,K,P,C)
	print(ans)

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 = -1e10
	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 = ( K - procCnt ) // currentCycleItemCnt

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, procCnt)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( ans, tmp )

			v = P[v]
			if v == n:
				# サイクル終了
				break

	return ans
	# print(ans)

if sys.argv[-1]=='ONLINE_JUDGE':
	# from numba import njit
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','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 )

	ans=main(N,K,P,C)
	print(ans)

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, np.int64 )
	cycleInfs = []


	# print(P)

	ans = -1e10
	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 = ( K - procCnt ) // currentCycleItemCnt

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, procCnt)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( ans, tmp )

			v = P[v]
			if v == n:
				# サイクル終了
				break

	return ans
	# print(ans)

if sys.argv[-1]=='ONLINE_JUDGE':
	from numba import njit
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','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 )

	ans=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()))
for i in range(N):
    P[i] -= 1
C = list(map(int,input().split()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    for j in range(k):
        val += d[j]
        ans = max(ans,val)


    if K >= 2*len(d):
        val = (K//len(d)-1) * sum(d)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)

print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
for i in range(N):
    P[i] -= 1
C = list(map(int,input().split()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    for j in range(k):
        val += d[j]
        ans = max(ans,val)


    if K > len(d):
        val = (K//len(d)-1) * sum(d)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N,K = LMIIS()
    P = list(map(lambda x: int(x)-1,input().split()))
    C = LMIIS()
    score_sets = []
    used = [False]*N
    tmp = P[0]
    for i in range(N):
        if not used[i]:
            tmp = i
            score_set = []
            while not used[tmp]:
                used[tmp] = True
                tmp = P[tmp]
                score_set.append(C[tmp])
            score_sets.append(score_set)
        
    ans = -INF
    for score_set in score_sets:
        # 合計が最大になる区間を探す
        len_set = len(score_set)
        sum_score_set_real = sum(score_set)
        sum_score_set = max(0,sum_score_set_real)


        
        for i in range(len_set):
            cum_sum_1 = 0
            for j in range(i,min(len_set, i+K)):
                cum_sum_1 += score_set[j]
                num_move = j-i+1
                tmp_max = cum_sum_1 + (K - num_move) // len_set * sum_score_set
                ans = max(ans, tmp_max)
        for i in range(1,len_set-1):
            cum_sum_2 = sum_score_set_real
            for j in range(max(i,len_set-1-(K-i)),len_set-1):
                cum_sum_2 -= score_set[j]
                num_move = len_set - (j-i+1)
                tmp_max = cum_sum_2 + (K - num_move) // len_set * sum_score_set
                ans = max(ans,tmp_max)






        
                
    print(ans)

    #3 10
    #1 2 3
    #-20 11 10
    #10回回る：1*3+1=4
    #8回: 1*2+11+10=23

# 3 10
# 1 2 3
# -20 11 10
    
main()

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
for i in range(N):
    P[i] -= 1
C = list(map(int,input().split()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    for j in range(k):
        val += d[j]
        ans = max(ans,val)




    if K > len(d):
        val = (K//len(d)-1) * sum(d)
        ans = max(ans,val)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)
            #print(j)
            #print(val,i,j)
        #print(K//len(d)-1,len(d),K)

print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -10**20
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cum = list(itertools.accumulate(scores * 2))
    st = SegmentTree(cum, max, -10**20)
    cycle, residue = divmod(K, cyclelen)
    ans = max([ans] + [
        st.query(start2 + 1, start2 + 1 + min(cyclelen, K)) - cum[start2]
        for start2 in range(cyclelen)
    ])
    if cum[-1] > 0 and cycle > 0:
        v = cum[-1] * cycle // 2 + max(
            st.query(0, start2 + residue + 1) - cum[start2]
            for start2 in range(cyclelen))
        ans = max(ans, v)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for i in range(1, N+1):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (True, circle_length, circle_score)
        if i == K:
            return (False, K, -10**10)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for i in range(1, circle_length+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            return max_score
        if i == K:
            return max_score
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = 0
    tmp_score = 0
    for i in range(1, (K%circle_length)+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            return max_score + tmp_max_score
        if i == K:
            return max_score + tmp_max_score
    if K%circle_length == 0:
        return max_score
    return max_score + tmp_max_score

tot_max = -10**10
for i in range(N):
    is_circle, circle_length, circle_score = f(i)
    max_score = f1(i, circle_length)
    if is_circle and circle_score > 0:
        max_score2 = f2(i, circle_length, circle_score)
        if max_score2 > max_score:
            max_score = max_score2
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for i in range(1, N+1):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (True, circle_length, circle_score)
        if i == K:
            return (False, K, -10**10)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for i in range(1, circle_length+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = 0
    tmp_score = 0
    for i in range(1, (K%circle_length)+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score + tmp_max_score
    if K%circle_length == 0:
        return max_score
    return max_score + tmp_max_score

tot_max = -10**10
for i in range(N):
    is_circle, circle_length, circle_score = f(i)
    max_score = f1(i, circle_length)
    if is_circle and circle_score > 0:
        max_score2 = f2(i, circle_length, circle_score)
        if max_score2 > max_score:
            max_score = max_score2
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for i in range(1, N+1):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (True, circle_length, circle_score)
        if i == K:
            return (False, 6000, -10**10)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for i in range(1, circle_length+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = 0
    tmp_score = 0
    for i in range(1, (K%circle_length)+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score + tmp_max_score
    if K%circle_length == 0:
        return max_score
    return max_score + tmp_max_score

tot_max = -10**10
for i in range(N):
    is_circle, circle_length, circle_score = f(i)
    max_score = f1(i, circle_length)
    if is_circle and circle_score > 0:
        max_score2 = f2(i, circle_length, circle_score)
        if max_score2 > max_score:
            max_score = max_score2
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

Solution code:
import itertools
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -10**20
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cum = list(itertools.accumulate(scores * 2))
    st = SegmentTree(cum, max, -10**20)
    cycle, residue = divmod(K, cyclelen)
    if cum[-1] > 0 and cycle > 0:
        v1 = cum[-1] * (cycle - 1) // 2 + max(
            st.query(start2, start2 + cyclelen + 1) - cum[start2]
            for start2 in range(cyclelen))
        v2 = cum[-1] * cycle // 2 + max(
            st.query(start2, start2 + residue + 1) - cum[start2]
            for start2 in range(cyclelen))
        ans = max([ans, v1, v2])
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for i in range(1, N+1):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (True, circle_length, circle_score)
        if i == K:
            return (False, 6000, -10**10)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for i in range(1, circle_length+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = -10**10
    tmp_score = 0
    for i in range(1, (K%circle_length)+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score + tmp_max_score
    if K%circle_length == 0:
        return max_score
    return max_score + tmp_max_score

tot_max = -10**10
for i in range(N):
    is_circle, circle_length, circle_score = f(i)
    max_score = f1(i, circle_length)
    if is_circle and circle_score > 0:
        max_score2 = f2(i, circle_length, circle_score)
        if max_score2 > max_score:
            max_score = max_score2
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for i in range(1, N+1):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (True, circle_length, circle_score)
        if i == K:
            return (False, 6000, -10**10)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for i in range(1, circle_length+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = -10**10
    tmp_score = 0
    for i in range(1, (K%circle_length)+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score + tmp_max_score
    if K%circle_length == 0:
        return max_score
    return max_score + tmp_max_score

tot_max = -10**10
for i in range(N):
    is_circle, circle_length, circle_score = f(i)
    max_score = f1(i, circle_length)
    if is_circle:
        max_score2 = f2(i, circle_length, circle_score)
        if max_score2 > max_score:
            max_score = max_score2
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for i in range(1, N+1):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (True, circle_length, circle_score)
        if i == K:
            return (False, 6000, -10**10)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for i in range(1, circle_length+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = -10**10
    tmp_score = 0
    for _ in range(1, (K%circle_length)+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score + tmp_max_score
    return max_score + tmp_max_score

tot_max = -10**10
for i in range(N):
    is_circle, circle_length, circle_score = f(i)
    max_score = f1(i, circle_length)
    if is_circle:
        max_score2 = f2(i, circle_length, circle_score)
        if max_score2 > max_score:
            max_score = max_score2
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)