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.

Solution (Python):
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import bisect_right
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

INF = float("inf")


N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
used = [-1]*N 
renketu = []
index = 0
def dfs(fr,cur,parent,index,li):
    Next = fr[cur]
    Next -= 1
    for chi in [Next]:
        if chi == parent or used[chi] != -1:
            continue
        used[chi] = index
        li.append(chi)
        dfs(fr,chi,cur,index,li)
for i in range(N):
    if used[i] != -1:
        continue
    li = [i]
    used[i] = index
    dfs(P,i,-1,index,li)
    index += 1
    renketu.append(li)
n = len(renketu)
ans = -1*10**20
for i in range(n):
    li = renketu[i]
    nn = len(li)
    val = 0
    nnow = li[0]
    for jj in range(nn):
        val += C[P[nnow]-1]
        nnow = P[nnow]-1
    if val <= 0:
        for k in range(nn):
            now = li[k]
            v = 0
            for j in range(nn):
                v += C[P[now]-1]
                ans = max(ans,v)
                now = P[now]-1
    else:
        vvv = val*(K//nn)
        vvv -= val
        nnn = K % nn
        nnn += nn
        for k in range(nn):
            now = li[k]
            v = 0
            for j in range(nnn):
                v += C[P[now]-1]
                now = P[now]-1
                ans = max(ans,vvv+v)
print(ans)

Solution (Python):
import sys
input=sys.stdin.readline

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

ans=-10**20
m=[]
cycle=[0]*n
for i in range(n):
    now=i
    temp=[]
    s=0
    while True:
        now=p[now]-1
        s+=c[now]
        if temp==[]:
            temp.append(s)
        else:
            temp.append(max(temp[-1],s))
        if now==i:
            cycle[i]=s
            m.append(temp)
            break

for i in range(n):
    t=len(m[i])
    if cycle[i]<=0:
        if k>=t:
            ans=max(ans,m[i][t-1])
        else:
            ans=max(ans,m[i][k-1])

    else:
        x=k//t
        y=k%t
        if x>=1:
            temp=(x-1)*cycle[i]+m[i][t-1]
            ans=max(ans,temp)
            if y!=0:
                temp=x*cycle[i]+m[i][y-1]
                ans=max(ans,temp)
        else:
            ans=max(ans,m[i][k-1])

print(ans)

Solution (Python):
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if n is None:
            return

        if self.v is None:
            self.v = n
            return
        self.v = self.f(self.v, n) 


def main():
    N, K = read_values()
    P = read_list()
    C = read_list()

    res = V(max)
    for i in range(N):
        t = []
        c = 0
        p = i
        while len(t) == 0 or p != i:
            p = P[p] - 1
            c += C[p]
            t.append(c)

        m = len(t)
        
        if m > K or c <= 0:
            res.ud(max(t[:K]))
        else:
            s = K // m * c
            k = K % m
            
            tmp = V(max)
            for i in range(k):
                tmp.ud(s + t[i])
            
            s -= c
            for v in t:
                tmp.ud(s + v)
            
            res.ud(tmp.v)

    print(res)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.readline

n, k = map(int, input().split())
p = [int(x) - 1 for x in input().split()]
c = list(map(int, input().split()))


class UnionFind(object):
    def __init__(self, n):
        self._par = list(range(n))
        self.size = [1] * n
 
    def root(self, v):
        if self._par[v] == v:
            return v
        self._par[v] = self.root(self._par[v])
        return self._par[v]
 
    def unite(self, u, v):
        u, v = self.root(u), self.root(v)
        if u == v:
            return False
        if self.size[u] > self.size[v]:
            u, v = v, u 
        self.size[v] += self.size[u]
        self._par[u] = v
 
    def same(self, u, v):
        return self.root(u) == self.root(v)

uf = UnionFind(n)
for i in range(n):
    uf.unite(i, p[i])

ans = []
for i in range(n):
    ite = uf.size[uf.root(i)]
    
    if k > ite:
        memo = [0 for _ in range(ite+1)]
        tmp = i
        for j in range(ite):
            tmp = p[tmp]
            memo[j+1] = memo[j] + c[tmp]
        div = k // ite
        mod = k % ite
        
        if memo[-1] <= 0:
            ans.append(max(memo[1:]))
        else:
            m = max(memo[1:])
            ans.append(max(max(memo[:mod+1]) + div * memo[-1], (div-1) * memo[-1] + m))
    
    else:
        memo = [0 for _ in range(k+1)]
        tmp = i
        for j in range(k):
            tmp = p[tmp]
            memo[j+1] = memo[j] + c[tmp]
        ans.append(max(memo[1:]))
        

print(max(ans))

Solution (Python):
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
L = []
S = set()
for i in range(N):
    if i in S:
        continue
    L.append([C[i]])
    S.add(i)
    tmp = i
    Next = P[i] - 1
    while Next != tmp:
        S.add(Next)
        L[-1].append(C[Next])
        Next = P[Next] - 1

ans = 0

for l in L:
    score = 0
    k = len(l)
    SUM = sum(l)
    l = [0] + l + l
    if SUM > 0:
        score = SUM * (K // k)
        m = K % k
        for i in range(2 * k):
            l[i+1] += l[i]
        for i in range(k):
            for j in range(i+1, i+m+1):
                ans = max(ans, score + l[j] - l[i])
        if K // k >= 1:
            score = SUM * (K // k - 1)
            m = k
            for i in range(k):
                for j in range(i+1, i+m+1):
                    ans = max(ans, score + l[j] - l[i])
    else:
        m = k
        for i in range(2 * k):
            l[i+1] += l[i]
        for i in range(k):
            for j in range(i+1, i+m+1):
                ans = max(ans, score + l[j] - l[i])

if ans == 0:
    ans = max(C)

print(ans)

Solution (Python):
from itertools import product
from itertools import accumulate as acc

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]

visited = [0]*N
g = []
for i in range(N):
    if visited[i]:
        continue
    g.append([])
    
    while visited[i] == 0:
        g[-1].append(i)
        visited[i] = 1
        i = P[i]
c = [[C[g_j] for g_j in g_i] for g_i in g]
c_acc = [[0]+list(acc(c_i*2)) for c_i in c]
c_sum = [sum(c_i) for c_i in c]
c_len = [len(c_i) for c_i in c]

max_num = -(10**18)
for i, g_i in enumerate(g):
    for j, start in enumerate(g_i):
        for k, end in enumerate(g_i*2):
            if not (j < k):
                continue
            cost = k-j
            score = c_acc[i][k+1] - c_acc[i][j+1]
            if c_sum[i] > 0:
                count = (K-cost)//c_len[i]
                cost += c_len[i]*count
                score += c_sum[i]*count
            if 1 <= cost <= K:
                max_num = max(max_num, score)
            

print(max_num)

Solution (Python):
n, k = map(int, input().split())
p = [int(pi) - 1 for pi in input().split()]
c = list(map(int, input().split()))
A = max(c)
seen = [False] * n
for i in range(n):
    if seen[i]:
        continue
    ids = []
    ccost = 0
    while not seen[i]:
        ccost += c[i]
        ids.append(i)
        seen[i] = True
        i = p[i]
    
    cn = len(ids)
    ccnt, m = divmod(k, cn)
    if ccnt > 0:
        ccnt -= 1
        m += cn
    ans = max(c[i] for i in ids)
    for s in ids:
        so = s
        now = 0
        for _ in range(m):
            s = p[s]
            now += c[s]
            
            ans = max(now, ans)
    if ccost > 0:
        ans += ccnt * ccost
    A = max(A, ans)
print(A)

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

ans = -float('inf')

for i in range(1, N+1):
    score = [0]
    alr = set()
    now = i
    while not now in alr:
        alr.add(now)
        now = P[now-1]
        score.append(score[-1] + C[now-1])
    if len(score)-1 >= K:
        for j in range(K):
            ans = max(ans, score[j+1])
    else:
        base = 0
        if score[-1] > 0:
            base = score[-1]*(K//(len(score)-1))
            L = K % (len(score)-1)
            for j in range(len(score)-1):
                ans = max(ans, (base-score[-1])+score[j+1])
            for j in range(L):
                ans = max(ans, base+score[j+1])
        else:
            for j in range(len(score)-1):
                ans = max(ans, base+score[j+1])

print(ans)

Solution (Python):
import sys
input=lambda: sys.stdin.readline().rstrip()
n,k=map(int,input().split())
P=[int(i) for i in input().split()]
C=[int(i) for i in input().split()]
A=[[0]*n]
Cur=[int(i)+1 for i in range(n)]
L=[0]*n
for _ in range(n):
  N=[0]*n
  for i in range(n):
    N[i]=A[-1][i]+C[P[Cur[i]-1]-1]
    Cur[i]=P[Cur[i]-1]
    if L[i]==0 and Cur[i]==i+1:
      L[i]=_+1
  A.append(N)
ans=max(A[1])
for i in range(n):
  ct=0
  loop=L[i]
  loop_ct=A[loop][i]
  rem=-float("inf")
  if k>loop and loop_ct>0:
    ct+=(k//loop-1)*loop_ct
    rem=0
    for j in range(loop):
      if j+1<=k%loop:
        rem=max(rem,A[j+1][i]+loop_ct)
      else:
        rem=max(rem,A[j+1][i])
    ans=max(ans,rem+ct)
  else:
    for j in range(min(k,n)):
      rem=max(rem,A[j+1][i])
    ans=max(ans,rem)
print(ans)

Solution (Python):
mod = 1000000007
eps = 10**-9


def main():
    import sys
    input = sys.stdin.readline

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

    ans = -10**10
    for v0 in range(1, N+1):
        seen = [0] * (N+1)
        seen[v0] = 1
        k = K
        score = 0
        v = v0
        ma = -10**10
        flg = 0
        S = [0] * (N+1)
        SK = [0] * (N+1)
        SK[v0] = k
        while True:
            nxt = P[v]
            score += C[nxt]
            if seen[nxt]:
                flg = 1
                score_loop = score - S[nxt]
                loop_size = SK[nxt] - k + 1
                k -= 1
                v = nxt
                break
            S[nxt] = score
            SK[nxt] = k-1
            ma = max(ma, score)
            seen[nxt] = 1
            v = nxt
            k -= 1
            if k == 0:
                break

        if flg:
            
            if score_loop > 0:
                x = k // loop_size - 1
                score += score_loop * x
                k -= x * loop_size
                ma = max(ma, score)
            else:
                k = loop_size
            for _ in range(k):
                nxt = P[v]
                score += C[nxt]
                ma = max(ma, score)
                v = nxt
        ans = max(ans, ma)
    print(ans)


if __name__ == '__main__':
    main()

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

for i in range(n):
    p[i] -= 1
def score(a, k):
    now = p[a]
    s = c[now]
    cnt = 1
    l = [s]
    while now != a and cnt < k:
        now = p[now]
        s += c[now]
        l.append(s)
        cnt += 1
    if cnt == k:
        return max(l)
    l.append((k // cnt - 1) * s + max(l))
    s = (k // cnt) * s
    k %= cnt
    cnt=0
    while cnt < k:
        now = p[now]
        s += c[now]
        l.append(s)
        cnt += 1
    return max(l)
print(max(score(i, k) for i in range(n)))

Solution (Python):
n, k = map(int, input().split())
p = list(map(lambda x: int(x) - 1, input().split()))
c = list(map(int, input().split()))

ans = -float('inf')
visited = [False] * n
for i in range(n):
    if not visited[i]:
        visited[i] = True
        loop = [i]
        cost = [c[i]]
        while not visited[p[loop[-1]]]:
            visited[p[loop[-1]]] = True
            cost.append(c[p[loop[-1]]])
            loop.append(p[loop[-1]])

        total_cost = sum(cost)
        
        
        

        m = len(loop)
        point = [-float('inf')] * m
        for j1 in range(m):
            s = 0
            for j2 in range(1, min(m, k) + 1):
                s += cost[(j1 + j2) % m]
                point[j1] = max(point[j1], s, s + total_cost * ((k - j2) // m))

        
        ans = max(ans, max(point))

print(ans)

Solution (Python):
def numba_compile(numba_config):
    import os, sys
    if sys.argv[-1] == "ONLINE_JUDGE":
        from numba import njit
        from numba.pycc import CC
        cc = CC("my_module")
        for func, signature in numba_config:
            globals()[func.__name__] = njit(signature)(func)
            cc.export(func.__name__, signature)(func)
        cc.compile()
        exit()
    elif os.name == "posix":
        exec(f"from my_module import {','.join(func.__name__ for func, _ in numba_config)}")
        for func, _ in numba_config:
            globals()[func.__name__] = vars()[func.__name__]
    else:
        from numba import njit
        for func, signature in numba_config:
            globals()[func.__name__] = njit(signature, cache=True)(func)
        print("compiled!", file=sys.stderr)

import numpy as np

def solve(N, K, P, C):
    ans = -10**18
    for start in range(N):
        t = 1
        s = 0
        idx = start
        while P[idx] != start:
            idx = P[idx]
            s += C[idx]
            t += 1
        s += C[start]
        q = K // t
        
        score = 0
        
        if s >= 0:
            x = max(0, (q-2)*t)
            score += s * (x//t)
            
            idx = start
            for _ in range(x, K):
                idx = P[idx]
                score += C[idx]
                ans = max(ans, score)
        else:
            idx = start
            for _ in range(1, min(N, K+1)):
                idx = P[idx]
                score += C[idx]
                ans = max(ans, score)
    return ans

numba_compile([
    [solve, "i8(i8,i8,i8[:],i8[:])"],
])


def main():
    N, K = map(int, input().split())
    P = np.array(input().split(), dtype=np.int64)-1
    C = np.array(input().split(), dtype=np.int64)
    ans = solve(N, K, P, C)
    print(ans)

main()

Solution (Python):


import sys
input=sys.stdin.readline

n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ans=-10**18
for pos in range(n):
    value=0
    points=[]
    s=set()
    for j in range(n):
        s.add(pos)
        pos=p[pos]-1
        value+=c[pos]
        points.append(value)
        if pos in s:
            break
    loop_value=max(0,points[-1])
    l=len(s)
    for j in range(l):
        if j<(k%l):
            ans=max(ans,points[j]+loop_value*(k//l))
        else:
            ans=max(ans,points[j]+loop_value*(k//l-1))
print(ans)

Solution (Python):
import sys

def solve():
    input = sys.stdin.readline
    N, K = map(int, input().split())
    P = [int(p) - 1 for p in input().split()]
    C = [int(c) for c in input().split()]

    roopCount = [0] * N
    for i in range(N):
        index = i
        for j in range(N):
            if P[index] == i:
                roopCount[i] = j + 1
                break
            else: 
                index = P[index]

    maxPoint = -10 ** 20
    for i in range(N):
        visited = [-10 ** 14] * N
        point = 0
        index = i
        count = K
        while count > 0:
            index = P[index]
            if visited[index] == -10 ** 14:
                point += C[index]
                visited[index] = point
                count -= 1
            else:
                point += C[index]
                if point <= visited[index]:
                    maxPoint = max(maxPoint, max(visited))
                    break
                else:
                    count -= 1
                    add = point - visited[index]
                    visited[index] = point
                    
                    roop = count // roopCount[index]
                    visited[index] += add * roop
                    count %= roopCount[index]
                    point = visited[index]
                    for _ in range(count):
                        index = P[index]
                        point += C[index]
                        visited[index] = point
                    maxPoint = max(maxPoint, max(visited))
                    break
        else:
            maxPoint = max(maxPoint, max(visited))

    print(maxPoint)
    

    return 0

if __name__ == "__main__":
    solve()

Solution (Python):
n,k = map(int,input().split())
p = [i-1 for i in list(map(int,input().split()))]
c = list(map(int,input().split()))
ans = -float("inf")
for i in range(n):
    now = i
    cnt = [0]
    for j in range(n):
        nxt = p[now]
        cnt.append(cnt[j]+c[nxt])
        now = nxt
        if now == i:
            break
    m = len(cnt)-1
    if k <= m:
        s = max(cnt[1:(k+1)])
    elif cnt[-1] < 0:
        s = max(cnt[1:])
    else:
        t = k//m
        s = (t-1)*cnt[-1]+max(cnt[1:])
        s = max(s, t*cnt[-1]+max(cnt[:(k-t*m+1)]))
    ans = max(ans,s)
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10**7) 
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right

from collections import deque, defaultdict


from collections import Counter

from itertools import accumulate,combinations,permutations,product

from heapq import heapify,heappop,heappush

from functools import reduce,lru_cache

from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): 
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    

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

    
    tans=-float('inf')
    for i in range(N):
        start=i
        cur=P[i]-1
        score=C[cur]
        time=1
        ans=-float('inf')

        f2=0
        while True:
            
            if cur==start and f2==0:
                f2=1

                d=(K//time)
                if d>=2:
                    time=(d-1)*time
                    score=(d-1)*score

            ans=max(ans,score)


            cur=P[cur]-1
            score=score+C[cur]
            time=time+1
            if time>K:
                break
        tans=max(ans,tans)
    print(tans)





if __name__ == "__main__":
    main()

Solution (Python):
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
a=[-1]*n
ans=0
if sum([i<0 for i in c])==n:
    print(max(c))
    exit()

for i in range(n):
    if a[i]!=-1:
        continue
    b=[i+1]
    while len(b)==len(set(b)):
        b.append(p[b[-1]-1])
    b.pop()
    e=len(b)
    d=sum([c[i-1] for i in b])
    for i in b:
        a[i-1]=[d,e]
for i in range(n):
    score=0
    tmp=i
    t=k%a[i][1]
    if a[i][0]>=0:
        score=a[i][0]*(k//a[i][1])
    tscore=score
    for j in range(t):
        tmp=p[tmp]-1
        tscore+=c[tmp]
        score=max(score,tscore)
    ans=max(ans,score)
for i in range(n):
    score=0
    tmp=i
    t=k%a[i][1]
    if k//a[i][1]==0:
        continue
    if a[i][0]>=0:
        score=a[i][0]*(k//a[i][1]-1)
    tscore=score
    for j in range(a[i][1]):
        tmp=p[tmp]-1
        tscore+=c[tmp]
        score=max(score,tscore)
    ans=max(ans,score)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,k=MI()
per=LI()
for i in range(n):
    per[i]-=1
points=LI()
ans=-inf
for i in range(n):
    val=0
    
    res=[]
    pos=per[i]
    inipos=per[i]
    count=0
    while True:
        val+=points[pos]
        pos=per[pos]
        if len(res)==0:
            res.append(val)
        else:
            res.append(max(res[-1],val))
        
        count+=1
        if pos==inipos:
            break
    loop=(val,count)
    
    
    for x in range(len(res)):
        if loop[0]<=0:
            ans=max(ans,res[x])
        else:
            ans=max(ans,res[x]+loop[0]*((k-x-1)//loop[1]))
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline


def calc(start, P, C, k):
    seen = {start}
    loop = 1
    pos = start
    res = 0
    maxim = -float("INF")
    for _ in range(k):
        next = P[pos]
        point = C[next]
        res += point
        pos = next
        if res > maxim:
            maxim = res
        if pos in seen:
            break
        seen.add(pos)
        loop += 1

    if res <= 0:
        return maxim
    if loop >= k + 1:
        return maxim
    residue = k - loop
    t = residue // loop
    residue %= loop
    max1 = res * t + maxim
    res *= (t+1)
    max2 = res
    for _ in range(residue):
        next = P[pos]
        point = C[next]
        res += point
        pos = next
        if res > max2:
            max2 = res

    return max(max1, max2)


def main():
    n, k = map(int, input().split())
    P = list(map(lambda x: int(x)-1, input().split()))
    C = list(map(int, input().split()))

    ans = -float("INF")
    for start in range(n):
        res = calc(start, P, C, k)
        if ans < res:
            ans = res

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

INF = 10**18


def main():

    N, K = in_nn()
    P = in_nl()
    C = in_nl()

    if K < N + 10:
        ans = -INF
        for i in range(N):
            score = 0
            max_score = -INF
            now = i

            for j in range(K):
                now = P[now] - 1
                score += C[now]
                max_score = max(score, max_score)
            ans = max(ans, max_score)

        print(ans)
        exit()

    else:

        ans = -INF
        for i in range(N):
            score = 0
            max_score = -INF
            now = i
            search = {now}
            move_cnt = 0

            for _ in range(N + 10):
                now = P[now] - 1
                score += C[now]
                max_score = max(score, max_score)
                move_cnt += 1

                if now in search:
                    break
                search.add(now)

            if score < 0:
                ans = max(ans, max_score)
            else:
                tk = (K % move_cnt) + move_cnt
                score = score * (K // move_cnt - 1)
                max_score = score
                now = i
                for x in range(tk):
                    now = P[now] - 1
                    score += C[now]
                    max_score = max(score, max_score)
                ans = max(ans, max_score)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from itertools import accumulate
def solve(P, C, K, Checked, s):
    B = []
    B.append( C[s])
    now = P[s]
    Checked[s] = True
    while now != s:
        B.append(C[now])
        Checked[now] = True
        now = P[now]
    sumB = sum(B)
    L = len(B)
    accB = [0] + list( accumulate(B))
    ret = B[0]
    for i in range(L):
        for j in range(i+1,L+1):
            if j - i > K:
                continue
            if accB[j] - accB[i] > ret:
                ret = accB[j] - accB[i]
    accRB = [0] + list( accumulate(B[::-1]))
    
    
    for i in range(L+1):
        for j in range(L+1):
            if i==0 and j==0:
                continue
            if i + j > K:
                continue
            t = accB[i] + accRB[j]
            if sumB > 0:
                t += (K-(i+j))//L*sumB
            if t > ret:
                ret = t
                
    return ret
        
    
def main():
    N, K = map( int, input().split())
    P = list( map( lambda x: int(x)-1, input().split()))
    C = list( map( int, input().split()))
    Checked = [False]*N
    ans = C[0]
    for s in range(N):
        if Checked[s]:
            continue
        ans_s = solve(P, C, K, Checked, s)
        if ans_s > ans:
            ans = ans_s
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):


from sys import stdin

N,K = map(int,stdin.readline().split())

P = list(map(int,stdin.readline().split()))
C = list(map(int,stdin.readline().split()))
end = [-1] * N
sc = [0] * N
for i in range(N):
    P[i] -= 1



ans = max(C)
for i in range(N):

    now = i
    nsum = 0
    lis = [0]
    cnt = None

    for j in range(min(N,K)):
        now = P[now]
        nsum += C[now]
        ans = max(ans , nsum)
        lis.append(nsum)

        if i == now and nsum > 0:
            ans = max(ans , nsum*(K//(len(lis)-1)) + max(lis[:K%(len(lis)-1)+1]))
            cnt = j+1
            break

    if cnt == None:
        continue
    
    loopnum = K // cnt
    if loopnum > 0:
        loopnum -= 1
    loopscore = loopnum * lis[-1]
    rem = K - cnt * loopnum

    now = i
    nsum = loopscore

    

    for j in range(rem):
        now = P[now]
        nsum += C[now]
        ans = max(ans , nsum)

print (ans)

Solution (Python):
n,k = map(int,input().split())
p = list(map(lambda x: int(x)-1,input().split()))
c = list(map(int,input().split()))

ans = max(c)
if(ans <= 0):
    print(ans)
    exit()

for i in range(n):
    now = i
    score = [0]
    while(p[now] != i ):
        now = p[now]
        score.append(score[-1] + c[now])
    cyc_score = score[-1] + c[i]
    cyc = len(score)

    max_loop = k//cyc
    if(cyc_score <= 0):
        tmp = max(score[: min(k+1, cyc)])
    else:
        tmp = max(score) + (max_loop-1)*cyc_score
        tmp = max(tmp, max(score[:(k%cyc) + 1]) + max_loop*cyc_score)

    ans = max(ans,tmp)
print(ans)