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:
def segfunc(x,y):
  return x+y

class SegmentTree(object):
    def __init__(self, A, dot, unit):
        n = 1 << (len(A) - 1).bit_length()
        tree = [unit] * (2 * n)
        for i, v in enumerate(A):
            tree[i + n] = v
        for i in range(n - 1, 0, -1):
            tree[i] = dot(tree[i << 1], tree[i << 1 | 1])
        self._n = n
        self._tree = tree
        self._dot = dot
        self._unit = unit

    def __getitem__(self, i):
        return self._tree[i + self._n]

    def update(self, i, v):
        i += self._n
        self._tree[i] = v
        while i != 1:
            i >>= 1
            self._tree[i] = self._dot(self._tree[i << 1], self._tree[i << 1 | 1])

    def add(self, i, v):
        self.update(i, self[i] + v)

    def sum(self, l, r): #これで[l,r)から取り出す。
        l += self._n
        r += self._n
        l_val = r_val = self._unit
        while l < r:
            if l & 1:
                l_val = self._dot(l_val, self._tree[l])
                l += 1
            if r & 1:
                r -= 1
                r_val = self._dot(self._tree[r], r_val)
            l >>= 1
            r >>= 1
        return self._dot(l_val, r_val)


N,K = map(int,input().split())
P = list(map(int,input().split()))
for i in range(N):
  P[i]-=1
#print(P)
C = list(map(int,input().split()))
Flag = True
for c in C:
  if c >= 0:
    Flag = False
    break
if Flag:
  print(max(C))
  exit()
L = []
visited = set([])
for i in range(N):
  if i in visited:
    continue
  now = i
  temp = []
  while now not in visited:
    nxt = P[now]
    visited.add(now)
    temp.append(C[nxt])
    now = nxt
  L.append(temp)
#print(L)
INF = float("inf")
ans = 0
for X in L:
  n = len(X)
  #print(X)
  Tree = SegmentTree(X, segfunc, 0)
  A = sum(X)
  T = [0 for _ in range(n+1)]
  for i in range(n+1): #i個選ぶ
    nokori = n-i
    temp = INF
    #print(i,nokori)
    for j in range(nokori+1):
      #print(j,j+i)
      tt = Tree.sum(j,j+i)
      #print(tt)
      temp = min(temp,tt)
    #print(temp)
    T[-1-i] = A-temp
    #print(T[i])
  if A <= 0:
    hani = min(K,N)
    tmp = max(T[:hani])
    ans = max(ans,tmp)
  else:
    hani = K%n+1
    loop = K//n
    #print(loop,T)
    tmp = max(T[:hani])+loop*A
    ans = max(ans,tmp)
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()))


