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:
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 = 2000
#K = 10**7
#P = [None] + random.sample(range(1, N+1), k=N)
#C = [None] + random.choices(range(-10**9, 10**9), k=N)

verbose = False
g = {}
for i in range(1, N+1): g.update({i: P[i-1]})

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

Submission status: Runtime Error

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

loop_num = [ 0 for i in range( N ) ]
loop_val = [ 0 for i in range( N ) ]

each_max = [ 0 for i in range( N ) ]

loop_ok = [ 1 for i in range( N ) ]

x = 1
num = 0
val = 0
for i in range( N ):
    num = 0
    val = 0
    x = i - 1
    flag = 0
    while x != i and loop_ok[x] == 1:
        if flag == 0:
            x = i
            flag += 1
        loop_ok[x] = 0
        x = P[x] - 1
        num += 1
        val += C[x]

    loop_num[i] = num
    loop_val[i] = val
    if K < num:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( K ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value
        each_max[i] = maxx
    else:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( num ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value

        sho = K // num
        amari = K % num
        max_ = val * sho
        max_dash = 0
        value = 0
        x = i
        for j in range( amari ):
            x = P[x] - 1
            value += C[x]
            if max_dash < value:
                max_dash = value
        max_ += max_dash
        each_max[i] = max( maxx , max_ )



#print(loop_num,loop_val)

print( int( max(each_max) ) )

Submission status: Runtime Error

Solution 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 = -10 ** 18
for si in range(N):
    KK = K
    x = si
    c = []
    tot = 0
    while True:
        x = P[x]
        c.append(C[x])
        tot += C[x]
        if x == si:
            break

    s = 0
    if KK > N:
        sho = KK // len(c)
        yo = KK % len(c)
        KK = yo
        if tot > 0:
            s += tot * sho
    for k in range(KK):
        s += c[k]
        ans = max(s, ans)

print(ans)

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 = -1e18

for i in range(n):
    now = p[i] - 1 
    score = [c[now]]
    while True:
        now = p[now] - 1
        score.append(score[-1] + c[now])
        if now == i:
            break
    loopsum = score[-1]
    looplen = len(score)
    if looplen >= k:
        ans = max(ans,max(score[:k]))
    if loopsum <= 0:
        ans = max(ans,max(score))
    else:
        loopnum = k//looplen
        loopnum_mod = k % looplen
        ans = max(ans,(loopnum-1)*loopsum + max(score))    
        ans = max(ans,loopnum*loopsum+max(score[:loopnum_mod]))

print(ans)

Submission status: Runtime Error

Solution code:
# 公式解説を見てからやった
# 複数サイクルでき、1-K回移動可能
# N < 5000?多分、O(N * 2N)くらいで行けそうに見えるが。。。

if __name__ == "__main__":

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

	# 一度計算したサイクル情報を一応キャッシュしておく。。。
	# あんまり意味なさそう
	cycleIDs = [ -1 for _ in range(N) ]
	cycleInfs = []


	# print(P)

	ans = -1e19
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			currentCycleItemCnt, currentCycleTotal = cycleInfs[ cycleIDs[v] ]
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleInfs.append( (currentCycleItemCnt, currentCycleTotal) )
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID

		procCnt = 0
		currentCycleSumTmp = 0

		while True:

			# 頂点vにコマが置かれた時の最高スコアを計算し、
			# これまでの最高スコアを上回ったら、これまでの最高スコアを更新する
			procCnt += 1
			currentCycleSumTmp += C[v]
			if K < procCnt:
				break

			cycleLoopCnt = 0
			if procCnt < K and 0 < currentCycleTotal:
				cycleLoopCnt = ( K - procCnt ) // currentCycleItemCnt

			print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, "procCnt, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( ans, tmp )

			v = P[v]
			if v == n:
				# サイクル終了
				break

	print(ans)

Submission status: Runtime Error

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

M=[[0]*(k+1) for _ in range(n)]
for j in range(1,k+1):
    for i in range(1,n):
        M[i][j]=M[s[i]][j-1]+c[s[i]]

ans=-1e10
for i in range(1,n):
    ans=max(ans,max(M[i][1:]))

print(ans)

Submission status: Runtime Error

Solution code:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N,K = LMIIS()
    P = list(map(lambda x: int(x)-1,input().split()))
    C = LMIIS()
    score_sets = []
    used = [False]*N
    tmp = P[0]
    for i in range(N):
        if not used[i]:
            tmp = i
            score_set = []
            while not used[tmp]:
                used[tmp] = True
                tmp = P[tmp]
                score_set.append(C[tmp])
            score_sets.append(score_set)
        
    ans = -INF
    for score_set in score_sets:
        # 合計が最大になる区間を探す
        len_set = len(score_set)
        sum_score_set_real = sum(score_set)
        sum_score_set = max(0,sum_score_set_real)


        
        for i in range(len_set):
            cum_sum_1 = 0
            for j in range(i,min(len_set, i+K)):
                cum_sum_1 += score_set[j]
                num_move = j-i+1
                tmp_max = cum_sum_1 + (K - num_move) // len_set * sum_score_set
                ans = max(ans, tmp_max)

        for i in range(1,len_set-1):
            cum_sum_2 = sum_score_set_real
            for j in range(i,len_set-1-(K-i)):
                cum_sum_2 -= score_set[j]
            for j in range(max(i,len_set-1-(K-i)),len_set-1):
                cum_sum_2 -= score_set[j]
                num_move = len_set - (j-i+1)
                tmp_max = cum_sum_2 + (K - num_move) // len_set * sum_score_set
                ans = max(ans,tmp_max)






        
                
    print(ans)

    
main()

Submission status: Runtime Error

Solution code:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N,K = LMIIS()
    P = list(map(lambda x: int(x)-1,input().split()))
    C = LMIIS()
    score_sets = []
    used = [False]*N
    tmp = P[0]
    for i in range(N):
        if not used[i]:
            tmp = i
            score_set = []
            while not used[tmp]:
                used[tmp] = True
                tmp = P[tmp]
                score_set.append(C[tmp])
            score_sets.append(score_set)
        
    ans = -INF
    for score_set in score_sets:
        # 合計が最大になる区間を探す
        len_set = len(score_set)
        sum_score_set_real = sum(score_set)
        sum_score_set = max(0,sum_score_set_real)


        
        for i in range(len_set):
            cum_sum_1 = 0
            for j in range(i,min(len_set, i+K)):
                cum_sum_1 += score_set[j]
                num_move = j-i+1
                tmp_max = cum_sum_1 + (K - num_move) // len_set * sum_score_set
                ans = max(ans, tmp_max)
        for i in range(1,len_set-1):
            cum_sum_2 = sum_score_set_real
            for j in range(i,len_set-(K-i)):
                cum_sum_2 -= score_set[j]
            for j in range(max(i,len_set-(K-i)),len_set-1):
                cum_sum_2 -= score_set[j]
                num_move = len_set - (j-i+1)
                tmp_max = cum_sum_2 + (K - num_move) // len_set * sum_score_set
                ans = max(ans,tmp_max)
                
    print(ans)

    
main()

Submission status: Runtime Error

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

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

rc = [0] * n
rp = [0] * n
for i in range(n):
    if rc[i]!=0:
        continue
    else:
        nw = set([i])
        np = c[i]
        nx = p[i]
        while not nx in nw:
            nw.add(nx)
            np += c[nx]
            nx = p[nx]
        cnt = len(nw)
        for x in nw:
            rc[x] = cnt
            rp[x] = np
ret = - 10 ** 18
for i in range(n):
    if rc[i] == 1:
        if rp[i]>=0:
            ret = max(ret, k*rp[i])
        else:
            ret = max(ret, rp[i])
        continue
    pseq = [0]
    nx = p[i]
    for j in range(1,rc[i]+1):
        pseq.append(pseq[-1]+c[nx])
        nx = p[nx]
    pseq = pseq[1:]
    if k <= rc[i]:
        ret = max(ret, max(pseq[:k]))
    elif rp[i] < 0:
        ret = max(ret, max(pseq))
    else:
        tmp = max(pseq)
        tmp = max(tmp, rp[i] + max(pseq[:k%rc[i]]))
        tmp += rp[i]*(k//rc[i]-1)
        ret = max(ret, tmp)
print(ret)

Submission status: Runtime Error

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

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

rc = [0] * n
rp = [0] * n

for i in range(n):
    if rc[i]!=0:
        continue
    else:
        nw = set([i])
        np = c[i]
        nx = p[i]
        while not nx in nw:
            nw.add(nx)
            np += c[nx]
            nx = p[nx]
        cnt = len(nw)
        for x in nw:
            rc[x] = cnt
            rp[x] = max(0, np)
ret = - 10 ** 18
for i in range(n):
    pseq = [0]
    nx = p[i]
    for j in range(1,rc[i]+1):
        pseq.append(pseq[-1]+c[nx])
        nx = p[nx]
    pseq = pseq[1:]
    if k <= rc[i]:
        ret = max(ret, max(pseq[:k]))
    elif rp[i] < 0:
        ret = max(ret, max(pseq))
    else:
        tmp = max(pseq)
        tmp = max(tmp, rp[i] + max(pseq[:k%rc[i]]))
        tmp += rp[i]*(k//rc[i]-1)
        ret = max(ret, tmp)
print(ret)

Submission status: Runtime Error

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

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

rc = [0] * n
rp = [0] * n

for i in range(n):
    if rc[i]!=0:
        continue
    else:
        nw = set([i])
        np = c[i]
        nx = p[i]
        while not nx in nw:
            nw.add(nx)
            np += c[nx]
            nx = p[nx]
        cnt = len(nw)
        for x in nw:
            rc[x] = cnt
            rp[x] = max(0, np)
ret = - 10 ** 18
for i in range(n):
    pseq = [0]
    nx = p[i]
    for j in range(1,rc[i]+1):
        pseq.append(pseq[-1]+c[nx])
        nx = p[nx]
    pseq = pseq[1:]
    if k <= rc[i]:
        ret = max(ret, max(pseq[:k]))
    elif rp[i] < 0:
        ret = max(ret, max(pseq))
    else:
        tmp = max(pseq)
        tmp = max(tmp, rp[i] + max(pseq[:k%rc[i]]))
        tmp += rp[i]*(k//rc[i]-1)
        ret = max(ret, tmp)
print(ret)

Submission status: Runtime Error

Solution code:
def main():
    INF = 10**9
    n,k = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))

    scores = [0]*n

    for s in range(n):
        start = s
        dp = [-INF]*(n+1)
        dp[0] = 0
        for i in range(n):
            p = P[s]-1
            dp[i+1] = dp[i] + C[p]
            
            if start == p:
                break
            s = p

        if k < i+1:
            scores[start] = max(dp[1:k+1])
        elif dp[i+1]<=0:
            scores[start] = max(dp[1:])
        else:
            r = k%(i+1)
            q = k//(i+1)
            scores[start] = max(max(dp[1:r+1])+dp[i+1]*q, max(dp[1:]))
    
    print(max(scores))
main()

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=list(map(int, input().split()))
c=list(map(int, input().split()))
s=sum(c)
def f(x,m):
  tmp=0
  a=0
  for i in range(x):
    tmp+=c[m]
    a=max(a,tmp)
    m=p[m]
  return a
if s>0:
  ans=s*(k//n)
  tmp=0
  for i in range(n):
    tmp=max(tmp, f(i,k%n))
  ans+=tmp
else:
  ans=0
  for i in range(n):
    ans=max(ans, f(i,min(n,k)))
print(ans)

Submission status: Runtime Error

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

k-=1

m=int(log2(k))
nxt=[[0]*n for _ in range(m+1)]
point=[[0]*n for _ in range(m+1)]
for i in range(n):
  p[i]-=1
  nxt[0][i]=p[i]
  point[0][i]=c[p[i]]
for j in range(m):
  for i in range(n):
    nxt[j+1][i]=nxt[j][nxt[j][i]]
    point[j+1][i]=point[j][i]+point[j][nxt[j][i]]
min_nk=min(n,k)
ans=-10**18
for s in range(n):
  pla=p[s]
  cur=c[pla]
  if ans<cur:
    ans=cur
  for _ in range(min_nk):
    pla=p[pla]
    cur+=c[pla]
    if ans<cur:
      ans=cur
  if n<k:
    pla=p[s]
    cur=c[pla]
    for i in range(m+1):
      if (k-n)&(1<<i):
        cur+=point[i][pla]
        pla=nxt[i][pla]
    res=cur
    for _ in range(n):
      pla=p[pla]
      cur+=c[pla]
      if res<cur:
        res=cur
    if ans<res:
      ans=res
print(ans)

Submission status: Runtime Error

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

k-=1

m=int(log2(k))
nxt=[[0]*n for _ in range(m+1)]
point=[[0]*n for _ in range(m+1)]
for i in range(n):
  p[i]-=1
  nxt[0][i]=p[i]
  point[0][i]=c[p[i]]
for j in range(m):
  for i in range(n):
    nxt[j+1][i]=nxt[j][nxt[j][i]]
    point[j+1][i]=point[j][i]+point[j][nxt[j][i]]
min_nk=min(n,k)
ans=-10**18
for s in range(n):
  pla=p[s]
  cur=c[pla]
  if ans<cur:
    ans=cur
  for _ in range(min_nk):
    pla=p[pla]
    cur+=c[pla]
    if ans<cur:
      ans=cur
  if True:
    pla=p[s]
    cur=c[pla]
    for i in range(m+1):
      if (k-n)&(1<<i):
        cur+=point[i][pla]
        pla=nxt[i][pla]
    res=cur
    for _ in range(n):
      pla=p[pla]
      cur+=c[pla]
      if res<cur:
        res=cur
    if ans<res:
      ans=res
print(ans)

Submission status: Runtime Error

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

k-=1

m=int(log2(k))
nxt=[[0]*n for _ in range(m+1)]
point=[[0]*n for _ in range(m+1)]
for i in range(n):
  p[i]-=1
  nxt[0][i]=p[i]
  point[0][i]=c[p[i]]
for j in range(m):
  for i in range(n):
    nxt[j+1][i]=nxt[j][nxt[j][i]]
    point[j+1][i]=point[j][i]+point[j][nxt[j][i]]

ans=-10**18
for s in range(n):
  if k<=n:
    pla=p[s]
    cur=c[pla]
    res=cur
    for _ in range(k):
      pla=p[pla]
      cur+=c[pla]
      if res<cur:
        res=cur
    if ans<res:
      ans=res
  else:
    pla=p[s]
    cur=c[pla]
    for i in range(m+1):
      if (k-n)&(1<<i):
        cur+=point[i][pla]
        pla=nxt[i][pla]
    res=cur
    for _ in range(n):
      pla=p[pla]
      cur+=c[pla]
      if res<cur:
        res=cur
    if ans<res:
      ans=res
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
pos = [int(i)-1 for i in input().split()]
c = list(map(int, input().split()))
ret = - 10**18
for i in range(n):
    nowsum = [0]
    nxtpos = pos[i]
    while nxtpos != i:
        nowsum.append(nowsum[-1]+c[nxtpos])
        nxtpos = pos[nxtpos]
    nowsum.append(nowsum[-1]+c[nxtpos])
    nowsum = nowsum[1:]
    if k<len(nowsum):
        ret = max(ret, max(nowsum[:k]))
    else:
        if nowsum[-1]<0:
            ret = max(ret, max(nowsum))
        else:
            ret = max(ret, nowsum[-1]*(k//len(nowsum)-1)+max(max(nowsum), nowsum[-1]+max(nowsum[:k%len(nowsum)])))
print(ret)

Submission status: Runtime Error

Solution code:

            break

    if sum(tensuulist)<=0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu%=syuki
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

print(ans)

Submission status: Runtime Error

Solution code:
//他人のソースコードを借りています。

from itertools import accumulate

N, K, *PC = map(int, open(0).read().split())
P, C = [0] + PC[:N], [0] + PC[N:]

ans = float("-inf")
for start in range(1, N + 1):
    path = []

    cur = P[start]
    path = [C[start]]
    while cur != start:
        path.append(C[cur])
        cur = P[cur]

    A = list(accumulate(path))
    q, r = divmod(K, len(path))
    res = 0
    if A[-1] >= 0:
        if r == 0:
            q -= 1
            r += len(path)
        res += A[-1] * q
    elif q >= 1:
        r = len(path)

    ans = max(ans, res + max(A[:r]))

print(ans)

Submission status: Runtime Error

Solution code:
//他人のソースコードを借りています・

n, k = [int(e) for e in input().split()]
p =  [int(e) for e in input().split()]
c =  [int(e) for e in input().split()]
 
 
t = k // n
k %= n
 
if k == 0:
    t -= 1
    k = n
 
w = sum(c)
if w > 0:
    s = w * t
else:
    s = 0
 
u = - 10 ** 9
for i in range(n):
    m = p[i] - 1
    l = [c[m]]
    for j in range(1, k):
        m = p[m] - 1
        l.append(l[-1] + c[m])
    l.sort()
    if l[-1] > u:
        u = l[-1]
 
print(s + u)

Submission status: Runtime Error

Solution code:
import itertools
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -10**20
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cycle, residue = divmod(K, cyclelen)
    scores *= 2
    scores = list(itertools.accumulate(scores))
    st = SegmentTree(scores, max, -10**20)
    ans = max(
        [ans] +
        [st.query(start2 + 1, start2 + K + 1) for start2 in range(cyclelen)])
    if scores[-1] > 0 and cycle > 0:
        ans2 = scores[-1] * cycle // 2
        v = max(
            st.query(start2 + 1, start2 + residue + 1) - scores[start2]
            for start2 in range(cyclelen))
        ans = max([ans, ans2, ans2 + v])

print(ans)

Submission status: Runtime Error

Solution code:
import numpy

N,K = map(int, input().split())
P_list = [0] + [int(e) for e in input().split()]
C_list = [0] + [int(e) for e in input().split()]

#Pがすべて異なるので、別のに交わるループは存在しない
#どんな風に駒が動き、スコアを重ねるかを整理する
moved_set = set()

all_organaized_P_list = list()
all_organaized_C_list = list()

for i in range(1,N+1):
    if i not in moved_set:
        now = i
        next = P_list[now]
        moved_set.add(now)
        organaized_C_list = list()
        organaized_C_list.append(C_list[now])

        while 1:
            if next in moved_set:
                break
            else:
                now = next
                next = P_list[now]
                moved_set.add(now)
                organaized_C_list.append(C_list[now])
                
        all_organaized_C_list.append(organaized_C_list)

#print(all_organaized_C_list)

#整理したループ毎に得点を求める
def get_loop_ans(organaized_C_list):
    #ループしない場合の得点を求める
    ans = max(organaized_C_list)
    #print(res)
    repeated_C_list = organaized_C_list + organaized_C_list
    
    for i in range(0,len(organaized_C_list)):
        temp_ans = list()
        temp_ans.append(repeated_C_list[i])

        for j in range(1,min(K+1,len(organaized_C_list))):
            temp_ans.append(temp_ans[-1]+repeated_C_list[i+j])

        temp_ans.append(ans)
        ans = max(temp_ans)
    
    in_loop_ans = ans
    loop_ans = sum(organaized_C_list)
    
    #print("#",in_loop_ans,loop_ans)
    if loop_ans < 0:
        return in_loop_ans
    else:
        return in_loop_ans + loop_ans*(K//len(organaized_C_list))

ans = max(C_list[1:])

for organaized_C_list in all_organaized_C_list:
    temp_ans = get_loop_ans(organaized_C_list)
    #print(organaized_C_list,temp_ans)
    ans = max(ans,temp_ans)
    
print(ans)

Submission status: Runtime Error

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

from itertools import accumulate

def calc_score():
    score = []
    flg = False
    ans = -10**18
    for i in range(1,n+1):
        score = []
        visit = [False] * (n + 1)
        for t in range(1, k+1):
            if visit[i]:
                # ループ検出
                flg = True
                break
            visit[i] = True
            score.append(c[i])
            i = p[i]
        
        score_cumsum = list(accumulate(score))
        max_score = max(score_cumsum)
        # print(score)
        # print(score_cumsum)

        # ループあり
        if flg:
            q,r = divmod(k, sum(visit))
            # print(q,r)
            ans = max(ans, q * sum(score) + max(score_cumsum[:r]), max_score)
        else:
            ans = max(ans, max_score)
    
    return ans

print(calc_score())

Submission status: Runtime Error

Solution code:
import numpy as np

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

cycles, check = [], [False]*n
for pi in p:
    if not check[pi-1]:
        curr, cycle = pi, []
        check[pi-1] = True
        while pi != p[curr-1]:
            check[curr-1] = True
            cycle.append(c[curr-1])
            curr = p[curr-1]
        check[curr-1] = True
        cycles.append(cycle + [c[curr-1]])

scores = []
for cycle in (np.array(cycle) for cycle in cycles):
    for i in range(cycle.size):
        cum = np.roll(cycle, i).cumsum()
        if cum[-1] > 0 and k > cycle.size:
            scores.append(cum[-1]*(k//cycle.size-1) + np.concatenate([cum, cum[:k % cycle.size]+cum[-1]]).max())
        else:
            scores.append(cum[:min(k, cum.size)-1].max())
print(max(scores))

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
Pls = [0] + list(map(int,input().split()))
Cls = [0] + list(map(int,input().split()))
used = [False]*(N+1)
loopmax = []
for i in range(1,N+1):
    loop = [Cls[i]]
    pi = Pls[i]
    if used[i]:
        continue
    else:
        while pi != i:
            loop.append(Cls[pi])
            used[pi] = True
            pi = Pls[pi]
        if sum(loop) > 0:
            rm = (K-1) % lenloop
            lenloop = len(loop)
            if rm == K:
                max1 = (K//len(loop)-1)*sum(loop)
            else:
                max1 = (K//len(loop))*sum(loop)           
            max3 = -10**9
            for k in range(1,rm + 1):
                max2 = sum(loop[:k])
                for j in range(lenloop):
                    max2 += -loop[j] + loop[(k + j) % lenloop]
                    max3 = max(max2,max3)
            loopmax.append(max3 + max1)
        else:
            max1 = 0
            lenloop = len(loop)
            rm = (K-1) % lenloop + 1
            max3 = -10**9
            for k in range(1,rm + 1):
                max2 = sum(loop[:k])
                for j in range(lenloop):
                    max2 += -loop[j] + loop[(k + j) % lenloop]
                    max3 = max(max2,max3)
            loopmax.append(max3 + max1)
print(max(loopmax))

Submission status: Runtime Error

Solution code:
N, K, *PC = map(int, open(0).read().split())
P, C = [0] + PC[:N], [0] + PC[N:]

ans = float("-inf")
for start in range(1, N + 1):
    acc = 0
    cur = start
    cycle = 0
    for l in range(K):
        cur = P[cur]
        acc += C[cur]
        ans = max(ans, acc)
        if cur == start:
            cycle = l + 1
            break

    q, r = divmod(K, cycle)
    if r == 0 and q > 1:
        r = cycle
        q -= 1

    res = acc * q
    ans = max(ans, res)
    for l in range(r):
        cur = P[cur]
        res += C[cur]
        ans = max(ans, res)

print(ans)