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:
import sys
import resource
sys.setrecursionlimit(10000)
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=[-10000000000]
for i in range(1,n+1):
    m=find(i,i,n,c[p[i-1]-1],0,0,0)
    if m[2]>=k:
        m=find(i,i,k,c[p[i-1]-1],0,0,0)
        if m[0]>kara[0]:
            kara[0]=m[0]
        result=kara[0]
    elif m[1]<=0:
        if m[0]>kara[0]:
            kara[0]=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] and m[1]*(k-w)//m[2]+spe>kara[0]:
            kara[0]=m[1]*(k-w)//m[2]+spe
        elif m[1]+spe<=m[0] and m[1]*((k-w)//m[2]-1)+m[0]>kara[0]:
            kara[0]=m[1]*((k-w)//m[2]-1)+m[0]
        result=kara[0]
print(result)

Submission status: Runtime Error

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

#ループ探し
l = [0] * 5010
counter = 0
for i in range(N):
    P[i] = P[i]-1
    l[i] = []
for i in range(N):
    if P[i] == -1:
        continue
    else:
        a = i
        while True:
            #print(P, a)
            if P[a] != -1:
                l[counter].append(C[a])
                n = P[a]
                P[a] = -1
                a = n
            else:
                counter += 1
                break

#最大を考える
for i in range(counter):
    pp = []
    s = sum(l[i])
    m = len(l[i])
    l[i] = l[i] + l[i]
    #print(l[i])
    if s <= 0:
        K = min(K, m)
        for j in range(m):
            for k in range(1, K+1):
                pp.append(sum(l[i][j:j+k]))
                #print(l[i][j:j+k])
        #print(pp)
        l[i] = max(pp)
    else:
        ss = s * (K//m)
        K = K % m
        for j in range(m):
            for k in range(1, K+1):
                pp.append(sum(l[i][j:j+k]))
        l[i] = max(pp) + ss

print(max(l[0:counter]))

Submission status: Runtime Error

Solution code:
from collections import defaultdict
def f(s):
  return int(s) - 1

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

loop = []

first = -1
x = -1
loop_mem = []
cnt = 0
score = 0

rem = set(range(N))

while len(rem) > 0:
  if first < 0:
    first = rem.pop()
    x = first
  loop_mem.append(x)
  if x != first:
    rem.remove(x)
  if first != P[x]:
    cnt += 1
    score += C[x]
    x = P[x]
  else:
    cnt += 1
    score += C[x]
    loop.append((loop_mem, cnt, score))
    first = -1
    loop_mem = []
    cnt = 0
    score = 0

ans = -1e10
for loop_mem, cnt, score in loop:
  imax = [-1e10 for _ in range(cnt-1)]
  for x in loop_mem:
    tmp = 0
    for j in range(cnt - 1):
      tmp += C[x]
      imax[j] = max(imax[j], tmp)
      x = P[x]
  for j in range(1, cnt-1):
    imax[j] = max(imax[j-1], imax[j])
  if score <= 0:
    ans = max(ans, imax[-1])
  else:
    M = K // cnt
    m = K % cnt
    if M >= 1:
      tmp = max(score * M + max(imax[m-1], 0), score * (M-1) + imax[-1])
    else:
      tmp = imax[m-1]
  	ans = max(ans, tmp)

print(ans)

Submission status: Runtime Error

Solution code:
from math import inf
n,k=map(int,input().split())
arr=[0]+list(map(int,input().split()))
cost=[0]+list(map(int,input().split()))
ma=-inf
for i in range(1,n+1):
    se=set()
    cur=i
    pref=[0]
    f=0
    while(True):
        if cur not in se:
            se.add(cur)
            co=cost[cur]
            cur=arr[cur]
            pref.append(pref[-1]+co)
            ma=max(ma,pref[-1])
            f+=1
        else:
            break
        if k<=f:
            break
    print(pref)
    if k>=f:
        ans=pref[-1]*(k//f)
        for j in range(k%f+1):
            ma=max(ma,ans+pref[j])
print(ma)

Submission status: Runtime Error

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

ans=-10**20
for i in range(n):
    loop=1
    j=p[i]-1
    acm=[c[j]]
    while j!=i:
        j=p[j]-1
        acm.append(acm[-1]+c[j])
        loop+=1
    
    if acm[-1]>0:
        if k<loop:
            cur=max(acm[:k])
        else:
            cur=(k//loop)*acm[-1]
            cur=max(cur,cur+max(acm[:k%loop]))
    else:
        cur=max(acm[:min(k,loop)])
    
    ans=max(cur,ans)

print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P_L = [int(x)-1 for x in input().split()]
C_L = [int(x) for x in input().split()]

ans = float("-Inf")
for s in range(N):
    _s_l = []
    _v = s
    _cumsum = 0
    _ans = float("-Inf")
    while True:
        _nextv = P_L[_v]
        _cumsum += C_L[_nextv]
        _s_l.append(_cumsum)
        _v = _nextv
        if _nextv == s:
            break
    if K <= len(_s_l):
        _ans = max(_s_l[:K])
    else:
        if _s_l[-1] < 0:
            _ans = max(_s_l)
        else:
            _l = len(_s_l)
            _ans = max(_s_l[-1] * (K // _l) + max(_s_l[:K % _l]),
                       _s_l[-1] * (K // _l - 1) + max(_s_l))
    ans = max(ans, _ans)

print(ans)

Submission status: Runtime Error

Solution 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+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)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import itertools
import numpy as np

if __name__ == "__main__":

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

	# print(P)
	# 一度計算したサイクル情報をキャッシュしておくための配列
	cycleIDs = np.full( N, -1, np.int64 )
	cycleInfs = []
	cycleID = 0
	procCnt = 0

	for n in range(N):
		v = n

		if cycleIDs[v] != -1:
			continue
		else:
			currentCycleCosts = []
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleCosts.append( C[v] )
				cycleIDs[v] = cycleID

				v = P[v]
				if cycleIDs[v] != -1:
					# サイクル終了
					# ループを含めない最大の処理回数
					procCnt = K % len( currentCycleCosts )
					# ただし、割り切れる場合も、1サイクル分は処理するものとする
					# (1回以上はやらなければならないのを考慮？)
					if procCnt == 0:
						procCnt = len( currentCycleCosts )

					cycleInfs.append( ( procCnt, np.array( currentCycleCosts ) ) )
					cycleID += 1
					break



	scores = []
	# loopScore = 0
	# procCnt = 0
	for procCnt, currentCycleCosts in cycleInfs:

		# サイクル内でループしてスコアを稼ぐ場合の考慮
		# if np.sum(currentCycleCosts) > 0:
		# 	cycleLoopCnt =  ( K - procCnt ) // currentCycleCosts.size
		# 	loopScore = cycleLoopCnt * np.sum(currentCycleCosts)

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleCosts.size):
			if np.sum(currentCycleCosts) > 0:
				# acc = list(itertools.accumulate( np.roll( currentCycleCosts, i )[:procCnt] ) )
				scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() ) + (( K - procCnt ) // currentCycleCosts.size) * np.sum(currentCycleCosts) )
			else:
				scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() )


	print(max(scores))

Submission status: Runtime Error

Solution code:
R, C, K = map(int, input().split())
L = 4
items = [[0 for c in range(C)] for r in range(R)]
for k in range(K):
    r, c, v = map(int, input().split())
    items[r-1][c-1] = v
dp = [[[0 for limit in range(L)] for c in range(C)] for r in range(R)]
for r in range(R):
    for c in range(C):
        upper = 0 if r == 0 else max(dp[r-1][c])
        left = [0]*L if c == 0 else dp[r][c-1]
        item = items[r][c]
        dp[r][c][0] = max(upper, left[0])
        dp[r][c][1] = max(upper+item, left[1])
        dp[r][c][2] = max(left[1] + item, left[2])
        dp[r][c][3] = max(left[2] + item, left[3])
print(max(dp[R-1][C-1]))

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
A=[]
S=[]
p=2**N-1
for i in range(N):
  if p>>i&1:
    s=i+1
    tmp=[C[i]]
    while s!=P[i]:
      i=P[i]-1
      tmp.append(C[i])
      p^=1<<i
    A.append(tmp)
    S.append(sum(tmp))
ans=-1*(10**9)-1
for i in range(len(A)):
  a=A[i]
  n=len(a)
  s=S[i]
  for j in range(n):
    t=0
    k=n
    if K>n:
      if s > 0:
        k=K%n
        if :
          k=n
          t=s*(K//n-1)
        else:
          k=K%n
          t=s*(K//n)
    else:
      k=K
    for jj in range(j,k+j):
      if jj>=n:
        jj-=n
      t+=a[jj]
      ans=max(ans,t)
    ans=max(ans,t)
print(ans)

Submission status: Runtime Error

Solution code:
IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
MAX_N = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

def find_cycle(p, pos):
    cnt = 0
    steps = [0] * (MAX_N+1)
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        path[pos] = True
        cnt += 1
        break
        pos = p[pos]
        if path[pos]: break # found closure
#    st = steps.index(pos) # start of closure
    st = 0
    return [steps[:st], steps[st:cnt]]


def score(steps, c):
    ret = [0]*len(steps)
    for i in range(len(steps)): ret[i] = c[steps[i]]
    return ret

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    [preclosure_path, closure_path] = find_cycle(P, i)
    if verbose: print('closure found:', closure_path)
#    closure_scores = score(closure_path, C)
#    preclosure_scores = score(preclosure_path, C)
#    closure_score = sum(closure_scores)
#    preclosure_len, closure_len = len(preclosure_path), len(closure_path)

#    cycles = (K-preclosure_len)//closure_len
#    resid = (K-preclosure_len)%closure_len
#    if cycles>=1: cycles -= 1
#    abbrev = closure_score * cycles
   
#    trail = preclosure_scores + closure_scores * 3
#    path = preclosure_path + closure_path*3
#    if verbose: print('score trail:', trail)
#    if verbose: print('path:', preclosure_path + closure_path*3)
#    if verbose: print('mark:', mark)
#    mark = min(K, len(preclosure_path+closure_path)+resid)
#    localmax = max(cumsum(trail[0:mark])) + max(0, closure_score*cycles)
#    if verbose: print('localmax:', localmax, 'cycles:', cycles)
#    maxsc = max(localmax, maxsc)

#    if verbose: print('going greedy')
#    for j in range(1, closure_len):
#        if K<=mark+j: break
#        target = path[j]
#        if done[target]: continue
#        localmax = max(cumsum(trail[j:mark+j])) + max(0, closure_score*cycles)
#        maxsc = max(localmax, maxsc)
#        done[target] = True
#        if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Submission status: Runtime Error

Solution code:
#import random
#import itertools

IN = list(map(int, input().split())) N, K = IN[0], IN[1] P = [None] +
list(map(int, input().split())) C = [None] + list(map(int,
input().split())) MAX_N = 4500 #N = 1000 #K = 10**7 #P = [None] +
[random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i
in range(1, N+1)] #C = [None] + random.choices(range(-10**9, 10**9),
k=N)

verbose = False

def cumsum(a): tmp = [0]*(len(a)+1) for i in range(1, len(a)+1):
    tmp[i] = a[i-1] + tmp[i-1] return tmp[1:]

def find_cycle(p, pos): cnt = 0 steps = [0] * (MAX_N+1) path = [False]
    * (MAX_N+1) while True: steps[cnt] = pos path[pos] = True cnt += 1
    break pos = p[pos] if path[pos]: break # found closure # st =
    steps.index(pos) # start of closure st = 0 return [steps[:st],
    steps[st:cnt]]


def score(steps, c): ret = [0]*len(steps) for i in range(len(steps)):
    ret[i] = c[steps[i]] return ret

maxsc = -10**9-1 done = [False] * (N+1) for i in range(1, N+1): if
verbose: print('entering', i) if done[i]: continue [preclosure_path,
closure_path] = find_cycle(P, i) if verbose: print('closure found:',
closure_path) # closure_scores = score(closure_path, C) #
preclosure_scores = score(preclosure_path, C) # closure_score =
sum(closure_scores) # preclosure_len, closure_len =
len(preclosure_path), len(closure_path)

#    cycles = (K-preclosure_len)//closure_len resid =
#    (K-preclosure_len)%closure_len if cycles>=1: cycles -= 1 abbrev =
#    closure_score * cycles
   
#    trail = preclosure_scores + closure_scores * 3 path =
#    preclosure_path + closure_path*3 if verbose: print('score
#    trail:', trail) if verbose: print('path:', preclosure_path +
#    closure_path*3) if verbose: print('mark:', mark) mark = min(K,
#    len(preclosure_path+closure_path)+resid) localmax =
#    max(cumsum(trail[0:mark])) + max(0, closure_score*cycles) if
#    verbose: print('localmax:', localmax, 'cycles:', cycles) maxsc =
#    max(localmax, maxsc)

#    if verbose: print('going greedy') for j in range(1, closure_len):
#    if K<=mark+j: break target = path[j] if done[target]: continue
#    localmax = max(cumsum(trail[j:mark+j])) + max(0,
#    closure_score*cycles) maxsc = max(localmax, maxsc) done[target] =
#    True if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Submission status: Runtime Error

Solution code:

IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
MAX_N = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

def find_cycle(p, pos):
    cnt = 0
    steps = [0] * (MAX_N+1)
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        path[pos] = True
        pos = p[pos]
        cnt += 1
        break
        if path[pos]: break # found closure
#    st = steps.index(pos) # start of closure
    st = 0
    return [steps[:st], steps[st:cnt]]


def score(steps, c):
    ret = [0]*len(steps)
    for i in range(len(steps)): ret[i] = c[steps[i]]
    return ret

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    [preclosure_path, closure_path] = find_cycle(P, i)
    if verbose: print('closure found:', closure_path)
#    closure_scores = score(closure_path, C)
#    preclosure_scores = score(preclosure_path, C)
#    closure_score = sum(closure_scores)
#    preclosure_len, closure_len = len(preclosure_path), len(closure_path)

#    cycles = (K-preclosure_len)//closure_len
#    resid = (K-preclosure_len)%closure_len
#    if cycles>=1: cycles -= 1
#    abbrev = closure_score * cycles
   
#    trail = preclosure_scores + closure_scores * 3
#    path = preclosure_path + closure_path*3
#    if verbose: print('score trail:', trail)
#    if verbose: print('path:', preclosure_path + closure_path*3)
#    if verbose: print('mark:', mark)
#    mark = min(K, len(preclosure_path+closure_path)+resid)
#    localmax = max(cumsum(trail[0:mark])) + max(0, closure_score*cycles)
#    if verbose: print('localmax:', localmax, 'cycles:', cycles)
#    maxsc = max(localmax, maxsc)

#    if verbose: print('going greedy')
#    for j in range(1, closure_len):
#        if K<=mark+j: break
#        target = path[j]
#        if done[target]: continue
#        localmax = max(cumsum(trail[j:mark+j])) + max(0, closure_score*cycles)
#        maxsc = max(localmax, maxsc)
#        done[target] = True
#        if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Submission status: Runtime Error

Solution code:
IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
MAX_N = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

def find_cycle(p, pos):
    cnt = 0
    steps = [0] * (MAX_N+1)
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        path[pos] = True
        pos = p[pos]
        cnt += 1
        break
        if path[pos]: break # found closure
    st = steps.index(pos) # start of closure
    return [steps[:st], steps[st:cnt]]


def score(steps, c):
    ret = [0]*len(steps)
    for i in range(len(steps)): ret[i] = c[steps[i]]
    return ret

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    [preclosure_path, closure_path] = find_cycle(P, i)
    if verbose: print('closure found:', closure_path)
#    closure_scores = score(closure_path, C)
#    preclosure_scores = score(preclosure_path, C)
#    closure_score = sum(closure_scores)
#    preclosure_len, closure_len = len(preclosure_path), len(closure_path)

#    cycles = (K-preclosure_len)//closure_len
#    resid = (K-preclosure_len)%closure_len
#    if cycles>=1: cycles -= 1
#    abbrev = closure_score * cycles
   
#    trail = preclosure_scores + closure_scores * 3
#    path = preclosure_path + closure_path*3
#    if verbose: print('score trail:', trail)
#    if verbose: print('path:', preclosure_path + closure_path*3)
#    if verbose: print('mark:', mark)
#    mark = min(K, len(preclosure_path+closure_path)+resid)
#    localmax = max(cumsum(trail[0:mark])) + max(0, closure_score*cycles)
#    if verbose: print('localmax:', localmax, 'cycles:', cycles)
#    maxsc = max(localmax, maxsc)

#    if verbose: print('going greedy')
#    for j in range(1, closure_len):
#        if K<=mark+j: break
#        target = path[j]
#        if done[target]: continue
#        localmax = max(cumsum(trail[j:mark+j])) + max(0, closure_score*cycles)
#        maxsc = max(localmax, maxsc)
#        done[target] = True
#        if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Submission status: Runtime Error

Solution code:
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):
    piece = i+1
    temp = 0
    hoge = []
    hogehoge = []
    key = 0
    for j in range(N):
        if j+1 > K:
            key = 1
            break
        piece = P[piece-1]
        temp += C[piece-1]
        hogehoge.append(C[piece-1])
        hoge.append(temp)
        if piece == i+1:
            break
    if key == 1:
        ans = max(ans,max(hoge))
    elif hoge[-1]<=0:
        ans = max(ans,max(hoge))
    else:
        d = K//len(hoge)
        r = K%len(hoge)
        peak = max(hoge[-1]*(d-1)+max(hoge[r:]),hoge[-1]*d+max(hoge[:r]))
        ans = max(ans,peak)
print(ans)

Submission status: Runtime Error

Solution code:

IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
MAX_N = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

def find_cycle(p, pos):
    cnt = 0
    steps = [0] * (MAX_N+1)
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        path[pos] = True
        pos = p[pos]
        cnt += 1
        if path[pos]: break # found closure
    print(steps[:10])
    st = steps.index(pos) # start of closure
    return [steps[:st], steps[st:cnt]]


def score(steps, c):
    ret = [0]*len(steps)
    for i in range(len(steps)): ret[i] = c[steps[i]]
    return ret

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    [preclosure_path, closure_path] = find_cycle(P, i)
    if verbose: print('closure found:', closure_path)
#    closure_scores = score(closure_path, C)
#    preclosure_scores = score(preclosure_path, C)
#    closure_score = sum(closure_scores)
#    preclosure_len, closure_len = len(preclosure_path), len(closure_path)

#    cycles = (K-preclosure_len)//closure_len
#    resid = (K-preclosure_len)%closure_len
#    if cycles>=1: cycles -= 1
#    abbrev = closure_score * cycles
   
#    trail = preclosure_scores + closure_scores * 3
#    path = preclosure_path + closure_path*3
#    if verbose: print('score trail:', trail)
#    if verbose: print('path:', preclosure_path + closure_path*3)
#    if verbose: print('mark:', mark)
#    mark = min(K, len(preclosure_path+closure_path)+resid)
#    localmax = max(cumsum(trail[0:mark])) + max(0, closure_score*cycles)
#    if verbose: print('localmax:', localmax, 'cycles:', cycles)
#    maxsc = max(localmax, maxsc)

#    if verbose: print('going greedy')
#    for j in range(1, closure_len):
#        if K<=mark+j: break
#        target = path[j]
#        if done[target]: continue
#        localmax = max(cumsum(trail[j:mark+j])) + max(0, closure_score*cycles)
#        maxsc = max(localmax, maxsc)
#        done[target] = True
#        if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Submission status: Runtime Error

Solution code:
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):
    piece = i+1
    temp = 0
    hoge = []
    key = 0
    for j in range(N):
        piece = P[piece-1]
        temp += C[piece-1]
        hoge.append(temp)
        if j+1 > K:
            key = 1
            break
        if piece == i+1:
            break
    if key == 1:
        ans = max(ans,max(hoge))
    elif hoge[-1]<=0:
        ans = max(ans,max(hoge))
    else:
        d = K//len(hoge)
        r = K%len(hoge)
        peak = max(hoge[-1]*(d-1)+max(hoge[r:]),hoge[-1]*d+max(hoge[:r]))
        ans = max(ans,peak)
print(ans)

Submission status: Runtime Error

Solution code:
IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
MAX_N = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

def find_cycle(p, pos):
    cnt = 0
    steps = [0] * (MAX_N+1)
    path = [False] * (MAX_N+1)
    while True:
        steps[cnt] = pos
        path[pos] = True
        pos = p[pos]
        cnt += 1
        if path[pos]: break # found closure
    st = steps.index(pos)-1 # start of closure
    return [steps[:st], steps[st:cnt-1]]


def score(steps, c):
    ret = [0]*len(steps)
    for i in range(len(steps)): ret[i] = c[steps[i]]
    return ret

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    [preclosure_path, closure_path] = find_cycle(P, i)
#    if verbose: print('closure found:', closure_path)
#    closure_scores = score(closure_path, C)
#    preclosure_scores = score(preclosure_path, C)
#    closure_score = sum(closure_scores)
#    preclosure_len, closure_len = len(preclosure_path), len(closure_path)

#    cycles = (K-preclosure_len)//closure_len
#    resid = (K-preclosure_len)%closure_len
#    if cycles>=1: cycles -= 1
#    abbrev = closure_score * cycles
   
#    trail = preclosure_scores + closure_scores * 3
#    path = preclosure_path + closure_path*3
#    if verbose: print('score trail:', trail)
#    if verbose: print('path:', preclosure_path + closure_path*3)
#    if verbose: print('mark:', mark)
#    mark = min(K, len(preclosure_path+closure_path)+resid)
#    localmax = max(cumsum(trail[0:mark])) + max(0, closure_score*cycles)
#    if verbose: print('localmax:', localmax, 'cycles:', cycles)
#    maxsc = max(localmax, maxsc)

#    if verbose: print('going greedy')
#    for j in range(1, closure_len):
#        if K<=mark+j: break
#        target = path[j]
#        if done[target]: continue
#        localmax = max(cumsum(trail[j:mark+j])) + max(0, closure_score*cycles)
#        maxsc = max(localmax, maxsc)
#        done[target] = True
#        if verbose: print('done:', target, 'with', localmax)

print(maxsc)

Submission status: Runtime Error

Solution code:
IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = [None] + list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
MAX_N = 4500
#N = 1000
#K = 10**7
#P = [None] + [random.choice(list(itertools.chain(range(1,i), range(i+1,N)))) for i in range(1, N+1)]
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

def find_cycle(p, pos):
    cnt = 0
    steps = [0] * (MAX_N+1)
    path = [False] * (MAX_N+1)
#    while True:
#        steps[cnt] = pos
#        pos = p[pos]
#        cnt += 1
#        if path[pos]:
#            break # found closure
#        else:
#            path[pos] = True
    st = steps.index(pos)-1 # start of closure
    return [steps[:st], steps[st:cnt-1]]

def score(steps, c):
    ret = [0]*len(steps)
    for i in range(len(steps)): ret[i] = c[steps[i]]
    return ret

maxsc = -10**9-1
done = [False] * (N+1)
for i in range(1, N+1):
    if verbose: print('entering', i)
    if done[i]: continue
    [preclosure_path, closure_path] = find_cycle(P, i)
#    if verbose: print('closure found:', closure_path)
#    closure_scores = score(closure_path, C)
#    preclosure_scores = score(preclosure_path, C)
#    closure_score = sum(closure_scores)
#    preclosure_len, closure_len = len(preclosure_path), len(closure_path)

#    cycles = (K-preclosure_len)//closure_len
#    resid = (K-preclosure_len)%closure_len
#    if cycles>=1: cycles -= 1
#    abbrev = closure_score * cycles
   
#    trail = preclosure_scores + closure_scores * 3
#    path = preclosure_path + closure_path*3
#    if verbose: print('score trail:', trail)
#    if verbose: print('path:', preclosure_path + closure_path*3)
#    if verbose: print('mark:', mark)
#    mark = min(K, len(preclosure_path+closure_path)+resid)
#    localmax = max(cumsum(trail[0:mark])) + max(0, closure_score*cycles)
#    if verbose: print('localmax:', localmax, 'cycles:', cycles)
#    maxsc = max(localmax, maxsc)

#    if verbose: print('going greedy')
#    for j in range(1, closure_len):
#        if K<=mark+j: break
#        target = path[j]
#        if done[target]: continue
#        localmax = max(cumsum(trail[j:mark+j])) + max(0, closure_score*cycles)
#        maxsc = max(localmax, maxsc)
#        done[target] = True
#        if verbose: print('done:', target, 'with', localmax)

print(maxsc)