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:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -10**18
group_id = 0
group_ids = [-1] * n
groups = {}
# とりあえずグループ分けはできそう（せいぜいNなので）
for i in range(n):
    j = i
    group = []
    group_loop_score = 0
    while group_ids[j] == -1:
        group.append(j)
        group_ids[j] = group_id
        j = p[j] - 1
        group_loop_score += c[j]
    if len(group) > 0:
        groups[group_id] = [group_loop_score, group]
        group_id += 1

for gid, gsets in groups.items():
    if gsets[0] < 0:
        # 一周する前にK回以下で探索を断ち切ったほうがいい
        # ちょい無理やりくさいけど倍した長さの累積和を使ってスタートとゴールを決めてN^2
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[(i - 1)]
        tmp = gsets[0]
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + k + 1)):
                tmp = max(tmp, tmp_ruiseki[j] - tmp_ruiseki[i])
        ans = max(ans, tmp)
    else:
        # Kを一周の長さで割ったあまりぶんの長さ以下で貪欲した最大値を最後に加えるとする
        # 残りの(K-上記あまりぶん)はぜんぶ一周に使う
        kk = k % len(gsets[1])
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[i - 1]
        max_rest = 0  # どっかで正になるので0スタートにしとくわ
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + kk + 1)):
                max_rest = max(max_rest, tmp_ruiseki[j] - tmp_ruiseki[i])
        ans = max(ans, max_rest + gsets[0] * (k // len(gsets[1])))
print(ans)

Submission status: Wrong Answer

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

#if max(C) < 0:
#  print(min(C))
#  quit()
  
already = [0] * N
A = [-float("inf")] * N

for i in range(N):#スタート地点
  if already[i] == 0:
    already[i] = 1
    q = [i + 1]
    now = i + 1
    score = []
    T = True
    while T:
      now = P[now - 1]
      score.append(C[now - 1])
      if now in q:
        T = False
      else:
        q.append(now)
        already[now - 1] = 1
    
    #A.append(q)
    #S.append(score)
    #print(q)#ループのルート
    #print(score)#ループ中のスコア
    roop = sum(score)
    if len(q) >= K:
      aa = -float("inf")
      for j in range(len(q)):
        time = 0
        bb = 0
        p = j
        while time != K:
          time += 1
          bb += score[p]
          aa = max(aa, bb)
          p += 1
          if p == len(q):
            p = 0
      A[i] = aa      
    else:  
      if roop <= 0:
        aa = -float("inf")
        for j in range(len(q)):
          time = 0
          bb = 0
          p = j
          while time != len(q):
            time += 1
            bb += score[p]
            aa = max(aa, bb)
            p += 1
            if p == len(q):
              p = 0
        A[i] = aa            
      else:
        aa = -float("inf")
        for j in range(len(q)):#j番目start
          for k in range(len(q)):#k個まで余らせる
            ll = int((K - k) / len(q)) 
            time = 0
            bb = ll * roop
            p = j
            while time != k:
              time += 1
              bb += score[p]
              aa = max(aa, bb)
              p += 1
              if p == len(q):
                p = 0
        A[i] = aa           
        

#print(A)      
print(max(A))

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, input().split())
    p = [int(i) - 1 for i in input().split()]
    c = [int(i) for i in input().split()]

    seen = set()
    loop_list = []
    for start in range(n):
        v = start
        loop = []
        while v not in seen:
            seen.add(v)
            loop.append(c[v])
            v = p[v]
        seen.add(v)
        if loop:
            loop_list.append(loop)

    ans = min(min(c) * n, 0)
    for loop in loop_list:
        loop_len = len(loop)
        loop_num = k // loop_len
        loop_mod = k % loop_len
        loop_sum = sum(loop)
        mod_max = min(loop)
        for start in range(loop_len):
            current_sum = loop[start]
            mod_max = max(current_sum, mod_max)
            for i in range(1, loop_mod):
                current_sum += loop[(start + i) % loop_len]
                mod_max = max(current_sum, mod_max)
        ans = max(mod_max + max(loop_sum * loop_num, 0), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


def make_group_shim0(x, check):
    lis = [x - 1]
    while not P[x - 1] - 1 in lis:
        lis.append(P[x - 1] - 1)
        check.append(P[x - 1] - 1)

        x = P[x - 1]
    return lis


Big_lis = []
check = []
i = 1
while i < N:
    if i - 1 not in check:
        Big_lis.append(make_group_shim0(i, check))
    i += 1
print(Big_lis)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -10**18
group_id = 0
group_ids = [-1] * n
groups = {}
# とりあえずグループ分けはできそう（せいぜいNなので）
for i in range(n):
    j = i
    group = []
    group_loop_score = 0
    while group_ids[j] == -1:
        group.append(j)
        group_ids[j] = group_id
        j = p[j] - 1
        group_loop_score += c[j]
    if len(group) > 0:
        groups[group_id] = [group_loop_score, group]
        group_id += 1

for gid, gsets in groups.items():
    if gsets[0] < 0:
        # 一周する前にK回以下で探索を断ち切ったほうがいい
        # ちょい無理やりくさいけど倍した長さの累積和を使ってスタートとゴールを決めてN^2
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[(i - 1)]
        tmp = gsets[0]
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + k + 1)):
                tmp = max(tmp, tmp_ruiseki[j] - tmp_ruiseki[i])
        ans = max(ans, tmp)
    else:
        # Kを一周の長さで割ったあまりぶんの長さ以下で貪欲した最大値を最後に加えるとする
        # 残りの(K-上記あまりぶん)はぜんぶ一周に使う
        kk = k % len(gsets[1])
        if kk == 0:
            ans = max(ans, k * gsets[0])
            continue
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[i - 1]
        max_rest = 0  # どっかで正になるので0スタートにしとくわ
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + kk + 1)):
                max_rest = max(max_rest, tmp_ruiseki[j] - tmp_ruiseki[i])
        ans = max(ans, max_rest + gsets[0] * (k // len(gsets[1])))
print(ans)

Submission status: Wrong Answer

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

seen = []
roots = []
candidates = []

for i in range(N):
    if i+1 in seen:
        continue
    root = [i+1]
    seen.append(i+1)
    to = P[i]
    while(root[0] != to):
        root.append(to)
        seen.append(to)
        to = P[to-1]
    roots.append(root)
for root in roots:
    length = len(root)
    eachMoveBests = [None] * length
    for i in range(length):
        score = 0
        to = P[root[i]-1]
        for j in range(len(root)):
            score += C[to-1]
            to = P[to-1]
            if eachMoveBests[j] == None or score > eachMoveBests[j]:
                eachMoveBests[j] = score
    # 周回スコア
    aroundScore = eachMoveBests[len(eachMoveBests)-1]
    if length < K:
        for i in range(len(eachMoveBests)):
            if K-i-1 % length == 0:
                candidates.append(aroundScore * ((K-i-1) // length))
            else:
                candidates.append(aroundScore * ((K-i-1) // length) + eachMoveBests[i])
    else:
        candidates.append(max(eachMoveBests[:K]))

print(max(candidates))

Submission status: Wrong Answer

Solution code:
def solve_loop(loop, K):
    S = sum(loop)
    L = len(loop)
    if S >= 0:
        acc = S * (K//L)
        K = K % L
    else:
        acc = 0
        K = min(K, L)

    ans = -10 ** 9 - 1
    for i in range(L):
        #print(loop[i:] + loop[:i])
        tmp = 0
        for l in range(K):
            tmp += loop[(i+l) % L]
            #print(i, l, tmp)
            ans = max(tmp, ans)

    #print(loop, ans, acc)
    if S >= 0 and K//L > 0:
        return max(acc, acc + ans)
    return ans + acc

def solve():
    N, K = map(int, input().split())
    P = list(map(lambda n: int(n)-1, input().split())) # 0-based index
    C = list(map(int, input().split()))

    flag = [False] * N
    ans = -10**9-1
    for i in range(N):
        if flag[i]:
            continue
        j = P[i]
        loop = []
        sumC = 0
        for _ in range(N):
            if flag[j]: # loop end
                break
            flag[j] = True
            loop += [C[j]]
            j = P[j]
        ans = max(ans, solve_loop(loop, K))
    print(ans)

solve()

Submission status: Wrong Answer

Solution code:
#"""
N, K = map(int, input().split())
Ps = [P-1 for P in map(int, input().split())]
Cs = list(map(int, input().split()))
"""
N = 151 
K = 220061270 
Ps = [47, 128, 12, 133, 95, 32, 45, 118, 97, 70, 107, 58, 55, 14, 38, 24, 142, 31, 42, 113, 34, 82, 100, 75, 148, 110, 149, 143, 51, 62, 130, 21, 81, 105, 123, 108, 7, 103, 91, 137, 144, 147, 54, 78, 17, 140, 87, 26, 16, 69, 43, 146, 92, 141, 11, 3, 115, 112, 106, 57, 93, 101, 135, 98, 63, 65, 136, 25, 35, 61, 48, 117, 74, 90, 9, 66, 77, 80, 88, 30, 109, 40, 114, 132, 1, 89, 71, 20, 41, 27, 134, 29, 120, 124, 127, 138, 52, 122, 39, 139, 46, 22, 94, 49, 99, 10, 83, 5, 0, 2, 13, 76, 33, 36, 129, 64, 126, 6, 
8, 116, 96, 68, 60, 73, 28, 111, 125, 67, 50, 53, 44, 121, 37, 56, 4, 150, 18, 131, 23, 72, 85, 104, 79, 86, 84, 145, 102, 59, 119, 15, 19] 
Cs = [88823, 55717, 32755, -55276, 61522, 51208, -28916, 34824, 72293, 63213, 9010, 77108, -39173, -11657, 9923, -25718, 18506, 35820, 27834, 10014, -95118, 90886, 37836, -38611, 8005, -3000, 3113, 9065, -37655, -97788, -48317, -72954, 15805, -29469, -40867, -13273, -47709, 95381, -84591, -87631, 47821, -45960, 35421, 71276, -25716, -646, -40407, 89340, 10805, -84687, -1294, 82148, 
-80277, 58461, -33470, -41825, -42495, -57191, 9112, -38173, 60204, 33766, -5186, 86810, 84094, -41348, 
53393, 45495, 55329, -81984, 90086, -90177, -80673, 26196, -3983, 99730, -35595, -90631, 52483, -83958, 
40189, 98649, 27109, -88172, 83055, -12245, 36129, 10685, -2313, 46226, -63650, 98138, 44594, -35296, -74169, -23382, -29076, 59384, 53341, -97406, 18231, -3740, -11764, -39617, 89282, -57712, 82451, -36357, 
-44702, 2625, 38354, -69828, -26256, -39663, -29595, -61375, -55690, -67791, 89343, 8876, 83093, -9342, 
-20286, 26384, 72052, -85616, 79198, -48738, -47590, -90170, 45721, 91376, 31630, -72930, -26550, -54972, -59317, 5420, -17386, 10650, -46183, -6530, -23182, -3986, -51850, -83919, 55296, -50737, 21335, 92842, 84708]
#"""
group = [-1] * N
grouped_Cs = []
next_num = 0
for i in range(N):
    if group[i] == -1:
        g = []
        while group[i] == -1:
            group[i] = next_num
            g.append(Cs[i])
            i = Ps[i]
        grouped_Cs.append(g)
        next_num += 1

max_score = -(10 ** 18 + 10 ** 9)
for g in grouped_Cs:
    l = len(g)
    for k in range(1, l+1):    
        q = (K - k) // l
        cycle_score = max(0, sum(g) * q)
        score = sum(g[:k]) + cycle_score
        max_score = max(score, max_score)
        for i in range(l):
            score -= g[i]
            score += g[(i+k)%l]
            max_score = max(score, max_score)

print(max_score)

Submission status: Wrong Answer

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

ind = 0
path = [[]]
cost = [[]]
path_i = 0
while True:
    path[path_i].append(ind)
    cost[path_i].append(C[ind])
    pre_ind = ind
    if P[P[pre_ind]-1] == INF:
        for i in range(len(P)):
            if P[i] != INF and i != ind:
                ind = i
                path_i += 1
                path.append(list())
                cost.append(list())
                break
    else:
        ind = P[ind]-1

    P[pre_ind] = INF

    if len(set(P)) == 1:
        break


max_c = -INF
for i in range(len(path)):
    for j in range(len(path[i])):
        if K > len(path[i]):
            if sum(cost[i]) > 0:
                tmp_c = sum(cost[i]) * (K // len(path[i]))
                tmp_sub = tmp_c
                for k in range(K % len(path[i])):
                    if len(path[i])-1 <= j + k:
                        cicle_k = (j + k) - (len(path[i]) - 1)
                        tmp_cc = sum(cost[i][j:len(path[i])])
                        tmp_cc += sum(cost[i][:abs(cicle_k)])
                    else:
                        if j+k == 0:
                            tmp_cc = cost[i][0]
                        else:
                            tmp_cc = sum(cost[i][j:j+k])
                    if tmp_c < tmp_sub + tmp_cc:
                        tmp_c = tmp_sub + tmp_cc
            else:
                tmp_c = cost[i][j]
        else:
            if sum(cost[i]) > 0:
                tmp_c = sum(cost[i]) * (K // len(path[i]))
                tmp_c = -INF
                for k in range(K % len(path[i])):
                    if len(path[i]) <= j + k:
                        cicle_k = (j + k) - (len(path[i]) - 1)
                        tmp_cc = sum(cost[i][j:len(path[i])])
                        tmp_cc += sum(cost[i][:abs(cicle_k)])
                    else:
                        tmp_cc = sum(cost[i][j:j+k])
                    if tmp_c < tmp_cc:
                        tmp_c = tmp_cc
            else:
                tmp_c = cost[i][j]

        if max_c < tmp_c:
            max_c = tmp_c


print(max_c)

Submission status: Wrong Answer

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

#if max(C) < 0:
#  print(min(C))
#  quit()
  
already = [0] * N
A = [-float("inf")] * N

for i in range(N):#スタート地点
  if already[i] == 0:
    already[i] = 1
    q = [i + 1]
    now = i + 1
    score = []
    T = True
    while T:
      now = P[now - 1]
      score.append(C[now - 1])
      if now in q:
        T = False
      else:
        q.append(now)
        already[now - 1] = 1
    
    #A.append(q)
    #S.append(score)
    #print(q)#ループのルート
    #print(score)#ループ中のスコア
    roop = sum(score)
    if len(q) >= K:
      aa = -float("inf")
      for j in range(len(q)):
        time = 0
        bb = 0
        p = j
        while time != K:
          time += 1
          bb += score[p]
          aa = max(aa, bb)
          p += 1
          if p == len(q):
            p = 0
      A[i] = aa      
    else:  
      if roop <= 0:
        aa = -float("inf")
        for j in range(len(q)):
          time = 0
          bb = 0
          p = j
          while time != len(q):
            time += 1
            bb += score[p]
            aa = max(aa, bb)
            p += 1
            if p == len(q):
              p = 0
        A[i] = aa            
      else:
        ll = int(K / len(q)) 
        rr = K % len(q)
        aa = -float("inf")
        for j in range(len(q)):
          time = 0
          bb = ll * roop
          p = j
          while time != rr:
            time += 1
            bb += score[p]
            aa = max(aa, bb)
            p += 1
            if p == len(q):
              p = 0
        A[i] = aa           
        

#print(A)      
print(max(A))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -10**18
group_id = 0
group_ids = [-1] * n
groups = {}
# とりあえずグループ分けはできそう（せいぜいNなので）
for i in range(n):
    j = i
    group = []
    group_loop_score = 0
    while group_ids[j] == -1:
        group.append(j)
        group_ids[j] = group_id
        j = p[j] - 1
        group_loop_score += c[j]
    if len(group) > 0:
        groups[group_id] = [group_loop_score, group]
        group_id += 1

for gid, gsets in groups.items():
    if gsets[0] < 0:
        # 一周する前にK回以下で探索を断ち切ったほうがいい
        # ちょい無理やりくさいけど倍した長さの累積和を使ってスタートとゴールを決めてN^2
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[(i - 1)]
        ans = max(ans, gsets[0])
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + k + 1)):
                ans = max(ans, tmp_ruiseki[j] - tmp_ruiseki[i])
    else:
        # Kを一周の長さで割ったあまりぶんの長さ以下で貪欲した最大値を最後に加えるとする
        # 残りの(K-上記あまりぶん)はぜんぶ一周に使う
        kk = k % len(gsets[1])
        if kk == 0:
            ans = max(ans, k * gsets[0])
            continue
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[i - 1]
        ans = max(ans, gsets[0])
        max_rest = 0  # どっかで正になるので0スタートにしとくわ
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + kk + 1)):
                max_rest = max(max_rest, tmp_ruiseki[j] - tmp_ruiseki[i])
        ans = max(ans, max_rest + gsets[0] * (k // len(gsets[1])))
print(ans)

Submission status: Wrong Answer

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

# mv_array = [set() for _ in range(n)]
score_mv_array = [[] for _ in range(n)]
score_array = [0]*n

def get_sum(array):
    score_array = [0]
    for i, a in enumerate(array):
        score_array.append(score_array[i]+a)
    return max(score_array)

def get_max(array, q, mod):
    if q == 0:
        m_score = get_sum(array[:mod])
    else:
        m_score = get_sum(array+array[:mod])
        m_score = sum(array)*(q-1) + m_score
    return m_score

for i in range(n):
    score = 0
    max_score = c[i]
    pos = i
    start_pos = p[pos]-1
    for j in range(k):
        pos = p[pos]-1
        if j!=0 and pos == start_pos:
            # len_mv = len(score_mv_array[i])
            len_mv = j+1
            q, mod = divmod(k-j, len_mv)
            score += get_max(score_mv_array[i], q, mod)
            max_score = max(score, max_score)
            break
        score += c[pos]
        score_mv_array[i].append(c[pos])
        max_score = max(score, max_score)
    score_array[i] = max_score

print(max(score_array))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -10**10
group_id = 0
group_ids = [-1] * n
groups = {}
# とりあえずグループ分けはできそう（せいぜいNなので）
for i in range(n):
    j = i
    group = []
    group_loop_score = 0
    while group_ids[j] == -1:
        group.append(j)
        group_ids[j] = group_id
        j = p[j] - 1
        group_loop_score += c[j]
    if len(group) > 0:
        groups[group_id] = [group_loop_score, group]
        group_id += 1

for gid, gsets in groups.items():
    if gsets[0] < 0:
        # 一周する前にK回以下で探索を断ち切ったほうがいい
        # ちょい無理やりくさいけど倍した長さの累積和を使ってスタートとゴールを決めてN^2
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[(i - 1)]
        ans = max(ans, gsets[0])
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + k + 1)):
                ans = max(ans, tmp_ruiseki[j] - tmp_ruiseki[i])
    else:
        # Kを一周の長さで割ったあまりぶんの長さ以下で貪欲した最大値を最後に加えるとする
        # 残りの(K-上記あまりぶん)はぜんぶ一周に使う
        kk = k % len(gsets[1])
        if kk == 0:
            ans = max(ans, k * gsets[0])
            continue
        tmp_arr = gsets[1] * 2
        tmp_arr_length = len(gsets[1]) * 2
        tmp_ruiseki = [0] * (tmp_arr_length + 1)
        for i in range(1, tmp_arr_length + 1):
            tmp_ruiseki[i] = c[p[tmp_arr[i - 1]] - 1] + tmp_ruiseki[i - 1]
        ans = max(ans, gsets[0])
        max_rest = 0  # どっかで正になるので0スタートにしとくわ
        for i in range(tmp_arr_length):
            for j in range(i + 1, min(tmp_arr_length, i + kk + 1)):
                max_rest = max(max_rest, tmp_ruiseki[j] - tmp_ruiseki[i])
        ans = max(ans, max_rest + gsets[0] * (k // len(gsets[1])))
print(ans)

Submission status: Wrong Answer

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

score_array = [0]*n

def get_sum(array):
    score_array = [0]
    for i, a in enumerate(array):
        score_array.append(score_array[i]+a)
    return max(score_array)

def get_max(array, q, mod):
    if q == 0:
        m_score = get_sum(array[:mod])
    else:
        m_score = get_sum(array+array[:mod])
        m_score = sum(array)*(q-1) + m_score
    return m_score

# max_score = -float('inf')

for i in range(n):
    score = 0
    max_score = c[i]
    score_mv_array = []
    pos = i
    start_pos = p[pos]-1
    for j in range(k):
        pos = p[pos]-1
        if j!=0 and pos == start_pos:
            # len_mv = len(score_mv_array[i])
            len_mv = j+1
            q, mod = divmod(k-j, len_mv)
            score += get_max(score_mv_array, q, mod)
            max_score = max(score, max_score)
            break
        score += c[pos]
        score_mv_array.append(c[pos])
        max_score = max(score, max_score)
    score_array[i] = max_score

print(max(score_array))
# print(max_score)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit, b1, i4, i8, f8

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = 10**9
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    # INF = 1 << 60
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]

        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        # al = np.array([],dtype='int')
        if K < len(visited):
            for j in range(len(visited)-1):
                # al = np.append(al,C[visited[j+1]])
                al[j]=C[visited[j+1]]
            # print(al)
            # a_cum = np.array([],dtype='int')
            a_cum = np.zeros(len(al))
            a_cum = al.cumsum()
            a = a_cum.max()
            # print(a)
            # a = acum.max()
        else:        
            for j in range(1,len(visited)):
                # al = np.append(al,C[visited[j+1]])
                al[j-1]=C[visited[j]]
            visitedLoop = visited[loopStart:]
            # print("visitedLoop: ",visitedLoop)
            sum_visitedLoop = 0
            for j in range(len(visitedLoop)):
                sum_visitedLoop += C[visitedLoop[j]]
            if sum_visitedLoop<=0:
                # print(al)
                a = al.cumsum().max()
            else:
                # 残り回数を循環配列の長さで割った余り
                q,mod = divmod((K-len(visited)+1),len(visitedLoop))
                # print('q,mod:',q,mod)
                # am = np.array([0],dtype='int')
                am = np.zeros(mod+1)

                for j in range(mod):
                    # am = np.append(am,C[visitedLoop[j]])
                    am[j+1] = C[visitedLoop[j]]
                am_sum = am.cumsum().max()
                # print('al:',al)
                # print(visitedLoop)
                # print(sum_visitedLoop)
                # print('am:',am)
                a = al.cumsum()[-1] + q*sum_visitedLoop + am_sum
        best_score = max(best_score, a)
    return best_score

res = solve(K,P,C)
print(int(res))

Submission status: Wrong Answer

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

score_array = [0]*n

def get_sum(array):
    score_array = [0]
    for i, a in enumerate(array):
        score_array.append(score_array[i]+a)
    return max(score_array)

def get_max(array, q, mod):
    if q == 0:
        m_score = get_sum(array[:mod])
    else:
        m_score = get_sum(array+array[:mod])
        m_score = sum(array)*(q-1) + m_score
    return m_score

max_score = -float('inf')

for i in range(n):
    score = 0
    # max_score = c[i]
    score_mv_array = []
    pos = i
    start_pos = p[pos]-1
    for j in range(k):
        pos = p[pos]-1
        if j!=0 and pos == start_pos:
            # len_mv = len(score_mv_array[i])
            len_mv = j+1
            q, mod = divmod(k-j, len_mv)
            score += get_max(score_mv_array, q, mod)
            max_score = max(score, max_score)
            break
        score += c[pos]
        score_mv_array.append(c[pos])
        max_score = max(score, max_score)
    # score_array[i] = max_score

# print(max(score_array))
print(max_score)

Submission status: Wrong Answer

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

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

from itertools import accumulate

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

circles = []
used = [0]*n

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


score = -10**20

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

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

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

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

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

    score = max(score, s+ss)

print(score)