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: Runtime Error

Solution code:
#D - Moving_piece
N,K = map(int,input().split())
P =[]
C =[]
P = list(map(int,input().split()))
C = list(map(int,input().split()))

score_output = -1000000010
i = 0
for i in range(N):
    ichi = i
    score = 0
    step  = 0
    loop  = 0
    score_max = -1000000010
    while True:
        step  += 1
        score += C[ichi]
        ichi   = (P[ichi] -1)
        if i ==  (P[ichi] -1):
            score += C[ichi]
            break
        
    path = 0
    cnt  = 0
    
    while True:
        cnt  += 1
        path += C[ichi]
        
        if cnt > K:
            break
        
        loop = long((K - cnt) / (step+ 1))
        if score > 0:
            score_max = path + loop * score
        else:
            score_max = path
        if score_max > score_output:
            score_output = score_max

        ichi   = P[ichi]-1
        if i == (P[ichi] -1):
            break
# 出力
print(score_output)

Submission status: Runtime Error

Solution code:
n, k = [int(i) for i in input().split(' ')]
number = [int(i) for i in input().split(' ')]
point = [int(i) for i in input().split(' ')]
res = []
def main(number, point, tmp, i, k, cnt) :
  tmp += point[number[i-1]-1]
  cnt += 1
  next = number[i-1]
  if k > cnt :
    return main(number, point, tmp, next, k, cnt)
  else :
    return tmp  
  
for i in number :
  tmp = 0
  cnt = 0
  res.append(main(number, point, tmp, i, k, cnt))
print(max(res))

Submission status: Runtime Error

Solution code:
n, k = [int(i) for i in input().split(' ')]
number = [int(i) for i in input().split(' ')]
point = [int(i) for i in input().split(' ')]
res = []
def main(number, point, tmp, i, k, cnt) :
  tmp += point[number[i-1]-1]
  cnt += 1
  next = number[i-1]
  if k > cnt :
    return main(number, point, tmp, next, k, cnt)
  else :
    return tmp  
  
for i in number :
  tmp = 0
  cnt = 0
  res.append(main(number, point, tmp, i, k, cnt))
  print(max(res))

Submission status: Runtime Error

Solution code:
%%cython
from sys import stdin
 
def main():
    readline = stdin.readline
    N, K = map(int, readline().split())
    P = list(map(int, readline().split()))
    C = list(map(int, readline().split()))
    P = [i-1 for i in P]
    Position_list=[P]
    Score_list=[[0 for i in range(N)]]
    Max_list=[]
 
    for j in range(K):
        Updated_Position=[]
        Updated_Score=[]
        Current_Position=Position_list[j]
        Current_Score=Score_list[j]
        for i in range(N):
            Position=P[i]
            Updated_Position.append(Current_Position[Position])
            Updated_Score.append(Current_Score[i]+C[Current_Position[i]])
        Position_list.append(Updated_Position)
        Score_list.append(Updated_Score)
        Max_list.append(max(Score_list[j+1]))
   
    print(max(Max_list))
