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
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(1, n + 1):
        if not seen[i1 - 1]:
            cycle_t = []
            koko = i1
            while True:
                if seen[koko - 1]:
                    cycles.append(cycle_t)
                    break
                cycle_t.append(c[koko - 1])
                seen[koko - 1] = 1
                koko = p[koko - 1]

    score = max(c)
    for cycle in cycles:
        score_t = max(cycle)
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        if rem == 0:
            kaisu -= 1
            rem = cycle_len
        cycle.extend(cycle)
        cycle = tuple(accumulate(cycle))
        for i1 in range(2, rem + 1):
            for i2 in range(cycle_len):
                score_t = max(score_t, cycle[i1+i2] - cycle[i2])
        if cycle_sum > 0:
            score_t += kaisu * cycle_sum
        score = max(score, score_t)
    print(score)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            while True:
                if seen[koko]:
                    cycles.append(cycle)
                    break
                cycle.append(c[koko])
                seen[koko] = 1
                koko = p[koko] - 1

    score = max(c)
    for cycle in cycles:
        score_t = max(cycle)
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        if rem == 0:
            kaisu -= 1
            rem = cycle_len
        cycle = tuple(accumulate(cycle + cycle))
        for i1 in range(2, rem + 1):
            for i2 in range(cycle_len):
                score_t = max(score_t, cycle[i1+i2] - cycle[i2])
        if cycle_sum > 0:
            score_t += kaisu * cycle_sum
        score = max(score, score_t)
    print(score)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            while True:
                if seen[koko]:
                    cycles.append(cycle)
                    break
                cycle.append(c[koko])
                seen[koko] = 1
                koko = p[koko] - 1

    score = max(c)
    for cycle in cycles:
        score_t = max(cycle)
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        if rem == 0:
            kaisu -= 1
            rem = cycle_len
        cycle = tuple(accumulate(cycle + cycle))
        for i1 in range(cycle_len):
            for i2 in range(1, rem+1):
                score_t = max(score_t, cycle[i1+i2] - cycle[i1])
        if cycle_sum > 0:
            score_t += kaisu * cycle_sum
        score = max(score, score_t)
    print(score)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            while True:
                if seen[koko]:
                    cycles.append(cycle)
                    break
                cycle.append(c[koko])
                seen[koko] = 1
                koko = p[koko] - 1

    score = max(c)
    for cycle in cycles:
        score_t = max(cycle)
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        if rem == 0:
            kaisu -= 1
            rem = cycle_len
        cycle = tuple(accumulate(cycle + cycle))
        if rem:
            for i1 in range(cycle_len):
                for i2 in range(1, rem+1):
                    score_t = max(score_t, cycle[i1+i2] - cycle[i1])
        if cycle_sum > 0:
            score_t += kaisu * cycle_sum
        score = max(score, score_t)
    print(score)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            while True:
                if seen[koko]:
                    cycles.append(cycle)
                    break
                cycle.append(c[koko])
                seen[koko] = 1
                koko = p[koko] - 1

    score = max(c)
    for cycle in cycles:
        score_t = max(cycle)
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        cycle = tuple(accumulate(cycle + cycle))
        if rem:
            for i1 in range(cycle_len):
                for i2 in range(1, rem+1):
                    score_t = max(score_t, cycle[i1+i2] - cycle[i1])
        if cycle_sum > 0:
            score_t += kaisu * cycle_sum
        score = max(score, score_t)
    print(score)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            while True:
                if seen[koko]:
                    cycles.append(cycle)
                    break
                cycle.append(c[koko])
                seen[koko] = 1
                koko = p[koko] - 1

    score = max(c)
    for cycle in cycles:
        score_t = cycle[0]
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        cycle = tuple(accumulate(cycle + cycle))
        for i1 in range(cycle_len):
            for i2 in range(1, rem+1):
                score_t = max(score_t, cycle[i1+i2] - cycle[i1])
        if cycle_sum > 0:
            score_t += kaisu * cycle_sum
        score = max(score, score_t)
    print(score)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            while True:
                if seen[koko]:
                    cycles.append(cycle)
                    break
                cycle.append(c[koko])
                seen[koko] = 1
                koko = p[koko] - 1

    score_each_cycle = set()
    for cycle in cycles:
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        score = cycle[0]
        cycle = tuple(accumulate(cycle + cycle))
        for i1 in range(cycle_len):
            for i2 in range(rem):
                score = max(score, cycle[i1+i2+1] - cycle[i1])
        if cycle_sum > 0:
            score += kaisu * cycle_sum
        score_each_cycle.add(score)
    r = max(max(c), max(score_each_cycle))
    print(r)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = p[i1] - 1
            while True:
                cycle.append(c[koko])
                seen[koko] = 1
                if koko == i1:
                    cycles.append(cycle)
                    break
                koko = p[koko] - 1

    score_each_cycle = set()
    for cycle in cycles:
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        score = cycle[0]
        cycle = tuple(accumulate(cycle + cycle))
        for i1 in range(cycle_len):
            for i2 in range(rem):
                score = max(score, cycle[i1+i2+1] - cycle[i1])
        if cycle_sum > 0:
            score += kaisu * cycle_sum
        score_each_cycle.add(score)
    r = max(max(c), max(score_each_cycle))
    print(r)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = p[i1] - 1
            while True:
                cycle.append(c[koko])
                seen[koko] = 1
                if koko == i1:
                    cycles.append(cycle)
                    break
                koko = p[koko] - 1

    score_each_cycle = set()
    score = max(c)
    for cycle in cycles:
        cycle_len = len(cycle)
        cycle_sum = sum(cycle)
        kaisu, rem = divmod(k, cycle_len)
        cycle = tuple(accumulate(cycle + cycle))
        for i1 in range(cycle_len):
            for i2 in range(rem):
                score = max(score, cycle[i1+i2+1] - cycle[i1])
        if cycle_sum > 0:
            score += kaisu * cycle_sum
        score_each_cycle.add(score)
    print(score)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            k2 = k
            while k2:
                koko = p[koko] - 1
                cycle.append(c[koko])
                seen[koko] = 1
                if koko == i1:
                    cycles.append((cycle, True, sum(cycle)))
                    break
                k2 -= 1
            if k2 == 0:
                cycles.append((cycle, False, sum(cycle)))
    score_each_cycle = []
    for cycle in cycles:
        if cycle[1]:
            cycle0 = cycle[0]
            cycle_l = len(cycle0)
            kaisu, rem = divmod(k, cycle_l)
            scores = [0] * cycle_l
            scores[0] = cycle0[0]
            cycle0.extend(cycle0)
            cycle0 = [0] + cycle0
            cycle0 = tuple(accumulate(cycle0))
            for i1 in range(cycle_l):
                score = cycle0[1]
                for i2 in range(1, cycle_l+1):
                    score = max(score, cycle0[i1+i2]-cycle0[i1])
                scores[i1] = score
            if cycle[2] > 0:
                for j1 in range(rem + 1):
                    scores[j1] += kaisu * cycle[2]
            score_each_cycle.append((max(scores)))
        else:
            cycle0 = cycle[0]
            cycle_l = len(cycle[0])
            scores = [0] * cycle_l
            cycle0 = [0] + cycle0
            cycle0 = tuple(accumulate(cycle0))
            score = cycle0[1]
            for i1 in range(cycle_l):
                for i2 in range(1, cycle_l - i1):
                    score = max(score, cycle0[i1+i2]-cycle0[i1])
            score_each_cycle.append(score)
    r = max(max(c), max(score_each_cycle))
    print(r)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            k2 = k
            while k2:
                koko = p[koko] - 1
                cycle.append(c[koko])
                seen[koko] = 1
                if koko == i1:
                    cycles.append((cycle, True, sum(cycle)))
                    break
                k2 -= 1
            if k2 == 0:
                cycles.append((cycle, False, sum(cycle)))
    score_each_cycle = []
    for cycle in cycles:
        if cycle[1]:
            cycle_l = len(cycle[0])
            kaisu, rem = divmod(k, cycle_l)
            scores = [0] * cycle_l
            scores[0] = cycle[0][0]
            cycle[0].extend(cycle[0])
            for i1 in range(cycle_l):
                score = cycle[0][i1]
                for i2 in range(1, cycle_l):
                    score = max(score, sum(cycle[0][i1:i1+i2]))
                scores[i1] = score
            if cycle[2] > 0:
                for j1 in range(rem + 1):
                    scores[j1] += kaisu * cycle[2]
            score_each_cycle.append((max(scores)))
        else:
            cycle_l = len(cycle[0])
            scores = [0] * cycle_l
            for i1 in range(cycle_l):
                score = cycle[0][i1]
                for i2 in range(1, cycle_l - i1):
                    score = max(score, sum(cycle[0][i1:i1+i2]))
                scores[i1] = score
            score_each_cycle.append(max(scores))


        score_each_cycle.append(score)
    r = max(max(c), max(score_each_cycle))
    print(r)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    seen = [0] * n
    cycles = []
    for i1 in range(n):
        if not seen[i1]:
            cycle = []
            koko = i1
            k2 = k
            while k2:
                koko = p[koko] - 1
                cycle.append(c[koko])
                seen[koko] = 1
                if koko == i1:
                    score_sum = sum(cycle)
                    cycles.append((cycle, True, score_sum))
                    break
                k2 -= 1
            if k2 == 0:
                cycles.append((cycle, False, sum(cycle)))
    score_each_cycle = []
    for cycle in cycles:
        if cycle[1]:
            cycle_l = len(cycle[0])
            kaisu, rem = divmod(k, cycle_l)
            score = cycle[0][0]
            cycle[0].extend(cycle[0])
            for i1 in range(cycle_l+1):
                for i2 in range(1, rem+1):
                    score = max(score, sum(cycle[0][i1:i1+i2]))
            score += kaisu * cycle[2]
        else:
            score = max(cycle[0])

        score_each_cycle.append(score)
    r = max(max(c), max(score_each_cycle))
    print(r)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,K =map(int,input().split())
