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:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


class Doubling():
    def __init__(self, a0, M, C):
        """
        a0 is an array-like object which contains ai, 0 <= i < N.
        ai is the next value of i.
        """
        N = len(a0)
        self.N = N
        self.nt = [[None] * N for i in range(M.bit_length()+1)]
        self.s = [[0] * N for i in range(M.bit_length()+1)]
        for i, a in enumerate(a0):
            self.nt[0][i] = a
            self.s[0][i] = C[a]

        for i in range(1, len(self.nt)):
            for j in range(N):
                if self.nt[i-1][j] is None:
                    self.nt[i][j] = None
                else:
                    self.nt[i][j] = self.nt[i-1][self.nt[i-1][j]]
                    self.s[i][j] = self.s[i-1][self.nt[i-1][j]] * (1<<i)

    def apply(self, i, n):
        """
        Apply n times from i
        """
        j = i
        s = 0
        for k in range(n.bit_length()):
            m = 1 << k
            if m & n:
                j = self.nt[k][j]
                s += self.s[k][j]
            if j is None:
                break

        return j, s


@mt
def slv(N, K, P, C):
    P = [p-1 for p in P]
    S = [[0] * (N+1) for _ in range(N)]


    if K < 2*N:
    # if True:
        ans = -INF
        for i in range(N):
            c = i
            a = 0
            for j in range(K):
                n = P[c]
                a += C[n]
                ans = max(ans, a)
                c = n
        error_print('--')
        return ans

    ga = -INF
    for i in range(N):
        c = i
        done = {c: 0}
        # S[i][0] = C[i]
        ans = -INF
        for j in range(1, N+1):
            n = P[c]
            S[i][j] = C[n] + S[i][j-1]
            c = n
            if n in done:
                break
            else:
                done[n] = j
        ans = max(ans, S[i][1])
        ans = max(ans, S[i][done[n]])
        if S[i][j] - S[i][done[n]] > 0:
            ans = S[i][done[n]]
            a = S[i][j] - S[i][done[n]]
            l = j - done[n]
            k = K - done[n]
            m = (k // l)
            if m > 0:
                m -= 1
            ans += a * m
            rem = K - m * l - done[n]
            c = n
            b = ans
            for _ in range(rem):
                n = P[c]
                b += C[n]
                ans = max(ans, b)
                c = n
        # ans -= C[i]
        # print(i, ans)
        ga = max(ga, ans)

    return ga


    # from pprint import pprint
    # pprint(S)

    # for i in range(N):



def main():
    N, K = read_int_n()
    P = read_int_n()
    C = read_int_n()
    print(slv(N, K, P, C))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
input = sys.stdin.readline
INF = float("inf")


# 処理内容
def main():
    N, K = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))

    ans = max(C)

    if K <= N:
        for i in range(N):
            score = 0
            v = P[i] - 1
            for _ in range(K):
                score += C[v]
                ans = max(score, ans)
                v = P[v] - 1
    else:
        for i in range(N):
            score = 0
            S = 0
            v = P[i] - 1
            for _ in range(N):
                S += C[v]
                ans = max(S, ans)
                v = P[v] - 1

            m = K // N
            q = K % N
            if m * S > 0:
                score += m * S
                ans = max(score, ans)

            for _ in range(q):
                score += C[v]
                ans = max(score, ans)
                v = P[v] - 1   
        
    print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    N,K = map(int,input().split())
    P_list = tuple(map(int,input().split()))
    C_list = tuple(map(int,input().split()))
    for d in C_list:
        if d > 0:
            break
    else:
        print(min(C_list))
        

    max_sum=-10**9
    for i in range(N):
        m_sum=0
        k=i
        for j in range(K):
            m_sum += C_list[k]
            if C_list[k] >= 0 and m_sum > max_sum:
                max_sum=m_sum
            k=P_list[k]-1
    print(max_sum)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    INF = 10 ** 15
    N, K = list(map(int, input().split()))
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    # P のループの最初を検索しておく
    loop_list = list()
    visited = [0] * N
    for i in range(N):
        if visited[i] == 1:
            continue
        start = i
        size = 0
        sum_c = 0
        while visited[i] == 0:
            visited[i] = 1
            size += 1
            sum_c += C[i]
            i = P[i]
        loop_list.append((start, size, sum_c))
    # 各ループごとに考える
    ans = - INF
    for start, size, sum_c in loop_list:
        MAX_LEN = K % size
        if MAX_LEN == 0:
            MAX_LEN = K
        # 2順ループを作っておく
        CUMSUM_CC = [0] * (2 * size)
        cur_index = P[start]
        CUMSUM_CC[0] = C[P[start]]
        for i in range(1, 2 * size):
            cur_index = P[cur_index]
            CUMSUM_CC[i] += C[cur_index] + CUMSUM_CC[i - 1]
        # 最大MAX_LENの連続部分列での最大スコア
        max_score = - INF
        for left in range(2 * size):
            for right in range(left, min(2 * size, left + MAX_LEN)):
                s = CUMSUM_CC[right]
                if left > 0:
                    s -= CUMSUM_CC[left - 1]
                max_score = max(max_score, s)
        if sum_c > 0 and MAX_LEN != K:
            max_score += sum_c * (K // size)
        ans = max(ans, max_score)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

n,k = ip()
P = [0]+ip()
C = [0]+ip()
dt = {}
for i in range(1,n+1):
    dt[P[i]] = C[i]
vis = {}
x = []
for i in range(1,n+1):
    if vis.get(P[i],1):
        vis[P[i]] = 0
        x.append([dt[P[i]]])
        cur = P[P[i]]
        while cur != P[i]:
            x[-1].append(dt[cur])
            vis[cur] = 0
            cur = P[cur]
#print(x)

def find(arr,size):
    l = len(arr)
    if size == 1:
        return max(arr)
    arr = arr + arr
    t = sum(arr[:size])
    for i in range(size,l+size):
        t = max(t,t+arr[i]-arr[i-size])
    return t

ans = float('-inf')
for cycle in x:
    if sum(cycle) > 0:
        msize = 0
        mx = float('-inf')
        for leng in range(1,len(cycle)):
            t = find(cycle,leng)
            if t > mx:
                mx = t
                msize = leng
        ans = max(ans,(sum(cycle)*(k//len(cycle)))+mx)
    else:
        mx = float('-inf')
        for leng in range(1,len(cycle)):
            t = find(cycle,leng)
            if t > mx:
                mx = t
                msize = leng
        ans = max(ans,mx)
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
N, K = map(int, input().split())
*P, = map(int, input().split())
*C, = map(int, input().split())

P = [p-1 for p in P]

used = [0]*N
ans = -float('inf')
for x in range(N):
    if used[x]:
        continue
    used[x] = 1
    Q = [C[x]]

    while not used[P[x]]:
        x = P[x]
        used[x] = 1
        Q.append(C[x])

    M = len(Q)
    acc = list(accumulate(Q*2))
    if acc[M-1] > 0:
        ret = acc[M-1]*(K//M)
        ret += max(acc[K % M+i] - acc[i] for i in range(M))

    else:
        R = Q*2
        ret = -float('inf')
        prev = 0
        cnt = 0
        for i, r in enumerate(R):
            if cnt >= K:
                prev -= R[i-K]
                cnt -= 1
            if prev+r > r:
                cnt += 1
                s = prev + r
            else:
                cnt = 1
                s = r
            s = max(r, prev+r)
            ret = max(ret, s)
            prev = s

    if ret > ans:
        ans = ret

print(ans if ans > -float('inf') else max(C))

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

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


def solve(x):

    cnt = 0
    arr = [c[x]]
    start = p[x]
    nxt = p[x]
    if nxt in q:
        q.remove(nxt)
    flg = 0
    while cnt < n * 2 - 1:
        arr.append(c[nxt])
        nxt = p[nxt]
        cnt += 1
        if nxt == start and flg == 0:
            cycle = cnt
            flg = 1

    div, mod = divmod(k, cycle)

    ans = max(sum(arr[:cycle]) * div, 0)

    tmp = max(arr)

    a = [0] + list(accumulate(arr))
    for i in range(cycle * 2 - mod):
        for j in range(i + 1, i + 1 + mod):
            tmp = max(tmp, a[j] - a[i])

    return ans + tmp


q = list(range(n))

ans = -10000000000000

while q:
    curr = q.pop()
    ans = max(ans, solve(curr))

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = list(map(int, input().split()))
ans = max(C)
C = [0] + C

roop, fact = [], set()
for i in range(1, N+1):
    if i in fact:
        continue
    else:
        s = i
        fact.add(s)
        root = [s]
        while P[s] not in fact:
            s = P[s]
            root.append(s)
            fact.add(s)
        roop.append(root)

for x in range(len(roop)):
    length = len(roop[x])
    roop_score = [[C[roop[x][i]] for i in range(length)]]
    per_roop = 0

    if length <= K:
        per_roop = sum(roop_score[0])
        ans = max(ans, K//length * per_roop)
    if length < K:
        ans = max(ans, max(roop_score[0]) + (K - 1)//length * per_roop)

    for i in range(1, min(length-1, K)):
        roop_score.append([])
        for j in range(length):
            roop_score[i].append(roop_score[0][j-1] + roop_score[i-1][j])
        ans = max(ans, max(roop_score[i]) + (K - (i+1))//length * max(0, per_roop))

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')

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


ans = - (10 ** 9 + 1) 
for i in range(N):
    res = [0] * (N + 1)
    seen = [0] * N
    k = 0
    pos = i
    while True:
        if seen[pos]:
            break
        if k >= K:
            break
        seen[pos] = 1
        pos = P[pos] - 1
        k += 1
        # print("k: {} pos: {}".format(k, pos))
        res[k] = res[k-1] + C[pos]
    # TODO: 10 ** 9を無視した実装
    # print("i: {} k: {} res: {}".format(i, k, res))

    ans = max(ans, max(res[1:]))
    if k < K:
        # kのループが存在する
        if res[k] > 0:
            q, mod = divmod(K, k)
            tmp_ans = (res[k] * q) + res[mod]
            ans = max(ans, tmp_ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import math
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))

pused = []
looplist = []

for i in range(1, N+1):
    if i in pused:
        continue
    loop = [i]
    pused.append(i)
    p = P[i]
    while p not in pused:
        pused.append(p)
        loop.append(p)
        p = P[p]
    looplist.append(loop)


ans = []
for loop in looplist:
    wloop = loop + loop
    pts = [-1*math.inf] * (len(loop) + 1)
    for startind in range(len(loop)):
        for l in range(len(loop)):
            wa = C[wloop[startind]]
            for _ in range(l):
                x = startind
                wa += C[wloop[x+1]]
                x += 1
            if wa > pts[l+1]:
                pts[l+1] = wa

    loopwa = 0
    for i in range(len(loop)):
        loopwa += loop[i]

    if loopwa >= 0:
        if K > len(loop):
            pt = loopwa*(K//len(loop)) + pts[K - len(loop)*(K//len(loop))]
            ans.append(pt)
        else:
            ans.append(max(pts[:K+1]))

    else:
        ans.append(max(pts[:K+1]))
print(max(ans))

Submission status: Wrong Answer

Solution code:
N,K=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

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

        if x == y:
            return

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

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

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

Q=[]
uf=UnionFind(N)
for i in range(N):
    uf.union(i,P[i]-1)
D1=list(uf.all_group_members().values())
D2=[]
for i in D1:
    ans=0
    for j in i:
        ans+=C[j]
    D2.append(ans)
L=[len(i) for i in D1]
S=min(2*max(L),K)

for i in range(N):
    ans=-float('inf')
    ans1=0
    now=P[i]-1
    for j in range(S):
        ans1+=C[now]
        now=P[now]-1
        ans=max(ans1,ans)
    Q.append(ans)
    
for i,value in enumerate(D2):
    ans3=value*(K//L[i])
    for j in D1[i]:
        ans=-float('inf')
        ans1=0
        now=P[j]-1
        for k in range(K%L[i]):
            ans1+=C[now]
            now=P[now]-1
            ans=max(ans1,ans)
        Q.append(ans3+ans)
print(max(Q))

Submission status: Wrong Answer

Solution code:
import copy
import math
import time
import statistics
import math
import itertools
import bisect
from decimal import *

# a = get_int()
def get_int():
    return int(input())
# a = get_string()
def get_string():
    return input()
# a_list = get_int_list()
def get_int_list():
    return [int(x) for x in input().split()]
# a_list = get_string_list():
def get_string_list():
    return input().split()
# a, b = get_int_multi()
def get_int_multi():
    return map(int, input().split())
# a_list = get_string_char_list()
def get_string_char_list():
    return list(str(input()))
# print("{} {}".format(a, b))
# a_list = [0] * a
'''
while (idx < n) and ():

    idx += 1
'''

def main():

    start = time.time()

    n, k = get_int_multi()
    p = get_int_list()
    c = get_int_list()

    kaisuu = [-1] * n
    score = [0] * n
    score_max = [0] * n

    link = [-1] * n
    link_saki = [-1] * n
    link_score = [0] * n
    link_score_max = [0] * n



    for i in range(n):
        wk = 0
        wk2 = 0
        ichi = i
        for ii in range(n):
            ichi = p[ichi] -1
            wk += c[ichi]
            wk2 = max(wk2, wk)
            if i == ichi:
                kaisuu[i] = ii+1
                score[i] = wk
                score_max[i] = wk2
                break

            if kaisuu[ichi] > 0:
                link[i] = ii+1
                link_saki[i] = ichi
                link_score[i] = wk
                link_score_max[i] = wk2
                break



    #print(time.time() - start)

    wk = 0
    ans = - 10 ** 20
    for i in range(n):
        ichi = p[i] -1
        wk = c[ichi]
        wk2 = c[ichi]
        idx = 0
        while idx < k-1:

            #ループするならメモを使って減らす
            if ((k - 1 - idx) > kaisuu[ichi]) and kaisuu[ichi] > 0:
                roopsuu = (k - 1 - idx) // kaisuu[ichi]
                wk += roopsuu * score[ichi]
                idx += roopsuu * kaisuu[ichi]
                wk2 = max(wk2, max(wk, score_max[ichi]))
                continue

            #Linkするならメモを使って減らす
            if ((k - 1 - idx) > link[ichi]) and link[ichi] > 0:
                idx += link[ichi]
                wk += link_score[ichi]
                wk2 = max(wk, max(wk, link_score_max[ichi]))
                ichi = link_saki[ichi]

                continue

            ichi = p[ichi] -1
            wk += c[ichi]

            wk2 = max(wk2, wk)
            idx += 1

        ans = max(ans , wk2)
    print(ans)
    #print(time.time() - start)




if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
INF = float('inf')
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]

max_score = -INF
for init in range(1, N + 1):   # 初めの場所をiとする
    score = defaultdict(int)  # int/bool/list....
    visited = defaultdict(bool)  # int/bool/list....
    visited[init] = True
    i = init
    max_init = -INF
    for k in range(1, K + 1):
        # score[P[i]] = score[i] + C[P[i]]
        prev = i
        i = P[i]    # k回移動後に着くところ
        if visited[i]:
            if k == K:  break # これ以上移動できない
            start = i   # ループを開始するノード
            loop_score = 0
            loop_len = 0
            # ループを探す
            jj = start
            while P[jj] != start:
                jj = P[jj]
                loop_score += C[jj]
                loop_len += 1
            loop_score += C[start]
            loop_len += 1

            loop_num = (K - k) // loop_len # ループを何回回れるか
            loop_rem = (K - k) % loop_len

            if loop_rem == 0:
                loop_num -= 1
                loop_rem = loop_len

            jj = start
            temp = 0
            temp_max = 0
            for l in range(loop_rem):
                jj = P[jj]
                temp += C[jj]
                temp_max = max(temp_max, temp)

            loop_max = temp_max + max(loop_num * loop_score, 0)
            # max_init = max(max(score.values()), score[start] + loop_max)
            max_init = max(max_init, score[start] + loop_max)

        # まだ訪れたことのないところ
        score[i] = score[prev] + C[i]
        max_init = max(max_init, score[i])
    max_score = max(max_score, max_init)

if max_score == -INF:
    max_score = max(C[1:])

print(max_score)

Submission status: Wrong Answer

Solution code:
# -*- coding:utf-8 -*-


def solve():
    N, K = list(map(int, input().split()))
    Ps = list(map(int, input().split()))
    Cs = list(map(int, input().split()))

    # 最低一回は移動させないといけないの忘れてた
    ans = -float("inf")
    for i in range(N):
        ans = max(ans, Cs[i])

    loop_list = []
    for now in range(N):
        visited = set()
        visited.add(now)
        move = 0
        total_score = 0
        max_score = ans

        while True:  # たかだかN回
            nx = Ps[now]-1
            total_score += Cs[nx]
            max_score = max(max_score, total_score)
            move += 1
            if nx in visited:
                # 一周した
                if total_score > 0:
                    # 一周する価値あるので、loop_listに追加
                    loop_list.append((now, total_score, move))
                break

            # 一周してない
            if move == K:
                # もう移動できないので終わり
                break
            visited.add(nx)
            now = nx
        ans = max(ans, max_score)


    # 一周した方が得かつ、移動回数が余っているなら、ぐるぐる回る
    for s, score, move in loop_list:
        total_score = score*(K//move)
        restK = K % move
        max_score = total_score

        now = s
        while restK != 0:
            restK -= 1
            nx = Ps[now]-1
            total_score += Cs[nx]
            max_score = max(max_score, total_score)
            now = nx
        ans = max(ans, max_score)

    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"

def main():
    n,k = map(int,ipt().split())
#    n = 5000
#    k = 1
    p = [int(i)-1 for i in ipt().split()]
#    p = [(i-1)%n for i in range(n)]
#    c = [10**9 for i in range(n)]
    c = [int(i) for i in ipt().split()]
    ma = -10**18
    al = [False]*n
    for i in range(n):
        if al[i]:
            continue
        pts = []
        nap = i
        for j in range(n):
            nap = p[nap]
            pts.append(c[nap])
            al[nap] = True
            if nap == i:
                break
        ln = len(pts)
        jt = (k-1)%ln
        jt += 1
        sma = 0
        for jp in pts:
            sma += jp
        if sma > 0:
            nm = ((k-1)//ln)*sma
        else:
            nm = 0
        ma1 = -10**18
#        print(pts,al)
        for ji in range(ln):
            sm = 0
            for jj in range(jt):
                sm += pts[ji-jj]
#                print(i,j,j-jj,sm)
                if ma1 < sm:
                    ma1 = sm
        ma1 += nm
        if ma < ma1:
            ma = ma1
#        print(ma)

    print(ma)




    return None

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def resolve():
    '''
    code here
    '''
    N, K = [int(item) for item in input().split()]
    Ps = [int(item)-1 for item in input().split()]
    Cs = [int(item) for item in input().split()]

    loops = [[0 for _ in range(N)] for _ in range(N)]
    for i in range(N):
        next_node = i
        loops[i][i] = 1
        while True:
            next_node = Ps[next_node]
            if loops[i][next_node] != 1:
                loops[i][next_node] = 1
            else:
                break

    prio_num = [0 for _ in range(N)]
    for i in range(N):
        prio_num[i] = sum(loops[i])

    # print(prio_num)
    res_list = [0 for _ in range(N)]
    for i in range(N):
        num = K % prio_num[i]
        if num == 0:
            num = K

        prio = prio_num[i]
        cnt = 0
        temp_num = 0
        prio_num1 = 0

        next_node = i
        temp_max = -10000000000000000
        while cnt < prio:
            next_node = Ps[next_node]
            prio_num1 += Cs[next_node]
            
            if cnt < num:
                temp_num += Cs[next_node]
                temp_max = max(temp_max, temp_num)
                # print(i, temp_num, temp_max)
            cnt += 1

        if prio_num1 > 0:
            res_list[i] = temp_max + prio_num1 * (K //prio)
        else:
            res_list[i] = temp_max

    # print(res_list)
    print(max(res_list))

if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 63


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] <= 0 or K <= len(loop)-2:
                j = i
                max_val = -INF
                iter = 0
                done = False
                while iter <= K:
                    if j >= len(loop):j=0
                    if i != j and j:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    iter += 1
                    if done : break
                    if i == j: done = True
                ans = max(ans, max_val)
                continue


            rest = K
            #if K <= len(loop) - i - 1:
            #    val += loopSum[i + K - 1] - loopSum[i]
            #    ans = max(ans, val)
            #    continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            val += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(lambda x:int(x) - 1, input().split()))
C = list(map(int, input().split()))
scores = []


def max_sum(lst):
    maximum = 0
    temp = 0
    for i in lst:
        temp += C[i]
        maximum = max(maximum, temp)
    return maximum


for i in range(N):
    count = 0
    now = i
    passed = []
    while count <= K:
        nxt = P[now]
        count += 1
        if nxt in passed:
            break
        passed.append(nxt)
        now = nxt
    
    point = 0
    if count <= K:
        steps = len(passed)
        lp_points = sum(C[pos] for pos in passed)
        if lp_points > 0:
            lp_cnt = K // steps
            point += lp_points * lp_cnt
            rest = passed[:K - steps * lp_cnt]
            point += max_sum(rest)
        else:
            point = max_sum(passed)
    else:
        point = C[passed[0]]
        point += max_sum(passed[1:])
    scores.append(point)

print(max(scores))