Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
            j = p[j] - 1
        # le = len(l)
        # l *= (k//le +2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
import math
import numpy as np
import collections
import bisect
from collections import deque
from copy import copy, deepcopy
 
 
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    ans=-10e10
    tmp_sum_list = [None for i in range(N)]
    for p in range(1,N+1):
        _p=p
        end=False
        tmp_list=[]
        p_list=[]
        if tmp_sum_list[p-1] is None:
            for i in range(N):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_sum=sum(tmp_list)
            tmp_len=len(tmp_list)
            for _p in p_list:
                tmp_sum_list[_p-1]=(tmp_sum,tmp_len)

        if tmp_sum_list[p-1][0]<=0:
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            for i in range(tmp_sum_list[p-1][1]):            
                if p==P[_p-1]:
                    end=True
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                p_list.append(_p)
                if end:
                    break
            tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans=tmp_max
        else:
            tmp_ans=(K//(tmp_sum_list[p-1][1]))*tmp_sum_list[p-1][0]
            tmp_sum=0
            tmp_max=0
            tmp_list=[]
            mod = K%tmp_sum_list[p-1][1]
            for j in range(mod):
                _p=P[_p-1]
                tmp_list.append(C[_p-1])
                tmp_max=max(np.cumsum(np.array(tmp_list,dtype=np.int64)))
            tmp_ans+=tmp_max

        ans = max(ans,tmp_ans)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
            l.append(c[p[j]-1])
        #     j = p[j] - 1
        # le = len(l)
        # l *= (k//le +2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

print(ans)

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()]

ans = -10000000000
for i in range(N):
    x = i
    A = C[x]
    maxA = A
    length = 1 
    point = 1 
    while(P[x] != i and length<K):
        x = P[x]
        A += C[x]
        length += 1
        if A > maxA:
            maxA = A
            point = length
    if A > 0 and (K - point) // length > 0 :
        maxA += ((K - point) // length) * A
    ans = max(ans, maxA)

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = c[0]
jud = []
for i in range(n):
    if i not in jud:
        l = []
        j = p[i] - 1
        while j not in jud:
            jud.append(j)
        #     l.append(c[p[j]-1])
        #     j = p[j] - 1
        # le = len(l)
        # l *= (k//le +2)
        # for ii in range(le):
        #     val = l[ii]
        #     ans = max(ans,val)
        #     for cnt in range(ii+1, ii + k):
        #         val += l[cnt]
        #         ans = max(val, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')

n,k = [int(x) for x in input().split()]
perm  =  [int(x)-1 for x in input().split()]
cost = [int(x) for x in input().split()]


ans = -10**9
for node in xrange(n):
    visited = [False for _ in xrange(n)]
    curnode = perm[node]
    cost_lst = [0]
    while not visited[curnode]:
        visited[curnode] = True
        cost_lst.append(cost_lst[-1] + cost[curnode])
        curnode = perm[curnode]

    cycles_n = k // (len(cost_lst)-1)
    rem = k % (len(cost_lst)-1)

    if cycles_n > 0:
        ans = max(ans, max(cost_lst[1:]))
    if cycles_n == 0:
        ans = max(ans, max(cost_lst[1:rem+1]))
    if cycles_n > 0 and cost_lst[-1] > 0:
        if rem != 0:
            opt1 = cycles_n * cost_lst[-1] + max(cost_lst[1:rem+1])
        else:
            opt1 = cycles_n * cost_lst[-1]
        ans = max(ans, opt1)

print(ans)

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()))

ans=0
check=set()

