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:
    #!/usr/bin/env python3
    import sys


    def solve(N: int, K: int, P: "List[int]", C: "List[int]"):

        if K > N-1:
            temp_max = C[0]
            for i in range(N):
                score_i = ["er"]*N 
                score_i_max = [0]*N
                h = P[i]-1
                score_i[0] = C[h]
                score_i_max[0] = C[h]
                if h == i: break
                for j in range(1, N):
                    h = P[h]-1
                    score_i[j] = score_i[j-1] + C[h]
                    score_i_max[j] = max(score_i[j-1], score_i[j])
                    if h == i: break

                # print(score_i)
                mod_k = K % (j+1)
                rat_k = K //(j+1)
                if score_i[j] > 0:
                    t = rat_k * score_i[j] + max(0,(score_i_max[mod_k-1]))
                    temp_max = max(t, temp_max)
                else:
                    temp_max = max(score_i_max[j], temp_max)

            print(temp_max)
        
        elif K <= N:
            score = [[0]*N for i in range(N)]
            temp_max = C[0]
            for i in range(N):
                h = i
                for j in range(1, K):
                    h = P[h]-1
                    score[i][j] = score[i][j-1] + C[h]
                    temp_max = max(score[i][j], temp_max)
            print(temp_max)


        return


    # Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
    def main():
        def iterate_tokens():
            for line in sys.stdin:
                for word in line.split():
                    yield word
        tokens = iterate_tokens()
        N = int(next(tokens))  # type: int
        K = int(next(tokens))  # type: int
        P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
        C = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
        solve(N, K, P, C)

    if __name__ == '__main__':
        main()

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

    P_id = [p - 1 for p in P]

    max_ = -float('inf')

    for start in range(N):
        # print("#loop{}".format(start))

        # 解析

        current = start
        visited = [-1] * N
        visited[current] = 0

        history = [current]
        before_loop_ids = []
        loop_ids = []

        for step in range(1, N):  # 高々N回で抜ける
            next_ = P_id[current]
            if visited[next_] != -1:
                # loop_start = history.index(next_)
                loop_start = visited[next_]
                loop_ids = history[loop_start:]
                before_loop_ids = history[:loop_start]
                history.append(next_)
                break
            else:
                history.append(next_)
                current = next_
                visited[current] = step

        score_per_loop = sum([C[i] for i in loop_ids])
        # print('history', history)
        # print('before', before_loop_ids)
        # print('loop', loop_ids)
        # print('score_per_loop', score_per_loop)

        score = 0
        current = start
        num_move = K

        # before loop

        for _ in range(min(len(before_loop_ids), K)):
            current = P_id[current]
            score += C[current]
            max_ = score if score > max_ else max_
            # max_ = max(max_, score)
            num_move -= 1

        # loop
        n = num_move // len(loop_ids)
        num_move -= n * len(loop_ids)
        if score_per_loop > 0:
            score += n * score_per_loop
            # max_ = max(max_, score)
            max_ = score if score > max_ else max_

        # after loop
        for i in range(num_move):
            current = P_id[current]
            score += C[current]
            # max_ = max(max_, score)
            max_ = score if score > max_ else max_
            num_move -= 1

        assert num_move == 0, 'expected:{} actual:{}'.format(0, num_move)

    print(max_)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

n, k = map(int, input().split())
k = k+1
p = [0] * n
c = [0] * n
a = [0] * (n+1)
ans = [0] * n

