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:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

maxcost = -float('inf')
for pi in p:    # O(n^2)
    curr, costs = pi, [0]
    while pi != p[curr-1]:
        costs.append(costs[-1]+c[curr-1])
        curr = p[curr-1]
    costs.append(costs[-1]+c[curr-1])
    l = len(costs)-1
    if costs[-1] > 0 and k > l:
        maxcost = max(maxcost, costs[-1]*(k//l)+max(costs[1:k % l+1]) or 0)
    else:
        maxcost = max(maxcost, max(costs[1:min(k, l)+1]))

print(maxcost)

Submission status: Runtime Error

Solution code:
R, C, K = map(int, input().split())
item = [[0] * (C) for i in range(R+1)]
for i in range(K):
  r, c, v = map(int, input().split())
  r -= 1
  c -= 1
  item[r][c] = v

dp = [[[0] * 4 for i in range(C)] for j in range(R)]
for i in range(1, 4):
    dp[0][0][i] = item[0][0]
for i in range(R):
  for j in range(C):
    for k in range(3):
      if(j != C - 1):
        dp[i][j + 1][k + 1] = max(dp[i][j][k]+item[i][j + 1], dp[i][j][k + 1], dp[i][j + 1][k + 1])
      if(i != R - 1):
          dp[i + 1][j][k + 1] = max(dp[i + 1][j][3], dp[i][j][3] + item[i + 1][j])
        
print(dp[R - 1][C - 1][3])

Submission status: Runtime Error

Solution code:
N,K=input().split()
N=int(N)
K=int(K)
P=input().split()
C=input().split()
for i in range(N):
    P[i]=int(P[i])-1
for i in range(N):
    C[i]=int(C[i])
ans=-1000000001
for i in range(N):
    x=0
    n=i
    sum=0
    period=0
    while period<=N:
        sum+=C[n]
        n=P[n]
        period+=1
        if n==i:
            break
    m=int(K/period)
    K2=K
    if m>1 and sum>0:
        x=(m-1)*sum
        K2-=(m-1)*period
    elif K2>N and sum<=0:
        K2=N
    for j in range(K2):
        x+=C[n]
        n=P[n]
        ans=max(ans,x)
        if j>=2*N:
			break
print(ans)

Submission status: Runtime Error

Solution code:
ans = 0

for loop in loops:

    num = len(loop)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]
    ans_tmp = -1e9
    sumL = sum(L)
    by_loop = max(sumL, 0) * div
    if k > num and sumL <= 0:
        r = num
    L += L[:r]
    ACC = [0] + list(accumulate(L))

    for i in range(num):
        for j in range(i + 1, i + r + 1):
            ans_tmp = max(ans_tmp, ACC[j] - ACC[i] + by_loop)

    ans = max(ans, ans_tmp)
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np


def parse():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    pc = {i: (pi - 1, ci) for i, (pi, ci) in enumerate(zip(p, c))}
    return k, pc


def split_simple():
    k, pc = parse()
    lst = [[]]
    lst[0].append(pc.pop(0))
    while True:
        if not pc:
            break
        p, _ = lst[-1][-1]
        if p in pc:
            pcj = pc.pop(p)
            lst[-1].append(pcj)
        else:
            j = next(iter(pc.keys()))
            pcj = pc.pop(j)
            lst.append([pcj])
    return k, [np.array([ls[1] for ls in lst_], dtype=np.long) for lst_ in lst]


def inner(n, k, s, sim):
    if k < n or s <= 0:
        return sim.max()
    else:
        div = k // n
        mod = k % n
        return s * div + sim[:, :mod].max()


def main():
    k, data_set = split_simple()
    result = min([d.min() for d in data_set])
    for data in data_set:
        n = data.size
        rep = np.repeat(data[None], 2, axis=0).flatten()
        sim = np.array([[rep[i:i+p].sum()
                         for p in range(1, min(k, n) + 1)] for i in range(n)])
        cand = inner(n, k, data.sum(), sim)
        result = max(result, cand)
    print(result)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

maxcost = -float('inf')
for pi in p:    # O(n^2)
    curr, costs = pi, [0]
    while pi != p[curr-1]:
        costs.append(costs[-1]+c[curr-1])
        curr = p[curr-1]
    costs.append(costs[-1]+c[curr-1])
    l = len(costs)-1
    if costs[-1] > 0:
        maxcost = max(maxcost, costs[-1]*(k//l)+max(costs[1:k % l+1]))
    else:
        maxcost = max(maxcost, max(costs[1:min(k, l)+1]))

print(maxcost)

Submission status: Runtime Error

Solution code:
import numpy as np
N,K = list(map(int, input().split()))
input_list = list(map(int, input().split()))
input_list = list(np.array(input_list)-1)
c_list = list(map(int, input().split()))

#for i in range(N):
def roop_func(l, i, start, return_list=[]):
    return_list.append(l[i])
    if l[i] == start:
        return return_list 
    return roop_func(l, l[i],start, return_list)

total_best = -100000000000000000000
for start in range(N):
    p_list = roop_func(input_list, start, start,[])
    epoc = sum([c_list[i] for i in p_list])
    if epoc <= 0: # 回るごとに下がる場合
        best = c_list[p_list[0]]
        current_score = c_list[p_list[0]]
        for i in range(1, min(K, len(p_list))):
            current_score += c_list[p_list[i]]
            if best < current_score:
                best = current_score
    else: #回るごとに上がる場合
        syo,amari = divmod(K, len(p_list))
        base = (syo-1) * epoc
        tmp = p_list
        p_list.extend(p_list[:amari])
        tmp2 = p_list
        best = c_list[p_list[0]] + base
        current_score = c_list[p_list[0]] + base
        for i in range(1, len(p_list)):
            current_score += c_list[p_list[i]]
            if best < current_score:
                best = current_score
    if best > total_best:
        total_best = best
        
print(total_best)

Submission status: Runtime Error

Solution code:
import sys
import math
import itertools
import collections
from collections import deque
import copy

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()
    C = NLI()
    
    P2 =  copy.deepcopy(P)
    P2.insert(0,0)

    C2 =  copy.deepcopy(C)
    C2.insert(0,0)    

    tmp_ls = []
    visit_ls = [0 for _ in range(N+1)]
    loop_ls = []
    
    n = 1
    
    while n <N+1:
        if visit_ls[P2[n]] == 1:
            n += 1
            continue
        else:
            tmp_ls.append(P2[n])
            visit_ls[P2[n]] = 1
            n = P2[n]
            if P2[n] in tmp_ls:
                loop_ls.append(tmp_ls)
                tmp_ls =[]
                n += 1
    
    #print(loop_ls)
    C2.extend(C2)
    #print(C)
    
    def maxreturn(X,ls):
        
        if max(ls)<0:
            return max(ls)
        else:
            
            len_ls = len(ls)
            if K > len_ls:
                #K//len_ls周して残りで最大になるかも
                X = K%len_ls
                rounded = K // len_ls
            else:
                #1周しないので
                X = K

            len_ls = len(ls)
#            if cnt > 0:
            #X = min(K,len_ls)
            ls.extend(ls)
            points = [0 for _ in range(len_ls)]
            rtn = 0
            for x in range(X):
                for l in range(len_ls):
                    
                    points[l] += C2[ls[l+x]]
                    #print(C2[ls[l+x]],x,l,points,"point",ls[x+l])
                    rtn = max(rtn,max(points))
            #print("ROUND",rounded)
            
            cnt = 0
            for l in range(len_ls):
                cnt += C2[ls[l]]
            if cnt > 0:
                rtn = cnt * rounded + rtn
 
            return rtn
    
    ans = min(C)
    for p in range(len(loop_ls)):
        ans = max(ans,maxreturn(K,loop_ls[p]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

maxcost = -float('inf')
for pi in p:    # O(n^2)
    curr, costs = pi, [0]
    while pi != p[curr-1]:
        curr = p[curr-1]
        costs.append(costs[-1]+c[curr-1])
    loopsum = costs[-1]+c[pi-1]
    if loopsum > 0:
        maxcost = max(maxcost, loopsum*(k//len(costs))+max(costs[1:k % len(costs)+1]))
    else:
        maxcost = max(maxcost, max(costs[1:min(k, n)+1]))

print(maxcost)

Submission status: Runtime Error

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

maxcost = -float('inf')
for pi in p:    # O(n^2)
    curr, costs = pi, [0]
    while pi != p[curr-1]:
        curr = p[curr-1]
        costs.append(costs[-1]+c[curr-1])
    loopsum = costs[-1]+c[pi-1]
    if loopsum > 0:
        maxcost = max(maxcost, loopsum*(k//len(costs))+max(costs[1:k % len(costs)+1]))
    else:
        maxcost = max(maxcost, max(costs[1:min(k, n)]))

print(maxcost)

Submission status: Runtime Error

Solution code:
import heapq

N, K = map(int, input().split(" "))
 
Ps = list(map(int, input().split(" ")))
Cs = list(map(int, input().split(" ")))


max_points = []
heapq.heapify(max_points)
for start_point in range(1, N+1):
    flg = False
    max_point = -float('inf')
    C_point = 0
    max_point = []
    heapq.heapify(max_point)
    now_point = start_point
    for _ in range(K):
        next_point = Ps[now_point-1]
        C_point += Cs[next_point-1]
        
        heapq.heappush(max_point, -C_point)
        now_point = next_point
    
    if next_point == start_point:
            flg = True
            l = _ + 1
            break
        
    if flg:
        print(l)
        q, r = divmod(K, l)
        now_point = start_point
        for _ in range(r):
            next_point = Ps[now_point-1]
            ins = max_point[_]
            heapq.heappush(max_point,ins + Cs[next_point-1])
            
            now_point = next_point
        
        
        
        
    
    max_point_ = heapq.heappop(max_point)
    heapq.heappush(max_points, max_point_)
 
print(-heapq.heappop(max_points))

Submission status: Runtime Error

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

max_ans = -10**9
for i in range(1, N+1):
    v = i
    s = 0
    loop = []
    while True:
        loop.append(v)
        s += P[v]
        v = C[v]
        if v == i:
            break

    L = len(loop)
    a = K // L
    r = K % L
    ans = a * max(0, sums[i])

    tmp = P[loop[0]]
    if r > 0:
        for j in range(1, r):
            if P[loop[j]] >= 0:
                tmp += P[loop[j]]
            else:
                break

    ans += tmp
    if ans > max_ans:
        max_ans = ans

print(max_ans)

Submission status: Runtime Error

Solution code:

def my_solve(n, k, p, c):

    p = [0] + p
    c = [0] + c
    score = [[0] * (n + 1) for _ in range(n + 1)]
    # score[i][j]: iからstartしてj回移動した時のスコア
    l_cycle = [0] * (n + 1)
    for i in range(1, n + 1):
        start = i
        move_cnt = 0
        nxt = i
        while move_cnt < n:
            nxt = p[nxt]
            score[i][move_cnt + 1] += score[i][move_cnt] + c[nxt]
            move_cnt += 1
            if nxt == start:
                l_cycle[start] = move_cnt
                break
    # for i in range(1, n + 1):
    #     print(score[i])
    # print('l_cycle', l_cycle)
    ans = -float('inf')
    for s in range(1, n + 1):
        if k <= l_cycle[s]:
            # サイクルを回らないので
            temp = max(score[s][1:k + 1])
            ans = max(ans, temp)
            continue
        # 以降は一周以上出来る時

        # 一周以下でやめる場合を探索
        temp = max(score[s][1:l_cycle[s] + 1])
        ans = max(ans, temp)
        # if score[s][l_cycle[s]] <= 0:
        #     # 周回する意味がない
        #     continue
        sk = k // l_cycle[s]  # 何周出来るか
        remk = k % l_cycle[s]
        temp = sk * score[s][l_cycle[s]]  # 周回によるスコア
        if remk != 0:
            temp += max(score[s][1:remk + 1])
        ans = max(ans, temp)
    return ans


def ac_solve(n, k, p, c):
    for i in range(n):
        p[i] -= 1
    ans = -float('inf')
    for st in range(n):
        x = st
        score = []
        tot = 0
        while True:
            x = p[x]
            score.append(c[x])
            tot += c[x]
            if x == st:
                break
        l = len(score)
        now = 0
        t = 0
        for i in range(l):
            t += score[i]
            if i + 1 > k:
                break
            now = t
            if tot > 0:
                cycle_num = (k - (i + 1)) // l
                now += tot * cycle_num
            ans = max(ans, now)
    return ans


def main():
    while True:
        n = random.randint(2, 5)
        k = random.randint(1, 10)
        p = list(range(1, n + 1))
        random.shuffle(p)
        c = [random.randint(-100, 100) for _ in range(n)]
        c2 = c[:]
        ans1 = my_solve(n, k, p, c)
        org_p = p[:]
        ans2 = ac_solve(n, k, org_p, c2)
        # assert org_p == p, f'{org_p}:{p}'
        if ans1 == ans2:
            continue
            print('ok')
        else:
            print('ng')
            print(n, k)
            print(f'my_ans:{ans1}')
            print(f'ac_ans:{ans2}')


def main2():
    n = int(input())
    k = int(input())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    print(my_solve(n, k, p, c))


if __name__ == '__main__':
    main2()

Submission status: Runtime Error

Solution code:
import random


def my_solve(n, k, p, c):

    p = [0] + p
    c = [0] + c
    score = [[0] * (n + 1) for _ in range(n + 1)]
    # score[i][j]: iからstartしてj回移動した時のスコア
    l_cycle = [0] * (n + 1)
    for i in range(1, n + 1):
        start = i
        move_cnt = 0
        nxt = i
        while move_cnt < n:
            nxt = p[nxt]
            score[i][move_cnt + 1] += score[i][move_cnt] + c[nxt]
            move_cnt += 1
            if nxt == start:
                l_cycle[start] = move_cnt
                break
    # for i in range(1, n + 1):
    #     print(score[i])
    # print('l_cycle', l_cycle)
    ans = -float('inf')
    for s in range(1, n + 1):
        if k <= l_cycle[s]:
            # サイクルを回らないので
            temp = max(score[s][1:k + 1])
            ans = max(ans, temp)
            continue
        # 以降は一周以上出来る時

        # 一周以下でやめる場合を探索
        temp = max(score[s][1:l_cycle[s] + 1])
        ans = max(ans, temp)
        # if score[s][l_cycle[s]] <= 0:
        #     # 周回する意味がない
        #     continue
        sk = k // l_cycle[s]  # 何周出来るか
        remk = k % l_cycle[s]
        temp = sk * score[s][l_cycle[s]]  # 周回によるスコア
        if remk != 0:
            temp += max(score[s][1:remk + 1])
        ans = max(ans, temp)
    return ans


def ac_solve(n, k, p, c):
    for i in range(n):
        p[i] -= 1
    ans = -float('inf')
    for st in range(n):
        x = st
        score = []
        tot = 0
        while True:
            x = p[x]
            score.append(c[x])
            tot += c[x]
            if x == st:
                break
        l = len(score)
        now = 0
        t = 0
        for i in range(l):
            t += score[i]
            if i + 1 > k:
                break
            now = t
            if tot > 0:
                cycle_num = (k - (i + 1)) // l
                now += tot * cycle_num
            ans = max(ans, now)
    return ans


def main():
    while True:
        n = random.randint(2, 5)
        k = random.randint(1, 10)
        p = list(range(1, n + 1))
        random.shuffle(p)
        c = [random.randint(-100, 100) for _ in range(n)]
        c2 = c[:]
        ans1 = my_solve(n, k, p, c)
        org_p = p[:]
        ans2 = ac_solve(n, k, org_p, c2)
        # assert org_p == p, f'{org_p}:{p}'
        if ans1 == ans2:
            continue
            print('ok')
        else:
            print('ng')
            print(n, k)
            print(f'my_ans:{ans1}')
            print(f'ac_ans:{ans2}')


def main2():
    n = int(input())
    k = int(input())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    print(my_solve(n, k, p, c))


if __name__ == '__main__':
    main2()

Submission status: Runtime Error

Solution code:
 bmn,km;lghjklm

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):
    seen = [-1]*N
    cumsum = [0]*(N+1)
    now = i
    j = 0
    while seen[now] == -1:
        seen[now] = 1
        now = P[now]
        cumsum[j+1] = cumsum[j] + C[now]
        j += 1
    loop_size = j
    if K <= loop_size:
        ans = max([ans] + cumsum[1:K+1])
    else:
        if cumsum[loop_size] > 0:
            loop_n = K//loop_size
            score = cumsum[loop_size]*loop_n + max(cumsum[1:K%loop_size+1])
            ans = max(ans, score)
        else:
            ans = max([ans] + cumsum[1:loop_size+1])
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()))

check=[0]*n
group=[]

for i in range(n):
    tmp=i
    if check[tmp]==0:
        tmp_group=[]
        while check[tmp]==0:
            tmp_group.append(tmp)
            check[tmp]=1
            tmp=p[tmp]-1

        group.append(tmp_group)

ans="start"

#startの最低とgoalの最高の和
for item in group:
    
    #一周すると何になるか。これはどこスタートでも同じ
    circle=0
    cnt=k
    if len(item)<k:
        for v in item:
            circle+=c[v]
        circle=circle*(k//len(item))
        circle=max(circle,0)    
        cnt=k%len(item)
    
    #一周した後のあまりで最強を探す


    goal="INF"
    
    #startは各groupのindexが入ってる
    for start in range(len(item)):
        tmp=0
        #print("start",item,start,cnt)
        for i in range(start,start+cnt):
            #print(">>",i)
            tmp+=c[item[i%len(item)]]
            #print(item[i%len(item)],c[item[i%len(item)]])
            if goal=="INF":
                goal=tmp
            else:
                goal=max(goal,tmp)

    #print(item,circle,goal)
    if ans=="start":
        ans=goal+max(0,circle)
    else:
        ans=max(ans,goal+max(0,circle))

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()))
D = list()
nlist = list(range(N))

l = list()
ilist = list()
i = nlist[0]
while len(nlist) > 0:
  while True:
    if i in ilist:
      D.append(l)
      break
    else:
      l.append(C[P[i]])
      ilist.append(i)
      nlist.remove(i)
      i = P[i]

def culcmax(A):
  S = list()
  for i in range(len(A)):
    if i == 0:
      S.append(A[i])
    else:
      S.append(max(S[-1] + A[i], A[i]))
  return max(S)
ret = list()
for L in D:
  if K >= len(L):
    tmp_ret = list()
    for i in range(len(L)):
      l_ = L[:i].copy()
      tmp = L[i:].copy()
      l_.extend(tmp)
      tmp_ret.append(culcmax(l_))
    ret.append(max(tmp_ret))
  else:
    L_ = L.copy()
    L_.extend(L_)
    tmp_ret = list()
    for i in range(len(L)):
      l_ = L_[i:i+K]
      tmp_ret.append(culcmax(l_))
    ret.append(max(tmp_ret))
print(max(ret))

Submission status: Runtime Error

Solution code:
#import random

IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
#N = 4500
#K = 10**9
#P = [None] + random.sample(range(1, N+1), k=N)
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False
g = {}
for i in range(1, N+1): g.update({i: P[i-1]})

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    pos = i
    cnt = 0
    steps, scores = [0]*(N+N+N+N), [0]*(N+N+N+N)
    path = [False] * (N+1)
    while True:
        steps[cnt] = pos
        scores[cnt] = C[pos]
        pos = P[pos]
        cnt += 1
        if path[pos]:
            break # found closure
        else:
            path[pos] = True
    if verbose: print('closure found')
    st = steps.index(pos) # start of closure
    if verbose: print('closure steps identified')
    closure_path = steps[st:cnt]
    closure_scores = scores[st:cnt]
    closure_score = sum(closure_scores)
    preclosure_len = st
    score_len = 0
    if verbose: print('closure path:', closure_path)
    closure_len = len(closure_path)
    cycles = (K-preclosure_len-closure_len)//closure_len
    resid = (K-preclosure_len)%closure_len
    if cycles >= 1: cycles -= 1
    if cycles<1:
        score_len = K
    else:
        score_len = preclosure_len + closure_len + 1 + closure_len + resid
#        score_len = K - closure_len*cycles + 1
    if (cycles > 0):
        scores[cnt] = closure_score*cycles
        cnt+=1
    for j in range(closure_len*3):
        if cnt+j>len(scores): break
        scores[cnt+j] = closure_scores[j%closure_len]
    if verbose: print('preclosure:', preclosure_len,
                      'cycle len', closure_len,
                      'cycles:', cycles, 'resid:', resid)
    if verbose: print(i, ':', scores)
    localmax = max(cumsum(scores[0:(score_len)]))
    maxsc = max(localmax, maxsc)
    if verbose: print(i, ': done with', localmax, 'score_len:', score_len)

    if verbose: print('going greedy')
    for j in range(1, closure_len):
        target = steps[j]
        if done[target]: continue
        localmax = max(cumsum(scores[j:(score_len+j)]))
        maxsc = max(localmax, maxsc)
        done[target] = True
        if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Submission status: Runtime Error

Solution code:
#D
N, K = map(int,(input().split()))
P=list(map(int, input().split()))
C=list(map(int, input().split()))
P= [d-1 for d in P]

Position_list=[P]
Score_list=[[0,0,0,0,0]]
Max_list=[0]

for j in range(K):
    Updated_Position=[]
    Updated_Score=[]
    Current_Position=Position_list[j]
    for i in range(N):
        Position=Current_Position[i]
        Updated_Position.append(Current_Position[Position])
        Updated_Score.append(Score_list[j][i]+C[Position])
    Position_list.append(Updated_Position)
    Score_list.append(Updated_Score)
    Max_list.append(max(Score_list[j+1]))
    
print(max(Max_list))

Submission status: Runtime Error

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

if n >= k:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        for j in range(k):
            now = p[now] - 1
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
        ans = max(max(score), ans)
    print(ans)
else:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        check = [0] * n
        for j in range(k):
            go = p[now] - 1
            if check[go] == 1:
                break
            now = go
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
            check[now] = 1
        d = k % j
        t = k // j
        score_2 = []
        for j in range(d):
            now = p[now] - 1
            if j == 0:
                score_2.append(c[now])
            else:
                score_2.append(score_2[j-1] + c[now])
        res = max(score)
        res_2 = score[-1] * t + max(score_2)
        ans = max(ans, res, res_2)

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

if n >= k:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        for j in range(k):
            now = p[now] - 1
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
        ans = max(max(score), ans)
else:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        check = [0] * n
        cnt = 0
        for j in range(k):
            go = p[now] - 1
            if check[go] == 1:
                break
            now = go
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
            check[now] = 1
            cnt += 1
        d = k // cnt
        e = k % cnt
        ans = max(score[-1] * d + max(score[:e]), max(score), 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()))
vis = [0]*n
group = []
gcnt = 0
ans = -10**10

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

def dfs(a):
    if vis[a] == 0:
        vis[a] = 1
        temp.append(a)
        dfs(p[a])

for i in range(n):
    temp = []
    dfs(i)
    if len(temp) != 0:
        group.append(temp)
        gcnt += 1

for i in range(gcnt):
    dp = []
    ref = -10**10
    kcnt = 0
    gnum = len(group[i])
    for j in group[i]:
        dp.append(c[j])
    for j in group[i]:
        dp.append(c[j])
    for j in range(gnum): #部分数列の項数
        ref1 = sum(dp[0: j + 1])
        for l in range(gnum): #部分数列の始まり
            if l != 0:
                ref1 -= dp[l - 1]
                ref1 += dp[l + j]
            if ref1 > ref:
                ref = ref1
                kcnt = j + 1
    tempk = k - kcnt
    if tempk >= gnum: #残り回数が１周分以上ある場合
        tempsum = sum(dp[:gnum])
        if tempsum > 0:
            ref += tempsum*(tempk//gnum)
        ans = max(ans, ref)
    else:
        ans = max(ans, ref)
print(ans)

Submission status: Runtime Error

Solution code:
zimport sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, K = MAP()
P = LIST()
C = LIST()

loop_point = [0]*N
loop_count = [0]*N
searched = [0]*N

for i in range(N):
	if searched[i]:
		continue
	idx = i
	points = 0
	cnt = 0
	while not searched[P[idx]-1]:
		idx = P[idx]-1
		searched[idx] = 1
		cnt += 1
		points += C[idx]
	loop_count[i] = cnt
	loop_point[i] = points

	while not loop_point[P[idx]-1]:
		idx_next = P[idx]-1
		loop_count[idx_next] = loop_count[idx]
		loop_point[idx_next] = loop_point[idx]
		idx = idx_next

ans = -INF
for i in range(N):
	p = 0
	idx = i
	loop = loop_point[i] > 0 and K > loop_count[i]
	for j in range(1, min(K+1, loop_count[i]+1)):
		idx = P[idx] - 1
		p += C[idx]
		if loop:
			final_p = p + loop_point[i]*((K-j)//loop_count[i])
		else:
			final_p = p
		ans = ans if ans > final_p else final_p
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)

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=[]
for i in range(n):
    l=[]
    j=p[i]-1
    l+=[c[p[i]-1]]
    while j!=i:
        l+=[l[-1]+c[p[j]-1]]
        j=p[j]-1
    a+=[l]
l=[]
for i in a:
    if len(i)>=k:
        l+=[max(i)]
        continue
    p=i[-1]
    if p<0:
        l+=[max(i)]
    else:
        q=len(i)
        l+=[p*(k//q)+max(i[:k%q])]
print(max(l))