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 numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

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**18

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)
# テレポート, teleporter

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        # al = np.array([i])
        # al = np.delete(al,-1)
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                # al = np.append(al,C[next])
                next = P[next]
        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        if (K < len(visited)) or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            # if q>0:
            a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
            b = al_cum[-1] + (q-1)*am_cum[-1] + am_cum.max()
            a = max(a,b)
            # else:
            #     a = al_cum[-1] + am_cum[:mod+1].max()
            #     b = al_cum.max()
            #     a = max(a,b)
        best_score = max(best_score, a)
    return best_score

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

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

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**18

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)
# テレポート, teleporter

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        al = np.array([i])
        al = np.delete(al,-1)
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                al = np.append(al,C[next])
                next = P[next]
        # print(visited,loopStart)
        # al = np.zeros(len(visited)-1)
        # for j in range(1,len(visited)):
        #         al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        if (K < len(visited)) or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            # if q>0:
            a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
            b = al_cum[-1] + (q-1)*am_cum[-1] + am_cum.max()
            a = max(a,b)
            # else:
            #     a = al_cum[-1] + am_cum[:mod+1].max()
            #     b = al_cum.max()
            #     a = max(a,b)
        best_score = max(best_score, a)
    return best_score

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

Submission status: Wrong Answer

Solution code:
def solve():
    from collections import defaultdict
    class UnionFind():
        def __init__(self, n):
            self.n = n
            self.par = [-1] * n

        def find(self, x):
            if self.par[x] < 0:
                return x
            else:
                while self.par[x] > 0:
                  x = self.par[x]
                return x

        def unite(self, x, y):
            x = self.find(x)
            y = self.find(y)

            if x == y:
                return

            if self.par[x] > self.par[y]:
                x, y = y, x

            self.par[x] += self.par[y]
            self.par[y] = x

        def size(self, x):
            return -self.par[self.find(x)]

        def same(self, x, y):
            return self.find(x) == self.find(y)

    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    mp = defaultdict(int)
    uf = UnionFind(n)

    for i in range(n):
        uf.unite(i, p[i] - 1)

    for i in range(n):
        mp[uf.find(i)] += c[i]

    ans = -10 ** 14
    for i in range(n):
        roop = uf.size(i)
        times = (k - 1) // roop if mp[uf.find(i)] > 0 else 0
        over = max(min(roop, k - roop * times), 1)
        tmp = 0
        s = -10 ** 10
        idx = i
        for j in range(over):
            tmp += c[idx]
            s = max(s, tmp)
            idx = p[idx] - 1
        s += times * mp[uf.find(i)]
        ans = max(ans, s)
    print(ans)


solve()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

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**18

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)
# テレポート, teleporter

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        al = np.array([i])
        al = np.delete(al,-1)
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                al = np.append(al,C[next])
                next = P[next]
        # print(visited,loopStart)
        # al = np.zeros(len(visited)-1)
        # for j in range(1,len(visited)):
        #         al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        if (K < len(visited)) or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            if q>0:
                a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
                b = al_cum[-1] + (q-1)*am_cum[-1] + am_cum.max()
                a = max(a,b)
            else:
                a = al_cum[-1] + am_cum[:mod+1].max()
                b = al_cum.max()
                a = max(a,b)
        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()))
for i in range(len(P)):
	P[i] -= 1
C = list(map(int, input().split()))

score = []
now = 0
for i in range(n):
	now = P[now]
	score.append(C[now])
#print(score)
score *= 2

pt = max(C)
if k==1:
	print(pt)
	exit()

if sum(C)>0 and n<k:
	max_len = k%n
else:
	max_len = n

for i in range(1,max_len):
	for start in range(n):
		if pt < sum(score[start:start+i]):
			pt = sum(score[start:start+i])
			#print('---', i, pt)
if sum(C)<0 or n>k:
	'''1週できないとき'''
	'''1週以上できるとき1週の期待値がマイナス'''
	print(pt)
else:
	'''期待値プラス'''
	print(pt+ (sum(C)*(k//n)))
	#print(pt, (sum(C)*(k//n)), 'sum(C)', sum(C), 'k//n', k//n)
	#print(29507023469)
	#print(945172369)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

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**18

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)
    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)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        if (K < len(visited)) or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            if q>0:
                a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
                b = al_cum[-1] + (q-1)*am_cum[-1] + am_cum.max()
                a = max(a,b)
            else:
                a = al_cum[-1] + am_cum[:mod+1].max()
        best_score = max(best_score, a)
    return best_score

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
k -= 1
for j in range(n):
    ret = C[j]
    now = P[j] - 1
    r = D[U.root(now)]
    m = U.get_size(now)
    ans = max(ans, ret)
    if k // m and r >= 0:
        ret += k // m * r
        ans = max(ans, ret)
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ans = max(ans, ret)
    else:
        for l in range(min(m, k)):
            now = P[now] - 1
            ret += C[now]
            ans = max(ans, ret)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N, K = map(int, rl().split())
    P = list(map(lambda n: int(n) - 1, rl().split()))
    C = list(map(int, rl().split()))
    
    ans = max(C)
    for s in range(N):
        roop = 0
        cur = s
        visited = {cur}
        while 1:
            cur = P[cur]
            roop += C[cur]
            if cur in visited:
                break
            visited.add(cur)
        div, mod = divmod(K, len(visited))
        tmp = roop * div if 0 < roop else 0
        cur = s
        while mod:
            cur = P[cur]
            tmp += C[cur]
            ans = max(ans, tmp)
            mod -= 1
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
k -= 1
for j in range(n):
    r = D[U.root(j)]
    m = U.get_size(j)
    now = P[j] - 1
    ret = C[now]
    ans = max(ans, ret)
    if k // m and r >= 0:
        ret += k // m * r
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ans = max(ans, ret)
    else:
        for l in range(min(m, k)):
            now = P[now] - 1
            ret += C[now]
            ans = max(ans, ret)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

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**18

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)
    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)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        if (K < len(visited)) or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            if q>0:
                a = al_cum[-1] + (q-1)*am_cum[-1]
                am = np.append(am,am[1:mod+1])
                # print(am)
                a += am.cumsum().max()
            else:
                a = al_cum[-1] + am_cum[:mod+1].max()
        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=[int(x)-1 for x in input().split()]
