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:
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)
  if first != P[x]:
    cnt += 1
    score += C[x]
    x = P[x]
  else:
    cnt += 1
    score += C[x]
    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-1)]
  for x in loop_mem:
    tmp = 0
    for j in range(cnt - 1):
      tmp += C[x]
      imax[j] = max(imax[j], tmp)
      x = P[x]
  for j in range(1, cnt-1):
    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-1], 0), score * (M-1) + imax[-1])
    else:
      tmp = imax[m-1]
      ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
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)
  if first != P[x]:
    cnt += 1
    score += C[x]
    x = P[x]
  else:
    cnt += 1
    score += C[x]
    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-1)]
  for x in loop_mem:
    tmp = 0
    for j in range(cnt - 1):
      tmp += C[x]
      imax[j] = max(imax[j], tmp)
      x = P[x]
  for j in range(1, cnt-1):
    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-1], 0), score * (M-1) + imax[-1])
    else:
      tmp = imax[m-1]
  ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

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


def make_group_shim0(x, check):
    lis = [x - 1]
    while not P[x - 1] - 1 in lis:
        lis.append(P[x - 1] - 1)
        check.append(P[x - 1] - 1)
        x = P[x - 1]
    return lis


Big_lis = []
check = []
i = 1
while i < NN:
    if i - 1 not in check:
        Big_lis.append(make_group_shim0(i, check))
    i += 1


LIST_no_kazu = len(Big_lis)
ans1 = -100000000
ans2 = -10000000000
for i in range(LIST_no_kazu):
    N = len(Big_lis[i])

    k_hasuu = K % N
    k_kaisu = K // N
    summ = 0

    for j in Big_lis[i]:
        summ += C[j]

    dp = [[0 for i in range(NN)] for j in range(K)]

    for j in range(N):
        if j in Big_lis[i]:
            dp[0][P[j] - 1] = C[P[j] - 1]
            ans1 = max(ans1, dp[0][P[j] - 1])

    for k in range(1, K):
        for j in Big_lis[i]:
            dp[k][P[j] - 1] = dp[k - 1][j] + C[P[j] - 1]
            ans1 = max(ans1, dp[k][P[j] - 1])
    ans2 = max(ans2, ans1)

print(ans2)

Submission status: Wrong Answer

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


def make_group_shim0(x, check):
    lis = [x - 1]
    while not P[x - 1] - 1 in lis:
        lis.append(P[x - 1] - 1)
        check.append(P[x - 1] - 1)
        x = P[x - 1]
    return lis


Big_lis = []
check = []
i = 1
while i < NN:
    if i - 1 not in check:
        Big_lis.append(make_group_shim0(i, check))
    i += 1
print(Big_lis)


LIST_no_kazu = len(Big_lis)
ans1 = -100000000
ans2 = -10000000000
for i in range(LIST_no_kazu):
    N = len(Big_lis[i])

    k_hasuu = K % N
    k_kaisu = K // N
    summ = 0

    for j in Big_lis[i]:
        summ += C[j]

    dp = [[0 for i in range(NN)] for j in range(K)]

    for j in range(N):
        if j in Big_lis[i]:
            dp[0][P[j] - 1] = C[P[j] - 1]
            ans1 = max(ans1, dp[0][P[j] - 1])

    for k in range(1, K):
        for j in Big_lis[i]:
            dp[k][P[j] - 1] = dp[k - 1][j] + C[P[j] - 1]
            ans1 = max(ans1, dp[k][P[j] - 1])
    ans2 = max(ans2, ans1)

print(ans2)

Submission status: Wrong Answer

Solution code:
from sys import stdin
from math import inf
input=stdin.readline
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):
    m=1
    cur=arr[i]
    co=cost[cur]
    l=[0,co]
    ma = max(ma, l[-1])
    while(m<k and cur!=i):
        cur=arr[cur]
        co=cost[cur]
        l.append(l[-1]+co)
        m += 1
        ma=max(ma,l[-1])
    if m<=k:
        for j in range(k%m+1):
            ma = max(ma, l[-1] * (k//m) + l[j])
        ma=max(ma,l[-1]*(k//m-1)+max(l))
print(ma)

'''
3 4
3 1 2
-1 3 -1
'''

Submission status: Wrong Answer

Solution code:
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])
print(ma)

Submission status: Wrong Answer

Solution code:
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(True):
        if cur not in se:
            se.add(cur)
            co=cost[cur]
            cur=arr[cur]
            pref.append(pref[-1]+co)
            ma=max(ma,pref[-1])
            f+=1
        else:
            break
    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])
