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
from io import StringIO
import unittest

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    n,k=map(int, readline().rstrip().split())
    pp=list(map(int, readline().rstrip().split()))
    cc=list(map(int, readline().rstrip().split()))
    #n=int(readline())
    #ss=readline().rstrip()
    #yn(1)
    mp=[1]*n
    i=0
    ansTTT = -100000000000
    while 1:
        ans = -100000000000
        if i ==n:
            break
        if mp[i] == 0:
            i+=1
            continue
        st = []
        sss=0
        while 1:
            old=i
            i=pp[i]-1
            if mp[i]==0:
                break
            else:
                mp[i]=0
                st.append(cc[i])
                sss+=cc[i]
        lst = len(st)
        st.extend(st)

        for j in range(1,lst*2):
            st[j]+=st[j-1]
        to = lst
        adddd = 0
        if k < lst:
            to = k
        elif sss>0:
            adddd=sss*(k//lst)
            ans = 0 #
        for x in range(0,to):
            for z in range(0,to):
                if x==0:
                    ans = max(ans,st[x+z])
                else:
                    ans = max(ans,st[x+z]-st[x-1])
        if ans > sss:
            ans += sss
        ans += adddd

        ansTTT=max(ansTTT,ans)
    print(ansTTT)
    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * n

  def find(self, x):
    if self.parents[x] < 0:
      return x
    else:
      self.parents[x] = self.find(self.parents[x])
      return self.parents[x]

  def union(self, x, y):
    x = self.find(x)
    y = self.find(y)
    if x == y:
      return
    if self.parents[x] > self.parents[y]:
      x, y = y, x
    self.parents[x] += self.parents[y]
    self.parents[y] = x

  def size(self, x):
    return -self.parents[self.find(x)]

  def same(self, x, y):
    return self.find(x) == self.find(y)

  def members(self, x):
    root = self.find(x)
    return [i for i in range(self.n) if self.find(i) == root]

  def roots(self):
    return [i for i, x in enumerate(self.parents) if x < 0]

  def group_count(self):
    return len(self.roots())

  def all_group_members(self):
    ret = defaultdict(list)
    for i in range(self.n):
      ret[self.find(i)].append(i)
    return ret

  def __str__(self):
    return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N, K = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))

uf = UnionFind(N)

for i in range(N):
  uf.union(i, P[i])

D = uf.all_group_members()
E = defaultdict(list)
F = defaultdict(int)

Num = [0]*N

for root in uf.roots():
  i = root
  n = 0
  E[root].append(0)
  while P[i] != root:
    i = P[i]
    n += 1
    Num[i] = n
    E[root].append(E[root][-1] + C[i])
  E[root].append(E[root][-1] + C[root])
  F[root] = n + 1
  #追加分
  i = root
  while P[i] != root:
    i = P[i]
    E[root].append(E[root][-1] + C[i])
  E[root].append(E[root][-1] + C[root])

#print(Num, E, F)
ans = -float("inf")

