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=[0]+list(map(int,input().split()))
c=[0]+list(map(int,input().split()))

used=[0 for i in range(n+1)]
#1からn+1までの辺で試す
ans=-float("INF")
for i in range(1,n+1):
  #すでに探索したループは見なくて良い
  if used[i]==1:
    continue
  #今自分が居ることろをnow
  #一周のループの合計 loop_sum
  now=i
  loop=[i]
  loop_sum=0
  #連結部分を見つける
  while(1):
      loop.append(p[now])
      loop_sum+=c[p[now]]
      now=p[now]
      used[now]=1
      if p[now]==i:
          loop_sum+=c[p[now]]
          break
  #この連結なループの中で最大値を求める
  length=len(loop)
  #aから始まってk回移動
  for a in loop:
      #一周する前での最大値
      max_cost=-float("INF")
      cnt=0
      cost=0
      while cnt<length:
          cnt+=1
          a=p[a]
          cost+=c[a]
          if max_cost<cost:
            max_cost=cost
            max_num=cnt
          if cnt==k:
              ans=max(ans,max_cost)
              break
      
      if loop_sum<0:
        ans=max(ans,max_cost)
      else:
        ans=max(ans,max_cost+((k-max_num)//length)*loop_sum)
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 = [[0,0] for _ in range(N)]

for start in range(N):
    now, score, moves = start, 0, 0
    while True:
        now = P[now] - 1
        score += C[now]
        moves += 1

        if now == start: break
    
    cycle[start] = [moves, score]

ans = -10**18
for start in range(N):
    cycle_moves, cycle_score = cycle[start]
    if cycle_score < 0:
        score = 0
        moves_left = cycle_moves
    else:
        score = (K // cycle_moves) * cycle_score
        moves_left = K % cycle_moves
    
    max_score, now = score, start
    while moves_left > 0:
        now = P[now] - 1
        score += C[now]
        max_score = max(max_score,score)

        moves_left -= 1
    
    ans = max(ans,max_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()))

def sim(start,mx): # simulate mx step from start, returns max_score
    if mx==0:
        return 0
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]

    while True:
        nxt=p[nxt]-1
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==mx:
            break

    return max(p_lis)

visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0

for i in range(n):
    if i in visited_p:
        continue
    visited_p.add(i)
    now_p=0
    nxt=p[i]-1
    visited=set()
    while True:
        nxt=p[nxt]-1
        visited_p.add(nxt)
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]
    cycle_score.append(now_p)
    cycle_points.append(list(visited))

ans=-float('inf')

for c_num in range(len(cycle_score)):
#    print(c_num,cycle_score[c_num],cycle_points[c_num])
    cycle_len=len(cycle_points[c_num])
    for start in cycle_points[c_num]:

        if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
            score = sim(start,min(cycle_len+5,k))
            ans=max(ans,score)

        else: # loop as many as possible
            loop_num = k // cycle_len
            nokori=k%cycle_len

            score = sim(start,nokori) + loop_num*cycle_score[c_num]
            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()))

cycle = [[0,0] for _ in range(N)]

for start in range(N):
    now, score, moves = start, 0, 0
    while True:
        now = P[now] - 1
        score += C[now]
        moves += 1

        if now == start: break
    
    cycle[start] = [moves, score]

