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:
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 max_in_group(l,Cs,K):
    max_list = []
    for i in range(len(l)):
        sum = 0
        for j in range(len(l)):
            index = (i + j) % len(l)
            sum += Cs[l[index]-1]
            if i == 0:
                max_list.append(sum)
            else:
                if max_list[j] < sum:
                    max_list[j] = sum
    if len(l) > K:
        m = max(max_list[0:K])
    elif max_list[len(l)-1] <= 0:
        m = max(max_list)
    else:
        q = K // len(l)
        r = K % len(l)
        m = q * max_list[len(l)-1] + max(max_list[0:r])
    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)

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 max_in_group(l,Cs,K):
    sum_lists = []
    sum_list = []
    sum = 0
    for i in range(len(l)):
        for j in range(len(l)):
            index = (i + j) % len(l)
            sum += Cs[l[index]-1]
            sum_list.append(sum)
            if j == len(l)-1:
                sum_lists.append(sum_list)
                sum_list = []
                sum = 0
    max_list = []
    for i in range(len(l)):
        for j in range(len(l)):
            if i == 0:
                max_list.append(sum_lists[i][j])
            else:
                if max_list[j] < sum_lists[i][j]:
                    max_list[j] = sum_lists[i][j]
    if len(l) > K:
        m = max(max_list[0:K])
    elif max_list[len(l)-1] <= 0:
        m = max(max_list)
    else:
        q = K // len(l)
        r = K % len(l)
        m = q * max_list[len(l)-1] + max(max_list[0:r])
    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)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
plst, clst = [], []
plst = list(map(int, input().split()))
clst = list(map(int, input().split()))

ans = float('-inf')
visited = [0 for _ in range(n)]
for _ in range(n):
    new = plst[_] - 1
    lst = []
    i = 0
    temp = 0
    while visited[new] == 0:
        temp += clst[new]
        visited[new] = 1
        new = plst[new] -1
        i += 1
        lst.append(new)
    if lst:
        mod = k % i
        if k > i:
            loop = k // i
            temp2 = temp * loop
            ans = max(ans, temp2)
        for l in lst:
            new = l
            temp = 0
            newi = 0
            while newi < min(k, i):
                temp += clst[new]
                if newi < mod:
                    ans = max(ans, temp2 + temp)
                ans = max(ans, temp)
                new = plst[new] -1
                newi += 1  

print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
plst, clst = [], []
plst = list(map(int, input().split()))
clst = list(map(int, input().split()))

ans = float('-inf')
visited = [0 for _ in range(n)]
for _ in range(n):
    new = plst[_] - 1
    lst = []
    i = 0
    temp = 0
    while visited[new] == 0:
        temp += clst[new]
        visited[new] = 1
        new = plst[new] -1
        i += 1
        lst.append(new)
    if lst:
        print('lst:', lst)
        mod = k % i
        if k > i:
            loop = k // i
            temp2 = temp * loop
            ans = max(ans, temp2)
        for l in lst:
            new = l
            temp = 0
            newi = 0
            while newi < min(k, i):
                temp += clst[new]
                if newi < mod:
                    ans = max(ans, temp2 + temp)
                ans = max(ans, temp)
                new = plst[new] -1
                newi += 1  
print(ans)

Submission status: Runtime Error

Solution code:
ans = float('-inf')
visited = [0 for _ in range(n)]
for _ in range(n):
    new = plst[_] - 1
    lst = []
    i = 0
    temp = 0
    while visited[new] == 0:
        temp += clst[new]
        visited[new] = 1
        new = plst[new] -1
        i += 1
        lst.append(new)
    if lst:
        mod = k % i
        ans = max(ans, temp)
        loop = k // i
        temp2 = temp * loop
        for l in lst:
            new = l
            temp = 0
            newi = 0
            while newi < min(k, i):
                temp += clst[new]
                if newi < mod:
                    ans = max(ans, temp2 + temp)
                ans = max(ans, temp)
                new = plst[new] -1
                newi += 1  
print(ans)

Submission status: Runtime Error

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

result_max = -10**14

