Problem:


Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Runtime Error

Solution code:
import numpy as np

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

scores = np.zeros((N,K))
print(scores)

for i in range(N):
    position = i
    for k in range(K):
        if k == 0:
            scores[i][k] = C[P[position]-1]
        else:
            scores[i][k] = C[P[position]-1] + scores[i][k-1]
        position = P[i]-1

print(int(scores.max()))

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**15
dp = [[0]*(n+1) for _ in range(k+1)]
for i in range(k):
    for j in range(n):
        dp[i+1][P[j]-1] = dp[i][j]+C[P[j]-1]
    ans = max(ans, max(dp[i+1][:-1]))
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(score_sum))])

    #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) 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(score_sum))])

    ans = max(ans, t_ans)

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+1)
        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:
import sys
import numpy as np
input = sys.stdin.buffer.readline
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))
PG = {}
CG = {}
G = [-1] * (N + 1)


def f(n):
    if G[n] == -1:
        idx = len(PG) + 1
        _P = []
        _C = []
        i = n
        while True:
            if P[i] in _P:
                break
            _P.append(P[i])
            _C.append(C[P[i]])
            G[P[i]] = idx
            i = P[i]
        PG[idx] = _P
        CG[idx] = _C
    else:
        _P = PG[G[n]]
        _C = CG[G[n]]
        idx = _P.index(n) + 1
        # print(f'{idx=}')
        _P = _P[idx:] + _P[:idx]
        _C = _C[idx:] + _C[:idx]
    # print(f'{_P=}, {_C=}')
    if len(_P) < K:  # ぐるぐる回れる
        cumsum = np.array(_C).cumsum()
        if cumsum[-1] <= 0:  # cumsumの最後が0以下だったらぐるぐる回らずmaxのところでやめる
            ans = cumsum.max()
            # print(f'case 1 {cumsum=}, {ans=}')
            return ans
        div, mod = divmod(K, len(_P))
        ans = div * cumsum[-1]
        ans = max(ans, ans + cumsum[:mod].max())
        return ans
    else:
        cumsum = np.array(_C[:K]).cumsum()
        ans = cumsum.max()
        # print(f'{cumsum=}, {ans=}')
        return ans
    return 0


# f(1)
# print('')
# f(2)
# print('')
# f(3)
# print('')
# f(4)
# print('')
# f(5)

ans = f(1)
for i in range(1, N + 1):
    ans = max(ans, f(i))
# print(f'last answer = {ans}')
# print(f'{G=}, {PG=}, {CG=}')
print(ans)

Submission status: Runtime Error

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

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(k, 0, -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]
                    cost[i][l] = total
                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:
n,k = map(int, input().split())
lst1 = [ int(i) for i in input().split()]
lst2 = [ int(i) for i in input().split()]
visited = [0]*n
count = 0
track = []
count_lst = []
x = 0
while True:
    track.append(lst2[x-1])
    visited[x-1] = 1
    if visited[x-1] != 0:
        max = track[0]
        for d in track:
            c += d
            if max < d:
                max = d
        count_lst.append(max)
        for i, num in enumerate(visited):
            if num == 0:
                x = i
                count = 0
        break
    else:
        x = lst1[x-1]
print(max(count_lst))

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

Submission status: Runtime Error

Solution code:
N, K = list(map(int, input().split()))
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))
ans = -10**9-1
for i in range(N):
    cumsum = [0]*(N+1)
    seen = [-1]*N
    K_ = K
    now = i
    j = 0
    while K_ > 0 and seen[now] == -1:
        seen[now] = 1
        now = P[now]
        cumsum[j+1] = cumsum[j] + C[now]
        K_ -= 1
        j += 1
    if K_ == 0:
        ans = max(ans, max(cumsum[1:j]))
    else:
        if cumsum[j] > 0:
            loop_size = j
            loop_n = K//loop_size - 1
            tmp = loop_n*cumsum[loop_size]
            tmp += max(max(cumsum[1:loop_size]), cumsum[loop_size] + max(cumsum[1:K_%loop_size+1]))
            ans = max(ans, tmp)
        else:
            ans = max(ans, max(cumsum[1:j]))
print(ans)

Submission status: Runtime Error

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

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

maxpoints=[]
points=[]

for i in range(n):
    gone=set([])
    now=i
    next=p[now]
    point=c[next]
    maxpoint=[point]
    gone.add(i)

    for j in range(min(k,n)):
        now=next
        next=p[now]
        if next in gone:
            point+=c[next]
            maxpoint.append(max(maxpoint[-1],point))
            maxpoints.append(maxpoint)
            points.append(point)
            break
        point+=c[next]
        gone.add(now)
        maxpoint.append(max(maxpoint[-1],point))

