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

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

N,K = map(int,input().split())

P = tuple(map(lambda x: int(x)-1,input().split()))
C = tuple(map(int,input().split()))

acc = [0]*N
visited = [-1]*N
last = [0]*N

res = -10**9

for p in range(N):
    c = 0
    v = p
    for j in range(min2(N+1,K)):
        if visited[v] == p:
            break
        visited[v] = p
        acc[v] = c
        last[v] = j
        c += C[v]
        v = P[v]
        res = max2(c,res)
    else:
        continue

    i = last[v]

    delta = c - acc[v]
    remaining = K - i
    cycle = j-i
    if delta > 0 and remaining >= cycle:
        cnt = remaining//cycle - 1
        c = acc[v]+cnt*delta
        remaining -= cnt*cycle
        for _ in range(remaining):
            c += C[v]
            res = max2(res, c)
            v = P[v]

print(res)

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
    ans = s
    while now != a and cnt < k:
        now = p[now]
        s += c[now]
        ans = max(ans, s)
        cnt += 1
    if cnt == k:
        return ans
    if k % cnt == 0:
        return (k // cnt - 1) * s + ans
    s = (k // cnt) * s
    k %= cnt
    cnt = 0
    while cnt < k:
        now = p[now]
        s += c[now]
        ans = max(ans, s)
        cnt += 1
    return ans

print(max(score(i, k) for i in range(n)))

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

ans=-float('inf')

for start in range(N):
    loop_len=1
    pos=P[start]
    score=C[pos]
    scores=[score]

    while pos!=start:
        loop_len+=1
        pos=P[pos]
        score+=C[pos]
        scores.append(score)
    
    loops=(K-1)//loop_len

    if score>0:
        cand=score*loops + max(scores[:(K-loop_len*loops)])
    else:
        cand=max(scores[:min(K,loop_len)])
    ans=max(ans,cand)
print(ans)

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

ans = max(C)
S = set(range(N))
while S:
  scores = []
  x = S.pop()
  while True:
    scores.append(C[x])
    x = P[x]
    if x not in S:
      break
    S.remove(x)
  l = len(scores)
  if K <= l:
    for i in range(l):
      if scores[i] <= 0:
        continue
      ss = 0
      for k in range(K):
        ss += scores[(i+k)%l]
        ans = max(ans, ss)
  else:
    t = sum(scores)
    if t < 0:
      t = 0
    q, r = divmod(K, l)
    for i in range(l):
      if scores[i] <= 0:
        continue
      ss = t * (q - 1)
      for k in range(l):
        ss += scores[(i+k)%l]
        ans = max(ans, ss + (t if k < r else 0))

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)
for i in range(N):
    s = i
    l = [C[i]]
    while True:
        s = P[s]
        if s == i:
            break
        l.append(C[s])
        

    if sum(l) > 0:
        if K>=len(l):
            c = (K//len(l)-1)*sum(l)
            n = K%len(l)+len(l)
        else:
            c = 0
            n = K
        ans = max(ans,c)
        s = i
        for j in range(n):
            c += C[s]
            s = P[s]
            ans = max(ans,c)

    n = min(N,K)
    s = i
    c = 0
    for j in range(n):
        c += C[s]
        s = P[s]
        ans = max(ans,c)
            
print(ans)

Solution (Python):
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
n,k = ma()
Pt = lma()
P = [p-1 for p in Pt]
C = lma()
class unionfind():
    def __init__(self,n):
        self.par = list(range(n))
        self.size = [1]*n
        self.rank = [0]*n

    def root(self,x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

    def same(self,x,y):
        return self.root(x) == self.root(y)

    def unite(self,x,y):
        x = self.root(x)
        y = self.root(y)
        if x==y:return
        else:
            if self.rank[x] < self.rank[y]:
                 x,y = y,x
            if self.rank[x] == self.rank[y]:
                self.rank[x]+=1
            self.par[y] = x
            self.size[x] +=self.size[y]
    def get_size(self,x):
        x = self.root(x)
        return self.size[x]
uf = unionfind(n)
for i in range(n):
    uf.unite(i,P[i])

def score(x):
    l = uf.get_size(x)
    p,r = divmod(k,l)
    tmp = [0 for i in range(l)]
    gain_cycle = 0
    tval = 0
    for i in range(l):
        nex = P[x]
        gain_cycle +=C[nex]
        tval+=C[nex]
        tmp[i] = tval
        x = nex

    
    ret = -10**10
    tval = 0
    if p==0:
        for i in range(r):
            ret = max(ret,tmp[i])

    elif gain_cycle>=0:
        for i in range(l):
            if i<=r-1:
                tval=tmp[i] + gain_cycle*p
            else:
                tval=tmp[i] + gain_cycle*(p-1)
            ret = max(ret,tval)
    else:
        for i in range(l):
            ret = max(tmp[i],ret)

    return ret

        

ans = -10**15
for i in range(n):
    ans = max(ans,score(i))
print(ans)

Solution (Python):

from collections import defaultdict
INF = float('inf')
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]

max_score = -INF
for init in range(1, N + 1):   
    score = defaultdict(int)  
    
    visited = [-1] * (N + 1)
    visited[init] = 0  
    i = init
    max_init = -INF
    for k in range(1, K + 1):
        prev = i
        i = P[i]    



        
        if visited[i] < 0:  
            visited[i] = k
            score[i] = score[prev] + C[i]
            max_init = max(max_init, score[i])
            continue

        loop_score = (score[prev] + C[i]) - score[i]
        loop_len = k - visited[i]

        score[i] = score[prev] + C[i]
        max_init = max(max_init, score[i])

        if k == K:
            break 

        start = i   
        loop_num = (K - k) // loop_len 
        loop_rem = (K - k) % loop_len

        if loop_rem == 0:
            loop_num -= 1
            loop_rem = loop_len

        jj = start
        temp = 0
        temp_max = 0
        for l in range(loop_rem):
            jj = P[jj]
            temp += C[jj]
            temp_max = max(temp_max, temp)

        
        loop_max = temp_max + loop_num * loop_score
        max_init = max(max_init, score[start] + loop_max)
        break

    max_score = max(max_score, max_init)

if max_score == -INF:
    max_score = max(C[1:])

print(max_score)

Solution (Python):
from itertools import accumulate
import sys
sys.setrecursionlimit(10**6)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def dfs(G, v, p):
    seen[v] = True
    sc.append(c[v])

    for nv in G[v]:
        if nv == p:
            continue
        if seen[nv]:
            pos[0] = nv
            return

        dfs(G, nv, v)
        if pos[0] != -1:
            return


G = [[] for _ in range(n)]
for i in range(n):
    G[i].append(p[i]-1)

seen = [False]*n
ans = -float('inf')
for i in range(n):
    if seen[i] == False:
        pos = [-1]
        sc = []
        dfs(G, i, -1)

        if sc:
            sumsc = sum(sc)
            lenc = len(sc)
            for j in range(lenc):
                if j != 0:
                    sc = sc[1:] + [sc[0]]
                ac = list(accumulate(sc))
                
                if sumsc <= 0:
                    ans = max(ans, max(ac[:min(k, lenc)]))
                else:
                    if k%lenc == 0:
                        ans = max(ans, ac[-1]*(k//lenc - 1) + max(ac))
                    else:
                        ans = max(ans, ac[-1]*(k//lenc) + max(ac[:k%lenc]))
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()))
INF = 10**18
ans = -INF
for i in range(N):
    arr = []
    tot = 0
    cnt = 0
    nex = i
    while cnt < K:
        nex = P[nex]
        tot += C[nex]
        arr.append(tot)
        cnt += 1
        if nex == i:
            break
    if cnt < K:
        cycle = cnt
        cycle_score = tot
        loop, amari = K//cycle, K%cycle
        for j in range(cycle):
            if j < amari:
                arr.append(cycle_score*loop+arr[j])
            else:
                arr.append(cycle_score*(loop-1)+arr[j])
    ans = max(ans, max(arr))
print(ans)

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

n, k = map(int, input().split())
parr = list(map(int, input().split()))
carr = list(map(int, input().split()))
scores = []

for i in range(n):
  cur = i
  
  roop_num = 0
  roop_score = 0
  while True:
    cur = parr[cur] - 1
    roop_num += 1
    roop_score += carr[cur]
    if cur == i:
      break
  tmp_max = -10**9
  
  
  if roop_score <= 0:
    score = 0
    max_iter = roop_num
  elif k <= roop_num:
    score = 0
    max_iter = k
  else:
    
    num = k // roop_num - 1
    score = roop_score*num
    max_iter = k - roop_num*num
  cur = i
  for _ in range(max_iter):
      cur = parr[cur] - 1
      score += carr[cur]
      if score > tmp_max:
        tmp_max = score
  scores += [tmp_max]

print(max(scores))

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, k = LI()
p = LI()
c = LI()
C = []
S = []
for i in range(n):
    lst = [-1]*n
    cnt = 0
    idx = i
    s = 0
    while lst[idx] == -1:
        lst[idx] = cnt
        s += c[idx]
        cnt += 1
        idx = p[idx] - 1
    C.append(cnt)
    S.append(s)

if n >= k:
    ans = -10**10
    for i in range(n):
        cnt = 0
        ret = 0
        idx = p[i]
        while cnt < k:
            ret += c[idx-1]
            idx = p[idx-1]
            cnt += 1
            ans = max(ans, ret)
    print(ans)
else:
    ans = -10**10
    for i in range(n):
        if S[i] > 0:
            tmp = S[i] * (k // C[i])
            r = k % C[i]
            cnt = 0
            ret = 0
            idx = p[i]
            tmp -= S[i]
            r += C[i]
            while cnt < r:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, tmp + ret)
        else:
            cnt = 0
            ret = 0
            idx = p[i]
            while cnt < n:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, ret)
    print(ans)

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()

def main():
    N, K = map(int, input().split())
    P = [0] + list(map(int, input().split()))
    C = [0] + list(map(int, input().split()))
    circle_scores = [0] * (N + 1)
    circle_times = [0] * (N + 1)

    checked = set()  
    all_negative = True
    for i in range(1, N + 1):
        if i in checked: continue
        visited = set()
        now = i
        while now not in visited:
            visited.add(now)
            now = P[now]
            circle_scores[i] += C[now]
            circle_times[i] += 1
        for j in visited:
            circle_scores[j] = circle_scores[i]
            circle_times[j] = circle_times[i]
            checked.add(j)

    ans = max(C[1:])
    for i in range(1, N + 1):
        q, r = K // circle_times[i], K % circle_times[i]
        if q > 0: q, r = q - 1, r + circle_times[i]
        val = circle_scores[i] * q
        if circle_scores[i] <= 0:
            val = 0
            r = min(circle_times[i] - 1, K)
        now = P[i]
        add_val = C[now]
        add_max_val = C[now]
        for _ in range(r - 1):
            now = P[now]
            add_val += C[now]
            add_max_val = max(add_max_val, add_val)
        ans = max(ans, val + add_max_val)
    print(ans)



if __name__ == "__main__":
    main()

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

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 s in range(N):
    c = 0
    i = P[s]
    score = C[i]
    ans = max(ans, score)
    c += 1
    while i != s and c < K:
        i = P[i]
        score += C[i]
        ans = max(ans, score)
        c += 1
    if c == K or score <= 0:
        continue
    q = K // c
    score *= q - 1
    c *= q - 1
    while c < K:
        i = P[i]
        score += C[i]
        ans = max(ans, score)
        c += 1
print(ans)

Solution (Python):
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -10**9
for i in range(n):
    scores = [0]
    seen = set([i])
    now = i
    loop = False
    for _ in range(k):
        now = p[now]-1
        scores.append(c[now])
        if now in seen:
            loop = True
            break
        seen.add(now)
    for i in range(len(scores)-1):
        scores[i+1] += scores[i]
    tmp = max(scores[1:])
    ans = max(ans, tmp)
    if (not loop) or scores[-1]<=0:
        continue
    tmp = scores[-1]*(k//(len(scores)-1))
    rem = k%(len(scores)-1)
    tmp += max(scores[:rem+1])
    ans = max(ans, tmp)
    tmp = scores[-1]*(k//(len(scores)-1)-1)
    tmp += max(scores)
    ans = max(ans, tmp)
print(ans)

Solution (Python):
N, K = map(int, input().split())
P = list(map(int, input().split()))
P = [p - 1 for p in P]
C = list(map(int, input().split()))

vis = [False] * N
ans = [-float('inf')] * N

for root in range(N):
    if vis[root]:
        continue
    vis[root] = True

    cycle = [root]
    costs = [C[root]]
    u = P[root]
    vis[u] = True
    while u != root:
        cycle.append(u)
        costs.append(C[u])
        u = P[u]
        vis[u] = True

    
    
    

    L = len(cycle)
    S = sum(costs)
    for i, v in enumerate(cycle):
        cnt = 0
        for step in range(1, min(L, K) + 1):
            cnt += costs[(i + step) % L]
            val1 = cnt
            val2 = cnt + (K - step) // L * S
            ans[v] = max(ans[v], val1, val2)

print(max(ans))

Solution (Python):
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ans=-10**9

for i in range(1,n+1):
    m=i
    co=0
    an=0
    for j in range(n):
        m=p[m-1]
        co+=1
        if m==i:
            break      
    m=i
    x=[0 for j in range(2*co)]
    for j in range(2*co-1):
        m=p[m-1]
        x[j+1]=x[j]+c[m-1]
    
    if k<=co:
        ans=max(ans,max(x[j] for j in range(1,k+1)))
    else:
        if x[co]<=0:
            ans=max(ans,max(x[j] for j in range(1,co+1)))
        else:
            f=max(0,(k//co)-1)
            an+=x[co]*f
            s=k-f*co
            ans=max(ans,an+max(x[j] for j in range(1,s+1)))
            
            
            
            
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()))
D = [-1]*n
ans = -float("inf")
for i, p in enumerate(P):
    ans = max(ans, C[p])
    temp = p
    res = C[p]
    cnt = 1
    while temp != i and cnt < k:
        temp = P[temp]
        res += C[temp]
        cnt += 1
        ans = max(ans, res)
    D[i] = (cnt, res)
for i in range(n):
    a, b = D[i]
    ans = max(ans, b)
    if a == k:
        continue
    if b < 0:
        continue
    temp = b * (k//a-1)
    rest = k%a+a
    now = i
    for _ in range(rest):
        now = P[now]
        temp += C[now]
        ans = max(ans, temp)
print(ans)

Solution (Python):
n, k = map(int, input().split())
P = tuple(map(lambda x: int(x)-1, input().split()))
C = tuple(map(int, input().split()))
from collections import deque
ans = -2*10**9
for idx, root in enumerate(P):
    scores = [C[root]]
    p = P[root]
    while True:
        scores.append(scores[-1] + C[p])
        p = P[p]
        if p == root:
            break

    sc = scores[-1]
    if sc <= 0:
        if k < len(scores):
            ans = max(ans, max(scores[:k]))
        else:
            ans = max(ans, max(scores))
    else:
        kk, r = divmod(k, len(scores))
        if r == 0:
            ans = max(ans, kk*sc, (kk-1)*sc + max(scores))
        else:
            ans = max(ans, kk*sc + max(scores[:r]))
print(ans)

Solution (Python):
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
seen = set()
circuits = []

for x in range(N):
    cir = []
    point = 0
    while True:
        if x in seen: 
            if cir != []: circuits.append((cir,point))
            break
        seen.add(x)
        point += C[x]
        cir.append(x)
        x = P[x] - 1
ans = -1000000000000
for x in circuits:
    tmp = 0
    if  K >= len(x[0]) * 2: 
        if x[1] > 0: tmp = (K // len(x[0]) - 1) * x[1]
        r = K % len(x[0]) + len(x[0])
    else:
        r = K
    for y in x[0]:
        tmp2 = 0
        for _ in range(r):
            y = P[y] - 1
            tmp2 += C[y]
            ans = max(ans, tmp + tmp2)
print(ans)

Solution (Python):
from collections import defaultdict

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]


sep = []
visited = [0] * n
for i in range(n):
  s = i
  box = []
  while visited[s] == 0:
    box.append(s)
    visited[s] = 1
    s = P[s]
  if box != []:
    sep.append(box)

ans = - 10 ** 19
for sp in sep:
  SB = defaultdict(int)
  sumC = sum([C[i] for i in sp]) 
  sn = len(sp)

  if sumC > 0:
    d, mk = divmod(k, sn)
    if d > 0:
      pscore = (d - 1) * sumC
      mk += sn 
    else:
      pscore = 0
  else:
    mk = min(k, sn * 2)
    pscore = 0

  for p in sp: 
    cnt = 0
    score = 0
    mv = - 10 ** 19
    s = p
    while cnt < mk:
      score += C[s]
      s = P[s]
      cnt += 1
      mv = max(mv, score)
    
    SB[p] = mv

  ans = max(ans, max(SB.values()) + pscore)
  
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 = -10**29
for start in range(N):
    now = start
    point = 0
    for j in range(K):
        now = P[now]
        point += C[now]
        ans = max(ans, point)
        if now == start:
            break
    loop_cnt = j+1
    left_k = K - loop_cnt
    if point < 0: continue
    tmp = point
    point *= left_k // loop_cnt + 1
    point -= tmp
    ans = max(ans, point)
    for j in range(left_k%loop_cnt+loop_cnt):
        now = P[now]
        point += C[now]
        ans = max(ans, point)

print(ans)

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

pList = list(map(int,input().split()))

cList = list(map(int,input().split()))

cSum = sum(cList)
p = dict()
c = dict()

for i in range(n):
    p[i] = pList[i]
    c[i] = cList[i]

highScore = min(cList)
for i in range(n):
    count = 0
    zahyou = i
    score = 0
    zumi =zahyou
    loop = False
    while count < k:
        if not(loop):
            if zahyou == zumi and count != 0:
                loop = True
                if score > 0:
                    score += score * ((k // count) - 2)
                    count += ((k // count) - 2) * count
                else:
                    break
        zahyou = p[zahyou] - 1
        score += c[zahyou]
        count += 1
        if highScore < score:
            highScore = score

print(highScore)

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

for start in range(N):
    cur=P[start]
    scores=[C[cur]]
    for _ in range(K):
        if cur==start:
            break
        cur = P[cur]
        scores.append(C[cur]+scores[-1])


    
    
    
    
    
    
    
    

    
    for goal in range(len(scores)):
        no_loop_sum=scores[goal]
        remain_hops=K-goal-1
        

        if scores[-1]>0:
            loops=remain_hops//len(scores)
        else:
            loops=0
        ans=max(ans,no_loop_sum+scores[-1]*loops)
print(ans)

Solution (Python):
N,K = map(int,input().split())
P = list(map(int,input().split()))
for i in range(N):
  P[i]-=1

C = list(map(int,input().split()))
Flag = True
for c in C:
  if c >= 0:
    Flag = False
    break
if Flag:
  print(max(C))
  exit()
L = []
for i in range(N):
  visited = set([])
  now = i
  temp = []
  while now not in visited:
    nxt = P[now]
    visited.add(now)
    temp.append(C[nxt])
    now = nxt
  L.append(temp)

ans = 0
S = []
for X in L:
  start = [0]
  for i in range(len(X)):
    temp = start[-1]+X[i]
    start.append(temp)
  S.append(start)

for X,SS in zip(L,S):
  n = len(X)
  cycle_sum = SS[-1]
  if K <= n:
    kouho = max(SS[:K+1])
  elif cycle_sum < 0:
    kouho = max(SS)
  else:
    amari = K%n
    loop = K//n
    first = 0 
    second = 0 
    first = (loop-1)*cycle_sum + max(SS)
    second = loop*cycle_sum + max(SS[:amari+1])
    kouho = max(first,second)
  ans = max(ans,kouho)
print(ans)

Solution (Python):
def roop(i,K):
    n=i
    ma=[-1]*N
    ma[n]=0
    point=0
    maxp=-10**30
    cnt=0
    isroop=False
    while cnt<K:
        cnt+=1
        n=P[n]
        point+=C[n]
        ma[n]=point
        maxp=max(maxp,point)
        if n==i:
            isroop=True
            break
    if not isroop:
        return maxp
    
    allpoint=(K//cnt)*point
    K%=cnt
    lastpoint=0
    j=0
    n=i
    lastp=0
    while(j<K):
       j+=1
       n=P[n]
       lastp+=C[n]
       lastpoint=max(lastpoint,lastp)
    return max([allpoint+lastpoint,allpoint-point+maxp,maxp])

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

ans=-10**30
for i in range(N):
    ans=max(ans,roop(i,K))
print(ans)

Solution (Python):
n, k = map(int, input().split())
plst = list(map(int, input().split()))
clst = list(map(int, input().split()))
check = [False for _ in range(n)]
loop_s = []
for i in range(n):
    if check[i]:
        continue
    check[i] = True
    loop = []
    start = i
    while 1:
        loop.append(clst[i])
        i = plst[i] - 1
        check[i] = True
        if i == start:
            break
    loop_s.append(loop)

ans = -10 ** 20
for loop in loop_s:
    ans_tmp = 0
    l = len(loop)
    kk = k
    if l < k:
        ans_tmp = max(0, sum(loop) * (k // l - 1))
        kk = k % l + l
    tmp2 = -10 ** 20
    for i in range(l):
        tmp3 = 0
        for j in range(kk):
            pos = (i + j) % l
            tmp3 += loop[pos]
            tmp2 = max(tmp2, tmp3)
    ans = max(ans_tmp + tmp2, ans)
print(ans)

Solution (Python):
import sys
from collections import defaultdict
from queue import deque
readline = sys.stdin.buffer.readline
from collections import Counter



def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def accumurate(l):
    ret = [0] * len(l)
    ret[0] = l[0]

    for i in range(1, len(l)):
        ret[i] = ret[i - 1] + l[i]

    return ret


def main():

    n, k = geta(int)
    p = [0] + list(geta(int))
    c = [0] + list(geta(int))

    inf = 1 << 32

    used = [False] * (n + 1)
    ans = -inf

    for i in range(1, n + 1):

        if used[i]:
            continue
        else:
            used[i] = True

        c_loop = []
        j = p[i]
        c_loop += [c[j]]

        while j != i:
            used[j] = True
            j = p[j]
            c_loop += [c[j]]

        n_loop = len(c_loop)
        cs_loop = accumurate(c_loop + c_loop)
        tot_loop = cs_loop[n_loop - 1]

        _jmax = min(k, n_loop)

        for _i in range(n_loop):
            for _j in range(1, _jmax + 1):
                _tmp = cs_loop[_j + _i] - cs_loop[_i]

                if tot_loop > 0 and k > _j:
                    _tmp += (k - _j) // n_loop * tot_loop

                if ans < _tmp:
                    ans = _tmp

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
n,k = map(int,input().split())
p = [0] + list(map(int,input().split()))
c = [0] + list(map(int,input().split()))
maxsc = -1E20
for s in range(1,n+1):
  x = s
  sc = [0]
  i = 0
  while i<k:
    x = p[x]
    sc.append(sc[i]+c[x])
    i += 1
    if x == s:
      loop = i
      loopsc = sc[i]
      if loopsc > 0:
        baseup = loopsc * int((k-i)/loop)
        for j in range(loop):
          sc[j+1] += baseup
        for j in range((k-i)%loop):
          sc[j+1] += loopsc
      i=k
  sc[0] = -1e20
  maxsc = max(maxsc, max(sc))
print(maxsc)

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(N):
    hoge = []
    p = i
    s = 0
    for j in range(K):
        p = P[p]-1
        s += C[p]
        hoge.append(s)
        ans = max(ans,s)
        if p == i:
            s *= (K-1)//len(hoge)
            s += max(hoge[0:(K-1)%len(hoge)+1])
            ans = max(ans,s)
            break
print(ans)

Solution (Python):
from itertools import accumulate
import sys

input = sys.stdin.buffer.readline

n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

kouho = []

used = [False] * (n)
for i in range(n):
    if used[i]:
        continue
    now = i
    cnt = 0
    res = 0
    route = []
    while True:
        if used[now]:
            break
        route.append(C[P[now] - 1])
        used[now] = True
        nex = P[now] - 1
        cnt += 1
        res += C[nex]
        now = nex
    kouho.append((res, cnt, route))

ans = -(10 ** 20)
for res, cnt, route in kouho:
    kaisu = min(k, cnt)
    temp2 = -(10 ** 20)
    route += route
    ACR = list(accumulate([0] + route))
    for shiten in range(cnt):
        for kosuu in range(1, kaisu + 1):
            temp3 = ACR[kosuu + shiten] - ACR[shiten]
            if res > 0 and k >= cnt:
                temp3 += (k - kosuu) // cnt * res
            temp2 = max(temp2, temp3)
    ans = max(ans, temp2)
    
print(ans)

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

frag, loop, lsum = set(), [], []
for i in range(n):
    if i in frag:
        continue
    now, tmpl, tmps = i, [], 0
    while (now not in frag):
        frag.add(now), tmpl.append(now)
        now = p[now] - 1
        tmps += c[now]
    else:
        loop.append(tmpl * 2)
        lsum.append(tmps)

lacc = []
for l in loop:
    tmp = [0]
    for li in l[1:]: 
        tmp.append(tmp[-1] + c[li])
    lacc.append(tmp)

ans = min(c)
for l, la, ls in zip(loop, lacc, lsum):
    llen = len(l) // 2
    for cnt in range(1, min(llen, k) + 1):
        for i in range(len(l) - cnt - 1):
            tmp = la[i + cnt] - la[i]
            tmp2 = ls * (k // llen - (cnt > k % llen))
            ans = max(ans, tmp, tmp + tmp2)
print(ans)

Solution (Python):
import sys
from collections import defaultdict
from queue import deque
readline = sys.stdin.buffer.readline
from collections import Counter



def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def accumurate(l):
    ret = [0] * len(l)
    ret[0] = l[0]

    for i in range(1, len(l)):
        ret[i] = ret[i - 1] + l[i]

    return ret


def main():
    n, k = geta(int)
    p = [0] + list(geta(int))
    c = [0] + list(geta(int))

    inf = 1 << 32

    used = [False] * (n + 1)

    ans = -inf

    for i in range(1, n + 1):

        if used[i]:
            continue
        else:
            used[i] = True

        c_loop = []
        j = p[i]
        c_loop += [c[j]]

        while j != i:
            used[j] = True
            j = p[j]
            c_loop += [c[j]]

        n_loop = len(c_loop)
        c_loop += c_loop
        cs_loop = accumurate(c_loop)
        tot_loop = cs_loop[n_loop - 1]

        _jmax = k if k < n_loop else n_loop

        _ans = -inf
        _len = 0
        for _i in range(n_loop):
            for _j in range(1, _jmax + 1):
                _tmp = cs_loop[_j + _i] - cs_loop[_i]

                if tot_loop > 0 and k > _j:
                    _tmp += (k - _j) // n_loop * tot_loop

                if _ans < _tmp:
                    _ans = _tmp

        if ans < _ans:
            ans = _ans

    print(ans)


if __name__ == "__main__":
    main()