max = -26748126786421
for i in range(N):
    A=[]
    total =C[i]
    A.append(i)
    B=[]
    B.append(C[i])
    max_a = -12131313
    while P[i]-1 not in A:
        i = P[i]-1
        A.append(i)
        B.append(C[i])
        total += C[i]
    
    #print(total)
    
    if total > 0 and K >len(A):
        max_a = sum(B) * (K//len(A))
        
        #print(max_a,A,B)
        for n in range(K%len(A)):
            max_a += B[n]
            if max_a > max:
                max = max_a
        
    elif total <= 0 and K >len(A):
        max_a=0
        for n in range(len(A)):
            max_a += A[n]
            if max_a > max:
                max = max_a
    else:
        max_a=0
        for n in range(K):
            max_a += C[A[n]]
            if max_a > max:
                max = max_a
print(max)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

class Doubling:
    def __init__(self, lst, max_step):
        self.lst = lst
        self.max_step = max_step
        self.k = int(log2(max_step * 2 - 1)) + 1
        # print(self.k)
        self.D = self.create()

    def create(self):
        len_ = len(self.lst)
        D = [[-1] * len_ for _ in range(self.k)]
        D[0] = self.lst
        d = 2
        for i in range(1, self.k):
            for j in range(len_):
                D[i][j] = D[i - 1][D[i - 1][j]]
            d *= 2
        # print(D)
        return D

    def step(self, start, step):
        v = start
        for i in range(self.k, -1, -1):
            l = 1 << i
            if l <= step:
                v = self.D[i][v]
                # print(i, l)
                step -= l
        return v

def solve():
    N, K = MI()
    P = LI1()
    C = LI()

    ans = -INF
    for i in range(N):
        S = [0] * (N+1)
        used = [0] * N
        used[i] = 1
        mxs = [-INF] * (N+1)
        STEP = [-1] * N
        step = 0
        while 1:
            next = P[i]
            step = step + 1
            score = S[step-1] + C[next]
            S[step] = score
            mxs[step] = max(mxs[step-1], score)
            # ans_l = max(ans_l, S[step])
            if step == K:
                # print(mxs, mxs[K])
                ans = max(ans, mxs[K])
                break

            if used[next]:
                left = K - step
                # print(next, S, step, S[step], left)
                p = left // step
                q = left % step
                # print(mxs, p, q, mxs[step])
                # 現在の最高得点で打ち切る
                ans = max(ans, mxs[step])
                # print(next, S, STEP)
                ss = S[step] - S[STEP[next]]

                # さらにスコアを伸ばす
                if p > 0:
                    ans = max(ans, S[step] + max(0, mxs[step]))
                    ans = max(ans, S[step] + ss * p + max(0, mxs[q]))
                else:
                    ans = max(ans, S[step] + max(0, mxs[q]))

                # plus = max(S[step] * p + max(0, mxs[q]), mxs[step])
                # ans = max(ans, max(mxs[step], S[step] + mxs[step] * p + mxs[q]))
                # ans = max(ans, max(mxs[step], S[step] + max(0, plus)))
                break
            STEP[next] = i
            used[next] = 1
            i = next
    print(ans)

    
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
def main():
    INF = 10 ** 20
    N, K = list(map(int, input().split()))
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    # P のループの最初を検索しておく
    loop_list = list()
    visited = [0] * N
    for i in range(N):
        if visited[i] == 1:
            continue
        start = i
        size = 0
        sum_c = 0
        while visited[i] == 0:
            visited[i] = 1
            size += 1
            sum_c += C[i]
            i = P[i]
        loop_list.append((start, size, sum_c))
    # 各ループごとに考える
    ans = - INF
    for start, size, sum_c in loop_list:
        MAX_LEN = K % size
        if MAX_LEN == 0:
            MAX_LEN = K
        # 2順ループを作っておく
        CUMSUM_CC = [0] * (2 * size)
        cur_index = P[start]
        CUMSUM_CC[0] = C[P[start]]
        for i in range(1, 2 * size):
            cur_index = P[cur_index]
            CUMSUM_CC[i] += C[cur_index] + CUMSUM_CC[i - 1]
        # 最大MAX_LENの連続部分列での最大スコア
        max_score = - INF
        for left in range(2 * size):
            for right in range(left, min(2 * size, left + MAX_LEN)):
                s = CUMSUM_CC[right]
                if left > 0:
                    s -= CUMSUM_CC[left - 1]
                max_score = max(max_score, s)
        if sum_c > 0:
            max_score += sum_c * ((K - 1) // size)
        ans = max(ans, max_score)
    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()))

P = [0] + P
C = [0] + C

ans = -10**17
Loop = []
LoopValue = []
LoopCount = []

for i in range(1, n+1):
    if i in []:
        pass
    else:
        Visited = []
        Value = [0]
        count = 0
        pos = P[i]
        while pos != i:
            Visited.append(pos)
            Value.append(Value[-1] + C[pos])
            count += 1
            pos = P[pos]
        Visited.append(i)
        count += 1
        Value.append(Value[-1] + C[pos])
        Loop.append(Visited)
        LoopValue.append(Value)
        LoopCount.append(count)
        
        
        if k//count == 0:
            tmp = max(Value[1:k%count + 1])
        else:
            tmp = max(max(Value[1:]), k//count*Value[-1] + max(0, max(Value[:k%count + 1])))
        ans = max(tmp, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, k = LI()
p = LI()
c = LI()
C = []
S = []
for i in range(n):
    lst = [-1]*n
    cnt = 0
    idx = i
    s = 0
    while lst[idx] == -1:
        lst[idx] = cnt
        s += c[idx]
        cnt += 1
        idx = p[idx] - 1
    C.append(cnt)
    S.append(s)

if n >= k:
    ans = -10**10
    for i in range(n):
        cnt = 0
        ret = 0
        idx = p[i]
        while cnt < k:
            ret += c[idx-1]
            idx = p[idx-1]
            cnt += 1
            ans = max(ans, ret)
    print(ans)
else:
    ans = -10**10
    for i in range(n):
        if S[i] >= 0:
            tmp = S[i] * (k // C[i])
            r = k % C[i]
            cnt = 0
            ret = 0
            idx = p[i]
            ans = max(ans, tmp)
            while cnt < r:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, tmp + ret)
        else:
            cnt = 0
            ret = 0
            idx = p[i]
            while cnt < n:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, ret)
    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()))
