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:
(n,k),p,c  = [list(map(int, s.split())) for s in open(0)]

pset = set(p)
ans = c[0]
for x in range(1,n+1):
    _sum = [0 for _ in range(2*n)]
    num = 0
    while x in pset:
        pset.remove(x)
        _sum[num + 1] = _sum[num] + c[x-1]
        x = p[x-1]
        num += 1
    if num > 0:
        for i in range(1,num):
            _sum[num + i] += _sum[num] + _sum[i]
        # i == 0
        tmp = _sum[num] * (k//num)
        if tmp > ans:
            ans = tmp
        for i in range(1,num):
            base = max(0, _sum[num]) * ((k-i)//num)
            for j in range(num):
                tmp = _sum[j+i] - _sum[j] + base
                if tmp > ans:
                    ans = tmp
print(ans)

Submission status: Wrong Answer

Solution code:
def f(x):
  D=[-1]*(N+1)
  D[x]=0
  S=[None]*(N+1)
  S[x]=0
  ima=x+0
  for count in range(1, K+1):
    if D[P[ima]]<0:
      D[P[ima]]=D[ima]+1
      S[P[ima]]=S[ima]+C[P[ima]]
      ima=P[ima]+0
    else:
      if S[ima]+C[P[ima]]>S[P[ima]]:
        isshu=count-D[P[ima]]
        atonanshu=(K-count)//isshu
        atonanho=(K-count)%isshu
        agatta=S[ima]+C[P[ima]]-S[P[ima]]
        S[P[ima]]=S[ima]+C[P[ima]]+agatta*atonanshu
        D[P[ima]]=D[ima]+1
        
        ima=P[ima]+0
        for _ in range(atonanho):
          S[P[ima]]=S[ima]+C[P[ima]]
          D[P[ima]]=D[ima]+1
          ima=P[ima]+0
      break
      
  if D[x]==0:
    S[x]=None
  return max([s for s in S if s is not None])

N, K=map(int, input().split())
P=[None]+list(map(int, input().split()))
C=[None]+list(map(int, input().split()))

print(max([f(x) for x in range(1, N+1)]))

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)
    
    # 途中に負の数が混じってて、端っこが両方正なら、端っこのリストをつなげる
    # （上の例でいう2と1を一つのリストにする）
    if A[0] > 0 and A[-1] > 0 and len(positives) >= 2:
        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)
    # print(f'{positives=}')
    # もし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)
        # 連続領域がn個以上の場合、左からn個の合計を計算した後、
        # 領域を右にずらしながら合計を計算することで、O(L) で計算できる 
        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(f'{loop_c=}')

    # 一周したときのスコア
    sum_1_loop = sum(loop_c)
    # print(f'{loop_c=}, {sum_1_loop=}')

    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)
        # print(f'{n_loops=}, {score=}, {K=}')
        # 残りの移動回数でできるだけスコアを稼ぐ
        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(f'{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
    m1=0
    for j in range(min(k,len(c1))):
        m1+=c1[j]
        ans=max(m1,ans)
    if m1>0:
        t=k//len(c1)
        m1=max(0,m1*(t-1))
        ind=max(0,len(c)*(t-1))
        ans=max(ans,m1)
        for i in range(ind,k):
            m1+=c1[i%len(c1)]
            ans=max(ans,m1)
out(ans)

Submission status: Wrong Answer

Solution code:
import math
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

unions = []
checked_num = set()
for i in range(N):
    num = i
    union_set = []
    while num not in checked_num:
        checked_num.add(num)
        union_set.append(Cs[num])
        num = Ps[num]-1
        if num == i:
            unions.append(union_set)
            break

final_max_score = -math.inf

for num_set in unions:
    length = len(num_set)
    count = 0
    if K > length:
        num_sum = sum(num_set)
        remainder = K%length
        if num_sum > 0:
            count = K//length
        K = length
    for k in range(1, K+1):
        #print(k)
        #print(num_set)
        score = 0
        max_score = -math.inf
        for i in range(length):
            score = 0
            score += sum(num_set[i:k+i])
            if i+k-length > 0:
                score += sum(num_set[0:i+k-length])
            if score > max_score:
                max_score = score
        if (count > 0 and k <= remainder):
            max_score = max_score + num_sum*count
        elif (count > 0 and k > remainder):
            max_score = max_score + num_sum*(count-1)
        #print(max_score)
    if max_score > final_max_score:
        final_max_score = max_score
print(final_max_score)

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
        ans = max(ans, tmp)
        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
import numpy as np
import numba
from numba import jit
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@jit
def main(n,k,p,c):
  last=k%n
  by_last=k//n
  sum1=c.sum()
  cnt=sum1*by_last
  if sum1<0:
    for i in range(n):
      ans=0
      nxt=i
      for j in range(n):
          nxt=p[nxt]-1
          cnt=max(ans,cnt)
          ans+=c[nxt]
          cnt=max(ans,cnt)
    return cnt
  else:
    for i in range(n):
      ans=sum1*by_last
      nxt=i
      for j in range(last):
        nxt=p[nxt]-1
        cnt=max(ans,cnt)
        ans+=c[nxt]
        cnt=max(ans,cnt)
    return cnt

n,k = map(int, readline().split())
p = np.array(readline().split(), np.int64)
c = np.array(readline().split(), np.int64)

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

Submission status: Wrong Answer

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

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

INF = float('inf')

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

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop_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])

    max_points.append(max_point)

