qyliang/CodeNanoFix huggingface dataset:
Buggy code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
ans = -1000000000
for i in range(N):
  cost = 0
  S = []
  x = P[i] - 1
  l = 1
  while 1:
    cost += C[x]
    S.append(cost)
    if x == i:
      break
    l += 1
    x = P[x] - 1
  print(S, l)
  if cost > 0:
    ans = max(ans, cost * (K // l) + max(S[:K % l]))
  else:
    ans = max(ans, max(S))
print(ans)

Fixed code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
ans = -1000000000
for i in range(N):
  cost = 0
  S = []
  x = P[i] - 1
  l = 1
  while 1:
    cost += C[x]
    S.append(cost)
    if x == i:
      break
    l += 1
    x = P[x] - 1
  if cost > 0:
    for j in range(l):
      ans = max(ans, S[j] + cost * ((K - j - 1) // l))
  else:
    ans = max(ans, max(S[:min(K, l)]))
print(ans)
Buggy code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))

dummy=set()
loop=[]
X=set(range(N))
while len(dummy)!=N:
  a=[]
  k=min(X-dummy)
  a.append(k)
  dummy.add(k)
  l=P[k]-1
  while l!=k:
    a.append(l)
    dummy.add(l)
    l=P[l]-1
  loop.append(a)

ans=-(10**300)
for l in loop:
  temp=0
  s=len(l)
  ssum=0
  k=0
  for i in range(s):
    ssum+=C[l[i]]
  if ssum>0:
    temp+=(K%s)*ssum
    k=K-(K%s)
  else:
    k=min(K,s)
  kmax=-(10**300)
  for ii in range(1,k):
    for jj in range(s):
      tempscore=temp
      for kk in range(ii):
        tempscore+=C[l[(jj+kk)%s]]
      if tempscore>kmax:
        kmax=tempscore
  if kmax>ans:
    ans=kmax
print(ans)

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

dummy=set()
loop=[]
X=set(range(N))
while len(dummy)!=N:
  a=[]
  k=min(X-dummy)
  a.append(k)
  dummy.add(k)
  l=P[k]-1
  while l!=k:
    a.append(l)
    dummy.add(l)
    l=P[l]-1
  loop.append(a)

ans=-(10**300)
for l in loop:
  temp=0
  s=len(l)
  ssum=0
  k=0
  for i in range(s):
    ssum+=C[l[i]]
  if ssum>0:
    temp+=((K-1)//s)*ssum
    k=K-((K-1)//s)*s
  else:
    k=min(K,s)
  kmax=-(10**300)
  for ii in range(s):
    tempscore=temp
    for jj in range(1,k+1):
      tempscore+=C[l[(ii+jj)%s]]
      if tempscore>kmax:
        kmax=tempscore
  if kmax>ans:
    ans=kmax
print(ans)
Buggy code:
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 + (0 if k > r else t))

print(ans)

Fixed code:
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)
Buggy code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
    scores = []
    idx = i  # starting index
    while True:
        idx = Ps[idx]  # point to the next index
        scores.append(Cs[idx])  # fetch a score to add
        if idx == i:  # when the cycle is closed
            break
    len_cycle = len(scores)
    sum_cycle = sum(scores)

    if sum_cycle <= 0:  # when each cycle reduces the total score
        score = 0
        for j in range(min(K, len_cycle)):
            score += scores[j]
            max_score = max(max_score, score)
    else:
        if K // len_cycle > 0:
            num_multiply = K // len_cycle - 1
            for j in range(K % len_cycle + len_cycle):
                score += scores[j]
                max_score = max(max_score, score)
        else:
            num_multiply = 0  # len_cycle > K
            score = sum_cycle * num_multiply
            for j in range(K):
                score += scores[j]
                max_score = max(max_score, score)
            
print(max_score)

Fixed code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
    scores = []
    idx = i  # starting index
    while True:
        idx = Ps[idx]  # point to the next index
        scores.append(Cs[idx])  # fetch a score to add
        if idx == i:  # when the cycle is closed
            break

    len_cycle = len(scores)
    sum_cycle = sum(scores)

    if sum_cycle <= 0:  # when each cycle reduces the total score
        score = 0
        for j in range(min(K, len_cycle)):
            score += scores[j]
            max_score = max(max_score, score)
    else:
        if K // len_cycle > 0:
            num_multiply = K // len_cycle - 1
            score = sum_cycle * num_multiply
            scores = scores * 2
            for j in range(K % len_cycle + len_cycle):
                score += scores[j]
                max_score = max(max_score, score)
        else:
            num_multiply = 0  # len_cycle > K
            score = sum_cycle * num_multiply
            for j in range(K):
                score += scores[j]
                max_score = max(max_score, score)

print(max_score)
Buggy code:
import sys
sys.setrecursionlimit(10**9)

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):
  cycle = []
  nex = P[i]
  tot = 0
  nex = i
  while True:
    nex = P[nex]
    cycle.append(C[nex])
    tot += C[nex]
    if nex == i: break

  l = len(cycle)
  t = 0
  for j in range(1,l+1):
    t += cycle[j-1]
    if j > K: break
    now = t
    if tot > 0:
      now += tot*(K-j)//l
    ans = max(ans, now)


Fixed code:
import sys
sys.setrecursionlimit(10**9)

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):
  cycle = []
  tot = 0
  nex = i
  while True:
    nex = P[nex]
    cycle.append(C[nex])
    tot += C[nex]
    if nex == i: break

  l = len(cycle)
  t = 0
  for j in range(l):
    t += cycle[j]
    if j+1 > K: break
    now = t
    if tot > 0:
      now += tot*((K-(j+1))//l)
    ans = max(ans, now)

print(ans)
Buggy code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
c = [1] * N
s = [C[P[i]-1] for i in range(N)]
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        s[i] += C[P[j]-1]
        if  c[i] <= K:
            if s[i] > m[i][c[i]-1]:
                m[i][c[i]] = s[i]
            else:
                m[i][c[i]] = m[i][c[i]-1]
print(c)
print(s)
print(m)
ans = min(C)
for i in range(N):
    if s[i] > 0:
        if  s[i] * (K//c[i]) + m[i][K%c[i]] > ans:
            ans = s[i] * (K//c[i]) + m[i][K%c[i]]
    else:
        if max(m[i][1:c[i]]) > ans:
            ans = max(m[i][1:c[i]])
print(ans)


Fixed code:
N, K = map(int, input().split())
P, C = [list(map(int, input().split())) for _ in range(2)]
c = [1] * N
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
ans = max(C)
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        m[i][c[i]] = m[i][c[i]-1] + C[P[j]-1]
    if m[i][c[i]] > 0:
        ans = max(ans, m[i][c[i]] * (K//c[i]-1) + max(m[i] + [m[i][c[i]] + m[i][j+1] for j in range(K%c[i])]))
    else:
        ans = max(ans, max(m[i][1:min(c[i],K)+1]))
print(ans)
Buggy code:
from itertools import accumulate 

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

ans = -10**9-1
seen = [False]*N
for i in range(N):
    if seen[i]:
        continue
    loop = []
    now = i
    while seen[now] == False:
        seen[now] = True
        loop.append(C[now])
        now = P[now]
    loop_size = len(loop)
    loop_score = sum(loop)
    cumsum = list(accumulate(loop+loop))
    for j in range(1, loop_size+2):
        for l in range(loop_size+1):
            r = l+j
            subseq = cumsum[r] - cumsum[l]
            ans = max(ans, subseq, subseq+loop_score*((K-j)//loop_size))
print(ans)

Fixed code:
from itertools import accumulate 

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

ans = -10**18-1
seen = [False]*N
for i in range(N):
    if seen[i]:
        continue
    loop = []
    now = i
    while seen[now] == False:
        seen[now] = True
        loop.append(C[now])
        now = P[now]
    loop_size = len(loop)
    loop_score = sum(loop)
    cumsum = [0]+list(accumulate(loop+loop))
    for j in range(1, min(K, loop_size)+1):
        for l in range(loop_size+1):
            r = l+j
            subseq = cumsum[r] - cumsum[l]
            ans = max(ans, subseq, subseq+loop_score*((K-j)//loop_size))
print(ans)
Buggy code:
from itertools import accumulate
 
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]
 
check = [False] * n
loops = []
 
for i in range(n):
    if check[i]:
        continue
    check[i] = True
    next = P[i]
    tmp = [i]
    while next != i:
        check[next] = True
        tmp.append(next)
        next = P[next]
    loops.append(tmp)
 
 
ans = 0
 
for loop in loops:
 
    num = len(loop)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]
    ans_tmp = 0  
    sumL = sum(L)
    by_loop = max(sumL, 0) * div
    if k>num and sumL <= 0:
      r = num
    L += L[:r]
    ACC = [0] + list(accumulate(L))
 
    for i in range(num):
            for j in range(i+1, i+r+1):
                ans_tmp = max(ans_tmp, ACC[j] - ACC[i] + by_loop)
 
    ans = max(ans, ans_tmp)
print(ans)

Fixed code:
from itertools import accumulate
 
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]
 
check = [False] * n
loops = []
 
for i in range(n):
    if check[i]:
        continue
    check[i] = True
    next = P[i]
    tmp = [i]
    while next != i:
        check[next] = True
        tmp.append(next)
        next = P[next]
    loops.append(tmp)
 
 
ans = 0
 
for loop in loops:
 
    num = len(loop)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]
    ans_tmp = 0  
    sumL = sum(L)
    by_loop = max(sumL, 0) * div
    if k>num and sumL <= 0:
      r = num
    L += L[:r]
    ACC = [0] + list(accumulate(L))
 
    for i in range(num):
            for j in range(i+1, i+r+1):
                ans_tmp = max(ans_tmp, ACC[j] - ACC[i] + by_loop)
 
    ans = max(ans, ans_tmp)
if ans == 0:
    ans = max(C)
print(ans)
Buggy code:
from itertools import accumulate

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

seen = [False]*n
ans = -float('inf')
for i in range(n):
    if not seen[i]:
        sc = []
        stop = i
        while True:
            seen[i] = True
            sc.append(c[i])
            if p[i] == stop:
                break
            i = p[i]

        lens = len(sc)
        for j in range(lens):
            if j != 0:
                sc = sc[1:] + [sc[0]]
            ac = list(accumulate(sc))

            if sum(sc) <= 0:
                ans = max(ans, max(ac[:min(k, lens)]))
            else:
                if k%lens == 0:
                    ans = max(ans, ac[-1]*(k//lens-1) + max(ac))
                else:
                    ans = max(ans, ac[-1]*(k//lenc) + max(ac[:k%lenc]+[0]))
print(ans)

Fixed code:
from itertools import accumulate
import sys
sys.setrecursionlimit(10**8)

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

seen = [False]*n
ans = -float('inf')
for i in range(n):
    if not seen[i]:
        sc = []
        stop = i
        while True:
            seen[i] = True
            sc.append(c[i])
            if p[i] == stop:
                break
            i = p[i]

        lens = len(sc)
        for j in range(lens):
            if j != 0:
                sc = sc[1:] + [sc[0]]
            ac = list(accumulate(sc))

            if sum(sc) <= 0:
                ans = max(ans, max(ac[:min(k, lens)]))
            else:
                if k%lens == 0:
                    ans = max(ans, ac[-1]*(k//lens-1) + max(ac))
                else:
                    ans = max(ans, ac[-1]*(k//lens) + max(ac[:k%lens]))
print(ans)
Buggy code:
N, K = list(map(int, input().split()))
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))
ans = -10**9-1
for i in range(N):
    cumsum = [0]*(N+1)
    seen = [-1]*N
    K_ = K
    now = i
    j = 0
    while K_ > 0 and seen[now] == -1:
        seen[now] = 1
        now = P[now]
        cumsum[j+1] = cumsum[j] + C[now]
        K_ -= 1
        j += 1
    if K_ == 0:
        ans = max(ans, max(cumsum[1:j+1]))
    else:
        if cumsum[j] > 0:
            loop_size = j
            loop_n = K//loop_size - 1
            tmp = loop_n*cumsum[loop_size]
            tmp += max(max(cumsum[1:loop_size]), cumsum[loop_size] + max(cumsum[0:K_+1]))
            ans = max(ans, tmp)
        else:
            ans = max(ans, max(cumsum[1:j+1]))
print(ans)

Fixed code:
N, K = list(map(int, input().split()))
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))
ans = -10**9-1
for i in range(N):
    cumsum = [0]*(N+1)
    seen = [-1]*N
    K_ = K
    now = i
    j = 0
    while K_ > 0 and seen[now] == -1:
        seen[now] = 1
        now = P[now]
        cumsum[j+1] = cumsum[j] + C[now]
        K_ -= 1
        j += 1
    if K_ == 0:
        ans = max(ans, max(cumsum[1:j+1]))
    else:
        if cumsum[j] > 0:
            loop_size = j
            loop_n = K//loop_size - 1
            tmp = loop_n*cumsum[loop_size]
            tmp += max(max(cumsum[1:loop_size+1]), cumsum[loop_size] + max(cumsum[0:K_%loop_size+1]))
            ans = max(ans, tmp)
        else:
            ans = max(ans, max(cumsum[1:j+1]))
print(ans)
Buggy code:
from itertools import accumulate


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

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

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

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


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


Fixed code:
from itertools import accumulate


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

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

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

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


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


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

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

        remain_hops=K


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


Fixed code:
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)
Buggy code:
# -*- coding: utf-8 -*-
# map(int, input().split())

def junkan_max_score(junkan, C, K):
    ruiseki = [0]
    for i in range(len(junkan)):
        if i < len(junkan)-1:
            j = junkan[i+1]
        else:
            j = junkan[0]
        ruiseki.append(ruiseki[-1]+C[j])

    n_junkan = int(K/len(junkan))
    if n_junkan == 0:
        return max(ruiseki[:K])
    elif ruiseki[-1] <= 0:
        return max(ruiseki)
    else:
        junkan_score = n_junkan*ruiseki[-1]
        nokori_K = K-(n_junkan*len(junkan))
        return junkan_score+max(ruiseki[:nokori_K+1])
        

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

p_junkan = {i:[i] for i in range(N)}

for i, lst in p_junkan.items():
    j = P[i]-1
    while j != i:
        lst.append(j)
        j = P[j]-1


junkan_max = [junkan_max_score(lst, C, K) for i,lst in p_junkan.items()]
print(max(junkan_max))

Fixed code:
# -*- coding: utf-8 -*-
# map(int, input().split())

def junkan_max_score(junkan, C, K):
    ruiseki = [0]
    for i in range(len(junkan)):
        j = junkan[i]
        ruiseki.append(ruiseki[-1]+C[j])

    n_junkan = int(K/len(junkan))
    if n_junkan == 0:
        return max(ruiseki[1:K+1])
    elif ruiseki[-1] <= 0:
        return max(ruiseki[1:])
    else:
        junkan_score = n_junkan*ruiseki[-1]
        nokori_K = K-(n_junkan*len(junkan))
        if nokori_K == 0:
            return junkan_score-ruiseki[-1]+max(ruiseki[1:])
        else:
            return junkan_score+max(ruiseki[1:nokori_K+1])
        

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

p_junkan = {i:[] for i in range(1,N+1)}

for i, lst in p_junkan.items():
    j = P[i-1]
    while j != i:
        lst.append(j-1)
        j = P[j-1]
    lst.append(i-1)

junkan_max = [junkan_max_score(lst, C, K) for i,lst in p_junkan.items()]
print(max(junkan_max))
Buggy code:
n, k = map(int, input().split())
p = [int(i)-1 for i in input().split()]
c = [int(i) for i in input().split()]


def merge(p_a, c_a, p_b, c_b):
    p_c = []
    c_c = []
    for i, j in zip(p_a, c_a):
        p_c.append(p_b[i])
        c_c.append(j + c_b[i])
    return p_c, c_c


ans = -10**18
for i in range(n):
    co = 0
    for _ in range(n):
        i = p[i]
        co += c[i]
        ans = max(ans, co)

if k > n:
    k -= n
    a = list(range(n))
    b = [0] * n
    while k > 0:
        if k % 2 == 1:
            a, b = merge(a, b, p, c)
        p, c = merge(p, c, p, c)
        k //= 2
    ans = max(ans, max(b))

    for i in range(n):
        i = a[i]
        co = b[i]
        for _ in range(n):
            i = p[i]
            co += c[i]
            ans = max(ans, co)


print(ans)


Fixed code:
n, k = map(int, input().split())
p = [int(i)-1 for i in input().split()]
c = [int(i) for i in input().split()]


def merge(p_a, c_a, p_b, c_b):
    p_c = []
    c_c = []
    for i, j in zip(p_a, c_a):
        p_c.append(p_b[i])
        c_c.append(j + c_b[i])
    return p_c, c_c


ans = -10**18
for i in range(n):
    co = 0
    for _ in range(min(n, k)):
        i = p[i]
        co += c[i]
        ans = max(ans, co)

if k > n:
    pp = p[:]
    cc = c[:]
    for i in range(n):
        c[i] = cc[p[i]]
    k -= n
    a = list(range(n))
    b = [0] * n
    while k > 0:
        if k % 2 == 1:
            a, b = merge(a, b, p, c)
        p, c = merge(p, c, p, c)
        k //= 2

    #print(a, b)
    ans = max(ans,max(b))
    for i in range(n):
        co = b[i]
        i = a[i]
    #    print(i, co)
        for _ in range(n):
            i = pp[i]
            co += cc[i]
    #        print(i, co)
            ans = max(ans, co)
    #    print()

print(ans)
Buggy code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<0:ans=max(ans,max(cycle[1:k%L+1]))
    else:ans=max(ans,k//L*S+max(cycle[:k%L+1]))
print(ans)

Fixed code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:
        if k>L:ans=max(ans,(k//L-1)*S+max(max(cycle),max(cycle[:k%L+1])+S)) 
        else:ans=max(ans,max(cycle[:k+1]))
print(ans)