Plist = [0]
Plist += list(map(int,input().split()))
Clist = [0]
Clist += list(map(int,input().split()))
Sum = sum(Clist)
def f(x):
    score = 0
    place = Plist[x]
    maxscore = -10**9-1
    maxplace = 0
    for i in range(K):
        score += Clist[place]
        if maxscore < score :
            maxscore = max(score,maxscore)
            maxplace = i+1
        place = Plist[place]
        if place == Plist[x]:
            break
    return [maxscore, maxplace,i+1,score]
def S(maxscore,maxplace,i,score):
    if score >0:
        return maxscore + score*((K-maxplace)//i)
    else:
        return maxscore
ans = -(10**9+1)
for i in range(1,N+1):
    g = f(i)
    ans = max(ans,S(g[0],g[1],g[2],g[3]))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    score_each_c = [0] * n
    cycle_each_c = [0] * n
    loop_each_c = [True] * n
    max_each_c = [0] * n
    for i1 in range(n):
        t0 = 0
        cnt = 0
        koko = i1
        maxs = c[p[koko]-1]
        while True:
            koko = p[koko] - 1
            t0 += c[koko]
            cnt += 1
            if cnt <= k:
                maxs = max(maxs, t0)
            if koko == i1:
                break
        score_each_c[i1] = t0
        cycle_each_c[i1] = cnt
        max_each_c[i1] = maxs
        loop_each_c[i1] = t0 > maxs

    res_each_c = [0] * n
    for j1 in range(n):
        if cycle_each_c[j1] == k:
            res_each_c[j1] = max(score_each_c[j1], max_each_c[j1])
        elif cycle_each_c[j1] < k:
            kaisu, rem = divmod(k, cycle_each_c[j1])
            t0 = 0
            koko = j1
            while rem:
                koko = p[koko] - 1
                t0 += c[koko]
                rem -= 1
            res_each_c[j1] = score_each_c[j1] * kaisu + t0
        else:
            t0 = 0
            koko = j1
            k2 = k
            maxs = c[p[koko]-1]
            while k2:
                koko = p[koko] - 1
                t0 += c[koko]
                maxs = max(maxs, t0)
                k2 -= 1
            res_each_c[j1] = max(t0, maxs)
    print(max(max(res_each_c), max(max_each_c)))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
    n, k = map(int, input().split())
    p = tuple(map(int, input().split()))
    c = tuple(map(int, input().split()))

    score_each_c = [0] * n
    cycle_each_c = [0] * n
    loop_each_c = [True] * n
    max_each_c = [0] * n
    for i1 in range(n):
        t0 = 0
        cnt = 0
        koko = i1
        maxs = c[p[koko]-1]
        while True:
            koko = p[koko] - 1
            t0 += c[koko]
            maxs = max(maxs, t0)
            cnt += 1
            if koko == i1:
                break
        score_each_c[i1] = t0
        cycle_each_c[i1] = cnt
        max_each_c[i1] = maxs
        loop_each_c[i1] = t0 > maxs

    res_each_c = [0] * n
    for j1 in range(n):
        if cycle_each_c[j1] == k:
            res_each_c[j1] = max(score_each_c[j1], max_each_c[j1])
        elif cycle_each_c[j1] < k:
            kaisu, rem = divmod(k, cycle_each_c[j1])
            t0 = 0
            koko = j1
            while rem:
                koko = p[koko] - 1
                t0 += c[koko]
                rem -= 1
            res_each_c[j1] = score_each_c[j1] * kaisu + t0
        else:
            t0 = 0
            koko = j1
            k2 = k
            maxs = c[p[koko]-1]
            while k2:
                koko = p[koko] - 1
                t0 += c[koko]
                maxs = max(maxs, t0)
                k2 -= 1
            res_each_c[j1] = max(t0, maxs)
    print(max(max(res_each_c), max(max_each_c)))

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()))
p=[x-1 for x in p]
mi=set(range(n))
g={}
# g[id]=[ary]
while mi:
  x0=mi.pop()
  ary=[c[x0]]
  x=x0
  while p[x]!=x0:
    x=p[x]
    mi.discard(x)
    ary.append(c[x])
  cnt=len(ary)
  tmp=0
  ary*=2
  cary=[tmp]
  for x in ary:
    tmp+=x
    cary.append(tmp)
  g[x0]=[cnt,cary]
