Problem:


Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n, k = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
for i in range(n):
    P[i] -= 1

# for ij in range(100):
    # print("-----")
    # from random import randint
    # n = 5
    # k = 1
    # PP = [[randint(-100,100),i] for i in range(n)]
    # PP.sort()
    # P = [PP[i][1] for i in range(n)]
    # C = [randint(-10,10) for i in range(n)]
    # P=[4, 1, 0, 2, 3]
    # C=[10, -4, -5, 0, 5]


V = [0] * n
ans = -float("inf")
an = 0
for i in range(n):
    if V[i] == 0:
        A = []
        V[i] = 1
        ii = P[i]
        V[ii] = 1
        A.append(C[ii])
        while ii != i:
            ii = P[ii]
            V[ii] = 1
            A.append(C[ii])
        # print(A)
        an = 0
        anb=0
        anb2=0
        kb=k
        kb2=k
        if sum(A) > 0:
            anb += sum(A) * (k//len(A))
            kb = k%len(A)
        if k >= len(A) and sum(A) > 0:
            anb2 += sum(A) * (k//len(A)-1)
            kb2 = k % len(A) + len(A)
        A += A
        S = [A[0]]
        # print(anb,anb2,kb,kb2)
        for i in range(1,len(A)):
            S.append(S[-1]+A[i])
        # print(S)
        anc = 0
        for i in range(len(S)):
            for j in range(i+1, min(i+kb2+1,len(S))):
                anc = max(anc,S[j]-S[i])

        for i in range(len(S)):
            for j in range(i+1, min(i+kb+1,len(S))):
                an = max(an,S[j]-S[i])

        ans = max(an+anb,anc+anb2,ans)
            
if ans == 0 and max(C) < 0:
    ans = max(C)
print(ans)
# aaa = -float("inf")
# for i in range(n):
#     ii = P[i]
#     aa = C[ii]
#     aaa = max(aaa,aa)
#     for j in range(k-1):
#         ii = P[ii]
#         aa += C[ii]
#         aaa = max(aaa,aa)

# if aaa != ans:
#     print(C,P)
#     print(aaa,ans)
#     break

Submission status: Accepted

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


def solve(v):
    res = []
    set_ = set()
    tot = 0
    while True:
        nxt_v = p[v] - 1
        cost = c[nxt_v]
        if nxt_v not in set_:
            set_.add(nxt_v)
            tot += cost
            res.append(tot)
            v = nxt_v
        else:
            break
    return res, tot


ans = -INF

# 1回移動する場合
for v in range(n):
    ans = max(c[v], ans)

for v in range(n):
    res, tot = solve(v)
    if tot < 0:
        for i in range(min(k, len(res))):
            ans = max(res[i], ans)
    else:
        lap, rem = divmod(k, len(res))
        tmp = lap * tot
        if lap > 0:
            ans = max(ans, tmp)
        for i in range(min(rem, len(res))):
            ans = max(tmp + res[i], ans)
            
        if lap == 0:
            continue
        lap -= 1
        tmp = lap * tot
        for i in range(min(k, len(res))):
            ans = max(tmp + res[i], ans)
            
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import bisect_right
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
#import numpy as np
INF = float("inf")
#d = defaultdict(int)
#d = defaultdict(list)
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
used = [-1]*N 
renketu = []
index = 0
def dfs(fr,cur,parent,index,li):
    Next = fr[cur]
    Next -= 1
    for chi in [Next]:
        if chi == parent or used[chi] != -1:
            continue
        used[chi] = index
        li.append(chi)
        dfs(fr,chi,cur,index,li)
for i in range(N):
    if used[i] != -1:
        continue
    li = [i]
    used[i] = index
    dfs(P,i,-1,index,li)
    index += 1
    renketu.append(li)
n = len(renketu)
ans = -1*10**20
for i in range(n):
    li = renketu[i]
    nn = len(li)
    val = 0
    nnow = li[0]
    for jj in range(nn):
        val += C[P[nnow]-1]
        nnow = P[nnow]-1
    if val <= 0:
        for k in range(nn):
            now = li[k]
            v = 0
            for j in range(nn):
                v += C[P[now]-1]
                ans = max(ans,v)
                now = P[now]-1
    else:
        vvv = val*(K//nn)
        vvv -= val
        nnn = K % nn
        nnn += nn
        for k in range(nn):
            now = li[k]
            v = 0
            for j in range(nnn):
                v += C[P[now]-1]
                now = P[now]-1
                ans = max(ans,vvv+v)
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline

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

ans=-10**20
m=[]
cycle=[0]*n
for i in range(n):
    now=i
    temp=[]
    s=0
    while True:
        now=p[now]-1
        s+=c[now]
        if temp==[]:
            temp.append(s)
        else:
            temp.append(max(temp[-1],s))
        if now==i:
            cycle[i]=s
            m.append(temp)
            break

for i in range(n):
    t=len(m[i])
    if cycle[i]<=0:
        if k>=t:
            ans=max(ans,m[i][t-1])
        else:
            ans=max(ans,m[i][k-1])

    else:
        x=k//t
        y=k%t
        if x>=1:
            temp=(x-1)*cycle[i]+m[i][t-1]
            ans=max(ans,temp)
            if y!=0:
                temp=x*cycle[i]+m[i][y-1]
                ans=max(ans,temp)
        else:
            ans=max(ans,m[i][k-1])

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if n is None:
            return

        if self.v is None:
            self.v = n
            return
        self.v = self.f(self.v, n) 


def main():
    N, K = read_values()
    P = read_list()
    C = read_list()

    res = V(max)
    for i in range(N):
        t = []
        c = 0
        p = i
        while len(t) == 0 or p != i:
            p = P[p] - 1
            c += C[p]
            t.append(c)

        m = len(t)
        # print(f"m: {m}, t: {t}, c: {c}")
        if m > K or c <= 0:
            res.ud(max(t[:K]))
        else:
            s = K // m * c
            k = K % m
            # print(f"s: {s}, k: {k}")
            tmp = V(max)
            for i in range(k):
                tmp.ud(s + t[i])
            
            s -= c
            for v in t:
                tmp.ud(s + v)
            
            res.ud(tmp.v)

    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

#高々N回で1周する
class UnionFind(object):
    def __init__(self, n):
        self._par = list(range(n))
        self.size = [1] * n
 
    def root(self, v):
        if self._par[v] == v:
            return v
        self._par[v] = self.root(self._par[v])
        return self._par[v]
 
    def unite(self, u, v):
        u, v = self.root(u), self.root(v)
        if u == v:
            return False
        if self.size[u] > self.size[v]:
            u, v = v, u # size[u] <= size[v]
        self.size[v] += self.size[u]
        self._par[u] = v
 
    def same(self, u, v):
        return self.root(u) == self.root(v)

uf = UnionFind(n)
for i in range(n):
    uf.unite(i, p[i])

ans = []
for i in range(n):
    ite = uf.size[uf.root(i)]
    #print(ite)
    if k > ite:
        memo = [0 for _ in range(ite+1)]
        tmp = i
        for j in range(ite):
            tmp = p[tmp]
            memo[j+1] = memo[j] + c[tmp]
        div = k // ite
        mod = k % ite
        #print(memo)
        if memo[-1] <= 0:
            ans.append(max(memo[1:]))
        else:
            m = max(memo[1:])
            ans.append(max(max(memo[:mod+1]) + div * memo[-1], (div-1) * memo[-1] + m))
    
    else:
        memo = [0 for _ in range(k+1)]
        tmp = i
        for j in range(k):
            tmp = p[tmp]
            memo[j+1] = memo[j] + c[tmp]
        ans.append(max(memo[1:]))
        

print(max(ans))

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
L = []
S = set()
for i in range(N):
    if i in S:
        continue
    L.append([C[i]])
    S.add(i)
    tmp = i
    Next = P[i] - 1
    while Next != tmp:
        S.add(Next)
        L[-1].append(C[Next])
        Next = P[Next] - 1

ans = 0

for l in L:
    score = 0
    k = len(l)
    SUM = sum(l)
    l = [0] + l + l
    if SUM > 0:
        score = SUM * (K // k)
        m = K % k
        for i in range(2 * k):
            l[i+1] += l[i]
        for i in range(k):
            for j in range(i+1, i+m+1):
                ans = max(ans, score + l[j] - l[i])
        if K // k >= 1:
            score = SUM * (K // k - 1)
            m = k
            for i in range(k):
                for j in range(i+1, i+m+1):
                    ans = max(ans, score + l[j] - l[i])
    else:
        m = k
        for i in range(2 * k):
            l[i+1] += l[i]
        for i in range(k):
            for j in range(i+1, i+m+1):
                ans = max(ans, score + l[j] - l[i])

if ans == 0:
    ans = max(C)

print(ans)

Submission status: Accepted

Solution code:
from itertools import product
from itertools import accumulate as acc

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
# N, K = 5000, 10**9
# P = list(range(1, N+1))
# C = list(range(N, -1, -1))
# # print(len(P), len(C))

P = [p-1 for p in P]

visited = [0]*N
g = []
for i in range(N):
    if visited[i]:
        continue
    g.append([])
    # print(g)
    while visited[i] == 0:
        g[-1].append(i)
        visited[i] = 1
        i = P[i]
c = [[C[g_j] for g_j in g_i] for g_i in g]
c_acc = [[0]+list(acc(c_i*2)) for c_i in c]
c_sum = [sum(c_i) for c_i in c]
c_len = [len(c_i) for c_i in c]

max_num = -(10**18)
for i, g_i in enumerate(g):
    for j, start in enumerate(g_i):
        for k, end in enumerate(g_i*2):
            if not (j < k):
                continue
            cost = k-j
            score = c_acc[i][k+1] - c_acc[i][j+1]
            if c_sum[i] > 0:
                count = (K-cost)//c_len[i]
                cost += c_len[i]*count
                score += c_sum[i]*count
            if 1 <= cost <= K:
                max_num = max(max_num, score)
            # print((j, k), score)

print(max_num)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
p = [int(pi) - 1 for pi in input().split()]
c = list(map(int, input().split()))
A = max(c)
seen = [False] * n
for i in range(n):
    if seen[i]:
        continue
    ids = []
    ccost = 0
    while not seen[i]:
        ccost += c[i]
        ids.append(i)
        seen[i] = True
        i = p[i]
    #print(ids)
    cn = len(ids)
    ccnt, m = divmod(k, cn)
    if ccnt > 0:
        ccnt -= 1
        m += cn
    ans = max(c[i] for i in ids)
    for s in ids:
        so = s
        now = 0
        for _ in range(m):
            s = p[s]
            now += c[s]
            #print(so+1, s+1, now)
            ans = max(now, ans)
    if ccost > 0:
        ans += ccnt * ccost
    A = max(A, ans)
print(A)

Submission status: Accepted

Solution code:
import sys
input=lambda: sys.stdin.readline().rstrip()
n,k=map(int,input().split())
P=[int(i) for i in input().split()]
C=[int(i) for i in input().split()]
A=[[0]*n]
Cur=[int(i)+1 for i in range(n)]
L=[0]*n
for _ in range(n):
  N=[0]*n
  for i in range(n):
    N[i]=A[-1][i]+C[P[Cur[i]-1]-1]
    Cur[i]=P[Cur[i]-1]
    if L[i]==0 and Cur[i]==i+1:
      L[i]=_+1
  A.append(N)
ans=max(A[1])
for i in range(n):
  ct=0
  loop=L[i]
  loop_ct=A[loop][i]
  rem=-float("inf")
  if k>loop and loop_ct>0:
    ct+=(k//loop-1)*loop_ct
    rem=0
    for j in range(loop):
      if j+1<=k%loop:
        rem=max(rem,A[j+1][i]+loop_ct)
      else:
        rem=max(rem,A[j+1][i])
    ans=max(ans,rem+ct)
  else:
    for j in range(min(k,n)):
      rem=max(rem,A[j+1][i])
    ans=max(ans,rem)
print(ans)

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    input = sys.stdin.readline

    N, K = map(int, input().split())
    P = [0] + list(map(int, input().split()))
    C = [0] + list(map(int, input().split()))

    ans = -10**10
    for v0 in range(1, N+1):
        seen = [0] * (N+1)
        seen[v0] = 1
        k = K
        score = 0
        v = v0
        ma = -10**10
        flg = 0
        S = [0] * (N+1)
        SK = [0] * (N+1)
        SK[v0] = k
        while True:
            nxt = P[v]
            score += C[nxt]
            if seen[nxt]:
                flg = 1
                score_loop = score - S[nxt]
                loop_size = SK[nxt] - k + 1
                k -= 1
                v = nxt
                break
            S[nxt] = score
            SK[nxt] = k-1
            ma = max(ma, score)
            seen[nxt] = 1
            v = nxt
            k -= 1
            if k == 0:
                break

        if flg:
            #print(v0, score_loop, loop_size, seen)
            if score_loop > 0:
                x = k // loop_size - 1
                score += score_loop * x
                k -= x * loop_size
                ma = max(ma, score)
            else:
                k = loop_size
            for _ in range(k):
                nxt = P[v]
                score += C[nxt]
                ma = max(ma, score)
                v = nxt
        ans = max(ans, ma)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

for i in range(n):
    p[i] -= 1
def score(a, k):
    now = p[a]
    s = c[now]
    cnt = 1
    l = [s]
    while now != a and cnt < k:
        now = p[now]
        s += c[now]
        l.append(s)
        cnt += 1
    if cnt == k:
        return max(l)
    l.append((k // cnt - 1) * s + max(l))
    s = (k // cnt) * s
    k %= cnt
    cnt=0
    while cnt < k:
        now = p[now]
        s += c[now]
        l.append(s)
        cnt += 1
    return max(l)
print(max(score(i, k) for i in range(n)))

Submission status: Accepted

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

ans = -float('inf')
visited = [False] * n
for i in range(n):
    if not visited[i]:
        visited[i] = True
        loop = [i]
        cost = [c[i]]
        while not visited[p[loop[-1]]]:
            visited[p[loop[-1]]] = True
            cost.append(c[p[loop[-1]]])
            loop.append(p[loop[-1]])

        total_cost = sum(cost)
        # print(loop)
        # print(cost)
        # print(total_cost)

        m = len(loop)
        point = [-float('inf')] * m
        for j1 in range(m):
            s = 0
            for j2 in range(1, min(m, k) + 1):
                s += cost[(j1 + j2) % m]
                point[j1] = max(point[j1], s, s + total_cost * ((k - j2) // m))

        # print(point)
        ans = max(ans, max(point))

print(ans)

Submission status: Accepted

Solution code:
def numba_compile(numba_config):
    import os, sys
    if sys.argv[-1] == "ONLINE_JUDGE":
        from numba import njit
        from numba.pycc import CC
        cc = CC("my_module")
        for func, signature in numba_config:
            globals()[func.__name__] = njit(signature)(func)
            cc.export(func.__name__, signature)(func)
        cc.compile()
        exit()
    elif os.name == "posix":
        exec(f"from my_module import {','.join(func.__name__ for func, _ in numba_config)}")
        for func, _ in numba_config:
            globals()[func.__name__] = vars()[func.__name__]
    else:
        from numba import njit
        for func, signature in numba_config:
            globals()[func.__name__] = njit(signature, cache=True)(func)
        print("compiled!", file=sys.stderr)

import numpy as np

def solve(N, K, P, C):
    ans = -10**18
    for start in range(N):
        t = 1
        s = 0
        idx = start
        while P[idx] != start:
            idx = P[idx]
            s += C[idx]
            t += 1
        s += C[start]
        q = K // t
        #print(R)
        score = 0
        #print(ans, s)
        if s >= 0:
            x = max(0, (q-2)*t)
            score += s * (x//t)
            #print(f"score={score}")
            idx = start
            for _ in range(x, K):
                idx = P[idx]
                score += C[idx]
                ans = max(ans, score)
        else:
            idx = start
            for _ in range(1, min(N, K+1)):
                idx = P[idx]
                score += C[idx]
                ans = max(ans, score)
    return ans

numba_compile([
    [solve, "i8(i8,i8,i8[:],i8[:])"],
])


def main():
    N, K = map(int, input().split())
    P = np.array(input().split(), dtype=np.int64)-1
    C = np.array(input().split(), dtype=np.int64)
    ans = solve(N, K, P, C)
    print(ans)

main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
input=sys.stdin.readline

n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ans=-10**18
for pos in range(n):
    value=0
    points=[]
    s=set()
    for j in range(n):
        s.add(pos)
        pos=p[pos]-1
        value+=c[pos]
        points.append(value)
        if pos in s:
            break
    loop_value=max(0,points[-1])
    l=len(s)
    for j in range(l):
        if j<(k%l):
            ans=max(ans,points[j]+loop_value*(k//l))
        else:
            ans=max(ans,points[j]+loop_value*(k//l-1))
print(ans)

Submission status: Accepted

Solution code:
import sys

def solve():
    input = sys.stdin.readline
    N, K = map(int, input().split())
    P = [int(p) - 1 for p in input().split()]
    C = [int(c) for c in input().split()]

    roopCount = [0] * N
    for i in range(N):
        index = i
        for j in range(N):
            if P[index] == i:
                roopCount[i] = j + 1
                break
            else: 
                index = P[index]

    maxPoint = -10 ** 20
    for i in range(N):
        visited = [-10 ** 14] * N
        point = 0
        index = i
        count = K
        while count > 0:
            index = P[index]
            if visited[index] == -10 ** 14:
                point += C[index]
                visited[index] = point
                count -= 1
            else:
                point += C[index]
                if point <= visited[index]:
                    maxPoint = max(maxPoint, max(visited))
                    break
                else:
                    count -= 1
                    add = point - visited[index]
                    visited[index] = point
                    
                    roop = count // roopCount[index]
                    visited[index] += add * roop
                    count %= roopCount[index]
                    point = visited[index]
                    for _ in range(count):
                        index = P[index]
                        point += C[index]
                        visited[index] = point
                    maxPoint = max(maxPoint, max(visited))
                    break
        else:
            maxPoint = max(maxPoint, max(visited))

    print(maxPoint)
    #print(roopCount)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, K = map(int, input().split())
    P = tuple(map(int, input().split())) #1行ベクトル
    C = tuple(map(int, input().split()))
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列

    
    tans=-float('inf')
    for i in range(N):
        start=i
        cur=P[i]-1
        score=C[cur]
        time=1
        ans=-float('inf')

        f2=0
        while True:
            
            if cur==start and f2==0:
                f2=1

                d=(K//time)
                if d>=2:
                    time=(d-1)*time
                    score=(d-1)*score

            ans=max(ans,score)


            cur=P[cur]-1
            score=score+C[cur]
            time=time+1
            if time>K:
                break
        tans=max(ans,tans)
    print(tans)





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
a=[-1]*n
ans=0
if sum([i<0 for i in c])==n:
    print(max(c))
    exit()
#一周した時のスコアを計算
for i in range(n):
    if a[i]!=-1:
        continue
    b=[i+1]
    while len(b)==len(set(b)):
        b.append(p[b[-1]-1])
    b.pop()
    e=len(b)
    d=sum([c[i-1] for i in b])
    for i in b:
        a[i-1]=[d,e]
for i in range(n):
    score=0
    tmp=i
    t=k%a[i][1]
    if a[i][0]>=0:
        score=a[i][0]*(k//a[i][1])
    tscore=score
    for j in range(t):
        tmp=p[tmp]-1
        tscore+=c[tmp]
        score=max(score,tscore)
    ans=max(ans,score)
for i in range(n):
    score=0
    tmp=i
    t=k%a[i][1]
    if k//a[i][1]==0:
        continue
    if a[i][0]>=0:
        score=a[i][0]*(k//a[i][1]-1)
    tscore=score
    for j in range(a[i][1]):
        tmp=p[tmp]-1
        tscore+=c[tmp]
        score=max(score,tscore)
    ans=max(ans,score)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,k=MI()
per=LI()
for i in range(n):
    per[i]-=1
points=LI()
ans=-inf
for i in range(n):
    val=0
    #res=[0 for j in range(n+1)]
    res=[]
    pos=per[i]
    inipos=per[i]
    count=0
    while True:
        val+=points[pos]
        pos=per[pos]
        if len(res)==0:
            res.append(val)
        else:
            res.append(max(res[-1],val))
        #res[count]=max(val,res[count-1])
        count+=1
        if pos==inipos:
            break
    loop=(val,count)
    #print(loop)
    #print(res)
    for x in range(len(res)):
        if loop[0]<=0:
            ans=max(ans,res[x])
        else:
            ans=max(ans,res[x]+loop[0]*((k-x-1)//loop[1]))
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


def calc(start, P, C, k):
    seen = {start}
    loop = 1
    pos = start
    res = 0
    maxim = -float("INF")
    for _ in range(k):
        next = P[pos]
        point = C[next]
        res += point
        pos = next
        if res > maxim:
            maxim = res
        if pos in seen:
            break
        seen.add(pos)
        loop += 1

    if res <= 0:
        return maxim
    if loop >= k + 1:
        return maxim
    residue = k - loop
    t = residue // loop
    residue %= loop
    max1 = res * t + maxim
    res *= (t+1)
    max2 = res
    for _ in range(residue):
        next = P[pos]
        point = C[next]
        res += point
        pos = next
        if res > max2:
            max2 = res

    return max(max1, max2)


def main():
    n, k = map(int, input().split())
    P = list(map(lambda x: int(x)-1, input().split()))
    C = list(map(int, input().split()))

    ans = -float("INF")
    for start in range(n):
        res = calc(start, P, C, k)
        if ans < res:
            ans = res

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

INF = 10**18


def main():

    N, K = in_nn()
    P = in_nl()
    C = in_nl()

    if K < N + 10:
        ans = -INF
        for i in range(N):
            score = 0
            max_score = -INF
            now = i

            for j in range(K):
                now = P[now] - 1
                score += C[now]
                max_score = max(score, max_score)
            ans = max(ans, max_score)

        print(ans)
        exit()

    else:

        ans = -INF
        for i in range(N):
            score = 0
            max_score = -INF
            now = i
            search = {now}
            move_cnt = 0

            for _ in range(N + 10):
                now = P[now] - 1
                score += C[now]
                max_score = max(score, max_score)
                move_cnt += 1

                if now in search:
                    break
                search.add(now)

            if score < 0:
                ans = max(ans, max_score)
            else:
                tk = (K % move_cnt) + move_cnt
                score = score * (K // move_cnt - 1)
                max_score = score
                now = i
                for x in range(tk):
                    now = P[now] - 1
                    score += C[now]
                    max_score = max(score, max_score)
                ans = max(ans, max_score)

    print(ans)


if __name__ == '__main__':
    main()