for root, L in E.items():
  loop, k = divmod(K, F[root])
  if k == 0:
    loop -= 1
    k += F[root]
  temp = 0
  if L[-1] >= 0:
    temp += (L[-1]//2) * loop
  for i in range(F[root]):
    for j in range(i+1, i+k):
      ans = max(ans, temp + E[root][j] - E[root][i])

print(ans)

Submission status: Wrong Answer

Solution code:
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd

def maxSumSubSizek(arr, k): 
    n = len(arr)
    res = 0
    for i in range(k): 
        res += arr[i] 

    curr_sum = res 
    for i in range(k, n): 
        curr_sum += arr[i] - arr[i-k] 
        res = max(res, curr_sum) 
    return res 

def main():
    n,k = map(int, input().split())
    perm = [0] + list(map(int, input().split()))
    sqscore = [0] + list(map(int, input().split()))


    ans = -10**10
    visited = [False]*(n + 1)
    for i in range(1, n + 1):
        if not visited[i]:
            cycleScores = []
            j = i
            cycsum = 0
            maxsum = -10**10
            while not visited[j]:
                visited[j] = True
                score = sqscore[j]
                cycsum += score
                maxsum = max(maxsum, score)
                cycleScores.append(sqscore[j])
                j = perm[j]
            
            if maxsum <= 0:
                # All numbers are negative/0; take one step.
                ans = max(ans, maxsum)
            else:
                # positive numbers exist in cycle
                if k > len(cycleScores):
                    if cycsum <= 0:
                        temp = cycleScores + cycleScores
                        msf = cycleScores[0]
                        for i in cycleScores[1:]:
                            msf = max(msf + i, i)
                            ans = max(ans, msf)
                    else:
                        # finish k/len(cycScores) cycles. Whatever is left, find subarray with max sum of that length
                        mult = k // len(cycleScores)

                        tempans = mult * cycsum
                        k -= mult * len(cycleScores)
                        
                        # find subarray of size k with in cycleScore with max Sum.
                        temp = cycleScores + cycleScores
                        for step in range(1, k + 1):
                            ans = max(ans, tempans + maxSumSubSizek(temp, step))
                else:
                    temp = cycleScores + cycleScores
                    for step in range(1, k + 1):
                        ans = max(ans, maxSumSubSizek(temp, step))
    print(ans)


        




































# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
 
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
nk = [int(s) for s in input().split()]
n = nk[0]
k = nk[1]

P = [int(s) for s in input().split()]
C = [int(s) for s in input().split()]

loop = {}
score = {}

for num in range(n):
  if num+1 not in loop:
    l = []
    s = []
    numloop = -1
    
    while numloop-1 != num:
      if numloop == -1:
        numloop = P[num]
      else:
        numloop = P[numloop-1]
      l.append(numloop)
      scoreloop = C[numloop-1]
      s.append(scoreloop)
      
    loop[num+1] = l
    score[num+1] = s
    
    for nums in range(len(l)-1):
      loop[l[nums+1]] = l[nums:] + l[:nums]
      score[l[nums+1]] = s[nums:] + s[:nums]

value = []

for cand in loop:
  if len(loop[cand]) < k:
    value.append(max([sum(score[cand][:ind+1])
                     for ind in list(range(len(loop[cand])))]))
  elif sum(score[cand]) <= 0:
    value.append(max([sum(score[cand][:ind+1])
                     for ind in list(range(len(loop[cand])))]))
  else:
    value.append(sum(score[cand]) * (k//len(loop[cand])) +
                 max([sum(score[cand][:ind+1])
                     for ind in list(range(len(loop[cand])))]))
print(max(value))

Submission status: Wrong Answer

Solution code:
n, k = list(map(int, input().split()))
p = [int(i) - 1 for i in input().split()]
c = [int(i) for i in input().split()]
import copy
p_list = [[0 for _ in range(n)] for _ in range(n)]
position = [[-1 for _ in range(n)] for _ in range(n)]
t = (k % n) - 1
tmp = copy.deepcopy(c)
shuki = [-1 for _ in range(n)]
for i in range(n):
    p_list[0][i] += c[p[i]]
    position[0][i] = p[i]
for i in range(1, n):
    for j in range(n):
        p_list[i][j] = p_list[i - 1][j] + c[p[position[i - 1][j]]]
        position[i][j] = p[position[i - 1][j]]
        if (i <= t) & (shuki[j]== -1):
            tmp[j] = max(tmp[j], p_list[i][j])
        if position[i][j] == position[0][j]:
            shuki[j] = i 
ans = max(c)
for i in range(n):
    if shuki[i] <= k:
        v = p_list[shuki[i]][i] * (k // shuki[i])
        if v > 0:
            if k % n > 0:
                v += tmp[i]
        else:
            v = tmp[i]
        ans = max(v, ans)
    else:
        ans = max(max(p_list))
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()))
L = [0]*N
Max = -10**9
for i in range(N):
    if L[i] != 0:
        continue
    else:
        c = 0
        L[i] = 1
        c += C[i]
        a = P[i] - 1
        Cs = [c]
        Ds = [c]
        l = 1
        while a != i:
            c += C[a]
            Ds.append(C[a])
            a = P[a]-1
            L[a] = 1
            l += 1
            Cs.append(c)
        if c > 0:
            m = -10**9
            k = K % l
            for i in range(1,k+1):
                for j in range(l):
                    if j + i > l:
                        M = Cs[l-1] - Cs[j]+Ds[j] + Cs[i+j-l-1]
                    else:
                        M = Cs[j+i-1]-Cs[j]+Ds[j]
                    if M > m:
                        m = M
            x = K // l
            max0 = c*x+m
        else:
            if K >= l:
                A = [0]*l
                A[0] = Ds[0]
                for i in range(1,l):
                    A[i] = min([A[i-1]+Ds[i],Ds[i]])
                max0 = c - A[l-1]
                if max0 == 0:
                    max0 = max(Ds)
            else:
                m = -10**10
                k = K
                for i in range(1,k+1):
                    for j in range(l):
                        if j + i > l:
                            M = Cs[l-1] - Cs[j]+Ds[j] + Cs[i+j-l-1]
                        else:
                            M = Cs[j+i-1]-Cs[j]+Ds[j]
                        if M > m:
                            m = M
                max0 = m
    if Max < max0:
        Max = max0
print(Max)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**6)
N,K=map(int, sys.stdin.readline().split())
P=[None]+map(int, sys.stdin.readline().split())
C=[None]+map(int, sys.stdin.readline().split())

