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

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)
  cnt += 1
  score += C[x]
  if first != P[x]:
    x = P[x]
  else:
    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)]
  imax[0] = 0
  for x in loop_mem:
    tmp = 0
    for j in range(1, cnt):
      tmp += C[x]
      imax[j] = max(imax[j], tmp)
      x = P[x]
  for j in range(2, cnt):
    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], 0), score * (M-1) + imax[-1])
    else:
      tmp = imax[m]
    ans = max(ans, tmp)

print(ans)

Submission status: Accepted

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(cur not in se and f<k):
        se.add(cur)
        cur=arr[cur]
        co = cost[cur]
        pref.append(pref[-1]+co)
        ma=max(ma,pref[-1])
        f+=1

    if pref[-1]>0 and k>=f:
        ans=pref[-1]*(k//f)
        for j in range(k%f+1):
            ma=max(ma,ans+pref[j])
        ma=max(ma,pref[-1]*(k//f-1)+max(pref))
print(ma)

Submission status: Accepted

Solution code:
# import numpy as np
import itertools

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 )
	cycleIDs = [ -1 for _ in range(N)]
	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 )
					# それで足りてるのかわからないが、Last2周分は、ループ合計がプラスでも必ずしもループするとは限らない
					# その部分は、ちゃんと計算する
					# -------------------------------------------------
					# 4 101
					# 2 3 4 1
					# 50 -49 -50 50
					# 上記のようなパターンの場合、
					# 最大25回ループ + 1回処理可能だが、その場合、25 + 50 = 75
					# 24回ループ + 2回処理でやめると、124になる
					# 無条件でループする回数は、ループ可能な最大の回数-1らしい
					# -------------------------------------------------
					# 割り切れて、尚且つサイクル合計がマイナスのパターンで、最低１個は処理するのにもここで対応
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

					cycleInfs.append( ( procCnt, len(currentCycleCosts), currentCycleCosts * 3 ) )
					cycleID += 1
					break



	# scores = []
	# procCnt = 0
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

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

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleSize):
			# print(np.roll( currentCycleCosts, i ).cumsum()[:procCnt])
			ans = max( ans, max( itertools.accumulate( currentCycleCosts[i:i+procCnt] ) ) + loopScore )


	print(ans)
	# print(max(scores))

Submission status: Accepted

Solution code:
from itertools import accumulate

n, k = map(int, input().split())
p = [int(x) - 1 for x in input().split()]
c = list(map(int, input().split()))
ans = -(10 ** 18)

for i in range(n):
    pos = i
    scores = []
    while True:
        pos = p[pos]
        scores.append(c[pos])
        if pos == i:
            break
    m = len(scores)
    s = list(accumulate(scores))
    for j in range(min(m, k)):
        x = (k - j - 1) // m
        ans = max(ans, s[j], s[j] + s[-1] * x)

print(ans)

Submission status: Accepted

Solution code:
# import numpy as np
import itertools

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 )
	cycleIDs = [ -1 for _ in range(N)]
	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 )
					# それで足りてるのかわからないが、Last2周分は、ループ合計がプラスでも必ずしもループするとは限らない
					# その部分は、ちゃんと計算する
					# -------------------------------------------------
					# 4 101
					# 2 3 4 1
					# 50 -49 -50 50
					# 上記のようなパターンの場合、
					# 最大25回ループ + 1回処理可能だが、その場合、25 + 50 = 75
					# 24回ループ + 2回処理でやめると、124になる
					# 無条件でループする回数は、ループ可能な最大の回数-1らしい
					# -------------------------------------------------
					# 割り切れて、尚且つサイクル合計がマイナスのパターンで、最低１個は処理するのにもここで対応
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

					cycleInfs.append( ( procCnt, len(currentCycleCosts), currentCycleCosts * 3 ) )
					cycleID += 1
					break



	# scores = []
	# procCnt = 0
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

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

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleSize):
			# print(np.roll( currentCycleCosts, i ).cumsum()[:procCnt])
			ans = max( ans, max( list( itertools.accumulate( currentCycleCosts[i:i+procCnt] ) ) ) + loopScore )


	print(ans)
	# print(max(scores))