#print(maxpoints)
#print(points)

ans=-float('inf')

for i in range(n):
    if k<=n:
        temp=maxpoints[i][k-1]
    elif points[i]<=0:
        temp=maxpoints[i][-1]
    else:
        times=k//len(maxpoints[i])
        odd=k%len(maxpoints[i])
        temp=points[i]*times+maxpoints[i][odd-1]
    ans=max(temp,ans)
print(ans)

Submission status: Runtime Error

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

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 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)
        after = 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(after):
            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:
from collections import deque
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
p=[0]+p
c=[0]+c

root=[[] for _ in range(n+1)]
point=[[] for _ in range(n+1)]
s=[[] for _ in range(n+1)]
ss=[[] for _ in range(n+1)]

ans=-(10**15)
for i in range(1,n+1):
    loc=i
    r=deque([i])
    a=0
    while True:
        loc=p[loc]
        if r[0]!=loc:
            a+=c[loc]
            point[i].append(c[loc])
            r.append(loc)
            ss[i].append(a)
        else:
            a+=c[loc]
            point[i].append(c[loc])
            r.append(loc)
            s[i]=a
            ss[i].append(a)
            break
    root[i]=list(r)
for i in range(1,n+1):
    score=0
    if s[i]<=0:
        if k>=len(point[i]):
            score=max(ss[i])
        else:
            score=max(ss[i][:k])
    else:
        a=k//len(point[i])
        b=k%len(point[i])
        score+=a*s[i]
        score+=max(ss[i][:b])
    ans=max(ans,score)
print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**6)
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))
scores = list()
max_list = list()
for i in range(N):
    next = Ps[i] - 1
    scores = [Cs[next]]
    while next != i:
        next = Ps[next] - 1
        scores.append(Cs[next]+scores[-1])
    l = len(scores)
    if scores[-1] <= 0 or l >= K:
        max_list.append(max(scores[:min(l,K)]))
    else:
        a, b = divmod(K, l)
        max_list.append(a*scores[-1] + max(scores[:b]))
    #print(scores)
print(max(max_list))

Submission status: Runtime Error

Solution code:
import sys
from itertools import accumulate

input = sys.stdin.readline


class UnionFind:
    """Union Find class.

    "Path compression" and "Union by rank" are used.

    References:
        <https://en.wikipedia.org/wiki/Disjoint-set_data_structure>
    """

    def __init__(self, N):
        self.N = N
        self.__make_set()

    def __make_set(self):
        self._parent = list(range(self.N + 1))
        self._rank = [0] * (self.N + 1)
        self._size = [1] * (self.N + 1)

    def find(self, x):
        if self._parent[x] != x:
            self._parent[x] = self.find(self._parent[x])
        return self._parent[x]

    def union(self, x, y):
        x_root = self.find(x)
        y_root = self.find(y)

        if x_root == y_root:
            return

        x_rank = self._rank[x_root]
        y_rank = self._rank[y_root]
        if x_rank > y_rank:
            self._parent[y_root] = x_root
            self._size[x_root] += self._size[y_root]
        elif x_rank < y_rank:
            self._parent[x_root] = y_root
            self._size[y_root] += self._size[x_root]
        else:
            self._parent[y_root] = x_root
            self._rank[x_root] += 1
            self._size[x_root] += self._size[y_root]

    def same_set(self, x, y):
        return self.find(x) == self.find(y)

    def size(self, x):
        return self._size[self.find(x)]


def main():
    N, K = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))

    uf = UnionFind(N)
    for i, p in enumerate(P, 1):
        uf.union(i, p)

    ans = -float("inf")
    visited_cc = set()
    for i in range(1, N + 1):
        cc = uf.find(i)
        if cc in visited_cc:
            continue
        visited_cc.add(cc)

        CC = []
        j = P[i - 1]
        while True:
            CC.append(C[j - 1])
            if i == j:
                break
            j = P[j - 1]
        n_CC = len(CC)
        loop_cost = sum(CC)
        CC = list(accumulate([0] + CC * 2))

        if K < n_CC:
            cost = [-float("inf")] * n_CC
            for n_move in range(1, K):
                for j in range(n_CC):
                    tmp = CC[j + n_move] - CC[j]
                    cost[n_move - 1] = max(cost[n_move - 1], tmp)
            res = max(cost)
        else:
            cost = [-float("inf")] * n_CC
            for n_move in range(1, n_CC):
                for j in range(n_CC):
                    tmp = CC[j + n_move] - CC[j]
                    cost[n_move - 1] = max(cost[n_move - 1], tmp)
            q, r = divmod(K, n_CC)
            if loop_cost > 0:
                res = max(loop_cost * q + max(cost[:r]), loop_cost * (q - 1) + max(cost))
            else:
                res = max(cost)

        ans = max(ans, res)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

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


