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: Runtime Error

Solution code:
# coding: utf-8
# Your code here!
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
    if start==now:
        flag+=1
    if start==now and flag==2:
        return [max,sum,count]
    elif count==up:
        return [max,sum,count]
    else:
        count+=1
        sum+=c[p[now-1]-1]
        if max<=sum:
            max=sum
        return find(start,p[now-1],up,max,sum,count,flag)
kara=[]
if n>k:
    for i in range(1,n+1):
        kara.append(find(i,i,k,c[p[i-1]-1],0,0,0)[0])
    result=max(kara)
else:
    for i in range(1,n+1):
        m=find(i,i,n,c[p[i-1]-1],0,0,0)
        if m[1]<=0:
            kara.append(m[0])
        else:
            w=k%m[2]
            if w==0:
                w=m[2]
            spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
            if m[1]+spe>m[0]:
                kara.append(m[1]*(k-w)//m[2]+spe)
            else:
                kara.append(m[1]*((k-w)//m[2]-1)+m[0])
    result=max(kara)
print(result)

Submission status: Runtime Error

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

import sys
if max(c[1:])<0:
    print(max(c[1:])
    sys.exit()
    

used=[0 for i in range(n+1)]
#1からn+1までの辺で試す
ans=-float("INF")
for i in range(1,n+1):
  #すでに探索したループは見なくて良い
  if used[i]==1:
    continue
  #今自分が居ることろをnow
  #一周のループの合計 loop_sum
  now=i
  loop=[i]
  loop_sum=0
  #連結部分を見つける
  while(1):
      loop.append(p[now])
      loop_sum+=c[p[now]]
      now=p[now]
      used[now]=1
      if p[now]==i:
          loop_sum+=c[p[now]]
          break
  #この連結なループの中で最大値を求める
  length=len(loop)
  cnt=0
  cost=0
  #aから始まってk回移動
  for a in loop:
      #一周する前での最大値
      max_cost=-float("INF")
      while cnt<length:
          cnt+=1
          a=p[a]
          cost+=c[a]
          max_cost=max(max_cost,cost)
          if cnt==k:
              ans=max(ans,max_cost)
              break
      if loop_sum<=0:
        ans=max(ans,max_cost)
      else:
        ans=max(ans,max_cost+(k-cnt)//n*loop_sum)
print(ans)

Submission status: Runtime Error

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

import sys
if max(c[1:])<0:
    print(max(c[1:]):
    sys.exit()
    

used=[0 for i in range(n+1)]
#1からn+1までの辺で試す
ans=-float("INF")
for i in range(1,n+1):
  #すでに探索したループは見なくて良い
  if used[i]==1:
    continue
  #今自分が居ることろをnow
  #一周のループの合計 loop_sum
  now=i
  loop=[i]
  loop_sum=0
  #連結部分を見つける
  while(1):
      loop.append(p[now])
      loop_sum+=c[p[now]]
      now=p[now]
      used[now]=1
      if p[now]==i:
          loop_sum+=c[p[now]]
          break
  #この連結なループの中で最大値を求める
  length=len(loop)
  cnt=0
  cost=0
  #aから始まってk回移動
  for a in loop:
      #一周する前での最大値
      max_cost=-float("INF")
      while cnt<length:
          cnt+=1
          a=p[a]
          cost+=c[a]
          max_cost=max(max_cost,cost)
          if cnt==k:
              ans=max(ans,max_cost)
              break
      if loop_sum<=0:
        ans=max(ans,max_cost)
      else:
        ans=max(ans,max_cost+(k-cnt)//n*loop_sum)
print(ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,k = readInts()
p = [0]+readInts()
c = [0]+readInts()

ans = -1*float("inf")
for i in range(1,n+1):
	j = p[i]
	past[j] = True
	t = [0]
	al = set()
	while j not in al:
		t.append(t[-1]+c[j])
		al.add(j)
		j = p[j]
	if t[-1]<0:
		ans = max(ans, max(t[1:k+1]))
	else:
		kuri = k//(len(t)-1)
		s = kuri*t[-1]
		ans = max(ans, max(s,s+max(t[:k-kuri*(len(t)-1)+1])))

print(ans)

Submission status: Runtime Error

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

import sys
if max(c[1:])<0:
    print(max(c[1:])):
    sys.exit()
    

used=[0 for i in range(n+1)]
#1からn+1までの辺で試す
ans=-float("INF")
for i in range(1,n+1):
  #すでに探索したループは見なくて良い
  if used[i]==1:
    continue
  #今自分が居ることろをnow
  #一周のループの合計 loop_sum
  now=i
  loop=[i]
  loop_sum=0
  #連結部分を見つける
  while(1):
      loop.append(p[now])
      loop_sum+=c[p[now]]
      now=p[now]
      used[now]=1
      if p[now]==i:
          loop_sum+=c[p[now]]
          break
  #この連結なループの中で最大値を求める
  length=len(loop)
  cnt=0
  cost=0
  #aから始まってk回移動
  for a in loop:
      #一周する前での最大値
      max_cost=-float("INF")
      while cnt<length:
          cnt+=1
          a=p[a]
          cost+=c[a]
          max_cost=max(max_cost,cost)
          if cnt==k:
              ans=max(ans,max_cost)
              break
      if loop_sum<=0:
        ans=max(ans,max_cost)
      else:
        ans=max(ans,max_cost+(k-cnt)//n*loop_sum)
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)
 
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def search(s,k, lis_p, lis_c, lis):
    if len(lis) >= k:
        return lis
    s = lis_p[s - 1]
    lis.append(lis_c[s - 1])
    return search(s, k, lis_p, lis_c, lis)

ans = -10**10
for i in range(n):
    l = search(i+1, k, p, c, [])
    d = max([sum(l[:j+1]) for j in range(len(l))])
    if d> ans:
        ans = d
print(ans)

Submission status: Runtime Error

Solution code:
import os
import sys

import numpy as np


def solve(x, t):
    visit = [0] * n
    visit[x] = 1
    loop = [0] * n
    count = 0
    ans = c[p[x] - 1]
    l = True
    sub = 0
    while True:
        x = p[x] - 1
        if l:
            if visit[x]:
                if loop[x]:
                    ln = sum(loop)
                    if t > l:
                        sub += (t // ln - 1) * count * (count > 0)
                        t %= ln
                        t += ln
                    l = False
                count += c[x]
                loop[x] = 1
            visit[x] = 1
        sub += c[x]
        t -= 1
        ans = max(sub, ans)
        if t < 1:
            return ans


# >>> numba compile >>>
numba_config = [
    [solve, "i8(i8,i8)"],
]
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:
        vars()[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)}"
    )
else:
    from numba import njit

    for func, signature in numba_config:
        vars()[func.__name__] = njit(signature, cache=True)(func)
    print("compiled!", file=sys.stderr)
# <<< numba compile <<<
(n, k), p, c = [np.int_(i.split()) for i in open(0)]
print(max(solve(i, k) for i in range(n)))

Submission status: Runtime Error

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

def search(s,k_, lis_p, lis_c, lis):
    if len(lis) >= k_:
        return lis
    s = lis_p[s - 1]
    lis.append(lis_c[s - 1])
    return search(s, k_, lis_p, lis_c, lis)

ans = -10**10
for i in range(n):
    l = search(i+1, k, p, c, [])
    d = max([sum(l[:j+1]) for j in range(len(l))])
    if d> ans:
        ans = d
print(ans)

Submission status: Runtime Error

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

ans = -10**18

for start in range(N):
    x = start
    s = []
    total = 0
    while True:
        x = p[x]
        s.append(x)
        total += c[x]
        if x == start:
            break #周期判定

    l = len(s)
    now = 0
    for i in range(l):
        now += s[i]
        if i+1 > k:
            break
        if total > 0:
            e = (K - i - 1)//l
            now += total * e
        ans = max(ans, now)

print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
    if start==now:
        flag+=1
    if start==now and flag==2:
        return [max,sum,count]
    elif count==up:
        return [max,sum,count]
    else:
        count+=1
        sum+=c[p[now-1]-1]
        if max<=sum:
            max=sum
        return find(start,p[now-1],up,max,sum,count,flag)
kara=[]
if n>k:
    for i in range(1,n+1):
        kara.append(find(i,i,k,c[p[i-1]-1],0,0,0)[0])
    result=max(kara)
else:
    for i in range(1,n+1):
        m=find(i,i,n,c[p[i-1]-1],0,0,0)
        if m[1]<=0:
            kara.append(m[0])
        else:
            w=k%m[2]
            spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
            if w==0:
                spe=0
            if m[0]>int(m[1]*(k-w)//m[2]+spe):
                kara.append(m[0])
            else:
                kara.append(int(m[1]*(k-w)//m[2]+spe))
    result=max(kara)
print(result)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
    if start==now:
        flag+=1
    if start==now and flag==2:
        return [max,sum,count]
    elif count==up:
        return [max,sum,count]
    else:
        count+=1
        sum+=c[p[now-1]-1]
        if max<=sum:
            max=sum
        return find(start,p[now-1],up,max,sum,count,flag)
kara=[]
if n>k:
    for i in range(1,n+1):
        kara.append(find(i,i,k,c[p[i-1]-1],0,0,0)[0])
    result=max(kara)
else:
    for i in range(1,n+1):
        m=find(i,i,n,c[p[i-1]-1],0,0,0)
        if m[1]<=0:
            kara.append(m[0])
        else:
            w=k%m[2]
            spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
            if w==0:
                spe=0
            if m[0]>int(m[1]*(k-w)/m[2]+spe):
                kara.append(m[0])
            else:
                kara.append(int(m[1]*(k-w)/m[2]+spe))
    result=max(kara)
print(result)

Submission status: Runtime Error

Solution code:
INF = 1*((10**9)*5000 + 1)
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

# print(n,k)
# print(P)
# print(C,end='\n\n')

vis = [False]*(n+1)
def dfs(i, c, sum_c=0):
    if vis[i]: return c, sum_c
    vis[i] = True
    c.append(C[i])
    sum_c += C[i]
    ret = dfs(P[i], c, sum_c)
    # vis[i] = False
    return ret

lst_costs = []
for i in range(n):
    costs, lp_c = dfs(i, [])
    if len(costs) == 0: continue
    lst_costs.append((costs,lp_c))

def max_calc(costs, st, num):
    len_c = len(costs)
    max_c = -INF
    sum_c = 0
    for d in range(num):
        i = (st + d) % len_c
        x = costs[i]
        sum_c += x
        max_c = max(max_c, sum_c)
    return max_c

score = -INF
for costs, lp_c in lst_costs:
    # print(costs, lp_c)
    len_c = len(costs)
    cnt, remain = divmod(k, len_c)
    for st in range(len_c):
        cost = -INF
        if lp_c <= 0:
            max_c = max_calc(costs, st, len_c)
            cost = max_c
            # print('1. cost',cost)
        else: # lp_c > 0:
            if cnt == 0:
                max_c = max_calc(costs, st, min(len_c, k))
                cost = max_c
                # print('2. cost',cost)
            else: # cnt > 0
                max_c = max_calc(costs, st, len_c + remain)
                if cnt > 1 :
                    cost = lp_c * (cnt-1)
                    cost = max({cost, cost + max_c, max_c})
                    # print('3. cost',cost)
                else: # cnt == 1
                    cost = max({lp_c, max_c})
                    # print('4. cost',cost)
        score = max({score, cost})
print(score)

Submission status: Runtime Error

Solution code:
import sys

n,k=map(int,input().split())

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

check=[0 for i in range(n)]

if max(c)<0:
    print(max(c))
    sys.exit()

ans=0

for i in range(n):
    if check[i]==0:
        cnt=0
        check[i]=1
        li=[i]
        pc=p[i]-1
        while pc!=i:
            check[pc]=1
            li.append(pc)
            pc=p[pc]-1
        sumli=0
        for j in li:
            sumli+=c[j]
        add=0
        ki=k
        if sumli>0:
            add=sumli*(k//len(li))
        if ki>len(li):
            ki=ki%len(li)
        for w in range(1,ki+1):
            sumwmax=0
            sumw=0
            for j in range(w):
                sumw+=c[li[j]]
            for j in range(len(li)):
                sumw=sumw-c[li[j]]+c[li[(j+w)%len(li)]]
                print(sumw)
                sumwmax=max(sumw,sumwmax)
            cnt=max(cnt,sumwmax)
    ans=max(ans,cnt+add)

print(ans)

Submission status: Runtime Error

Solution code:
INF = 1*((10**9)*5000 + 1)
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

# print(n,k)
# print(P)
# print(C,end='\n\n')

vis = [False]*(n+1)
def dfs(i, c, sum_c=0):
    if vis[i]: return c, sum_c
    vis[i] = True
    c.append(C[i])
    sum_c += C[i]
    ret = dfs(P[i], c, sum_c)
    # vis[i] = False
    return ret

lst_costs = []
for i in range(n):
    costs, lp_c = dfs(i, [])
    if len(costs) == 0: continue
    lst_costs.append((costs,lp_c))

def max_calc(costs, st, num):
    len_c = len(costs)
    max_c = -INF
    sum_c = 0
    for d in range(num):
        i = (st + d) % len_c
        x = costs[i]
        sum_c += x
        max_c = max(max_c, sum_c)
    return max_c

score = -INF
for costs, lp_c in lst_costs:
    # print(costs, lp_c)
    len_c = len(costs)
    cnt, remain = divmod(k, len_c)
    for st in range(len_c):
        cost = -INF
        if lp_c <= 0:
            max_c = max_calc(costs, st, len_c)
            cost = max_c
            # print('1. cost',cost)

        else: # lp_c > 0:
            if cnt == 0:
                max_c = max_calc(costs, st, min(len_c, k))
                cost = max_c
                # print('2. cost',cost)
            else: # cnt > 0
                max_c = max_calc(costs, st, len_c + remain)
                cost = lp_c * (cnt-1)
                cost = max(cost, cost + max_c)
                # print('3. cost',cost)
        score = max({score, cost})
print(score)

Submission status: Runtime Error

Solution code:
import sys

n,k=map(int,input().split())

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

check=[0 for i in range(n)]

if max(c)<0:
    print(max(c))
    sys.exit()

ans=0

for i in range(n):
    if check[i]==0:
        cnt=0
        check[i]=1
        li=[i]
        pc=p[i]-1
        while pc!=i:
            check[pc]=1
            li.append(pc)
            pc=p[pc]-1
        print(li)
        sumli=0
        for j in li:
            sumli+=c[j]
        add=0
        ki=k
        if sumli>0:
            add=sumli*(k//len(li))
        if ki>len(li):
            ki=ki%len(li)
        for w in range(1,ki+1):
            sumwmax=0
            sumw=0
            for j in range(w):
                sumw+=c[li[j]]
            for j in range(len(li)):
                sumw=sumw-c[li[j]]+c[li[(j+w)%len(li)]]
                print(sumw)
                sumwmax=max(sumw,sumwmax)
            cnt=max(cnt,sumwmax)
    ans=max(ans,cnt+add)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
if sum(C)<=0 or N>=K:
  cnt=0
  for k in C:
    if k>=0:
      break
    cnt+=1
  if cnt==N:
    print(max(C))
    sys.exit()  
  ans=0
  for i in range(N):
    score=[0]*min(K,N)
    now=i
    cr=0
    ks=0
    for j in range(N):
      now=P[now]-1
      cr+=C[now]
      score[j]=cr
      ks+=1
      if ks>=K:
        break
    #sys.stderr.write(str(score))
    ans=max(ans,max(score))
  print(ans)
else:
  t=K//N
  ansp=t*sum(C)
  s=K%N
  ans=0
  #print(sum(C)*t)
  for i in range(N):
    score=[0]*s
    now=i
    cr=0
    for j in range(s):
      now=P[now]-1
      cr+=C[now]
      score[j]=cr
    ans=max(ans,max(score))
    #print(i,score,max(score))
  print(ans+ansp)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
    if start==now:
        flag+=1
    if start==now and flag==2:
        return [max,sum,count]
    elif count==up:
        return [max,sum,count]
    else:
        count+=1
        sum+=c[p[now-1]-1]
        if max<sum:
            max=sum
        return find(start,p[now-1],up,max,sum,count,flag)
kara=[]
if n>k:
    for i in range(1,n+1):
        kara.append(find(i,i,k,c[p[i-1]-1],0,0,0)[0])
    result=max(kara)
else:
    for i in range(1,n+1):
        m=find(i,i,n,c[p[i-1]-1],0,0,0)
        if m[1]<=0:
            kara.append(m[0])
        else:
            w=k%m[2]
            spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
            if w==0:
                spe=0
            if m[0]>int(m[1]*(k-w)/m[2]+spe):
                kara.append(m[0])
            else:
                kara.append(int(m[1]*(k-w)/m[2]+spe))
    result=max(kara)
print(result)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

def check(cir,num):
    m = len(cir)
    a = sum(cir)
    if num == 1:
        ss = max(cir)
    else:
        ac = list(accumulate([0]+cir))
        l = 0
        r = 1
        ss = ac[r]-ac[l]
        i = 0
        while 1:
            if r == m:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
                ss = max(ss,ac[r]-ac[l])
                break
            elif i%2==0:
                r = ac[r+1:l+num+1].index(max(ac[r+1:l+num+1])) + r+1
            else:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
            i+=1
            ss = max(ss,ac[r]-ac[l])

        num = m-num
        l = 0
        r = num
        i = 0
        ss = max(ss,a-ac[r]+ac[l])
        while 1:
            if r == m:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
                ss = max(ss,a-ac[r]+ac[l])
                break
            elif i%2==0:
                r = ac[r+1:l+m].index(min(ac[r+1:l+m])) + r+1
            else:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
            i+=1
            ss = max(ss,a-ac[r]+ac[l])
    return ss


from itertools import accumulate

n,k = readints()
p = [x-1 for x in readints()]
c = readints()

circles = []
used = [0]*n

for i in range(n):
    if not used[i]:
        circles.append([c[i]])
        used[i] = 1
        j = p[i]
        while not used[j]:
            circles[-1].append(c[j])
            used[j] = 1
            j = p[j]

score = -10**20

for cir in circles:
    m = len(cir)
    a = sum(cir)
    if k>m:
        if a>0:
            score = max(score, (k//m)*a + check(cir,k%m), (k//m-1)*a + check(cir,m))
        else:
            score = max(score,check(cir,m))
    else:
        score = max(score,check(cir,k))

print(score)

Submission status: Runtime Error

Solution code:
INF = 1*((10**9)*5000 + 1)
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

# print(n,k)
# print(P)
# print(C,end='\n\n')

vis = [False]*(n+1)
def dfs(i, c, sum_c=0):
    if vis[i]: return c, sum_c
    vis[i] = True
    c.append(C[i])
    sum_c += C[i]
    ret = dfs(P[i], c, sum_c)
    # vis[i] = False
    return ret

lst_costs = []
for i in range(n):
    costs, lp_c = dfs(i, [])
    if len(costs) == 0: continue
    lst_costs.append((costs,lp_c))

def max_calc(costs, st, remain=0):
    len_c = len(costs)
    max_c = -INF
    sum_c = 0
    for d in range(len_c + remain):
    # for d in range(len_c):
        i = (st + d) % len_c
        x = costs[i]
        sum_c += x
        max_c = max(max_c, sum_c)
    return max_c

score = -INF
for costs, lp_c in lst_costs:
    # print(costs, lp_c)
    cnt, remain = divmod(k, len(costs))
    len_c = len(costs)
    for st in range(len_c):
        cost = -INF
        if lp_c <= 0:
            max_c = max_calc(costs, st)
            cost = max_c
            # print('1. cost',cost)

        else: # lp_c > 0:
            if cnt == 0:
                max_c = max_calc(costs, st)
                cost = max_c
                # print('2. cost',cost)

            else: # cnt > 0
                cost = lp_c * (cnt-1)
                max_c = max_calc(costs, st, remain)
                cost = max(cost, cost + max_c)

        score = max({score, cost})
print(score)

Submission status: Runtime Error

Solution code:
INF = 1*((10**9)*5000 + 1)
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

# print(n,k)
# print(P)
# print(C,end='\n\n')

vis = [False]*(n+1)
def dfs(i, c, sum_c=0):
    if vis[i]: return c, sum_c
    vis[i] = True
    c.append(C[i])
    sum_c += C[i]
    ret = dfs(P[i], c, sum_c)
    # vis[i] = False
    return ret

lst_costs = []
for i in range(n):
    costs, lp_c = dfs(i, [])
    if len(costs) == 0: continue
    lst_costs.append((costs,lp_c))

# print(*lst_costs,sep='\n',end='\n\n')

score = -INF
for costs, lp_c in lst_costs:
    # print(costs, lp_c)
    cnt, remain = divmod(k, len(costs))
    len_c = len(costs)
    for st in range(len_c):
        cost = -INF
        if lp_c <= 0:
            max_c = -INF
            sum_c = 0
            for d in range(len_c):
                i = (st + d) % len_c
                x = costs[i]
                # print(st,d,i,x)
                sum_c += x
                max_c = max(max_c, sum_c)
            cost = max_c
            # print('1. cost',cost)
        else: # lp_c > 0:
            if cnt == 0:
                max_c = -INF
                sum_c = 0
                for d in range(len_c):
                    i = (st + d) % len_c
                    x = costs[i]
                    sum_c += x
                    max_c = max(max_c, sum_c)
                cost = max_c
                # print('2. cost',cost)

            else: # cnt > 0
                cost = lp_c * (cnt-1)
                max_c = -INF
                sum_c = 0
                # for d in range(remain):
                for d in range(len_c+remain):
                    i = (st + d) % len_c
                    x = costs[i]
                    sum_c += x
                    max_c = max(max_c, sum_c)
                cost = max_c + cost
                # print('3. cost',cost)

        score = max({score, cost})
print(score)

Submission status: Runtime Error

Solution code:
INF = 1*((10**9)*5000 + 1)
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

# print(n,k)
# print(P)
# print(C,end='\n\n')

vis = [False]*(n+1)
def dfs(i, c, sum_c=0):
    if vis[i]: return c, sum_c
    vis[i] = True
    c.append(C[i])
    sum_c += C[i]
    ret = dfs(P[i], c, sum_c)
    # vis[i] = False
    return ret

lst_costs = []
for i in range(n):
    costs, lp_c = dfs(i, [])
    if len(costs) == 0: continue
    lst_costs.append((costs,lp_c))

# print(*lst_costs,sep='\n',end='\n\n')

score = -INF
for costs, lp_c in lst_costs:
    # print(costs, lp_c)
    cnt, remain = divmod(k, len(costs))
    len_c = len(costs)
    for st in range(len_c):
        cost = -INF
        if lp_c <= 0:
            max_c = -INF
            sum_c = 0
            for d in range(len_c):
                i = (st + d) % len_c
                x = costs[i]
                # print(st,d,i,x)
                sum_c += x
                max_c = max(max_c, sum_c)
            cost = max_c
            # print('1. cost',cost)
        else: # lp_c > 0:
            if cnt == 0:
                max_c = -INF
                sum_c = 0
                for d in range(len_c):
                    i = (st + d) % len_c
                    x = costs[i]
                    sum_c += x
                    max_c = max(max_c, sum_c)
                cost = max_c
                # print('2. cost',cost)

            else: # cnt > 0
                cost = lp_c * cnt
                max_c = -INF
                sum_c = 0
                for d in range(remain):
                    i = (st + d) % len_c
                    x = costs[i]
                    sum_c += x
                    max_c = max(max_c, sum_c)
                cost = max_c + cost
                # print('3. cost',cost)

        score = max({score, cost})
print(score)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(5000)
 
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
def search(s,k, lis_p, lis_c, lis):
    if len(lis) >= k:
        return lis
    s = lis_p[s - 1]
    lis.append(lis_c[s - 1])
    return search(s, k, lis_p, lis_c, lis)
 
ans = -10**10
for i in range(n):
    l = search(i+1, k, p, c, [])
    d = max([sum(l[:j+1]) for j in range(len(l))])
    if d> ans:
        ans = d
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

from itertools import accumulate

n,k = readints()
p = [x-1 for x in readints()]
c = readints()

circles = []
used = [0]*n

for i in range(n):
    if not used[i]:
        circles.append([c[i]])
        used[i] = 1
        j = p[i]
        while not used[j]:
            circles[-1].append(c[j])
            used[j] = 1
            j = p[j]


score = -10**20

for cir in circles:
    m = len(cir)
    a = sum(cir)

    if a>0:
        s = (k//m) * sum(cir)
    else:
        s = 0

    if k>m:
        if a>0:
            num = k%m
        else:
            num = m
    else:
        num = k

    if num == 0:
        ss = 0
    if num==1:
        ss = max(cir)
    else:
        ac = list(accumulate([0]+cir))
        l = 0
        r = 1
        ss = ac[r]-ac[l]
        i = 0
        while 1:
            if r == m:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
                ss = max(ss,ac[r]-ac[l])
                break
            elif i%2==0:
                r = ac[r+1:l+num+1].index(max(ac[r+1:l+num+1])) + r+1
            else:
                l = ac[l+1:r].index(min(ac[l+1:r])) + l+1
            i+=1
            ss = max(ss,ac[r]-ac[l])

        num = m-num
        l = 0
        r = num
        i = 0
        ss = max(ss,a-ac[r]+ac[l])
        while 1:
            if r == m:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
                ss = max(ss,a-ac[r]+ac[l])
                break
            elif i%2==0:
                r = ac[r+1:l+m].index(min(ac[r+1:l+m])) + r+1
            else:
                l = ac[l+1:r-num+1].index(max(ac[l+1:r-num+1])) + l+1
            i+=1
            ss = max(ss,a-ac[r]+ac[l])

    score = max(score, s+ss)

print(score)