Submission status: Accepted

Solution code:
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()))
	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 )
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )
					cycleInfs.append( ( procCnt, len(currentCycleCosts), np.array( currentCycleCosts + currentCycleCosts ) ) )
					cycleID += 1
					break
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:
		loopScore = 0
		if np.sum(currentCycleCosts) > 0:
			cycleLoopCnt =  ( K - procCnt ) // currentCycleSize
			loopScore = cycleLoopCnt * np.sum(currentCycleCosts[:currentCycleSize])

		for i in range(currentCycleSize):
			ans = max( ans, np.roll( currentCycleCosts, i ).cumsum()[:procCnt].max() + loopScore )

	print(ans)

Submission status: Accepted

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]
            if k%loop>0:
                cur=max(cur,cur+max(acm[:k%loop]))
            else:
                cur-=acm[-1]
                cur+=max(acm)
    else:
        cur=max(acm[:min(k,loop)])
    
    ans=max(cur,ans)
    
print(ans)

Submission status: Accepted

Solution code:
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 )
					# それで足りてるのかわからないが、Last2周分は、ループするものとして確定させない
					# その部分は、ちゃんと計算する
					# -------------------------------------------------
					# 4 101
					# 2 3 4 1
					# 50 -49 -50 50
					# 上記のようなパターンの場合、
					# 最大25回ループ + 1回処理可能だが、その場合、25 + 50 = 75
					# 24回ループ + 2回処理でやめると、124になる
					# 無条件でループする回数は、最大の回数だけでなく、
					# 最大の回数-1も考慮の必要あり
					# -------------------------------------------------
					# あるいは、割り切れて、尚且つサイクル合計がマイナスのパターンで、最低１個は処理するのにもここで対応
					if len( currentCycleCosts ) + procCnt <= K:
						procCnt += len( currentCycleCosts )

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



	# scores = []
	# procCnt = 0
	ans = -10 ** 9
	for procCnt, currentCycleSize, currentCycleCosts in cycleInfs:

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

		# このサイクルに属する全頂点分をまとめて計算する
		for i in range(currentCycleSize):
			# scores.append( np.roll( currentCycleCosts, i )[:procCnt].cumsum().max() + loopScore )
			# print(np.roll( currentCycleCosts, i ).cumsum()[:procCnt])
			ans = max( ans, np.roll( currentCycleCosts, i ).cumsum()[:procCnt].max() + loopScore )


	print(ans)
	# print(max(scores))

Submission status: Accepted

Solution code:
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]

