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

Solution code:


from sys import stdin

N,K = map(int,stdin.readline().split())

P = list(map(int,stdin.readline().split()))
C = list(map(int,stdin.readline().split()))
end = [-1] * N
sc = [0] * N
for i in range(N):
    P[i] -= 1



ans = max(C)
for i in range(N):

    now = i
    nsum = 0
    lis = [0]
    cnt = None

    for j in range(min(N,K)):
        now = P[now]
        nsum += C[now]
        ans = max(ans , nsum)
        lis.append(nsum)

        if i == now and nsum > 0:
            ans = max(ans , nsum*(K//(len(lis)-1)) + max(lis[:K%(len(lis)-1)+1]))
            cnt = j+1
            break

    if cnt == None:
        continue
    
    loopnum = K // cnt
    if loopnum > 0:
        loopnum -= 1
    loopscore = loopnum * lis[-1]
    rem = K - cnt * loopnum

    now = i
    nsum = loopscore

    #print (lis,loopscore,cnt)

    for j in range(rem):
        now = P[now]
        nsum += C[now]
        ans = max(ans , nsum)

print (ans)

Submission status: Accepted

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)
if(ans <= 0):
    print(ans)
    exit()

for i in range(n):
    now = i
    score = [0]
    while(p[now] != i ):
        now = p[now]
        score.append(score[-1] + c[now])
    cyc_score = score[-1] + c[i]
    cyc = len(score)

    max_loop = k//cyc
    if(cyc_score <= 0):
        tmp = max(score[: min(k+1, cyc)])
    else:
        tmp = max(score) + (max_loop-1)*cyc_score
        tmp = max(tmp, max(score[:(k%cyc) + 1]) + max_loop*cyc_score)

    ans = max(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n, k = map(int, readline().split())
    p = list(map(int, readline().split()))
    p = [x - 1 for x in p]
    c = list(map(int, readline().split()))
    ans = -INF

    for i in range(n):
        cur = i
        nx = -1
        cnt = 0
        score_dict = dict()
        score_dict[0] = 0
        score = 0
        rem = k
        while rem > 0 and nx != i:
            cnt += 1
            rem -= 1
            nx = p[cur]
            score += c[nx]
            score_dict[cnt] = score
            ans = max(ans, score)
            cur = nx

        if rem > 0 and score > 0:
            loop = (rem - 1) // cnt
            if loop > 0:
                score += score * loop
                rem -= loop * cnt
            for j in range(rem + 1):
                st = score + score_dict[j]
                ans = max(ans, st)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
p = list(map(lambda x : int(x) - 1, input().split()))
c = list(map(int, input().split()))
score = [0] * (n + 1)

max_score = -10 ** 9
for i in range(n):
    x = i
    temp_max = [-10 ** 9] * (n + 1)
    for j in range(1, n + 1):
        score[j] = score[j - 1] + c[p[x]]
        temp_max[j] = max(temp_max[j-1], score[j])
        x = p[x]
        if x == i:
            break
    if j >= k:
        max_score = max(max_score, temp_max[k])
    elif score[j] < 0:
        max_score = max(max_score, temp_max[j])
    else:
        m = k // j
        a = score[j] * (m - 1) + temp_max[j]
        b = score[j] * m + temp_max[k % j]
        max_score = max(max_score, a, b)
print(max_score)

Submission status: Accepted

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

def naive(K, P, C):
    P = P - 1
    N = len(P)
    INF = 1 << 60
    ret = -INF
    for v in range(N):
        for n in range(1, K + 1):
            s = 0
            w = v
            for _ in range(n):
                s += C[w]
                w = P[w]
            ret = max(ret, s)
    return ret

@njit((i8, i8[:], i8[:]), cache=True)
def main(K, P, C):
    N = len(P)
    INF = 1 << 60
    P = P - 1
    best_score = -INF
    for v in range(N):
        w = v
        L = 0
        S = 0
        while True:
            S += C[w]
            L += 1
            w = P[w]
            if v == w:
                break
        score = 0
        w = v
        for n in range(1, L + 1):
            # はじめに n 個とったあと、周期
            score += C[w]
            w = P[w]
            if n > K:
                break
            max_add = (K - n) // L
            x = score + max(S * 0, S * max_add)
            best_score = max(best_score, x)
    return best_score

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

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

d = [[0]*N for _ in [0]*N]
l = [0]*N
for i in range(N):
    j = i
    cnt = 0
    while True:
        prev_j = j
        j = P[j]-1
        d[i][j] = d[i][prev_j] + C[j]
        cnt += 1
        if j==i: break
    l[i] = cnt

ans = -(10**10)
for i in range(N):
    n = (K-N)//l[i]
    tmp = max(0,d[i][i]) * n
    k = K - n*l[i]
    j = i
    for _ in range(2*N):
        if k<=0: break
        k -= 1
        tmp += C[j]
        j = P[j] -1
        ans = max(ans,tmp)

print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
if max(C) < 0:
    print(max(C))
else:
    maxAll = 0
    isCovered = [False] * n
    index = 0
    while index < n:
        if isCovered[index]:
            index += 1
            continue
        else:
            cycleCValue = []
            newIndex = index
            while newIndex != index or not cycleCValue:
                isCovered[newIndex] = True
                cycleCValue.append(C[P[newIndex] - 1])
                newIndex = P[newIndex] - 1
            maxValue = 0
            cycleCPartialSum = [0]
            for elem in cycleCValue:
                cycleCPartialSum.append(cycleCPartialSum[-1] + elem)
            for i in range(len(cycleCValue)): # number of elements to sum
                if i > k:
                    continue
                for j in range(len(cycleCValue)): # starting element
                    if i + j <= len(cycleCValue):
                        curSum = cycleCPartialSum[i + j] - cycleCPartialSum[j]
                    else:
                        curSum = cycleCPartialSum[(i + j) % len(cycleCValue)] + cycleCPartialSum[-1] - cycleCPartialSum[j]
                    if cycleCPartialSum[-1] > 0:
                        curSum += ((k - i) // len(cycleCValue)) * cycleCPartialSum[-1]
                    if curSum > maxValue:
                        maxValue = curSum
            if maxAll < maxValue:
                maxAll = maxValue
            index += 1
    print(maxAll)

Submission status: Accepted

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

ans = -float('inf')
v = []
for n in range(N):
    loop, score = 0, 0
    t = n
    for i in range(min(N, K)):
        n = P[n]-1
        score += C[n]
        ans = max(ans, score)
        if n == t:
            loop = i+1
            break
    v.append((loop, score))

for n in range(N):
    loop, score = v[n]
    if loop > 0 and score > 0:
        r = (K-1)//loop
        nscore = r*score
        for i in range(K-r*loop):
            n = P[n]-1
            nscore += C[n]
            ans = max(nscore, ans)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
P = [int(a)-1 for a in input().split()]
C = [int(a) for a in input().split()]
ma = -10 ** 10
for i in range(N):
    l = 1
    j = P[i]
    s = C[j]
    ma = max(ma, s)
    while j != i:
        j = P[j]
        s += C[j]
        l += 1
        if K >= l:
            ma = max(ma, s)
    
    c = 1
    j = P[j]
    t = C[j]
    if K >= c:
        ma = max(ma, t + (K - c) // l * s)
    
    while j != i:
        j = P[j]
        t += C[j]
        c += 1
        if K >= c:
            ma = max(ma, t + (K - c) // l * s)

print(ma)

Submission status: Accepted

Solution code:
def nasu(s):
  x = s
  ma = MC
  su = 0
  L = []
  for i in range(K):
    x = P[x] - 1
    su += C[x]
    L.append(C[x])
    ma = max(ma, su)
    if x == s:
      break
  else:
    return ma
  if su <= 0:
    return ma
  n = i + 1
  div, mod = divmod(K, n)
  ans = (div - 1) * su + ma
  da = div * su
  for i in range(mod):
    da += L[i]
    ans = max(ans, da)
  return ans

N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))
MC = min(C)

ans = MC
for i in range(N):
  ans = max(ans, nasu(i))
print(ans)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,k = LI()
    p = LI()
    for i in range(n):
        p[i] -= 1
    c = LI()
    bfs = [0]*n
    lis = []
    for i in range(n):
        if not bfs[i]:
            bfs[i] = 1
            x = i
            path = [c[x]]
            while 1:
                x = p[x]
                if bfs[x]:
                    break
                path.append(c[x])
                bfs[x] = 1
            lis.append([0]+list(accumulate(path*2)))
    ans = -float("inf")
    for path in lis:
        n = len(path) >> 1
        m = k//n
        if k%n == 0:
            m -= 1
        s = m*path[n]
        if s < 0:
            s = 0
            res = n
        else:
            res = k-m*n
        for l in range(n):
            for j in range(1,res+1):
                ns = s+path[l+j]-path[l]
                if ans < ns:
                    ans = ns
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(500005)
stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().strip()

n, k = na()
f = na()
c = na()

for i in range(n):
    f[i] -= 1

def mx(a, inf, sup):
    n = len(a)
    b = a + a
    ret = -1000000009 if inf > 0 else 0
    for i in range(n):
        s = 0
        for j in range(sup):
            s += b[i+j]
            if j >= inf-1:
                ret = max(ret, s)
    return ret

done = [False] * n
ans = -1000000007
for i in range(n):
    if not done[i]:
        a = []
        cur = i
        while not done[cur]:
            done[cur] = True
            a.append(c[cur])
            cur = f[cur]
        s = sum(a)
        need = k
        if need >= len(a):
            if s >= 0:
                can = need//len(a)*s + mx(a, 0, need % len(a))
                if need > 1:
                    can = max(can, (need//len(a)-1)*s + mx(a, 0, len(a)))
                else:
                    can = max(can, mx(a, 1, len(a)))
            else:
                can = mx(a, 1, len(a))
        else:
            can = mx(a, 1, need)
        ans = max(ans, can)

print(ans)

Submission status: Accepted

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

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

best = max(C)
for i in range(N):
    curr = 0
    score = [0]
    start = i
    while P[start] != i:
        start = P[start]
        curr += C[start]
        score.append(curr)
    cycle_score = score[-1] + C[i]
    cycle_len = len(score)

    for j in range(cycle_len):
        if j <= K and j != 0:
            cycles = (K - j)//cycle_len
            thing = score[j] + max(0, cycle_score) * cycles
            best = max(best, thing)
        elif j == 0 and K >= cycle_len:
            thing = cycle_score * K // cycle_len
            best = max(best,thing)

print(best)

Submission status: Runtime Error

Solution code:
N,K=list(map(int,input().split()))
import numpy as np
P=np.array(list(map(int,input().split())))
C=list(map(int,input().split()))
P=P-np.array([1]*N)
eachscore=np.zeros(N)
maxscore=np.zeros(K)
for i in range(K):
    eachscoreadd=np.zeros(N)
    for t in range(N):
        eachscoreadd[P[t]]=eachscore[t]+C[P[t]]
    eachscore=eachscoreadd
    maxscore[i]=max(eachscore)
print(max(maxscore))

Submission status: Runtime Error

Solution code:

import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            k2 = k - 1
            while k2:
                koko = p[koko] - 1
                cycle.append(c[koko])
                seen[koko] = 1
                if koko == i1:
                    cycles.append((cycle, True, sum(cycle)))
                    break
                k2 -= 1
            if k2 == 0:
                cycles.append((cycle, False, sum(cycle)))
    score_each_cycle = []
    for cycle in cycles:
        if cycle[1]:
            cycle0 = cycle[0]
            cycle_l = len(cycle0)
            kaisu, rem = divmod(k, cycle_l)
            scores = [0] * cycle_l
            scores[0] = cycle0[0]
            cycle0.extend(cycle0)
            cycle0 = [0] + cycle0
            cycle0 = tuple(accumulate(cycle0))
            for i1 in range(cycle_l):
                score = cycle0[1]
                for i2 in range(1, cycle_l+1):
                    score = max(score, cycle0[i1+i2]-cycle0[i1])
                scores[i1] = score
            if cycle[2] > 0:
                for j1 in range(rem + 1):
                    scores[j1] += kaisu * cycle[2]
            score_each_cycle.append((max(scores)))
        else:
            cycle0 = cycle[0]
            cycle_l = len(cycle[0])
            scores = [0] * cycle_l
            cycle0 = [0] + cycle0
            cycle0 = tuple(accumulate(cycle0))
            score = cycle0[1]
            for i1 in range(cycle_l):
                for i2 in range(1, cycle_l - i1):
                    score = max(score, cycle0[i1+i2]-cycle0[i1])
            score_each_cycle.append(score)
    r = max(max(c), max(score_each_cycle))
    print(r)

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=[]
for i in range(n):
  ct=0
  score=0
  s=[]
  pos=i
  while ct<k:
    ct+=1
    pos=p[pos]-1
    score+=c[pos]
    s.append(score)
    if pos==i:
      break
  if s[-1]<0:
    ans.append(max(s))
  elif pos!=i:
    ans.append(max(s))
  else:
    ans.append(max(s[-1]*(k//len(s)-1)+max(s),s[-1]*(k//len(s))+max(s[0:k%len(s)])))
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()))
ans=[]
for i in range(n):
  ct=0
  score=0
  s=[]
  pos=i
  while ct<k:
    ct+=1
    pos=p[pos]-1
    score+=c[pos]
    s.append(score)
    if pos==i:
      break
  if s[-1]<0:
    ans.append(max(s))
  elif pos!=i:
    ans.append(max(s))
  elif max(s)==max(s[0:k%len(s)]):
    ans.append(s[-1]*(k//len(s))+max(max(s[0:k%len(s)]),0))
  else:
    ans.append(s[-1]*(k//len(s)-1)+max(s))
print(max(ans))

Submission status: Runtime Error

Solution code:
a=[list(map(int,input().split(" "))) for i in range(3)]
score1=[0]*a[0][0]
for i in range(a[0][0]):
  num= i
  sco=0
  score2 = [0]*a[0][1]
  for j in range(a[0][1]):
    num = a[1][num]-1
    score2[j] = sco = sco+a[2][num]
  score1[i]=max(score2)
print(max(score1))

Submission status: Runtime Error

Solution code:
a=[list(map(int,input().split(" "))) for i in range(3)]
score1=[0]*a[0][0]
for i in range(a[0][0]):
  num= i
  score2 = [0]*a[0][1]
  for j in range(a[0][1]):
    num = a[1][num]-1
    score2[j] += a[2][num]
  score1[i]=max(score2)
print(max(score1))

Submission status: Runtime Error

Solution code:
a=[list(map(int,input().split(" "))) for i in range(3)]
print(score)
for i in range(a[0][0]):
  num= i
  for j in range(a[0][1]):
    num = a[1][num]-1
    score[i] += a[2][num]
print(max(score))

Submission status: Runtime Error

Solution code:
a=[list(map(int,input().split(" "))) for i in range(3)]
score =[0]*a[0][1]
for i in range(a[0][0]):
  num= i
  for j in range(a[0][1]):
    num = a[1][num]-1
    score[i] += a[2][num]
print(max(score))

Submission status: Runtime Error

Solution code:
a=[list(map(int,input().split(" "))) for i in range(3)]
score =[0]*a[0][1]
for i in range(a[0][0]):
  num= i
  for j in range(a[0][1]):
    num = a[1][num]-1
    print(num)
    score[i] += a[2][num]
print(max(score))

Submission status: Runtime Error

Solution code:
from numba import njit
n, k = map(int, input().split())
li_p = list(map(lambda x: int(x)-1, input().split()))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []
used = [0] * n
@njit
for i in range(n):
    if(used[i]):
        continue
    
    loop = []
    v = i
    while not used[v]:
        used[v] = 1
        loop.append(li_c[v])
        v = li_p[v]
    li_loop.append(loop)

ans = -(10**30) 
@njit
for loop in li_loop:
    loop_len = len(loop)

    cumsum = [0]*(2*loop_len+1)
    for i in range(2*loop_len):
        cumsum[i+1] = cumsum[i] + loop[i%loop_len]
    
    amari = [-(10**30)] * loop_len

    for i in range(loop_len):
        for j in range(loop_len):
            amari[j] = max(amari[j], cumsum[i+j] - cumsum[i])
    
    for r in range(loop_len):
        if r>k:
            continue
        q = (k-r)//loop_len
        if r==0 and q==0:
            continue
        if cumsum[loop_len]>0:
            ans = max(ans, amari[r] + cumsum[loop_len]*q)
        elif r>0:
            ans = max(ans, amari[r])
print(ans)

Submission status: Runtime Error

Solution code:
from copy import copy
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []
used = []

for i in range(n):
    if(i in used):
        continue

    point = [li_c[i]]
    cnt = 0
    path = [i]
    used.append(i)
    while True:
        used.append(li_p[path[-1]])
        path.append(li_p[path[-1]])
        point.append(li_c[path[-1]])
        if(len(path)!=len(set(path))):
            break
    loop = point[:-1]
    li_loop.append(loop)
    if len(used)==n:
        break

for loop in li_loop:
    loop_len = len(loop)
    cumsum = [0]*(2*loop_len+1)
    for i in range(2*loop_len):
        cumsum[i+1] = cumsum[i] + loop[i%loop_len]
    amari = [-100000000000] * loop_len

    for i in range(loop_len):
        for j in range(loop_len):
            amari[j] = max(amari[j], sum[i+j] - sum[i])

    if sum(loop):
        print(max(amari[:loop_len]))
    else:
        ans = -100000000000
        for r in range(loop_len):
            if r > k:
                continue
            if r==0 and (k-r//loop_len)==0:
                continue
            ans = max(ans, amari[r] + (k-r)//loop_len * sum(loop))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
pi = list(map(int, input().split()))
ci = list(map(int, input().split()))

pi = [p-1 for p in pi]

def cycle_score(i, pi, ci, n_cycles, mods):
    ssum = 0
    scores = [0] * len(pi)
    j = i
    cnt = 0
    max_score = -10**10
    max_mod_score = -10**10
    while 1:
        j = pi[j]

        s = ci[j]
        ssum += s
        max_score = max(ssum, max_score)

        if cnt < mods:
            max_mod_score = max(ssum, max_mod_score)
        # scores[cnt] = ssum

        cnt += 1

        if j == i:
            break

    if ssum > 0:
        ans = n_cycles * ssum + max_mod_score
    else:
        if n_cycles >= 1:
            ans = max_scores
        else:
            ans = max_mod_score

    return ans 


max_ans = -100000000000
for i in range(len(pi)):
    n_cycles = K // len(pi)
    mods = K % len(pi)
    ans = cycle_score(i, pi, ci, n_cycles, mods)
    max_ans = max(ans, max_ans)


print(max_ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
k_max = 5100
score = [-10**18-1] * N

for i in range(N):
  score_i = [-10**18-1] * k_max # iからスタートしてK回操作する場合の累積和
  score_i[0] = C[P[i]-1]
  index = P[i]-1
  for k in range(1, K):
    if index == i:
      # 既に進んだことがあるマスの場合
      
      loop_score = score_i[k-1] # 1ループで増えるスコア
      if loop_score > 0:
        loop_num = k # ループする要素数はk(indexが0 ~ k-1)
        
        tmp_score = [-10**18-1] * k_max
        tmp_score[0] = (K//k -1) * loop_score
#        print("loop_score", loop_score)
#        print("tmp_score", tmp_score)
        tmp_index = index
#        print("loop_num + K%k + 1", loop_num + K%k + 1)
        for j in range (1, loop_num + K%k + 1):
          tmp_score[j] = tmp_score[j-1] + C[P[tmp_index]-1]
          tmp_index = P[tmp_index]-1
#        print("max(tmp_score)", max(tmp_score))
        score_i[k] = max(tmp_score)
      break
    score_i[k] = score_i[k-1] + C[P[index]-1]
    index = P[index]-1
  score[i] = max(score_i)
print(max(score))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
pi = list(map(int, input().split()))
ci = list(map(int, input().split()))

pi = [p-1 for p in pi]

def cycle_score(i, pi, ci):
    ssum = 0
    scores = [0] * len(pi)
    j = i
    cnt = 0
    while 1:
        j = pi[j]

        s = ci[j]
        ssum += s
        scores[cnt] = ssum

        cnt += 1

        if j == i:
            break

    return scores


max_ans = -100000000000
for i in range(len(pi)):
    scores = cycle_score(i, pi, ci)
    n_cycles = K // len(scores)
    mods = K % len(scores)
 
    if scores[-1] > 0:
        this_ans = n_cycles * scores[-1] + max(scores[:mods])
    else:
        if n_cycles >= 1:
            this_ans = max(scores)
        else:
            this_ans = max(scores[:mods])

    max_ans = max(this_ans, max_ans)


print(max_ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
pi = list(map(int, input().split()))
ci = list(map(int, input().split()))

pi = [p-1 for p in pi]

def cycle_score(i, pi, ci):
    ssum = 0
    scores = []
    j = i
    while 1:
        j = pi[j]

        s = ci[j]
        ssum += s
        scores += [ssum]

        if j == i:
            break

    return scores


max_ans = -100000000000
for i in range(len(pi)):
    scores = cycle_score(i, pi, ci)
    n_cycles = len(scores) // K
    mods = len(scores) % K
 
    if scores[-1] > 0:
        this_ans = n_cycles * scores[-1] + scores[:mods]
    else:
        if n_cycles >= 1:
            this_ans = max(scores)
        else:
            this_ans = max(scores[:mods])

    max_ans = max(this_ans, max_ans)


print(max_ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
k_max = 5100
score = [0] * N

for i in range(N):
  score_i = [-10**18-1] * k_max # iからスタートしてK回操作する場合の累積和
  score_i[0] = C[P[i]-1]
  index = P[i]-1
  for k in range(1, K):
    if index == i:
      # 既に進んだことがあるマスの場合
      
      # ループ終了インデックスからループ開始インデックスの累積和の差を確認
      loop_score = score_i[k-1] # 1ループで増えるスコア
      if loop_score > 0:
        loop_num = k # ループする要素数はk(indexが0 ~ k-1)
        
        tmp_score = [-10**18-1] * k_max
        tmp_score[0] = (K//k -1) * loop_score
#        print("loop_score", loop_score)
#        print("tmp_score", tmp_score)
        tmp_index = index
        for j in range (1, loop_num + K%k+1):
          tmp_score[j] = tmp_score[j-1] + C[P[tmp_index]-1]
          tmp_index = P[tmp_index]-1
#        print("max(tmp_score)", max(tmp_score))
        score_i[k] = max(tmp_score)
      else:
        score[i] = max(score_i)
      break
    score_i[k] = score_i[k-1] + C[P[index]-1]
    index = P[index]-1
  score[i] = max(score_i)
print(max(score))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
k_max = 5001
score = [0] * N

for i in range(N):
  score_i = [-10**18-1] * k_max # iからスタートしてK回操作する場合の累積和
  score_i[0] = C[P[i]-1]
  index = P[i]-1
  for k in range(1, K):
    if index == i:
      # 既に進んだことがあるマスの場合
      
      # ループ終了インデックスからループ開始インデックスの累積和の差を確認
      loop_score = score_i[k-1] # 1ループで増えるスコア
      if loop_score > 0:
        loop_num = k # ループする要素数はk(indexが0 ~ k-1)
        
        tmp_score = [0] * k_max
        tmp_score[0] = (K//k -1) * loop_score
        tmp_index = index
        for j in range (1, loop_num + K%k):
          tmp_score[j] = tmp_score[j-1] + C[P[tmp_index]-1]
          tmp_index = P[tmp_index]-1
        score[i] = max(tmp_score)
      else:
        score[i] = max(score_i)
      break
    else:
      if k == K-1:
        score_i[k] = score_i[k-1] + C[P[index]-1]
        score[i] = max(score_i)
        break   
    score_i[k] = score_i[k-1] + C[P[index]-1]
    index = P[index]-1
print(max(score))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
k_max = 5001
score = [0] * N

for i in range(N):
  score_i = [-10**18-1] * k_max # iからスタートしてK回操作する場合の累積和
  score_i[0] = C[P[i]-1]
  index = P[i]-1
  for k in range(1, K):
    if index == i:
      # 既に進んだことがあるマスの場合
      
      # ループ終了インデックスからループ開始インデックスの累積和の差を確認
      loop_score = score_i[k-1] # 1ループで増えるスコア
      if loop_score > 0:
        loop_num = k # ループする要素数はk(indexが0 ~ k-1)
        
        tmp_score = [0] * k_max
        tmp_score[0] = (K//k -1) * loop_score
        tmp_index = index
        for j in range (1, loop_num + K%k + 1):
          tmp_score[j] = tmp_score[j-1] + C[P[tmp_index]-1]
          tmp_index = P[tmp_index]-1
        score[i] = max(tmp_score)
      else:
        score[i] = max(score_i)
      break
    else:
      if k == K-1:
        score_i[k] = score_i[k-1] + C[P[index]-1]
        score[i] = max(score_i)
        break   
    score_i[k] = score_i[k-1] + C[P[index]-1]
    index = P[index]-1
print(max(score))

Submission status: Runtime Error

Solution code:
def make_group(N,Ps):
    l = list(range(1,N+1))
    start = l[0]
    next = l.pop(0)
    l2 = []
    l3 = [start]
    while(len(l) != 0):
        if Ps[next-1] == start:
            l2.append(l3)
            start = l[0]
            next = l.pop(0)
            l3 = [start]
        else:
            l3.append(Ps[next-1])
            l.remove(Ps[next-1])
            next = Ps[next-1]
    l2.append(l3)
    return l2

def solve_max(l,Cs,k):
    for i in range(len(l)):
        sum = 0
        for j in range(k):
            index = (i + j) % len(l)
            sum += Cs[l[index]-1]
            if i == 0:
                m = sum
            else:
                if m < sum:
                    m = sum
    return m

def max_in_group(l,Cs,K):
    sum_list = []
    max_list = []
    sum = 0
    for i in range(len(l)):
        sum += Cs[l[i]-1]

    if len(l) > K:
        m = solve_max(l,Cs,K)
    elif  sum <= 0:
        m = solve_max(l,Cs,len(l))
    else:
        q = K // len(l)
        r = K % len(l)
        m_ = solve_max(l,Cs,r)
        m = q * sum + m_
    return m


N, K = list(map(int,input().split()))
Ps = list(map(int,input().split()))
Cs = list(map(int,input().split()))
groups = make_group(N,Ps)
m = max_in_group(groups[0],Cs,K)
for i in range(1,len(groups)):
    if m < max_in_group(groups[i],Cs,K):
        m = max_in_group(groups[i],Cs,K)
print(m)