for i in range(N):
    tmp = P[i]
    cumulative_cost = [C[tmp]]
    while True:
        tmp = P[tmp]
        tmp_cum_cost = cumulative_cost[len(cumulative_cost)-1] + C[tmp]
        cumulative_cost.append(tmp_cum_cost)
        if tmp == i:
            break

    if len(cumulative_cost) < K:
        one_loop_sum = cumulative_cost[len(cumulative_cost)-1]
        tmp_sum = 0
        if one_loop_sum > 0:
            tmp_sum += (K // len(cumulative_cost)) * one_loop_sum
            rem_K = K % len(cumulative_cost)
            if rem_K != 0:
                tmp_sum += max(cumulative_cost[0:rem_K])
        else:
            tmp_sum = max(cumulative_cost)

        result_max = max(result_max, tmp_sum)
    else:
        result_max = max(result_max, max(cumulative_cost[0:K]))

print(result_max)

Submission status: Runtime Error

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

result_max = -10**14

for i in range(N):
    tmp = P[i]
    cumulative_cost = [C[tmp]]
    while True:
        tmp = P[tmp]
        tmp_cum_cost = cumulative_cost[len(cumulative_cost)-1] + C[tmp]
        cumulative_cost.append(tmp_cum_cost)
        if tmp == i:
            break

    if len(cumulative_cost) < K:
        one_loop_sum = cumulative_cost[len(cumulative_cost)-1]
        tmp_sum = 0
        if one_loop_sum > 0:
            tmp_sum += (K // len(cumulative_cost)) * one_loop_sum
            rem_K = K
            rem_K %= len(cumulative_cost)
            tmp_sum += max(cumulative_cost[0:rem_K])
        else:
            tmp_sum = max(cumulative_cost)

        result_max = max(result_max, tmp_sum)
    else:
        result_max = max(result_max, max(cumulative_cost[0:K]))

print(result_max)

Submission status: Runtime Error

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

result_max = -10**14

for i in range(N):
    tmp = P[i]
    cumulative_cost = [C[tmp]]
    while True:
        tmp = P[tmp]
        tmp_cum_cost = cumulative_cost[len(cumulative_cost)-1] + C[tmp]
        cumulative_cost.append(tmp_cum_cost)
        if tmp == i:
            break

    if len(cumulative_cost) < K:
        one_loop_sum = cumulative_cost[len(cumulative_cost)-1]
        tmp_sum = 0
        rem_K = K
        if one_loop_sum > 0:
            tmp_sum += (K // len(cumulative_cost)) * one_loop_sum
            rem_K %= len(cumulative_cost)
        tmp_sum += max(cumulative_cost[0:rem_K])
        result_max = max(result_max, tmp_sum)
    else:
        result_max = max(result_max, max(cumulative_cost[0:K]))

print(result_max)

Submission status: Runtime Error

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

cumulatives = []
result_max = -10**14

for i in range(N):
    tmp = P[i]
    cumulative_cost = [C[tmp]]
    while True:
        tmp = P[tmp]
        tmp_cum_cost = cumulative_cost[len(cumulative_cost)-1] + C[tmp]
        cumulative_cost.append(tmp_cum_cost)
        if tmp == i:
            break

    cumulatives.append(cumulative_cost)
    if len(cumulative_cost) < K:
        one_loop_sum = cumulative_cost[len(cumulative_cost)-1]
        tmp_sum = 0
        rem_K = K
        if one_loop_sum > 0:
            tmp_sum += (K // len(cumulative_cost)) * one_loop_sum
            rem_K %= len(cumulative_cost)
        tmp_sum += max(cumulative_cost[0:rem_K])
        result_max = max(result_max, tmp_sum)
    else:
        result_max = max(result_max, max(cumulative_cost[0:K]))

print(result_max)

Submission status: Runtime Error

Solution code:
import sys
import math
import copy
import random
import itertools
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = 10 ** 21
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def solve(n=None, s1=None, s2=None):
    n, k = getList()
    pli = getList()
    cli = getList()

    ans = max(cli)
    for i in range(n):
        cycle = [i]
        pts = [cli[i]]
        pos = i
        while True:
            pos = pli[pos] - 1
            if pos != i:
                cycle.append(pos)
                pts.append(cli[pos])
            else:
                break
        lc = len(cycle)
        for j in range(lc - 1):
            pts[j+1] += pts[j]

        if k <= lc:
            tmp = max(pts[:k])
        else:
            each = k % lc
            rotate = k // lc
            if pts[-1] > 0:
                tmp = pts[-1] * rotate
                if pts:
                    tmp += max(pts[:each])
            else:
                tmp = max(pts)
        # print(tmp, sum(pts), pts)
        ans = max(ans, tmp)

    print(ans)

def main():
    n = getN()
    for _ in range(n):
        solve()
    return


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

Submission status: Runtime Error

Solution code:
import sys
import math
import copy
import random
import itertools
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = 10 ** 21
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def solve(n=None, s1=None, s2=None):
    n, k = getList()
    pli = getList()
    cli = getList()

    ans = max(cli)
    for i in range(n):
        cycle = [i]
        pts = [cli[i]]
        pos = i
        while True:
            pos = pli[pos] - 1
            if pos != i:
                cycle.append(pos)
                pts.append(cli[pos])
            else:
                break
        lc = len(cycle)
        for j in range(lc - 1):
            pts[j+1] += pts[j]

        if k <= lc:
            tmp = max(pts[:k])
        else:
            each = k % lc
            rotate = k // lc
            if pts[-1] > 0:
                tmp = pts[-1] * rotate + max(pts[:each])
            else:
                tmp = max(pts)
        # print(tmp, sum(pts), pts)
        ans = max(ans, tmp)

    print(ans)


def main():
    n = getN()
    for _ in range(n):
        solve()
    return


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

Submission status: Runtime Error

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


groups = []
is_appear = [False]*n
group_size = [0]*n
for i in range(n):
    if is_appear[i]:
        continue
    group = []
    group.append(i)
    is_appear[i] = True
    j = p[i]
    while j != i:
        group.append(j)
        is_appear[j] = True
        j = p[j]
        
    groups.append(group)
    
    for i in group:
        group_size[i] = len(group)


cycle_score = [0]*n
for g in groups:
    score = 0
    for i in range(len(g)):
        score += c[g[i]]
    
    for i in g:
        cycle_score[i] = score

best = 0        
for i in range(n):
    score = 0
    best_i = 0
    cyc_num = k//group_size[i]
    if cycle_score[i]>0 and cyc_num>=1:
        remain = k-group_size[i]*(cyc_num-1)
        score += cycle_score*(cyc_num-1)
        
    elif cycle_score[i]<=0:
        remain = group_size[i]
    elif cyc_num<1:
        remain = k
    
    j = i
    for _ in range(remain):
        j = p[j]
        score += c[j]
        best_i = max(best_i,score)
    best = max(best,best_i)
    
print(best)

Submission status: Runtime Error

Solution code:
# ABC175 D
import bisect

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

F=[0]*N

def op(n):
    C_n=[]
    P_n=[]
    m=n
    while 1:
        C_n.append(C[m-1])
        P_n.append(m)
        F[m-1]=1
        m=P[m-1]
        if m==n:
            break
    sum_C_n=sum(C_n)
    C_n=C_n[:]+C_n[:]
    n=len(P_n)
    res=[]
    for k in range(1,min(n+1,K)):
        res_k=[]
        sum_k=sum(C_n[:k])
        p=sum_k
        for i in range(n):
            sum_k+=C_n[i+k]-C_n[i]
            p=max(p,sum_k)
        if K-k>=n and sum_C_n>=0:
                p+=sum_C_n*(K-k)//n
        res.append(p)
    return max(res)
    
res=-float('inf')
while 0 in F:
    n=bisect.bisect_right(F,0)
    res=max(op(n),res)
print(res)

Submission status: Runtime Error

Solution code:
# ABC175 D
import bisect

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

F=[0]*N

def op(n):
    C_n=[]
    P_n=[]
    m=n
    while 1:
        C_n.append(C[m-1])
        P_n.append(m)
        F[m-1]=1
        m=P[m-1]
        if m==n:
            break
    sum_C_n=sum(C_n)
    C_n=C_n[:]+C_n[:]
    n=len(P_n)
    res=[]
    for k in range(1,min(n+1,K)):
        res_k=[]
        for i in range(n):
            res_k.append(sum(C_n[i:i+k]))
        p=max(res_k)
        if K-k>=n and sum_C_n>=0:
                p+=sum_C_n*(K-k)//n
        res.append(p)
    return max(res)
    
res=-float('inf')
while 0 in F:
    n=bisect.bisect_right(F,0)
    res=max(op(n),res)
print(res)

Submission status: Runtime Error

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


@njit
def main():
    n, k = map(int, input().split())
    p = [int(x)-1 for x in input().split()]
    c = list(map(int, input().split()))
    
    doubling = [[0]*n for i in range(31)]
    doubling_max = [[0]*n for i in range(31)]
    place = [[0]*n for i in range(31)]
    
    ans = -1000000000
    for i in range(n):
        sub = c[p[i]]
        if sub >= 0:
            break
        if ans < sub:
            ans = sub
        if i == n-1:
            print(ans)
            sys.exit()
            
    
    for i in range(31):
        if i == 0:
            for j in range(n):
                doubling[i][j] = c[p[j]]
                place[i][j] = p[j]
            continue
        for j in range(n):
            place[i][j] = place[i-1][place[i-1][j]]
            doubling[i][j] = doubling[i-1][j]+doubling[i-1][place[i-1][j]]
    
    for i in range(31):
        if i == 0:
            for j in range(n):
                doubling_max[i][j] = doubling[i][j]
            continue
        for j in range(n):
            doubling_max[i][j] = max(doubling_max[i-1][j], doubling[i-1][j]+doubling_max[i-1][place[i-1][j]])
    
    ans = 0
    judge = []
    key = 0
    while k:
        if k%2:
            judge.append(key)
        k //= 2
        key += 1
    judge.reverse()
    
    for i in range(n):
        pl = i
        key = 0
        for j in range(len(judge)):
            if ans < key+doubling_max[judge[j]][pl]:
                ans = key+doubling_max[judge[j]][pl]
            key += doubling[judge[j]][pl]
            pl = place[judge[j]][pl]
        

    print(ans)
        
    


    
    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from sys import stdin, setrecursionlimit
#input = stdin.buffer.readline
setrecursionlimit(10 ** 7)

from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter
from itertools import combinations, permutations, combinations_with_replacement
from itertools import accumulate
from math import ceil, sqrt, pi, radians, sin, cos

MOD = 10 ** 9 + 7
INF = 10 ** 18

N, K = map(int, input().split())
P = list(map(lambda x: int(x) - 1, input().split())) # インデックスと場所を対応させる
A = list(map(int, input().split()))

if K <= 5000:
    for i in range(N):
        now = i
        point = 0
        max_point = -INF
        for _ in range(K):
            now = P[now]
            point += A[now]
            max_point = max(max_point, point)
        print(max_point)
else:
    for i in range(N):
        now = i
        point = 0
        max_point = -INF
        
        pre_loop = 
        loop_start = 
        loop_point =

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):
  exist_i = [(False, -1)] * k_max # (exist, j)
  exist_i[i] = (True, 0)
  score_i = [0] * K # iからスタートしてK回操作する場合の累積和
  score_i[0] = C[P[i]-1]
  index = P[i]-1
  for j in range(1, K):
    if exist_i[index][0] == True:
      # 既に進んだことがあるマスの場合
      
      # ループ終了インデックスからループ開始インデックスの累積和の差を確認
      loop_score = 0
      if exist_i[index][1] >= 1:
        loop_score = score_i[j-1] - score_i[exist_i[index][1] - 1] # 1ループで増えるスコア
      else:
        loop_score = score_i[j-1]
#      print("i, j, score_i", i, j, score_i)
#      print("i, j, loop_score", i, j, loop_score)
      if loop_score > 0:
        loop_num = j - exist_i[index][1] # ループする要素数
        num = K-j # 残りの操作数
        tmp_score = score_i[j-1] + num // loop_num * loop_score # ループ前までの累積和
#        print("i, j, tmp_score", i, j, tmp_score)
        tmp_array = [0] * (num % loop_num + 1)
        tmp_array[0] = tmp_score
        for l in range(1, num % loop_num + 1):
          tmp_array[l] = tmp_array[l-1] + C[P[index]-1]
          index = P[index]-1
#        print("i, j, tmp_array", i, j, tmp_array)
        score[i] = max(tmp_array)
      else:
#        print("i, j, score_i", i, j, score_i)
        score[i] = max(score_i)
#      print("i, j, score_i", i, j, score_i)
      break
    else:
      if j == K-1:
        score_i[j] = score_i[j-1] + C[P[index]-1]
        score[i] = max(score_i)
#        print("i, j, score_i", i, j, score_i)
        break   
    score_i[j] = score_i[j-1] + C[P[index]-1]
#    print("i, j, score_i", i, j, score_i)
#    print("i, j, score", i, j, score)
    exist_i[index] = (True, j)
    index = P[index]-1
print(max(score))

Submission status: Runtime Error

Solution code:

N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
    scores = []
    idx = i  # starting index
    while True:
        idx = Ps[idx]  # point to the next index
        scores.append(Cs[idx])  # fetch a score to add
        if idx == i:  # when the cycle is closed
            break

    len_cycle = len(scores)
    sum_cycle = sum(scores)

    if sum_cycle <= 0:  # when each cycle reduces the total score
        score = 0
        for j in range(min(K, len_cycle)):
            score += scores[j]
            max_score = max(max_score, score)
    else:
        if K // len_cycle > 0:
            num_multiply = K // len_cycle - 1
            score = sum_cycle * num_multiply
            for j in range(K % len_cycle + len_cycle):
                score += scores[j]
                max_score = max(max_score, score)
        else:
            num_multiply = 0  # len_cycle > K
            score = sum_cycle * num_multiply
            for j in range(K):
                score += scores[j]
                max_score = max(max_score, score)

print(max_score)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
    scores = []
    idx = i  # starting index
    while True:
        idx = Ps[idx]  # point to the next index
        scores.append(Cs[idx])  # fetch a score to add
        if idx == i:  # when the cycle is closed
            break
    len_cycle = len(scores)
    sum_cycle = sum(scores)

    if sum_cycle <= 0:  # when each cycle reduces the total score
        score = 0
        for j in range(min(K, len_cycle)):
            score += scores[j]
            max_score = max(max_score, score)
    else:
        if K // len_cycle > 0:
            num_multiply = K // len_cycle - 1
            for j in range(K % len_cycle + len_cycle):
                score += scores[j]
                max_score = max(max_score, score)
        else:
            num_multiply = 0  # len_cycle > K
            score = sum_cycle * num_multiply
            for j in range(K):
                score += scores[j]
                max_score = max(max_score, score)
            
print(max_score)

Submission status: Runtime Error

Solution code:
def main():
    import numpy as np
    import sys
    input=sys.stdin.readline
    n,k=map(int,input().split())
    p=list(map(int,input().split()))
    c=list(map(int,input().split()))
    
    visited=np.array([0]*n)
    ans=-10**12
    for i in range(n):
        mvnum=0
        score=0
        scorebymove=[0]
        now=p[i]-1
        while (not visited[now]) and mvnum<=k:
            mvnum+=1
            visited[now]=1
            score+=c[now]
            scorebymove.append(score)
            ans=max(ans,score)
            now=p[now]-1
        print(not visited[now])
        mvrem=k-mvnum
        if score>=0 and mvnum<=k:
            score+=score*(mvrem//mvnum)
            ans=max(ans,score)
        else:mvrem=0
        mvrem-=mvnum*(mvrem//mvnum)
        if mvrem>0:
            score+=scorebymove[mvrem]
        ans=max(ans,score)
        visited*=0
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
positions = [int(i) for i in input().split()]
scores = [int(i) for i in input().split()]
if max(scores) <= 0:
  print(max(scores))
else:
  positions = [0] + positions
  scores = [0] + scores
  max_point = -pow(10, 9)
  #print(max_point)
  dic = {}
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    if f_pos not in dic:
      point_loop = 0
      loop = 0
      pos_set = set([f_pos])
      while True:
        f_pos = positions[f_pos]
        point_loop += scores[f_pos]
        #print('pos', f_pos)
        #print(point)
        loop += 1
        if f_pos in pos_set:
          for j in pos_set:
            dic[j] = [loop, point_loop]
          break
        pos_set.add(f_pos)
    else:
      loop, point_loop = dic[f_pos]
    #print(loop, point)
    loop_c = k // loop
    r = k % loop
    if loop_c ==　0 or point_loop <= 0:
      if point_loop <= 0:
        if loop_c > 0:
          r = loop
      point = 0
      for _ in range(r):
        f_pos = positions[f_pos]
        point += scores[f_pos]
        max_point = max(max_point, point)
    else:
      point1, point2 = 0, 0
      point1 = loop_c * point_loop
      max_point1 = point1
      for _ in range(r):
        f_pos = positions[f_pos]
        point1 += scores[f_pos]
        max_point1 = max(point1, max_point1)
      point2 = (loop_c - 1) * point_loop
      max_point2 = point2
      for _ in range(loop):
        f_pos = positions[f_pos]
        point2 += scores[f_pos]
        max_point2 = max(point2, max_point2)
      max_point = max(max_point, max(max_point1, max_point2))
  print(max_point)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
positions = [int(i) for i in input().split()]
scores = [int(i) for i in input().split()]
if max(scores) <= 0:
  print(max(scores))
else:
  positions = [0] + positions
  scores = [0] + scores
  max_point = -pow(10, 9)
  #print(max_point)
  dic = {}
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    if f_pos not in dic:
      point_loop = 0
      loop = 0
      pos_set = set([f_pos])
      while True:
        f_pos = positions[f_pos]
        point_loop += scores[f_pos]
        #print('pos', f_pos)
        #print(point)
        loop += 1
        if f_pos in pos_set:
          for j in pos_set:
            dic[j] = [loop, point_loop]
          break
        pos_set.add(f_pos)
    else:
      loop, point_loop = dic[f_pos]
    #print(loop, point)
    loop_c = k // loop
    r = k % loop
    if loop_c ==　0 or point_loop <= 0:
      if point_loop <= 0:
        if point_c > 0:
          r = loop
      point = 0
      for _ in range(r):
        f_pos = positions[f_pos]
        point += scores[f_pos]
        max_point = max(max_point, point)
    else:
      point1, point2 = 0, 0
      point1 = loop_c * point_loop
      max_point1 = point1
      for _ in range(r):
        f_pos = positions[f_pos]
        point1 += scores[f_pos]
        max_point1 = max(point1, max_point1)
      point2 = (loop_c - 1) * point_loop
      max_point2 = point2
      for _ in range(loop_c):
        f_pos = positions[f_pos]
        point2 += scores[f_pos]
        max_point2 = max(point2, max_point2)
      max_point = max(max_point, max(max_point1, max_point2))
  print(max_point)

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 = []
R = -1000000001
#それぞれについての累積和の計算
for i in range(N):#このループはN個の初期マスの時のループ
    t = i  # tは現在の位置
    cnt = 0  # 累積和
    sum = []  # 累積和のリスト
    res = 0
    while True:#このループは一つの初期マスの累積和。最初のコマに戻るまで
        t = P[t]-1
        cnt += C[t]
        sum.append(cnt)
        if t == i:
            break
    #S.append(sum)
    if len(sum) >=  K:
        res = max(sum[:K])
    else:
        if sum[-1] <= 0:
            res = max(sum)
        else:
            score1 = sum[-1] * (K // len(sum) - 1) + max(sum)
            score2 = sum[-1] * (K // len(sum)) + max(sum[0:K % len(sum)])
            res = max(score1,score2)
    R = max(R,res)
print(R)

Submission status: Runtime Error

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

visit = [0]*n
r = [max(c)]

for position in range(n):
    if visit[position] > 0:
        continue

    nex = position

    score = [0]

    while visit[nex]<1:
        visit[nex] = 1
        score.append(score[-1]+c[nex])
        nex= p[nex]-1

    last = score[-1]
    count = len(score)-1

    for i in score[1:]:
        score.append(last+i)

    if (count >= k) or (last <= 0):
        result = []
        _count = min(count, k)
        for i in range(1, count+1):
            result.append(max(score[i:i+_count])-score[i-1])
        r.append(max(result))
    else:
        rou = k//count
        _count = k%count
        result = [0]
        for i in range(1, count+1):
            result.append(max(score[i:i+_count])-score[i-1])
        r.append(rou*last + max(result))

print(max(r))