N, K = li()
P = [0] + li() + [0]*10
C = [0] + li() + [0]*10
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:
import sys
import numpy as np
input = sys.stdin.buffer.readline
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))
PG = {}
CG = {}
G = [-1] * (N + 1)


def f(n):
    if G[n] == -1:
        idx = len(PG) + 1
        _P = []
        _C = []
        i = n
        while True:
            if P[i] in _P:
                break
            _P.append(P[i])
            _C.append(C[P[i]])
            G[P[i]] = idx
            i = P[i]
        PG[idx] = _P
        CG[idx] = _C
    else:
        _P = PG[G[n]]
        _C = CG[G[n]]
        idx = _P.index(n) + 1
        # print(f'{idx=}')
        _P = _P[idx:] + _P[:idx]
        _C = _C[idx:] + _C[:idx]
    # print(f'{_P=}, {_C=}')
    if len(_P) < K:  # ぐるぐる回れる
        cumsum = np.array(_C).cumsum()
        if cumsum[-1] <= 0:  # cumsumの最後が0以下だったらぐるぐる回らずmaxのところでやめる
            ans = cumsum.max()
            # print(f'case 1 {cumsum=}, {ans=}')
            return ans
        div, mod = divmod(K, len(_P))
        ans = div * cumsum[-1]
        ans = max(ans, ans + cumsum[:mod].max())
        return ans
    else:
        cumsum = np.array(_C[:K]).cumsum()
        ans = cumsum.max()
        # print(f'{cumsum=}, {ans=}')
        return ans


# f(1)
# print('')
# f(2)
# print('')
# f(3)
# print('')
# f(4)
# print('')
# f(5)

ans = f(1)
for i in range(1, N + 1):
    ans = max(ans, f(i))
# print(f'last answer = {ans}')
# print(f'{G=}, {PG=}, {CG=}')
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import accumulate
N, K = map(int, input().split())
P = [i-1 for i in map(int, input().split())]
C = list(map(int, input().split()))

seen = [0] * N

ans = -10**20

for i in range(N):
    if not seen[i]:
        seen[i] = 1
        loop = [C[i]]
        while True:
            i = P[i]
            if seen[i]:
                break
            seen[i] = 1
            loop.append(C[i])
        L = len(loop)
        loop = loop + loop
        loop = [0] + list(accumulate(loop))
        if loop[L] <= 0:
            move = min(L, K)
            for i in range(L):
                for j in range(1, move + 1):
                    ans = max(ans, loop[i + j] - loop[i])
        else:
            if K > L:
                div, mod = divmod(K, L)
                tmp = div * loop[L]
                move = min(mod, L)
                if move:
                    for i in range(L):
                        for j in range(1, move + 1):
                            ans = max(ans, tmp + loop[i + j] - loop[i])
                else:
                    ans = max(ans, tmp)
                tmp = (div - 1) * loop[L]
                move = L
                for i in range(L):
                    for j in range(1, move + 1):
                        ans = max(ans, tmp + loop[i + j] - loop[i])
            else:
                move = K
                for i in range(L):
                    for j in range(1, move + 1):
                        ans = max(ans, tmp + loop[i + j] - loop[i])

print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 63


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] < 0 or K <= len(loop)-2:
                j = i
                max_val = -INF
                iter = 0
                done = False
                while iter <= K:
                    if j >= len(loop):j=0
                    if i != j and j:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    iter += 1
                    if done : break
                    if i == j: done = True
                ans = max(ans, max_val)
                continue


            rest = K
            #if K <= len(loop) - i - 1:
            #    val += loopSum[i + K - 1] - loopSum[i]
            #    ans = max(ans, val)
            #    continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            val += max(loopSum[:rest])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, k = map(int, input().split())
p = [int(x) - 1 for x in input().split()]
c = [int(x) for x in input().split()]

ans = -float('inf')
for i in range(n):
    now = i
    c_sum = [0]
    s = set()
    cnt = 0
    while True:
        s.add(now)
        c_sum.append(c_sum[-1] + c[now])
        cnt += 1
        now = p[now]
        if now in s:
            break
    if k < cnt:
        ans = max(ans, max(c_sum[1: k + 1]))
    else:
        score = c_sum[-1]
        count = k // cnt
        k_ = k - count*cnt
        score *= count
        score += max(c_sum[1: k_ + 1])
        ans = max(ans, score, max(c_sum[1: ]))
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()))

