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:
"""
1. マス同士は有効グラフの一本道になっている。で、必ずどこかでループが発生している。

2. 各点から各点に移動する場合のスコアの合計とステップ数(ループ内の場合は一周以内のもの)を前処理(dfs)で求めておく。dp[i][j] => iからjまでのスコアとステップ数

3. K > N の場合、ループを通るとスコアがマイナスになるなら（dp[i][i]がマイナスになるようなiが存在するなら）、ループを一周しない方がよい。
ループを通るとスコアがプラスになるなら、

各iに対して地点iからスタートする場合というのをシミュレートすると実装が楽そう。
K <= Nの場合はi番目からスタートして、dfsでstep数がKに到達するまで進み続けて、スコアの最大値を図る。
Kが大きい場合は、dfsで道をたどっていってループを検出したら、その時点でループスコアがマイナスかプラスかを判断して、マイナスなら終了。
プラスならループスコア*(K//ループstep)を加算してできる限りKを減らす。そこからstep数がKに到達するまでdfsで道をたどっていって最大値を求める。
各スタート地点ごとにO(N)で処理可能なので、全体ではO(N^2)で処理できる
"""
import sys
sys.setrecursionlimit(10000)
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

def dfs(cur,score,scores,step,steps):
    if scores[cur] == None:
        scores[cur] = score
        steps[cur] = step
    else:
        if scores[cur] > score:
            return
        else:
            loopStep = step - steps[cur]
            loopScore = score - scores[cur]

            scores[cur] = score
            steps[cur] = step

            scores[cur] += ((K - steps[cur])//loopStep)*loopScore
            steps[cur] += ((K - steps[cur])//loopStep)*loopStep
            
    if steps[cur] < K:
        p = P[cur-1]
        c = C[p-1]
        dfs(p,scores[cur]+c,scores,steps[cur]+1,steps)
    else:
        return

ans = -float("INF")
for i in range(1,N+1):
    scores = [None]*(N+1)
    steps = [None]*(N+1)
    dfs(i,0,scores,0,steps)
    for j in range(N+1):
        if scores[j] != None and steps[j] != 0:
            ans = max(ans,scores[j])
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n, k = [int(e) for e in input().split()]
    P = [int(e) for e in input().split()]
    C = [int(e) for e in input().split()]

    A = []
    for i in range(1, n + 1):
        score = 0
        max_score = -(10 ** 18)
        move_count = 0
        di = i
        S = set()
        while True:
            di = P[di - 1]
            if di in S or move_count == k:
                break

            score += C[di - 1]
            if max_score < score:
                max_score = score

            move_count += 1
            S.add(di)

        len_s = len(S)
        if score > 0 and move_count < k:
            score = score * (k // len_s)
            max_score = score
            di = i
            for si in range(k % len_s):
                di = P[di - 1]
                score += C[di - 1]
                if max_score < score:
                    max_score = score

        A.append(max_score)

    print(max(A))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ans = -float('inf')
v = [False for _ in range(n)]
for i in range(n):
  j = i
  if v[j]:
    continue
  r = []
  while(v[j] == False):
    r.append(j)
    v[j] = True
    j = p[j]
  cr = []
  for ri in r:
    cr.append(c[ri])
  k1 = k%len(cr)
  k2 = k//len(cr)
  if k1 == 0:
    k1 = len(cr)
    k2 = max(k2-1,0)
  cr2 = cr+cr
  #print(k1,k2,cr)
  now = -float('inf')
  csum = [0 for _ in range(len(cr2)+1)]
  for i0 in range(len(cr2)):
    csum[i0+1] = csum[i0]+cr2[i0]
  for i0 in range(len(cr)):
    for i1 in range(k1):
      now = max(csum[i0+i1+1]-csum[i0],now)
  if sum(cr) > 0:
    now += sum(cr)*k2
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import accumulate
import sys
sys.setrecursionlimit(1000000)

def func(x):
    return x - 1

def main():
    N, K = map(int, input().split())
    P = list(map(func,map(int, input().split())))
    C = list(map(int, input().split()))
    flag = False
    for i in range(N):
        if C[i] >= 0:
            flag = True
    if not flag:
        print(max(C))
        exit()
    cand = []
    visited = [False] * N
    for i in range(N):
        if not visited[i]:
            Q = deque([i])
            tmp = []
            while Q:
                x = Q.pop()
                visited[x] = True
                v = P[x]
                if not visited[v]:
                    Q.append(v)
                    tmp.append(C[v])
            tmp.append(C[v])
            cand.append(tmp+tmp)
    ans = 0
    for item in cand:
        tmp_score = 0
        L = len(item) // 2
        #S = sum(item) // 2
        #print(item, sum(item[0:L]))
        S = sum(item[0:L])
        D = [0] + list(accumulate(item))
        if K <= L:
            cnt = K
            for l in range(L):
                for j in range(cnt):
                    tmp = D[l+j+1] - D[l] 
                    tmp_score = max(tmp_score, tmp)
            ans = max(ans, tmp_score)
        else:
            if S > 0:
                cnt = K % L
                for l in range(L):
                    for j in range(cnt):
                        tmp = D[l+j+1] - D[l]
                        tmp_score = max(tmp_score, tmp)
                tmp_score += (K // L) * S
                ans = max(ans, tmp_score)
            else:
                cnt = min(K,L+1)
                for l in range(L):
                    for j in range(cnt):
                        tmp = D[l+j+1] - D[l] 
                        tmp_score = max(tmp_score, tmp)
                ans = max(ans, tmp_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 = tuple(map(int,input().split()))
for i in range(n):
  p[i] -= 1

ans = -10**9
v = [False for _ in range(n)]
for i in range(n):
  j = i
  if v[j]:
    continue
  r = []
  while(v[j] == False):
    r.append(j)
    v[j] = True
    j = p[j]
  cr = []
  for ri in r:
    cr.append(c[ri])
  k1 = k%len(cr)
  if k1 == 0:
    k1 = len(cr)
  k2 = k//len(cr)
  cr2 = cr+cr
  #print(k1,k2,cr)
  now = -float('inf')
  csum = [0 for _ in range(len(cr2)+1)]
  for i0 in range(len(cr2)):
    csum[i0+1] = csum[i0]+cr2[i0]
  for i0 in range(len(cr)):
    for i1 in range(k1):
      now = max(csum[i0+i1+1]-csum[i0],now)
  if sum(cr) > 0:
    now += sum(cr)*k2
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import accumulate
import sys
sys.setrecursionlimit(1000000)

def func(x):
    return x - 1

def main():
    N, K = map(int, input().split())
    P = list(map(func,map(int, input().split())))
    C = list(map(int, input().split()))
    flag = False
    for i in range(N):
        if C[i] >= 0:
            flag = True
    if not flag:
        print(max(C))
        exit()
    cand = []
    visited = [False] * N
    for i in range(N):
        if not visited[i]:
            Q = deque([i])
            tmp = []
            while Q:
                x = Q.pop()
                visited[x] = True
                v = P[x]
                if not visited[v]:
                    Q.append(v)
                    tmp.append(C[v])
            tmp.append(C[v])
            cand.append(tmp+tmp)
    ans = 0
    for item in cand:
        tmp_score = 0
        S = sum(item) // 2
        L = len(item) // 2
        D = [0] + list(accumulate(item))
        if K <= L:
            cnt = K
            for l in range(L):
                for j in range(cnt):
                    tmp = D[l+j+1] - D[l] 
                    tmp_score = max(tmp_score, tmp)
            ans = max(ans, tmp_score)
        else:
            if S > 0:
                cnt = K % L
                for l in range(L):
                    for j in range(cnt):
                        tmp = D[l+j+1] - D[l]
                        tmp_score = max(tmp_score, tmp)
                tmp_score += (K // L) * S
                ans = max(ans, tmp_score)
            else:
                cnt = min(K,L+1)
                for l in range(L):
                    for j in range(cnt):
                        tmp = D[l+j+1] - D[l] 
                        tmp_score = max(tmp_score, tmp)
                ans = max(ans, tmp_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 = tuple(map(int,input().split()))
for i in range(n):
  p[i] -= 1

ans = -10**9
v = [False for _ in range(n)]
for i in range(n):
  j = i
  if v[j]:
    continue
  r = []
  while(v[j] == False):
    r.append(j)
    v[j] = True
    j = p[j]
  cr = []
  for ri in r:
    cr.append(c[ri])
  k1 = k%len(cr)
  if k1 == 0:
    k1 = len(cr)
  k2 = k//len(cr)
  cr2 = cr+cr
  #print(k1,k2,cr)
  now = -float('inf')
  for i0 in range(len(cr)):
    for i1 in range(k1):
      now = max(sum(cr2[i0:i0+i1+1]),now)
  if sum(cr) > 0:
    now += sum(cr)*k2
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n, k = [int(e) for e in input().split()]
    P = [int(e) for e in input().split()]
    C = [int(e) for e in input().split()]

    A = []
    for i in range(1, n + 1):
        score = 0
        max_score = -(10 ** 18)
        move_count = 0
        di = i
        S = set()
        while True:
            di = P[di - 1]
            if di in S or move_count == k:
                break

            score += C[di - 1]
            if max_score < score:
                max_score = score

            move_count += 1
            S.add(di)

        len_s = len(S)
        if score > 0 and move_count < k:
            a = score * (k // len_s)
            di = i
            for si in range(k % len_s):
                di = P[di - 1]
                a += C[di - 1]

            A.append(a)

        else:
            A.append(max_score)

    print(max(A))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ans = -10**9
v = [False for _ in range(n)]
for i in range(n):
  j = i
  if v[j]:
    continue
  r = []
  while(v[j] == False):
    r.append(j)
    v[j] = True
    j = p[j]
  cr = []
  for ri in r:
    cr.append(c[ri])
  k1 = k%len(cr)
  if k1 == 0:
    k1 = len(cr)
  k2 = k//len(cr)
  cr2 = cr+cr
  #print(k1,k2,cr)
  now = -float('inf')
  for i in range(len(cr)):
    for j in range(k1):
      now = max(sum(cr2[i:i+j+1]),now)
  if sum(cr) > 0:
    now += sum(cr)*k2
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
N,K = map(int,input().split())
P = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]

# 順列のループを見つける → 各ループの最大値(周回できる? or 周回できない?)
used = []
sets = []
nowP = []
j = 0

for i in range(len(P)) : # ~5000
    start_position = i
    j = start_position
    sets_buf = []
    while True : # ~ 5000
        if P[j] in used :
            break
        used.append(P[j])
        sets_buf.append(P[j])
        j = P[j] - 1
    if len(sets_buf) >= 1 :
        sets.append(sets_buf)

buf = []
for j in range(len(sets)) : # ~5000
    now_C = [C[k-1] for k in sets[j]]
    sm = sum(now_C) # ~5000

    if K > len(sets[j]) :
        amari = K % len(sets[j])
        if amari == 0 :
            amari = len(sets[j])
    else :
        amari = K

    amaribuf = []
    for i in range(len(now_C)) : #~5000
        C_usiro = now_C[:i]
        per_C_set = now_C[i:]
        per_C_set.extend(C_usiro)
        thobuf = [0]
        for k in range(1,amari+1) : #~5000
            thobuf.append(thobuf[k-1] + per_C_set[k-1])
        del thobuf[0]
        amaribuf.append(max(thobuf)) # ~5000
    amaritekinayatu = max(amaribuf)

    if sm >= 0 :
        buf.append((K // len(sets[j])) * sm + amaritekinayatu)
    else :
        buf.append(amaritekinayatu)
print(max(buf))
    

#    amari = K % len(sets[j])
#    amaribuf = []
#    for i in range(len(now_C)) :
#        C_usiro = now_C[:i]
#        per_C_set = now_C[i:]
#        per_C_set.extend(C_usiro)
#        print(per_C_set)
#        print(amari)
#        thobuf = []
#        for k in range(len(per_C_set)) :
#            thobuf.append(sum(per_C_set[:k]))
#        amaribuf.append(max(thobuf))
#    amaritekinayatu = max(amaribuf)
#    print("amaritekina",amaritekinayatu)
#    if sm >= 0 :
#        print("1")
#        buf.append((K // len(sets[j])) * sm + amaritekinayatu)
#    else :
#        print("2")
#        buf.append(amaritekinayatu)
#print("buf",buf)
#print(max(buf))





#score = []
#for i in range(len(sets)) : # i番目の集合
#    now_set = sets[i]
#    buf = [] # 現在のループネットワークにおけるスコアを格納
#    for j in range(len(now_set)) : # ~5000 i番目の集合の中のj要素目をnow_setのスタートとする
#        P_usiro = now_set[:j]
#        per_now_set = now_set[j:]
#        per_now_set.extend(P_usiro) # now_setのj番目(0~len(now_set))をスタートとするlen(now_set)の順列の配列生成
#        now_C = [C[k-1] for k in per_now_set] # 現在のjからの得点配列
#        value_buf = [0]
#
#        if (len(now_set) < K) and sum(now_C) >= 0 : # 例外
#            for k in range(K % len(now_set)) : # 余りの分の中における最大を探す ~?
#                value_buf.append(value_buf[k]+now_C[k])
#            del value_buf[0]
#            buf.append((K // len(now_set)) * sum(now_C) + max(value_buf))
#            continue
#
#        if (len(now_set) < K) :
#            for k in range(len(now_set)) : 
#                value_buf.append(value_buf[k]+now_C[k])
#            del value_buf[0]
#            buf.append(max(value_buf))
#        else :
#            for k in range(K) :
#                value_buf.append(value_buf[k]+now_C[k])
#            del value_buf[0]
#            buf.append(max(value_buf))
#    score.append(max(buf))

#print(max(score))

Submission status: Wrong Answer

Solution code:
import numpy as np
N,K = map(int,input().split())
P = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]

# 順列のループを見つける → 各ループの最大値(周回できる? or 周回できない?)
used = []
sets = []
nowP = []
j = 0

for i in range(len(P)) : # ~5000
    start_position = i
    j = start_position
    sets_buf = []
    while True : # ~ 5000
        if P[j] in used :
            break
        used.append(P[j])
        sets_buf.append(P[j])
        j = P[j] - 1
    if len(sets_buf) >= 1 :
        sets.append(sets_buf)

buf = []
for j in range(len(sets)) :
    now_C = [C[k-1] for k in sets[j]]
    sm = sum(now_C)

    if K > len(sets[j]) :
        amari = K % len(sets[j])
        if amari == 0 :
            amari = len(sets[j])
    else :
        amari = K

    amaribuf = []
    for i in range(len(now_C)) :
        C_usiro = now_C[:i]
        per_C_set = now_C[i:]
        per_C_set.extend(C_usiro)
        thobuf = []
        for k in range(1,amari+1) :
            thobuf.append(sum(per_C_set[:k]))
        amaribuf.append(max(thobuf))
    amaritekinayatu = max(amaribuf)

    if sm >= 0 :
        buf.append((K // len(sets[j])) * sm + amaritekinayatu)
    else :
        buf.append(amaritekinayatu)
print(max(buf))
    

#    amari = K % len(sets[j])
#    amaribuf = []
#    for i in range(len(now_C)) :
#        C_usiro = now_C[:i]
#        per_C_set = now_C[i:]
#        per_C_set.extend(C_usiro)
#        print(per_C_set)
#        print(amari)
#        thobuf = []
#        for k in range(len(per_C_set)) :
#            thobuf.append(sum(per_C_set[:k]))
#        amaribuf.append(max(thobuf))
#    amaritekinayatu = max(amaribuf)
#    print("amaritekina",amaritekinayatu)
#    if sm >= 0 :
#        print("1")
#        buf.append((K // len(sets[j])) * sm + amaritekinayatu)
#    else :
#        print("2")
#        buf.append(amaritekinayatu)
#print("buf",buf)
#print(max(buf))





#score = []
#for i in range(len(sets)) : # i番目の集合
#    now_set = sets[i]
#    buf = [] # 現在のループネットワークにおけるスコアを格納
#    for j in range(len(now_set)) : # ~5000 i番目の集合の中のj要素目をnow_setのスタートとする
#        P_usiro = now_set[:j]
#        per_now_set = now_set[j:]
#        per_now_set.extend(P_usiro) # now_setのj番目(0~len(now_set))をスタートとするlen(now_set)の順列の配列生成
#        now_C = [C[k-1] for k in per_now_set] # 現在のjからの得点配列
#        value_buf = [0]
#
#        if (len(now_set) < K) and sum(now_C) >= 0 : # 例外
#            for k in range(K % len(now_set)) : # 余りの分の中における最大を探す ~?
#                value_buf.append(value_buf[k]+now_C[k])
#            del value_buf[0]
#            buf.append((K // len(now_set)) * sum(now_C) + max(value_buf))
#            continue
#
#        if (len(now_set) < K) :
#            for k in range(len(now_set)) : 
#                value_buf.append(value_buf[k]+now_C[k])
#            del value_buf[0]
#            buf.append(max(value_buf))
#        else :
#            for k in range(K) :
#                value_buf.append(value_buf[k]+now_C[k])
#            del value_buf[0]
#            buf.append(max(value_buf))
#    score.append(max(buf))

#print(max(score))

Submission status: Wrong Answer

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
from collections import defaultdict as dd
n, k = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))

def max_val(start, k):
    visited = set([start])
    node = start
    next_node = P[node]
    node_his = []
    add_point_his = []
    total_point_his = []
    total_point = 0
    #before_roop
    while next_node not in visited:
        node = next_node
        next_node = P[node]
        node_his.append(node)
        add_point = C[node]
        total_point += add_point
        add_point_his.append(add_point)
        total_point_his.append(total_point)
        visited.add(node)
    else:
        node = next_node
        node_his.append(node)
        add_point = C[node]
        total_point += add_point
        add_point_his.append(add_point)
        total_point_his.append(total_point)
        visited.add(node)
    #print(visited, node_his, add_point_his, total_point_his)
    loop_head = P[node]
    loop_idx = node_his.index(loop_head)
    loop = node_his[loop_idx:]
    add_point_in_loop = add_point_his[loop_idx:]
    total_point_in_loop = list(accumulate(add_point_in_loop))
    #print(loop_idx, loop_idx, loop, add_point_in_loop)
    point_per_roop = sum(add_point_in_loop)
    loop_len = len(loop)
    #print(point_per_roop, loop_len)
    if k <= len(node_his):
        return max(total_point_his[:k])
    else:
        if point_per_roop > 0:
            point = total_point_his[-1]
            k -= len(node_his)
            loop_time = k // loop_len
            rest = k % loop_len
            return max(point + point_per_roop * loop_time + max(total_point_in_loop[:rest] + [0]), max(total_point_his))
        else:
            return max(total_point_his)
#print(max_val(1, k))

max_score = -float("inf")
for i in range(1, n+1):
    max_score = max(max_val(i, k), max_score)
print(max_score)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
n, k = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))

def max_val(start, k):
    visited = set([start])
    node = start
    next_node = P[node]
    node_his = []
    add_point_his = []
    total_point_his = []
    total_point = 0
    #before_roop
    while next_node not in visited:
        node = next_node
        next_node = P[node]
        node_his.append(node)
        add_point = C[node]
        total_point += add_point
        add_point_his.append(add_point)
        total_point_his.append(total_point)
        visited.add(node)
    else:
        node = next_node
        node_his.append(node)
        add_point = C[node]
        total_point += add_point
        add_point_his.append(add_point)
        total_point_his.append(total_point)
        visited.add(node)
    #print(visited, node_his, add_point_his, total_point_his)
    loop_head = P[node]
    loop_idx = node_his.index(loop_head)
    loop = node_his[loop_idx:]
    add_point_in_loop = add_point_his[loop_idx:]
    #print(loop_idx, loop_idx, loop, add_point_in_loop)
    point_per_roop = sum(add_point_in_loop)
    loop_len = len(loop)
    #print(point_per_roop, loop_len)
    if k <= len(node_his):
        return max(total_point_his[:k])
    else:
        if point_per_roop > 0:
            point = total_point_his[-1]
            k -= len(node_his)
            loop_time = k // loop_len
            rest = k % loop_len
            return max(point + point_per_roop * loop_time + max(total_point_his[:rest] + [0]), max(total_point_his))
        else:
            return max(total_point_his)
#print(max_val(1, k))

max_score = -float("inf")
for i in range(1, n+1):
    max_score = max(max_val(i, k), max_score)
print(max_score)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
n, k = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))

def max_val(start, k):
    visited = set([start])
    node = start
    next_node = P[node]
    node_his = []
    add_point_his = []
    total_point_his = []
    total_point = 0
    #before_roop
    while next_node not in visited:
        node = next_node
        next_node = P[node]
        node_his.append(node)
        add_point = C[node]
        total_point += add_point
        add_point_his.append(add_point)
        total_point_his.append(total_point)
        visited.add(node)
    else:
        node = next_node
        node_his.append(node)
        add_point = C[node]
        total_point += add_point
        add_point_his.append(add_point)
        total_point_his.append(total_point)
        visited.add(node)
    #print(visited, node_his, add_point_his, total_point_his)
    loop_head = P[node]
    loop_idx = node_his.index(loop_head)
    loop = node_his[loop_idx:]
    add_point_in_loop = add_point_his[loop_idx:]
    #print(loop_idx, loop_idx, loop, add_point_in_loop)
    point_per_roop = sum(add_point_in_loop)
    loop_len = len(loop)
    #print(point_per_roop, loop_len)
    if k <= len(node_his):
        return max(total_point_his[:k])
    else:
        if point_per_roop > 0:
            point = total_point_his[-1]
            k -= len(node_his)
            loop_time = k // loop_len
            rest = k % loop_len
            return point + point_per_roop * loop_time + max(total_point_his[:rest] + [0])
        else:
            return max(total_point_his[:k])
#print(max_val(1, k))

max_score = -float("inf")
for i in range(1, n+1):
    max_score = max(max_val(i, k), max_score)
print(max_score)

Submission status: Wrong Answer

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

# Pが1,2,...Nの順列なので、1,2,3,4,5,3,4,5,...のような途中からのループは起こり得ない
# スタートの点数が入らないのは面倒なので、スタートの次のマスから考える

ans = -(10**9)
# どのマスから始めるか
for i in range(1, N + 1):
    # ループに入るまでの経路(iの次から)
    route = []
    visit = [False] * (N + 1)
    visit[i] = True
    now = i
    while True:
        next = P[now]
        # まだ訪れていないマスの場合
        if visit[next] == False:
            visit[next] = True
            route.append(next)
            now = next
        # 既に訪れたマスの場合
        else:
            break
    # iに戻ってくる
    route.append(i)

    cumsum = [0]
    for x in route:
        cumsum.append(cumsum[-1] + C[x])
    # print(cumsum)

    # ループするほど損する場合
    if cumsum[-1] <= 0:
        if K >= len(route):
            tmp = max(cumsum[1:])
        else:
            tmp = max(cumsum[1:K + 1])
        ans = max(ans, tmp)
    # ループするほど得する場合
    else:
        loop_size = len(route)
        loop_cnt = K // loop_size
        spare_cnt = K % loop_size
        if spare_cnt == 0:
            tmp = cumsum[-1] * loop_cnt
        else:
            tmp = cumsum[-1] * loop_cnt + max(cumsum[1:spare_cnt + 1])
        ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

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

# Pが1,2,...Nの順列なので、1,2,3,4,5,3,4,5,...のような途中からのループは起こり得ない
# スタートの点数が入らないのは面倒なので、スタートの次のマスから考える

ans = -(10**9)
# どのマスから始めるか
for i in range(1, N + 1):
    # ループに入るまでの経路(iの次から)
    route = []
    visit = [False] * (N + 1)
    visit[i] = True
    now = i
    while True:
        next = P[now]
        # まだ訪れていないマスの場合
        if visit[next] == False:
            visit[next] = True
            route.append(next)
            now = next
        # 既に訪れたマスの場合
        else:
            break
    # iに戻ってくる
    route.append(i)

    cumsum = [0]
    for x in route:
        cumsum.append(cumsum[-1] + C[x])
    # print(cumsum)

    # ループするほど損する場合
    if cumsum[-1] <= 0:
        tmp = max(cumsum[1:])
        ans = max(ans, tmp)
    # ループするほど得する場合
    else:
        loop_size = len(route)
        loop_cnt = K // loop_size
        spare_cnt = K % loop_size
        if spare_cnt == 0:
            tmp = cumsum[-1] * loop_cnt
        else:
            tmp = cumsum[-1] * loop_cnt + max(cumsum[1:spare_cnt + 1])
        ans = max(ans, tmp)

print(ans)