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: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            cost_sum = 0
            costs = []
            min_distance = inf
            while(True):
                dest = edges[left][2]
                cost = edges[dest][0]
                if(passed[dest]==False):
                    #passed[left] = True
                    passed[dest] = True
                    cost_sum += cost
                    costs.append(cost_sum)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = cost_sum
                    break
            # 2 period項準備
            remainder = times%period
            cost_minus = [0]
            for j in range(period-1):
                cost_minus.append(costs[j])
            if(increase_period <= 0):
                """
                for j in range(period):
                    costs.append(costs[j]+increase_period)
                maxindex = 0
                maxindex_start = 0
                maxvalue = -inf

                if(remainder==0):
                    remainder += period

                for st in range(period):
                    maxvalue_candidate = max(costs[st:st+period])
                    if(maxvalue_candidate - cost_minus[st] > maxvalue):
                        maxvalue = maxvalue_candidate - cost_minus[st]
                        maxindex = costs[st:st+period].index(maxvalue_candidate) + st
                        maxindex_start = st
                """
                costs_last = []
                # a_0は0なので。そしてこれは最大値を考えるときには数えないので
                remainder2 = remainder % period

                #print("x", costs, increase_period, remainder2)
                """
                for j in range(remainder2, period):
                    costs_last.append(costs[j])
                for j in range(0, remainder2):
                    costs_last.append(costs[j]+increase_period)
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                """
                for j in range(period):
                    costs_last.append(costs[j])
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                maxvalue = -inf
                #print(costs_last, cost_minus)
                for j in range(period):
                    maxvalue_candidate = max(costs_last[j:j+period])
                    if(maxvalue_candidate-cost_minus[j] > maxvalue):
                        maxvalue = maxvalue_candidate-cost_minus[j]

                travel_max = max(maxvalue, travel_max)
            else:
                costs_last = []
                # a_0は0なので。そしてこれは最大値を考えるときには数えないので
                remainder2 = remainder % period
                times_period = times//period-1
                add_n = times_period * increase_period
                #print(costs, increase_period, remainder2, times_period, add_n)
                for j in range(remainder2, period):
                    costs_last.append(costs[j]+add_n)
                for j in range(0, remainder2):
                    costs_last.append(costs[j]+add_n+increase_period)
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                maxvalue = -inf
                #print(costs_last, cost_minus)
                for j in range(period):
                    maxvalue_candidate = max(costs_last[j:j+period])
                    if(maxvalue_candidate-cost_minus[j] > maxvalue):
                        maxvalue = maxvalue_candidate-cost_minus[j]
                travel_max = max(maxvalue, travel_max)






    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            cost_sum = 0
            costs = []
            min_distance = inf
            while(True):
                dest = edges[left][2]
                cost = edges[dest][0]
                if(passed[dest]==False):
                    #passed[left] = True
                    passed[dest] = True
                    cost_sum += cost
                    costs.append(cost_sum)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = cost_sum
                    break
            # 2 period項準備
            remainder = times%period
            cost_minus = [0]
            for j in range(period-1):
                cost_minus.append(costs[j])
            if(increase_period <= 0):
                """
                for j in range(period):
                    costs.append(costs[j]+increase_period)
                maxindex = 0
                maxindex_start = 0
                maxvalue = -inf

                if(remainder==0):
                    remainder += period

                for st in range(period):
                    maxvalue_candidate = max(costs[st:st+period])
                    if(maxvalue_candidate - cost_minus[st] > maxvalue):
                        maxvalue = maxvalue_candidate - cost_minus[st]
                        maxindex = costs[st:st+period].index(maxvalue_candidate) + st
                        maxindex_start = st
                """
                costs_last = []
                # a_0は0なので。そしてこれは最大値を考えるときには数えないので
                remainder2 = remainder % period

                #print("x", costs, increase_period, remainder2)
                for j in range(remainder2, period):
                    costs_last.append(costs[j])
                for j in range(0, remainder2):
                    costs_last.append(costs[j]+increase_period)
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                maxvalue = -inf
                #print(costs_last, cost_minus)
                for j in range(period):
                    maxvalue_candidate = max(costs_last[j:j+period])
                    if(maxvalue_candidate-cost_minus[j] > maxvalue):
                        maxvalue = maxvalue_candidate-cost_minus[j]

                travel_max = max(maxvalue, travel_max)
            else:
                costs_last = []
                # a_0は0なので。そしてこれは最大値を考えるときには数えないので
                remainder2 = remainder % period
                times_period = times//period-1
                add_n = times_period * increase_period
                #print(costs, increase_period, remainder2, times_period, add_n)
                for j in range(remainder2, period):
                    costs_last.append(costs[j]+add_n)
                for j in range(0, remainder2):
                    costs_last.append(costs[j]+add_n+increase_period)
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                maxvalue = -inf
                #print(costs_last, cost_minus)
                for j in range(period):
                    maxvalue_candidate = max(costs_last[j:j+period])
                    if(maxvalue_candidate-cost_minus[j] > maxvalue):
                        maxvalue = maxvalue_candidate-cost_minus[j]
                travel_max = max(maxvalue, travel_max)






    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            cost_sum = 0
            costs = []
            min_distance = inf
            while(True):
                dest = edges[left][2]
                cost = edges[dest][0]
                if(passed[dest]==False):
                    #passed[left] = True
                    passed[dest] = True
                    cost_sum += cost
                    costs.append(cost_sum)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = cost_sum
                    break
            # 2 period項準備
            remainder = times%period
            cost_minus = [0]
            for j in range(period-1):
                cost_minus.append(costs[j])
            if(increase_period <= 0):
                for j in range(period):
                    costs.append(costs[j]+increase_period)
                maxindex = 0
                maxindex_start = 0
                maxvalue = -inf

                if(remainder==0):
                    remainder += period

                for st in range(period):
                    maxvalue_candidate = max(costs[st:st+period])
                    if(maxvalue_candidate - cost_minus[st] > maxvalue):
                        maxvalue = maxvalue_candidate - cost_minus[st]
                        maxindex = costs[st:st+period].index(maxvalue_candidate) + st
                        maxindex_start = st
                travel_max = max(maxvalue, travel_max)
            else:
                costs_last = []
                # a_0は0なので。そしてこれは最大値を考えるときには数えないので
                remainder2 = remainder % period
                times_period = times//period-1
                add_n = times_period * increase_period
                #print(costs, increase_period, remainder2, times_period, add_n)
                for j in range(remainder2, period):
                    costs_last.append(costs[j]+add_n)
                for j in range(0, remainder2):
                    costs_last.append(costs[j]+add_n+increase_period)
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                maxvalue = -inf
                #print(costs_last, cost_minus)
                for j in range(period):
                    maxvalue_candidate = max(costs_last[j:j+period])
                    if(maxvalue_candidate-cost_minus[j] > maxvalue):
                        maxvalue = maxvalue_candidate-cost_minus[j]
                travel_max = max(maxvalue, travel_max)






    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            costs = [0]
            min_distance = inf
            while(True):
                dest = edges[left][2]
                cost = edges[dest][0]
                if(passed[dest]==False):
                    passed[left] = True
                    passed[dest] = True
                    costs.append(costs[-1] + cost)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = costs[-1]+cost
                    break
            # 2 period項準備
            remainder = times%period
            if(increase_period <= 0):
                for j in range(period):
                    costs.append(costs[j]+increase_period)
                maxindex = 0
                maxindex_start = 0
                maxvalue = -inf

                if(remainder==0):
                    remainder += period
                """
                for st in range(period):
                    maxvalue_candidate = max(costs[st+1:st+period])
                    if(maxvalue_candidate - costs[st] > maxvalue):
                        maxvalue = maxvalue_candidate - costs[st]
                        maxindex = costs[st+1:st+period].index(maxvalue_candidate) + st+1
                        maxindex_start = st
                """
                for st in range(period):
                    maxvalue_candidate = max(costs[st+1:st+remainder+1])
                    if(maxvalue_candidate - costs[st] > maxvalue):
                        maxvalue = maxvalue_candidate - costs[st]
                        maxindex = costs[st+1:st+remainder+1].index(maxvalue_candidate) + st+1
                        maxindex_start = st
                travel_max = max(maxvalue, travel_max)
            else:
                costs_last = []
                # a_0は0なので。そしてこれは最大値を考えるときには数えないので
                remainder2 = (remainder+1) % period
                times_period = (1+times)//period-1
                add_n = times_period * increase_period

                for j in range(remainder2, period):
                    costs_last.append(costs[j]+add_n)
                for j in range(0, remainder2):
                    costs_last.append(costs[j]+add_n+increase_period)
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                maxvalue = -inf
                for j in range(period):
                    maxvalue_candidate = max(costs_last[j:j+period])
                    if(maxvalue_candidate-costs[j] > maxvalue):
                        maxvalue = maxvalue_candidate-costs[j]
                travel_max = max(maxvalue, travel_max)






    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_tree(N_vertices, edges, times, inf):

    """
    edges: [start, dest, cost] -> [cost, start, end]
    """

    distance = 0

    passed = [False] * N_vertices

    travel_max = -inf
    for i in range(N_vertices):
        if(passed[i] == False):
            distance = 0
            left = i
            costs = [0]
            min_distance = inf
            while(True):
                dest = edges[left][2]
                cost = edges[dest][0]
                if(passed[dest]==False):
                    passed[left] = True
                    passed[dest] = True
                    costs.append(costs[-1] + cost)
                    left = dest
                    if(min_distance > cost):
                        min_distance = cost
                else:
                    period = len(costs)
                    increase_period = costs[-1]+cost
                    break
            # 2 period項準備
            remainder = times%period
            if(increase_period <= 0):
                for j in range(period):
                    costs.append(costs[j]+increase_period)
                maxindex = 0
                maxindex_start = 0
                maxvalue = -inf

                if(remainder==0):
                    remainder += period
                for st in range(period):
                    maxvalue_candidate = max(costs[st+1:st+period])
                    if(maxvalue_candidate - costs[st] > maxvalue):
                        maxvalue = maxvalue_candidate - costs[st]
                        maxindex = costs[st+1:st+period].index(maxvalue_candidate) + st+1
                        maxindex_start = st
                travel_max = max(maxvalue, travel_max)
            else:
                costs_last = []
                # a_0は0なので。そしてこれは最大値を考えるときには数えないので
                remainder2 = (remainder+1) % period
                times_period = (1+times)//period-1
                add_n = times_period * increase_period

                for j in range(remainder2, period):
                    costs_last.append(costs[j]+add_n)
                for j in range(0, remainder2):
                    costs_last.append(costs[j]+add_n+increase_period)
                for j in range(period):
                    costs_last.append(costs_last[j]+increase_period)
                maxvalue = -inf
                for j in range(period):
                    maxvalue_candidate = max(costs_last[j:j+period])
                    if(maxvalue_candidate-costs[j] > maxvalue):
                        maxvalue = maxvalue_candidate-costs[j]
                travel_max = max(maxvalue, travel_max)






    return travel_max