ans=-float('inf')
for cnt,cary in g.values():
  x,y=divmod(k,cnt)
  tmp1=max(0,cary[cnt]*x)
  tmp2=-float('inf')
  for i in range(cnt):
    for j in range(y):
      tmp2=max(tmp2,cary[i+j+1]-cary[i])
  ans=max(ans,tmp1+tmp2)
  tmp1=max(0,cary[cnt]*(x-1))
  tmp2=-float('inf')
  for i in range(cnt):
    for j in range(cnt):
      tmp2=max(tmp2,cary[i+j+1]-cary[i])
  ans=max(ans,tmp1+tmp2)
  

print(ans)

Submission status: Wrong Answer

Solution code:
def cycle_getter(N, start):
    """
    :param N: 移動回数
    :param start:　初期条件
    :return front: cycleまでの要素のリスト
            cycle: cycle内の要素のリスト
            end: cycle後の余った部分の要素のリスト
            cnt: cycle回数
    """
    p = start
    front, cycle, end = [], [], []
    cnt = 0
    visit = {p:0}
    L, R = N, -1
    P = [p]
    for i in range(1,N):
        p = lift(p)
        if p in visit:
            """
            (L, R) = (サイクルに入るまでに移動した回数, サイクルの終端に着くまでに移動した回数)
            [6,2,3,4,0,1,2] ⇒ (L, R) = (1, 6)
            """
            L, R = visit[p], i
            period = R-L
            break
        visit[p] = i
        P.append(p)
    front = P[:L]
    if L != N:
        cycle, end = P[L:R], P[L:L+(N-L)%period]
        cnt = (N-L)//period
    return front, cycle, end, cnt