C=[int(x) for x in input().split()]

def circle_grouping(P):
  P_in=[]
  P_group=[]
  for i in range(N):
    if i in P_in:
      pass
    else:
      start=i
      j=P[i]
      ls=[i]
      P_in.append(i)
      while j!=start:
        ls.append(j)
        P_in.append(j)
        j=P[j]
      P_group.append(ls)
  return P_group

def circle_maximum(A,K):
  max_val=max(A)
  for i in range(len(A)):
    val=0
    for k in range(K):
      pos=(i+k)%len(A)
      val+=A[pos]
      max_val=max(max_val,val)
  return max_val

score=max(C)
P_group=circle_grouping(P)
for A in P_group:
  k_rem=K%len(A)
  cycle=K//len(A)
  if k_rem==0:
    k_rem=len(A)
    cycle-=1
  B=[C[i] for i in A]
  score=max(score,max(0,sum(B))*cycle+circle_maximum(B,k_rem))
print(score)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

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**18

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)
    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)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        if (K < len(visited)) or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            if q>0:
                am += am[:mod+1]
                a = al_cum[-1] + (q-1)*am_cum[-1] + am.cumsum().max()
            # print('q,mod:',q,mod)
            else:
                a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
        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()))

#N,K=5 ,2
#P=[2 ,4 ,5 ,1 ,3]
#C=[3 ,4 ,-10 ,-8 ,8]

q1=True
L_c=[1]*N
L=[]
while q1:
    
    q2=True
    for i in range(N):
        if L_c[i]==1:
            n=i
            break
    l=[]
    l_c=[1]*N
    while q2:
        if l_c[n]==1:
            L_c[n]=0
            l_c[n]=0
            l.append(P[n])
            n=P[n]-1
        else:
            q2=False
            L.append(l)
    q2=True
    
    if sum(L_c)==0:
        q1=False
T=[]
for i in L:
    a=[]
    for u in i:
        a.append(C[P[u-1]-1])
    T.append(a)

num=0
r=[]
for i in T:
    kosuu=len(i)
    #print(kosuu)
    wa=sum(i)
    rr=[]
    for y in range(kosuu):
        f=i[y]
        d=[]
        d.append(f)
        for u in range(1,kosuu):
            f+=i[(y+u)%kosuu]
            d.append(f)
        rr.append(d)
    #print('rr',rr)
    r.append(rr) 
    #print('r',r)
    
    mx=[]
    INF=float('inf')
    for i in range(kosuu):
        mxx=-INF
        for t in rr:
            mxx=max(mxx,t[i])
        mx.append(mxx)
    #print(mx)
    
    if wa<=0:
        if kosuu<=K:
            num=max(mx) 
        else:
            num=max(mx[0:K])
    else:
        mm=K//kosuu
        m=K%kosuu
        we=[i for i, v in enumerate(mx) if v == max(mx)]
        max_index=we[0] 
        if kosuu<=K:
            if max_index>m:
                num=max(mx)+wa*(mm-1) 
            else:
                num=max(mx)+wa*(mm) 
        else:
            num=max(mx[0:K])
             
print(num)

Submission status: Wrong Answer

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

ans = -100000000000000000000

for i in range( 1, N+1):
    naw = i
    S = 0
    l = 0
    lmax = -100000000000000000000
    kl = K

    while 1:
        naw = p[naw]
        S += c[naw]
        l += 1
        kl -= 17
        if S > lmax:
            lmax = S
            max_l = l
        if kl == 0 or naw == i:
            break
    
    if kl == 0:
        imax = lmax
    else:
        if S <= 0:
            imax = lmax
        else:
            imax = lmax + S * ( (K - max_l) // l)
    
    if (imax > ans):
        ans = imax

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

    def root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.root(self.table[x])
            return self.table[x]

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
k -= 1
for j in range(n):
    r = D[U.root(j)]
    m = U.get_size(j)
    ret = 0
    ret_max = 0
    now = P[j] - 1
    if k // m and r >= 0:
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
        ret_max += k // m * r
    else:
        for l in range(min(m, k)):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
    ans = max(ans, ret_max + C[j])

print(ans)