check_flag = [0] * (N + 1)
check_flag[0] = 1

point_list = [[0]]
for i in range(1, N + 1):
    point = []
    p = 0
    buf = i
    while P[buf] != i:
        buf = P[buf]
        p += C[buf]
        point.append(p)
    buf = P[buf]
    p += C[buf]
    point.append(p)
    point_list.append(point)

max_list = []
for j in range(1, N + 1):
    if point_list[j][-1] <= 0:
        if len(point_list[j]) > K:
            max_list.append(max(point_list[j][:K]))
        else:
            max_list.append(max(point_list[j]))
    else:
        if len(point_list[j]) > K:
            max_list.append(max(point_list[j][:K]))
        else:
            division, mod = divmod(K, len(point_list[j]))
            max_list.append(division * point_list[j][-1] + max(point_list[j][:mod]))

ans = max(max_list)
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( )))

def score(i):
    log = [-1 for i in range(N)]
    log_score = []
    now = i
    count = 0
    while log[now] == -1:
        log[now] = count
        count += 1
        now = P[now]-1
        log_score.append(C[now])
    n = len(log_score)
    score = [sum(log_score[:i+1]) for i in range(n)]
    if log[now] == 0:
        lag = 0
        lag_score = 0
        roop_score = [log_score[0]]
        for i in log_score[1:]:
            roop_score.append(roop_score[-1] + i)
        roop = len(roop_score)
    else:
        lag = log[now]
        lag_score = sum(log_score[:lag])
        roop_score = [sum(log_score[lag:i+1]) for i in range(lag,n)] 
        roop_score = [log_score[lag]]
        for i in log_score[lag+1:]:
            roop_score.append(roop_score[-1] + i)  
        roop = len(roop_score)
    if K <= n:
        ans = max(score)
    else:
        num_roop = (K - lag)//roop
        amari = (K - lag)%roop
        ans = max(num_roop*roop_score[-1] + max(roop_score[:amari]) + lag_score,max(score))
    return ans
print(max([score(i) for i in range(N)]))

Submission status: Runtime Error

Solution code:
N, K = list(map(int, input().split()))
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))
ans = -10**9-1
for i in range(N):
    cumsum = [0]*(N+1)
    seen = [-1]*N
    K_ = K
    now = i
    j = 0
    while K_ > 0 and seen[now] == -1:
        seen[now] = 1
        now = P[now]
        cumsum[j+1] = cumsum[j] + C[now]
        K_ -= 1
        j += 1
    if K_ == 0:
        ans = max(ans, max(cumsum[1:j+1]))
    else:
        if cumsum[j] > 0:
            loop_size = j
            loop_n = K//loop_size - 1
            tmp = loop_n*cumsum[loop_size]
            tmp += max(max(cumsum[1:loop_size]), cumsum[loop_size] + max(cumsum[1:K_%loop_size+1]))
            ans = max(ans, tmp)
        else:
            ans = max(ans, max(cumsum[1:j]))
print(ans)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N, K = [int(x) for x in input().split()]
    P = [int(x) for x in input().split()]
    C = [int(x) for x in input().split()]

    score = [[0] for j in range(N)]

    dic = {}

    for i in range(N):
        next = P[i] - 1
        visited = set()
        j = 0
        memo = {}
        while next not in visited:
            score[i].append(C[next] + score[i][-1])
            visited.add(next)
            memo[next] = j
            j += 1
            next = P[next] - 1
        dic[i] = (next - 1, len(score[i]) - memo[next] - 1)

    # print(score)
    # print(dic)
    ans = max(C)
    for i in range(N):
        if K <= len(score[i]) - 1:
            ans = max(ans, max(score[i][1:K + 1]))
        else:
            if score[i][-1] <= 0:
                ans = max(ans, max(score[i][1:K + 1]))
            else:
                q, r = divmod(K - (len(score[i]) - 1), dic[i][1])
                tmp = score[i][-1]
                tmp += q * (score[i][-1] - score[i][-1 - (dic[i][1])])
                if max(score[i][-1 - (dic[i][1] - 1):-1 - (dic[i][1] - 1) + r]) - score[i][-1 - dic[i][1]] > 0:
                    tmp += max(score[i][-1 - (dic[i][1] - 1):-1 - (dic[i][1] - 1) + r]) - score[i][-1 - dic[i][1]]
                ans = max(ans, tmp)

    print(ans)


if __name__ == '__main__':
    main()