################################################################################


import sys
input = sys.stdin.readline
from itertools import accumulate

def lift(x): return P[x-1]

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
res = -float("inf")
for i in range(1,N+1):
    front, cycle, end, cnt = cycle_getter(K,i)

print(res)

Submission status: Wrong Answer

Solution code:
def cycle_getter(N, start):
    """
    :param N: 移動回数
    :param start:　初期条件
    :return front: cycleまでの要素のリスト
            cycle: cycle内の要素のリスト
            end: cycle後の余った部分の要素のリスト
            cnt: cycle回数
    """
    p = start
    front, cycle, end = [], [], []
    cnt = 0
    visit = {p:0}
    L, R = N, -1
    for i in range(1,N):
        p = lift(p)
        if p in visit:
            """
            (L, R) = (サイクルに入るまでに移動した回数, サイクルの終端に着くまでに移動した回数)
            [6,2,3,4,0,1,2] ⇒ (L, R) = (1, 6)
            """
            L, R = visit[p], i
            period = R-L
            break
        visit[p] = i
    p = start

    return front, cycle, end, cnt

################################################################################


import sys
input = sys.stdin.readline
from itertools import accumulate

def lift(x): return P[x-1]

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
res = -float("inf")
for i in range(1,N+1):
    front, cycle, end, cnt = cycle_getter(K,i)
print(res)

Submission status: Wrong Answer

