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

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 = -float("inf")
    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
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            r -= 1
            next = P[next] - 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
ppp = list(map(int, input().split()))
ccc = list(map(int, input().split()))
S = set(range(N))
INF = float('inf')
ans = -INF
while S:
    p = list(S)[0]
    D = set()
    a = []
    for _ in range(2 * N):
        p = ppp[p] - 1
        if p in D:
            break
        D.add(p)
        a.append(ccc[p])
    S -= D
    length = len(a)
    MMM = [-INF] * (length + 1)
    for start in range(length):
        acc = 0
        for i in range(length):
            acc += a[(start + i) % length]
            MMM[i+1] = max(MMM[i+1], acc)
    q, r = divmod(K, length)
    tem = max(MMM[-1] * q + max(MMM[:r + 1]), max(MMM))
    ans = max(ans, tem)
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
from math import inf
input=stdin.readline
n,k=map(int,input().split())
arr=[0]+list(map(int,input().split()))
cost=[0]+list(map(int,input().split()))
ma=-inf
for i in range(1,n+1):
    m=1
    cur=arr[i]
    co=cost[cur]
    l=[0,co]
    ma = max(ma, l[-1])
    while(m<k and cur!=i):
        cur=arr[cur]
        co=cost[cur]
        l.append(l[-1]+co)
        m += 1
        ma=max(ma,l[-1])
    if m<=k:
        for j in range(k%m+1):
            ma = max(ma, l[-1] * (k//m) + l[j])
print(ma)

Submission status: Wrong Answer

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

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

ans = -12345678901234567
for st in range(n):
    score = 0
    now = st

    # ループするまで or kまで
    for i in range(1,k+1):
        now = p[now]
        score += c[now]
        ans = max(ans,score)
        if now == st:
            score *= k//i
            i *= k//i
            ans = max(ans,score)
            break

    for j in range(i+1,k+1):
        now = p[now]
        score += c[now]
        ans = max(ans,score)
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()))
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)
        if le == 0:
            continue
        # l *= (k//le + 2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

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