for i in range(N):
    
    if i in check:
        continue
    
    # create loop
    tmpK=K
    tmpans=0
    loop_check=set()
    tmp_idx=i
    loop=[]
    while tmp_idx not in loop_check:
        loop.append(C[tmp_idx])
        loop_check.add(tmp_idx)
        check.add(tmp_idx)
        tmp_idx=P[tmp_idx]
    
    S=sum(loop)
    L=len(loop)
    if S>=0 and tmpK//L>=2:
        tmpans=S*(tmpK//L-1)
        tmpK=tmpK%L+L
    
    # 部分最大列を検索
    #print('loop',loop)
    loop=[0]+loop*2
    for i in range(len(loop)-1):
        loop[i+1]+=loop[i]
    n=2*L
    def init_min(init_min_val):
        #set_val
        for i in range(n):
            seg_min[i+num_min-1]=init_min_val[i]    
        #built
        for i in range(num_min-2,-1,-1) :
            seg_min[i]=min(seg_min[2*i+1],seg_min[2*i+2])
    def query_min(p,q):
        if q<=p:
            return ide_ele_min
        p += num_min-1
        q += num_min-2
        res=ide_ele_min
        while q-p>1:
            if p&1 == 0:
                res = min(res,seg_min[p])
            if q&1 == 1:
                res = min(res,seg_min[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = min(res,seg_min[p])
        else:
            res = min(min(res,seg_min[p]),seg_min[q])
        return res
    #####単位元######
    ide_ele_min = 10**15
    #num_min:n以上の最小の2のべき乗
    num_min =2**(n-1).bit_length()
    seg_min=[ide_ele_min]*2*num_min

    init_min(loop)
    local_max=0
    for i,v in enumerate(loop):
        if i>=1:
            #print('v,min=',v,query_min(max(0,i-tmpK),i),v-query_min( max(0,i-tmpK),i ))
            local_max=max(local_max,v-query_min( max(0,i-tmpK),i ) )
    
    ans=max(ans,local_max+tmpans)

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

Submission status: Wrong Answer

Solution code:
import copy

def cost_val(visit_list, P, C):
    maxval = [-10**10] * (len(P) + 1)
    for start_idx in visit_list:
        cost = 0
        now_id = start_idx
        for i in range(len(visit_list)):
            now_id = P[now_id]
            cost += C[now_id]
            maxval[i + 1] = max(maxval[i + 1], cost)
    return maxval[1:len(visit_list) + 1]

def cycles(P):
    cycle_list = []
    visit_list = [False] * len(P)
    for i in range(len(P)):
        if visit_list[i]:
            continue
        now_id = i
        cycle = []
        for j in range(len(P)):
            if visit_list[now_id]:
                break
            cycle.append(now_id)
            visit_list[now_id] = True
            now_id = P[now_id]
        cycle_list.append(cycle)
    return cycle_list

def main():
    N, K = map(int, input().split())
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    cycle_list = cycles(P)
    ans = max(C)
    for cycle in cycle_list:
        maxval = cost_val(cycle, P, C)
        if len(cycle) > K:
            ans = max(ans, max(maxval[:K]))
        else:
            if K % len(cycle) == 0:
                ans = max(ans, max(maxval), maxval[-1] * (K // len(cycle)))
            else:
                ans = max(ans, max(maxval), maxval[-1] * (K // len(cycle)) + max(maxval[:(K % len(cycle))]))
    return ans

if __name__ == '__main__':
    print(main())

Submission status: Wrong Answer

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**18
P = list(map(lambda x: x-1, P))

for i in range(N):
    visit = [False]*N
    now = i
    l = []
    visit[now] = True
    
    for j in range(N+10):
        nex = P[now]
        l.append(C[nex])
        
        if visit[nex]:
            break
        
        visit[nex] = True
        now = nex
    
    su = sum(l)
    
    if su>=0:
        if K>=len(l):
            now = su*(K//len(l))
            rem = K%len(l)
            ans = max(ans, now)
        
            for j in range(rem):
                now += l[j]
                ans = max(ans, now)
                
            now = l[0]
            ans = max(ans, now)
            
            for j in range(1, len(l)):
                now += l[j]
                ans = max(ans, now)
        else:
            now = l[0]
            ans = max(ans, now)
            
            for j in range(1, K):
                now += l[j]
                ans = max(ans, now)
    else:
        now = l[0]
        ans = max(ans, now)
        
        if K<len(l):
            for j in range(1, K):
                now += l[j]
                ans = max(ans, now)
        else:
            for j in range(1, len(l)):
                now += l[j];
                ans = max(ans, now)

print(ans)

Submission status: Wrong Answer

Solution code:

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

N,K = map(int,input().split())

P = tuple(map(lambda x: int(x)-1,input().split()))
C = tuple(map(int,input().split()))

acc = [0]*N
visited = [-1]*N
last = [0]*N

res = -10**9

for p in range(N):
    c = 0
    v = p
    for j in range(N+1):
        if visited[v] == p:
            break
        visited[v] = p
        acc[v] = c
        last[v] = j
        c += C[v]
        v = P[v]
        res = max2(c,res)

    i = last[v]

    delta = c - acc[v]
    remaining = K - i
    cycle = j-i
    if delta > 0 and remaining >= cycle:
        cnt = remaining//cycle - 1
        c = acc[v]+cnt*delta
        remaining -= cnt*cycle
        for _ in range(remaining):
            c += C[v]
            res = max2(res, c)
            v = P[v]

print(res)

Submission status: Wrong Answer

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

P = [p-1 for p in list(map(int, input().split()))]
C = list(map(int, input().split()))

max_points = []
for i in range(N):
    max_point = 0
    visit = [0] * N
    visit[i] = 1
    S = [0]
    pos = P[i]
    loop = 0  # P は順列なので、すでにvisitした点に戻ったとき、loopが位数となる
    while True:
        if visit[pos] == 0:
            visit[pos] = 1
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
        else:
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
            break

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop_point > 0:
        max_point += loop_point * (K // loop)
        resi = K % loop
        if resi:
            max_point += max(S[0:resi+1])
    else:
        max_point = max(S[1:loop])

    max_points.append(max_point)

print(max(max_points))

Submission status: Wrong Answer

Solution code:
import copy

def cost_val(visit_list, P, C):
    maxval = [-10**10] * (len(P) + 1)
    for start_idx in visit_list:
        cost = 0
        now_id = start_idx
        for i in range(len(visit_list)):
            now_id = P[now_id]
            cost += C[now_id]
            maxval[i + 1] = max(maxval[i + 1], cost)
    return maxval[1:len(visit_list) + 1]

def cycles(P):
    cycle_list = []
    visit_list = [False] * len(P)
    for i in range(len(P)):
        if visit_list[i]:
            continue
        now_id = i
        cycle = []
        for j in range(len(P)):
            if visit_list[now_id]:
                break
            cycle.append(now_id)
            visit_list[now_id] = True
            now_id = P[now_id]
        cycle_list.append(cycle)
    return cycle_list

def main():
    N, K = map(int, input().split())
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    cycle_list = cycles(P)
    ans = max(C)
    for cycle in cycle_list:
        maxval = cost_val(cycle, P, C)
        if K % len(cycle) == 0:
            ans = max(ans, max(maxval), maxval[-1] * (K // len(cycle)))
        else:
            ans = max(ans, max(maxval), maxval[-1] * (K // len(cycle)) + max(maxval[:(K % len(cycle))]))
    return ans

if __name__ == '__main__':
    print(main())

Submission status: Wrong Answer

Solution code:
import sys, math
from functools import lru_cache
from collections import defaultdict
sys.setrecursionlimit(500000)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N, K = mi()
    P = list(mi())
    C = list(mi())
    m = -10**100

    # loopを格納
    loops = []
    # 数えたかどうか
    done = [False]*N
    
    for i in range(N):
        # もう数えているならskip
        if done[i]:
            continue

        now = P[i]-1
        T = 1
        s = C[now]
        lst = [now]

        done[now] = True

        # 戻ってくるまでループ
        while now != i:
            now = P[now]-1
            T += 1
            s += C[now]
            lst.append(now)

            done[now] = True

        loops.append((T, s, lst))

    # print(loops)

    ans = -10**100
    # 各loopごと
    for loop in loops:
        # loopの周期、総和、構成要素を取得
        T, s, lst = loop

        # loopの周回回数
        n = max(K//T-1, 0) if s > 0 else 0

        # loopをn周した時のscore
        score = s*n

        # loopをn周した後の残り
        rest = K-n*T if s > 0 else T

        # 残りで移動した時の最大値を計算
        for v in lst:
            now = v
            s = 0
            for _ in range(rest):
                now = P[now]-1
                s += C[now]
                m = max(m, s)
        
        ans = max(score+m, ans)

    print(ans)



if __name__ == '__main__':
    main()

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()))

ans=0
check=set()

for i in range(N):
    
    if i in check:
        continue
    
    # create loop
    tmpK=K
    tmpans=0
    loop_check=set()
    tmp_idx=i
    loop=[]
    while tmp_idx not in loop_check:
        loop.append(C[tmp_idx])
        loop_check.add(tmp_idx)
        check.add(tmp_idx)
        tmp_idx=P[tmp_idx]
    
    S=sum(loop)
    L=len(loop)
    if S>=0 and tmpK//L>=2:
        tmpans=S*(tmpK//L-1)
        tmpK=tmpK%L+L
    
    # 部分最大列を検索
    #print('loop',loop)
    loop*=2
    for i in range(len(loop)-1):
        loop[i+1]+=loop[i]
    n=2*L
    def init_min(init_min_val):
        #set_val
        for i in range(n):
            seg_min[i+num_min-1]=init_min_val[i]    
        #built
        for i in range(num_min-2,-1,-1) :
            seg_min[i]=min(seg_min[2*i+1],seg_min[2*i+2])
    def query_min(p,q):
        if q<=p:
            return ide_ele_min
        p += num_min-1
        q += num_min-2
        res=ide_ele_min
        while q-p>1:
            if p&1 == 0:
                res = min(res,seg_min[p])
            if q&1 == 1:
                res = min(res,seg_min[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = min(res,seg_min[p])
        else:
            res = min(min(res,seg_min[p]),seg_min[q])
        return res
    #####単位元######
    ide_ele_min = 10**15
    #num_min:n以上の最小の2のべき乗
    num_min =2**(n-1).bit_length()
    seg_min=[ide_ele_min]*2*num_min

    init_min(loop)
    local_max=0
    for i,v in enumerate(loop):
        if i>=1:
            #print('v,min=',v,query_min(max(0,i-tmpK),i),v-query_min( max(0,i-tmpK),i ))
            local_max=max(local_max,v-query_min( max(0,i-tmpK),i ) )
    
    ans=max(ans,local_max+tmpans)

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

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
p=list(map(int, input().split()))
c=list(map(int, input().split()))
ans = -999999999999999
z = 0
l = 0
lv = 0

for i in range(n):
    v = 0
    tmp = i
    cl =[]
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ans < v:
                ans = v
            if tmp in cl:
                if lv < v - c[tmp]:
                    l = len(cl)
                    lv = v - c[tmp]
                break
            cl.append(tmp)           

    #print(cl)

if k >= n and l > 0:
    z = lv * int(k/l)
    k = k%l
elif k >= n and l == 0:
    z = sum(c) * int(k/n)
    k = k%n

for i in range(n):
    v = 0
    tmp = i
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ans < v:
                ans = v
            #print(tmp,v,ans) 

if z > 0:
    print(ans+z)
else:
    print(ans)

Submission status: Wrong Answer

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

def main():
    input = sys.stdin.readline
    n, k = map(int, input().split())
    


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys, math
from functools import lru_cache
from collections import defaultdict
sys.setrecursionlimit(500000)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    N, K = mi()
    P = list(mi())
    C = list(mi())
    m = -10**100

    # loopを格納
    loops = []
    # 数えたかどうか
    done = [False]*N
    
    for i in range(N):
        # もう数えているならskip
        if done[i]:
            continue

        now = P[i]-1
        T = 1
        s = C[now]
        lst = [now]

        done[now] = True

        # 戻ってくるまでループ
        while now != i:
            now = P[now]-1
            T += 1
            s += C[now]
            lst.append(now)

            done[now] = True

        loops.append((T, s, lst))

    print(loops)

    ans = -10**100
    # 各loopごと
    for loop in loops:
        # loopの周期、総和、構成要素を取得
        T, s, lst = loop

        # loopの周回回数
        n = max(K//T-1, 0) if s > 0 else 0

        # loopをn周した時のscore
        score = s*n

        # loopをn周した後の残り
        rest = K-n*T if s > 0 else T

        # 残りで移動した時の最大値を計算
        for v in lst:
            now = v
            s = 0
            for _ in range(rest):
                now = P[now]-1
                s += C[now]
                m = max(m, s)
        
        ans = max(score+m, ans)

    # print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

P = list(map(int,input().split()))

C = list(map(int,input().split()))

ans = -10000000

if K <= 50000:
    for i in range(N):
        count = 0
        tmp_point = 0
        nv = i
        while count < K:
            nvv = P[nv]
            nvv -= 1
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
    print(ans)
else:
    loop = [0]*N
    for i in range(N):
        count = 0
        check = [False]*N
        tmp_point = 0
        nv = i
        while True:
            nvv = P[nv]
            nvv -= 1
            if check[nvv] == True:
                break
            check[nvv] = True
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
        loop[i] = [tmp_point, count, i]
    loop.sort(reverse=True)
    #print(loop)
    new_ans = -10000000
    for value, counter, key in loop:
        if value < 0:
            break
        shou = K//counter
        amari = K%counter
        tmp_ans = value*shou    
        new_ans = max(new_ans, tmp_ans)
        count = 0
        nv = key
        while count < amari:
            nvv = P[nv]
            nvv -= 1
            tmp_ans += C[nvv]
            count += 1
            nv = nvv
            new_ans = max(new_ans, tmp_ans)

        if amari == 0:
            amari = counter
            shou -= 1
            tmp_ans = value*shou    
            new_ans = max(new_ans, tmp_ans)
            count = 0
            nv = key
            while count < amari:
                nvv = P[nv]
                nvv -= 1
                tmp_ans += C[nvv]
                count += 1
                nv = nvv
                new_ans = max(new_ans, tmp_ans)

    print(max(loop[0][0], ans, new_ans))

Submission status: Wrong Answer

Solution code:

N,K=5000,100000
P=list(range(1,5000))+[0]
C=[123,-121]*2500

ans=0
check=set()

for i in range(N):
    
    if i in check:
        continue
    
    # create loop
    tmpK=K
    tmpans=0
    loop_check=set()
    tmp_idx=i
    loop=[]
    while tmp_idx not in loop_check:
        loop.append(C[tmp_idx])
        loop_check.add(tmp_idx)
        check.add(tmp_idx)
        tmp_idx=P[tmp_idx]
    
    S=sum(loop)
    L=len(loop)
    if S>=0 and tmpK//L>=2:
        tmpans=S*(tmpK//L-1)
        tmpK=tmpK%L+L
    
    # 部分最大列を検索
    #print('loop',loop)
    loop*=2
    for i in range(len(loop)-1):
        loop[i+1]+=loop[i]
    n=2*L
    def init_min(init_min_val):
        #set_val
        for i in range(n):
            seg_min[i+num_min-1]=init_min_val[i]    
        #built
        for i in range(num_min-2,-1,-1) :
            seg_min[i]=min(seg_min[2*i+1],seg_min[2*i+2])
    def query_min(p,q):
        if q<=p:
            return ide_ele_min
        p += num_min-1
        q += num_min-2
        res=ide_ele_min
        while q-p>1:
            if p&1 == 0:
                res = min(res,seg_min[p])
            if q&1 == 1:
                res = min(res,seg_min[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = min(res,seg_min[p])
        else:
            res = min(min(res,seg_min[p]),seg_min[q])
        return res
    #####単位元######
    ide_ele_min = 10**15
    #num_min:n以上の最小の2のべき乗
    num_min =2**(n-1).bit_length()
    seg_min=[ide_ele_min]*2*num_min

    init_min(loop)
    local_max=0
    for i,v in enumerate(loop):
        if i>=1:
            #print('v,min=',v,query_min(max(0,i-tmpK),i),v-query_min( max(0,i-tmpK),i ))
            local_max=max(local_max,v-query_min( max(0,i-tmpK),i ) )
    
    ans=max(ans,local_max+tmpans)

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

Submission status: Wrong Answer

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

reach = [False]*n
x = []
for i in range(n):
    if reach[i]:continue
    buf = []
    index = i
    while not reach[index]:
        buf.append(c[index])
        reach[index] = True
        index = p[index]
    x.append(buf)

ans = max(c)
import itertools
for i in x:
    n = k//len(i)
    ind = k%len(i)
    ii = i+i
    r = list(itertools.accumulate(ii))
    a = max(0,r[len(i)-1]*n)
    for j in range(len(i)):
        for z in range(1,min(len(i),k)+1):
            s = r[j+z]-r[j]
            if z<ind+1:ans = max(ans,a+s)
            else:ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

Solution code:
import copy

def cost_val(visit_list, P, C):
    maxval = [-10**10] * (len(P) + 1)
    for start_idx in visit_list:
        cost = 0
        now_id = start_idx
        for i in range(len(visit_list)):
            now_id = P[now_id]
            cost += C[now_id]
            maxval[i + 1] = max(maxval[i + 1], cost)
    return maxval[1:len(visit_list) + 1]

def cycles(P):
    cycle_list = []
    visit_list = [False] * len(P)
    for i in range(len(P)):
        if visit_list[i]:
            continue
        now_id = i
        cycle = []
        for j in range(len(P)):
            if visit_list[now_id]:
                break
            cycle.append(now_id)
            visit_list[now_id] = True
            now_id = P[now_id]
        cycle_list.append(cycle)
    return cycle_list

def main():
    N, K = map(int, input().split())
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    cycle_list = cycles(P)
    ans = max(C)
    for cycle in cycle_list:
        maxval = cost_val(cycle, P, C)
        if len(cycle) >= K:
            ans = max(ans, max(maxval[:K]))
        else:
            if K % len(cycle) == 0:
                ans = max(ans, max(maxval), maxval[-1] * (K // len(cycle)))
            else:
                ans = max(ans, max(maxval), maxval[-1] * (K // len(cycle)) + max(maxval[:(K % len(cycle))]))
    return ans

if __name__ == '__main__':
    print(main())

Submission status: Wrong Answer

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect
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: #正なら親の番号
            self.par[x]=self.find(self.par[x]) #一回調べたら根を繋ぎ変える、経路圧縮
            return self.par[x]
    def union(self,x,y):
        x=self.find(x) #x,yの親
        y=self.find(y)

        if x==y: #親が同じなら何もしない
            return 
        if self.par[x]>self.par[y]: #要素数が大きい方をxにする
            x,y=y,x
        self.par[x]+=self.par[y] #xがある集合に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)

    def member(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.par) if x<0]
    
    def group_count(self): #集合の数、木の数
        return len(self.roots())

    def all_member(self): #辞書型で返す
        return {r: self.member(r) for r in self.roots()}
    def __str__(self):
        return "\n".join('{}:{}'.format(r,self.member(r)) for r in self.roots)


n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
tree=UnionFind(n)
for i in range(n):
    if p[i]-1 not in set(tree.member(i)):
        tree.union(i,p[i]-1)
finalans=-10**10
for i in tree.roots():
    res=tree.member(i)
    point=[0]*(len(res)*2)
    point[0]=c[res[0]]
    for j in range(1,len(res)*2):
        if j<len(res):
            point[j]=point[j-1]+c[res[j]]
        else:
            point[j]=point[j-1]+c[res[j-len(res)]]
    m=-10**20
    if k<=len(res):
        for j in range(1,k+1):
            for t in range(j-1,j+len(res)-1):
                cand=point[t]-point[t-j] if t-j>=0 else point[t]
                m=max(m,cand)
        ans=m
    else:
        if point[len(res)-1]>0:
            r=k%(len(res))
            M=-10**10
            if r==0:
              r=len(res)
            for j in range(1,r+1):
                for t in range(j-1,j+len(res)-1):
                    cand=point[t]-point[t-j] if t-j>=0 else point[t]
                    M=max(M,cand)
            if r==len(res):
              ans=point[len(res)-1]*((k//(len(res)))-1)+M
            else:
              ans=point[len(res)-1]*(k//(len(res)))+M
        else:
            for j in range(1,len(res)+1):
                for t in range(j-1,j+len(res)-1):
                    cand=point[t]-point[t-j] if t-j>=0 else point[t]
                    m=max(m,cand)
            ans=m
    finalans=max(ans,finalans)
print(finalans)