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:
class UnionFind():
    def __init__(self,n):
        self.n=n
        self.root=[-1]*n
        self.rank=[-1]*n

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

    def Unite(self,x,y):
        x=self.Find_Root(x)
        y=self.Find_Root(y)

        if x==y:return
        elif self.rank[x]>self.rank[y]:
            self.root[x] +=self.root[y]
            self.root[y]=x
        else:
            self.root[y] +=self.root[x]
            self.root[x]=y
            if self.rank[x]==self.rank[y]:
                self.rank[y] +=1

    def isSameGroup(self,x,y):
        return self.Find_Root(x)==self.Find_Root(y)

    def size(self,x):
        return -self.root[self.Find_Root(x)]

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

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

    def group_members(self):
        return {i:self.members(i) for i in self.roots()}

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


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

UnionFind=UnionFind(N+1)
for i in range(N):
    UnionFind.Unite(i+1,P[i])

D=UnionFind.group_members()
E=[]
for i in D:
    A,length=D[i],len(D[i])
    if A[0]==0:continue
    index,F=A[0]-1,[]
    while len(F)!=length:
        index=P[index]-1
        F.append(C[index])
    E.append(F)

ans=-float("inf")
for A in E:
    length=len(A)
    if sum(A)<0:
        A=A*2
        for i in range(length):
            point=0
            for j in range(min(K,length)):
                point +=A[i+j]
                ans=max(ans,point)
    else:
        div,mod=divmod(K,length)
        base=div*sum(A)
        A=A*2
        for i in range(length):
            point=0
            for j in range(max(1,mod)):
                point +=A[i+j]
                ans=max(ans,base+point)
print(ans)

Submission status: Wrong Answer

Solution code:
class UnionFind():
    def __init__(self,n):
        self.n=n
        self.root=[-1]*n
        self.rank=[-1]*n

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

    def Unite(self,x,y):
        x=self.Find_Root(x)
        y=self.Find_Root(y)

        if x==y:return
        elif self.rank[x]>self.rank[y]:
            self.root[x] +=self.root[y]
            self.root[y]=x
        else:
            self.root[y] +=self.root[x]
            self.root[x]=y
            if self.rank[x]==self.rank[y]:
                self.rank[y] +=1

    def isSameGroup(self,x,y):
        return self.Find_Root(x)==self.Find_Root(y)

    def size(self,x):
        return -self.root[self.Find_Root(x)]

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

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

    def group_members(self):
        return {i:self.members(i) for i in self.roots()}

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


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

UnionFind=UnionFind(N+1)
for i in range(N):
    UnionFind.Unite(i+1,P[i])

D=UnionFind.group_members()
E=[]
for i in D:
    A,length=D[i],len(D[i])
    if A[0]==0:continue
    index,F=A[0]-1,[]
    while len(F)!=length:
        index=P[index]-1
        F.append(C[index])
    E.append(F)

ans=-float("inf")
for A in E:
    length=len(A)
    if sum(A)<0:
        A=A*2
        for i in range(length):
            point=0
            for j in range(min(K,length)):
                point +=A[i+j]
                ans=max(ans,point)
    else:
        div,mod=divmod(K,length)
        base=div*sum(A)
        A=A*2
        for i in range(length):
            point=0
            for j in range(mod):
                point +=A[i+j]
                ans=max(ans,base+point)
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()))
vis = [0 for i in range(N)]
cumCs = []
for i in range(N):
  nextP = i
  if vis[nextP]>1:
    continue
  cumCs.append([0, C[nextP]])
  vis[nextP] = 1
  while 1:
    nextP = P[nextP] - 1
    if vis[nextP]>1:
      break
    cumCs[-1].append(cumCs[-1][-1] + C[nextP])
    vis[nextP] += 1
ans = -1e9
for cumC in cumCs:
  lenC = (len(cumC)-1)//2
  if K<=lenC:
    maxC = -1e9
    for i in range(lenC):
      for j in range(i+1, i+K+1):
        if maxC < cumC[j]-cumC[i]:
          maxC = cumC[j]-cumC[i]
    ans = max(maxC, ans)
  else:
    n = K//lenC
    d = K%lenC
    maxC = -1e9
    if d==0:
      d = lenC
      n -= 1
    if cumC[lenC] <= 0:
      for i in range(lenC):
        for j in range(i+1, i+lenC+1):
          if maxC < cumC[j]-cumC[i]:
            maxC = cumC[j]-cumC[i]
      ans = max(maxC, ans)
    else:
      for i in range(lenC):
        for j in range(i+1, i+d+1):
          if maxC < cumC[j]-cumC[i]:
            maxC = cumC[j]-cumC[i]
      ans = max(cumC[lenC]*n + maxC, ans)
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=float('inf')*-1

