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
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
    elif s == 0 and K > N:
        rem = min(K - N, N)
        m_lans = 0
    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)

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)

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=[i-1 for i in P]
idle_max=-10**27



for s in range(0,N):
    k=K-1
    score=0
    s=P[s]
    score+=C[s]
    count=1
    idle_max=max(idle_max,score)
    visited={s:[count,score]}
    while k and not P[s] in visited:

        k-=1
        count+=1
        s=P[s]
        score+=C[s]
        visited[s]=[count,score]

        idle_max=max(idle_max,score)
    #print(visited)
    if k:
        c1,score1=visited[s]
        c2,score2=visited[P[s]]
        c1+=1

        score1+=C[P[s]]
        n=c1-c2
        s=P[s]
        score+=(score1-score2)*(k//n)
        k%=n
        idle_max=max(idle_max,score)
    while k:
        k-=1
        s=P[s]
        score+=C[s]
        idle_max=max(idle_max,score)


print(idle_max)

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=[i-1 for i in P]
idle_max=-10**27



for s in range(0,N):
    k=K-1
    score=0
    s=P[s]
    score+=C[s]
    count=1
    idle_max=max(idle_max,score)
    visited={s:[count,score]}
    while k and not P[s] in visited:

        k-=1
        count+=1
        s=P[s]
        score+=C[s]
        visited[s]=[count,score]

        idle_max=max(idle_max,score)
    #print(visited)
    if k:
        c1,score1=visited[s]
        c2,score2=visited[P[s]]
        n=c1-c2+1
        score+=(score1-score2)*(k//n)
        k%=n
        idle_max=max(idle_max,score)
    while k:
        k-=1
        s=P[s]
        score+=C[s]
        idle_max=max(idle_max,score)


print(idle_max)

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=[i-1 for i in P]
idle_max=-10**27



for s in range(0,N):
    k=K-1
    score=0
    s=P[s]
    score+=C[s]
    count=1
    idle_max=max(idle_max,score)
    visited={s:[count,score]}
    while k and not P[s] in visited:

        k-=1
        count+=1
        s=P[s]
        visited[s]=[count,score]
        score+=C[s]
        idle_max=max(idle_max,score)
    if k:
        c1,score1=visited[s]
        c2,score2=visited[P[s]]
        n=c1-c2+1
        score+=(score1-score2)*(k//n)
        k%=n
        idle_max=max(idle_max,score)
    while k:
        k-=1
        s=P[s]
        score+=C[s]
        idle_max=max(idle_max,score)


print(idle_max)

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=[i-1 for i in P]
idle_max=-10**27



for s in range(0,N):
    k=K-1
    score=0
    s=P[s]
    score+=C[s]
    count=1
    idle_max=max(idle_max,score)
    visited={s:count}
    while k and not P[s] in visited:

        k-=1
        count+=1
        s=P[s]
        visited[s]=count
        score+=C[s]
        idle_max=max(idle_max,score)
    if k:
        n=visited[s]-visited[P[s]]+1
        score+=score*(k//n)
        k%=n
        idle_max=max(idle_max,score)
    while k:
        k-=1
        s=P[s]
        score+=C[s]
        idle_max=max(idle_max,score)


print(idle_max)

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=[i-1 for i in P]
idle_max=-10**27



for s in range(0,N):
    k=K-1
    score=0
    s=P[s]
    score+=C[s]
    count=1
    idle_max=max(idle_max,score)
    visited={s}
    while k and not P[s] in visited:
        visited.add(P[s])
        k-=1
        count+=1
        s=P[s]

        score+=C[s]
        idle_max=max(idle_max,score)
    if k:
        score+=score*(k//len(visited))
        k%=len(visited)
        idle_max=max(idle_max,score)
    while k:
        k-=1
        s=P[s]
        score+=C[s]
        idle_max=max(idle_max,score)


print(idle_max)

Submission status: Wrong Answer

Solution code:
N,K = map(int, input().split())
P = [int(p) for p in input().split()]
C = [int(c) for c in input().split()]

ans = max(C)
for i in range(N):
    used = [0]*N
    used[i] = 1
    loop = [C[i]]
    j = P[i]-1
    while used[j] == 0:
        used[j] = 1
        loop.append(loop[-1]+C[j])
        j = P[j]-1
    M = len(loop)
    if K >= M:
        if K%M == 0:
            t = 0
        else:
            t = max(loop[:K%M])
            t = max(t, 0)
        num = max(loop[-1]*(K//M)+t, max(loop))
    else:
        num = max(loop[:K])
    ans = max(ans, num)
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()))

point_loop_list = [0 for _ in range(N)]
point_set = set()
loop_list = []
for i in range(N):
    if i in point_set:
        continue
    loop = [i]
    j = P[i] - 1
    while j != i:
        loop.append(j)
        point_set.add(j)
        j = P[j] - 1
    loop += loop
    loop_list.append(loop)

# print(loop_list)

loop_sum_list = [0 for _ in range(N)]

for loop in loop_list:
    loop_len = len(loop) // 2
    s = sum([C[j] for j in loop[:loop_len]])

    for i, p in enumerate(loop[:loop_len]):
        point_loop_list[p] = loop[i:i+loop_len]
        loop_sum_list[p] = s

# for l in point_loop_list:
#     print(l)
# # 
# print(loop_sum_list)

ans = min(C)

for l, s in zip(point_loop_list, loop_sum_list):
    p = 0
    loop_len = len(l)
    if s > 0:
        p += s * (K // loop_len)
        m = 0
        cs = 0
        for i in range(K % loop_len):
            cs += C[l[i]]
            m = max(m, cs)
        p += m
    else:
        m = C[l[0]]
        cs = m
        for i in range(1, loop_len):
            cs += C[l[i]]
            m = max(m, cs)
        p += m
    ans = max(p, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
# import numpy as np
import sys, math, heapq
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial, gcd
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep="\n")

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

used = [0] * N
loops = []
loop = []

for n in range(N):
    if used[n] == 1:
        continue

    # loop check
    val = 0
    step = 0
    p = P[n] - 1
    while used[p] == 0:
        used[p] = 1
        c = C[p]
        val += c
        step += 1
        p = P[p] - 1
    loops.append((n, step, val))
# print(loops)
loops.sort(key=lambda x: -x[2])
# print(loops)

start, step, val = loops[0]
loop = []
used = [0] * N
while used[start] == 0:
    used[start] = 1
    start = P[start] - 1
    loop.append(start)

# print(loop)
base = K // step * val
resi = K % step
maxv = -float("inf")
for start in loop:
    v = 0
    step = 0
    val = 0
    while step < resi:
        start = P[start] - 1
        val += C[start]
        step += 1
    maxv = max(maxv, val)
print(base + maxv)

Submission status: Wrong Answer

Solution code:
# import numpy as np
import sys, math, heapq
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial, gcd
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep="\n")

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

used = [0] * N
loops = []
loop = []

for n in range(N):
    if used[n] == 1:
        continue

    # loop check
    val = 0
    step = 0
    p = P[n] - 1
    while used[p] == 0:
        used[p] = 1
        c = C[p]
        val += c
        step += 1
        p = P[p] - 1
    loops.append((n, step, val))
print(loops)
loops.sort(key=lambda x: -x[2])
print(loops)

start, step, val = loops[0]
loop = []
used = [0] * N
while used[start] == 0:
    used[start] = 1
    start = P[start] - 1
    loop.append(start)

print(loop)
base = K // step * val
resi = K % step
maxv = -float("inf")
for start in loop:
    v = 0
    step = 0
    val = 0
    while step < resi:
        start = P[start] - 1
        val += C[start]
        step += 1
    maxv = max(maxv, val)
print(base + maxv)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))
ans = -float('inf')
checked = [False] * N
for i in range(1, N+1):
    v = i
    score = 0
    loop = []
    while True:
        loop.append(v)
        score += C[v]
        if i == P[v]:
            break
        v = P[v]

    size = len(loop)
    num = K-1
    s = C[i]
    for j in range(1, size):
        if s+C[loop[j]] >= s:
            s += C[loop[j]]
            num -= 1
        else:
            break

    if score > 0:
        s += score*(num//size)

    ans = max(ans, s)
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=[]
for i in range(n):
  ct=0
  score=0
  s=[]
  pos=i
  while ct<k:
    ct+=1
    pos=p[pos]-1
    score+=c[pos]
    s.append(score)
    if pos==i:
      break
  if s[-1]<0:
    ans.append(max(s))
  elif pos!=i:
    ans.append(max(s))
  elif k%len(s)==0:
    ans.append(s[-1]*(k//len(s)-1)+max(s))
  elif max(s)==max(s[0:k%len(s)]):
    ans.append(s[-1]*(k//len(s))+max(max(s[0:k%len(s)]),0))
  else:
    ans.append(s[-1]*(k//len(s)-1)+max(s))
print(max(ans))

Submission status: Wrong Answer

Solution code:
a=[list(map(int,input().split(" "))) for i in range(3)]
ans=[0]*a[0][0]
for i in range(a[0][0]):
  num =i
  count =0
  summ =0
  summax =0
  summaxnum =0
  for j in range(min(a[0][0],a[0][1])):
    num = a[1][num]-1
    count+=1
    summ += a[2][num]
    if count == 1:
      summax=summ
      summaxnum =count
    if summax < summ:
      summax=summ
      summaxnum =count
    if num==i:
      break
  if summ<0:
    ans[i]=summax
  elif a[0][1]%count>=summaxnum:
    ans[i]=summax+summ*(a[0][1]//count)
  else:
    ans[i]=summax+summ*(a[0][1]//count -1)    
print(max(ans))

Submission status: Wrong Answer

Solution code:
a=[list(map(int,input().split(" "))) for i in range(3)]
score =[0]*a[0][0]
for i in range(a[0][0]):
  num= i
  for j in range(a[0][1]):
    num = a[1][num]-1
    score[i] += a[2][num]
print(max(score))

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [i-1 for i in map(int, input().split())]
C = list(map(int, input().split()))

ans = -float("inf")

for i in range(N):
    curr = 0
    curr_score = 0


    loop_score = 0
    loop_length = 0
    K_ = K
    j = i
    while True:
        j = P[j]
        loop_score += C[j]
        loop_length += 1
        if j == i:
            break
    if loop_score > 0:
        curr_score += loop_score * (K//loop_length)
        curr = curr_score
        K_ -= loop_length*(K//loop_length)
    for k in range(K_):
        j = P[j]
        curr_score += C[j]
        curr = max(curr, curr_score)
    ans = max(curr, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
from copy import copy
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []
used = [False] * n

for i in range(n):
    if(used[i]):
        continue
    
    path = [i]
    loop = []
    v = i
    while not used[v]:
        used[v] = True
        loop.append(li_c[v])
        v = li_p[v]

    li_loop.append(loop)

for loop in li_loop:
    loop_len = len(loop)

    cumsum = [0]*(2*loop_len+1)
    for i in range(2*loop_len):
        cumsum[i+1] = cumsum[i] + loop[i%loop_len]
    amari = [-(10**30)] * loop_len

    for i in range(loop_len):
        for j in range(loop_len):
            amari[j] = max(amari[j], cumsum[i+j] - cumsum[i])
    
    ans = -(10**30)    
    
    for r in range(loop_len):
        if r>k:
            continue
        q = (k-r)//loop_len
        if r==0 and q==0:
            continue
        if cumsum[loop_len]>0:
            ans = max(ans, amari[r] + cumsum[loop_len]*q)
        elif r>0:
            ans = max(ans, amari[r])
print(ans)

Submission status: Wrong Answer

Solution code:
from copy import copy
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []
used = [False] * n

for i in range(n):
    if(used[i]):
        continue
    
    path = [i]
    loop = []
    v = i
    while not used[v]:
        used[v] = True
        loop.append(li_c[v])
        v = li_p[v]

    li_loop.append(loop)

for loop in li_loop:
    loop_len = len(loop)

    cumsum = [0]*(2*loop_len+1)
    for i in range(2*loop_len):
        cumsum[i+1] = cumsum[i] + loop[i%loop_len]
    amari = [-(10**30)] * loop_len

    for i in range(loop_len):
        for j in range(loop_len):
            amari[j] = max(amari[j], cumsum[i+j] - cumsum[i])
    
    ans = -(10**30)    
    
    for r in range(loop_len):
        if r>k:
            continue
        q = (k-r)//loop_len
        if r==0 and q==0:
            continue

        if cumsum[loop_len]:
            ans = max(ans, amari[r] + cumsum[loop_len]*q)
        elif r>0:
            ans = max(ans, amari[r])
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N, K = list(map(int, input().split()))
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))

    P_now = P
    nloop = [1]*N
    countup = [1]*N
    score = [[0]*N]
    for iter in range(N):
        score.append([score[iter][i]+C[num-1] if countup[i] else score[iter][i] for i, num in enumerate(P_now)])
        P_now = [P[i-1] for i in P_now]
        countup = [0 if P_now[i]==P[i] else countup[i] for i in range(N)]
        if sum(countup) == 0:
            break
        nloop = [nloop[i]+countup[i] for i in range(N)]
    score[-1] = [0 if score[-1][i]<0 else score[-1][i] for i in range(N)]
    del score[0]
    score_t = [list(x) for x in zip(*score)]

    amari = [K%nloop[i] for i in range(N)]
    max_score1 = [max(row[0:amari[i]]) if amari[i]>0 else C[i] for i, row in enumerate(score_t)]
    max_score2 = [K//nloop[i]*score[-1][i] for i in range(N)]
    max_score_list = [max_score1[i] + max_score2[i] for i in range(N)]
    print(max(max_score_list))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from copy import copy
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []
used = []

for i in range(n):
    if(i in used):
        continue

    point = [li_c[i]]
    cnt = 0
    path = [i]
    used.append(i)
    while True:
        used.append(li_p[path[-1]])
        path.append(li_p[path[-1]])
        point.append(li_c[path[-1]])
        if(len(path)!=len(set(path))):
            break
    loop = point[:-1]
    li_loop.append(loop)
    if len(used)==n:
        break

for loop in li_loop:
    loop.sort(reverse=True)
    ans = loop[0]
    loop = loop[1:]
    loop.append(ans)
    k -= 1
    if(sum(loop)<0):
        for p in loop:
            if ans+p < ans or k==0:
                break
            ans += p
            k -= 1
        li_point.append(ans)
    else:
        amari = ans
        loop2 = copy(loop)
        for p in loop:
            if amari+p < amari:
                break
            amari += p
            loop2 = loop2[1:]
            loop2.append(p)
            k -= 1
        ans = amari
        ans += sum(loop2)*(k//len(loop2))
        ans += sum(loop2[:k%len(loop2)])
        li_point.append(ans)

print(max(li_point))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []
used = []

for i in range(n):
    if(i in used):
        continue

    point = [li_c[i]]
    cnt = 0
    path = [i]
    used.append(i)
    while True:
        used.append(li_p[path[-1]])
        path.append(li_p[path[-1]])
        point.append(li_c[path[-1]])
        if(len(path)!=len(set(path))):
            break
    loop_start_at = path.index(path[-1])
    loop = point[loop_start_at:-1]
    li_loop.append(loop)
    n -= len(loop)
    if(n==0):
        break

for loop in li_loop:
    loop.sort(reverse=True)
    ans = loop[0]
    loop = loop[1:]
    loop.append(ans)
    cnt = 1
    if(sum(loop)<0):
        for p in loop:
            if ans+p < ans or cnt==k:
                break
            ans += p
            cnt += 1
        li_point.append(ans)
    else:
        k -= 1
        ans += sum(loop)*(k//len(loop))
        ans += sum(loop[:k%len(loop)])
        li_point.append(ans)

print(max(li_point))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []

for i in range(n):
    next_iter = 0
    if(li_loop!=None):
        for l in li_loop:
            if li_c[i] in l:
                next_iter = 1
                break
    if(next_iter):
        continue

    point = [li_c[i]]
    cnt = 0
    path = [i]
    while True:
        path.append(li_p[path[-1]])
        point.append(li_c[path[-1]])
        if(len(path)!=len(set(path))):
            break
    loop_start_at = path.index(path[-1])
    loop = point[loop_start_at:-1]
    li_loop.append(sorted(loop))
    n -= len(loop)
    if(n==0):
        break

for loop in li_loop:
    loop.sort(reverse=True)
    if(sum(loop)<0):
        ans = loop[0]
        cnt = 1
        for p in loop:
            if(cnt==1):
                continue
            if ans+p < ans or cnt==k:
                break
            ans += p
            cnt += 1
        li_point.append(ans)
    else:
        ans = 0
        ans += sum(loop)*(k//len(loop))
        ans += sum(loop[:k%len(loop)])
        li_point.append(ans)
print(max(li_point))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_loop = []
li_point = []

for i in range(n):
    next_iter = 0
    if(li_loop!=None):
        for l in li_loop:
            if li_c[i] in l:
                next_iter = 1
                break
    if(next_iter):
        continue

    point = [li_c[i]]
    cnt = 0
    path = [i]
    while True:
        path.append(li_p[path[-1]])
        point.append(li_c[path[-1]])
        if(len(path)!=len(set(path))):
            break
    loop_start_at = path.index(path[-1])
    loop = point[loop_start_at:-1]
    li_loop.append(sorted(loop))
    n -= len(loop)
    if(n==0):
        break

for loop in li_loop:
    ans = 0
    loop.sort(reverse=True)
    if(sum(loop)<0):
        cnt = 0
        for p in loop:
            if ans+p < ans or cnt==k:
                break
            ans += p
            cnt += 1
        li_point.append(ans)
    else:
        ans += sum(loop)*(k//len(loop))
        ans += sum(loop[:k%len(loop)])
        li_point.append(ans)
print(max(li_point))

Submission status: Wrong Answer

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

pi = [p-1 for p in pi]

def cycle_score(i, pi, ci, n_cycles, mods):
    ssum = 0
    scores = [0] * len(pi)
    j = i
    cnt = 0
    max_score = -10**10
    max_mod_score = -10**10
    while 1:
        j = pi[j]

        s = ci[j]
        ssum += s
        max_score = max(ssum, max_score)

        if cnt < mods:
            max_mod_score = max(ssum, max_mod_score)
        # scores[cnt] = ssum

        cnt += 1

        if j == i:
            break

    if ssum > 0:
        ans = n_cycles * ssum + max_mod_score
    else:
        if n_cycles >= 1:
            ans = max_score
        else:
            ans = max_mod_score

    return ans 


max_ans = -100000000000
for i in range(len(pi)):
    n_cycles = K // len(pi)
    mods = K % len(pi)
    ans = cycle_score(i, pi, ci, n_cycles, mods)
    max_ans = max(ans, max_ans)


print(max_ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
li_p = list(map(int, input().split()))
li_p = list(map(lambda x: x-1, li_p))
li_c = list(map(int, input().split()))
li_point = []
for i in range(n):
    point = [li_c[i]]
    cnt = 0
    path = [i]
    while True:
        path.append(li_p[path[-1]])
        point.append(li_c[path[-1]])
        if(len(path)!=len(set(path))):
            break
    loop_start_at = path.index(path[-1])
    loop = point[loop_start_at:-1]
    loop_sum = sum(loop)
    loop_len = len(point) - loop_start_at - 1
    loop_num = (k-loop_start_at) // loop_len
    amari = sum(loop[:(k-loop_start_at) % loop_len])
    s = sum(point[:loop_start_at]) + loop_sum*loop_num + amari
    li_point.append(s)
print(max(li_point))

Submission status: Wrong Answer

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

cloop = [[0, 10**9] for _ in range(n+1)] 
for i in range(1, n+1):
    if cloop[i][0] != 0:
        continue
    x = c[i]
    cp = i
    li = [i]
    d = 1
    while True:
        if p[cp] == i:
            break
        cp = p[cp]
        x += c[cp]
        li.append(cp)
        d += 1
    for _ in li:
        cloop[_][0] = x
        cloop[_][1] = d


ans = -10**18
for i in range(1, n+1):
    if k <= cloop[i][1]:
        gk = k - (k // cloop[i][1] - 1) * cloop[i][1]
        tmp = max(0, cloop[i][0] * (k // cloop[i][1] - 1))
    else:
        gk = k
        tmp = 0
    cp = i
    ck = 0
    while ck < gk:
        cp = p[cp]
        ck += 1
        tmp += c[cp]
        ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

cloop = [[0, 0] for _ in range(n+1)] 
for i in range(1, n+1):
    if cloop[i][0] != 0:
        continue
    x = c[i]
    cp = i
    li = [i]
    d = 1
    while True:
        if p[cp] == i:
            break
        cp = p[cp]
        x += c[cp]
        li.append(cp)
        d += 1
    for _ in li:
        cloop[_][0] = x
        cloop[_][1] = d


ans = -10**18
for i in range(1, n+1):
    gk = k - (k // cloop[i][1] - 1) * cloop[i][1]
    tmp = max(0, cloop[i][0] * (k // cloop[i][1] - 1))
    cp = i
    ck = 0
    while ck < gk:
        cp = p[cp]
        ck += 1
        tmp += c[cp]
        ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

cloop = [[0, 0] for _ in range(n+1)] 
for i in range(1, n+1):
    if cloop[i][0] != 0:
        continue
    x = c[i]
    cp = i
    li = [i]
    d = 1
    while True:
        if p[cp] == i:
            break
        cp = p[cp]
        x += c[cp]
        li.append(cp)
        d += 1
    for _ in li:
        cloop[_][0] = x
        cloop[_][1] = d


ans = -10**18
for i in range(1, n+1):
    if cloop[i][0] > 0:
        gk = k % cloop[i][1]
        tmp = cloop[i][0] * (k // cloop[i][1])
    elif k % cloop[i][1] == 0:
        gk = cloop[i][1]
        tmp = 0
    else:
        gk = k % cloop[i][1]
        tmp = 0
    cp = i
    ck = 0
    while ck < gk:
        cp = p[cp]
        ck += 1
        tmp += c[cp]
        ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

cloop = [[0, 0] for _ in range(n+1)] 
for i in range(1, n+1):
    if cloop[i][0] != 0:
        continue
    x = c[i]
    cp = i
    li = [i]
    d = 1
    while True:
        if p[cp] == i:
            break
        cp = p[cp]
        x += c[cp]
        li.append(cp)
        d += 1
    for _ in li:
        cloop[_][0] = x
        cloop[_][1] = d


ans = -10**18
for i in range(1, n+1):
    if cloop[i][0] > 0:
        gk = k % cloop[i][1]
        tmp = cloop[i][0] * (k // cloop[i][1])
    else:
        gk = k % cloop[i][1] + cloop[i][1]
        tmp = 0
    cp = i
    ck = 0
    while ck < gk:
        cp = p[cp]
        ck += 1
        tmp += c[cp]
        ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

cloop = [[0, 0] for _ in range(n+1)] 
for i in range(1, n+1):
    if cloop[i][0] != 0:
        continue
    x = c[i]
    cp = i
    li = [i]
    d = 1
    while True:
        if p[cp] == i:
            break
        cp = p[cp]
        x += c[cp]
        li.append(cp)
        d += 1
    for _ in li:
        cloop[_][0] = x
        cloop[_][1] = d


ans = -10**18
for i in range(1, n+1):
    gk = k % cloop[i][1]
    tmp = max(0, cloop[i][0] * (k // cloop[i][1]))
    cp = i
    ck = 0
    ans = max(ans, tmp)
    while ck < gk:
        cp = p[cp]
        ck += 1
        tmp += c[cp]
        ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

ans = -10**18
for i in range(1, n+1):
    cp = i
    ck = 0
    loop = False
    tmp1 = 0
    tmp2 = -10**18
    while ck < k or loop == False:
        cp = p[cp]
        ck += 1
        tmp1 += c[cp]
        tmp2 = max(tmp1, tmp2)
        if cp == i:
            loop = True
    if ck < k and loop:
        if tmp1 > 0:
            tmp2 += tmp1 * (k - ck) // ck
    ans = max(ans, tmp2)
print(ans)