sumC = sum(C)
if sumC > 0:
    t = sumC * (K // N)
    remainMove = K % N
    m = 10**9 * (-1) -1
    if remainMove ==0:
        m = 0
    for i in range(N):
      now = 0
      pos = P[i] - 1
      for j in range(remainMove):
        now += C[pos]
        pos = P[pos]-1
        print(now)
        m = max(now, m)

    print(m + t)
else:
    remainMove = N
    m = 10**9 * (-1) -1
    for i in range(N):
      now = 0
      pos = P[i] - 1
      for j in range(remainMove):
        now += C[pos]
        pos = P[pos]-1

        #print(now)
        m = max(now, m)
    print(m)

Submission status: Wrong Answer

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

loop_list = [] # ([indexes])
loop_score_list = []
loop_index_list = [0]*N
is_included_loop = [0] * N
num_loop = 0

for start in range(N):
    if is_included_loop[start]:
        continue
    now = start
    count = 1
    visited = [-1]*N # count
    visited[now] = 0
    while True:
        now = P[now]
        if visited[now] != -1:
            terminate_count = count
            start_count = visited[now]
            loop_start_idx = now
            break
        visited[now] = count
        count += 1
    
    num_loop += 1
    now = loop_start_idx
    loop_indexes = [now]
    visited = [-1]*N
    visited[now] = 0
    count = 1
    loop_score = 0
    while True:
        now = P[now]
        if visited[now] != -1:
            break
        loop_indexes.append(now)
        visited[now] = count
        loop_index_list[now] = num_loop
        loop_score += C[now]
        is_included_loop[now] = 1
    loop_list.append(loop_indexes)
    loop_score_list.append(loop_score)


scores = []
for start in range(N):
    tmp_score = 0
    rest = K
    now = start
    while not is_included_loop[now] and rest > 0:
        now = P[now]
        rest -= 1
        tmp_score += C[now]
        scores.append(tmp_score)
    
    if rest <= 0:
        scores.append(tmp_score)
        continue
    # loop
    number_of_loop = loop_index_list[now] - 1
    one_cicle_score = loop_score_list[number_of_loop]
    if one_cicle_score < 0:
        continue
    if rest <= len(loop_list[number_of_loop]):
        while rest >= 0:
            now = P[now]
            rest -= 1
            tmp_score += C[now]
            scores.append(tmp_score)
        continue
    else:
        n_l = rest // len(loop_list[number_of_loop])
        tmp_score += n_l * one_cicle_score
        scores.append(tmp_score)
print(max(scores))

Submission status: Wrong Answer

Solution code:
N,K=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

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

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

Q=[]
uf=UnionFind(N)
for i in range(N):
    uf.union(i,P[i]-1)
D1=list(uf.all_group_members().values())
D2=[]
for i in D1:
    ans=0
    for j in i:
        ans+=C[j]
    D2.append(ans)
L=[len(i) for i in D1]
S=min(2*max(L),K)

for i in range(N):
    ans=-float('inf')
    ans1=0
    now=P[i]-1
    for j in range(S):
        ans1+=C[now]
        now=P[now]-1
        ans=max(ans1,ans)
    Q.append(ans)
    
if K>min(L):
    for i,value in enumerate(D2):
        if value>0:
            ans3=value*(K//L[i])
            for j in D1[i]:
                ans=0
                ans1=0
                now=P[j]-1
                for k in range(K%L[i]):
                    ans1+=C[now]
                    now=P[now]-1
                    ans=max(ans1,ans)
                Q.append(ans3+ans)
print(max(Q))

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

def main():
    inf=float("inf")
    n,k=map(int,input().split())
    plst=list(map(int,input().split()))
    clst=list(map(int,input().split()))
    sm=-inf

    seen=[0]*n
    for i in range(n):
        if seen[i] : continue
        pos=i
        work=[]
        while not seen[pos]:
            seen[pos]=1
            work.append(clst[pos])
            pos=plst[pos]-1
        nwork=len(work)
        work=[0]+list(accumulate(work))

        sm_add=0
        numcut=min(nwork,k)
        if work[-1]>0 and k>=nwork:
            sm_add=work[-1]*(k//nwork)
            numcut=k%nwork
        
        if numcut==0:
            if sm<sm_add : sm=sm_add

        for i in range(nwork):
            for j in range(i,i+numcut):
                if j<nwork :
                    smwork=work[j+1]-work[i]
                else :
                    smwork=work[nwork]-work[i]+work[j-nwork+1]
                if smwork+sm_add>sm : sm=smwork+sm_add


    print(sm)

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()))
INF = 10**18
ans = -INF
for i in range(N):
    arr = []
    tot = 0
    rest = K
    visited = {}
    visited[i] = rest
    point = {}
    point[i] = 0
    nex = i
    while rest:
        nex = P[nex]
        tot += C[nex]
        arr.append(tot)
        rest -= 1
        if nex in visited:
            loop = visited[nex]-rest
            loop_point = tot-point[nex]
            rest2 = min(rest, loop)
            nex2 = nex
            tot2 = tot
            while rest2:
                nex2 = P[nex2]
                tot2 += C[nex2]
                arr.append(tot2)
                rest2 -= 1
            if loop_point > 0:
                tot += (rest//loop)*loop_point
                arr.append(tot)
                rest = rest%loop
                while rest:
                    nex = P[nex]
                    tot += C[nex]
                    arr.append(tot)
                    rest -= 1
            break
        else:
            visited[nex] = rest
            point[nex] = tot
    #print(i, arr)
    ans = max(ans, max(arr))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

def main():
    input = sys.stdin.readline
    n, k = map(int, input().split())
    p = list(map(lambda x:int(x) - 1, input().split()))
    c = list(map(int, input().split()))
    seen = [0] * n
    accumulate = []
    for i in range(n):
        if seen[i] == 0:
            accumulate.append([c[i]])
            pre = i
            while True:
                if seen[pre] == 1:
                    accumulate[-1].pop()
                    break
                seen[pre] = 1
                now = p[pre]
                pre = now
                accumulate[-1].append(accumulate[-1][-1] + c[now])
    
    ans = -float("INF")
    for lst in accumulate:
        if len(lst) >= k:
            for interval in range(1, k + 1):
                for start in range(len(lst)):
                    if start + interval >= len(lst):
                        num = lst[-1] + lst[(start + interval) % len(lst)] - lst[start]                    
                    else:
                        num = lst[(start + interval)] - lst[start]
                    ans = max(ans, num)
        else:
            if lst[-1] > 0:
                for interval in range(1, len(lst)):
                    for start in range(len(lst)):
                        num = (k - interval) // len(lst) * lst[-1]
                        if start + interval >= len(lst):
                            num += (lst[-1] + lst[(start + interval) % len(lst)] - lst[start])                    
                        else:
                            num += (lst[(start + interval)] - lst[start])
                        ans = max(ans, num)
                """
                for interval in range(1, k - len(lst) * (k // len(lst)) + 1):
                    for start in range(len(lst)):
                        num = (k // len(lst)) * lst[-1]
                        if start + interval >= len(lst):
                            num += (lst[-1] + lst[(start + interval) % len(lst)] - lst[start])
                        else:
                            num += lst[(start + interval)] - lst[start]
                        ans = max(ans, num)
                """
            else:
                for interval in range(1, len(lst)):
                    for start in range(len(lst)):
                        if start + interval >= len(lst):
                            num = lst[-1] + lst[(start + interval) % len(lst)] - lst[start]                    
                        else:
                            num = lst[(start + interval)] - lst[start]
                        ans = max(ans, num)
            
    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()))
