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 sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

from itertools import accumulate

n,k = readints()
p = [x-1 for x in readints()]
c = readints()

circles = []
used = [0]*n

for i in range(n):
    if not used[i]:
        circles.append([c[i]])
        used[i] = 1
        j = p[i]
        while not used[j]:
            circles[-1].append(c[j])
            used[j] = 1
            j = p[j]


score = -10**20

for cir in circles:
    m = len(cir)
    a = sum(cir)

    if a>0:
        s = (k//m) * sum(cir)
    else:
        s = 0

    if k>m:
        if a>0:
            num = k%m
        else:
            num = m
    else:
        num = k

    if num==1:
        ss = max(cir)
    else:
        ac = list(accumulate([0]+cir))
        l = 0
        r = 1
        ss = ac[r]-ac[l]
        i = 0
        while 1:
            if r == m:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
                ss = max(ss,ac[r]-ac[l])
                break
            elif i%2==0:
                r = ac[r+1:l+num+1].index(max(ac[r+1:l+num+1])) + r+1
            else:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
            i+=1
            ss = max(ss,ac[r]-ac[l])

        num = m-num
        l = 0
        r = num
        i = 0
        ss = max(ss,a-ac[r]+ac[l])
        while 1:
            if r == m:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
                ss = max(ss,a-ac[r]+ac[l])
                break
            elif i%2==0:
                r = ac[r+1:l+m].index(min(ac[r+1:l+m])) + r+1
            else:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
            i+=1
            ss = max(ss,a-ac[r]+ac[l])

    score = max(score, s+ss)

print(score)

Submission status: Runtime Error

Solution code:


Submission status: Runtime Error

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

ind = 0
path = [[]]
cost = [[]]
path_i = 0
while True:
    path[path_i].append(ind)
    cost[path_i].append(C[ind])
    pre_ind = ind
    if P[P[pre_ind]-1] == INF:
        for i in range(len(P)):
            if P[i] != INF and i != ind:
                ind = i
                path_i += 1
                path.append(list())
                cost.append(list())
                break
    else:
        ind = P[ind]-1

    P[pre_ind] = INF

    if len(set(P)) == 1:
        break

max_c = -INF
for i in range(len(path)):
    for j in range(len(path[i])):
        if K > len(path[i]):
            if sum(cost[i]) > 0:
                tmp_c = sum(cost[i]) * (K // len(path[i]))
                tmp_sub = tmp_c
                for k in range(K % len(path[i])):
                    if len(path[i]) <= j + k:
                        cicle_k = (j + k) - (len(path[i]) - 1)
                        tmp_cc = sum(cost[i][j:len(path[i])])
                        tmp_cc += sum(cost[i][:abs(cicle_k)])
                    else:
                        tmp_cc = sum(cost[i][j:j+k])
                    if tmp_c < tmp_sub + tmp_cc:
                        tmp_c = tmp_sub + tmp_cc
            else:
                tmp_c = -INF
                for k in range(len(path[i])):
                    cicle_k = (j + k) % len(path[i])
                    tmp_cc = sum(cost[i][j:cicle_k])
                    if cicle_k <= k:
                        tmp_cc += sum(cost[i][:(k-cicle_k)])
                    if tmp_c < tmp_cc:
                        tmp_c = tmp_cc
        else:
            if sum(cost[i]) > 0:
                for k in range(K % len(path[i])):
                    cicle_k = (j + k) % len(path[i])
                    tmp_c = sum(cost[i][j:cicle_k])
                    if cicle_k <= k:
                        tmp_c += sum(cost[i][:(k-cicle_k)])
            else:
                tmp_c = -INF
                for k in range(len(path[i])):
                    cicle_k = (j + k) % len(path[i])
                    tmp_cc = sum(cost[i][j:cicle_k])
                    if cicle_k <= k:
                        tmp_cc += sum(cost[i][:(k-cicle_k)])
                    if tmp_c < tmp_cc:
                        tmp_c = tmp_cc

        if max_c < tmp_c:
            max_c = tmp_c


print(max_c)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

from itertools import accumulate

n,k = readints()
p = [x-1 for x in readints()]
c = readints()

circles = []
used = [0]*n

for i in range(n):
    if not used[i]:
        circles.append([c[i]])
        used[i] = 1
        j = p[i]
        while not used[j]:
            circles[-1].append(c[j])
            used[j] = 1
            j = p[j]


score = -10**20

for cir in circles:
    m = len(cir)
    a = sum(cir)

    if a>0:
        s = (k//m) * sum(cir)
    else:
        s = 0

    if k>m:
        if a>0:
            num = k%m
        else:
            num = m
    else:
        num = k

    if num==1:
        ss = max(cir)
    else:
        ac = list(accumulate([0]+cir))
        l = 0
        r = 1
        ss = ac[r]-ac[l]
        while 1:
            if r == m:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
                ss = max(ss,ac[r]-ac[l])
                break
            elif r-l==num:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
            else:
                r = ac[r+1:l+num+1].index(max(ac[r+1:l+num+1])) + r+1
            ss = max(ss,ac[r]-ac[l])

        num = m-num
        l = 0
        r = num
        while 1:
            if r == m:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
                ss = max(ss,a-ac[r]+ac[l])
                break
            elif r-l==num:
                r = ac[r+1:l+m].index(min(ac[r+1:l+m])) + r+1
            else:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
            ss = max(ss,a-ac[r]+ac[l])

    score = max(score, s+ss)

print(score)

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 = [p-1 for p in P]
    
    check = [False] * N
    ans = -float("inf")
    for i in range(N):
        if check[i]:
            continue
        start = i
        position = i
        score_list = []
        j = 0
        while True:
            check[position] = True
            if j == 0:
                score_list.append(C[P[position]])
                position = P[position]
            else:
                score_list.append(C[P[position]] + score_list[-1])
                position = P[position]
                if position == start:
                    # print(position, start)
                    break
            j += 1
            # print(check)
        # print("score_list", score_list)
        for j in range(len(score_list)):
            if j != 0:
                tmp = score_list.pop(0)
                score_list = [x-tmp for x in score_list]
                score_list.append(tmp + score_list[-1])
            # print(score_list)
            # 最大得点を求める
            base_score = 0
            # 何周もするとき、正なら多く周回したほうが値は大きくなる
            tmp_K = K
            if K > len(score_list) and score_list[-1] >= 0:
                base_score = score_list[-1] * (K // len(score_list))
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            elif K > len(score_list) and score_list[-1] < 0:
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            print(score_list)
            if tmp_K == 0:
                tmp_max_score = base_score - sum(score_list) + max(score_list)
            elif base_score == 0 and max(score_list[:tmp_K]) < 0:
                tmp_max_score = max(score_list[:tmp_K])
            else:
                tmp_max_score = base_score + max(0, max(score_list[:tmp_K]))
                tmp_max_score = max(tmp_max_score,
                                    base_score - sum(score_list) + max(score_list))
            if tmp_max_score > ans:
                print("tmp_max", tmp_max_score, tmp_K, score_list)
                ans = tmp_max_score
    print(ans)
            
    
main()

Submission status: Runtime Error

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

ind = 0
path = [[]]
cost = [[]]
path_i = 0
while True:
    path[path_i].append(ind)
    cost[path_i].append(C[ind])
    pre_ind = ind
    if P[P[pre_ind]-1] == INF:
        for i in range(len(P)):
            if P[i] != INF and i != ind:
                ind = i
                path_i += 1
                path.append(list())
                cost.append(list())
                break
    else:
        ind = P[ind]-1

    P[pre_ind] = INF

    if len(set(P)) == 1:
        break

max_c = -INF
for i in range(len(path)):
    for j in range(len(path[i])):
        print('j:', j)
        if K > len(path[i]):
            if sum(cost[i]) > 0:
                tmp_c = sum(cost[i]) * (K // len(path[i]))
                print('cycle cost:', tmp_c)
                tmp_sub = tmp_c
                for k in range(K % len(path[i])):
                    print('j:k:', j, j+k)
                    if len(path[i]) <= j + k:
                        cicle_k = (j + k) - (len(path[i]) - 1)
                        print('cycle k:', cicle_k)
                        tmp_cc = sum(cost[i][j:len(path[i])])
                        tmp_cc += sum(cost[i][:abs(cicle_k)])
                    else:
                        tmp_cc = sum(cost[i][j:j+k])
                    if tmp_c < tmp_sub + tmp_cc:
                        tmp_c = tmp_sub + tmp_cc
                    print('after cost:', tmp_c)
            else:
                tmp_c = -INF
                for k in range(len(path[i])):
                    cicle_k = (j + k) % len(path[i])
                    tmp_cc = sum(cost[i][j:cicle_k])
                    if cicle_k <= k:
                        tmp_cc += sum(cost[i][:(k-cicle_k)])
                    if tmp_c < tmp_cc:
                        tmp_c = tmp_cc
        else:
            if sum(cost[i]) > 0:
                for k in range(K % len(path[i])):
                    cicle_k = (j + k) % len(path[i])
                    tmp_c = sum(cost[i][j:cicle_k])
                    if cicle_k <= k:
                        tmp_c += sum(cost[i][:(k-cicle_k)])
            else:
                tmp_c = -INF
                for k in range(len(path[i])):
                    cicle_k = (j + k) % len(path[i])
                    tmp_cc = sum(cost[i][j:cicle_k])
                    if cicle_k <= k:
                        tmp_cc += sum(cost[i][:(k-cicle_k)])
                    if tmp_c < tmp_cc:
                        tmp_c = tmp_cc

        if max_c < tmp_c:
            max_c = tmp_c


print(path)
print(max_c)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(2000)

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

def search(s,k, lis_p, lis_c, lis):
    if len(lis) >= k:
        return lis
    s = lis_p[s - 1]
    lis.append(lis_c[s - 1])
    return search(s, k, lis_p, lis_c, lis)

ans = -10**10
for i in range(n):
    l = search(i+1, k, p, c, [])
    d = max([sum(l[:j+1]) for j in range(len(l))])
    if d> ans:
        ans = d
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(2000)

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

def search(s,k, lis_p, lis_c, lis):
    if len(lis) >= k:
        return lis
    s = lis_p[s - 1]
    lis.append(lis_c[s - 1])
    return search(s, k, lis_p, lis_c, lis)

ans = -10**15
for i in range(n):
    l = search(i+1, k, p, c, [])
    d = max([sum(l[:j+1]) for j in range(len(l))])
    if d> ans:
        ans = d

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 search(s,k, lis_p, lis_c, lis):
    if len(lis) >= k:
        return lis
    s = lis_p[s - 1]
    lis.append(lis_c[s - 1])
    return search(s, k, lis_p, lis_c, lis)

ans = -10**15
for i in range(n):
    l = search(i+1, k, p, c, [])
    d = max([sum(l[:j+1]) for j in range(len(l))])
    if d> ans:
        ans = d

print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

from itertools import accumulate

n,k = readints()
p = [x-1 for x in readints()]
c = readints()

circles = []
used = [0]*n

for i in range(n):
    if not used[i]:
        circles.append([c[i]])
        used[i] = 1
        j = p[i]
        while not used[j]:
            circles[-1].append(c[j])
            used[j] = 1
            j = p[j]


score = -10**20

for cir in circles:
    m = len(cir)
    a = sum(cir)

    if a>0:
        s = (k//m) * sum(cir)
    else:
        s = 0

    if k>m:
        if a>0:
            num = k%m
        else:
            num = m
    else:
        num = k

    if num==1:
        score = max(score,s+max(cir))
    else:
        for i in range(m):
            ac = list(accumulate([0]+cir[i:]+cir[:i]))
            l = 0
            r = 1
            ss = ac[r]-ac[l]
            while 1:
                if r == m:
                    l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
                    ss = max(ss,ac[r]-ac[l])
                    break
                elif r-l==num:
                    l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
                else:
                    r = ac[r+1:l+num+1].index(max(ac[r+1:l+num+1])) + r+1
                ss = max(ss,ac[r]-ac[l])
            score = max(score, s+ss)

print(score)

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 = [p-1 for p in P]
    
    check = [False] * N
    ans = -float("inf")
    for i in range(N):
        if check[i]:
            continue
        start = i
        position = i
        score_list = []
        j = 0
        while True:
            check[position] = True
            if j == 0:
                score_list.append(C[P[position]])
                position = P[position]
            else:
                score_list.append(C[P[position]] + score_list[-1])
                position = P[position]
                if position == start:
                    # print(position, start)
                    break
            j += 1
            # print(check)
        # print("score_list", score_list)
        for j in range(len(score_list)):
            if j != 0:
                tmp = score_list.pop(0)
                score_list = [x-tmp for x in score_list]
                score_list.append(tmp + score_list[-1])
            # print(score_list)
            # 最大得点を求める
            base_score = 0
            # 何周もするとき、正なら多く周回したほうが値は大きくなる
            tmp_K = K
            if K > len(score_list) and score_list[-1] >= 0:
                base_score = score_list[-1] * (K // len(score_list))
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            elif K > len(score_list) and score_list[-1] < 0:
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            # print(score_list)
            tmp_max_score = base_score + max(score_list[:tmp_K])
            if tmp_max_score > ans:
                # print("tmp_max", tmp_max_score, tmp_K, score_list)
                ans = tmp_max_score
    print(ans)
            
    
main()

Submission status: Runtime Error

Solution code:
import sys
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def main():
    N, K = NMI()
    P = NLI()
    P = [p-1 for p in P]
    C = NLI()

    seen = [0] * N
    loops = []
    for i in range(N):
        if seen[i] == 1:
            continue
        now = i
        now_loop = [now]
        now_cost = C[now]
        while True:
            seen[now] = 1
            goto = P[now]
            if seen[goto] == 1:
                break
            now_loop.append(goto)
            now_cost += C[goto]
            now = goto
        loops.append([now_loop, now_cost])

    ans = -float("inf")
    for loop, cost in loops:
        for i, start in enumerate(loop):
            for j, end in enumerate(loop):
                if i == j:
                    base = cost
                    moved = len(loop)
                elif i < j:
                    base = sum([C[p] for p in loop[i+1:j+1]])
                    moved = j - i
                else:
                    base = cost - sum([C[p] for p in loop[j+1:i+1]])
                    moved = len(loop) + j - i

                if moved > K:
                    print(loop, i, j)
                    continue

                if cost > 0:
                    tmp_K = K - moved
                    num_loop = tmp_K // len(loop)
                    tmp_ans = num_loop * cost + base
                else:
                    tmp_ans = base

                ans = max(ans, tmp_ans)

    print(ans)



if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
inhex = lambda x: int(x)-1

n,k=map(int, input().split())
p=list(map(inhex, input().split()))
c=list(map(int, input().split()))
ans = c[0]
for i in range(n):
    init = p[i]
    score = [c[init]]
    next = p[init]
    while next != init:
        score.append(score[-1] + c[next])
        next = p[next]
    sum = score[-1]
    lenth = len(score)
    score_max = int()
    if k <= lenth:
        score_max = max(score[:k])
    else:
        if sum <= 0:
            score_max = max(score)
        else:
            entire_use = (k//lenth)-1
            reminder = k % lenth
            before_max = max(score) + entire_use*sum
            after_max = max(score[:reminder]) + (entire_use+1)*sum
            score_max = max(before_max,after_max)
    ans = max(ans, score_max)
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()))

G = [[] for _ in range(2500)]
G_shaku = [[] for _ in range(2500)]
g = 0
check = [0]*N
ans = -10**9

def jump(x, temp):
    global g
    if check[P[x]-1] == 0:
        G[g].append(C[x])
        check[P[x]-1] = 1
        temp = 1
        
        jump(P[x]-1, temp)
    else:
        if temp:
            g += 1
        return
    
    
def shakumax(lis, k, l, idx):
    ans = 0

    for i in range(k):
        ans += lis[i]
    
    temp = ans
    
    for i in range(2*l-k):
        temp = temp - lis[i] + lis[i+k]
        ans = max(ans, temp)
           
    G_shaku[idx].append(ans)
    return ans  


for i in range(N):
    temp = 0
    jump(i, temp)

for idx, i in enumerate(G):
    l = len(i)
    if l > 0:
        ans1 = -10**9
        for j in range(1,min(K,l)+1):
            ans1 = max(shakumax(i*2, j, l, idx), ans1)
        
        if sum(i) <= 0:
            ans = max(ans1, ans)
        else:
            temp = 0
            try:
                temp = max(G_shaku[idx][:K%l])
            except:
                pass
            ans = max(K//l *sum(i) + temp, ans, ans1)
print(ans)

Submission status: Runtime Error

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

def main()
    plist = [i - 1 for i in map(int, input().split())]
    slist = list(map(int, input().split()))
    max_score = -math.inf
    for start in range(N):
        total_score_in_loop = 0
        now = start
        score_loop = []
        while True:
            now = plist[now]
            total_score_in_loop += slist[now]
            score_loop.append(slist[now])
            if now == start:
                break
        score_rem = 0
        loop_score = 0
        for index, score in enumerate(score_loop, start=1):
            score_rem += score
            if total_score_in_loop > 0:
                loop_score = total_score_in_loop * ((K-index) // len(score_loop))
            max_score = max(max_score, score_rem+loop_score)
    print(max_score)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 20:44:53 2020

"""

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

G = [[] for _ in range(2500)]
G_shaku = [[] for _ in range(2500)]
g = 0
check = [0]*N
ans = -10**9

def jump(x, temp):
    global g
    if check[P[x]-1] == 0:
        G[g].append(C[x])
        check[P[x]-1] = 1
        temp = 1
        
        jump(P[x]-1, temp)
    else:
        if temp:
            g += 1
        return
    
    
def shakumax(lis, k, l, idx):
    ans = 0

    for i in range(k):
        ans += lis[i]
    
    temp = ans
    
    for i in range(2*l-k):
        temp = temp - lis[i] + lis[i+k]
        ans = max(ans, temp)
           
    G_shaku[idx].append(ans)
    return ans  


for i in range(N):
    temp = 0
    jump(i, temp)

for idx, i in enumerate(G):
    dekai = 0
    l = len(i)
    if l > 0:
        ans1 = -10**9
        for j in range(1,min(K,l)+1):
            ans1 = max(shakumax(i*2, j, l, idx), ans1)
        if sum(i) <= 0:
            ans = max(ans1, ans)
        else:
            ans = max(K//l *sum(i) + max(G_shaku[idx][:K%l]), ans)
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
pos = [int(i) for i in input().split()]
score = [int(i) for i in input().split()]
if max(score) <= 0:
  print(max(score))
else:
  pos = [0] + pos
  score = [0] + score
  max_point = -10 ** 11
  s_dic = {}
  dic = {}
  loop = 0
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    if f_pos not in dic:
      points = [0]
      index = 0
      loop += 1
      while True:
        n_pos = pos[f_pos]
        points.append(points[-1] + score[n_pos])
        index += 1
        dic[f_pos] = [index, loop]
        if n_pos in dic:
          break
        f_pos = n_pos
      #print(nei)
      s_dic[loop] = points
      index = 1
    else:
      index, loop = dic[f_pos]
      points = s_dic[loop]
    #print(points)
    #print(count)
    loop_num = len(points) - 1
    s = points[index - 1]
    m = points[loop_num] - s
    a = k // loop_num
    b = k % loop_num
    if points[loop_num] > 0:
      point = points[loop_num] * a
      if point > max_point and a != 0:
        max_point = point
    else:
      point = 0
      if a > 0:
        b = loop_num
    #print(point)
    if b > 0:
      t_max = -10 ** 11
      if loop_num - index + 1 >= b:
        for j in range(b):
          t = points[j + index] - s
          #print(t)
          if t > t_max:
            t_max = t
      else:
        for j in range(index, loop_num + 1):
          t = points[j] - s
          #print(t)
          if t > t_max:
            t_max = t
        for j in range(1, b - loop_num + index):
          t = points[j] + m
          #print(t)
          if t > t_max:
            t_max = t
      point += t_max
    #print(point)
    if point > max_point:
      max_point = point
  print(max_point)

Submission status: Runtime Error

Solution code:
from itertools import accumulate


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**20
    for start in range(cells):
        route = []
        route_append = route.append
        now = start
        for _step in range(cells):
            nex = nexts[now]
            route_append(scores[nex])
            if nex == start:
                break
            now = nex

        length = len(route)
        total = sum(route)
        if total > 0:
            q, mod = divmod(moves, length)
            candidate = max(list(accumulate(route))[:mod]) + total * q
        else:
            candidate = max(list(accumulate(route))[:min(moves, length)])
        ans = max(ans, candidate)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import networkx as nx
import networkx.algorithms.cycles
from collections import deque

IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = list(map(int, input().split()))
C = [0]+list(map(int, input().split()))

g = nx.DiGraph()
g.add_nodes_from(range(1, N+1))

edges = []
for i in range(1, N+1): edges.append((i, P[i-1]))
g.add_edges_from(edges)

class cy:
    def __init__(self, steps, scores, to=None):
        self.steps = deque(steps)
        self.scores = deque(scores)
        if to==None:
            self.isCycle = True
        else:
            self.to = to
            self.isCycle = False    

CY = [None]*(N+1)
cpath = set()
for cycle in networkx.algorithms.cycles.simple_cycles(g):
    steps = deque(cycle)
    cpath.update(steps)
    scores = deque([C[i] for i in cycle])
    for i in cycle:
        rot = steps.index(i)
        steps.rotate(-rot)
        scores.rotate(-rot)
        CY[i] = cy(steps, scores)

P = [0] + P
for i in range(1, N+1):
    if CY[i] != None: continue # in closure
    steps, scores = [], []
    pos = i
    to = 0
    while True:
        steps.append(pos)
        scores.append(C[pos])
        pos = P[pos]
        if pos in cpath:
            CY[i] = cy(steps, scores, pos)
            break

maxsc = -10**9-1
for i in range(1, N+1):
    path = []
    pos = i
    if not CY[pos].isCycle: # out of closure
        path += list(CY[i].scores)
        pos = CY[i].to
    path += list(CY[i].scores) * ( int(K/len(CY[i].scores))+1 )
    path = path[0:K] # curtail
    score = [0]
    for j in range(len(path)): score.append(score[j]+path[j])
    maxsc = max([maxsc] + score[1:len(score)])

print (maxsc)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = list(map(lambda a: int(a) - 1, input().split()))
C = list(map(int, input().split()))
INF = 10**18

grp = []
visited = [False] * N

for i in range(N):
    if visited[i]:
        continue
    V = []
    while not visited[i]:
        V.append(i)
        visited[i] = True
        i = P[i]
    grp.append(V)

def solve(V, K):
    N = len(V)

    sumC = 0
    for v in V:
        sumC += C[v]

    ans = 0
    if sumC >= 0:
        q, K = divmod(K, N)
        ans = q * sumC
    else:
        K = min(K, N)
        1 / 0

    if K == 0:
        return ans

    def calc(now, K):
        ret = -INF
        acc = 0
        for _ in range(K):
            now = P[now]
            acc += C[now]
            ret = max(ret, acc)
        return ret

    mx = -INF
    for start in V:
        mx = max(mx, calc(start, K))

    return ans + mx

ans = max(C)
for V in grp:
    ans = max(ans, solve(V, K))
print(ans)