Solution code:
def cycle_getter(N, start):
    """
    :param N: 移動回数
    :param start:　初期条件
    :return front: cycleまでの要素のリスト
            cycle: cycle内の要素のリスト
            end: cycle後の余った部分の要素のリスト
            cnt: cycle回数
    """
    p = start
    front, cycle, end = [], [], []
    cnt = 0
    visit = {p:0}
    L, R = N, -1
    for i in range(1,N):
        p = lift(p)
        if p in visit:
            """
            (L, R) = (サイクルに入るまでに移動した回数, サイクルの終端に着くまでに移動した回数)
            [6,2,3,4,0,1,2] ⇒ (L, R) = (1, 6)
            """
            L, R = visit[p], i
            period = R-L
            break
        visit[p] = i
    p = start
    for _ in range(L):
        front.append(p)
        p = lift(p)
    if L != N:
        for _ in range(L,R):
            cycle.append(p)
            p = lift(p)
        for _ in range(N-(N-L)%period,N):
            end.append(p)
            p = lift(p)
        cnt = (N-L)//period
    return front, cycle, end, cnt

################################################################################


import sys
input = sys.stdin.readline
from itertools import accumulate

def lift(x): return P[x-1]

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
res = -float("inf")
for i in range(1,N+1):
    front, cycle, end, cnt = cycle_getter(K,i)

print(res)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI0(): return map(lambda s: int(s) - 1, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
def LMI0(): return list(map(lambda s: int(s) - 1, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')




N, K = MI()
P = LMI()
C = LMI()

# マス i を含むループ1週の (スコア, ループ長)
def loops():
    seen = set()
    for i in range(N):
        if i in seen:
            continue
        route = {i}
        s = 0
        cur = i
        while True:
            seen.add(cur)
            next = P[cur] - 1
            s += C[next]
            if next in route:
                yield s, route
                break
            else:
                route.add(next)
                cur = next

ans = -INF
for score, route in loops():
    if score > 0:
        lans = score * (K // len(route))
        times = K - (K // len(route) * len(route))
    else:
        lans = 0
        times = min(K, N)

    max_s = -INF
    route = list(route)
    for i in range(len(route)):
        s = 0
        cur = route[i]
        for _ in range(times):
            next = P[cur] - 1
            s += C[next]
            cur = next
            max_s = max(max_s, s)
    if score > 0:
        lans += max(0, max_s)
    else:
        lans += max_s
    ans = max(ans, lans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI0(): return map(lambda s: int(s) - 1, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
def LMI0(): return list(map(lambda s: int(s) - 1, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')




N, K = MI()
P = LMI()
C = LMI()

# マス i を含むループ1週の (スコア, ループ長)
def loops():
    seen = set()
    for i in range(N):
        if i in seen:
            continue
        route = {i}
        s = 0
        cur = i
        while True:
            seen.add(cur)
            next = P[cur] - 1
            s += C[next]
            if next in route:
                yield s, route
                break
            else:
                route.add(next)
                cur = next

ans = -INF
for score, route in loops():
    if score >= 0:
        base = score * (K // len(route))
        times = K - (K // len(route) * len(route))
        m_sur = 0
    else:
        base = 0
        times = min(K, N)
        m_sur = -INF

    route = list(route)
    for i in range(len(route)):
        s = 0
        cur = route[i]
        for _ in range(times):
            next = P[cur] - 1
            s += C[next]
            cur = next
            m_sur = max(m_sur, s)

    lans = base + m_sur
    ans = max(ans, lans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI0(): return map(lambda s: int(s) - 1, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
def LMI0(): return list(map(lambda s: int(s) - 1, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')




N, K = MI()
P = LMI()
C = LMI()

# マス i を含むループ1週の (スコア, ループ長)
score = [None] * N
for i in range(N):
    if score[i] is not None:
        continue
    route = {i}
    s = 0
    cur = i
    while True:
        next = P[cur] - 1
        s += C[next]
        if next in route:
            for j in route:
                score[j] = (s, len(route))
            break
        else:
            route.add(next)
            cur = next

ans = -INF
for i in range(N):
    lans = 0
    s, loop = score[i]
    if s >= 0:
        lans += s * (K // loop)
        rem = K - (K // loop * loop)
        if K // loop > 0:
            m_lans = lans
        else:
            m_lans = -INF
    else:
        rem = min(K, N)
        m_lans = -INF

    cur = i
    for j in range(rem):
        next = P[cur] - 1
        lans += C[next]
        cur = next
        if lans > m_lans:
            m_lans = lans

    if m_lans > ans:
        ans = m_lans
print(ans)