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 time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
from math import *
from bisect import *
from heapq import *
from collections import *

def lcm(a, b):  
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)    

    def ints(self, a):  
        print(" ".join([str(_) for _ in a]))
    
    def intsNL(self, a):
        for _ in a:
            print(_)
    
    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

N, K = In.ints()

P = In.ints()
C = [-1] + In.ints()

connection = [-1 for i in range(N+1)]

for i in range(N):
    connection[i+1] = P[i]

ans = -99999999999

for i in range(1, N+1):
    start = connection[i]
    tempans = C[start]
    tempk = K-1

    ans = max(ans, tempans)
    seen = [False for i in range(N+1)]
    seen[start] = True    

    while tempk > 0:
        nex = connection[start]
        if not seen[nex]:
            start=nex
            seen[start]=True
            tempans += C[start]
            ans = max(ans, tempans)
            tempk-=1            
        else:
            break
    
    if tempk>N:
        if tempans<=0:
            continue
        
        
        stepsround = K-tempk
        howManyRounds = tempk//stepsround

        tempans += tempans*howManyRounds
        tempk-=howManyRounds*stepsround

        ans = max(ans, tempans)

    if tempk>0:
        while tempk > 0:        
            start=connection[start]            
            tempans += C[start]
            ans = max(ans, tempans)
            tempk-=1            



Out.int(ans)


######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")

Submission status: Wrong Answer

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

def func(x):
    return x - 1

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

    print(ans)
            




if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"

def main():
    n,k = map(int,ipt().split())
#    n = 5000
#    k = 1
    p = [int(i)-1 for i in ipt().split()]
#    p = [(i-1)%n for i in range(n)]
#    c = [10**9 for i in range(n)]
    c = [int(i) for i in ipt().split()]
    ma = -10**18
    al = [False]*n
    for i in range(n):
        if al[i]:
            continue
        pts = []
        np = i
        for j in range(n):
            np = p[np]
            pts.append(c[np])
            al[np] = True
            if np == i:
                break
        ln = len(pts)
        jt = (k-1)%ln+1
        nm = 0
        sma = 0
        for j in pts:
            sma += j
        if sma > 0:
            nm = ((k-1)//ln)*sma
        ma1 = -10**18
        for j in range(ln):
            sm = 0
            for jj in range(jt):
                sm += pts[j-jj]
                if ma1 < sm:
                    ma1 = sm
        ma1 += nm
        if ma < ma1:
            ma = ma1
#        print(ma)

    print(ma)




    return None

if __name__ == '__main__':
    main()

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():
        if cycledist[lis[0]][0] != -INF:
            continue
        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):
        tmp_ans = cycledist[i][0] * (k // cycledist[i][1])

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

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys, math
from functools import lru_cache
from collections import defaultdict
sys.setrecursionlimit(500000)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N, K = mi()
    P = list(mi())
    C = list(mi())
    m = -10**100

    if sum(C) <= 0:
        for i in range(N):
            now = P[i]-1
            score = C[now]
            m = max(score, m)
            while now != i:
                now = P[now]-1
                score += C[now]
                m = max(score, m)
        print(m)
    else:
        ans = -10**100
        # iから始める
        for i in range(N):
            # 1回移動
            now = P[i]-1

            T = 1   # 周期
            s = C[now]   # 周期内の総和

            # 戻ってくるまでループ
            while now != i:
                now = P[now]-1
                s += C[now]
                T += 1

            # ループの中の和が負ならそのiはだめ
            if s < 0:
                continue

            tmp = s*(K//T)

            # 残り K%T 回以内で移動させた時の最大値を計算
            s = 0
            for _ in range(K%T):
                now = P[now]-1
                s += C[now]
                m = max(m, s)

            ans = max(ans, tmp+m)
            
        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()))

P = [p-1 for p in P]

D = [[-10**18]*(n+1) for _ in range(n)]
for i in range(n):
    D[i][0] = 0
Q = [0]*n
A = [0]*n
for i in range(n):
    pos = i
    for j in range(n):
        D[i][j+1] = C[P[pos]]+D[i][j]
        pos = P[pos]
        if pos == i:
            break
    Q[i] = D[i][j+1]
    A[i] = j+1
#print(D)
#print(Q)
#/Users/kobarishigetaka/Dropbox/kyopro/atcoder/abc175/d.pyprint(A)


ans = -10**18

for i in range(n):
    if k < A[i]:
        for j in range(k):
            ans = max(D[i][j+1], ans)
    else:
        if D[i][0] > Q[i]:
            for j in range(A[i]):
                ans = max(D[i][j+1], ans)
        else:
            q, r = divmod(k, A[i])
            temp = (q-1)*Q[i]
            if q-1 != 0:
                ans = max(temp, ans)
            for j in range(A[i]):
                ans = max(D[i][j+1]+temp, ans)
            temp = q*Q[i]
            ans = max(temp, ans)
            for j in range(r):
                ans = max(D[i][r]+temp, ans)