m = 0
for i in range(N):
  p = i
  s = 0
  for j in range(K):
    p = P[p]-1
    s = s + C[p]
    if s > m:
      m = s
print(m)

Submission status: Wrong Answer

Solution code:
def main():
    INF = 10 ** 15
    N, K = list(map(int, input().split()))
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    # P のループの最初を検索しておく
    loop_list = list()
    visited = [0] * N
    for i in range(N):
        if visited[i] == 1:
            continue
        start = i
        size = 0
        sum_c = 0
        while visited[i] == 0:
            visited[i] = 1
            size += 1
            sum_c += C[i]
            i = P[i]
        loop_list.append((start, size, sum_c))
    # 各ループごとに考える
    ans = - INF
    for start, size, sum_c in loop_list:
        MAX_LEN = K % size
        if MAX_LEN == 0:
            MAX_LEN = K
        # 2順ループを作っておく
        CUMSUM_CC = [0] * (2 * size)
        cur_index = P[start]
        CUMSUM_CC[0] = C[P[start]]
        for i in range(1, 2 * size):
            cur_index = P[cur_index]
            CUMSUM_CC[i] += C[cur_index] + CUMSUM_CC[i - 1]
        # 最大MAX_LENの連続部分列での最大スコア
        max_score = - INF
        for left in range(2 * size):
            for right in range(left, min(2 * size, left + MAX_LEN)):
                s = CUMSUM_CC[right]
                if left > 0:
                    s -= CUMSUM_CC[left - 1]
                max_score = max(max_score, s)
        if sum_c > 0:
            max_score += sum_c * ((K - 1) // size)
        ans = max(ans, max_score)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import copy
import math
import time
import statistics
import math
import itertools
import bisect
from decimal import *
 
# a = get_int()
def get_int():
    return int(input())
# a = get_string()
def get_string():
    return input()
# a_list = get_int_list()
def get_int_list():
    return [int(x) for x in input().split()]
# a_list = get_string_list():
def get_string_list():
    return input().split()
# a, b = get_int_multi()
def get_int_multi():
    return map(int, input().split())
# a_list = get_string_char_list()
def get_string_char_list():
    return list(str(input()))
# print("{} {}".format(a, b))
# a_list = [0] * a
'''
while (idx < n) and ():
 
    idx += 1
'''
 
def main():
 
    start = time.time()
 
    n, k = get_int_multi()
    p = get_int_list()
    c = get_int_list()
 
    kaisuu = [-1] * n
    score = [0] * n
 
    for i in range(n):
        wk = 0
        ichi = i
        for ii in range(n):
            ichi = p[ichi] -1
            wk += c[ichi]
            if i == ichi:
                kaisuu[i] = ii+1
                score[i] = wk
                break
 
 
    wk = 0
    ans = - 10 ** 20
    for i in range(n):
        ichi = p[i] -1
        wk = c[ichi]
        wk2 = c[ichi]
        idx = 0
        while idx < k-1:
            ichi = p[ichi] -1
            wk += c[ichi]
 
            wk2 = max(wk2, wk)
            idx += 1
 
            #ループするならメモを使って減らす
            if (k - 1 - idx > kaisuu[ichi] * 2) and kaisuu[ichi] > 0:
                roopsuu = ((k - 1 - idx) // kaisuu[ichi]) -1
                wk += roopsuu * score[ichi]
                idx += roopsuu * kaisuu[ichi]
                wk2 = max(wk2, wk)
 
        ans = max(ans , wk2)
    print(ans)
 
 
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

res = 0

if max(C) <= 0:
  res = max(C)
else:

  for i in range(N):
    aoc = 0
    tempRes = 0
    startIndex = i
    countIndex = i

    for j in range(K):
      countIndex = P[countIndex] - 1
      tempRes += C[countIndex]
      if countIndex == startIndex:
        aoc = tempRes
        break
      res = max(res, tempRes)

    if N < K and 0 < aoc:
      for s in range(N):
        tempRes = ((K-1) // (j+1)) * aoc
        startIndex = s
        countIndex = s

        for t in range(K%(j+1)):
          countIndex = P[countIndex] - 1
          tempRes += C[countIndex]
          if countIndex == startIndex:
            break
          res = max(res, tempRes)


print(res)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
mx=-float("inf")


for i in range(n):

  sc=0
  pn=i
  mass=[0]*n
  for j in range(k):
    if mass[pn]!=0:
      lpk=j-mass[pn][0]
      amari=(k-j)%lpk
      lpsc=sc-mass[pn][1]
      for l in range(amari):
        pn=p[pn]-1
        sc+=c[pn]
        mx=max(mx,sc)
      sc+=lpsc*((k-j-amari)//lpk)
      mx=max(mx,sc)
      break
    mass[pn]=[j,sc]
    pn=p[pn]-1
    sc+=c[pn]
    mx=max(mx,sc)
print(mx)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
#入力
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
#入力終了
ans = -1 * (10 ** 10)
for i in range(n): #どのマスで始めるか
    l = [] #ループを見つけるための探索済みリスト
    ind = i #今いる位置
    loop = []
    for j in range(k): #ｋ回繰り返す
        if ind in l: #もしすでにいまいる位置が探索済みだったら
            loop = l[l.index(ind):] #ループをリストに格納
            break
        l.append(ind)
        ind = p[ind]-1
    if len(loop) == 0 or len(loop) >= n: #もしループが無かったら普通にｋ回追う
        cnt = 0
        ind = i
        for j in range(k):
            ind = p[ind]-1
            cnt += c[ind]
            ans = max(ans, cnt)
        print(ans, "no loop")
        continue #この回は終わり
    x = l[:l.index(ind)] #ループまでの移動
    if sum([c[i] for i in loop]) <= 0: #もしループの移動時のポイントの和が０以下だったら
        ans = max(ans, sum(x), sum(x) + max(list(accumulate(loop)))) #ans, xの和, xの和とループの累積和のmax　でmaxを取る
    else:
        ans = max(ans, ((k-len(x))//len(loop))*sum([c[i] for i in loop])+sum([c[i] for i in loop[:(k-len(x))%len(loop)]]))
print(ans)