print(ma)

Submission status: Wrong Answer

Solution code:
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(True):
        if cur not in se:
            se.add(cur)
            co=cost[cur]
            cur=arr[cur]
            pref.append(pref[-1]+co)
            ma=max(ma,pref[-1])
            f+=1
        else:
            break
    ans=pref[-1]*(k//f)
    for j in range(k%f+1):
        ma=max(ma,ans+pref[j])
print(ma)

Submission status: Wrong Answer

Solution code:
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(True):
        if cur not in se:
            se.add(cur)
            co=cost[cur]
            cur=arr[cur]
            pref.append(pref[-1]+co)
            ma=max(ma,pref[-1])
            f+=1
        else:
            break
        if k<=f:
            break
    
    if k>=f:
        ans=pref[-1]*(k//f)
        for j in range(k%f+1):
            ma=max(ma,ans+pref[j])
print(ma)

Submission status: Wrong Answer

Solution code:
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(True):
        if cur not in se:
            se.add(i)
            co=cost[cur]
            cur=arr[cur]
            pref.append(pref[-1]+co)
            ma=max(ma,pref[-1])
            f+=1
        else:
            break
        if k<=f:
            break

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

Submission status: Wrong Answer

Solution code:
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(m):
        x = (k - j - 1) // m
        ans = max(ans, s[j], s[j] + s[-1] * x)

print(ans)

Submission status: Wrong Answer

Solution code:
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=max(acm[:min(k,loop)])
    
    ans=max(cur,ans)
    
print(ans)

Submission status: Wrong Answer

Solution code:
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):   # 初めの場所をinitとする
    score = [0]  # k回移動後のスコア
    i = init
    for k in range(1, K + 1):
        i = P[i]  # k回移動後に着くところ
        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)

Submission status: Wrong Answer

Solution code:
# やっとACしたのを少しリファクタ
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):   # 初めの場所をinitとする
    score = [0]  # k回移動後のスコア
    i = init
    for k in range(1, K + 1):
        i = P[i]  # k回移動後に着くところ
        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)

Submission status: Wrong Answer

Solution code:
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
    
    cur=max(acm[:min(loop-1,k)])
    if k>=loop:
        cur=max(cur,k//loop*acm[-1]+(max(max(acm[:k%loop]),0) if k%loop>0 else 0))
    ans=max(ans,cur)
print(ans)

Submission status: Wrong Answer

Solution code:
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
    
    cur=max(acm[:min(loop-1,k)])
    cur=max(cur,k//loop*acm[-1]+(max(max(acm[:k%loop]),0) if k%loop>0 else 0))
    ans=max(ans,cur)
print(ans)

Submission status: Wrong Answer

Solution code:
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
    
    cur=max(acm[:min(loop-1,k)])
    cur=max(cur,k//loop*acm[-1]+(max(acm[:k%loop]) if k%loop>0 else 0))
    ans=max(ans,cur)
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate 

N, K = list(map(int, input().split()))
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))

ans = -10**9-1
seen = [False]*N
for i in range(N):
    if seen[i]:
        continue
    loop = []
    now = i
    while seen[now] == False:
        seen[now] = True
        loop.append(C[now])
        now = P[now]
    loop_size = len(loop)
    loop_score = sum(loop)
    cumsum = [0]+list(accumulate(loop+loop))
    for j in range(1, loop_size+1):
        for l in range(loop_size+1):
            r = l+j
            subseq = cumsum[r] - cumsum[l]
            ans = max(ans, subseq, subseq+loop_score*((K-j)//loop_size))
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate 

N, K = list(map(int, input().split()))
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))

ans = -10**9-1
seen = [False]*N
for i in range(N):
    if seen[i]:
        continue
    loop = []
    now = i
    while seen[now] == False:
        seen[now] = True
        loop.append(C[now])
        now = P[now]
    loop_size = len(loop)
    loop_score = sum(loop)
    cumsum = list(accumulate(loop+loop))
    for j in range(1, loop_size+1):
        for l in range(loop_size):
            r = l+j
            subseq = cumsum[r] - cumsum[l]
            ans = max(ans, subseq, subseq+loop_score*((K-j)//loop_size))
print(ans)

Submission status: Wrong Answer

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	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 )
					# ただし、割り切れる場合も、1サイクル分は処理するものとする
					# (1回以上はやらなければならないのを考慮？)
					if procCnt == 0:
						procCnt = len( currentCycleCosts )

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



	# scores = []
	# procCnt = 0
	ans = -10 ** 9
	for procCnt, currentCycleCosts in cycleInfs:

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		loopScore = 0
		if np.sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
			loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			# scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() + loopScore )
			ans = max( ans, np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() + loopScore )


	print(ans)
	# print(max(scores))

Submission status: Wrong Answer

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	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 )
					# ただし、割り切れる場合も、1サイクル分は処理するものとする
					# (1回以上はやらなければならないのを考慮？)
					if procCnt == 0:
						procCnt = len( currentCycleCosts )

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



	scores = []
	# procCnt = 0
	for procCnt, currentCycleCosts in cycleInfs:

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		loopScore = 0
		if np.sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
			loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			if 0 < loopScore:
				# acc = list(itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )
				scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() + loopScore )
			else:
				scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() )


	print(max(scores))

