Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
cycles = []
nux = -100000000
cycles_score = []
for start in range(n):
    if done[start]:
        cycle = [start]
        score = C[start]
        nex = P[start]-1
        while nex != start:
            cycle.append(nex)
            score += C[nex]
            nex = P[nex]-1
        cycles.append(cycle)
        cycles_score.append(score)

for score, cycle in zip(cycles_score, cycles):
    l = len(cycle)
    acum = [0 for _ in range(2*l)]
    acum[0] = 0
    for i in range(2*l-1):
        acum[i+1] = acum[i]+C[cycle[i % l]]

    for r in range(l):
        q = (k-r)//l
        for i in range(l):
            if r == 0 and q == 0:
                continue
            nux = max(nux, score*q+acum[i+r]-acum[i])


print(nux)

"""n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
for start in range(n):
    if done[start]:
        nex = -1
        j = 0
        tuuka = []
        nax = -float("inf")
        while nex != start:
            if nex == -1:
                nex = P[start]-1
            else:
                nex = P[nex]-1
            tuuka.append(nex)
            score[start] += C[nex]
            nax = max(nax, score[start])
            j += 1
        loopn[start] = j
        for i in tuuka:
            done[i] = False
            loopn[i] = j
            score[i] = score[start]
            nokori = k-(k//loopn[start])*loopn[start]

    if score[start] < 0:
        score[start] = 0
    else:
        score[start] = (k//loopn[start])*score[start]
        nokori = k-(k//loopn[start])*loopn[start]
        i = 0
        nnnnn = (k//loopn[start])
        nscore = 0
        nax = 0
        while i < nokori:
            nex = P[nex]-1
            nscore += C[nex]
            if nscore < 0:
                break
            nax = max(nax, nscore)
            i += 1
        if nax > 0:
            score[start] += nax


ans = max(score)
if ans <= 0:
    ans = max(C)
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=-float('inf')
for i in range(n):
  T=1
  index=p[i]-1
  score=c[index]
  while index!=i:
    T+=1
    index=p[index]-1
    score+=c[index]
  #場合分け開始
  if T>k:
    score_list=[c[p[i]-1]]+[0]*(k-1)
    index=p[i]-1
    for s in range(1,k):
      index=p[index]-1
      score_list[s]=score_list[s-1]+c[index]
    score=max(score_list)
  else:
    if score<0:
      score_list=[c[p[i]-1]]+[0]*(n-1)
      index=p[i]-1
      for s in range(1,n):       
        index=p[index]-1
        score_list[s]=score_list[s-1]+c[index]        
      score=max(score_list)
    else:
      m=k//n
      score_list=[c[p[i]-1]]+[0]*(k-n*m-1)
      index=p[i]-1
      for s in range(1,k-n*m):
        index=p[index]-1
        score_list[s]=score_list[s-1]+c[index]
      score=max(score_list)+score*m
  ans=max(ans,score)

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=[]
S=[]
p=2**N-1
for i in range(N):
  if p>>i&1:
    s=i+1
    tmp=[C[i]]
    while s!=P[i]:
      i=P[i]-1
      tmp.append(C[i])
      p^=1<<i
    A.append(tmp)
    S.append(sum(tmp))
ans=-1*(10**9)-1
for i in range(len(A)):
  a=A[i]
  n=len(a)
  s=S[i]
  for j in range(n):
    t=0
    k=n
    if K>n:
      if s > 0:
        k=K%n
        t+=s*(K//n)
    else:
      k=K
    for jj in range(j,k+j):
      if jj>=n:
        jj-=n
      t+=a[jj]
      ans=max(ans,t)
    ans=max(ans,t)
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=[]
S=[]
p=2**N-1
for i in range(N):
  if p>>i&1:
    s=i+1
    tmp=[C[i]]
    while s!=P[i]:
      i=P[i]-1
      tmp.append(C[i])
      p^=1<<i
    A.append(tmp)
    S.append(sum(tmp))
ans=-1*(10**9)-1
for i in range(len(A)):
  n=len(A[i])
  s=S[i]
  for j in range(n):
    t=0
    k=n
    if K>n:
      if s > 0:
        k=K%n
        t+=s*(K//n)
    else:
      k=K
    for jj in range(j,k+j):
      if jj>=n:
        jj-=n
      t+=A[i][jj]
      ans=max(ans,t)
    ans=max(ans,t)
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=[]
M=[]
p=2**N-1
for i in range(N):
  if p>>i&1:
    s=i+1
    tmp=[C[i+1]]
    while s!=P[i]:
      tmp.append(C[i])
      i=P[i]-1
      p^=1<<i
    A.append(tmp)
    M.append(sum(tmp))
ans=-1*(10**9)-1
for i in range(len(A)):
  n=len(A[i])
  m=M[i]
  for j in range(n):
    t=0
    k=n
    if K>n:
      if m > 0:
        k=K%n
        t+=m*(K//n)
    else:
      k=K
    for jj in range(j,k+j):
      if jj>=n:
        jj-=n
      t+=A[i][jj]
      ans=max(ans,t)
    ans=max(ans,t)
print(ans)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy
n,k=map(int,input().split(" "))
P=list(map(int,input().split(" ")))
C=list(map(int,input().split(" ")))
count=[]
def f (i):
    q=deepcopy(i)
    count1=[]
    count2=0
    for j in range(k):
        count2+=C[i]
        count1.append(count2)
        
        i=P[i]-1
        if i==q:
            a=count1[-1]
            b=deepcopy(len(count1))
            if a>0:
                for l in range(b):
                    count1.append(count1[l]+a*(k-l-1)//b)
            break
   
    return max(count1)
for i in range(n):
    count.append(f(i))
print(max(count))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
def f(s):
  return int(s) - 1

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

loop = []

first = -1
x = -1
loop_mem = []
cnt = 0
score = 0

rem = set(range(N))

while len(rem) > 0:
  if first < 0:
    first = rem.pop()
    x = first
  loop_mem.append(x)
  if x != first:
    rem.remove(x)
  if first != P[x]:
    cnt += 1
    score += C[x]
    x = P[x]
  else:
    cnt += 1
    score += C[x]
    loop.append((loop_mem, cnt, score))
    first = -1
    loop_mem = []
    cnt = 0
    score = 0

ans = -1e10
for loop_mem, cnt, score in loop:
  imax = [-1e10 for _ in range(len(loop_mem))]
  for x in loop_mem:
    tmp = 0
    for j in range(len(loop_mem)):
      tmp += C[x]
      imax[j] = max(imax[j], tmp)
      x = P[x]
  for j in range(1, len(loop_mem)):
    imax[j] = max(imax[j-1], imax[j])
  if score <= 0:
    ans = max(ans, imax[-1])
  else:
    M = K // cnt
    m = K % cnt
    if M >= 1:
      tmp = max(score * M + max(imax[m-1], 0), score * (M-1) + imax[-1])
    else:
      tmp = imax[m-1]
  ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
'''
4 5
4 1 2 3
-19 4 10 6

4 4
4 1 2 3
-19 4 10 6
'''

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

minusOnly = True
for i in range(n):
    if c[i] > 0:
        minusOnly = False
        break

if minusOnly:
    print(max(c))
    exit()

ans = 0
used = [False]*n

for st in range(n):
    if not used[st]:
        gr = []
        now = st
        gr.append(st)
        used[st] = True
        while True:
            now = p[now]
            gr.append(now)
            used[now] = True
            if now == st:
                break
        gr.pop()

        cs = [c[i] for i in gr]
        s = sum(cs)
        point = 0
        point2 = 0
        plus = 0
        cs = cs + cs
        r = k
        if k > len(gr):
            if s > 0:
                point += s*(k//len(gr))
                r -= len(gr)*(k//len(gr))
                
                # sを使わない場合
                for i in range(len(gr)):
                    nowSum = 0
                    for g in range(len(gr)):
                        nowSum += cs[i+g]
                        point2 = max(point2, nowSum)

            else:
                r = len(gr)
        
        plus = 0
        for i in range(len(gr)):
            nowSum = 0
            for g in range(r):
                nowSum += cs[i+g]
                plus = max(plus, nowSum)
        point += plus
        
        ans = max(ans, point, point2)

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()))
def f(x,m):
  if m==0:return 0
  tmp=c[x]
  a=max(0,tmp)
  x=p[x]-1
  for i in range(m-1):
    tmp+=c[x]
    a=max(a,tmp)
    x=p[x]-1
  return a
def F(x):
  tmp=c[x]
  m=p[x]-1
  i=1
  while m!=x:
    i+=1
    tmp+=c[m]
    m=p[m]-1
  return (tmp,i)
ans=-float("INF")
for i in range(n):
  s,z=F(i)
  if s>0:
    tmp=s*(k//z)+f(i,k%z)
  else:
    tmp=f(i,min(n,k))
  ans=max(ans, tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
def f(s):
  return int(s) - 1

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

loop = []

first = -1
x = -1
loop_mem = []
cnt = 0
score = 0

rem = set(range(N))

while len(rem) > 0:
  if first < 0:
    first = rem.pop()
    x = first
  loop_mem.append(x)
  if x != first:
    rem.remove(x)
  if first != P[x]:
    cnt += 1
    score += C[x]
    x = P[x]
  else:
    cnt += 1
    score += C[x]
    loop.append((loop_mem, cnt, score))
    first = -1
    loop_mem = []
    cnt = 0
    score = 0

ans = -1e10
for loop_mem, cnt, score in loop:
  imax = [-1e10 for _ in range(len(loop_mem))]
  for x in loop_mem:
    tmp = 0
    for j in range(len(loop_mem)):
      tmp += C[x]
      imax[j] = max(imax[j], tmp)
      x = P[x]
  for j in range(1, len(loop_mem)):
    imax[j] = max(imax[j-1], imax[j])
  if score <= 0:
    ans = max(ans, imax[-1])
  else:
    M = K // cnt
    m = K % cnt
    if M >= 1:
      tmp = max(score * M + max(imax[m-1], 0), score * (M-1) + imax[-1])
    else:
      tmp = imax[m-1]
    ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())

p=list(map(int,input().split()))
score=list(map(int,input().split()))

group_score=[]
checked=[0]*n

for i in range(n):
    if checked[i]==0:
        tmp_group=[]
        tmp=i
        while checked[tmp]==0:
            checked[tmp]=1
            tmp_group.append(score[tmp])
            tmp=p[tmp]-1
        group_score.append(tmp_group)



#aryの中から連続するk個選択するときの最大
def calc(ary,k):
    ans=ary[0]
    for i in range(len(ary)):
        tmp=0
        for j in range(k):
            tmp+=ary[(i+j)%len(ary)]
            ans=max(ans,tmp)

    return ans

ans=score[0]
for group in group_score:
    #一周以上する場合
    if len(group)>k:
        cycle=sum(group)
        if cycle>0:
            cycle_sum=cycle*(len(group)//k)
            tmp=calc(group,len(group)%k)
            ans=max(ans,cycle_sum+tmp)

        else:
            tmp=calc(group,len(group))
            ans=max(ans,tmp)

    #一周しない場合k)
    else:
        tmp=calc(group,k)
        ans=max(ans,tmp)

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

cycle = []
cycles = []
for i in range(0,n):
  pos = i
  cnt = 1
  group = []
  while (p[pos]-1) != i:
    pos = p[pos]-1
    cnt += 1
    group.append(c[pos])
  cycle.append(cnt)
  group.append(c[i])
  cycles.append(group)
#print(cycles)

ans = -(10**10)
for i in range(0,n):
  if cycle[i] > k:
    tmp = 0
    for j in range(0,k):
      tmp += cycles[i][j]
      ans = max(ans, tmp)
  elif cycle[i]%k == 0:
    tmp = 0
    if sum(cycles[i]) > 0:
      tmp = (k//cycle[i] -1) * sum(cycles[i])
      for j in range(0,cycle[i]):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
    else:
      for j in range(0,cycle[i]):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
  else:  
    tmp = 0
    if sum(cycles[i]) > 0:
      tmp = k//cycle[i] * sum(cycles[i])
      for j in range(0,k%cycle[i]):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
    else:
      for j in range(0,k%cycle[i]):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
        
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()))
score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
cycles = []
nux = -100000000
cycles_score = []
for start in range(n):
    if done[start]:
        cycle = [start]
        score = C[start]
        nex = P[start]-1
        while nex != start:
            cycle.append(nex)
            score += C[nex]
            nex = P[nex]-1
        cycles.append(cycle)
        cycles_score.append(score)

for score, cycle in zip(cycles_score, cycles):
    l = len(cycle)
    acum = [0 for _ in range(2*l)]
    acum[0] = 0
    for i in range(2*l-1):
        acum[i+1] = acum[i]+C[cycle[i % l]]

    for r in range(1, l+1):
        q = (k-r)//l
        for i in range(l):
            if r == 0 and q == 0:
                continue
            nux = max(nux, score*q+acum[i+r]-acum[i])


print(nux)

"""n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
for start in range(n):
    if done[start]:
        nex = -1
        j = 0
        tuuka = []
        nax = -float("inf")
        while nex != start:
            if nex == -1:
                nex = P[start]-1
            else:
                nex = P[nex]-1
            tuuka.append(nex)
            score[start] += C[nex]
            nax = max(nax, score[start])
            j += 1
        loopn[start] = j
        for i in tuuka:
            done[i] = False
            loopn[i] = j
            score[i] = score[start]
            nokori = k-(k//loopn[start])*loopn[start]

    if score[start] < 0:
        score[start] = 0
    else:
        score[start] = (k//loopn[start])*score[start]
        nokori = k-(k//loopn[start])*loopn[start]
        i = 0
        nnnnn = (k//loopn[start])
        nscore = 0
        nax = 0
        while i < nokori:
            nex = P[nex]-1
            nscore += C[nex]
            if nscore < 0:
                break
            nax = max(nax, nscore)
            i += 1
        if nax > 0:
            score[start] += nax


ans = max(score)
if ans <= 0:
    ans = max(C)
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()))

cycle = []
cycles = []
for i in range(0,n):
  pos = i
  cnt = 1
  group = []
  while (p[pos]-1) != i:
    pos = p[pos]-1
    cnt += 1
    group.append(c[pos])
  cycle.append(cnt)
  group.append(c[i])
  cycles.append(group)
#print(cycles)

ans = -(10**10)
for i in range(0,n):
  if cycle[i] > k:
    tmp = 0
    for j in range(0,k):
      tmp += cycles[i][j]
      ans = max(ans, tmp)
  elif cycle[i]%k == 0:
    tmp = 0
    if sum(cycles[i]) > 0:
      tmp = (k//cycle[i] -1) * sum(cycles[i])
      for j in range(0,k):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
    else:
      for j in range(0,k):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
  else:  
    tmp = 0
    if sum(cycles[i]) > 0:
      tmp = k//cycle[i] * sum(cycles[i])
      for j in range(0,k%cycle[i]):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
    else:
      for j in range(0,k%cycle[i]):
      	tmp += cycles[i][j]
      	ans = max(ans, tmp)
        
print(ans)

Submission status: Wrong Answer

Solution code:
N , K = ( int(x) for x in input().split() )
P = list( int(x) for x in input().split() )
C = list( int(x) for x in input().split() )

loop_num = [ 0 for i in range( N ) ]
loop_val = [ 0 for i in range( N ) ]

each_max = [ 0 for i in range( N ) ]

loop_ok = [ 1 for i in range( N ) ]

x = 1
num = 0
val = 0
for i in range( N ):
    num = 0
    val = 0
    x = i - 1
    flag = 0
    while x != i and loop_ok[i] == 1:
        if flag == 0:
            x = i
            flag += 1
        loop_ok[x] = 0
        x = P[x] - 1
        num += 1
        val += C[x]
        
    flag = 0
    while x != i:
        if flag == 0:
            x = i
            flag += 1
        loop_num[x] = num
        loop_val[x] = val
        x = P[x] - 1

    if K < num or loop_val[i] <= 0:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( K ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value
        each_max[i] = maxx
    else:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( num ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value

        sho = K // num
        amari = K % num
        max_ = val * sho
        max_dash = 0
        value = 0
        x = i
        for j in range( amari ):
            x = P[x] - 1
            value += C[x]
            if max_dash < value:
                max_dash = value
        max_ += max_dash
        each_max[i] = max( maxx , max_ )



#print(loop_num,loop_val)

print( int( max(each_max) ) )

Submission status: Wrong Answer

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
from collections import deque
from itertools import accumulate

class SegmentTree(object):
    def __init__(self, A, dot, unit):
        n = 1 << (len(A) - 1).bit_length()
        tree = [unit] * (2 * n)
        for i, v in enumerate(A):
            tree[i + n] = v
        for i in range(n - 1, 0, -1):
            tree[i] = dot(tree[i << 1], tree[i << 1 | 1])
        self._n = n
        self._tree = tree
        self._dot = dot
        self._unit = unit

    def __getitem__(self, i):
        return self._tree[i + self._n]

    def update(self, i, v):
        i += self._n
        self._tree[i] = v
        while i != 1:
            i >>= 1
            self._tree[i] = self._dot(self._tree[i << 1], self._tree[i << 1 | 1])

    def add(self, i, v):
        self.update(i, self[i] + v)

    def sum(self, l, r):
        l += self._n
        r += self._n
        l_val = r_val = self._unit
        while l < r:
            if l & 1:
                l_val = self._dot(l_val, self._tree[l])
                l += 1
            if r & 1:
                r -= 1
                r_val = self._dot(self._tree[r], r_val)
            l >>= 1
            r >>= 1
        return self._dot(l_val, r_val)

def resolve():
    n, k = map(int, input().split())
    P = list(map(lambda x : int(x) - 1, input().split()))
    C = list(map(int, input().split()))

    if max(C) <= 0:
        print(max(C))
        return

    ans = -INF
    used = [False] * n
    for i in range(n):
        if used[i]:
            continue
        used[i] = True
        cycle = [C[i]]
        while not used[P[i]]:
            i = P[i]
            cycle.append(C[i])
            used[i] = True

        score = 0
        c = sum(cycle)
        n = 1 + 2 * len(cycle)
        if c > 0:
            q, r = divmod(k, len(cycle))
            score += c * q
            L = r
        else:
            L = min(n, k)

        tree = SegmentTree(list(accumulate([0] + cycle + cycle)), max, -INF)
        tmp = 0
        for i in range(n):
            tmp = max(tmp, tree.sum(i, min(i + L + 1, n)) - tree[i])
        ans = max(ans, score + tmp)

    print(ans)
resolve()

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 = [None] + P
C = [None] + C

all_max = C[1]
for st in range(1, N + 1):
    p = P[st]
    scores = [C[p]]

    while p != st:
        p = P[p]
        scores.append(C[p])

    num_elem = len(scores)
    all_sum = sum(scores)

    q, r = divmod(K, num_elem)

    max_ = scores[0]
    temp = scores[0]

    max_r = scores[0]
    temp_r = scores[0]
    for x in range(1, num_elem):
        if x < r:
            temp_r += scores[x]
            max_r = max(max_r, temp_r)

        temp += scores[x]
        max_ = max(max_, temp)

    temp_max = scores[0]
    if all_sum > 0 and q > 0:
        if r > 0:
            temp_max = max(all_sum * (q - 1) + max_, all_sum * q + max_r)
        else:
            temp_max = all_sum * (q - 1) + max_
    else:
        temp_max = max_

    all_max = max(all_max, temp_max)


print(all_max)

Submission status: Wrong Answer

Solution code:
N , K = ( int(x) for x in input().split() )
P = list( int(x) for x in input().split() )
C = list( int(x) for x in input().split() )

loop_num = [ 0 for i in range( N ) ]
loop_val = [ 0 for i in range( N ) ]

each_max = [ 0 for i in range( N ) ]

loop_ok = [ 1 for i in range( N ) ]

x = 1
num = 0
val = 0
for i in range( N ):
    num = 0
    val = 0
    x = i - 1
    flag = 0
    while x != i and loop_ok[i] == 1:
        if flag == 0:
            x = i
            flag += 1
        loop_ok[x] = 0
        x = P[x] - 1
        num += 1
        val += C[x]
        
    flag = 0
    while x != i:
        if flag == 0:
            x = i
            flag += 1
        loop_num[x] = num
        x = P[x] - 1

    loop_num[i] = num
    loop_val[i] = val
    if K < num:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( K ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value
        each_max[i] = maxx
    else:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( num ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value

        sho = K // num
        amari = K % num
        max_ = val * sho
        max_dash = 0
        value = 0
        x = i
        for j in range( amari ):
            x = P[x] - 1
            value += C[x]
            if max_dash < value:
                max_dash = value
        max_ += max_dash
        each_max[i] = max( maxx , max_ )



#print(loop_num,loop_val)

print( int( max(each_max) ) )

Submission status: Wrong Answer

Solution code:
N , K = ( int(x) for x in input().split() )
P = list( int(x) for x in input().split() )
C = list( int(x) for x in input().split() )

loop_num = [ 0 for i in range( N ) ]
loop_val = [ 0 for i in range( N ) ]

each_max = [ 0 for i in range( N ) ]

loop_ok = [ 1 for i in range( N ) ]

x = 1
num = 0
val = 0
for i in range( N ):
    num = 0
    val = 0
    x = i - 1
    flag = 0
    while x != i and loop_ok[i] == 1:
        if flag == 0:
            x = i
            flag += 1
        loop_ok[x] = 0
        x = P[x] - 1
        num += 1
        val += C[x]

    loop_num[i] = num
    loop_val[i] = val
    if K < num:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( K ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value
        each_max[i] = maxx
    else:
        maxx = -float('inf')
        value = 0
        x = i
        for j in range( num ):
            x = P[x] - 1
            value += C[x]
            if maxx < value:
                maxx = value

        sho = K // num
        amari = K % num
        max_ = val * sho
        max_dash = 0
        value = 0
        x = i
        for j in range( amari ):
            x = P[x] - 1
            value += C[x]
            if max_dash < value:
                max_dash = value
        max_ += max_dash
        each_max[i] = max( maxx , max_ )



#print(loop_num,loop_val)

print( int( max(each_max) ) )

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

answer = -float('inf')
for start_p in range(1, N+1):

    cycle_total_score = 0
    cycle_in_score = -float('inf')
    cycle_count = 0
    next_p = P[start_p]
    while True:
        cycle_total_score += C[next_p]
        cycle_in_score = max(cycle_in_score, cycle_total_score)
        cycle_count += 1

        if next_p == start_p:
            # print('start_p:', start_p, ' cycle_total_score:', cycle_total_score, 'cycle_in_score:', cycle_in_score, 'cycle_count:', cycle_count)
            break
        next_p = P[next_p]

    max_score = 0
    if K == cycle_count:
        max_score = cycle_in_score
    else:
        #あふれたK % cycle_count回数分だけスコアを足すためにmaxを探さす
        add_max_count = K % cycle_count
        add_total_score = 0
        add_score = -float('inf')
        add_count = 0
        add_next_p = P[start_p]
        while True:
            add_total_score += C[add_next_p]
            add_score = max(add_score, add_total_score)
            add_count += 1

            if add_count == add_max_count:
                break
            add_next_p = P[add_next_p]

        if K < cycle_count:
            #最大の試行回数がcycle_countよりも小さい場合K % cycle_countまでで一番良いところでbeak
            max_score = add_total_score
        else:
            if cycle_total_score >= 0:
                #1サイクルでプラスの場合はできるだけサイクルを回してK % cycle_countまでで一番良いところでbeak
                max_score = (K // cycle_count) * cycle_total_score + add_total_score
            else:
                #1サイクルでマイナスの場合はサイクルを回さないで、K % cycle_countまでで一番良いところでbreak
                max_score = add_total_score
    # print('max_score', max_score)
    answer = max(answer, max_score)

print(answer)

Submission status: Wrong Answer

Solution code:
"""
1. マス同士は有効グラフの一本道になっている。で、必ずどこかでループが発生している。

2. 各点から各点に移動する場合のスコアの合計とステップ数(ループ内の場合は一周以内のもの)を前処理(dfs)で求めておく。dp[i][j] => iからjまでのスコアとステップ数

3. K > N の場合、ループを通るとスコアがマイナスになるなら（dp[i][i]がマイナスになるようなiが存在するなら）、ループを一周しない方がよい。
ループを通るとスコアがプラスになるなら、

各iに対して地点iからスタートする場合というのをシミュレートすると実装が楽そう。
K <= Nの場合はi番目からスタートして、dfsでstep数がKに到達するまで進み続けて、スコアの最大値を図る。
Kが大きい場合は、dfsで道をたどっていってループを検出したら、その時点でループスコアがマイナスかプラスかを判断して、マイナスなら終了。
プラスならループスコア*(K//ループstep)を加算してできる限りKを減らす。そこからstep数がKに到達するまでdfsで道をたどっていって最大値を求める。
各スタート地点ごとにO(N)で処理可能なので、全体ではO(N^2)で処理できる
"""
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

ans = -float("INF")
for i in range(1,N+1):
    scores = [None]*(N+1)
    steps = [None]*(N+1)
    step = 0
    cur = i
    score = 0
    loopFlag = False
    while step <= K:
        if scores[cur]!=None and not loopFlag:
            loopFlag = True
            loopScore = score - scores[cur]
            loopStep = step - steps[cur]
            ans = max(ans,score)
            score += ((K-step)//loopStep)*loopScore
            step += ((K-step)//loopStep)*loopStep
        scores[cur] = score
        steps[cur] = step
        if step != 0:
            ans = max(ans,score)
        p = P[cur-1]
        c = C[p-1]
        cur = p
        score += c
        step += 1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)

N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))

answer = -float('inf')
for start_p in range(1, N+1):

    cycle_total_score = 0
    cycle_in_score = -float('inf')
    cycle_count = 0
    next_p = P[start_p]
    while True:
        cycle_total_score += C[next_p]
        cycle_in_score = max(cycle_in_score, cycle_total_score)
        cycle_count += 1

        if next_p == start_p:
            # print('start_p:', start_p, ' cycle_total_score:', cycle_total_score, 'cycle_in_score:', cycle_in_score, 'cycle_count:', cycle_count)
            break
        next_p = P[next_p]

    max_score = 0
    if K == cycle_count:
        max_score = cycle_in_score
    else:
        #あふれたK % cycle_count回数分だけスコアを足すためにmaxを探さす
        add_max_count = K % cycle_count
        add_total_score = 0
        add_score = -float('inf')
        add_count = 0
        add_next_p = P[start_p]
        while True:
            add_total_score += C[add_next_p]
            add_score = max(add_score, add_total_score)
            add_count += 1

            if add_count == add_max_count:
                break
            add_next_p = P[add_next_p]

        if K < cycle_count:
            #最大の試行回数がcycle_countよりも小さい場合K % cycle_countまでで一番良いところでbeak
            max_score = add_total_score
        else:
            if cycle_total_score >= 0:
                #1サイクルでプラスの場合はできるだけサイクルを回してK % cycle_countまでで一番良いところでbeak
                max_score = (K // cycle_count) * cycle_total_score + add_total_score
            else:
                #1サイクルでマイナスの場合はサイクルを回さないで、K % cycle_countまでで一番良いところでbreak
                max_score = add_total_score
    # print('max_score', max_score)
    answer = max(answer, max_score)

print(answer)