print(ans)

Submission status: Wrong Answer

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

ans = -10**9
loops = {}
for i in range(1,N+1):
    p = i
    k = K
    max_score = -10**9
    score = 0
    visited = set([p])
    visited_lst = [p]
    score_lst = [0]
    while 0 < k:
        score += C[P[p]]
        max_score = max(max_score,score)
        score_lst.append(score)
        p = P[p]
        k -= 1
        if p in visited:
            if p in loops:
                if 0 < loops[p][1]:
                    score += loops[p][0]*(k//loops[p][1])
                    k %= loops[p][1]
                    visited = set([p])
                    visited_lst = [p]
                    score_lst = [score]
                else:
                    break
            else:
                idx = visited_lst.index(p)
                l = len(score_lst)-1-idx
                for j in range(idx,l-1):
                        loops[visited_lst[j]] = [score-score_lst[idx],l]
                if 0 < score-score_lst[idx]:
                    score += (score-score_lst[idx])*(k//l)
                    k %= l
                    visited = set([p])
                    visited_lst = [p]
                    score_lst = [score]
                else:
                    break
        else:
            visited.add(p)
            visited_lst.append(p)
    # print(max_score)

    ans = max(ans,max_score)
# print(loops)
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 = max(C)
for i in range(N):
    check = {i}
    loop_score =[]
    k = i
    while True:
        loop_score.append(C[k])
        k = P[k]-1
        t = len(check)
        check.add(k)
        if len(check)==t:
            break
    cum_score = 0
    cum_scores = []
    for j in loop_score:
        cum_score+=j
        cum_scores.append(cum_score)
    loop = cum_scores[-1]
    compare = min(0,max(C))
    loops = K//len(cum_scores)
    plus = K%len(cum_scores)
    if loop > 0:
        compare = 0
        compare+=loops*loop
    final = cum_scores[:plus]
    if K < len(cum_scores):
        cum_scores = cum_scores[:K]
    if plus != 0:
        compare+=max(final)
    if max(cum_scores)>compare:
        compare = max(cum_scores)
    if compare>ans:
        ans = compare
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()))

cSum = sum(c)

ans = 0