print(max(max_points))

Submission status: Wrong Answer

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

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

INF = float('inf')

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

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop_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])

    max_points.append(max_point)

print(max(max_points))

Submission status: Wrong Answer

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

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

INF = float('inf')

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

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop_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])

    max_points.append(max_point)

print(max(max_points))

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)
        l *= (k//k + 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 = list(map(int, input().split()))
# p = list(int(input())-1 for _ in range(n))
c = list(map(int, input().split()))
# idx = [i for i in range(n)]
# pのidxの場所を取得する。
from collections import defaultdict
d = defaultdict(int)
for i,pp in enumerate(p):
    d[pp] = pp-1
from itertools import accumulate
ans = -10**18
for i in range(n):
    visited = []
    o = [-1]*n
    cur = i
    while o[cur] == -1:
        o[cur] = len(visited)
        visited.append(p[cur])
        cur = d[p[cur]]
    # print(visited)
    vlen = len(visited)
    tmp_score = 0
    if vlen >= k:
        for i in range(vlen):
            tmp_score += c[d[visited[i]]]
            ans = max(tmp_score,ans)
    else:
        t_sum = []
        for i in range(vlen):
            t_sum.append(c[d[visited[i]]])
        s = list(accumulate(t_sum))
        maxind = 0
        for i in range(1,vlen):
            if s[i]>s[i-1]:
                maxind = i
            else:
                break
        tk = k
        div = tk//vlen
        tk %= vlen
        tmp_score += div*s[-1]
        ans = max(tmp_score,ans)
        for i in range(tk):
            tmp_score += c[d[visited[i]]]
            ans = max(tmp_score,ans)
        ans = max(tmp_score,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import math
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

unions = []
checked_num = set()
for i in range(N):
    num = i
    union_set = []
    while num not in checked_num:
        checked_num.add(num)
        union_set.append(Cs[num])
        num = Ps[num]-1
        if num == i:
            unions.append(union_set)
            break

final_max_score = -math.inf

for num_set in unions:
    length = len(num_set)
    count = 0
    if K > length:
        num_sum = sum(num_set)
        remainder = K%length
        if num_sum > 0:
            count = K//length
        K = length
    for k in range(1, K+1):
        #print(k)
        #print(num_set)
        score = 0
        max_score = -math.inf
        for i in range(length):
            score = 0
            score += sum(num_set[i:k+i])
            if i+k-length > 0:
                score += sum(num_set[0:i+k-length])
            if score > max_score:
                max_score = score
        if (count > 0 and k <= remainder):
            if max_score < max_score + num_sum*count:
                max_score = max_score + num_sum*count
        elif (count > 0 and k > remainder):
            if max_score  <  max_score + num_sum*(count-1):
                max_score = max_score + num_sum*(count-1)
        """
            print (i,i+K, 0, i+K-length)
            print(num_set[i:i+K], num_set[0:i+K-length])
            print(sum(num_set[i:K]), sum(num_set[0:i+K-length]))
            print (score)
        """
        #print(max_score)
        if max_score > final_max_score:
            final_max_score = max_score
print(final_max_score)

"""
X = abs(X)
num = X//D
if num >= K:
    print(X-K*D)
elif num < K:
    rest_X = X - num*D # < X
    rest_K = K - num
    if rest_K%2 == 0:
        print(rest_X)
    else:
        print(abs(rest_X - D))
"""

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)

    ans = -1000000009
    for a, group in uf.all_group_members().items():
        # ダミーは飛ばす
        if a == 0:
            continue

        point = sum([c_s[gr] for gr in group])
        sho, amari = divmod(k, len(group))

        # マスの移動リストを作成
        target = []
        for i in range(len(group)):
            target.append([p_s[group[i]], c_s[group[i]]])

        # 巡回するため、要素を2倍にする。
        target_bai = target + target

        # 得点の計算
        if point < 0:
            base_score = 0
            amari = len(group)
        else:
            base_score = max(0, point * sho)

        score = -1000000009
        for i in range(len(target)):
            work_score = 0
            for j in range(amari):
                work_score += target_bai[i + j][1]
                score = max(score, work_score)

        ans = max(ans, base_score + 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 tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        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:
#!/usr/bin/env python3

import sys


def main():
    # inf = float('inf')              # sys.float_info.max = 1.79e+308
    inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input():  return sys.stdin.readline().rstrip()
    def ii():     return int(input())
    def isp():    return input().split()
    def mi():     return map(int, input().split())
    def mi_0():   return map(lambda x: int(x)-1, input().split())
    def lmi():    return list(map(int, input().split()))
    def lmi_0():  return list(map(lambda x: int(x)-1, input().split()))
    def li():     return list(input())
    def debug(x): print(x, file=sys.stderr)



    def calc_score(start):
        order = [None] * n
        accum = [None] * n
        order[start] = 0
        accum[start] = 0
        place = start
        cnt = 0
        current_score = 0
        M = -inf

        while cnt < k:
            place = P[place]    # 移動
            cnt += 1    # 移動回数
            current_score += C[place]    # 移動後の index でスコアに追加
            M = max(M, current_score)    # [スタートの次点, 現在地] まで任意の場所をゴールに選ぶときのスコア最大値
            if order[place] is None:
                # 未訪問
                order[place] = cnt
                accum[place] = current_score
            else:
                # 訪問ずみ。loop
                head_len = order[place]
                loop_len = cnt - head_len
                head_score = accum[place]
                loop_gain = current_score - accum[place]
                if loop_gain <= 0:
                    # debug('encountered loop, but non-positive loop.')
                    return M
                else:
                    # debug('encountered positive loop.')
                    loop_times, res = divmod(k - head_len, loop_len)
                    # place からスタートして "0 以上" res 以下だけ進むときの
                    res_score = 0    # 稼ぐ最大スコア
                    tmp_score = 0    # 現在の累積スコア
                    tmp_place = place    # 現在地
                    for _ in range(res):
                        tmp_place = P[tmp_place]
                        tmp_score += C[tmp_place]    # 移動後の index でスコアに追加
                        res_score = max(res_score, tmp_score)
                    loop_score = head_score + loop_times * loop_gain + res_score
                    return loop_score

        # debug('never encountered loop.')
        return M
            

    n, k = mi()
    P = lmi_0()
    C = lmi()

    ans = -inf
    for i in range(n):
        # debug(ans)
        ans = max(ans, calc_score(i))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import copy

def cost_val(visit_list, P, C):
    maxval = [-10**10] * (len(P) + 1)
    for start_idx in visit_list:
        cost = 0
        now_id = start_idx
        for i in range(len(visit_list)):
            now_id = P[now_id]
            cost += C[now_id]
            maxval[i + 1] = max(maxval[i + 1], cost)
    print(maxval)
    return maxval[1:len(visit_list) + 1]

def cycles(P):
    cycle_list = []
    visit_list = [False] * len(P)
    for i in range(len(P)):
        if visit_list[i]:
            continue
        now_id = i
        cycle = []
        for j in range(len(P)):
            if visit_list[now_id]:
                break
            cycle.append(now_id)
            visit_list[now_id] = True
            now_id = P[now_id]
        cycle_list.append(cycle)
    return cycle_list

def main():
    N, K = map(int, input().split())
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    cycle_list = cycles(P)
    ans = max(C)
    for cycle in cycle_list:
        maxval = cost_val(cycle, P, C)
        print("maxval = " + str(maxval))

        if len(cycle) > K:
            ans = max(ans, max(maxval[:K]))
        else:
            if K % len(cycle) == 0:
                ans = max(ans, max(maxval), max(map(lambda x: x + maxval[-1] * (K // len(cycle) - 1), maxval)), maxval[-1] * (K // len(cycle)))
            else:
                ans = max(ans, max(maxval), max(map(lambda x: x + maxval[-1] * (K // len(cycle) - 1), maxval)), maxval[-1] * (K // len(cycle)) + max(maxval[:(K % len(cycle))]))
    return ans

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

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
# TLE is doko
 
n,k=map(int,input().split())
 
p=list(map(int,input().split()))
p=[q-1 for q in p]
# 順列
c=list(map(int,input().split()))
 
# ループを発見したい
# from pprint import pprint
 
loopcnt=[]
visited=[]
 
for i in range(n):
    first=p[i]
    if first in visited:
        continue
    now=first
    vs=set([now])
    for j in range(n):
        now=p[now]
        if now in visited:
            continue
        visited.append(now)
        if now in vs:
            loopcnt.append(vs)
            continue
        vs.add(now)
        
lll=[]
for item in loopcnt:
    point=0
    for v in item:
        point+=c[v]
        
    lll.append((list(item),point))

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,(dv-1)*mxs+mxr,otl)
print(ans)

Submission status: Wrong Answer

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


def main():
    [n, num] = [int(e) for e in si().split()]
    pl = [int(e) for e in si().split()]
    cl = [int(e) for e in si().split()]

    M = -1000000000*5000-1
    for i in range(n):
        vis = [0 for _ in range(n)]
        val = [0 for _ in range(n)]
        flag, ith, k, idx, m, cv, cn = False, 0, num, i, 0, 0, 0
        while k > 0:
            idx = pl[idx]-1
            ith += 1
            if not flag and vis[idx]:
                flag = True
                cv = m-(val[idx]-cl[idx])
                cn = ith-vis[idx]
                rest = k//cn
                if rest:
                    m += cv*rest
                    k -= cn*rest
            elif not flag:
                vis[idx] = ith
                val[idx] = m+cl[idx]
            m += cl[idx]
            M = max(M, m)
            k -= 1
    print(M)


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()))
c = [1] * N
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        m[i][c[i]] = m[i][c[i]-1] + C[P[j]-1]
ans = max(C)
for i in range(N):
    if m[i][c[i]] > 0:
        if K%c[i] > 0:
            if  m[i][c[i]] * (K//c[i]) + max(m[i][1:K%c[i]+1]) > ans:
                ans = m[i][c[i]] * (K//c[i]) + max(m[i][1:K%c[i]+1])
        else:
            if  m[i][c[i]] * (K//c[i]) > ans:
                ans = m[i][c[i]] * (K//c[i])
    else:
        if max(m[i][1:min(c[i],K)+1]) > ans:
            ans = max(m[i][1:min(c[i],K)+1])
print(ans)