Submission status: Wrong Answer

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	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 )
					# ただし、割り切れる場合も、1サイクル分は処理するものとする
					# (1回以上はやらなければならないのを考慮？)
					if procCnt == 0:
						procCnt = len( currentCycleCosts )

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



	scores = []
	# loopScore = 0
	# procCnt = 0
	for procCnt, currentCycleCosts in cycleInfs:

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		# if np.sum(currentCycleCosts) > 0:
		# 	cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
		# 	loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			if np.sum(currentCycleCosts) > 0:
				# acc = list(itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )
				scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() + (( K - procCnt ) // currentCycleCosts.size) * np.sum(currentCycleCosts) )
			else:
				scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() )


	print(max(scores))

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	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 )
					# ただし、割り切れる場合も、1サイクル分は処理するものとする
					# (1回以上はやらなければならないのを考慮？)
					if procCnt == 0:
						procCnt = len( currentCycleCosts )

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



	scores = []
	# loopScore = 0
	# procCnt = 0
	for procCnt, currentCycleCosts in cycleInfs:

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		# if np.sum(currentCycleCosts) > 0:
		# 	cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
		# 	loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			if np.sum(currentCycleCosts) > 0:
				# acc = list(itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )
				scores.append( max( np.roll( currentCycleCosts, i )[:procCnt].cumsum() ) + (( K - procCnt ) // currentCycleCosts.size) * np.sum(currentCycleCosts) )
			else:
				scores.append( max( np.roll( currentCycleCosts, i )[:procCnt].cumsum() ) )


	print(max(scores))

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	cycleIDs = np.full( N, -1, np.int64 )
	cycleInfs = []
	cycleID = 0
	procCnt = 0

	for n in range(N):
		v = n

		if cycleIDs[n] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					# サイクル終了
					# ループを含めない最大の処理回数
					procCnt = K % len( currentCycleCosts )
					# ただし、割り切れる場合も、1サイクル分は処理するものとする
					# (1回以上はやらなければならないのを考慮？)
					if procCnt == 0:
						procCnt = len( currentCycleCosts )

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



	scores = []
	loopScore = 0
	procCnt = 0
	for procCnt, currentCycleCosts in cycleInfs:

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		# if np.sum(currentCycleCosts) > 0:
		# 	cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
		# 	loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			if np.sum(currentCycleCosts) > 0:
				# acc = list(itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )
				scores.append( max( itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) ) + (( K - procCnt ) // currentCycleCosts.size) * np.sum(currentCycleCosts) )
			else:
				scores.append( max( itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )  )


	print(max(scores))

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	cycleIDs = np.full( N, -1, np.int64 )
	cycleInfs = []
	cycleID = 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 v == n:
					# サイクル発見
					cycleInfs.append( np.array( currentCycleCosts ) )
					cycleID += 1
					break


	scores = []
	loopScore = 0
	procCnt = 0
	for currentCycleCosts in cycleInfs:

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

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		# if np.sum(currentCycleCosts) > 0:
		# 	cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
		# 	loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			if np.sum(currentCycleCosts) > 0:
				# acc = list(itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )
				scores.append( max( itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) ) + (( K - procCnt ) // currentCycleCosts.size) * np.sum(currentCycleCosts) )
			else:
				scores.append( max( itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )  )


	print(max(scores))

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	cycleIDs = np.full( N, -1, np.int64 )
	cycleInfs = []
	cycleID = 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 v == n:
					# サイクル発見
					cycleInfs.append( np.array( currentCycleCosts ) )
					cycleID += 1
					break


	scores = []
	loopScore = 0
	procCnt = 0
	for currentCycleCosts in cycleInfs:

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

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		if np.sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
			loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			# 累積和
			# acc = list(itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )
			scores.append( max( itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) ) + loopScore )

	print(max(scores))

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