max_points = []
for i in range(N):
    max_point = 0
    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_point > 0:
        max_point += loop_point * (K // loop)
        resi = K % loop
        if resi:
            max_point += max(S[0:resi+1])
    else:
        max_point = max(S[1:loop+1])

    max_points.append(max_point)

print(max(max_points))

Submission status: Wrong Answer

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

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

# 各点からスタートして、
# (1)得点の累計
# (2)ループするまでの各点までの最高点
# (3)ループするのに必要な回数
# (4)ループしきったときの得点変化
# を記録
# 得点変化が正のときは、できるだけループした上で、残り回数を使って(2)より最高点を求める

ans = -(10 ** 10)
for i in range(N): # スタート
  now = i
  point_sum = 0
  best = []
  cnt = 0
  while True:
    cnt += 1
    point_sum += C[now]
    if len(best) == 0:
      best.append(point_sum)
    else:
      best.append(max(best[-1], point_sum))
    now = P[now]
    if now == i:
      break
  point = 0
  if point_sum > 0:
    point += point_sum * (K // cnt)
  rest = K % cnt
  point += best[rest - 1]
  
  if K // cnt > 0: # 最後のループを回りきらないほうが良い場合を考慮
    if best[-1] > point_sum: # 最後のループを回りきるよりも、ループの途中のほうが得点が高い場合
      if point_sum > 0:
        if point < best[-2] + point_sum * (K // cnt - 1):
          point = best[-2] + point_sum * (K // cnt - 1)
      else:
        if point < best[-2]:
          point = best[-2]
  
  if ans < point:
    ans = point
  #print("i",i,"ans",ans)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
ans=-INF
for i in range(n):
    c1=[]
    a=i
    while True:
        a=p[a]-1
        c1.append(c[a])
        if a==i:
            break
    m=-INF
    m1=0
    for j in range(min(k,len(c1))):
        m1+=c1[j]
        m=max(m1,m)
    if k>len(c1):
        t=k//len(c1)
        m1*=t
        m=max(m,m1)
        for j in range(k%len(c1)):
            m1+=c1[j]
            m=max(m,m1)
    ans=max(ans,m)
out(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) for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -float("inf")
    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 next == i:
                break
            if cnt == K:
                f = True
                break
            next = P[next] - 1

        if f or tmp <= 0:
            continue

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


if __name__ == '__main__':
    main()

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_to_positive(A):
    # Aのリストを、正の数が連続している部分に分割する
    # 端っこは繋がっているとみなす
    # 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)
    
    # 端っこが両方正ならリストをつなげる
    if A[0] > 0 and A[-1] > 0:
        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 が最大


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

    positives = split_to_positive(A)
    # もし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)
        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(loop_c)

    # 一周したときのスコア
    sum_1_loop = sum(loop_c)

    if sum_1_loop < 0:
        # 一周したときに負になるようなら、ループしないほうがいい
        return find_max_continued(loop_c, min(K, L))
    else:
        # 一周したときに正になるなら、K回以内にできるだけループしたほうがいい

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

        # ただし、ちょうどx周分だけ移動できる場合、
        # 最後、完全に1周するより負の数を避けて終了したほうがいい場合もあるので、
        # わざと1周分減らしておく
        if K % L == 0:
            n_loops -= 1
        
        score = sum_1_loop * n_loops
        K -= n_loops * L # 残りの移動回数 (<=L)
        # 残りの移動回数でできるだけスコアを稼ぐ
        score += find_max_continued(loop_c, K)
        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(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:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
ans=-INF
for i in range(n):
    c1=[]
    a=i
    while True:
        a=p[a]-1
        c1.append(c[a])
        if a==i:
            break
    m=-INF
    m1=0
    for j in range(min(k,len(c1))):
        m1+=c1[j]
        m=max(m1,m)
    if k>len(c1):
        t=k//len(c1)
        m1=sum(c1)*t
        for j in range(k%len(c1)):
            m1+=c1[j]
            m=max(m,m1)
    ans=max(ans,m)
out(ans)

Submission status: Wrong Answer

Solution code:
mi=-(10**9+1)
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()]

#ループの最大値を求める
mxs=mi
otl=mi
inl=mi
lpc={-1:1}
for i in range(n):
    chkr={i:1}
    wks=0
    nxt=i
    for _ in range(min(n,k)):
        nxt=p[nxt]-1
        if chkr.get(nxt):
            wks+=c[nxt]
            otl=max(otl,wks)
            break
        chkr[nxt]=1
        wks+=c[nxt]
        otl=max(otl,wks)
    if mxs<wks:
        mxs=wks
        lpc=chkr
dv=k//len(lpc)
rst=k%len(lpc)

mxr=0
for i in lpc.keys():
    if i==-1:break
    wks=0
    nxt=i
    for _ in range(rst):
        nxt=p[nxt]-1
        wks+=c[nxt]
        mxr=max(mxr,wks)

ans=max(dv*mxs+mxr,otl)
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) for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -float("inf")
    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 next == i:
                break
            if cnt == K or next == i:
                f = True
                break
            next = P[next] - 1

        if f or tmp <= 0:
            continue

        q = K // cnt
        r = K % cnt
        next = P[i] - 1
        tmp *= q
        while r > 0:
            tmp += C[next]
            ans = max(ans, tmp)
            r -= 1
            next = P[next] - 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()))

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

ans = -12345678901234567
for st in range(n):
    score = 0
    now = st

    # ループするまで or kまで
    for i in range(1,k+1):
        now = p[now]
        score += c[now]
        ans = max(ans,score)
        if now == st:
            score *= k//i
            i *= k//i
            break

    if i == k:continue
    if score <= 0:continue
    for j in range(i+1,k+1):
        now = p[now]
        score += c[now]
        ans = max(ans,score)
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) for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -float("inf")
    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 next == i:
                break
            if cnt == K or next == i:
                f = True
                break
            next = P[next] - 1

        if f or tmp <= 0:
            continue

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
ans=-INF
for i in range(n):
    c1=[c[i]]
    a=i
    while True:
        a=p[a]-1
        if a==i:
            break
        else:
            c1.append(c[a])
    m=-INF
    m1=0
    for j in range(0,min(k,len(c1))):
        m1+=c1[j]
        m=max(m1,m)
    if k>len(c1):
        t=k//len(c1)
        m1=sum(c1)*t
        for j in range(k%len(c1)):
            m1+=c1[j]
            m=max(m,m1)
    ans=max(ans,m)
