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: Wrong Answer

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

INF = 1 << 100


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

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


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

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

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

if max(c) < 0:
    print(max(c))
    exit()

loop_list = []
visited = [False]*n
d = deque()
for start in range(n):
    if visited[start]:
        continue
    loop = [start]
    d.append(start)
    visited[start] = True
    while True:
        now = d.pop()
        next = p[now]
        d.append(next-1)
        if visited[next-1]:
            loop_list.append(loop)
            break
        else:
            visited[next-1] = True
            loop.append(next-1)
#print(loop_list)

ans = 0
for loop in loop_list:
    len_loop = len(loop)
    S = sum(c[v] for v in loop)
    for a in range(len_loop):
        dist_ab = 1
        cost_ab = 0
        for b in range(a+1, a+len_loop):
            b %= len_loop
            cost_ab += c[loop[b]]
            max_cost = cost_ab + max(0, S)*((k-dist_ab)//len_loop)
            ans = max(ans, max_cost)
            dist_ab += 1
            if dist_ab > k:
                break
print(ans)

Submission status: Wrong Answer

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

INF = 1 << 100


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

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

                ans = max(ans, max_val)
                continue


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

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
import math

def split_to_loops(G):
    # G[i]: i の次の頂点(0 <= i <= |G|-1) を格納しているリストがあるとき、
    # ループ単位にリストを分割する。
    # ex) G = [1, 3, 4, 0, 2]
    # => "0 -> 1 -> 3 -> 0" というループと
    #    "2 -> 4 -> 2" というループがある
    # このメソッドでは、[[0,1,3],[2,4]]が返される

    loops = []
    _all = set(range(len(G)))

    while _all:
        s = _all.pop()
        loop = [s]
        v = G[s]
        while v != s:
            _all.remove(v)
            loop.append(v)
            v = G[v]

        loops.append(loop)

    return loops

def split_list_by_negative(A):
    # Aのリストを、0以上の数が連続している部分に分割する
    # 端っこは繋がっているとみなす
    # ex) A = [1, -2, 4, 3, -1, 2, 6, 4, 5, -3, 2]
    # => [[4, 3], [2, 6, 4, 5], [2, 1]]
    positives = []
    l = []
    for a in A:
        if a >= 0:
            l.append(a)
        else:
            if l:
                positives.append(l)
            l = []

    if l:
        positives.append(l)
    
    # 途中に負の数が混じってて、端っこが両方正なら、端っこのリストをつなげる
    # （上の例でいう2と1を一つのリストにする）
    if A[0] >= 0 and A[-1] >= 0 and len(positives) >= 2:
        positives[-1] += positives[0]
        del positives[0]

    return positives

def find_max_continued(A, n):
    # A 内で連続した1個以上n個以内の領域の合計の最大値を見つける
    # ex) A = [-2, 4, 3, -1, 2, 6, 4, 5, -3], n = 3
    #       => [6, 4, 5] の合計 =15 が最大
    # ex) A = [-2, 4, 3, -1, 2, 6, -4, 5, -3], n = 3
    #       => [2, 6] の合計 =8 が最大
    # ex) A = [-2, -4, -3, -1, -2, -6, -4, -5, -3], n = 3
    #       => [-1] の合計 =-1 が最大


    # 方針：0以上の値が連続している部分を抜き出す
    # => [[4, 3], [2, 6, 4, 5]]

    positives = split_list_by_negative(A)
    # print(f'{positives=}')
    # もしAの中に正の数がないなら、A内の最大値が返すべき値
    if len(positives) == 0:
        return max(A)

    # それぞれの連続部分で、n個以内の連続部分の最大値を探す
    _max = 0
    for P in positives:
        _sum = sum(P[:n])
        _max = max(_max, _sum)
        L = len(P)
        # 連続領域がn個以上の場合、左からn個の合計を計算した後、
        # 領域を右にずらしながら合計を計算することで、O(L) で計算できる 
        for i in range(n, L):
            _sum += P[i] - P[i-n]
            _max = max(_max, _sum)

    return _max

def find_max_in_one_loop(loop, K, C):
    # loopにおける1回以上K回以内の移動でのスコアの最大値を見つける
    L = len(loop)
    loop_c = [C[v] for v in loop] # ループに登場するマスのスコアのリスト
    # print(f'{loop_c=}')

    # 一周したときのスコア
    sum_1_loop = sum(loop_c)
    # print(f'{loop_c=}, {sum_1_loop=}')

    if sum_1_loop < 0:
        # 一周したときに負になるようなら、ループしないほうがいい
        return find_max_continued(loop_c, min(K, L))
    else:
        # 一周以上移動できない場合
        if K < L:
            return find_max_continued(loop_c, K)

        # 一周以上移動できる場合
        # できるだけループしたほうがいい

        n_loops = K // L # ループできる回数

        # ただし、スコアが [1 1 1 -2] のようになっている場合、
        # 1周するより負の数を避けて途中で終了したほうがいいので、
        # 一旦わざとループできる回数から1周分減らしておく
        n_loops -= 1
        
        score = sum_1_loop * n_loops
        K -= n_loops * L # 残りの移動回数 (L <= K < 2*L)

        # 一周未満の時のスコアの最大値
        score_no_loop = find_max_continued(loop_c, L)
        # 一周してさらにK-L回以内で移動するときのスコア
        score_loop = sum_1_loop
        if K != L:
            # print(f'{K=}, {L=}, {K-L}, {find_max_continued(loop_c, K - L)}')
            score_loop += find_max_continued(loop_c, K - L)
        # 最後、一周しないほうがいいか、一周したほうがいいか、スコアの大きいほうを選ぶ
        score += max(score_no_loop, score_loop)
        return score

def main():
    N, K = map(int, input().split())
    # P は番号を1引くことで配列で扱いやすくする
    P = list(map(lambda x: int(x)-1, input().split()))
    C = list(map(int, input().split()))

    # ループごとに分割
    # ex) P = [1, 3, 4, 0, 2]
    # => "0 -> 1 -> 3 -> 0" というループと
    #    "2 -> 4 -> 2" というループがある
    # => loops = [[0,1,3],[2,4]]
    loops = split_to_loops(P)
    # print(f'{loops=}')

    ans = -(10 ** 10)
    for loop in loops:
        # [0,1,3] などのループ単位で、1回以上K回以内の移動での最大値を見つける
        # その最大値の中からさらに最大値を見つけて、答えとする
        ans = max(ans, find_max_in_one_loop(loop, K, C))
    
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ans = -float("inf")

for st in range(N):
  S = []
  temp = P[st]
  S.append(C[temp])
  while temp != st:
    temp = P[temp]
    S.append(S[-1] + C[temp])
  cnt = len(S)
  loop, k = divmod(K, cnt)
  if k == 0:
    loop -= 1
    k += cnt
  point = 0
  if S[-1] >= 0:
    point += S[-1] * loop
  ans = max(ans, point + max(S[:k]))

print(ans)

Submission status: Wrong Answer

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

INF = 1 << 100


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

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


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

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
def read_input():

    n, k = map(int, input().split())
    p = list(map(lambda x : int(x) - 1, input().split()))
    c = list(map(int, input().split()))

    return n, k, p, c

def solve_i(i, k, p, c, n):
    
    points = None
    maxi = None
    s = i
    i = p[i]
    while i != s:
        
        if points is None:
            points = [c[i]]
        else:
            points.append(points[-1] + c[i])

        i = p[i]

    points.append(points[-1] + c[i])

    if k < len(points):
        return max(points[:k])

    if points[-1] <= 0:
        return max(points)
    else:
        cycles = k // len(points)
        remainder = k % len(points)

        potential = points[-1] * cycles
        if remainder != 0:
            potential += max(points[:remainder])

        maxi = max(points)
        return max(maxi, potential)



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

    maxi = float('-Inf')
    for i in range(n):
        maxi = max(maxi, solve_i(i, k, p, c, n))

    return maxi


print(solve(*read_input()))

Submission status: Wrong Answer

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

for start in range(n):
    move=[]
    score=[]
    cnt=0
    now=p[start]
    flag=True
    ans_index=0
    while True:
        cnt+=1
        if now in move:
            break
        move.append(now)
        score.append(c[now-1])
        if c[now-1]<0:
            flag=False
        if cnt<=k and c[now-1]>=0 and flag:
            ans_index=cnt-1
        now=p[now-1]
    #print(start+1,move,score)
    t=sum(score)
    xxx=t//len(move)
    if t<=0:
        xxx=0
    ans=max(ans,xxx*t+score[ans_index])
print(ans)

Submission status: Wrong Answer

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

sumlist1 = [[0]*N for _ in range(N)]
walist = [[0]*N for _ in range(N)]
loopcount = [0]*N

for h in range(N):
    sumlist1[h][0] = C[h]
    walist[h][0] = C[h]
    now = h
    l = 0
    for i in range(1,N):
        now = P[now]-1

        if sumlist1[h][i-1] < 0:
            sumlist1[h][i] = C[now]
        else:
            sumlist1[h][i] += sumlist1[h][i-1] + C[now]
        walist[h][i] += walist[h][i-1] + C[now]
        
        l += 1
        if now == h:
            break
    else:
        l += 1
    loopcount[h] = l
#print(sumlist1)

maxlist = [0]*N
for i in range(N):
    T = loopcount[i]
    wa = walist[i][T-1]
    #print(wa)

    loop = K//T
    amari = K%T

    if wa >= 0:
        if amari != 0:
            maxlist[i] = wa*loop + max(sumlist1[i][:amari])
        else:
            maxlist[i] = wa*loop

    else:
        if loop == 0:
            maxlist[i] = max(sumlist1[i][:amari])
        else:
            maxlist[i] = max(sumlist1[i])

print(max(maxlist))
#print(sumlist1)

Submission status: Wrong Answer

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

INF = 1 << 100


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

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


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

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

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

G = [0] * N

d = -10 ** 9
j = 0

i = 0
s = 0

for l in range(N):
    s = 0
    j = l
    for i in range(K):
        s += C[j]        
        
        if s > d:
            d = s

        j = P[j] - 1
        if j == l and s > 0:
            if K-i > i:
                i = i * (K // i)
                s = s * i
        elif j == l:
            break


print(d)

Submission status: Wrong Answer

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

ans = -float("inf")

for st in range(N):
  S = [0]
  temp = st
  cnt = 1
  while P[temp] != st:
    temp = P[temp]
    cnt += 1
    S.append(S[-1] + C[temp])
  S.append(S[-1] + C[st])
  loop, k = divmod(K, cnt)
  if k == 0:
    loop -= 1
    k += cnt
  point = 0
  if S[-1] >= 0:
    point += S[-1] * loop
  for i in range(1, min(k+1, cnt+1)):
    ans = max(ans, point + S[i])

print(ans)

Submission status: Wrong Answer

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

vis = [False] * N
ans = [-float("inf")] * N

for root in range(N):
  if vis[root]:
    continue
  vis[root] = True
  
  cycle = [root]
  costs = [C[root]]
  u = P[root]
  vis[u] = True
  
  while u != root:
    cycle.append(u)
    costs.append(C[u])
    u = P[u]
    vis[u] = True

  L = len(cycle)
  S = sum(costs)
  for i, v in enumerate(cycle):
    cnt = 0
    for step in range(1, min(L, K) + 1):
      cnt = costs[i]
      val1 = cnt
      val2 = cnt + (K - step) // L * S
      ans[v] = max(ans[v], val1, val2)

print(max(ans))

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = max(C)
    for i in range(N):
        next = P[i]

        cnt = 0
        cyclevalue = 0

        while True:
            cyclevalue += C[next]
            cnt += 1
            if next == i:
                break
            next = P[next]

        q = K // cnt
        tmp = 0
        if q != 0:
            tmp = q * cyclevalue
            ans = max(ans, tmp)
        r = K % cnt
        next = P[i]

        if cyclevalue <= 0:
            tmp = 0
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = max(C)
    for i in range(N):
        next = P[i]

        cnt = 0
        cyclevalue = 0

        while True:
            cyclevalue += C[next]
            cnt += 1
            if next == i:
                break
            next = P[next]

        q = K // cnt
        tmp = 0
        if q != 0 or cyclevalue > 0:
            tmp = q * cyclevalue
            ans = max(ans, tmp)
        r = K % cnt
        next = P[i]

        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = max(C)
    for i in range(N):
        next = P[i]

        cnt = 0
        cyclevalue = 0

        while True:
            cyclevalue += C[next]
            cnt += 1
            if next == i:
                break
            next = P[next]

        q = K // cnt
        tmp = 0
        if q != 0 and cyclevalue > 0:
            tmp = q * cyclevalue
            ans = max(ans, tmp)
        r = K % cnt
        next = P[i]

        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
 
check = [False] * (N+10)
roop = []
 
for i in range(1, N+1):
    tmp = []
    s = P[i-1]
    while True:
        if check[s]:
            break
        check[s] = True
        tmp.append(s)
        s = P[s-1]
    if len(tmp) > 0:
        roop.append(tmp)
 
ans = -10**18
for li in roop:
    SUM = 0
    for i in li:
        SUM += C[i-1]
    length = len(li)
    amari = K%length
    if amari == 0:
        try_a = length
    else:
        try_a = amari
    for j in range(length):
        s = li[j]
        tmp1 = 0
        for k in range(try_a):
            tmp1 += C[s-1]
            now = tmp1
            if SUM > 0:
                e = (K-(k))//length
                now += SUM*e
            ans = max(ans, now)
            s = P[s-1]

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = max(C)
    for i in range(N):
        next = P[i]

        cnt = 0
        cyclevalue = 0

        while True:
            cyclevalue += C[next]
            cnt += 1
            if next == i:
                break
            next = P[next]

        q = K // cnt
        tmp = 0
        if q != 0:
            tmp = q * cyclevalue
            ans = max(ans, tmp)
        r = K % cnt
        next = P[i]

        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next]
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

def get_cycle(start_i):
    cycle = []
    i = start_i
    while True:
        i = P[i]
        if i == start_i:
            break
        cycle.append(i)
    cycle.append(start_i)
    return cycle

def get_cycle_scores(cycle):
    score = 0
    scores = [score]
    for i in cycle:
        score += C[i]
        scores.append(score)
    return scores

max_scores = []
for start_i in range(1,N+1):
    cycle = get_cycle(start_i)
    scores = get_cycle_scores(cycle)
    # 1cycle以下の場合は全て調べればよし
    if K <= len(cycle):
        max_score = max(scores[move] for move in range(1, K+1))
        max_scores.append(max_score)
        continue
    # 1サイクルの長さ
    cycle_len = len(cycle)
    # 1サイクルごとのスコア
    score_per_cycle = scores[cycle_len]
    # ラスト1サイクルのスコア
    scores_last_cycle = []
    # 最後の1cycleの値を調べる
    for move in range(K-cycle_len, K+1):
        # 何周したか
        loop_cnt = move // cycle_len
        # あまり
        rest_move = move % cycle_len
        # スコア = 1周ごとのスコア * 何周したか + あまり
        score = loop_cnt * score_per_cycle + scores[rest_move]
        scores_last_cycle.append(score)

    max_scores.append(max(scores_last_cycle))

print(max(max_scores))

Submission status: Wrong Answer

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

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  masu[now_mas]=1
  #このwhileはせいぜい5000
  while True:
    if count!=0 and masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    
    if ans22<ans:
      ans22=ans
      
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=(((k-1)//count)-1)*ans
    
    if ans22<ans:
      ans22=ans
    for i in range(k-((k-1)//count-1)*count):
      ans+=c[now_mas-1]
      if ans22<ans:
        ans22=ans
        
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  
  else:
    return max(ans,ans22)
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ < hantei:
    answ=hantei
print(answ)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
 
check = [False] * (N+10)
roop = []
 
for i in range(1, N+1):
    tmp = []
    s = P[i-1]
    while True:
        if check[s]:
            break
        check[s] = True
        tmp.append(s)
        s = P[s-1]
    if len(tmp) > 0:
        roop.append(tmp)
 
ans = -10**18
for li in roop:
    SUM = 0
    for i in li:
        SUM += C[i-1]
    length = len(li)
    amari = K%length
    if amari == 0:
        try_a = length
    else:
        try_a = amari
    for j in range(length):
        s = li[j]
        tmp1 = 0
        for k in range(try_a):
            tmp1 += C[s-1]
            now = tmp1
            if SUM > 0:
                e = (K-(k+1))//length
                now += SUM*e
            ans = max(ans, now)
            s = P[s-1]

print(ans)

Submission status: Wrong Answer

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


def main():
    [n, num] = [int(e) for e in si().split()]
    pl = [int(e) for e in si().split()]
    cl = [int(e) for e in si().split()]

    M = -1000000000*5000-1

    for i in range(n):
        vis = [0 for _ in range(n)]
        val = [0 for _ in range(n)]
        flag, ith, k, idx, m, cv, cn = False, 0, num, i, 0, 0, 0
        while k > 0:
            idx = pl[idx]-1
            ith += 1
            if not flag and vis[idx]:
                flag = True
                cv = m-(val[idx]-cl[idx])
                cn = ith-vis[idx]
                rest = k//cn
                if rest:
                    m += cv*rest
                    k -= cn*rest
            elif not flag:
                vis[idx] = ith
                val[idx] = m+cl[idx]
            m += cl[idx]
            M = max(M, m)
            k -= 1
    print(M)


if __name__ == '__main__':
    main()