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:
import math
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

unions = []
checked_num = set()
for i in range(N):
    num = i
    union_set = []
    while num not in checked_num:
        checked_num.add(num)
        union_set.append(Cs[num])
        num = Ps[num]-1
        if num == i:
            unions.append(union_set)
            break

final_max_score = -math.inf

for num_set in unions:
    length = len(num_set)
    count = 0
    if K > length:
        num_sum = sum(num_set)
        remainder = K%length
        if num_sum > 0:
            count = K//length
            num_sum_count = num_sum*count
            num_sum_count2 = num_sum*(count-1)
        K = length
    for k in range(1, K+1):
        #print(k)
        #print(num_set)
        max_score = 0
        for i in range(length):
            score = 0
            sum_list = num_set[i:k+i]
            if i+k-length > 0:
                sum_list += num_set[0:i+k-length]
            score = sum(sum_list)
                score += item
            if score > max_score:
                max_score = score
        if (count > 0 and k <= remainder):
            max_score = max_score + num_sum_count
        elif (count > 0 and k > remainder):
            max_score = max_score + num_sum_count2
            #print(max_score)
        if max_score > final_max_score:
            final_max_score = max_score
print(final_max_score)

Submission status: Runtime Error

Solution code:
def read_input():

    n, k = map(int, input().split())
    p = list(map(lambda x : int(x) - 1, input().split()))
    c = list(map(int, input().split()))

    return n, k, p, c

def solve_i(i, k, p, c, n):
    
    points = None
    maxi = None
    s = i
    i = p[i]
    t = 0

    while i != s:
        
        if points is None:
            points = [c[i]]
        else:
            points.append(points[-1] + c[i])

        i = p[i]
        t += 1
        if t == k:
            return max(points)

    if points[-1] <= 0:
        return max(points)
    else:
        cycles = k // len(points)
        remainder = k % len(points)

        potential = points[-1] * cycles + max(points[:remainder])
        maxi = max(points)
        return max(maxi, potential)



def solve(n, k, p, c):

    maxi = []
    for i in range(n):
        maxi.append(solve_i(i, k, p, c, n))

    return max(maxi)        


print(solve(*read_input()))

Submission status: Runtime Error

Solution code:
import sys

r,c,k=map(int,input().split())
dp=[[[0 for kk in range(4)] for jj in range(c+1)] for ii in range(r+1)]

g=[[0 for j in range(c)] for i in range(r)]
for i in range(k):
    rr,cc,v=map(int,input().split())
    rr-=1
    cc-=1
    g[rr][cc]=v
for i in range(1,r+1):
    for j in range(1,c+1):
        for k in range(4):
            dp[i][j][k]=max(dp[i][j][k],dp[i][j-1][k])#,dp[i][j-1][k])
            dp[i][j][0]=max(dp[i][j][0],dp[i-1][j][k])
            if k>0:
                if dp[i][j][k]<dp[i][j-1][k-1]+g[i-1][j-1]:
                    dp[i][j][k]=dp[i][j-1][k-1]+g[i-1][j-1]
            if dp[i][j][1]<dp[i-1][j][k]+g[i-1][j-1]:
                dp[i][j][1]=dp[i-1][j][k]+g[i-1][j-1]
print(max(dp[r][c]))

Submission status: Runtime Error

