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:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))

from collections import deque

def bfs(queue, cycle_index, cycle_num):
    cycle = []
    score = 0
    while queue:
        current = queue.popleft()
        cycle_index[current] = cycle_num
        cycle.append(current)
        score += c[current]

        if p[current] not in cycle_index:
            queue.append(p[current])
    return cycle, score

cycle_index = {}
cycle_num = 0
cycles = []
for i in range(1, n + 1):
    if i in cycle_index:
        continue
    queue = deque([i])
    cycle, score = bfs(queue, cycle_index, cycle_num)
    cycles.append((cycle, score))
    cycle_num += 1

ans = None
for i in range(1, n + 1):
    cycle, score = cycles[cycle_index[i]]
    tmp_ans = 0

    cum = [0]
    current = i
    for j in range(1, len(cycle)):
        current = p[current]
        cum.append(cum[-1] + c[current])

    if score > 0:
        q = (k // len(cycle))
        r = k % len(cycle)
        # 一周しない方がいいケースがある
        # FYI: https://atcoder.jp/contests/abc175/submissions/15968040
        tmp_ans = (score * q)
        if r:
            tmp_ans += max(cum[1:r+1])
        #if r == 0:
        #    tmp_ans = max((score * q), (score * (q - 1)) + max(cum[1:]))
        #else:
        #    tmp_ans = (score * q) + max(cum[1:r+1])
    else:
        r = min(k, len(cycle))
        tmp_ans = max(cum[1:r+1])

    if ans is None:
        ans = tmp_ans
    else:
        ans = max(ans, tmp_ans)
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
        tmp = 0

        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K or next == i:
                break
            next = P[next]

        q = K // cnt
        r = K % cnt
        next = P[i]
        tmp *= q
        ans = max(ans, tmp)
        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:
# 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:
                j = i
                max_val = -INF
                iter = -10
                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)
            val += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

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
        tmp = 0

        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if next == i:
                break
            next = P[next]

        q = K // cnt
        r = K % cnt
        next = P[i]
        tmp *= q
        ans = max(ans, tmp)
        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:
# 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:
                j = i
                max_val = -INF
                iter = 1
                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)
            val += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

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
        tmp = 0

        f = False
        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K:
                f = True
                break
            if next == i:
                break
            next = P[next]

        if f or tmp <= 0:
            continue

        q = K // cnt
        r = K % cnt
        next = P[i]
        tmp *= q
        ans = max(ans, tmp)
        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) for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = max(C)
    for i in range(N):
        next = P[i] - 1
        cnt = 0
        tmp = 0

        f = False
        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K:
                f = True
                break
            if next == i:
                break
            next = P[next] - 1

        if f or tmp <= 0:
            continue

        q = K // cnt
        r = K % cnt
        next = P[i] - 1
        tmp *= q
        ans = max(ans, tmp)
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            next = P[next] - 1
            r -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

n,k=nii()
p=lnii()
c=lnii()

ans=-10**18
for i in range(n):
  ini_x=i
  x=i
  t_max=-10**18
  t_ans=[0]
  while True:
    next_x=p[x]-1
    point=c[next_x]
    if t_ans:
      t_ans.append(t_ans[-1]+point)
    t_max=max(t_max,t_ans[-1])
    if next_x==ini_x:
      break
    else:
      x=next_x

  if t_ans[-1]<0:
    ans=max(ans,t_max)
  else:
    num=k//len(t_ans)
    num-=1
    c_ans=t_ans[-1]*num
    c_max=c_ans
    zan=k-(num*len(t_ans))
    s_list=t_ans*2
    for j in range(zan):
      c_ans+=s_list[j]
      c_max=max(c_max,c_ans)
    ans=max(ans,c_max)

print(ans)

Submission status: Wrong Answer

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

x=-10000000000
for i in range(n):
    m=i
    cn=[]
    cnt=0
    l=0
    while l<k:
        m=p[m]-1
        cnt += c[m]
        l+=1
        if i==m:
            l1=k//l
            cnt*=l1
            l=k-k%l
        cn.append(cnt)
        #print(cn,l)
    x=max(x,max(cn))