#最大スコアを返す
def dfs(par,cur):
    if par!=-1:
        global score
        global score_total
        score+=C[cur]
        score_total+=score
        global move_cnt
        move_cnt+=1
        SCORE.append(score)
    if move_cnt==K:
        return max(SCORE)
    if visit[cur]==1:
        return max(SCORE)
    visit[cur]=1
    to=P[cur]
    return dfs(cur,to)

ans=float("-inf")

for i in range(1,N+1):
    visit=[ 0 for _ in range(N+1) ]
    score=0
    move_cnt=0
    score_total=0
    SCORE=[0]
    ans=max(ans,dfs(-1,i))

print ans

Submission status: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()


show_flg=False
show_flg=True

ans=0

n,k=LI()
p=LI_()
c=LI()

rp=[-1]*n
pp=[-1]*n
def roop(y):
    pt=0
    if rp[y]!=-1:
        return rp[y],pp[y]
    x=y
    for i in range(n):
        x=p[x]
        pt+=c[i]
        if x==y:
            r=i+1
            break
    rp[y]=r
    
    x=y
    for i in range(r+1):
        rp[x]=r
        pp[x]=pt
        x=p[x]
        
    return r,pt

def tr(x,t):
    pt=0
    rt=-inf
    for i in range(t):
        x=p[x]
        pt+=c[x]
        rt=max(rt,pt)
    return rt