p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
    s = 0
    x = i
    roop = 0
    for j in range(n):
        s += c[x]
        a[j+1] = s
        x = p[x] - 1
        if x == i:
            roop = j + 1
            break
    if s < 0:
        ans[i] = max(a[1:min(roop, k-1)])
    else:
        if k%roop  == 0:
            ans[i] = max(s * (k // roop) , s * (k // roop - 1) + max(a))
        else:
            ans[i] = max(s * (k // roop) + max(a[:k % roop]), s * (k // roop - 1) + max(a))
print(max(ans))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**9)
N, K = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1
C = list(map(int, input().split()))

# memo = [[None for _ in range(K+1)] for _ in range(N)]

def f(now, count, nowVal, maxVal):
    if count == K:
        # print(max(maxVal, nowVal + C[P[now]]))
        return max(maxVal, nowVal + C[P[now]])

    tmpMax = max(maxVal, nowVal + C[P[now]])
    return f(P[now], count+1, nowVal+C[P[now]], tmpMax)

ans = -float("inf")
for i in range(N):
    ans = max(ans, f(i, 0, 0, -float("inf")))

print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]

ans = -float("inf")

# O(N)
for start in range(N):
    seen = [False] * N 
    cycle = []
    score = []
    
    seen[start] = True
    cycle.append(start)
    score.append(C[start])

    now = start
    # 鳩ノ巣原理からこのループは max 5000 しか回らない O(N)
    while True:
        nxt = P[now]-1
        if seen[nxt]:
            break
        
        cycle.append(nxt)
        score.append(C[nxt])

        now = nxt
    sum_v = sum(score)
    # 累積和
    score_sum = [ 0 for _ in range(len(score) + 1)]
    for i in range(len(score)):
        score_sum[i+1] = score_sum[i] + score[i]


    t_ans = max(score_sum[1:min(K, len(cycle))])

    #print(score_sum)
    #print(score_sum[:((K+1) % len(cycle))])
    
    if sum_v >= 0:
        aa = 0
        aa += (sum_v - C[start]) if K // len(cycle) > 0 else 0
        aa += sum_v * (K // len(cycle) - 1)
        nn = K % len(cycle)
        score_sum += score_sum[1:]
        if nn != 0:
            aa += max(score_sum[:nn+2])
        t_ans = max(t_ans, aa)
    else:
        t_ans = max(score_sum[1:min(K, len(cycle))])

    ans = max(ans, t_ans)

print(ans)

Submission status: Runtime Error

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

idx = c.index(max(c))
curr_sum = [c[idx]]


for i in range(k):
    idx = p[idx]
    curr_sum.append(curr_sum[-1] + c[idx])

print(max(curr_sum))

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
scores = []
for i in range(N):
  pos = P[i]-1
  s = [C[i]]
  j = 1
  while j < K and pos != i:
    s.append(s[-1]+C[pos])
    pos = P[pos]-1
    j += 1
  smax = max(s)
  length = len(s)
  if length < K and s[-1] > 0:
    smod = s[:K%length]
    smodmax = max(smod)
    if smax == smodmax:
      scores.append(s[length-1] * (K//length) + smax)
    else:
      scores.append(max(s[length-1] * ((K//length)-1) + smax, s[length-1] * (K//length), s[length-1] * (K//length) + smodmax))
  else:
    scores.append(smax)
print(max(scores))

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())

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

s = []
l = k % 5000
m = k // 5000
tc = sum(c)

for i in range(n):
    e = 0
    d = p[i]
    for j in range(l):
        e = e + c[d-1]
        d = p[d-1]
        s.append(e)

ans = m * tc + max(s)

print(ans)

Submission status: Runtime Error

Solution code:
def main():
    INF = 10**9
    n,k = map(int,input().split())
    P = [0] + list(map(int,input().split()))
    C = [0] + list(map(int,input().split()))

    scores = [0]*n

    for s in range(1,n+1):
        start = s
        dp = [-INF]*(n+2)
        dp[0] = 0
        for i in range(n):
            p = P[s]
            dp[i+1] = dp[i] + C[p]
            
            if start == p:
                break
            s = p
        if k <= i+1:
            scores[start-1] = max(dp[1:k+1])
        elif dp[i+1]<=0:
            scores[start-1] = max(dp[1:])
        else:
            r = k%(i+1)
            q = k//(i+1)
            scores[start-1] = max(max(dp[1:r+1])+dp[i+1]*q, max(dp[1:]))
    
    print(max(scores))
main()

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
P  = [0] + list(map(int,input().split()))
C = [0] + list(map(int,input().split()))

L = [[] for i in range(n+1)]
length = [0]*(n+1)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if j != 1:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = - float("Inf")

if k > n:

    
    for i in range(1,n+1):
        m = k//length[i]
        p = k%length[i]
        
        point = m * L[i][length[i]-1] + max(L[i][:p])

        ans = max(ans, point)

    
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
else:
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 17:30:06 2020

@author: divyarth
"""

import sys
import heapq
import math

#sys.setrecursionlimit(100000)
#input=sys.stdin.readline
#print=sys.stdout.write

from collections import deque
from collections import defaultdict
from collections import Counter

modH=int(10**9)+7
I=lambda : list(map(int,input().split(' ')))
def PRINT(lst,sep=' '): print(sep.join(map(str,lst)))


'''
s=input()
stack=[]
mm=0
for i in range(len(s)):
    if s[i]=='R':
        stack.append('R')
    else:
        cnt=0
        while len(stack):
            stack.pop()
            cnt+=1
        mm=max(mm,cnt)        
cnt=0
while len(stack):
    stack.pop()
    cnt+=1
mm=max(mm,cnt)
print(mm)
n=int(input())
lst=I()

if len(lst)<=2:
    print(0)
else:
    ans=0
    for i in range(len(lst)-2):
        for j in range(i+1,len(lst)-1):
            for k in range(j+1,len(lst)):
                a,b,c=sorted([lst[i],lst[j],lst[k]])
                if c<b+a and a!=b and b!=c and c!=a:
                    ans+=1
    print(ans)

    
'''
n,k=I()
PP=I()
c=I()
graph=[[] for i in range(n)]
for p in range(n):
    graph[p].append(PP[p]-1)

ans=[]
for start in range(n):
    visited=[0 for i in range(n)]
    node=start
    cycle=[]
    while not visited[node]:
        visited[node]=1
        cycle.append(c[node])
        node=graph[node][0]
    s=sum(cycle)*(k//len(cycle)) if sum(cycle)>=0 else 0
    cum_sum=[0]
    for sss in cycle: cum_sum.append(cum_sum[-1]+sss)
    ans.append((s+max([cum_sum[j+1] for j in range(k%len(cycle))])))
print(max(ans))

Submission status: Runtime Error

Solution code:
import sys
mINF = -float('inf')
n,k = map(int, sys.stdin.readline().rstrip("\n").split())
p = [int(s)-1 for s in sys.stdin.readline().rstrip("\n").split()]
c = [int(s) for s in sys.stdin.readline().rstrip("\n").split()]
loop = []
for i in range(n):
    loop_costs = []
    lc = 0
    np = i
    while True:
        lc += c[p[np]]
        loop_costs.append(lc)
        np = p[np]
        if np == i:
            break
    loop.append(loop_costs)
ans = mINF
for i in range(n):
    loop_i = loop[i]
    if len(loop_i) < k:
        if loop_i[-1] > 0:
            q, mod = divmod(k, len(loop_i))
            modmax = max(loop_i[:mod])
            ans = max(ans,loop_i[-1]*q+modmax)
        else:
            ans = max(ans,max(loop_i))
    else:
        ans = max(ans,max(loop_i[:k]))
print(ans)

Submission status: Runtime Error

Solution code:
def main():
    cells, moves = [int(x) for x in input().split()]
    nexts = [int(x) - 1 for x in input().split()]
    scores = [int(x) for x in input().split()]

    ans = -10 ** 9 - 5
    # whole_break = False
    for start in range(cells):
        route = []
        seen = set()
        route_append = route.append
        seen_add = seen.add
        now = start
        for _step in range(cells):
            nex = nexts[now]
            # if nex < start:
            #     whole_break = True
            #     break
            if nex in seen:
                break
            route_append(scores[nex])
            seen_add(nex)
            now = nex

        length = len(route)
        total = sum(route)
        # if whole_break:
        #     whole_break = False
        #     if moves > length:
        #         break

        if total > 0 and moves > length:
            q, mod = divmod(moves, length)
            candidate = max(sum(route[:x + 1]) for x in range(mod)) + total * q
        else:
            candidate = max(sum(route[:x + 1]) for x in range(length))
        ans = max(ans, candidate)

    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(int, input().split()))
for i in range(N):
    P[i] -= 1
C = list(map(int, input().split()))

# memo = [[None for _ in range(K+1)] for _ in range(N)]

def f(now, count, nowVal, maxVal):
    if count == K:
        # print(max(maxVal, nowVal + C[P[now]]))
        return max(maxVal, nowVal + C[P[now]])

    return f(P[now], count+1, nowVal+C[P[now]], tmpMax)

ans = -float("inf")
for i in range(N):
    ans = max(ans, f(i, 0, 0, -float("inf")))

print(ans)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
P  = [0] + list(map(int,input().split()))
C = [0] + list(map(int,input().split()))

L = [[] for i in range(n+1)]
length = [0]*(n+1)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if j != 1:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = - float("Inf")

if k > n:

    
    for i in range(1,n+1):
        m = k//length[i]
        p = k%length[i]
        
        point = m * L[i][length[i]-1] + max(L[i][:p])

        ans = max(ans, point)

    
    for a in L[1:]:
        if a =! []:
            ans = max(max(a[:k]), ans)
        
else:
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), 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 = -1 * float("inf")
for i in range(N):
    now_s = C[i]
    S = [C[i]]
    score = [C[i]]
    pre = [i]
    cur = i
    while True:
        if P[cur]-1 in pre:
            break
        cur = P[cur] - 1
        pre.append(cur)
        now_s += C[cur]
        S.append(now_s)
        score.append(C[cur])
    #print(score)
    #print(S)
    #print(pre)
    L = len(score)    
    if K <= L-1:
        ans = max(ans,max(S[1:K])-S[0])
    else:
        Sum = S[-1]
        if Sum <= 0:
            ans = max(ans,max(S[1:K])-S[0])
        else:
            if K % L == 0:
                ans = max(ans, (Sum * (K // L -1)) + max(S[1:K])-S[0])
            elif K % L == 1:
                ans = max(ans, (Sum * (K // L)) + max(0,S[1]-S[0]))
            else:
                ans = max(ans, (Sum * (K // L)) + max(S[1:K%L+1])-S[0])
                #print(S[1:K%L])
print(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()))

    P_id = [p - 1 for p in P]

    max_ = -float('inf')

    for start in range(N):
        # print("#loop{}".format(start))

        # 解析

        current = start
        visited = [-1] * N
        visited[current] = 0

        history = [current]
        before_loop_ids = []
        loop_ids = []

        for step in range(1, N):  # 高々N回で抜ける
            next_ = P_id[current]
            if visited[next_] != -1:
                # loop_start = history.index(next_)
                loop_start = visited[next_]
                loop_ids = history[loop_start:]
                before_loop_ids = history[:loop_start]
                history.append(next_)
                break
            else:
                history.append(next_)
                current = next_
                visited[current] = step

        score_per_loop = sum([C[i] for i in loop_ids])
        # print('history', history)
        # print('before', before_loop_ids)
        # print('loop', loop_ids)
        # print('score_per_loop', score_per_loop)

        score = 0
        current = start
        num_move = K

        # before loop

        for _ in range(min(len(before_loop_ids), K)):
            current = P_id[current]
            score += C[current]
            max_ = score if score > max_ else max_
            # max_ = max(max_, score)
            num_move -= 1

        # loop
        n = num_move // len(loop_ids)
        num_move -= n * len(loop_ids)
        if score_per_loop > 0:
            score += n * score_per_loop
            # max_ = max(max_, score)
            max_ = score if score > max_ else max_

        # after loop
        for i in range(num_move % len(loop_ids)):
            current = P_id[current]
            score += C[current]
            # max_ = max(max_, score)
            max_ = score if score > max_ else max_
            num_move -= 1

        assert num_move == 0, 'expected:{} actual:{}'.format(0, num_move)

    print(max_)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
P  = [0] + list(map(int,input().split()))
C = [0] + list(map(int,input().split()))

L = [[] for i in range(n+1)]
length = [0]*(n+10)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if j != 1:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = -float("Inf")

if k > n:

    
    for i in range(1,n+1):
        m = k//length[i]
        p = k%length[i]
        
        point = m * L[i][length[i]-1] + max(L[i][:p])

        ans = max(ans, point)

    
    for a in L[1:]:
        ans = max(max(a[:k]), ans)
        
else:
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
print(ans)

Submission status: Runtime Error

Solution code:

n, k = map(int, input().split())
k = k+1
p = [0] * n
c = [0] * n
a = [0] * (n+1)
ans = [0] * n

p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
    s = 0
    x = i
    roop = 0
    for j in range(n):
        s += c[x]
        a[j+1] = s
        x = p[x] - 1
        if x == i:
            roop = j + 1
            break
    if s < 0:
        ans[i] = max(a[1:min(roop+1, k-1)])
    else:
        ans[i] = max(s * (k // roop) + max(a[:k % roop]), s * (k // roop - 1) + max(a))
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()))

score = [0] * N
circle = [0] * N
circleScore = [0] * N
circleCnts = [0] * N
isReached = [False] * N
initiate = False

reach = []
cScore = 0
ans = -float('inf')
ansi = 0

def dfs(n, score):
    global cScore
    if isReached[n]:
        cScore = score
        return
    isReached[n] = True
    reach.append(n)
    dfs(P[n]-1, score + C[P[n]-1])

def dfsCalc(n, score, k, lim):
    global ansi, initiate
    if isReached[n] or k == lim:
        return

    isReached[n] = True
    if initiate:
        ansi = max(score + C[n], ansi, score)
    else:
        initiate = True
    dfsCalc(P[n]-1, score + C[n], k + 1,lim)


for n in range(N):
    reach = []
    dfs(P[n]-1, 0)
    for r in reach:
        circleCnts[r] = len(reach)
        circleScore[r] = cScore

for a in range(N):
    ansi = -float("inf")
    initiate = False
    isReached = [False] * N
    # print("circleCnts: ", circleCnts[a], " K: ", K)
    if K <= circleCnts[a]:
        if K != 1:
            dfsCalc(P[a] - 1, 0, 0, K)
        else:
            ansi = C[P[a] - 1]
        score[a] = ansi
    else:
        d = K % circleCnts[a]
        amount = K // circleCnts[a]
        ansPlus = 0
        if circleScore[a] > 0:
            ansPlus = amount * circleScore[a]
        if d != 1:
            dfsCalc(P[a] - 1, 0, 0, d)
        else:
            ansi = C[P[a] - 1]
        score[a] = ansi + ansPlus


#print(circleCnts)
#print(circleScore)
ans = max(score)
#print(score)
print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

def li():
    return [int(x) for x in input().split()]


N, K = li()
P = [0] + li()
C = [0] + li()

max_scores = [-10**12] * (N+10)
for init_i in range(1, N+1):
    i = init_i
    scores = [-10**12] * (K+10)
    scores[0] = 0
    for l in range(1, K+1):
        i = P[i]
        scores[l] = scores[l-1] + C[i]
    scores[0] = -10**12
    max_scores[i] = max(scores)
print(max(max_scores))

Submission status: Runtime Error

Solution code:
def abc175d_moving_piece():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    cost = [[None] * k for _ in range(n)]

    for i in range(n):
        for j in range(1, k+1):
            pos = i
            total = 0
            for l in range(j):
                if cost[pos][j-l-1] is None:
                    pos = p[pos]-1
                    total += c[pos]
                else:
                    total += cost[pos][j-l-1]
                    break
            cost[i][j-1] = total
    print(max(max(cost)))
abc175d_moving_piece()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
from itertools import accumulate #list(accumulate(A))

N, K = mi()
P = li()
C = li()
ans = -float('inf')

for i in range(N):
    ind = i
    his = []
    while True:
        ind = P[ind] - 1
        his.append(C[ind])
        if ind == i:
            his = list(accumulate(his))
            print(his)
            L = len(his)
            if K > L:
                if his[-1] > 0:
                    if not K%L:
                        ans = max(ans, his[-1] * (K//L))
                    else:
                        ans = max(ans, max(his[:K%L]) + his[-1] * (K//L), his[-1] * (K//L))
                else:
                    ans = max(ans, max(his))
            else:
                ans = max(ans, max(his[:K]))
            break

print(ans)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
P  = [0] + list(map(int,input().split()))
C = [0] + list(map(int,input().split()))

L = [[] for i in range(n+1)]
length = [0]*(n+1)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if j != 1:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = -float("Inf")

if k > n:

    
    for i in range(1,n+1):
        m = k//length[i]
        p = k%length[i]
        
        point = m * L[i][length[i]-1] + max(L[i][:p])

        ans = max(ans, point)

    
    for a in L[1:]:
        ans = max(max(a[:k]), ans)
else:
    for a in L[1:]:
        ans = max(max(a[:k]), ans)
        
print(ans)

Submission status: Runtime Error

Solution code:

import math

def maxSubArray(nums):
    dp = [0 for _ in range(len(nums))]
    dp[0] = nums[0]
    for i in range(1, len(nums)):
        dp[i] = max(dp[i-1]+nums[i], nums[i])
    return dp


n,k = map(int,input().split())
p_list = list(map(int, input().split()))
c_list = list(map(int, input().split()))

score = 0


new_list = []
t = 0
used = []
while len(used) != n:
    kari = []
    while t not in used:
        kari.append(c_list[t])
        used.append(t)
        t = p_list[t] -1
    if kari != []:
        new_list.append(kari)
    t = t + 1

answer_list = []

for j in range(len(new_list)):
    le = len(new_list[j])
    j_list = new_list[j] + new_list[j]
    cycle_point = sum(new_list[j])

    if cycle_point > 0:
        if le > k:
            dp = maxSubArray(j_list)
            dp = dp[:k]
            answer_list.append(max(dp))
        else:
            dp = maxSubArray(j_list)
            r = math.floor(k/le)
            p = k - r*le
            dp = dp[:p]
            answer_list.append(max(dp) + cycle_point*r)
    else:
        dp = maxSubArray(j_list)
        dp = dp[:k]
        answer_list.append(max(dp))

print(max(answer_list))

Submission status: Runtime Error

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

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

score = [0] * N

s = sum(C)
l = K // N
m = K % N

if s <= 0:
    for i in range(N):
        now = i
        tmp = min(N, K)
        tmp_scores = []
        while tmp > 0:
            now = P[now] - 1
            score[i] += C[now]
            tmp_scores.append(score[i])
            tmp -= 1
        score[i] = max(tmp_scores)
    ans = max(score)
else:
    for i in range(N):
        now = i
        tmp = m
        tmp_scores = []
        while tmp > 0:
            now = P[now] - 1
            score[i] += C[now]
            tmp_scores.append(score[i])
            tmp -= 1
        score[i] = max(tmp_scores)
    ans = max(score) + l * s

print(ans)
# print(score)
# print(29507023469 - s * 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()))
l = [0]*k
for i in range(n):
  for j in range(k):
    if j == 0:
      l[j] = c[p[i]-1]
      posi = p[i]-1
    else:
      l[j] = l[j-1] + c[p[posi]-1]
      posi = p[posi]-1
  if i == 0:
    r = max(l)
  else:
    r = max(r,max(l))
print(r)

Submission status: Runtime Error

Solution code:
import itertools
N,K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
places = []
n = 0
i = 0
T = list(range(1,N))
while n < N:
    L = [i]
    n += 1
    for _ in range(N):
        if not P[i] in L:
            i = P[i]
            T.remove(i)
            L.append(i)
            n += 1
        else:
             break
    places.append(L)
    if T:
        i = T[0]
scores = []
for L in places:
    s = 0
    M = []
    for l in L:
        s += C[l]
        M.append(s)
    scores.append(M)
ans = -(10**9)
for L in scores:
    l = len(L)
    if K >= l:
        ans = max(ans,L[-1])
        if L[-1] > 0:
            ans = max(ans,L[-1] * (K//l))
    for i,j in itertools.combinations(range(l),2):
        if j-i <= K:
            n = 0
            if L[-1] > 0:
                n = L[-1] * ((K-j+i)//l)
            ans = max(ans, L[j]-L[i]+n)
        if N-j+i <= K:
            n=0
            if L[-1]>0:
                n= L[-1] * ((K-l+j-i)//l)
            ans = max(ans,L[i] + L[-1] - L[j]+n)
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()))
a=-10**13
for i in range(n):
    b=0
    l=[]
    j=p[i]-1
    l+=[c[p[i]-1]]
    while j!=i:
        l+=[l[-1]+c[p[j]-1]]
        j=p[j]-1
    if len(l)>=k:
        b+=max(l)
    else:
        z=l[-1]
        if z<0:
            b+=max(l)
        else:
            q=len(l)
            b+=z*(k//q)+max(l[:k%q])

    if a<b:
        a=b
print(a)