max_score = max(C[1:])
for init in range(1, N + 1):   # 初めの場所をinitとする
    score = [0]  # k回移動後のスコア
    i = init
    for k in range(1, K + 1):
        i = P[i]  # k回移動後に着くところ
        score.append(score[-1] + C[i])
        max_score = max(max_score, score[k])
        if i == init:  # ループ検出
            loop_score = score[-1]
            loop_len = k
            if loop_score < 0:
                max_score = max(max_score, max(score[1:]))
            else:
                max_score = max(max_score, max(score[j] + loop_score * ((K - j) // loop_len) for j in range(1, loop_len + 1)))
            break

print(max_score)

Submission status: Accepted

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)
            if K % _l == 0:
                _ans = max(_s_l[-1] * (K // _l),
                           _s_l[-1] * (K // _l - 1) + max(_s_l))
            else:
                _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: Accepted

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):
  T=1
  index=p[i]-1
  T_score=c[index]
  flag=True
  while flag:
    T+=1
    index=p[index]-1
    T_score+=c[index]
    if index==i:
      flag=False
  #場合分け開始
  if T>=k:
    score_list=[c[p[i]-1]]+[0]*(k-1)
    index=p[i]-1
    for s in range(1,k):
      index=p[index]-1
      score_list[s]=score_list[s-1]+c[index]
    score=max(score_list)
  else:
    if T_score<=0:
      score_list=[c[p[i]-1]]+[0]*(T-1)
      index=p[i]-1
      for s in range(1,T):       
        index=p[index]-1
        score_list[s]=score_list[s-1]+c[index]        
      score=max(score_list)
    else:
      m1=k//T
      m2=k%T
      score_list=[c[p[i]-1]]+[0]*(T+m2-1)
      index=p[i]-1
      for s in range(1,T+m2):
        index=p[index]-1
        score_list[s]=score_list[s-1]+c[index]
      score=max(score_list)+T_score*(m1-1)
  ans=max(ans,score)
print(ans)

Submission status: Accepted

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

def check(start):
    global k
    i = start
    cnt = 0
    score = 0
    cand = []
    while True:
        i = p[i] - 1
        score += c[i]
        cand.append(score)
        cnt += 1
        if i == start:
            break
    res = - 10 ** 10
    if score >= 0:
        for j, candj in enumerate(cand):
            if k - j - 1 >= 0:
                res = max(res, ((k - j - 1) // cnt) * score + candj)
    else:
        for j, candj in enumerate(cand):
            if k - j - 1 >= 0:
                res = max(res, candj)
    return res

ans = - 10 ** 10

for i in range(n):
    ans = max(ans, check(i))

print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
# from numba import njit

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

# @njit(cache=False)
def main(N,K,P,C): #,ans):


	# XeXは、Float?
	# numbaの場合、intでないとまずいのかもしれないので、そのまま1e9はヤバそう
	# ans = -1e9
	ans = int(-1e9)		
	# ans = -10 ** 9		# これはOK

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


	# print(P)

	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 = int(( K - procCnt ) // currentCycleItemCnt)

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

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

	print(int(ans))

if sys.argv[-1]=='ONLINE_JUDGE':
	# from numba import njit
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','void(i8,i8,i8[:],i8[:])')(main)
	# main=njit(main, cache=True)
	cc.compile()
	exit(0)
from my_module import main



if __name__ == "__main__":
	N,K = map(int,input().split())
	P = np.array( input().split(), np.int64 )
	P -= 1
	C = np.array( input().split(), np.int64 )

	main(N,K,P,C) #,ans)
	#print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
# from numba import njit

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

# @njit(cache=False)
def main(N,K,P,C): #,ans):


	# XeXは、Float?numbaの場合、intに変換しないとまずいのかもしれない
	# ans = -1e9
	ans = -10 ** 9

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


	# print(P)

	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 = int(( K - procCnt ) // currentCycleItemCnt)

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

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

	print(int(ans))

if sys.argv[-1]=='ONLINE_JUDGE':
	# from numba import njit
	from numba.pycc import CC
	cc=CC('my_module')
	cc.export('main','void(i8,i8,i8[:],i8[:])')(main)
	# main=njit(main, cache=True)
	cc.compile()
	exit(0)
from my_module import main



if __name__ == "__main__":
	N,K = map(int,input().split())
	P = np.array( input().split(), np.int64 )
	P -= 1
	C = np.array( input().split(), np.int64 )

	# ans = -1e9	# NOTES: 2020/08/17 numba関数内でこれをやっていたら、データによってはWAになってしまっていた。詳細は、いまだに不明。
	main(N,K,P,C) #,ans)
	#print(ans)

Submission status: Accepted

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==0:
          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: Accepted

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)
        if r != 0:
            peak = max(hoge[-1]*(d-1)+max(hoge[r:]),hoge[-1]*d+max(hoge[:r]))
        else:
            peak = hoge[-1]*(d-1)+max(hoge)
        ans = max(ans,peak)
print(ans)

Submission status: Accepted

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 = 45000
#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
        pos = p[pos]
        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: Accepted

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

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

group_score=[]
checked=[0]*n

for i in range(n):
    if checked[i]==0:
        tmp_group=[]
        tmp=i
        while checked[tmp]==0:
            checked[tmp]=1
            tmp_group.append(score[tmp])
            tmp=p[tmp]-1
        group_score.append(tmp_group)



#aryの中から連続するk個選択するときの最大
def calc(k):
    if k==0:
        return 0
    global group
    ans="INF"
    for i in range(len(group)):
        tmp=0
        for j in range(k):
            tmp+=group[(i+j)%len(group)]
            if ans=="INF":
                ans=tmp
            else:
                if ans<tmp:
                    ans=tmp
    return ans

ans=score[0]
for group in group_score:
    #一周以上する場合
    if len(group)<k:
        cycle=sum(group)
        if cycle>0:
            cycle_sum=cycle*(k//len(group))
            tmp=calc(k%len(group))
            ans=max(ans,cycle_sum+tmp)

            if k//len(group)>=2:
                cycle_sum=cycle*(k//len(group)-1)
                tmp=calc(len(group))
                ans=max(ans,cycle_sum+tmp)
          

        tmp=calc(len(group))
        ans=max(ans,tmp)



    #一周しない場合k)
    else:
        tmp=calc(k)
        ans=max(ans,tmp)

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
cycles = []
nux = -1000000000000000
cycles_score = []
for start in range(n):
    if done[start]:
        done[start] = False
        cycle = [start]
        score = C[start]
        nex = P[start]-1
        while nex != start:
            done[nex] = False
            cycle.append(nex)
            score += C[nex]
            nex = P[nex]-1
        cycles.append(cycle)
        cycles_score.append(score)

for score, cycle in zip(cycles_score, cycles):
    l = len(cycle)
    acum = [0 for _ in range(2*l+1)]
    for i in range(2*l):
        acum[i+1] = acum[i]+C[cycle[i % l]]
    if score < 0:
        for r in range(l+1):
            for i in range(l):
                if r == 0:
                    continue
                if r <= k:
                    nux = max(nux, acum[i+r]-acum[i])
    else:
        for r in range(l+1):
            q = (k-r)//l
            for i in range(l):
                if r == 0 and q == 0:
                    continue
                if q <= 0 and r > k:
                    continue
                nux = max(nux, score*q+acum[i+r]-acum[i])


print(nux)

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

score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
for start in range(n):
    if done[start]:
        nex = -1
        j = 0
        tuuka = []
        nax = -float("inf")
        while nex != start:
            if nex == -1:
                nex = P[start]-1
            else:
                nex = P[nex]-1
            tuuka.append(nex)
            score[start] += C[nex]
            nax = max(nax, score[start])
            j += 1
        loopn[start] = j
        for i in tuuka:
            done[i] = False
            loopn[i] = j
            score[i] = score[start]
            nokori = k-(k//loopn[start])*loopn[start]

    if score[start] < 0:
        score[start] = 0
    else:
        score[start] = (k//loopn[start])*score[start]
        nokori = k-(k//loopn[start])*loopn[start]
        i = 0
        nnnnn = (k//loopn[start])
        nscore = 0
        nax = 0
        while i < nokori:
            nex = P[nex]-1
            nscore += C[nex]
            if nscore < 0:
                break
            nax = max(nax, nscore)
            i += 1
        if nax > 0:
            score[start] += nax


ans = max(score)
if ans <= 0:
    ans = max(C)
print(ans)
"""

Submission status: Accepted

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

for i, v in enumerate(P):
    G[i+1] = (v, C[v-1])

ans = -float("inf")

for i in range(1, N+1):
    loop = []
    S = i
    visited = [False for i in range(N+1)]
    while visited[S] == False:
        loop.append(G[S][-1])
        visited[S] = True
        S = G[S][0]

    circle_sum = sum(loop)
    this_case_ans = -float("inf")

    if circle_sum < 0:
        pass_sum = 0
        for i in range(len(loop)):
            pass_sum += loop[i]
            this_case_ans = max(this_case_ans, pass_sum)
        ans = max(ans, this_case_ans)
        continue

    else:
        L = len(loop)
        for i in range(1, L):
            loop[i] += loop[i-1]
        loop.insert(0, -float("inf"))
        for i in range(1, L+1):
            loop[i] = max(loop[i], loop[i-1])
        loop[0] = 0
        if K//L > 0:
            this_case_ans = max(K//L * circle_sum +
                                loop[K % L], (K//L-1)*circle_sum + loop[-1])
        else:
            for i in range(1, K+1):
                this_case_ans = max(this_case_ans, loop[i])
        ans = max(ans, this_case_ans)

print(ans)