if k > n * 2:
    if cSum > 0:
        ans += cSum * ((k // n) - 1)
        k = n + k % n

highScore = min(c)
for i in range(n):
    count = 0
    zahyou = i
    score = 0
    while count < k:
        zahyou = p[zahyou] - 1
        score += c[zahyou]
        count += 1
        if highScore < score:
            highScore = score



#print(ans,highScore,cSum)
print(ans+highScore)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
sumC = sum(C)
if sumC > 0:
    t = sumC * (K // N)
    remainMove = K % N
    m = 10**9 * (-1) -1
    for i in range(N):
      now = 0
      pos = P[i] - 1
      for j in range(remainMove):
        now += C[pos]
        pos = P[pos]-1

        #print(now)
        m = max(now, m)
    print(m+t)
else:
    remainMove = K
    m = 10**9 * (-1) -1
    for i in range(N):
      now = 0
      pos = P[i] - 1
      for j in range(remainMove):
        now += C[pos]
        pos = P[pos]-1

        #print(now)
        m = max(now, m)
    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=-10**10
for st in range(N):
	now = st+1
	temp=[0]
	while(P[now-1] != st+1):
		temp.append(temp[-1]+C[P[now-1]-1])
		now = P[now-1]
	temp.append(temp[-1]+C[P[now-1]-1])
	if temp[-1]<=0:
		ans = max(ans, (max(temp[1:])))
	else:
		t=temp[-1]*(K//(len(temp)-1))
		t+=max(temp[:1+K%(len(temp)-1)])
		ans=max(ans, t)
		
print(int(ans))

Submission status: Wrong Answer

Solution code:
def solve(N, K, P, C, n):
    ans = []
    done = set([n,])
    for i in range(1, K + 1):
        n = P[n]
        ans.append(C[n])
        if n in done:
            times = K // i
            mod = K % i
            if ans[-1] > 0:
                return ans[-1] * times + max(ans[:mod + 1])
            else:
                return max(ans)
        done.add(n)
    return (max(ans))
def main():
  N, K = map(int, input().split())
  P = {key: val for key, val in zip(range(1, N + 1), map(int, input().split()))}
  C = {key: val for key, val in zip(range(1, N + 1), map(int, input().split()))}
  print(max([solve(N, K, P, C, n) for n in range(1, N + 1)]))
if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
def examA():
    S = SI()
    ans = 0
    if "R" in S:
        ans = 1
    if "RR" in S:
        ans = 2
    if "RRR" in S:
        ans = 3
    print(ans)
    return

def examB():
    N = I()
    L = LI()
    L.sort()
    cnt = 0
    for i in range(N):
        for j in range(i+1,N):
            for k in range(j+1,N):
                if L[i]==L[j]:
                    continue
                if L[j]==L[k]:
                    continue
                if L[i]+L[j]>L[k]:
                    cnt += 1
    ans = cnt
    print(ans)
    return

def examC():
    X, K, D = LI()
    if X<0:
        X = -X
    ans = inf
    if X>K*D:
        ans = X-K*D
        print(ans)
        return

    K -= X//D
    X -= D * (X//D)

    ans = X
    if K>0:
        if K%2==1:
            ans = abs(X-D)
    print(ans)
    return

def examD():
    N, K = LI()
    P = LI()
    C = LI()

    B = [i for i in range(N)]
    for i,p in enumerate(P):
        p -= 1
        B[i] = p

    locat_doubling = [[0]*N for _ in range(31)]
    score_doubling = [[0]*N for _ in range(31)]

    for i in range(N):
        locat_doubling[0][i] = i
        locat_doubling[1][B[i]] = i
        score_doubling[0][i] = 0
        score_doubling[1][B[i]] = C[i]
    for k in range(2,31):
        for i in range(N):
            locat_doubling[k][i] = locat_doubling[k-1][locat_doubling[k-1][i]]
            score_doubling[k][i] = score_doubling[k-1][i] + score_doubling[k - 1][locat_doubling[k - 1][i]]

    score = [[0,-inf] for i in range(N)]
    locate = [[i,i] for i in range(N)]
    ans = max(C)

    if ans<0:
        print(ans)
        return

    for k in range(30)[::-1]:
        for i in range(N):
            if score[i][1]<0:
                continue
            #print(score[i],locate[i])
            score[i][1] += score_doubling[k + 1][locate[i][1]]
            if score[i][1] < score[i][0]:
                score[i][1] = score[i][0]
                locate[i][1] = locate[i][0]
        if K&(1<<k)>0:
            for i in range(N):
                score[i][0] += score_doubling[k+1][locate[i][0]]
                locate[i][0] = locat_doubling[k+1][locate[i][0]]
    for s in score:
        ans = max(ans,s[0],s[1])
    print(ans)
    return

def examE():
    R, C, K = LI()
    V = [[-inf]*C for _ in range(R)]
    for _ in range(K):
        r,c,v = LI()
        V[r-1][c-1] = v
    dp0 = [[0]*(C+1) for _ in range(R+1)]
    dp1 = [[0]*(C+1) for _ in range(R+1)]
    dp2 = [[0]*(C+1) for _ in range(R+1)]
    dp3 = [[0]*(C+1) for _ in range(R+1)]

    for r in range(R):
        for c in range(C):
            v = V[r][c]
            if 0<v:
                dp0[r+1][c+1] = max(dp0[r+1][c],dp0[r][c+1],dp1[r][c+1],dp2[r][c+1],dp3[r][c+1])
                dp1[r+1][c+1] = max(dp1[r+1][c],dp0[r+1][c]+v,dp0[r][c+1]+v,dp1[r][c+1]+v,dp2[r][c+1]+v,dp3[r][c+1]+v)
                dp2[r+1][c+1] = max(dp2[r+1][c],dp1[r+1][c]+v)
                dp3[r+1][c+1] = max(dp3[r+1][c],dp2[r+1][c]+v)
            else:
                dp0[r+1][c+1] = max(dp0[r+1][c],dp0[r][c+1],dp1[r][c+1],dp2[r][c+1],dp3[r][c+1])
                dp1[r+1][c+1] = dp1[r+1][c]
                dp2[r+1][c+1] = dp2[r+1][c]
                dp3[r+1][c+1] = dp3[r+1][c]

    ans = max(dp0[R][C],dp1[R][C],dp2[R][C],dp3[R][C])
    print(ans)
    return

def examF():

    ans = 0
    print(ans)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examD()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
D = [0] * N
i = 0
Sc = -(1e9 + 5)
while 0 in D:
    if D[i] == 1:
        for j in range(N):
            if D[j] == 0:
                i = j
                break
    G = []
    while True:
        G.append(C[i])
        D[i] = 1
        i = P[i] - 1
        if D[i] == 1:
            break
    l = len(G)
    s = sum(G)
    S = 0
    if K >= l and s > 0:
        n = K // l
        S = s * n
        K -= l * n
    elif K >= l and s < 0:
        K = l
    G *= 2
    M = -(1e9 + 5)
    for j in range(l):
        mj = -(1e9 + 5)
        tmp = S
        for k in range(1, K + 1):
            tmp += G[j + k]
            mj = max(mj, tmp)
        M = max(M, mj)
    Sc = max(Sc, M)
        
print(Sc)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
mx=-float("inf")

for i in range(n):
  sc=0
  pn=i
  mass=[0]*n
  for j in range(k):
    if mass[pn]!=0:
      lpk=j-mass[pn][0]
      amari=(k-j)%lpk
      lpsc=sc-mass[pn][1]

      if lpsc<0:
        mx=max(mx,sc)
        break
      for l in range(amari):
        pn=p[pn]-1
        sc+=c[pn]
      sc+=lpsc*((k-j-amari)//lpk)
      mx=max(mx,sc)
      break
    mass[pn]=[j,sc]
    pn=p[pn]-1
    sc+=c[pn]
    mx=max(mx,sc)
print(mx)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
pl = [0] + list(map(int, input().split()))
cl = [0] + list(map(int, input().split()))

ans = (10**18)*(-1)
for start in range(1,n+1):
    val = 0
    vals = []
    already_set = set()
    curr_mass = start
    while True:
        next_mass = pl[curr_mass]
        point = cl[next_mass]
        if next_mass in already_set:
            break
        else:
            vals.append(point)
            already_set.add(next_mass)
            curr_mass = next_mass
    if k <= len(vals):
        c_max = vals[0]
        c_val = vals[0]
        # if len(vals) > 1:
        for v in vals[1:k]:
            c_val += v
            c_max = max(c_max, c_val)
        # print(c_max)
        ans = max(c_max,ans)
    else:
        v_sum = sum(vals)
        if v_sum <= 0:
            c_max = vals[0]
            c_val = vals[0]
            # if len(vals) > 1:
            for v in vals[1:]:
                c_val += v
                c_max = max(c_max, c_val)
            # print(c_max)
            ans = max(c_max,ans)
        else:
            loop_cnt = k//len(vals)
            rem = k - loop_cnt*len(vals)
            c_max = v_sum*loop_cnt
            c_val = v_sum*loop_cnt
            if rem > 0:
                for v in vals[:rem]:
                    c_val += v
                    c_max = max(c_max, c_val)
            # print(c_max)
            ans = max(c_max,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()))

csum = sum(c)
if(k < n):
    ans = max(c)
    tab = [0 for i in range(n)]
    for i in range(k):
        ntab = [0 for i in range(n)]
        for j in range(n):
            ntab[p[j]-1] = tab[j] + c[p[j]-1]
        tab = ntab[:]
        mtab = max(tab)
        if(ans < mtab):
            ans = mtab
    print(ans)
else:
    ans = [0]
    tab = [0 for i in range(n)]
    for i in range(n):
        ntab = [0 for i in range(n)]
        for j in range(n):
            ntab[p[j]-1] = tab[j] + c[p[j]-1]
        tab = ntab[:]
        mtab = max(tab)
        ans.append(mtab)
    if(csum <= 0):
        print(max(ans[1:]))
    else:
        nans = max(c)
        for i in range(n):
            ki = k-i
            nans2 = (ki // n)*csum + ans[i]
            if(nans2 > nans):
                nans = nans2
        print(nans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 63


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] < 0:
                j = i
                max_val = -INF
                while True:
                    if j >= len(loop):j=0
                    if i != j and j:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    if i == j: break
                ans = max(ans, max_val)
                continue

            rest = K
            if K <= len(loop) - i - 1:
                val += loopSum[i + K - 1] - loopSum[i]
                ans = max(ans, val)
                continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            val += loopSum[rest]
            ans = max(ans, val)

    print(ans)



if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -10 ** 100
for i in range(n):
    d = [-1] * n
    d[i] = 0
    res = 0
    t = i
    cnt = 1
    while d[p[t] - 1] == -1:
        cnt += 1
        d[p[t] - 1] = d[t] + 1
        t = p[t] - 1
        res += c[t]
    t = p[t] - 1
    if k < d[t] + cnt * 2:
        t = i
        co = 0
        for i in range(k):
            t = p[t] - 1
            co += c[t]
            ans = max(ans, co)
    else:
        res += c[t]
        K = k - d[t]
        rt = 0
        q = i
        for i in range(d[t]):
            q = p[q] - 1
            rt += c[q]
        re = 0
        r = 0
        for i in range(K % cnt):
            t = p[t] - 1
            r += c[t]
            re = max(r, re)
        ans = max(ans, res * (K // cnt) + rt + re)
print(ans)