Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k >= le:
            tmp_1 = su
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3

            tmp_2 = div * su
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    if tmp_4 > tmp_5:
                        tmp_5 = tmp_4
            tmp_2 = max(tmp_2 + tmp_5, tmp_2)
            tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    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()))
a=-10**13
for i in range(n):
    b=0
    l=[]
    j=p[i]-1
    l+=[c[p[i]-1]]
    while j!=i:
        l+=[l[-1]+c[p[j]-1]]
        j=p[j]-1
    if len(l)>=k:
        b+=max(l[:k])
    else:
        z=l[-1]
        if z<0:
            b+=max(l)
        else:
            q=len(l)
            if k%q==0:
                b+=max([z*(k//q),(z-1)*(k//q)+max(l)])
            else:
                b+=z*(k//q)+max(l[:k%q])
    if a<b:
        a=b
print(a)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k > le:
            tmp_1 = su
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3

            tmp_2 = div * su
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    if tmp_4 > tmp_5:
                        tmp_5 = tmp_4
            tmp_2 = max(tmp_2 + tmp_5, tmp_2)
            tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
shuki = [-1 for _ in range(n)]
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]    
for i in range(1, n):
    for j in range(n):
        position[i][j] = p[position[i - 1][j]]
        p_list[i][j] = p_list[i - 1][j] + c[position[i][j]]        
        if (position[i][j] == j) & (shuki[j] == -1):
            shuki[j] = i + 1
ans = -(10 ** 18)

for i in range(n):    
    v = 0
    if shuki[i] >= 0:
        if p_list[shuki[i] - 1][i] > 0:
            v += p_list[shuki[i] - 1][i] * (k // shuki[i])
            if k % shuki[i] > 0:
                tmp_list = [p_list[j][i] for j in range(len(p_list))][:(k%shuki[i])]
                v += max(tmp_list)
        else:
            v += max([p_list[j][i] for j in range(len(p_list))][:k])
    else:
        v += max([p_list[j][i] for j in range(len(p_list))][:k])
    ans = max(v, ans)
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()))
a=-10**13
for i in range(n):
    b=0
    l=[]
    j=p[i]-1
    l+=[c[p[i]-1]]
    while j!=i:
        l+=[l[-1]+c[p[j]-1]]
        j=p[j]-1
    if len(l)>=k:
        b+=max(l[:k])
    else:
        z=l[-1]
        if z<0:
            b+=max(l)
        else:
            q=len(l)
            if k%q==0:
                b+=z*(k//q)
            else:
                b+=z*(k//q)+max(l[:k%q])
    if a<b:
        a=b
print(a)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k > le:
            tmp_1 = su
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le - 1):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3

            tmp_2 = div * su
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    if tmp_4 > tmp_5:
                        tmp_5 = tmp_4
            tmp_2 = max(tmp_2 + tmp_5, tmp_2)
            tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
shuki = [-1 for _ in range(n)]
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]    
for i in range(1, n):
    for j in range(n):
        position[i][j] = p[position[i - 1][j]]
        p_list[i][j] = p_list[i - 1][j] + c[position[i][j]]        
        if (position[i][j] == j) & (shuki[j] == -1):
            shuki[j] = i + 1
ans = max(c)

for i in range(n):    
    v = 0
    if shuki[i] >= 0:
        if p_list[shuki[i] - 1][i] > 0:
            v += p_list[shuki[i] - 1][i] * (k // shuki[i])
            if k % shuki[i] > 0:
                tmp_list = [p_list[j][i] for j in range(len(p_list))][:(k%shuki[i])]
                v += max(tmp_list)
        else:
            v += max([p_list[j][i] for j in range(len(p_list))][:k])
    else:
        v += max([p_list[j][i] for j in range(len(p_list))][:k])
    ans = max(v, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k > le:
            tmp_1 = su
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le - 1):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3
            if su < 0:
                tmp = tmp_1
            else:
                tmp_2 = div * su
                tmp_5 = - float('Inf')
                for i in range(le):
                    tmp_4 = 0
                    for j in range(mod + 1):
                        p = (i + j) % le
                        tmp_4 += s[p]
                        if tmp_4 > tmp_5:
                            tmp_5 = tmp_4
                tmp_2 = max(tmp_2 + tmp_5, tmp_2)
                tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k + 1):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k > le:
            tmp_1 = su
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le - 1):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3
            if su < 0:
                tmp = tmp_1
            else:
                tmp_2 = div * su
                tmp_5 = - float('Inf')
                for i in range(le):
                    tmp_4 = 0
                    for j in range(mod):
                        p = (i + j) % le
                        tmp_4 += s[p]
                        if tmp_4 > tmp_5:
                            tmp_5 = tmp_4
                tmp_2 = max(tmp_2 + tmp_5, tmp_2)
                tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    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()))