main()

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:
        if k>L:ans=max(ans,(k//L-1)*S+max(max(cycle),max(cycle[:k%L+1])+S)) 
        else:ans=max(ans,cycle[:min(k+1,L)])
print(ans)

Submission status: Runtime Error

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

#ループ探し
l = [0] * 5010
counter = 0
for i in range(N):
    P[i] = P[i]-1
for i in range(5005):
    l[i] = []
for i in range(N):
    if P[i] == -1:
        continue
    else:
        a = i
        while True:
            #print(P, a)
            if P[a] != -1:
                l[counter].append(C[a])
                n = P[a]
                P[a] = -1
                a = n
            else:
                counter += 1
                break
#print(l[0:3])
#最大を考える
pp = -10**(18)
for i in range(counter):
    ll = [0]
    m = len(l[i])
    s = sum(l[i])
    l[i] = l[i] + l[i]
    for j in range(m*2):
        ll.append(ll[-1] + l[i][j])

    #print(s)
    if s <= 0 or K < m:
        K = min(K, m)
        for j in range(1, K+1):
            pp = max(pp, max(ll[j:j+K])- ll[j-1])
    else:
        for j in range(1, m+1):
            a = max(ll[j:j+m-1])-ll[j-1]
            if K%m != 0:
                b = max(ll[j:j+K%m]) - ll[j-1]
                pp = max(pp, max((K//m)*s, K//m*s+b, (K//m-1)*s+a))
            else:
                b = max(ll[j:j+m-1]) - ll[j-1]
                pp = max(pp, max(K//m*s, (K//l-1)*s+a))

print(pp)

Submission status: Runtime Error

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

#ループ探し
l = [0] * 5010
counter = 0
for i in range(N):
    P[i] = P[i]-1
for i in range(5005)
    l[i] = []
for i in range(N):
    if P[i] == -1:
        continue
    else:
        a = i
        while True:
            #print(P, a)
            if P[a] != -1:
                l[counter].append(C[a])
                n = P[a]
                P[a] = -1
                a = n
            else:
                counter += 1
                break
#print(l[0:3])
#最大を考える
pp = -10**(18)
for i in range(counter):
    ll = [0]
    m = len(l[i])
    s = sum(l[i])
    l[i] = l[i] + l[i]
    for j in range(m*2):
        ll.append(ll[-1] + l[i][j])

    #print(s)
    if s <= 0 or K < m:
        K = min(K, m)
        for j in range(1, K+1):
            pp = max(pp, max(ll[j:j+K])- ll[j-1])
    else:
        for j in range(1, m+1):
            a = max(ll[j:j+m-1])-ll[j-1]
            if K%m != 0:
                b = max(ll[j:j+K%m]) - ll[j-1]
                pp = max(pp, max((K//m)*s, K//m*s+b, (K//m-1)*s+a))
            else:
                b = max(ll[j:j+m-1]) - ll[j-1]
                pp = max(pp, max(K//m*s, (K//l-1)*s+a))

print(pp)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:
        if k>L:ans=max(ans,(k//L-1)*S+max(max(cycle),max(cycle[:k%L+1])+S)) 
        else:ans=max(ans,cycle[:k+1])
print(ans)

Submission status: Runtime Error

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

#ループ探し
l = [0] * 5010
counter = 0
for i in range(N):
    P[i] = P[i]-1
    l[i] = []
for i in range(N):
    if P[i] == -1:
        continue
    else:
        a = i
        while True:
            #print(P, a)
            if P[a] != -1:
                l[counter].append(C[a])
                n = P[a]
                P[a] = -1
                a = n
            else:
                counter += 1
                break
#print(l[0:3])
#最大を考える
pp = -10**(18)
for i in range(counter):
    ll = [0]
    m = len(l[i])
    s = sum(l[i])
    l[i] = l[i] + l[i]
    for j in range(m*2):
        ll.append(ll[-1] + l[i][j])

    #print(s)
    if s <= 0 or K < m:
        K = min(K, m)
        for j in range(1, K+1):
            pp = max(pp, max(ll[j:j+K])- ll[j-1])
    else:
        for j in range(1, m+1):
            a = max(ll[j:j+m-1])-ll[j-1]
            if K%m != 0:
                b = max(ll[j:j+K%m]) - ll[j-1]
                pp = max(pp, max((K//m)*s, K//m*s+b, (K//m-1)*s+a))
            else:
                b = max(ll[j:j+m-1]) - ll[j-1]
                pp = max(pp, max(K//m*s, (K//l-1)*s+a))

print(pp)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:
        if k>L:ans=max(ans,cycle[:k])
        else:ans=max(ans,(k//L-1)*S+max(max(cycle),max(cycle[:k%L+1])+S))    
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:ans=max(ans,max(0,k//L-1)*S+max(cycle,max(cycle[:k%L+1])+S))
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<0:ans=max(ans,max(cycle[1:k%L+1]))
    else:ans=max(ans,k//L*S+max(cycle[:k%L+1]))
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
a=[1]*n
for i in range(n):
    if a[i]:
        a[i]=1
        start=i
        cycle=[0]
        for _ in range(n):
            i=p[i]
            cycle+=[cycle[-1]+c[i]]
            a[i]=1
            if i==start:break
        S,L=cycle[-1],len(cycle)-1
        if S<0:ans=max(ans,max(cycle[1:k]))
        else:ans=max(ans,k//L*S+max(cycle[:k%L+1]))
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<0:ans=max(ans,max(cycle[1:k]))
    else:ans=max(ans,k//L*S+max(cycle[:k%L+1]))
print(ans)

Submission status: Runtime Error

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

maxscore = -float("inf")
for i0 in range(n):
    i = i0
    score = 0
    cycle = []
    for t in range(n):
        i = p[i] - 1
        score += c[i]
        cycle.append(score)
        if i == i0:
            break
    l = len(cycle)
    if k <= l:
        curmax = max(cycle[:k])
    elif cycle[-1] <= 0:
        curmax = max(cycle)
    else:
        q = k // l
        curmax = q * cycle[-1] + max(cycle[:k - q * l])
    maxscore = max(maxscore, curmax)
print(maxscore)

Submission status: Runtime Error

Solution code:
import copy
N,K=map(int,input().split())
List_p=list(map(int,input().split()))
List_c=list(map(int,input().split()))
l=[]
number=[i for i in range(N)]
sub=copy.copy(List_c)
l.append(sub)
for i in range(N):
    number[i]=List_p[number[i]]
    sub[i]+=List_c[number[i]]
    l.append(sub)
j=[]
for i in range(len(l)):
    j.append(max(l[i]))
s=0
for i in range(len(List_c)):
    s+=List_c[i]
if s>=0:
    if K<=N:
        ans=j[1]
        for i in range(2,K+1):
            ans=max(ans,j[i])
        print(ans)
    else:
        ans=j[1]
        for i in range(2,N+1):
            ans=max(ans,j[i])
        print(ans+s*(K//N))
else:
    if K<=N:
        ans=j[1]
        for i in range(2,K+1):
            ans=max(ans,j[i])
        print(ans)
    else:
        ans=j[1]
        for i in range(2,N+1):
            ans=max(ans,j[i])
        print(ans)

Submission status: Runtime Error

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

ans = -10**18

for i in range(N):
    tmp_score = 0
    pos = i
    # ループになるまで移動
    for j in range(1, K+1):
        pos = P[pos]-1
        if K >= j:
            tmp_score += C[pos]
            ans = max(ans,tmp_score)
        if pos == i:
            break
    
    div = K // j
    mod = K % j

        if K >= j:
        tmp_score *= div
        ans = max(ans,tmp_score)
        # 端数ぶん移動
        # mod=0 のときは移動しない
        for _ in range(1, mod+1):
            pos = P[pos]-1
            tmp_score += C[pos]
            ans = max(ans,tmp_score)

print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8


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


position_history = []
max_score = 0
for start_position in range(n):
    max_the_start = 0
    loop_kaisu = 0
    next_position = p[start_position]
    start_position = p[start_position]
    score = 0
    while True:
        loop_kaisu += 1
        score += c[next_position-1]
        max_the_start = max(score, max_the_start)
        next_position = p[next_position-1]
        if next_position == start_position:
            break
    if score <= 0:
        max_score = max(max_score, max_the_start)
        continue
    nankai_loop_dekiru = k // loop_kaisu
    score = score * (nankai_loop_dekiru - 1)
    loop_kaisu *= (nankai_loop_dekiru-1)
    while loop_kaisu < k:
        loop_kaisu += 1
        score += c[next_position-1]
        next_position = p[next_position-1]
        max_the_start = max(score, max_the_start)
    max_score = max(max_the_start, max_score)

if max_score <= 0:
    print(max(n))
else:
    print(max_score)

Submission status: Runtime Error

Solution code:
# coding: utf-8


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


position_history = []
max_score = 0
for start_position in range(n):
    max_the_start = 0
    loop_kaisu = 0
    next_position = p[start_position]
    start_position = p[start_position]
    score = 0
    while True:
        loop_kaisu += 1
        score += c[next_position-1]
        max_the_start = max(score, max_the_start)
        next_position = p[next_position-1]
        if next_position == start_position:
            break
    if score <= 0:
        max_score = max(max_score, max_the_start)
        continue
    nankai_loop_dekiru = k // loop_kaisu
    score = score * (nankai_loop_dekiru - 1)
    loop_kaisu *= (nankai_loop_dekiru-1)
    print(k - loop_kaisu)
    while loop_kaisu < k:
        loop_kaisu += 1
        score += c[next_position-1]
        next_position = p[next_position-1]
        max_the_start = max(score, max_the_start)
    max_score = max(max_the_start, max_score)

if max_score <= 0:
    print(max(n))
else:
    print(max_score)

Submission status: Runtime Error

Solution code:
# coding: utf-8


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


position_history = []
max_score = 0
for start_position in range(n):
    max_the_start = 0
    loop_kaisu = 0
    next_position = p[start_position]
    start_position = p[start_position]
    score = 0
    while True:
        loop_kaisu += 1
        score += c[next_position-1]
        max_the_start = max(score, max_the_start)
        next_position = p[next_position-1]
        if next_position == start_position:
            break
    nankai_loop_dekiru = k // loop_kaisu
    score = score * (nankai_loop_dekiru - 1)
    loop_kaisu *= (nankai_loop_dekiru-1)
    while loop_kaisu < k:
        loop_kaisu += 1
        score += c[next_position-1]
        next_position = p[next_position-1]
        max_the_start = max(score, max_the_start)
    max_score = max(max_the_start, max_score)

if max_score <= 0:
    print(max(n))
else:
    print(max_score)

Submission status: Runtime Error

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

ans = -10**18

for i in range(N):
    tmp_score = 0
    pos = i
    # ループになるまで移動
    for j in range(1, K+1):
        pos = P[pos]-1
        tmp_score += C[pos]
        ans = max(ans,tmp_score)
        if pos == i:
            break
    
    div = K // j
    mod = K % j

    tmp_score *= div
    ans = max(ans,tmp_score)
    # 端数ぶん移動
    for _ in range(mod+1):
        pos = p[pos]-1
        tmp_score += c[pos]
        ans = max(ans,tmp_score)        
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1
ans = max(C)
for start in range(N):
    now = P[start]
    score = C[now]
    c = K-1
    k = 1
    kick = [score]
    step = None
    kick_score = None
    x = True
    if now == start:
        step = k
        kick_score = score
        x = False
    while c > 0 and k < N and x:
        now = P[now]
        score += C[now]
        ans = max(ans, score)
        c -= 1
        k += 1
        kick.append(score)
        if now == start:
            step = k
            kick_score = score
            break
    if kick_score != None:
        if kick_score > 0:
            ans = max(ans, kick_score*(K//step)+max(kick[:K%step]))
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1
ans = max(C)
for start in range(N):
    now = P[start]
    score = C[now]
    c = K-1
    k = 1
    kick = [score]
    step = None
    kick_score = None
    x = True
    if now == start:
        step = k
        kick_score = score
        x = False
    while c > 0 and k < N and x:
        now = P[now]
        score += C[now]
        ans = max(ans, score)
        c -= 1
        k += 1
        kick.append(score)
        if now == start:
            step = k
            kick_score = score
            break
    if kick_score != None and kick_score > 0:
        ans = max(ans, kick_score*(K//step)+max(kick[:K%step]))
print(ans)

Submission status: Runtime Error

Solution code:
import sys


class Solution:
    def find_loop(self, idx):
        self.st.append(idx)
        self.vis[idx] = True
        
        ndx = self.parr[idx]
        if not self.vis[ndx]:
            self.find_loop(ndx)

    def dp(self, idx, k):
        while k >= self.n:
            pass
        if k == 0:
            self.rcd[idx][k] = 0
            return 0
        elif self.rcd[idx][k] != -1:
            return self.rcd[idx][k]
        else:
            maxv = max(0, self.dp(self.parr[idx], k - 1) + self.carr[self.parr[idx]])
            self.rcd[idx][k] = maxv
            return maxv

    def run(self):
        self.n, self.k = map(int, input().split())
        self.parr = list(map(int, input().split()))
        self.carr = list(map(int, input().split()))

        # make sure parr is 0-indexed
        self.parr = [val - 1 for val in self.parr]

        self.cycle_size = [-1 for _ in range(self.n)]
        self.cycle_sum = [0 for _ in range(self.n)]
        self.vis = [False for _ in range(self.n)]
        
        # find out the size of closed loop
        for idx in range(self.n):
            if not self.vis[idx]:
                self.st = []
                self.find_loop(idx)
                sval = sum([self.carr[jdx] for jdx in self.st])
                for jdx in self.st:
                    self.cycle_size[jdx] = len(self.st)
                    self.cycle_sum[jdx] = max(0, sval)

        # print(self.cycle_size)
        # print(self.cycle_sum)

        # try starting point at different index
        self.rcd = [[-1 for _ in range(self.n + 1)] for _ in range(self.n)]
        maxv = -sys.maxsize
        for idx in range(self.n):
            maxv = max(
                maxv,
                self.dp(self.parr[idx], (self.k - 1) % self.cycle_size[idx]) + self.carr[self.parr[idx]] + (self.k - 1) // self.cycle_size[idx] * self.cycle_sum[idx]
            )
        print(maxv)

if __name__ == '__main__':
    solution = Solution()
    solution.run()

Submission status: Runtime Error

Solution code:
import sys


class Solution:
    def find_loop(self, idx):
        self.st.append(idx)
        self.vis[idx] = True
        
        ndx = self.parr[idx]
        if not self.vis[ndx]:
            self.find_loop(ndx)

    def dp(self, idx, k):
        if k == 0:
            self.rcd[idx][k] = 0
            return 0
        elif self.rcd[idx][k] != -1:
            return self.rcd[idx][k]
        else:
            maxv = max(0, self.dp(self.parr[idx], k - 1) + self.carr[self.parr[idx]])
            self.rcd[idx][k] = maxv
            return maxv

    def run(self):
        self.n, self.k = map(int, input().split())
        self.parr = list(map(int, input().split()))
        self.carr = list(map(int, input().split()))

        # make sure parr is 0-indexed
        self.parr = [val - 1 for val in self.parr]

        self.cycle_size = [-1 for _ in range(self.n)]
        self.cycle_sum = [0 for _ in range(self.n)]
        self.vis = [False for _ in range(self.n)]
        
        # find out the size of closed loop
        for idx in range(self.n):
            if not self.vis[idx]:
                self.st = []
                self.find_loop(idx)
                sval = sum([self.carr[jdx] for jdx in self.st])
                for jdx in self.st:
                    self.cycle_size[jdx] = len(self.st)
                    self.cycle_sum[jdx] = max(0, sval)

        for idx in range(self.n):
            while self.cycle_size[idx] < 1:
                pass

        # print(self.cycle_size)
        # print(self.cycle_sum)

        # try starting point at different index
        self.rcd = [[-1 for _ in range(self.n + 1)] for _ in range(self.n)]
        maxv = -sys.maxsize
        for idx in range(self.n):
            maxv = max(
                maxv,
                self.dp(self.parr[idx], (self.k - 1) % self.cycle_size[idx]) + self.carr[self.parr[idx]] + (self.k - 1) // self.cycle_size[idx] * self.cycle_sum[idx]
            )
        print(maxv)

if __name__ == '__main__':
    solution = Solution()
    solution.run()

Submission status: Runtime Error

Solution code:
import sys


class Solution:
    def find_loop(self, idx):
        self.st.append(idx)
        self.vis[idx] = True
        
        ndx = self.parr[idx]
        if not self.vis[ndx]:
            self.find_loop(ndx)

    def dp(self, idx, k):
        if k == 0:
            self.rcd[idx][k] = 0
            return 0
        elif self.rcd[idx][k] != -1:
            return self.rcd[idx][k]
        else:
            maxv = max(0, self.dp(self.parr[idx], k - 1) + self.carr[self.parr[idx]])
            self.rcd[idx][k] = maxv
            return maxv

    def run(self):
        self.n, self.k = map(int, input().split())
        self.parr = list(map(int, input().split()))
        self.carr = list(map(int, input().split()))

        # make sure parr is 0-indexed
        self.parr = [val - 1 for val in self.parr]

        self.cycle_size = [0 for _ in range(self.n)]
        self.cycle_sum = [0 for _ in range(self.n)]
        self.vis = [False for _ in range(self.n)]
        
        # find out the size of closed loop
        for idx in range(self.n):
            if not self.vis[idx]:
                self.st = []
                self.find_loop(idx)
                sval = sum([self.carr[jdx] for jdx in self.st])
                for jdx in self.st:
                    self.cycle_size[jdx] = len(self.st)
                    self.cycle_sum[jdx] = max(0, sval)

        # print(self.cycle_size)
        # print(self.cycle_sum)

        # try starting point at different index
        self.rcd = [[-1 for _ in range(self.n + 1)] for _ in range(self.n)]
        maxv = -sys.maxsize
        for idx in range(self.n):
            maxv = max(
                maxv,
                self.dp(self.parr[idx], (self.k - 1) % self.cycle_size[idx]) + self.carr[self.parr[idx]] + (self.k - 1) // self.cycle_size[idx] * self.cycle_sum[idx]
            )
        print(maxv)

if __name__ == '__main__':
    solution = Solution()
    solution.run()

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
points=[[] for i in range(N)]
for i in range(N):
  tmpl=[0]
  loc=i
  for j in range(1,N+1):
    tmpl+=[tmpl[j-1]+C[loc]]
    loc=P[loc]-1
  points[i]=tmpl
repeat=K//N
left=K%N
maxlist=[]
for i in range(N):
  if points[i][N]<0:
    maxlist+=[max(points[i][1:left+1])]
  else:
    tmp=repeat*points[i][N]+max(points[i][1:left+1])
    maxlist+=[tmp]
print(max(maxlist))

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
points=[[] for i in range(N)]
for i in range(N):
  tmpl=[0]
  loc=i
  for j in range(1,N+1):
    tmpl+=[tmpl[j-1]+C[i]]
    loc=P[i]
  points[i]=tmpl
repeat=K//N
left=K%N
ans=-float('inf')
maxlist=[]
for i in range(N):
  if points[i][N]<0:
    maxlist+=[max(points[i][1:left+1])]
  else:
    tmp=repeat*points[i][N]+max(points[i][1:left+1])
    maxlist+=[tmp]
print(max(maxlist))

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
points=[[] for i in range(N)]
for i in range(N):
  tmpl=[0]
  loc=i
  for j in range(1,N+1):
    tmpl+=[tmpl[j-1]+C[i]]
    loc=P[i]
  points[i]=tmpl
repeat=K//N
left=K%N
ans=-float('inf')
maxlist=[]
for i in range(N):
  if points[i][N]<0:
    maxlist+=[max(points[i][1:left+1])]
  else:
    tmp=repeat*points[i][N]+max(points[i][1:left+1])
    maxlist+=[tmp]
print(max(maxlist))

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
ans = -float('inf')
for s in range(N):
    ### Step1
    S = []  # 累積和S. ただし, 初項は0ではなく1回目の移動後の得点とする.
    # 1回目の移動
    i = P[s] - 1
    S.append(C[i])
    # 2回目以降の移動. スタート地点に戻ってくるまで繰り返し.
    while i != s:
        i = P[i] - 1
        S.append(S[-1] + C[i])

    ### Step2: KとSの長に応じて場合分けして, 得点の最大値を求める.
    # 1周未満しか移動できない場合:
    if K <= len(S):
        score = max(S[:K])
    # 1周以上回ることができるが, ループを1周したときに得点が減る場合:
    elif S[-1] <= 0:
        score = max(S)
    # 1週以上回ることができ, かつループを1週するごとに得点が増える場合:
    else:
        # ループを (K // len(S) - 1)回 廻る場合:
        score1 = S[-1] * (K // len(S) - 1)
        score1 += max(S)
        # ループを (K // len(S))回 廻る場合:
        score2 = S[-1] * (K // len(S))
        r = K % len(S)
        if r != 0:
            score2 += max(0, max(S[:r]))
        # score1 と score2 の大きい方がこの場合の得点の最大値
        score = max(score1, score2)

    ans = max(ans, score)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
import resource
sys.setrecursionlimit(10000)
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
    if start==now:
        flag+=1
    if start==now and flag==2:
        return [max,sum,count]
    elif count==up:
        return [max,sum,count]
    else:
        count+=1
        sum+=c[p[now-1]-1]
        if max<sum:
            max=sum
        return find(start,p[now-1],up,max,sum,count,flag)
kara=[-10000000000]
for i in range(1,n+1):
    m=find(i,i,n,c[p[i-1]-1],0,0,0)
    if m[2]>=k:
        m=find(i,i,k,c[p[i-1]-1],0,0,0)
        if m[0]>kara[0]:
            kara[0]=m[0]
        result=kara[0]
    elif m[1]<=0:
        if m[0]>kara[0]:
            kara[0]=m[0]
    else:
        w=k%m[2]
        if w==0:
            w=m[2]
        spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
        if m[1]+spe>m[0] and m[1]*(k-w)//m[2]+spe>kara[0]:
            kara[0]=m[1]*(k-w)//m[2]+spe
        elif m[1]+spe<=m[0] and m[1]*((k-w)//m[2]-1)+m[0]>kara[0]:
            kara[0]=m[1]*((k-w)//m[2]-1)+m[0]
        result=kara[0]
print(result)