ans = -10**18
for start in range(N):
    cycle_moves, cycle_score = cycle[start]
    if cycle_score < 0:
        score = 0
        moves_left = N
    else:
        score = (K // cycle_moves) * cycle_score
        moves_left = K % cycle_moves
    
    max_score, now = -10**18, start
    while moves_left > 0:
        now = P[now] - 1
        score += C[now]
        max_score = max(max_score,score)

        moves_left -= 1
    
    ans = max(ans,max_score)

print(ans)

Submission status: Wrong Answer

Solution code:
def mod_max(loop, mod):
    if mod == 0:
        return 0
    loop_len = len(loop)
    mm = min(loop)
    for start in range(loop_len):
        current_sum = 0
        for i in range(mod):
            current_sum += loop[(start + i) % loop_len]
            mm = max(current_sum, mm)
    return mm


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

    seen = set()
    loop_list = []
    for start in range(n):
        v = start
        loop = []
        while v not in seen:
            seen.add(v)
            loop.append(c[v])
            v = p[v]
        seen.add(v)
        if loop:
            loop_list.append(loop)

    ans = min(min(c) * n, 0)
    for loop in loop_list:
        loop_len = len(loop)
        loop_num = k // loop_len
        loop_mod = k % loop_len
        loop_sum = sum(loop)
        ans = max(mod_max(loop, min(loop_len, k)), ans)
        if loop_num > 0:
            ans = max(loop_sum * loop_num + mod_max(loop, loop_mod), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

cycles = []
visited = [False] * (n)

for i in range(n):
    if visited[i] is False:
        start = p[i]
        visited[p[i]] = True
        dst = p[start]
        cycle = [start]
    else:
        continue

    while dst != start:
        cycle.append(dst)
        visited[dst] = True
        dst = p[dst]

    cycles.append(cycle)

ans = -float("inf")
for cycle in cycles:
    score = -float("inf")
    total = 0

    if k <= len(cycle):
        for i in range(k):
            total += c[i]
            ans = max(ans, total)
    else:
        max_score = c[i]
        for i in range(len(cycle)):
            total += c[i]
            max_score = max(max_score, total)

        if total <= 0:
            ans = max(ans, max_score)
        else:
            score = total * (k // (len(cycle)))
            rem = k % len(cycle)
            rem_total = 0
            rem_max_score = 0
            for j in range(rem):
                rem_total += c[j]
                rem_max_score = max(rem_max_score, rem_total)

            ans = max(ans, score + rem_max_score)

print(ans)

Submission status: Wrong Answer

Solution code:
def mod_max(loop, mod):
    if mod == 0:
        return 0
    loop_len = len(loop)
    mm = min(loop)
    for start in range(loop_len):
        current_sum = 0
        for i in range(mod):
            current_sum += loop[(start + i) % loop_len]
            mm = max(current_sum, mm)
    return mm


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

    seen = set()
    loop_list = []
    for start in range(n):
        v = start
        loop = []
        while v not in seen:
            seen.add(v)
            loop.append(c[v])
            v = p[v]
        seen.add(v)
        if loop:
            loop_list.append(loop)

    ans = min(min(c) * n, 0)
    for loop in loop_list:
        loop_len = len(loop)
        loop_num = k // loop_len
        loop_mod = k % loop_len
        loop_sum = sum(loop)
        ans = max(mod_max(loop, min(loop_len, k)), ans)
        if loop_num > 0:
            ans = max(loop_sum * loop_num + max(mod_max(loop, loop_mod), 0), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

cycle = [[0,0] for _ in range(N)]

for start in range(N):
    now, score, moves = start, 0, 0
    while True:
        now = P[now] - 1
        score += C[now]
        moves += 1

        if now == start: break
    
    cycle[start] = [moves, score]

ans = -10**18
for start in range(N):
    cycle_moves, cycle_score = cycle[start]
    if cycle_score < 0:
        score = 0
        moves_left = K
    else:
        score = (K // cycle_moves) * cycle_score
        moves_left = K % cycle_moves
    
    max_score, now = -10**18, start
    while moves_left > 0:
        now = P[now] - 1
        score += C[now]
        max_score = max(max_score,score)

        moves_left -= 1
    
    ans = max(ans,max_score)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = 10**18

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]
        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        if (K < len(visited)) or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
        best_score = max(best_score, a)
    return best_score

res = solve(K,P,C)
print(int(res))

Submission status: Wrong Answer

Solution code:
import sys

n,k=map(int,input().split())

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

check=[0 for i in range(n)]

if max(c)<0:
    print(max(c))
    sys.exit()

ans=0

for i in range(n):
    if check[i]==0:
        cnt=0
        check[i]=1
        li=[i]
        pc=p[i]-1
        while pc!=i:
            check[pc]=1
            li.append(pc)
            pc=p[pc]-1
        sumli=0
        for j in li:
            sumli+=c[j]
        add=0
        ki=k
        if k>len(li):
            if sumli>0:
                add=sumli*(k//len(li))
                ki=ki%len(li)
            else:
                ki=len(li)
        for w in range(1,ki+1):
            sumwmax=0
            sumw=0
            for j in range(w):
                sumw+=c[li[j]]
            for j in range(len(li)):
                sumw=sumw-c[li[j]]+c[li[(j+w)%len(li)]]
                sumwmax=max(sumw,sumwmax)
            cnt=max(cnt,sumwmax)
        ans=max(ans,cnt+add)

print(ans)

Submission status: Wrong Answer

Solution code:
def mod_max(loop, mod):
    if mod == 0:
        return 0
    loop_len = len(loop)
    mm = min(loop)
    for start in range(loop_len):
        current_sum = loop[start]
        mm = max(current_sum, mm)
        for i in range(1, mod):
            current_sum += loop[(start + i) % loop_len]
            mm = max(current_sum, mm)
    return mm


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

    seen = set()
    loop_list = []
    for start in range(n):
        v = start
        loop = []
        while v not in seen:
            seen.add(v)
            loop.append(c[v])
            v = p[v]
        seen.add(v)
        if loop:
            loop_list.append(loop)

    ans = min(min(c) * n, 0)
    for loop in loop_list:
        loop_len = len(loop)
        loop_num = k // loop_len
        loop_mod = k % loop_len
        loop_sum = sum(loop)
        ans = max(loop_sum * loop_num + max(mod_max(loop, loop_mod), 0), mod_max(loop, min(loop_len, k)), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def sim(start,mx): # simulate mx step from start, returns max_score
    if mx==0:
        return 0
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]

    while True:
        nxt=p[nxt]-1
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==mx:
            break

    return max(p_lis)

visited_p=set() # already checked flag
cycle_score=[] # cycle loop score
cycle_points=[]
now_cycle=0

for i in range(n):
    if i in visited_p:
        continue
    visited_p.add(i)
    now_p=0
    nxt=p[i]-1
    visited=set()
    while True:
        nxt=p[nxt]-1
        visited_p.add(nxt)
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]
    cycle_score.append(now_p)
    cycle_points.append(list(visited))

ans=-float('inf')

for c_num in range(len(cycle_score)):
#    print(c_num,cycle_score[c_num],cycle_points[c_num])
    cycle_len=len(cycle_points[c_num])
    for start in cycle_points[c_num]:

        if cycle_score[c_num]<0: # no loop, just check min(loop_len,k)
            score = sim(start,min(cycle_len,k))
            ans=max(ans,score)

        else: # loop as many as possible
            loop_num = k // cycle_len
            nokori=k%cycle_len

            score = sim(start,nokori) + loop_num*cycle_score[c_num]
            ans=max(ans,score)

print(ans)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit, b1, i4, i8, f8

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = 10**9
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]

        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = np.zeros(len(al))
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # print(am_cum[-1])
        # ループ前の場合
        # print('al: ',al)
        # print('am: ',am)
        if K < len(visited):
            a = al_cum.max()
        # ループ部分がマイナスの場合
        elif am_cum[-1]<=0: 
            end = min(K-len(visited)+1,len(visitedLoop))
            # print('end: ',end)
            # print(am_cum[:end+1].max())
            a = max(al_cum.max(),al_cum[-1] + am_cum[:end+1].max())
        else:
            # 残り回数を循環配列の長さで割った余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
        best_score = max(best_score, a)
    return best_score

res = solve(K,P,C)
print(int(res))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n,k = readInts()
p = [0]
p.extend(readInts())
c = [0]
c.extend(readInts())

ans = -1*float("inf")
for i in range(1,n+1):
	t = [0]
	al = []
	j = p[i]
	while j not in al:
		t.append(t[-1]+c[j])
		al.append(j)
		j = p[j]

print(ans)

Submission status: Wrong Answer

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

def calc(x):
    global n,k
    next=x
    ma=max_c
    s=0
    l=[]
    for i in range(n):
        next=p[next]
        s+=c[next]
        l.append(c[next])
        ma=max(ma,s)
        if next==x:
            break
    if s<=0:
        return ma

    cycle=k//(i+1)
    rest=k%(i+1)
    ans=(cycle-1)*s+ma
    f=s*cycle
    for j in range(rest):
        f+=l[j]
        ans=max(ans,f)
    return ans

A=max_c
for start in range(n):
    A=max(A,calc(start))
print(A)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
G = [[0, 0] for _ in range(N)]
C = list(map(int, input().split()))
P = list(map(int, input().split()))

for i in range(N):
    G[i][0] = C[i]-1
    G[i][1] = P[C[i]-1]

loops = [[] for _ in range(N)]
sums = [0 for _ in range(N)]
for i in range(N):
    v = i
    while True:
        loops[i].append(v)
        sums[i] += G[v][1]
        v = G[v][0]
        if v == i:
            break

ans = [0 for _ in range(N)]
for i, loop in enumerate(loops):
    size = len(loop)
    a = K // size
    r = K % size
    if sums[i] > 0:
        ans[i] = a * sums[i]

    tmp = G[loop[0]][1]
    if r > 0:
        j = 1
        while j < r:
            if G[loop[j]][1] >= 0:
                tmp += G[loop[j]][1]
                j += 1
            else:
                break

    ans[i] += tmp

print(max(ans))

Submission status: Wrong Answer

Solution code:
import sys

n,k=map(int,input().split())

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

check=[0 for i in range(n)]

if max(c)<0:
    print(max(c))
    sys.exit()

ans=0

for i in range(n):
    if check[i]==0:
        cnt=0
        check[i]=1
        li=[i]
        pc=p[i]-1
        while pc!=i:
            check[pc]=1
            li.append(pc)
            pc=p[pc]-1
        sumli=0
        for j in li:
            sumli+=c[j]
        add=0
        ki=k
        if sumli>0:
            add=sumli*(k//len(li))
        if ki>len(li):
            ki=ki%len(li)
        for w in range(1,ki+1):
            sumwmax=0
            sumw=0
            for j in range(w):
                sumw+=c[li[j]]
            for j in range(len(li)):
                sumw=sumw-c[li[j]]+c[li[(j+w)%len(li)]]
                sumwmax=max(sumw,sumwmax)
            cnt=max(cnt,sumwmax)
        ans=max(ans,cnt+add)

print(ans)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit, b1, i4, i8, f8

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = 10**9
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]

        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = np.zeros(len(al))
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # print(am_cum[-1])
        # ループ前の場合
        if K < len(visited):
            a = al_cum.max()
        # ループ部分がマイナスの場合
        elif am_cum[-1]<=0: 
            end = max(K-len(visited)+1,len(visitedLoop))
            a = al_cum[-1] + am_cum[:end].max()
        else:
            # 残り回数を循環配列の長さで割った余り
            q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
            a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
        best_score = max(best_score, a)
    return best_score

res = solve(K,P,C)
print(int(res))

Submission status: Wrong Answer

Solution code:
import sys

n,k=map(int,input().split())

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

check=[0 for i in range(n)]

if max(c)<0:
    print(max(c))
    sys.exit()

ans=0

for i in range(n):
    if check[i]==0:
        cnt=0
        check[i]=1
        li=[i]
        pc=p[i]-1
        while pc!=i:
            check[pc]=1
            li.append(pc)
            pc=p[pc]-1
        sumli=0
        for j in li:
            sumli+=c[j]
        add=0
        ki=k
        if sumli>0:
            add=sumli*(k//len(li))
        if ki>len(li):
            ki=ki%len(li)
        for w in range(1,ki+1):
            sumwmax=0
            sumw=0
            for j in range(w):
                sumw+=c[li[j]]
            for j in range(len(li)):
                sumw=sumw-c[li[j]]+c[li[(j+w)%len(li)]]
                sumwmax=max(sumw,sumwmax)
            cnt=max(cnt,sumwmax)
    ans=max(ans,cnt+add)

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

used=[0 for i in range(n+1)]
#1からn+1までの辺で試す
ans=-float("INF")
for i in range(1,n+1):
  #すでに探索したループは見なくて良い
  if used[i]==1:
    continue
  #今自分が居ることろをnow
  #一周のループの合計 loop_sum
  now=i
  loop=[i]
  loop_sum=0
  #連結部分を見つける
  while(1):
      loop.append(p[now])
      loop_sum+=c[p[now]]
      now=p[now]
      used[now]=1
      if p[now]==i:
          loop_sum+=c[p[now]]
          break
  #この連結なループの中で最大値を求める
  length=len(loop)
  #aから始まってk回移動
  for a in loop:
      #一周する前での最大値
      max_cost=-float("INF")
      cnt=0
      cost=0
      while cnt<length:
          cnt+=1
          a=p[a]
          cost+=c[a]
          if max_cost<cost:
            max_cost=cost
            max_num=cnt
          if cnt==k:
              ans=max(ans,max_cost)
              break
      
      if loop_sum<=0:
        ans=max(ans,max_cost)
      else:
        ans=max(ans,max_cost+((k-max_num)//length)*loop_sum)
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
def mod_max(loop, mod):
    if mod == 0:
        return 0
    loop_len = len(loop)
    mm = min(loop)
    for start in range(loop_len):
        current_sum = loop[start]
        mm = max(current_sum, mm)
        for i in range(1, mod):
            current_sum += loop[(start + i) % loop_len]
            mm = max(current_sum, mm)
    return mm


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

    seen = set()
    loop_list = []
    for start in range(n):
        v = start
        loop = []
        while v not in seen:
            seen.add(v)
            loop.append(c[v])
            v = p[v]
        seen.add(v)
        if loop:
            loop_list.append(loop)

    ans = min(min(c) * n, 0)
    for loop in loop_list:
        loop_len = len(loop)
        loop_num = k // loop_len
        loop_mod = k % loop_len
        loop_sum = sum(loop)
        if loop_sum > 0:
            ans = max(loop_sum * loop_num + max(mod_max(loop, loop_mod), 0), ans)
        else:
            ans = max(mod_max(loop, max(loop_len, k)), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

n,k=map(int,input().split())

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

check=[0 for i in range(n)]

if max(c)<0:
    print(max(c))
    sys.exit()

ans=0

for i in range(n):
    if check[i]==0:
        cnt=0
        check[i]=1
        li=[i]
        pc=p[i]-1
        while pc!=i:
            check[pc]=1
            li.append(pc)
            pc=p[pc]-1
        sumli=0
        for j in li:
            sumli+=c[j]
        add=0
        ki=k
        if sumli>0:
            add=sumli*(k//len(li))
        ki=ki%len(li)
        for w in range(1,ki+1):
            sumwmax=0
            sumw=0
            for j in range(w):
                sumw+=c[li[j]]
            for j in range(len(li)):
                sumw=sumw-c[li[j]]+c[li[(j+w)%len(li)]]
                sumwmax=max(sumw,sumwmax)
            cnt=max(cnt,sumwmax)
    ans=max(ans,cnt+add)

print(ans)