for i in range(n):
    visited=[i]
    pin=0
    now=i
    for j in range(k):
        now=p[now]-1
        pin+=c[now]
        ans=max(ans,pin)
        visited+=[now]

        if visited[0]==visited[-1]:
            if pin>0:
                pin*=(k//(len(visited)-1))
                ans=max(ans,pin)
                if k%(len(visited)-1)==0:
                    break
                for s in range(k%(len(visited)-1)):
                    now=p[now]-1
                    pin+=c[now]
                    ans=max(ans,pin)

                break

            else:
                break

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=float('inf')*-1

for i in range(n):
    visited=[i]
    pin=0
    now=i
    for j in range(k):
        now=p[now]-1
        pin+=c[now]
        ans=max(ans,pin)
        visited+=[now]

        if visited[0]==visited[-1]:
            if pin>0:
                pin*=(k//(len(visited)-1))
                ans=max(ans,pin)
                if (len(visited)-1)%k==0:
                    break
                for s in range(k%(len(visited)-1)):
                    now=p[i]-1
                    pin+=c[now]
                    ans=max(ans,pin)

                break

            else:
                break

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=float('inf')*-1

for i in range(n):
    visited=[i]
    pin=0
    now=i
    for j in range(k):
        now=p[now]-1
        pin+=c[now]
        ans=max(ans,pin)
        visited+=[now]

        if visited[0]==visited[-1]:
            if pin>0:
                pin*=(len(visited)-1)
                ans=max(ans,pin)
                if (len(visited)-1)%k==0:
                    break
                for s in range(k%(len(visited)-1)):
                    now=p[i]-1
                    pin+=c[now]
                    ans=max(ans,pin)

            else:
                break

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from io import StringIO
import unittest
import os
import copy

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 累積和
def cumsum(target: []):
    result = []
    for cnt, a in enumerate(target):
        result.append(a) if cnt == 0 else result.append(result[cnt - 1] + a)
    return result


class UnionFind:
    def __init__(self, n):
        """
        コンストラクタ
        :要素数 n:
        """
        self.n = n
        # 添字x: 値yとすると・・
        #   root以外の場合： 要素xは集合yに所属する。
        #   rootの場合　　　： 集合xの要素数はy個である。(負数で保持する)
        self.parents = [-1] * n

    def getroot(self, x):
        """
        データが属するグループのID(と考えて良いはず)を取得する。
        :調査するグループ x:
        """
        # 値が負数 = ルートに到達したので、ルート木の番号を返す。
        if self.parents[x] < 0:
            return x
        else:
            # 値が正数 = ルートに到達していない場合、さらに親の情報を確認する。
            # 下の行は経路圧縮の処理。
            self.parents[x] = self.getroot(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        """
        2つのデータが属するグループを結合する。
        :結合するデータ(1つ目) x:
        :結合するデータ(2つ目) y:
        """
        # 既に同じ集合に存在するなら何もせず終了。
        x = self.getroot(x)
        y = self.getroot(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):
        """
        指定したグループに属するデータの数を返す。
        :調査グループ x:
        """
        # 添え字[root]には、要素数が負数で格納されている。そのため、取得する際は-反転する。
        return -self.parents[self.getroot(x)]

    def is_same(self, x, y):
        return self.getroot(x) == self.getroot(y)

    def members(self, x):
        """
        指定したグループに属するデータの一覧を返す。size()と比較して速度が圧倒的に遅いので注意。
        :調査グループ x:
        """
        root = self.getroot(x)
        return [i for i in range(self.n) if self.getroot(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 resolve(test_def_name=""):
    n, k = map(int, input().split())
    p_s = [0] + list(map(int, input().split()))
    c_s = [0] + list(map(int, input().split()))

    # UnionFindにて集合を明確にする。
    uf = UnionFind(n + 1)
    for cnt, p in enumerate(p_s):
        uf.union(cnt, p)

    # 各グループの情報を整理する
    group_s = []
    for a, ud_group in uf.all_group_members().items():
        # ダミーは飛ばす
        if a == 0:
            continue
        # マスの移動リストを作成
        work = [[p_s[ud_gr], c_s[ud_gr]] for ud_gr in ud_group]
        group_s.append(work)

    ans = -1000000009
    for group in group_s:
        # 商とあまり
        sho, amari = divmod(k, len(group))

        # 1周した時の値
        loop_sum = sum([gr[1] for gr in group])
        # 1周すると正数になる
        if loop_sum > 0:
            check_cnt = amari  # ループを最大限回すので、その余りをチェック
        elif k >= len(group):
            # 1周すると0以下になる かつ Kが1周以上できる量
            check_cnt = len(group)
        else:
            # 1周すると0以下になる かつ Kが1周できない量
            check_cnt = k

        if check_cnt == 0:
            ans = max(ans, loop_sum * sho)
            continue

        score = -1000000009
        cycle_group = group + group
        for i in range(len(group)):
            work_score = 0
            for j in range(check_cnt):
                work_score += cycle_group[i + j][1]
                score = max(score, work_score)

        if loop_sum > 0:
            score += loop_sum * sho

        ans = max(ans, score)

    print(ans)


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """5 2
2 4 5 1 3
3 4 -10 -8 8"""
        output = """8"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """2 3
2 1
10 -7"""
        output = """13"""
        self.assertIO(test_input, output)

    def test_input_3(self):
        test_input = """3 3
3 1 2
-1000 -2000 -3000"""
        output = """-1000"""
        self.assertIO(test_input, output)

    def test_input_4(self):
        test_input = """10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719"""
        output = """29507023469"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_1(self):
        test_input = """5 5
2 3 1 5 4
1 2 3 4 5"""
        output = """23"""
        self.assertIO(test_input, output)

        test_input = """5 5
2 1 4 5 3
-1 1 1 -1 1"""
        output = """3"""
        self.assertIO(test_input, output)

        test_input = """5 5
2 1 4 5 3
-100 1 1 -100 1"""
        output = """2"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_2(self):
        test_input = """5 100000000
2 1 4 5 3
-1 -1 -1 -1 -1"""
        output = """-1"""
        self.assertIO(test_input, output)

        test_input = """5 100000000
2 1 4 5 3
-1 -1 -1 -1 0"""
        output = """0"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_3(self):
        test_input = """5 4
2 1 4 5 3
1 2 3 4 5"""
        output = """17"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_4(self):
        test_input = """5 2
2 1 4 5 3
1 2 3 4 5"""
        output = """9"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Wrong Answer

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

Ps = list(map(int, input().split(" ")))
Cs = list(map(int, input().split(" ")))

max_points = 0
for now_point in range(2, N+1):
    max_point = -10 ** (-9) - 1
    C_point = 0
    for _ in range(K):
        next_point = Ps[now_point-1]
        C_point += Cs[next_point-1]
        if C_point > max_point:
            max_point = C_point
        now_point = next_point
    
    if max_points < max_point:
        max_points = max_point

print(max_points)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict, deque
from copy import deepcopy
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
def end_of_loop():raise StopIteration

def main():
    N, K = MI()
    P = LI()
    C = LI()
    #1週下再に加算されるスコア並びにあるますから出発した際に１マス進んだ際のスコアがわかればよい。
    #初期化
    ans = []
    result = -float('inf')
    #開始点
    for i in range(N):
        result2= 0
        # start
        temp = i
        d = [-float('inf')] * N
        for j in range(N):
            temp = P[temp]-1
            result2+=C[temp]
            d[j] = result2
            if temp == i:
                index = j+1
                score = result2
                if index < K:
                    amari = K % index
                    syou = K // index
                    if amari !=0:
                        result = max(result, syou*score+max(d[0:amari]), max(d))
                    else:
                        result = max(result, syou*score, max(d))
                    break
                else:
                    result = max(result, max(d[0:K]))
                    break
    print(result)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict, deque
from copy import deepcopy
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
def end_of_loop():raise StopIteration

def main():
    N, K = MI()
    P = LI()
    C = LI()
    #1週下再に加算されるスコア並びにあるますから出発した際に１マス進んだ際のスコアがわかればよい。
    #初期化
    ans = []
    result = -float('inf')
    #開始点
    for i in range(N):
        result2= 0
        # start
        temp = i
        d = [-float('inf')] * N
        for j in range(N):
            temp = P[temp]-1
            result2+=C[temp]
            d[j] = result2
            if temp == i:
                index = j+1

                score = result2
                if index < K:
                    amari = K % index
                    syou = K // index
                    while amari < index:
                        if amari !=0:
                            result = max(result, syou*score+max(d[0:amari]))
                        else:
                            result = max(result, syou*score)
                        amari += index
                        syou = syou - index
                    result = max(result, syou*score+max(d))
                    break
                else:
                    result = max(result, max(d[0:K]))
                    break
    print(result)

if __name__ == "__main__":
    main()

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

answer = -float('inf')
for start_p in range(1, N+1):

    cycle_total_score = 0
    cycle_in_score = -float('inf')
    cycle_count = 0
    next_p = P[start_p]
    while True:
        cycle_total_score += C[next_p]
        cycle_in_score = max(cycle_in_score, cycle_total_score)
        cycle_count += 1

        if next_p == start_p:
            # print('start_p:', start_p, ' cycle_total_score:', cycle_total_score, 'cycle_in_score:', cycle_in_score, 'cycle_count:', cycle_count)
            break
        next_p = P[next_p]
    


    max_score = 0
    if K == cycle_count:
        max_score = cycle_in_score
    else:
        #あふれたK % cycle_count回数分だけスコアを足すためにmaxを探さす
        add_max_count = K % cycle_count
        add_total_score = 0
        add_score = -float('inf')
        add_count = 0
        add_next_p = P[start_p]
        while True:
            add_total_score += C[add_next_p]
            add_score = max(add_score, add_total_score)
            add_count += 1

            if add_count == add_max_count:
                break
            add_next_p = P[add_next_p]
            
        if K < cycle_count:
            #最大の試行回数がcycle_countよりも小さい場合K % cycle_countまでで一番良いところでbeak
            max_score = add_total_score
        else:
            if cycle_total_score >= 0:
                #1サイクルでプラスの場合はできるだけサイクルを回してK % cycle_countまでで一番良いところでbeak
                max_score = (K // cycle_count) * cycle_total_score + add_total_score
            else:
                #1サイクルでマイナスの場合はサイクルを回さないで、K % cycle_countまでで一番良いところでbreak
                max_score = add_total_score
    # print('max_score', max_score)
    answer = max(answer, max_score)

print(answer)

Submission status: Wrong Answer

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

def s(P,C,l,nn):
    if nn==0:
        return 0
    else:
        tmp=C[P[l[0]-1]-1]
        MAX=C[P[l[0]-1]-1]
        for i in range(1,nn):
            tmp+=C[P[l[i]-1]-1]
            MAX=max(MAX,tmp)
        return MAX

def getmax(e,C,K,P):
    if K<=len(e):
        tmp=s(P,C,e,K)
    else:
        d=0
        for ee in e:
           d+=C[P[ee-1]-1] 
        if d<=0:
            tmp=s(P,C,e,len(e))
        else:
            a=K//len(e)
            b=K%len(e)
            tmp=s(P,C,e,b)+a*d
    return tmp

MAX=-10**18
for n in range(1,N+1):
    tmp=[0 for n in range(N)]
    l=[]
    prev=n
    l.append(prev)
    tmp[prev-1]+=1
    i=0
    while i<K:
        prev=P[prev-1]
        if tmp[prev-1]==0:
            tmp[prev-1]+=1
            l.append(prev)
            i+=1
        else:
            MAX=max(MAX,getmax(l,C,K,P))
            break
print(MAX)

Submission status: Wrong Answer

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

d = -10 ** 9
j = 0

i = 0
s = 0
x = []
z = []

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

        if not(j in z):
            x.append(j)

        j = P[j] - 1

        if j == l and s > 0:
            if K-i-1 > i:
                i = i * (K-i // i)
                s = s * i
        elif j == l:
            z.extend(x)
            x = []
            break
print(d)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate


def main():
    cells, moves = [int(x) for x in input().split()]
    jumps_from = [int(x) - 1 for x in input().split()]
    score_on = [int(x) for x in input().split()]

    ans = - 10**10
    for start in range(cells):
        route = []
        route_append = route.append
        position = start
        while True:
            route_append(score_on[position])
            position = jumps_from[position]
            if position == start:  # Looped
                break

        length = len(route)
        total = sum(route)
        accum_tmp = 0
        for i, score in enumerate(route):
            accum_tmp += score
            if i + 1 > moves:
                break
            accum = accum_tmp
            if total > 0:
                accum += total * ((moves) // length)
            ans = max(ans, accum)

        # if total > 0:
        #     q, mod = divmod(moves, length)
        #     if mod == 0:
        #         candidate = total * q
        #     else:
        #         candidate = max(list(accumulate(route))[:mod]) + total * q
        # else:
        #     candidate = max(list(accumulate(route))[:min(moves, length)])
        # ans = max(ans, candidate)
    return ans


if __name__ == '__main__':
    ans = main()
    print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate


def main():
    cells, moves = [int(x) for x in input().split()]
    jumps_from = [int(x) - 1 for x in input().split()]
    score_on = [int(x) for x in input().split()]

    ans = - 10**10
    for start in range(cells):
        route = []
        route_append = route.append
        position = start
        while True:
            route_append(score_on[position])
            position = jumps_from[position]
            if position == start:  # Looped
                break

        length = len(route)
        total = sum(route)
        accum_tmp = 0
        for i, score in enumerate(route):
            accum_tmp += score
            if i + 1 > moves:
                break
            accum = accum_tmp
            if total > 0:
                accum += total * ((moves - i - 1) // length)
            ans = max(ans, accum)
            accum_tmp = 0

        # if total > 0:
        #     q, mod = divmod(moves, length)
        #     if mod == 0:
        #         candidate = total * q
        #     else:
        #         candidate = max(list(accumulate(route))[:mod]) + total * q
        # else:
        #     candidate = max(list(accumulate(route))[:min(moves, length)])
        # ans = max(ans, candidate)
    return ans


if __name__ == '__main__':
    ans = main()
    print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate


def main():
    cells, moves = [int(x) for x in input().split()]
    jumps_from = [int(x) - 1 for x in input().split()]
    score_on = [int(x) for x in input().split()]

    ans = - 10**10
    for start in range(cells):
        route = []
        route_append = route.append
        position = start
        while True:
            route_append(score_on[position])
            position = jumps_from[position]
            if position == start:  # Looped
                break

        length = len(route)
        total = sum(route)
        accum_tmp = 0
        for i, score in enumerate(route):
            accum_tmp += score
            if i + 1 > moves:
                break
            accum = accum_tmp
            if total > 0:
                accum += total * (moves // length)
            ans = max(ans, accum)
            accum_tmp = 0

        # if total > 0:
        #     q, mod = divmod(moves, length)
        #     if mod == 0:
        #         candidate = total * q
        #     else:
        #         candidate = max(list(accumulate(route))[:mod]) + total * q
        # else:
        #     candidate = max(list(accumulate(route))[:min(moves, length)])
        # ans = max(ans, candidate)
    return ans


if __name__ == '__main__':
    ans = main()
    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()))

answer = -float('inf')
for start_p in range(1, N+1):

    cycle_total_score = 0
    cycle_in_score = -float('inf')
    cycle_count = 0
    next_p = P[start_p]
    while True:
        cycle_total_score += C[next_p]
        cycle_in_score = max(cycle_in_score, cycle_total_score)
        cycle_count += 1

        if next_p == start_p:
            # print('start_p:', start_p, ' cycle_total_score:', cycle_total_score, 'cycle_in_score:', cycle_in_score, 'cycle_count:', cycle_count)
            break
        next_p = P[next_p]
    
    max_score = 0
    if K <= cycle_count:
        #最大の試行回数がcycle_countよりも小さい場合はcycleの中で最大のスコアcycle_in_scoreを使用する
        max_score = cycle_in_score
    else:
        #あふれたK % cycle_count回数分だけスコアを足すためにmaxを探さす
        add_max_count = K % cycle_count
        add_total_score = 0
        add_score = -float('inf')
        add_count = 0
        add_next_p = P[start_p]
        while True:
            add_total_score += C[add_next_p]
            add_score = max(add_score, add_total_score)
            add_count += 1

            if add_count == add_max_count:
                break
            add_next_p = P[add_next_p]

        if cycle_total_score >= 0:
            #1サイクルでプラスの場合はできるだけサイクルを回してK % cycle_countまでで一番良いところでbeak
            max_score = (K // cycle_count) * cycle_total_score + add_total_score
        else:
            #1サイクルでマイナスの場合はサイクルを回さないで、K % cycle_countまでで一番良いところでbreak
            max_score = add_total_score
    # print('max_score', max_score)
    answer = max(answer, max_score)

print(answer)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate


def main():
    cells, moves = [int(x) for x in input().split()]
    jumps_from = [int(x) - 1 for x in input().split()]
    score_on = [int(x) for x in input().split()]

    ans = - 10**10
    for start in range(cells):
        route = []
        route_append = route.append
        position = start
        while True:
            route_append(score_on[position])
            position = jumps_from[position]
            if position == start:  # Looped
                break

        length = len(route)
        total = sum(route)
        accum_tmp = 0
        for i, score in enumerate(route):
            accum_tmp += score
            if i + 1 > moves:
                break
            accum = accum_tmp
            if total > 0:
                accum += total * (moves // length)
            ans = max(ans, accum)

        # if total > 0:
        #     q, mod = divmod(moves, length)
        #     if mod == 0:
        #         candidate = total * q
        #     else:
        #         candidate = max(list(accumulate(route))[:mod]) + total * q
        # else:
        #     candidate = max(list(accumulate(route))[:min(moves, length)])
        # ans = max(ans, candidate)
    return ans


if __name__ == '__main__':
    ans = main()
    print(ans)