ans=-inf
for i in range(n):
    r,ppx=roop(i)
    if k<=n:
        tmp=tr(i,k)
    else:
        tmp0=tr(i,2*n)
        tmp1=(k//r)*ppx+tr(i,k%r)
        tmp2=max(0,(k//r)-1)*ppx+tr(i,n)
        tmp=max(tmp0,tmp1,tmp2)
    ans=max(tmp,ans)
    #show(i,(r,pp),tr(i,n),(k//r),tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
# import sys
# readline = sys.stdin.readline
# generator = (readline().strip() for _ in range(N))

# N, M = map(int, input().split())
# As = list(map(int, input().split()))
# queries = (input() for _ in range(N))


class Tree:
    def __init__(self):
        self.idxs = []
        self.nexts = []
        self.scores = []
        self.used = set()

    def add_node(self, idx, next, score):
        self.idxs.append(idx)
        self.nexts.append(next)
        self.scores.append(score)
        self.used.add(next)

    def isin(self, idx):
        return idx in self.used

    def size(self):
        return len(self.idxs)

    def max_score(self, k):
        size = self.size()
        sumscore = sum(self.scores)
        if sumscore > 0:
            if size > k:
                cycle, remains = divmod(k, size)
                return cycle*sumscore + self.max_dist(remains)
        return self.max_dist(size)

    def max_dist(self, n):
        size = self.size()
        scores = self.scores*2
        max_score = -10**10
        for f in range(size):
            for t in range(f+1, f+n):
                score = sum(scores[f:t])
                max_score = max(max_score, score)
        return max_score


def solve():
    N, K = map(int, input().split())
    Ps = map(int, input().split())
    Cs = list(map(int, input().split()))

    trees = []
    tree = Tree()
    idx = 0

    for _ in range(N):
        p = next(Ps) - 1
        if tree.isin(p):
            trees.append(tree)
            tree = Tree()
        tree.add_node(idx, p, Cs[p])
        idx = p
    trees.append(tree)

    all_max = -10**10
    for tree in trees:
        score = tree.max_score(K)
        all_max = max(all_max, score)

    return all_max


def main():
    print(solve())


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

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  masu[now_mas]=1
  #このwhileはせいぜい5000
  while True:
    if count!=0 and masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    
    if ans22<ans:
      ans22=ans
      
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=(k//count)*ans
    
    if ans22<ans:
      ans22=ans
      
    for i in range(k-(k//count)*count):
      ans+=c[now_mas-1]
      
      if ans22<ans:
        ans22=ans
        
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  
  else:
    return max(ans,ans22)
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ < hantei:
    answ=hantei
print(answ)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
s=sum(C)
ans=[]
if k>n:
  if s>0:
    t=k//n
    for i in range(n):
      x=i
      for j in range(n):
        ans.append(C[x]+s*t)
        x=P[x]-1
    print(max(ans))
  else:
    k=n
if k<=n:
  for i in range(n):
    x=i
    for j in range(k):
      ans.append(C[x])
      x=P[x]-1
  print(max(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 ** 10
for i in range(1, n+1):
    base = i
    nxt = p[i]
    cnt = 0
    score = 0
    while True:
        cnt += 1
        if cnt > k:
            break
        score += c[nxt]
        ans = max(ans, score)
        #print("i = ", i, "ans = ", ans, "score = ", score)
        if nxt == base:
            break
        nxt = p[nxt]
    if cnt > k:
        continue
    if k - cnt <= cnt:
        score_tmp = score
        nxt = p[i]
        for j in range(k - cnt):
            score_tmp += c[nxt]
            ans = max(ans, score_tmp)
            #print("ans = ", ans, "score_tmp = ", score_tmp, "nxt = ", nxt, "c[nxt] = ", c[nxt])
            nxt = p[nxt]
    else:
        a = (k - cnt) // cnt
        score_tmp = score + score * a
        ans = max(ans, score_tmp)
        nxt = p[i]
        for j in range((k - cnt) - a * cnt):
            score_tmp += c[nxt]
            ans = max(ans, score_tmp)
            nxt = p[nxt]


#print("score:", score)

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N,K = map(int,input().split())
    P = list(map(int,input().split()))
    C = list(map(int,input().split()))
    
    if K > N:
        Z = N
    else:
        Z = K
        
    C_LOOP = []
    C_LOOPMAX = []
    C_LOOPSUM = []
    for n in range(N):
        p = P[n]-1
        c_max = C[n]
        c_sum = 0
        flag = False
        for i in range(Z):
            c_sum += C[p]
            if c_sum > c_max:
                c_max = c_sum
            p = P[p]-1
            if p == n:
                flag = True
            elif flag:
                break
                
        C_LOOP.append(i+2)
        C_LOOPMAX.append(c_max)
        C_LOOPSUM.append(c_sum)
            
    if K > N:
        C_LOOPLOOP = []
        for n in range(N):
            X = K//C_LOOP[n]
            C_LOOPLOOP.append(C_LOOPSUM[n]*X+C_LOOPMAX[n])
            
        print(max(max(C_LOOPMAX),max(C_LOOPLOOP)))
    else:
        print(max(C_LOOPMAX))
        
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

done = [0]*n

def cycle(st):
    global done
    visited = [0]*n
    visited[st] = 1
    idx = P[st]
    cyc = 0
    sco = [0]
    for _ in range(n):
        done[idx] += 1
        visited[idx] += 1
        cyc += 1
        sco.append(sco[-1] + C[idx])
        if visited[idx] > 1: break
        else: idx = P[idx]
    return cyc, sco

ans = -10**18

for i in range(n):
    if done[i] > 0: continue

    cyc, sco = cycle(i)

    if sco[-1] > 0:
        # 繰り返したほうが得
        d, m = divmod(k, cyc)
        #v = d * sco[-1] + max(sco[:m+1])
        v = d * sco[-1] + (max(sco) - min(sco))
    else:
        # 早期打ち切り
        v = max(sco) - min(sco)

    ans = max(ans, v)
    #print(i, cyc, sco, v)

print(ans)

Submission status: Wrong Answer

Solution code:
## coding: UTF-8
## coding: UTF-8

#ループ構造を見つけたらやめるところまで実装
#freshを用意して、Falseになったらやめる実装

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



#log = [1] #訪れた地点を記録するもの
#last  = 1 #最後に訪れた地点を記録するもの（ここから次に行くところを検索する）
fresh = [False] + [True] * N #まだついたことのない場所をTrueにしている
#fresh[1] = False
#turn = ['a'] + [0] * N #なん回目におとづれたか記録する
#status = True



def search_loop(start):
    log = [start] #訪れた地点を記録するもの
    last  = start #最後に訪れた地点を記録するもの（ここから次に行くところを検索する）
    score = [C[start-1]]
    counter = 0
    while True:
        next_spot = P[last - 1]
        counter += 1
        #print(next_spot)
        if(fresh[next_spot]):
            #処理を書く
            log.append(next_spot)
            score.append(C[next_spot-1])
            last = next_spot
            fresh[next_spot] = False
            #turn[next_spot] = counter
        else:
            #log.append(next_spot)
            last = next_spot
            fresh[next_spot] = False
            #最後の人処理をする
            break
    del log[-1]
    del score[-1]
    #print('hit')
    return log, counter-1, sum(score), score
    #last, counter#turn, counter

status = True
list_loop = []
list_elements = []
list_sum = []
list_score = []

while status:
    for i in range(N+1):
        if(fresh[i]):
            #print(search_loop(i))
            a = search_loop(i)
            list_loop.append(a[0])
            list_elements.append(a[1])
            list_sum.append(a[2])
            list_score.append(a[3])
            break
        if(i == N):
            status = False
        
#print(list_loop, list_elements, list_sum, list_score)

#print(search_loop(1))




#A = [13,−3,−25,20,−3,−16,−23,18,20,−7,12,−5,−22,15,−4,7]
#A = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22,15, -4, 7]

def maximum_subarray_kadane(array):
    best_sum = float('-inf')
    best_start = best_end = -1
    current_sum = 0
    for current_end, num in enumerate(array):
        if current_sum <= 0:
            current_start = current_end
            current_sum = num
        else:
            current_sum += num
        if current_sum > best_sum:
            best_sum = current_sum
            best_start = current_start
            best_end = current_end
    
    return best_sum, (best_start, best_end)
'''
array = [2, 3, -1, -20, 5, 10]
# (15, (4, 5))
print(maximum_subarray_kadane(array))
print(maximum_subarray_kadane(A))
'''


candi = []
def max_search_in_loop(l, e, s, sco):
    if(s > 0):
        if(K > 2*e):
            limit = (K // e) - 1 #周は絶対回る
            tmp = []
            for i in range(e):
                #stopat = i
                now = 0
                tmpmax = -2*10**9
                for j in range(K - limit):
                    now += sco[(i+j)%e]
                    tmpmax = max(tmpmax, now)
                tmp.append(tmpmax)
            candi.append(max(tmp) + s * limit)
        else:
            tmp = []
            for i in range(e):
                now = 0
                tmpmax = -2*10**9
                for j in range(K):
                    now += sco[(i+j)%e]
                    tmpmax = max(tmpmax, now)
                tmp.append(tmpmax)
            #print('chech', tmp)
            candi.append(max(tmp))
    else:
        tmp = []
        for i in range(e):
            now = 0
            tmpmax = -2*10**9
            for j in range(e*2):
                now += sco[(i+j)%e]
                tmpmax = max(tmpmax, now)
            tmp.append(tmpmax)
            #print('cahech', tmp)
        candi.append(max(tmp))        

for i in range(len(list_elements)):
    max_search_in_loop(list_loop[i], list_elements[i], list_sum[i], list_score[i])
print(max(candi))

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 = 0
for i in range(n):
    hoge = 0
    np = p[i]
    for j in range(k):
        # print(i,j,c[p[i]-1], ans)
        hoge += c[np-1]
        np = p[np-1]
        if hoge > ans:
            ans = hoge
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()))

L = [[] for i in range(n+1)]
length = [0]*(n+1)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if L[i] != []:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = - float("Inf")

if k > n:

    for i in range(1,n+1):
        m = k//length[i]
        p = k%length[i]
        if p == 0:
             point = m * L[i][length[i]-1]
        else:
            point = m * L[i][length[i]-1] + max(L[i][:p])

        ans = max(ans, point)
    
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:n-1]), ans)
        
else:
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
print(ans)

Submission status: Wrong Answer

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

res = 0

if max(C) <= 0:
  res = max(C)
else:

  for i in range(N):
    tempRes = 0
    startIndex = i
    countIndex = i

    for j in range(K):
      countIndex = P[countIndex] - 1
      tempRes += C[countIndex]
      if countIndex == startIndex:
        aoc = tempRes
        break
      res = max(res, tempRes)
    
    if N < K and 0 < aoc:
      for s in range(N):
        tempRes = ((K-1) // N) * aoc
        startIndex = s
        countIndex = s

        for t in range(K):
          tempRes += C[countIndex]
          countIndex = P[countIndex] - 1
          if countIndex == startIndex:
            break
          res = max(res, tempRes)


print(res)