Solution code:
def calc_max(P):
    p=P
    l=[]
    S=0
    max_range=0
    tmpM=0
    for _ in range(K):
        l.append(C[p])
        S+=C[p]
        if tmpM<S:
            tmpM=S
            max_range=_
        p=P[p]
        if p==P:
            break
    if S>0:
        t=len(l)
        tmpK=K-max_range
        return S*(tmpK//t)
    else:
        return S

N,K=map(int,input().split())
P=list(map(lambda x:int(x)-1,input().split()))
C=list(map(int,input().split()))
ans=max(map(calc_max,range(N)))
if ans==0:
    print(max(ans))
else:
    print(ans)

Submission status: Runtime Error

Solution code:
import math
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

unions = []
checked_num = set()
for i in range(N):
    num = i
    union_set = []
    while num not in checked_num:
        checked_num.add(num)
        union_set.append(Cs[num])
        num = Ps[num]-1
        if num == i:
            unions.append(union_set)
            break
final_max_score = -math.inf
for num_set in unions:
    length = len(num_set)
    cycle_sum_count = 0
    cycle_sum_count_minus_1 = 0
    if K > length:
        num_sum = sum(num_set)
        remainder = K%length
        if num_sum > 0:
            count = K//length
            cycle_sum_count = count * num_sum
            cycle_sum_count_minus_1 = (count-1) * num_sum
        K = length
    for k in range(1, K+1):
        #print(k)
        #print(num_set)
        score = 0
        max_score = -math.inf
        for i in range(length):
            score = 0
            score += sum(num_set[i:k+i])
            if i+k-length > 0:
                score += sum(num_set[0:i+k-length])
            if score > max_score:
                max_score = score
        if (count > 0 and k <= remainder):
            max_score = max_score + cycle_sum_count
        elif (count > 0 and k > remainder):
            max_score = max_score + cycle_sum_count_minus_1
        #print(max_score)
    if max_score > final_max_score:
        final_max_score = max_score
print(final_max_score)

Submission status: Runtime Error

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
ans=-INF
for i in range(n):
    c1=[]
    a=i
    while True:
        a=p[a]-1
        c1.append(c[a])
        if a==i:
            break
    m1=0
    for j in range(min(k,len(c1))):
        m1+=c1[j]
        ans=max(m1,ans)
    if m1>0:
        t=k//len(c1)
        m1=max(0,m1*(t-1))
        ind=max(0,len(c)*(t-1))
        ans=max(ans,m1)
        for i in range(ind,k):
            m1+=c1[i%len(c)]
            ans=max(ans,m1)
out(ans)

Submission status: Runtime Error

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
ans=-INF
for i in range(n):
    c1=[]
    a=i
    while True:
        a=p[a]-1
        c1.append(c[a])
        if a==i:
            break
    m=-INF
    m1=0
    for j in range(min(k,len(c1))):
        m1+=c1[j]
        ans=max(m1,ans)
    if m1>0:
        t=k//len(c1)
        m1=max(0,m1*(t-1))
        ind=max(0,len(c)*(t-1))
        ans=max(ans,m1)
        for i in range(ind,k):
            m1+=c1[i]
            ans=max(ans,m1)
out(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
p = input().split()
c = input().split()
l = []
for i in range(n):
    p[i] = int(p[i])
    c[i] = int(c[i])

wa = []
checked = []
for i in range(n):
    if i not in checked:
        index = i
        s = c[index]
        w = [0, c[index]]
        checked.append(index)
        index = p[index] - 1
        while index != i:
            s += c[index]
            w.append(s)
            checked.append(index)
            index = p[index] - 1

        large = [[] for x in range(len(w))]
        for ii in range(1, len(w)):
            for j in range(len(w)-ii):
                large[ii].append(w[ii+j] - w[j])
                if j != 0 and ii+j < len(w):
                    large[len(w)-1-ii].append(s - (w[ii+j] - w[j]))
        #print(large)

        for j in range(1, len(large)):
            large[j] = max(large[j])
        #print(large)
        if len(w)-1 >= k:
            wa.append(max(large[1:k+1]))
        elif len(w)-1 < k and large[-1] > 0:
            wa.append(max((k // (len(w)-1)) * large[-1] + max(large[1:(k % (len(w)-1))+1]), max(large[1:])))
        else:
            wa.append(max(large[1:]))

print(max(wa))

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 = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
            j = p[j] - 1
        le = len(l)
        l *= (k//1 + 2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

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 = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
            j = p[j] - 1
        le = len(l)
        ln = l*(k//le + 2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

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 = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
            j = p[j] - 1
        le = len(l)
        if le == 0:
            continue
        l *= (k//le +2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

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()))
c = [1] * N
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        m[i][c[i]] = m[i][c[i]-1] + C[P[j]-1]
ans = max(C)
for i in range(N):
    if m[i][c[i]] > 0:
        if  m[i][c[i]] * (K//c[i]) + max(m[i][1:K%c[i]+1]) > ans:
            ans = m[i][c[i]] * (K//c[i]) + max(m[i][1:K%c[i]+1])
    else:
        if max(m[i][1:min(c[i],K)+1]) > ans:
            ans = max(m[i][1:min(c[i],K)+1])
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
a=k%n
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=[]
if n>k:
    for i in range(1,n+1):
        kara.append(find(i,i,k,c[p[i-1]-1],0,0,0)[0])
    result=max(kara)
else:
    for i in range(1,n+1):
        m=find(i,i,n,c[p[i-1]-1],0,0,0)
        if m[1]<=0:
            kara.append(m[0])
        else:
            w=k%m[2]
            spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
            if m[0]>int(m[1]*(k-w)/m[2])+spe:
                kara.append(m[0])
            else:
                kara.append(int(m[1]*(k-w)//m[2])+spe)
    result=max(kara)
print(result)

Submission status: Runtime Error

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  N,K=LI()
  P=LI()
  P=[0]+P
  C=LI()
  C=[0]+C

  l=[[0] for _ in range(N)]
  check=[[False]*(N+1) for _ in range(N)]
  roop=[]
  for i in range(N):
    zahyo=i+1
    check[i][zahyo]=True
    f=False
    for j in range(N+1):
      zahyo=P[zahyo]
      if check[i][zahyo] and not f:
        roop.append(j+1)
        f=True
      score=C[zahyo]
      l[i].append(l[i][-1]+score)
  for i in range(N):
    print(l[i])
  print(roop)

  ans=0
  for i in range(N):
    roop_count=roop[i]
    if K<=roop_count:
      ans=max(ans,max(l[i][1:K+1])) # 1巡以内
    else:
      ans=max(ans,max(l[i][1:K+1])) # 1巡以内

      # 2巡目以降（1巡で負になるなら回らない方がいい）
      if l[i][roop_count]>0:
        c=K//roop_count
        _ans1=c*l[i][roop_count]
        k=K%roop_count
        _ans1+=max(l[i][1:k+1]+[0])
        ans=max(ans,_ans1)

        # 可能な巡数まで行かない方がいい場合も
        _ans2=(c-1)*l[i][roop_count]
        _ans2+=max(l[i][:roop_count]+[0])
        ans=max(ans,_ans1,_ans2)
        print(i,l[i][:K+1],_ans2)

  return ans

# main()
print(main())

Submission status: Runtime Error

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  N,K=LI()
  P=LI()
  P=[0]+P
  C=LI()
  C=[0]+C

  l=[[0] for _ in range(N)]
  check=[[False]*(N+1) for _ in range(N)]
  roop=[]
  for i in range(N):
    zahyo=i+1
    check[i][zahyo]=True
    f=False
    for j in range(N+1):
      zahyo=P[zahyo]
      if check[i][zahyo] and not f:
        roop.append(j+1)
        f=True
      score=C[zahyo]
      l[i].append(l[i][-1]+score)
  # for i in range(N):
  #   print(l[i])
  # print(roop)

  ans=0
  for i in range(N):
    roop_count=roop[i]
    if K<=roop_count:
      ans=max(ans,max(l[i][1:K+1])) # 1巡以内
    else:
      ans=max(ans,max(l[i][1:K+1])) # 1巡以内

      # 2巡目以降（1巡で負になるなら回らない方がいい）
      if l[i][roop_count]>0:
        c=K//roop_count
        _ans1=c*l[i][roop_count]
        k=K%roop_count
        _ans1+=max(l[i][1:k+1]+[0])
        ans=max(ans,_ans1)

        # 可能な巡数まで行かない方がいい場合も
        _ans2=(c-1)*l[i][roop_count]
        _ans2+=max(l[i][:roop_count])
        ans=max(ans,_ans1,_ans2)
        print(i,l[i][:K+1],_ans2)

  return ans

# main()
print(main())

Submission status: Runtime Error

Solution code:
mi=-(10**)
n,k=[int(x) for x in input().split()]
p=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]

#ループの最大値を求める
mxs=mi
otl=mi
lpc={-1:1}
for i in range(n):
    chkr={i:1}
    wks=0
    nxt=i
    for _ in range(n):
        nxt=p[nxt]-1
        if chkr.get(nxt):
            wks+=c[nxt]
            break
        chkr[nxt]=1
        wks+=c[nxt]
        otl=max(otl,wks)
    if mxs<wks:
        mxs=wks
        lpc=chkr
dv=k//len(lpc)
rst=k%len(lpc)

mxr=0
for i in lpc.keys():
    wks=0
    nxt=i
    for _ in range(rst):
        nxt=p[nxt]-1
        wks+=c[nxt]
        mxr=max(mxr,wks)

ans=max(dv*mxs+mxr,otl)
print(ans)

Submission status: Runtime Error

Solution code:
mi=-(10**9+1)
n,k=[int(x) for x in input().split()]
p=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]

#ループの最大値を求める
mxs=mi
otl=mi
lpc={}
for i in range(n):
    chkr={i:1}
    wks=0
    wks2=0
    nxt=i
    for _ in range(n):
        nxt=p[nxt]-1
        if chkr.get(nxt):
            wks+=c[nxt]
            break
        chkr[nxt]=1
        wks+=c[nxt]
        otl=max(otl,wks)
    if mxs<wks:
        mxs=wks
        lpc=chkr
dv=k//len(lpc)
rst=k%len(lpc)

mxr=0
for i in lpc.keys():
    wks=0
    nxt=i
    for _ in range(rst):
        nxt=p[nxt]-1
        wks+=c[nxt]
        mxr=max(mxr,wks)

ans=max(dv*mxs+mxr,otl)
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()))

seen = []
roots = []
candidates = []

for i in range(N):
    if i+1 in seen:
        continue
    root = [i+1]
    seen.append(i+1)
    to = P[i]
    while(root[0] != to):
        root.append(to)
        seen.append(to)
        to = P[to-1]
    roots.append(root)
for root in roots:
    eachMoveBests = [None] * (len(root))
    for i in range(len(root)):
        score = 0
        to = P[root[i]-1]
        for j in range(len(root)):
            score += C[to-1]
            to = P[to-1]
            if eachMoveBests[j] == None or score > eachMoveBests[j]:
                eachMoveBests[j] = score
    aroundTimes = K // len(root)
    surplus = K % len(root)
    sumRoot = 0
    for r in root:
        sumRoot += C[r-1]
    best = max(eachMoveBests)
    bestMoveTimes = eachMoveBests.index(best) + 1
    if surplus == 0:
        candidates.append(max(best,aroundTimes*sumRoot))
    elif bestMoveTimes <= surplus:
        candidates.append(max(best,aroundTimes*sumRoot+eachMoveBests[surplus-1]))
    else:
        candidates.append(max(best, aroundTimes*sumRoot+max(eachMoveBests[:surplus-1]), (aroundTimes-1)*sumRoot+best))
print(max(candidates))
# print(roots)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8, i8[:], i8[:]), cache=True)
def main(k,p,c):
  n=len(p)
  last=k%n
  by_last=k//n
  sum1=sum(c)
  cnt=sum1*by_last
  if sum1<0:
    for i in range(n):
      ans=-1000000000
      nxt=i
      for j in range(n):
          nxt=p[nxt]-1
          ans+=c[nxt]
          cnt=max(ans,cnt)
    return cnt
  else:
    for i in range(n):
      ans=sum1*by_last
      nxt=i
      for j in range(last):
        nxt=p[nxt]-1
        ans+=c[nxt]
        cnt=max(ans,cnt)
    return cnt

n,k = map(int, readline().split())
p = np.array(readline().split(), np.int64)
c = np.array(readline().split(), np.int64)
print(main(k,p,c))

Submission status: Runtime Error

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

seen = []
roots = []
candidates = []

for i in range(N):
    if i+1 in seen:
        continue
    root = [i+1]
    seen.append(i+1)
    to = P[i]
    while(root[0] != to):
        root.append(to)
        seen.append(to)
        to = P[to-1]
    roots.append(root)
for root in roots:
    eachMoveBests = [None] * (len(root))
    for i in range(len(root)):
        score = 0
        to = P[root[i]-1]
        for j in range(len(root)):
            score += C[to-1]
            to = P[to-1]
            if eachMoveBests[j] == None or score > eachMoveBests[j]:
                eachMoveBests[j] = score
    aroundTimes = K // len(root)
    surplus = K % len(root)
    sumRoot = 0
    for r in root:
        sumRoot += C[r-1]
    best = max(eachMoveBests)
    bestMoveTimes = eachMoveBests.index(best) + 1
    if surplus == 0:
        candidates.append(max(best,aroundTimes*sumRoot))
    elif bestMoveTimes <= surplus:
        candidates.append(max(best,aroundTimes*sumRoot+eachMoveBests[surplus-1]))
    else:
        candidates.append(max(best, aroundTimes*sumRoot+max(eachMoveBests[:surplus-1]), (aroundTimes-1)*sumRoot+best))
print(max(candidates))
# print(roots)






# # 各移動回数におけるベストなスコアを記録
# bests = [None] * N
# for i in range(N):
#     score = 0
#     to = P[i] - 1
#     for j in range(N):
#         score += C[to]
#         to = P[to] - 1
#         if bests[j] == None or score > bests[j]:
#             bests[j] = score
# print(bests)



# # if K <= N:
# #     best = None
# #     for i in range(N):
# #         score = 0
# #         to = P[i] - 1
# #         for j in range(K):
# #             score += C[to]
# #             to = P[to] - 1
# #             if best == None or score > best:
# #                 best = score
# #     print(best)
# # else:
# #     # 各移動回数におけるベストを記録しておく
# #     best = None
# #     bestMoveTime = None
# #     innerBests = [None] * N
# #     for i in range(N):
# #         score = 0
# #         to = P[i] - 1
# #         for j in range(N-1):
# #             score += C[to]
# #             to = P[to] - 1
# #             if best == None or score > best:
# #                 best = score
# #                 bestMoveTime = j+1
# #             if innerBests[j] == None or score > innerBests[j]:
# #                 innerBests[j] = score

# #     aroundTimes = K // N
# #     sumC = sum(C)
 
# #     if K % N >= bestMoveTime:
# #         print(K%N)
# #         print(bestMoveTime)
# #         print(max(best, aroundTimes*sumC+best))
# #     else:
# #         print(max(best, (aroundTimes-1)*sumC+best+max(innerBests[:N-bestMoveTime+1]), aroundTimes*sumC+max(innerBests[:K%N])))

# #         # print(max(best, aroundTimes*sumC+max(innerBests[:K % N]),(aroundTimes-1)*sumC+best))
    








# #     # noAroundBest = None
# #     # noAroundBestTimes = None
# #     # for i in range(N):
# #     #     score = 0
# #     #     to = P[i] - 1
# #     #     for j in range(N-1):
# #     #         score += C[to]
# #     #         to = P[to] - 1
# #     #         if noAroundBest == None or score > noAroundBest:
# #     #             noAroundBest = score
# #     #             noAroundBestTimes = j+1

# #     # aroundTimes = K // N
# #     # times = K % N
# #     # best = None
# #     # for i in range(N):
# #     #     score = 0
# #     #     to = P[i] - 1
# #     #     for j in range(times):
# #     #         score += C[to]
# #     #         to = P[to] - 1
# #     #         if best == None or score > best:
# #     #             best = score
# #     # sumC = sum(C)
# #     # print(aroundTimes)
# #     # print(sumC)
# #     # print(aroundTimes*sumC+)
# #     # # print(noAroundBestTimes)
# #     # # print(noAroundBest)
# #     # # print(aroundTimes)
# #     # # print(sumC)
# #     # if noAroundBestTimes <= times:
# #     #     print(max(noAroundBest, sumC*aroundTimes+noAroundBestTimes))
# #     # else:
# #     #     print(max(noAroundBest, sumC*aroundTimes+best, sumC*(aroundTimes-1)+noAroundBestTimes))

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 = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
            j = p[j] - 1
        le = len(l)
        l *= (k//le +2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

print(ans)

Submission status: Runtime Error

Solution code:
import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

R, C, K = rl()
I = [[0]*(C+2) for _ in range(R+2)]
for i in range(K):
	r, c, v = rl()
	I[r][c] = v

dp = [[[0]*4 for _ in range(C+2)] for _ in range(R+2)]

for i in range(R+1):
	for j in range(C+1):
		d = dp[i][j]
		for ni, nj in [[i+1, j], [i, j+1]]:
			nd = dp[ni][nj]
			v = I[ni][nj]
			for m in range(4):
				if i == ni:
					nd[m] = max(nd[m], d[m])
					if m < 3:
						nd[m+1] = max(nd[m+1], d[m]+v)
				else:
					nd[0] = max(nd[0], d[m])
					nd[1] = max(nd[1], d[m] + v)
ans = 0
for m in range(4):
	ans = max(ans, dp[R][C][m])
print(ans)

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np
import sys
input = sys.stdin.readline


@njit
def print_ans(N, K, pr, cr):
    """Test Case
    >>> print_ans(5, 3,[2, 4, 5, 1, 3], [3, 4, -10, -8, 8])
    8
    >>> print_ans(2, 3,[2, 1],[10, -7])
    13
    """
    maximum = 0
    pr = np.array(pr)
    pr = pr - 1
    cr = np.array(cr)
    maximum = max(maximum, np.max(cr))
    ar = cr.copy()
    for i in range(K):
        if len(ar.shape) == 1:
            newest = ar.copy()
        else:
            newest = ar[i, :].copy()
        tmp = newest[pr]
        ar = np.vstack((ar, tmp))
        tmp_sum = np.sum(ar, axis=0)
        maximum = max(maximum, np.max(tmp_sum))
    print(maximum)


if __name__ == '__main__':
    N, K = map(int, input().rstrip().split())
    pr = list(map(int, input().rstrip().split()))
    cr = list(map(int, input().rstrip().split()))
    print_ans(N, K, pr, cr)

Submission status: Runtime Error

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

#各地点からN回移動したときのスコアをあらかじめ求める
score = [[0 for j in range(N + 1)] for i in range(N)]
loop = [None for _ in range(N)]

for i in range(N):
    tmp = i
    flag = False
    for j in range(1, N + 1):
        tmp = P[tmp]
        score[i][j] = score[i][j - 1] + C[tmp]
        if tmp == i and not flag:
            loop[i] = j
            flag = True

if K <= N:
    res = -10**20
    for i in range(N):
        for j in range(1, K + 1):
            res = max(res, score[i][j])
    print(res)

else:
    raise Exception
    res = -10**20
    for i in range(N):
        for j in range(1, N + 1):
            res = max(res, score[i][j])
    for i in range(N):
        if score[i][loop[i]] > 0:
            s = score[i][loop[i]] * (K // loop[i])
            for j in range(K % loop[i] + 1):
                res = max(res, s + score[i][j])
    print(res)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline

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

for i in range(N):
    visit = [False]*N
    now = i
    l = []
    visit[now] = True
    
    for j in range(N+10):
        nex = P[now]
        l.append(C[nex])
        
        if visit[nex]:
            break
        
        visit[nex] = True
        now = nex
    
    su = sum(l)
    
    if su>=0:
        if K>=len(l):
            now = su*(K//len(l))
            rem = K%len(l)
            ans = max(ans, now)
        
            for j in range(rem):
                now += l[j]
                ans = max(ans, now)
                
            now = l[0]
            ans = max(ans, now)
            
            for j in range(1, len(l)):
                now += l[i]
                ans = max(ans, now)
        else:
            now = l[0]
            ans = max(ans, now)
            
            for j in range(1, K):
                now += l[j]
                ans = max(ans, now)
    else:
        now = l[0]
        ans = max(ans, now)
        
        if K<len(l):
            for j in range(1, K):
                now += l[j]
                ans = max(ans, now)
        else:
            for j in range(1, len(l)):
                now += l[j];
                ans = max(ans, now)

print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
p = [int(pn) for pn in input().split()]
c = [int(cn) for cn in input().split()]
ans = -(10 ** 9)
for start in range(n):
  scores = []
  current = p[start] - 1
  score = c[current]
  scores.append(score)
  period = 1
  isCircular = False
  for _ in range(k - 1):
    isCircular = (current == start)
    if isCircular:
      break
    current = p[current] - 1
    score += c[current]
    scores.append(score)
    period += 1
  if isCircular and score:
    loops, remaining = divmod(k, period)
    score = score * loops + max(0, max(scores[:remaining]))
  else:
    score = max(scores)
  if score > ans:
    ans = score

print(ans)