a=-10**13
for i in range(n):
    b=0
    l=[]
    j=p[i]-1
    l+=[c[p[i]-1]]
    while j!=i:
        l+=[l[-1]+c[p[j]-1]]
        j=p[j]-1
    if len(l)>=k:
        b+=max(l)
    else:
        z=l[-1]
        if z<0:
            b+=max(l)
        else:
            q=len(l)
            if k%q==0:
                b+=z*(k//q)
            else:
                b+=z*(k//q)+max(l[:k%q])
    if a<b:
        a=b
print(a)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k > le:
            tmp_1 = su
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le - 1):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3
            if su < 0:
                tmp = tmp_1
            else:
                tmp_2 = div * su
                tmp_5 = - float('Inf')
                for i in range(le):
                    tmp_4 = 0
                    for j in range(mod):
                        p = (i + j) % le
                        tmp_4 += s[p]
                        if tmp_4 > tmp_5:
                            tmp_5 = tmp_4
                tmp_2 += tmp_5
                tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    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()))

s_max = C[P[0] - 1]
for i in range(n):
    tmp_l = P[i] - 1
    tmp_s = C[tmp_l]
    tmp_max = tmp_s
    j = 1
    loop_sum = 0
    loop_cnt = 1
    max_cnt = 0
    while j < k:
        tmp_l = P[tmp_l] - 1
        loop_cnt += 1
        if tmp_l == i:
            loop_sum = tmp_s + C[tmp_l]
            break
        tmp_s += C[tmp_l]
        tmp_max = max(tmp_max, tmp_s)
        if tmp_max == tmp_s:
            max_cnt = loop_cnt
        j += 1
    loop_max = loop_sum * ((k - max_cnt) // loop_cnt) + tmp_max if loop_sum >= 0 else tmp_max
    s_max = max(s_max, loop_max)

print(s_max)

Submission status: Wrong Answer

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
# from collections import Counter,defaultdict,deque
# from itertools import permutations, combinations
# from heapq import heappop, heappush
# # input = sys.stdin.readline
# sys.setrecursionlimit(10**8)
# mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

n,k = inpm()
P = [0] + inpl()
C = [0] + inpl()

ans = 1000000010 * -1
for start in range(1,n+1):
    l = [0] * (n+1)
    l[start] = 1
    now = start
    score = []
    while True:
        l[now] = 1
        score.append(C[P[now]])
        if l[P[now]] == 1:
            break
        now = P[now]
    
    ruiseki = []
    for i in range(len(score)):
        if i == 0:
            ruiseki.append(score[i])
        else:
            ruiseki.append(ruiseki[i-1] + score[i])

    a = ruiseki[-1] #1ループでのスコア
    b = max(ruiseki) #1ループ中の最大スコア
    c = k // len(ruiseki) #ループ可能回数
    d = k % len(ruiseki) #ループ抜けてからのあまり回数

    tmp = 0
    if c == 0:
        tmp = max(ruiseki[:d])
    elif c > 0:
        if a <= 0:
            tmp = b
        if d == 0:
            tmp = a*(c-1) + b
        else:
            tmp = max(a*c + max(ruiseki[:d]),a*(c-1) + b)
    ans = max(ans,tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
Pls = [0] + list(map(int,input().split()))
Cls = [0] + list(map(int,input().split()))
used = [False]*(N+1)
loopmax = []
for i in range(1,N+1):
    loop = [Cls[i]]
    pi = Pls[i]
    if used[i]:
        continue
    else:
        while pi != i:
            loop.append(Cls[pi])
            used[pi] = True
            pi = Pls[pi]
        if sum(loop) > 0:
            max1 = (K//len(loop))*sum(loop)
            lenloop = len(loop)
            rm = (K-1) % lenloop + 1
            max3 = -10**9
            for k in range(1,rm + 1):
                max2 = sum(loop[:k])
                for j in range(lenloop):
                    max2 += -loop[j] + loop[(k + j) % lenloop]
                    max3 = max(max2,max3)
            loopmax.append(max3 + max1)
        else:
            max1 = 0
            lenloop = len(loop)
            rm = (K-1) % lenloop +1
            max3 = -10**9
            for k in range(1,rm + 1):
                max2 = sum(loop[:k])
                for j in range(lenloop):
                    max2 += -loop[j] + loop[(k + j) % lenloop]
                    max3 = max(max2,max3)
            loopmax.append(max3 + max1)
print(max(loopmax))

Submission status: Wrong Answer

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
# from collections import Counter,defaultdict,deque
# from itertools import permutations, combinations
# from heapq import heappop, heappush
# # input = sys.stdin.readline
# sys.setrecursionlimit(10**8)
# mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

n,k = inpm()
P = [0] + inpl()
C = [0] + inpl()

ans = 1000000010 * -1
for start in range(1,n+1):
    l = [0] * (n+1)
    l[start] = 1
    now = start
    score = []
    while True:
        l[now] = 1
        score.append(C[P[now]])
        if l[P[now]] == 1:
            break
        now = P[now]
    
    ruiseki = []
    for i in range(len(score)):
        if i == 0:
            ruiseki.append(score[i])
        else:
            ruiseki.append(ruiseki[i-1] + score[i])

    a = ruiseki[-1] #1ループでのスコア
    b = max(ruiseki) #1ループ中の最大スコア
    c = k // len(ruiseki) #ループ可能回数
    d = k % len(ruiseki) #ループ抜けてからのあまり回数

    tmp = 0
    if c == 0:
        tmp = max(ruiseki[:d])
    elif c > 0:
        if d == 0:
            tmp = a*(c-1) + b
        else:
            tmp = max(a*c + max(ruiseki[:d]),a*(c-1) + b)
    ans = max(ans,tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        su = sum(s)
        if k > le:
            tmp_1 = - float('Inf')
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le - i):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3
            if su < 0:
                tmp = tmp_1
            else:
                tmp_2 = div * su
                tmp_5 = - float('Inf')
                for i in range(le):
                    tmp_4 = 0
                    for j in range(mod):
                        p = (i + j) % le
                        tmp_4 += s[p]
                        if tmp_4 > tmp_5:
                            tmp_5 = tmp_4
                tmp_2 += tmp_5
                tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys, bisect, math, itertools, string, queue, copy
import numpy as np
import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

n,k = inpm()
P = [0] + inpl()
C = [0] + inpl()

ans = 1000000010 * -1
for start in range(1,n+1):
    l = [0] * (n+1)
    l[start] = 1
    now = start
    score = []
    while True:
        l[now] = 1
        score.append(C[P[now]])
        if l[P[now]] == 1:
            break
        now = P[now]
    
    ruiseki = []
    for i in range(len(score)):
        if i == 0:
            ruiseki.append(score[i])
        else:
            ruiseki.append(ruiseki[i-1] + score[i])

    a = ruiseki[-1] #1ループでのスコア
    b = max(ruiseki) #1ループ中の最大スコア
    c = k // len(ruiseki) #ループ可能回数
    d = k % len(ruiseki) #ループ抜けてからのあまり回数

    tmp = 0
    if c == 0:
        tmp = max(ruiseki[:d])
    elif c > 0:
        if d == 0:
            tmp = a*(c-1) + b
        else:
            tmp = max(a*c + max(ruiseki[:d]),a*(c-1) + b)
    ans = max(ans,tmp)

print(ans)

Submission status: Wrong Answer

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

import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
shuki = [-1 for _ in range(n)]
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]    
for i in range(1, n):
    for j in range(n):
        position[i][j] = p[position[i - 1][j]]
        p_list[i][j] = p_list[i - 1][j] + c[position[i][j]]        
        if (position[i][j] == j) & (shuki[j] == -1):
            shuki[j] = i + 1
ans = max(c)
for i in range(n):
    v = 0
    tmp_list = [p_list[i][j] for j in range(len(p_list))][:(k%shuki[i])]
    if len(tmp_list) > 0:        
        tmp = max(tmp_list)
    else:
        tmp = 0
    if shuki[i] >= 0:
        if p_list[shuki[i] - 1][i] > 0:
            v += p_list[shuki[i] - 1][i] * (k // shuki[i])
            if k - (k // shuki[i]) * shuki[i] > 0:
                v += tmp
        else:
            v = max([p_list[i][j] for i in range(len(p_list))][:k])
    else:
        v += tmp
    ans = max(v, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        if k > le:
            tmp_1 = - float('Inf')
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = (i + j) % le
                    tmp_3 += s[p]
                    if tmp_3 > tmp_1:
                        tmp_1 = tmp_3

            tmp_2 = div * sum(s)
            tmp_5 = - float('Inf')
            for i in range(le):
                tmp_4 = 0
                for j in range(mod):
                    p = (i + j) % le
                    tmp_4 += s[p]
                    if tmp_4 > tmp_5:
                        tmp_5 = tmp_4
            tmp_2 += tmp_5
            tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = (i + j) % le
                    tmp_1 += s[p]
                    if tmp_1 > tmp:
                        tmp = tmp_1

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
positions = [int(i) for i in input().split()]
scores = [int(i) for i in input().split()]
if max(scores) <= 0:
  print(max(scores))
else:
  positions = [0] + positions
  scores = [0] + scores
  max_point = -10 ** 9
  #print(max_point)
  dic = {}
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    if f_pos not in dic:
      point_loop = 0
      loop = 0
      pos_set = set([f_pos])
      while True:
        f_pos = positions[f_pos]
        point_loop += scores[f_pos]
        #print('pos', f_pos)
        #print(point)
        loop += 1
        if f_pos in pos_set:
          for j in pos_set:
            dic[j] = [loop, point_loop]
          break
        pos_set.add(f_pos)
    else:
      loop, point_loop = dic[f_pos]
    #print(loop, point)
    loop_c = k // loop
    r = k % loop
    if point_loop > 0:
      point = loop_c * point_loop
      if point > max_point and loop_c > 0:
        max_point = point
    else:
      point = 0
      if loop_c > 0:
        r = loop
    #print(point)
    if r > 0:
      for _ in range(r):
        f_pos = positions[f_pos]
        point += scores[f_pos]
        #print(point)
        if point > max_point:
          max_point = point
  #print('max_point')
  print(max_point)