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:
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=-float('inf')

for start in range(N):
    loop_len=1
    pos=P[start]
    score=C[pos]
    scores=[score]

    while pos!=start:
        loop_len+=1
        pos=P[pos]
        score+=C[pos]
        scores.append(score)
    
    loops=(K-1)//loop_len

    if score>0:
        cand=score*loops + max(scores[:(K%loop_len)])
    else:
        cand=max(scores[:min(K,loop_len)])
    ans=max(ans,cand)
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**10
for st in range(N):
  now = st+1
  temp=[0]
  while(P[now-1] != st+1):
    temp.append(temp[-1]+C[P[now-1]-1])
    now = P[now-1]
    temp.append(temp[-1]+C[P[now-1]-1])
  if len(temp)>=K+1:
    ans=max(ans, max(temp[1:K+1]))
    continue
  if temp[-1]<=0:
    ans = max(ans, (max(temp[1:])))
  else:
    t=temp[-1]*(K//(len(temp)-1))-temp[-1]
    t+=max(max(temp),max([temp[-1]+temp[i+1] for i in range(K%(len(temp)-1))]))
    ans=max(ans, t)
		
print(int(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 = -float("inf")
for i in range(N):
    hoge = []
    p = i
    s = 0
    for j in range(K):
        p = P[p]-1
        s += C[p]
        hoge.append(s)
        ans = max(ans,s)
        if p == i:
            S = s*((K-1)//len(hoge)) + max(hoge[:(K-1)%len(hoge)])
            if (K-1)//len(hoge) > 0:
                S = max(S,s*((K-1)//len(hoge))-1) + max(hoge)
            ans = max(ans,S)
            break
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**10
for st in range(N):
  now = st+1
  temp=[0]
  while(P[now-1] != st+1):
    temp.append(temp[-1]+C[P[now-1]-1])
    now = P[now-1]
    temp.append(temp[-1]+C[P[now-1]-1])
  if len(temp)>=K+1:
    ans=max(ans, max(temp[1:K+1]))
    continue
  if temp[-1]<=0:
    ans = max(ans, (max(temp[1:])))
  else:
    t=temp[-1]*(K//(len(temp)-1))-temp[-1]
    pりんt(temp+[temp[-1]+temp[i+1] for i in range(K%(len(temp)-1))])
    ans=max(ans, t)
		
print(int(ans))

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]
    while i != s:
        
        if points is None:
            points = [c[i]]
        else:
            points.append(points[-1] + c[i])

        i = p[i]

    points.append(points[-1] + c[i])

    if k < len(points):
        return max(points[:k])

    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 bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

N,K = LI()
P = LI()
C = LI()

ans = [0] * N
P = list(map(lambda x:x-1,P))

def rec(visited,next,s):
    if next in s:
        return visited,visited.index(next)
    else:
        s.add(next)
        visited.append(next)
        return rec(visited,P[next],s)

# @njit(nopython=True)
def solve():
    for i in range(N):
        s = set([i])
        visited = [i]
        a = 0
        visited,loopStart = rec(visited,P[i],s)
        # print(visited,loopStart)
        al = np.array([],dtype='int')
        if K < len(visited):
            for j in range(len(visited)-1):
                al = np.append(al,C[visited[j+1]])
            # print(al)
            a = al[1:].cumsum().max()
            # print(a)
            # a = acum.max()
        else:        
            for j in range(len(visited)-1):
                al = np.append(al,C[visited[j+1]])
            visitedLoop = visited[loopStart:]
            # print("visitedLoop: ",visitedLoop)
            sum_visitedLoop = 0
            for j in range(len(visitedLoop)):
                sum_visitedLoop += C[visitedLoop[j]]
            if sum_visitedLoop<=0:
                a = al.cumsum().max()
            else:
                # 残り回数を循環配列の長さで割った余り
                q,mod = divmod((K-len(visited)),len(visitedLoop))
                # print('q,mod:',q,mod)
                am = np.array([0],dtype='int')
                for j in range(mod+1):
                    am = np.append(am,C[visitedLoop[j]])
                    am_sum = am.cumsum().max()
                # print(am)
                # print('al:',al)
                # print(al.cumsum()[-1],q,sum_visitedLoop, am_sum)
                a = al.cumsum()[-1] + q*sum_visitedLoop + am_sum
        ans[i]=a
solve()
print(max(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=[]
for i in range(n):
    k1=i
    c1=0
    l1=[]#各初期値でのリスト
    l2=[]#ループするまでのリスト
    cl=0

    while True:
        if p[k1] not in l1:
            l1.append(p[k1])
            cl+=c[k1]
            l2.append(cl)
            k1=p[k1]-1
            if len(l1)==k:
                l.append(max(l2))
                break
        else:
            if cl<0:
                l.append(max(l2))
                break
            else:
                c1+=k*cl
                c1+=sum(l2[:k1%cl])
                l.append(c1)
                break
print(max(l))

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 = list(map(int,input().split()))
p = list(map(int,input().split()))
c = list(map(int,input().split()))

p = [i-1 for i in p]
import numpy as np
tuuka_id = []

point_list = []

for mass in range(n):
  score = 0
  scorelist = []
  move_cnt = 0
  st_mass = mass
  if mass in tuuka_id:
    continue
  
  tuuka_id.append(mass)
  while True:
    mass = p[mass]
    #print(mass, c[mass])
    tuuka_id.append(mass)
    score += c[mass]
    scorelist.append( c[mass] )
    move_cnt += 1
    
    if mass == st_mass:
      break
  
  scorel2 = scorelist + scorelist
  if move_cnt*2 =< k:
    mul = max(0,(k // move_cnt-1))
    k_res = move_cnt + k % move_cnt
    res_val = max([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )])
    point_list.append( max( score, res_val, score*mul + res_val ) )
  else:
    k_res = k
    res_val = max([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )])
    point_list.append( max( res_val ) )
    
print(point_list)

Submission status: Runtime Error

Solution code:
from itertools import accumulate
import sys
sys.setrecursionlimit(10**8)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def dfs(G, v, p):
    seen[v] = True
    his.append(v)
    sc.append(c[v])

    for nv in G[v]:
        if nv == p:
            continue
        if seen[nv]:
            pos[0] = nv
            return

        dfs(G, nv, v)
        if pos[0] != -1:
            return


G = [[] for _ in range(n)]
for i in range(n):
    G[i].append(p[i]-1)

seen = [False]*n
ans = -float('inf')
for i in range(n):
    if seen[i] == False:
        his = []
        pos = [-1]
        sc = []
        dfs(G, i, -1)

        sumsc = sum(sc)
        lenc = len(sc)
        for j in range(lenc):
            if j != 0:
                sc = sc[1:] + [sc[0]]
            ac = list(accumulate(sc))
            
            if sumsc <= 0:
                ans = max(ans, max(ac[:min(k, lenc)]))
            else:
                ans = max(ans, ac[-1] * (k//lenc) + max(ac[:k%lenc]))
print(ans)

Submission status: Runtime Error

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy
 
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            continue
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            continue
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            for j in range(mod):
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            continue
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

N,K = LI()
P = LI()
C = LI()

ans = [0] * N
P = list(map(lambda x:x-1,P))

def rec(visited,next):
    if next in s:
        return visited,visited.index(next)
    else:
        s.add(next)
        visited.append(next)
        return rec(visited,P[next])

for i in range(N):
    s = set([i])
    visited = [i]
    a = 0
    visited,loopStart = rec(visited,P[i])
    # print(visited,loopStart)
    al = np.array([],dtype='int')
    if K < len(visited):
        for j in range(len(visited)-1):
            al = np.append(al,C[visited[j+1]])
        # print(al)
        a = al[1:].cumsum().max()
        # print(a)
        # a = acum.max()
    else:        
        for j in range(len(visited)-1):
            al = np.append(al,C[visited[j+1]])
        visitedLoop = visited[loopStart:]
        # print("visitedLoop: ",visitedLoop)
        sum_visitedLoop = 0
        for j in range(len(visitedLoop)):
            sum_visitedLoop += C[visitedLoop[j]]
        if sum_visitedLoop<=0:
            a = al[1:].cumsum().max()
        else:
            # 残り回数を循環配列の長さで割った余り
            q,mod = divmod((K-len(visited)),len(visitedLoop))
            # print('q,mod:',q,mod)
            am = np.array([0],dtype='int')
            for j in range(mod+1):
                am = np.append(am,C[visitedLoop[j]])
                am_sum = am.cumsum().max()
            # print(am)
            # print('al:',al)
            # print(al.cumsum()[-1],q,sum_visitedLoop, am_sum)
            a = al.cumsum()[-1] + q*sum_visitedLoop + am_sum
    ans[i]=a

print(max(ans))

Submission status: Runtime Error

Solution code:
from itertools import accumulate
import sys
sys.setrecursionlimit(10**6)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def dfs(G, v, p):
    seen[v] = True
    his.append(v)
    sc.append(c[v])

    for nv in G[v]:
        if nv == p:
            continue
        if seen[nv]:
            pos[0] = nv
            return

        dfs(G, nv, v)
        if pos[0] != -1:
            return


G = [[] for _ in range(n)]
for i in range(n):
    G[i].append(p[i]-1)

seen = [False]*n
ans = -float('inf')
for i in range(n):
    if seen[i] == False:
        his = []
        pos = [-1]
        sc = []
        dfs(G, i, -1)

        sumsc = sum(sc)
        lenc = len(sc)
        for j in range(lenc):
            if j != 0:
                sc = sc[1:] + [sc[0]]
            ac = list(accumulate(sc))
            
            if sumsc <= 0:
                ans = max(ans, max(ac[:min(k, lenc)]))
            else:
                ans = max(ans, ac[-1] * (k//lenc) + max(ac[:k%lenc]))
print(ans)

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

ans = max(C)
for i in range(N):
    s = i
    l = [C[i]]
    while:
        s = P[s]
        if s == i:
            break
        l.append(C[s])
        

    if sum(l) > 0:
        c = K//len(l)*sum(l)
        n = K%len(l)
        ans = max(ans,c)
        s = i
        for j in range(n):
            c += C[s]
            s = P[s]
            ans = max(ans,c)

    n = min(N,K)
    s = i
    c = 0
    for j in range(n):
        c += C[s]
        s = P[s]
        ans = max(ans,c)
            
print(ans)

Submission status: Runtime Error

Solution code:
import copy

def cost_val(visit_list, P, C):
    maxval = [-10**10] * (len(P) + 1)
    for start_idx in visit_list:
        cost = 0
        now_id = start_idx
        for i in range(len(visit_list)):
            now_id = P[now_id]
            cost += C[now_id]
            maxval[i + 1] = max(maxval[i + 1], cost)
    return maxval[1:len(visit_list) + 1]

def cycles(P):
    cycle_list = []
    visit_list = [False] * len(P)
    for i in range(len(P)):
        if visit_list[i]:
            continue
        now_id = i
        cycle = []
        for j in range(len(P)):
            if visit_list[now_id]:
                break
            cycle.append(now_id)
            visit_list[now_id] = True
            now_id = P[now_id]
        cycle_list.append(cycle)
    return cycle_list

def main():
    N, K = map(int, input().split())
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    cycle_list = cycles(P)
    ans = -10**9
    for cycle in cycle_list:
        maxval = cost_val(cycle, P, C)
        if N >= K:
            ans = max(ans, max(maxval[:K]))
        else:
            ans = max(ans, max(maxval), maxval[-1] * (K // len(cycle)) + max(maxval[:(K % len(cycle))]))
    return ans

if __name__ == '__main__':
    print(main())

Submission status: Runtime Error

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy
 
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            continue
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            for j in range(mod):
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()

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**10
for st in range(N):
  now = st+1
  temp=[0]
  while(P[now-1] != st+1):
    temp.append(temp[-1]+C[P[now-1]-1])
    now = P[now-1]
    temp.append(temp[-1]+C[P[now-1]-1])
  if len(temp)>=K+1:
    ans=max(ans, max(temp[1:K+1]))
    continue
  if temp[-1]<=0:
    ans = max(ans, (max(temp[1:])))
  else::
    t=temp[-1]*(K//(len(temp)-1))-temp[-1]
    t+=max(temp+[temp[-1]+temp[i+1] for i in range(K%(len(temp)-1)+1)])
    ans=max(ans, t)
		
print(int(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
s = [C[P[i]-1] for i in range(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
        s[i] += C[P[j]-1]
        if  c[i] <= K:
            if s[i] > m[i][c[i]-1]:
                m[i][c[i]] = s[i]
            else:
                m[i][c[i]] = m[i][c[i]-1]
print(c)
print(s)
print(m)
ans = max(C)
for i in range(N):
    if s[i] > 0:
        print(s[i] * (K//c[i]) + m[i][K%c[i]])
        if  s[i] * (K//c[i]) + m[i][K%c[i]] > ans:
            ans = s[i] * (K//c[i]) + m[i][K%c[i]]
    else:
        print(max(m[i][1:min(c[i]+1,K+1)]))
        if m[i][min(c[i],K)] > ans:
            ans = m[i][min(c[i],K)]
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**10
for st in range(N):
  now = st+1
  temp=[0]
  while(P[now-1] != st+1):
    temp.append(temp[-1]+C[P[now-1]-1])
    now = P[now-1]
    temp.append(temp[-1]+C[P[now-1]-1])
  if len(temp)>=K+1:
    ans=max(ans, max(temp[1:K+1]))
    continue
  if temp[-1]<=0:
    ans = max(ans, (max(temp[1:])))
  else
    t=temp[-1]*(K//(len(temp)-1))-temp[-1]
    t+=max(temp+[temp[-1]+temp[i+1] for i in range(K%(len(temp)-1)+1)])
    ans=max(ans, t)
		
print(int(ans))

Submission status: Runtime Error

Solution code:
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            continue
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            for j in range(mod):
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**9)
N, K = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
weight = []
visited = [0]*N
ans = - float('inf')

def dfs(u, cnt, w):
  w += [C[u]]
  visited[u] = 1
  v = P[u]
  if visited[v] != 1:
    dfs(v, cnt+1, w)
  else:
    return


for i in range(N):
  weight = []
  visited = [0]*N
  dfs(i, 1, weight)
  print(i, weight)
  if len(weight) > K:
    weight = weight[:K]
    tmp = 0
    for j in range(K-1):
      weight[j+1] += weight[j]
    tmp = max(weight)
    ans = max(ans, tmp)
  else:
    s = sum(weight)
    if s > 0:
      tmp = (K//len(weight))*s
      weight = weight[:K%len(weight)]
      if len(weight) > 0:
        for j in range(len(weight)-1):
          weight[j+1] += weight[j]
        tmp += max(weight)
      elif len(weight) == 0:
        if weight[0] > 0:
          tmp += weight[0]
      ans = max(ans, tmp)
    else:
      tmp = 0
      for j in range(len(weight)-1):
        weight[j+1] += weight[j]
      tmp = max(weight)
      ans = max(ans, tmp)
print(ans)

Submission status: Runtime Error

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy
 
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            for j in range(mod):
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
C = list(map(int, input().split()))

memo = [[]  for i in range(n)]
for i in range(n):
    memo[i].append(C[i])
    j = P[i]
    while True:
        memo[i].append(memo[i][-1] + C[j])
        j = P[j]
        if j == i:
            memo[i].append(memo[i][-1] + C[j])
            break

circles = [memo[i][-1] - memo[i][0] for i in range(n)]

ans = -1e10
for i  in range(n):
    le = (len(memo[i]) - 1)
    m = k // le
    if circles[i] > 0 and m > 0:
        k_ = k % le
        if k_ > 0:
          alt = max(memo[i][:k_]) + circles[i] * m
        ans = max(alt, ans)
        alt =  max(memo[i][:-1]) + circles[i] * (m-1)
        ans = max(alt, ans)
    else:
        alt =  max(memo[i][:-1])
        ans = max(alt, ans)
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import accumulate
from collections import deque
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def dfs(G, v, p):
    seen[v] = True
    his.append(v)
    sc.append(c[v])

    for nv in G[v]:
        if nv == p:
            continue
        if seen[nv]:
            pos[0] = nv
            return

        dfs(G, nv, v)
        if pos[0] != -1:
            return


G = [[] for _ in range(n)]
for i in range(n):
    G[i].append(p[i]-1)

seen = [False]*n
ans = -float('inf')
for i in range(n):
    if seen[i] == False:
        his = []
        pos = [-1]
        sc = []
        dfs(G, i, -1)

        sumsc = sum(sc)
        lenc = len(sc)
        for j in range(lenc):
            if j != 0:
                sc = sc[1:] + [sc[0]]
            ac = list(accumulate(sc))
            
            if sumsc <= 0:
                ans = max(ans, max(ac[:min(k, lenc)]))
            else:
                ans = max(ans, ac[-1] * (k//lenc) + max(ac[:k%lenc]))
print(ans)

Submission status: Runtime Error

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy
 
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        tmp_max=-10e10
        tmp_ans=-10e10
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans+=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            for j in range(mod):
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()