out(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

# https://note.nkmk.me/python-union-find/

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


def main():
    n, k = ns()
    p = na1()
    c = na()

    uf = UnionFind(n)
    for i, pi in enumerate(p):
        uf.union(i, pi)

    cycledist = [[-INF for _ in range(2)] for __ in range(n)]
    for lis in uf.all_group_members().values():
        tmp = 0
        l = len(lis)
        for idx in lis:
            tmp += c[idx]
            cycledist[idx][1] = l
        for idx in lis:
            cycledist[idx][0] = tmp

    ans = -INF

    for i in range(n):
        t = cycledist[i][0] * (k // cycledist[i][1])
        if t >= 0:
            ans = max(ans, t)
        tmp_ans = max(0, t)

        tmp = 0
        idx = i
        for j in range(k % cycledist[i][1]):
            tmp += c[p[idx]]
            idx = p[idx]
            ans = max(ans, tmp_ans + tmp)

        tmp = 0
        idx = i
        for j in range(min(k, n)):
            tmp += c[p[idx]]
            idx = p[idx]
            ans = max(ans, tmp)

    print(ans)


if __name__ == '__main__':
    main()

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_to_positive(A):
    # Aのリストを、正の数が連続している部分に分割する
    # 端っこは繋がっているとみなす
    # 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)
    
    # 端っこが両方正ならリストをつなげる
    if A[0] > 0 and A[-1] > 0:
        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 が最大


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

    positives = split_to_positive(A)
    # もし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)
        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(loop_c)

    # 一周したときのスコア
    sum_1_loop = sum(loop_c)

    if sum_1_loop < 0:
        # 一周したときに負になるようなら、ループしないほうがいい
        return find_max_continued(loop_c, min(K, L))
    else:
        # 一周したときに正になるなら、K回以内にできるだけループしたほうがいい

        # ただし、ちょうど一周分だけ移動できる (K==L) 場合、
        # 完全に1周するより負の数を避けて終了したほうがいい場合もあるので、
        # 完全に1周しないパターンも含めて探索する
        if K == L:
            return find_max_continued(loop_c, K)
        else:
            # それ以外の場合、できるだけループさせる
            n_loops = K // L # ループできる回数
            score = sum_1_loop * n_loops

            # ループした後の残りの K % L 回の移動でできるだけスコアを稼ぐ
            score += find_max_continued(loop_c, K % L)
            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(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:
#!/usr/bin/env python3

import sys
import pprint

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, debug):
		self.debug = debug
	def print(self, *args):
		if self.debug:
			pprint.pprint(args)

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


def main():
	log = Logger(0)
	n, k = map(int, sys.stdin.readline().split())
	p = list(map(int, sys.stdin.readline().split()))
	c = list(map(int, sys.stdin.readline().split()))
	uf = UnionFind(n)
	max_score = -float("inf")
	for i in range(n):
		uf.union(p[i] - 1, i)
	log.print(uf.all_group_members())
	for i in range(n):
		cnt = k
		score = 0
		loop = uf.members(p[i]-1)
		log.print(loop)
		if k >= len(loop):
			loopsum = 0
			here = i
			for j in range(len(loop)):
				here = p[here] - 1
				loopsum += c[here]
			assert i == here
			if loopsum > 0:
				score += loopsum * (k // len(loop))
				cnt %= len(loop)
		tmp_max_score = -float("inf")
		here = i
		for j in range(len(loop) - 1):
			if j >= cnt:
				break
			here = p[here] - 1
			score += c[here]
			log.print(here, score)
			tmp_max_score = max(tmp_max_score, score)
		max_score = max(tmp_max_score, max_score)
	print(max_score)


# 5 -100 99 -3 5 -100


main()

Submission status: Wrong Answer

Solution code:
mi=-(10**9+1)
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()]

#ループの最大値を求める
mxs=mi
otl=mi
lpc={-1:1}
for i in range(n):
    chkr={i:1}
    wks=0
    nxt=i
    for _ in range(n):
        nxt=p[nxt]-1
        if chkr.get(nxt):
            wks+=c[nxt]
            otl=max(otl,wks)
            break
        chkr[nxt]=1
        wks+=c[nxt]
        otl=max(otl,wks)
    if mxs<wks:
        mxs=wks
        lpc=chkr
dv=k//len(lpc)
rst=k%len(lpc)

mxr=0
for i in lpc.keys():
    if i==-1:break
    wks=0
    nxt=i
    for _ in range(rst):
        nxt=p[nxt]-1
        wks+=c[nxt]
        mxr=max(mxr,wks)

ans=max(dv*mxs+mxr,otl)
print(ans)

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()))
was = [False]*n
sums = []
for i in range(n):
    if not was[i]:
        iWas = [False]*n
        pos = i
        sumn = []
        while not iWas[pos]:
            sumn += [c[pos]]
            iWas[pos] = True
            was[pos] = True
            pos = p[pos]-1
        sumn = sumn[:-1]
        sums.append(sumn)
m = -9999999999999999999999999
for i in range(len(sums)):
    totS = sum(sums[i])
    l = len(sums[i])
    for g in range(len(sums[i])):
        arr = []
        s = 0
        for j in range(l):
            s+=sums[i][(g+j)%l]
            arr.append(s)

        if totS > 1:
            add = max(arr[:k%l]+[-99999999999999999999])
            if add != -99999999999999999999:
                if k//l:
                    m = max(m,totS*(k//l)+add)
                else:
                    m = max(m,add)
            else:
                m = max(m,totS*(k//l))

        else:

            m = max(m, max(arr[:min(l,k)]))
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()))
ans = -9999999
z = 0
l = 0
lv = 0

for i in range(n):
    v = 0
    tmp = i
    cl =[]
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if tmp in cl:
                if lv < v - c[tmp]:
                    l = len(cl)
                    lv = v - c[tmp]
                break
            cl.append(tmp)           

    #print(cl)

if k >= n and l > 0:
    z = lv * int(k/l)
    k = k%l
elif k >= n and l == 0 and sum(c)>0:
    z = sum(c) * int(k/n)
    k = k%n

for i in range(n):
    v = 0
    tmp = i
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ans < v:
                ans = v
            #print(tmp,v,ans) 

if z > 0:
    print(ans+z)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
ans=-INF
flag=0
for i in range(n):
    q=[i]
    c1=[c[i]]
    a=i
    while True:
        a=p[a]-1
        if a==i:
            break
        else:
            q.append(a)
            c1.append(c[a])
    m=-INF
    m1=0
    for j in range(1,min(k+1,len(q))):
        m1+=c1[j]
        m=max(m1,m)
    if k+1>len(q):
        t=k//len(q)
        m1=sum(c1)*t
        for j in range(1,k%len(q)+1):
            m1+=c1[j]
            m=max(m,m1)
    ans=max(ans,m)
out(ans)