print(x)

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:
                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)
            val += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
            j = p[j] - 1
        le = len(l)
        su = sum(l)
        l *= 2
        v = (k//le)*su
        ans = max(ans, v)
        for ii in range(le):
            val = 0
            for cnt in range(0, le):
                val += l[ii + cnt]
                if su > 0:
                    v = val + ((k - cnt - 1)//le)*su
                    ans = max(ans, v)
                else:
                    ans = max(ans, val)

print(ans)

Submission status: Wrong Answer

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

x = -10000000000
for i in range(n):
    m = i
    cn = []
    cnt = 0
    l = 0
    while l < k:
        m = p[m]-1
        cnt += c[m]
        l += 1
        if i == m:
            l1 = k // l
            cnt *= l1
            l = k-k % l
        cn.append(cnt)
        #print(cn,l)
    x = max(x, max(cn))
print(x)

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 << 80


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:
                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)
            val += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

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

score = []
for start in range(N):
  position = start
  score_tmp = []
  for k in range(K):
    position = P[position] - 1
    score_tmp.append(C[position])
    if position == start:
      score_round = sum(score_tmp)
      length_round = len(score_tmp)
      nrounds = K // length_round
      mod = k % length_round
      score.append(nrounds * score_round + sum(score_tmp[:mod]))
    else:
      score.append(sum(score_tmp))
print(max(score))

Submission status: Wrong Answer

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

score = []
for start in range(N):
  position = start
  score_tmp = []
  for k in range(K):
    position = P[position] - 1
    score_tmp.append(C[position])
    if position == start:
      score_round = sum(score_tmp)
      length_round = len(score_tmp)
      nrounds = K // length_round
      mod = k % length_round
      score.append(nrounds * score_round + sum(score_tmp[:mod]))
    else:
      score.append(sum(score_tmp))
print(max(score))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = []

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(ans)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        if k%rp==0:
            ans = max(ans, total * (k//rp))
        else:
            s = k%rp
            ans2 = total * (k//rp)
            ans3 = total * (k//rp) + ls[s]
            ans = max(ans, ans2, ans3)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    ls = []

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        ls.append(ans)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        if k%rp==0:
            ans = max(ans, total * (k//rp))
        else:
            s = k%rp
            ans2 = total * (k//rp)
            ans3 = total * (k//rp) + ls[s]
            ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

Solution code:

import collections

n, k = map(int, input().split())

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


def maxv(arr, k):

    n = len(arr)
    sumA = arr[:] + [0]

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

    deque = collections.deque()

    ans = -float('inf')

    for i in range(-1, n):

        while deque and i - deque[0] > k:
            deque.popleft()

        if deque:
            ans = max(ans, sumA[i] - sumA[deque[0]])

        while deque and sumA[ deque[-1] ] > sumA[i]:
            deque.pop()

        deque.append(i)

    return ans



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

    vs = set()

    p = [0] + p
    c = [0] + c

    ans = -float('inf')

    for i in range(1, n + 1):

        if i not in vs:
            
            u = i
            vs.add(u)
            temp = [ c[p[u]] ]
            
            while p[u] not in vs:

                u = p[u]
                vs.add(u)
                temp.append( c[p[u]] )

            sum_temp = sum(temp)
            n_temp = len(temp)

            if sum_temp <= 0:

                total = maxv(temp + temp, min(n_temp, k))

                ans = max(ans, total)

                continue


            temp_k = k % n_temp

            if temp_k == 0:
                temp_k = n_temp
                k -= n_temp

            num_k = k // n_temp

            total1 = maxv( temp + temp, temp_k ) + sum_temp * (num_k)

            ans = max(ans, total1)

            if num_k >= 1:
                temp_k += n_temp
                num_k -= 1

                total2 = maxv( temp + temp, temp_k ) + sum_temp * (num_k)

                ans = max(ans, total2)

            


            # print (temp, ans, '|', temp + temp, temp_k, maxv( temp + temp, temp_k ))

    if ans < 0:
        ans = max(c[1:])

    return ans


ans = sol(n, k, p, c)    

print (ans)

Submission status: Wrong Answer

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

checked = [False] * n

ans = -10 ** 10
for i in range(n):
    if checked[i]:
        continue
    loop = []
    nxt = i
    while not checked[nxt]:
        checked[nxt] = True
        loop.append(c[nxt])
        nxt = p[nxt]

    L = len(loop)

    # loop_cost = 0
    # if sum(loop) > 0 and k > L:
    #     loop_cost = sum(loop) * (k // L)

    for start in range(L):
        s = 0
        dist = 0
        for end in range(start+1, start+L):
            dist += 1
            end %= L
            s += loop[end]
            ans = max(ans, s + max(0, sum(loop) * (k - dist) // L))

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = list(int(x)-1 for x in input().split())
c = list(map(int, input().split()))
score = -10**9
for i in range(n):
  rec = [0]
  here = i
  cnt = 0
  for _ in range(k):
    here = p[here]
    rec.append(rec[-1]+c[here])
    cnt += 1
    if here == i:
      break
  s = max(rec[1:])
  ps = rec[-1]*(k//cnt)+max(rec[0:k%cnt+1])
  s = max(ps,s)
  score = max(s,score)
print(score)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
score_max=max(C)
#スタート地点＝L
for L in range(n):
  score=0
  d=[0]*n
  r=0
  d[L]=1
  #k回移動する
  for _ in range(k):
    r+=1#移動回数をカウント
    L=P[L]-1#移動先の位置
    score+=C[L]
    score_max=max(score,score_max)
    #もしも移動した場所に未到達なら...
    if d[L]==0:
      d[L]=1
    #Cの最小値未満ならスコアは減り続けるのでbreak
    elif score<0:
      break
    else:
      roop=k//r#何回ループできるか
      score*=roop
      score_max=max(score,score_max)

      #ループ後のあまりの移動回数の処理
      h=k%r
      for _ in range(h):
        L=P[L]-1
        score+=C[L]
        score_max=max(score,score_max)
      break
print(score_max)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0

    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        if now == start:
            rp = j
            break
    else:
        continue

    if total <= 0:
        continue
    else:
        if k%rp==0:
            ans = max(ans, total * (k//rp))
        else:
            s = k%rp
            now = start
            total2 = 0
            ans1 = -float('inf')
            for _ in range(1, s + 1):
                now = pn[now] - 1
                total2 += cn[now]
                ans1 = max(ans1, total2)
            ans2 = ans1 + total * (k//rp)
            ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

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

P = [p-1 for p in list(map(int, input().split()))]
C = list(map(int, input().split()))

INF = float('inf')

max_points = []
for i in range(N):
    max_point = -INF
    visit = [0] * N
    visit[i] = 1
    S = [0]
    pos = P[i]
    loop = 0  # P は順列なので、すでにvisitした点に戻ったとき、loopが位数となる
    while True:
        if visit[pos] == 0:
            visit[pos] = 1
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
        else:
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
            break

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop > K:
        max_point = max(S[1:loop+1])
    else:
        if loop_point > 0:
            loop_num = K // loop
            max_point = max(max_point, loop_point * loop_num + max(S[:(K%loop)+1]))
            max_point = max(max_point, loop_point * (loop_num-1) + max(S[1:loop]))
        else:
            max_point = max(S[1:loop+1])

    max_points.append(max_point)

print(max(max_points))

Submission status: Wrong Answer

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

P = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]

maxsum = -10 ** 9

for i in range(N):
    cycle = []
    cycle.append(C[i])
    temp = P[i]-1
    while temp != i:
        cycle.append(C[temp])
        temp = P[temp]-1

    Kdiv = (K-1) // len(cycle)
    Krem = (K-1) % len(cycle) + 1

    cyclesum = sum(cycle)
    psum = 0
    for j in range(Krem):
        psum += cycle[j]
        if not j and cyclesum > 0:
            psum += cyclesum * Kdiv
        maxsum = max(maxsum, psum)

print(maxsum)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# template: v1.3.1

# O(N**2)で実装容易とのこと。純粋Pythonだと間に合わない？

import io
import sys
import math

### DEBUG ###
_DEB = 0   # 1:ON / 0:OFF

_INPUT = """\
2 3
2 1
10 -7
"""
_EXPECTED = """\
8

"""
if _DEB:
    sys.stdin = io.StringIO(_INPUT)
    print("!! Debug Mode !!")

def logd(str):
    if _DEB: print(f"[deb] {str}")


### INPUT ####

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

 
### Solve ####
def solve():
    clst=[]

    pcnt=0
    pi=0
    clst.append([])
    while pcnt < n:
        if p[pi] == -1:
            pi%=n
            if len(clst[-1]) != 0:
                clst.append([])
            pi+=1
            continue

        i=p[pi]-1
        clst[-1].append(c[i])
        p[pi]=-1
        pi=i
        pcnt+=1

    maxs=-float("inf")
    maxsi=-1
    
    
    for i,q in enumerate(clst):
        lenq=len(q)
        minstep=min(lenq,k)
        kqdiv,kqmod=divmod(k,lenq)
        s=sum(q)
        if s <= 0 or lenq < k:
            for qi in range(lenq):
                sbase=0
                for qj in range(k):
                    sbase+=q[(qi+qj)%lenq]
                    maxs=max(maxs,sbase)

        else:
            #Loop価値あり
            skq=(s)*(kqdiv-1)
            for qi in range(lenq):
                sbase=skq
                for ii in range(kqmod):
                    sbase+=q[(qi+ii)%lenq]
                for qj in range(lenq):
                    sbase+=q[(qi+qj)%lenq]
                    maxs=max(maxs,sbase)
                
    ans=maxs
    
    # OUPUT
    ans = str(ans)
    print(ans)
    return ans

### MAIN ###
if __name__ == "__main__":
    ans = solve()

    # Checker
    if _DEB:
        if _EXPECTED.strip() == ans.strip(): print("\n!! Success !!")
        else: print(f"\n!! Failed... !!\nANSWER:   {ans}\nExpected: {_EXPECTED}")