if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    """
    N_vertices = 2+N
    """
    N_vertices = N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i], i, PList[i]-1 ])

    weight = calcweight_tree(N_vertices, edges3, K, inf)

    #weight= calcweight_bellman_ford(N_vertices, 0, edges3, K+2, cost, inf)


    print( weight)

Submission status: Wrong Answer

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

INF = 10**18
score = -INF
for st in range(n):
    lap_cn = 0
    lap_sc = 0
    max_cn = 0
    max_sc = -INF
    nx = st
    while True:
        lap_cn += 1
        lap_sc += C[nx]
        if max_sc < lap_sc:
            if lap_cn < k:
                max_sc = lap_sc
                max_cn = lap_cn
        nx = P[nx]
        if nx == st: break
    score = max(score, max_sc + max(0, lap_sc) * ((k - max_cn) // lap_cn))

    # score = max(score, sum_sc + lap_sc * ((k - k_cn) // lap_cn))

print(score)

Submission status: Wrong Answer

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

INF = 10**18
score = -INF
for st in range(n):
    lap_cn = 0
    lap_sc = 0
    max_cn = 0
    max_sc = -INF
    nx = st
    while True:
        lap_cn += 1
        lap_sc += C[nx]
        if max_sc < lap_sc:
            max_sc = lap_sc
            max_cn = lap_cn
        nx = P[nx]
        if nx == st: break
    # sc = max_sc + max(0, lap_sc) * ((k - max_cn) // lap_cn)
    sc = max_sc
    if lap_sc > 0:
        if k > max_cn:
            sc += lap_sc * ((k - max_cn) // lap_cn)
        else:
            pass
    else:
        pass
    score = max(score, sc)

print(score)

Submission status: Wrong Answer

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

INF = 10**18
score = -INF
for st in range(n):
    lap_cn = 0
    lap_sc = 0
    max_cn = 0
    max_sc = -INF
    nx = st
    while True:
        lap_cn += 1
        lap_sc += C[nx]
        if max_sc < lap_sc:
            max_sc = lap_sc
            max_cn = lap_cn
        nx = P[nx]
        if nx == st: break
    score = max(score, max_sc + max(0, lap_sc) * ((k - max_cn) // lap_cn))

print(score)

Submission status: Wrong Answer

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 = -1e9-1	# NOTES: 2020/08/17 numba関数内でこれをやっていたら、データによってはWAになってしまっていた。詳細は、いまだに不明。

	# 一度計算したサイクル情報を一応キャッシュしておく。。。
	# あんまり意味なさそう
	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)
	#print(ans)

Submission status: Wrong Answer

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

# @njit(cache=True)
def calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

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

				v = P[v]
				if v == n:
					# サイクル発見
					cycleIDs[v] = cycleID
					cycleItemCnts[cycleID] = currentCycleItemCnt
					cycleTotalScores[cycleID] = currentCycleTotal
					cycleID += 1
					break

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

def upd(P,C,K,v,ans,currentCycleItemCnt,currentCycleTotal):

	# procCnt = 0
	currentCycleSumTmp = 0

	for k in range(min(K,currentCycleItemCnt)):

		# 頂点vにコマが置かれた時の最高スコアを計算し、
		# これまでの最高スコアを上回ったら、これまでの最高スコアを更新する

		procCnt = k+1
		currentCycleSumTmp += C[v]

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

		# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, "procCnt, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
		ans = max( ans, currentCycleSumTmp + cycleLoopCnt * currentCycleTotal )
		v = P[v]

	return ans





def main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores):

	ans = -1e18


	for n in range(N):

		v = n
		currentCycleItemCnt, currentCycleTotal = cycleItemCnts[ cycleIDs[v] ], cycleTotalScores[ cycleIDs[v] ]

		currentCycleSumTmp = 0

		# ans=upd(P,C,K,v,ans,currentCycleItemCnt,currentCycleTotal)
		for k in range(min(K,currentCycleItemCnt)):

			procCnt = k+1
			currentCycleSumTmp += C[v]

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

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, "procCnt, cycleLoopCnt, currentCycleTotal=", procCnt, cycleLoopCnt, currentCycleTotal)
			ans = max( ans, currentCycleSumTmp + cycleLoopCnt * currentCycleTotal )
			v = P[v]


	print(int(ans))

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



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 )

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

	calcCycle(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)

	# print(cycleItemCnts)


	main(N,K,P,C,cycleIDs,cycleItemCnts,cycleTotalScores)
	#print(ans)