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:
def examA():
    S = SI()
    ans = 0
    if "R" in S:
        ans = 1
    if "RR" in S:
        ans = 2
    if "RRR" in S:
        ans = 3
    print(ans)
    return

def examB():
    N = I()
    L = LI()
    L.sort()
    cnt = 0
    for i in range(N):
        for j in range(i+1,N):
            for k in range(j+1,N):
                if L[i]==L[j]:
                    continue
                if L[j]==L[k]:
                    continue
                if L[i]+L[j]>L[k]:
                    cnt += 1
    ans = cnt
    print(ans)
    return

def examC():
    X, K, D = LI()
    if X<0:
        X = -X
    ans = inf
    if X>K*D:
        ans = X-K*D
        print(ans)
        return

    K -= X//D
    X -= D * (X//D)

    ans = X
    if K>0:
        if K%2==1:
            ans = abs(X-D)
    print(ans)
    return

def examD():
    N, K = LI()
    P = LI()
    C = LI()

    B = [i for i in range(N)]
    for i,p in enumerate(P):
        p -= 1
        B[i] = p

    locat_doubling = [[0]*N for _ in range(31)]
    score_doubling = [[0]*N for _ in range(31)]

    for i in range(N):
        locat_doubling[0][i] = i
        locat_doubling[1][B[i]] = i
        score_doubling[0][i] = 0
        score_doubling[1][B[i]] = C[i]
    for k in range(2,31):
        for i in range(N):
            locat_doubling[k][i] = locat_doubling[k-1][locat_doubling[k-1][i]]
            score_doubling[k][i] = score_doubling[k-1][i] + score_doubling[k - 1][locat_doubling[k - 1][i]]

    score = [[0,-inf] for i in range(N)]
    locate = [[i,i] for i in range(N)]
    ans = max(C)

    if ans<0:
        print(ans)
        return

    for k in range(30)[::-1]:
        for i in range(N):
            if score[i][1]<0:
                continue
            #print(score[i],locate[i])
            if score_doubling[k + 1][locate[i][1]]>0:
                score[i][1] += score_doubling[k + 1][locate[i][1]]
                locate[i][1] = locat_doubling[k+1][locate[i][1]]

        if K&(1<<k)>0:
            for i in range(N):
                if score[i][1] < score[i][0]:
                    score[i][1] = score[i][0]
                    locate[i][1] = locate[i][0]
                score[i][0] += score_doubling[k+1][locate[i][0]]
                locate[i][0] = locat_doubling[k+1][locate[i][0]]
    for s in score:
        ans = max(ans,s[0],s[1])
    print(ans)
    return

def examE():
    R, C, K = LI()
    V = [[-inf]*C for _ in range(R)]
    for _ in range(K):
        r,c,v = LI()
        V[r-1][c-1] = v
    dp0 = [[0]*(C+1) for _ in range(R+1)]
    dp1 = [[0]*(C+1) for _ in range(R+1)]
    dp2 = [[0]*(C+1) for _ in range(R+1)]
    dp3 = [[0]*(C+1) for _ in range(R+1)]

    for r in range(R):
        for c in range(C):
            v = V[r][c]
            if 0<v:
                dp0[r+1][c+1] = max(dp0[r+1][c],dp0[r][c+1],dp1[r][c+1],dp2[r][c+1],dp3[r][c+1])
                dp1[r+1][c+1] = max(dp1[r+1][c],dp0[r+1][c]+v,dp0[r][c+1]+v,dp1[r][c+1]+v,dp2[r][c+1]+v,dp3[r][c+1]+v)
                dp2[r+1][c+1] = max(dp2[r+1][c],dp1[r+1][c]+v)
                dp3[r+1][c+1] = max(dp3[r+1][c],dp2[r+1][c]+v)
            else:
                dp0[r+1][c+1] = max(dp0[r+1][c],dp0[r][c+1],dp1[r][c+1],dp2[r][c+1],dp3[r][c+1])
                dp1[r+1][c+1] = dp1[r+1][c]
                dp2[r+1][c+1] = dp2[r+1][c]
                dp3[r+1][c+1] = dp3[r+1][c]

    ans = max(dp0[R][C],dp1[R][C],dp2[R][C],dp3[R][C])
    print(ans)
    return

def examF():

    ans = 0
    print(ans)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examD()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

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

l = [0] * n
m = -float('inf')
ind = 0

for i in range(n):
    if l[i] == 0:
        dots = 1
        l[i] = i+1
        now = i
        weight = c[i]
        while True:
            now = p[now] - 1
            if l[now]:
                break
            weight += c[now]
            dots += 1
            l[now] = i+1
        if m < weight / dots:
            ind = i
            m = weight / dots
            d = dots

q, r = divmod(k, d)
if m < 0: q = 0

mm = -float('inf')
if q == 0:
    for i in range(n):
        now = i
        weight = 0
        for _ in range(r):
            now = p[now] - 1
            weight += c[now]
            if mm < weight:
                ind = i
                mm = weight

else:
    for i in range(n):
        if l[i] == ind + 1:
            now = i
            weight = 0
            for _ in range(r):
                now = p[now] - 1
                weight += c[now]
                if mm < weight:
                    inde = i
                    mm = weight

if mm < 0: mm = max(max(c), mm)
print(q * m * d + mm)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
*P,=map(int,input().split())
*C,=map(int,input().split())
S=sum(C)
if S>0:
    ans=0
    ans+=(K//N)*S
    K=K%N
    i=1
    ans2=max(C)
    while i<=K:
        for k in range(N):
            now=k+1
            count=0
            for j in range(i):
                now=P[now-1]
                count+=C[now-1]
            ans2=max(ans,count)
        i+=1
    print(ans+ans2)

else:
    i=1
    ans=max(C)
    while i<=K:
        for k in range(N):
            now=P[k]
            count=0
            for j in range(i):
                count+=C[now-1]
                now=P[now-1]
            ans=max(ans,count)
        i+=1
    print(ans)

Submission status: Wrong Answer

Solution code:
import random
n=5000
k=random.randrange(10**9)
p=[i for i in range(n)]
c=[random.randrange(10**9+1) for i in range(n)]
print(n,k)

#到達したかの判定
#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
  #このwhileはせいぜい5000
  while True:
    if 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
    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)
hantei=0
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()))
max_value = -(10**10)
for first_m in range(1, N+1):
  now_m = first_m
  C_got = []
  for i in range(N):
    now_m = P[now_m-1]
    C_got.append(C[now_m-1])
    if now_m == first_m:
      break
  sum_C_got = sum(C_got)
  max_spc_got = -(10 ** 9)
  for j in range(1, (i+1 if K%(i+1)==0 else K%(i+1))+1):
    if sum(C_got[:j]) > max_spc_got:
      max_spc_got = sum(C_got[:j])
  max_thiscase = max(0, (K // (i+1))*sum_C_got) + max_spc_got
  if max_thiscase > max_value:
    max_value = max_thiscase
print(max_value)

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 = -1000000000
for i in range(N):
  cost = 0
  S = []
  x = P[i] - 1
  l = 1
  while 1:
    cost += C[x]
    S.append(cost)
    if x == i:
      break
    l += 1
    x = P[x] - 1
  if cost > 0:
    if K % l != 0:
      ans = max(ans, cost * (K // l) + max(S[:K % l]), cost * ((K // l) - 1) + max(S))
    else:
      ans = max(ans, cost * (K // l))
  else:
    ans = max(ans, max(S[:min(K, l)]))
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N,K = map(int,input().split())
    P_list = tuple(map(int,input().split()))
    C_list = tuple(map(int,input().split()))

    max_sum=-10**9
    for i in range(N):
        m_sum=0
        k=i
        for j in range(K):
            m_sum += C_list[k]
            if C_list[k] >= 0 and m_sum > max_sum:
                max_sum=m_sum
            k=P_list[k]-1
    print(max_sum)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#import sys
MOD = 10 ** 9 + 7
INFI = 10**10
#input = sys.stdin.readline
import math
from collections import deque
import itertools
import heapq
#import bisect
from fractions import Fraction
import copy
from functools import lru_cache
from collections import defaultdict
import pprint

#oo=list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
# ko=list("abcdefghijklmnopqrstuvwxyz")

def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

#    h,w,a,b = map(int, input().split())
#    c = [[0 for j in range(n)] for i in range(n)]

def ret(a):
    c=[None]*(len(a)-1)
    if len(a)==1:
        return a[0]
    elif len(a)==0:
        return 0
    for i in range(1,len(a)):
        c[i-1]=abs(a[i]-a[i-1])
    return ret(c)

def soinsubunkai(n):
    a = []
    i = 1
    while i*i <= n:
        if n % i == 0 and i!=1:
            a.append(i)
            n=n//i

        if n% i !=0 or i==1:
            i += 1
    nokori=[n]
    return a + nokori

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

def main():
    #l,r,d=map(int,input().split())
    n,k = map(int, input().split())
    p=list(map(int,input().split()))
    c = list(map(int, input().split()))
    loop=min(n,k)
    score=-INFI
    arr=set()
    loopscore=[]
    tempscore=0
    for i in range(n):
        temp=i
        arr = set()
        loopscore = []
        temp2=0
        iscore=0
        tempscore=0
        for j in range(loop):
            if p[temp]-1 in arr:
                break
            tempscore+=c[p[temp]-1]
            arr.add(p[temp]-1)
            temp=p[temp]-1
            loopscore.append(tempscore)

        if len(loopscore)<k:
            if loopscore[-1]>0:
                temp2=k//len(loopscore)-1
                if temp2<=0:
                    temp2=0
            iscore=temp2*loopscore[-1]
            last=loopscore[-1]
            temploop=list(map(lambda x: x+last,loopscore))
            loopscore.extend(temploop)
            nokori=k-temp2
            nokoriscore=max(loopscore[:nokori])
            iscore+=nokoriscore
        else:
            iscore=max(loopscore[:k])
        score=max(score,iscore)

    print(score)




if __name__ == "__main__":

    main()

Submission status: Wrong Answer

Solution code:
import math

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

# cycles = [None]*N
cycle_scores = [None]*N
cycle_lengths = [None]*N

for x in range(N):
    if cycle_scores[x] is not None: continue

    cycle = []
    i = x
    score = 0
    while True:
        i = P[i]
        score += C[i]
        cycle.append(i)
        if i == x: break

    for i in cycle:
        # cycles[i] = cycle
        cycle_scores[i] = score
        cycle_lengths[i] = len(cycle)

best = -math.inf
for x in range(N):
    fuel = K
    i = x
    partial = 0
    for w in range(cycle_lengths[x]):
        i = P[i]
        fuel -= 1
        partial += C[i]
        if cycle_scores[i] > 0 and fuel >= cycle_lengths[i]:
            score = partial + cycle_scores[i] * (fuel // cycle_lengths[i])
        else:
            score = partial
        best = max(best, score)

print(best)

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()))
    max_cost = [0]*n
    ans = -10**10
    for i in range(n):
        s = i+1
        pi = p[i]
        cost = c[i]
        big = c[i]
        num = 1
        while pi != s:
            big = max(big, cost)
            max_cost[num] = big
            cost += c[pi-1]
            pi = p[pi-1]
            num += 1
        if cost <= 0:
            ans = max(ans, big)
        else:
            number = k//num
            ans = max(ans, number*cost + max(max_cost[k%num], 0))
    print(ans)
            

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 63


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] < 0 or K <= len(loop) - i - 1:
                j = i
                max_val = -INF
                while True:
                    if j >= len(loop):j=0
                    if i != j and j:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    if i == j: break
                ans = max(ans, max_val)
                continue

            rest = K
            #if K <= len(loop) - i - 1:
            #    val += loopSum[i + K - 1] - loopSum[i]
            #    ans = max(ans, val)
            #    continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            val += loopSum[rest]
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import fractions
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
import collections
from collections import Counter
from collections import deque
import pprint
import itertools

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""


def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr.append([i, cnt])

    if temp != 1:
        arr.append([temp, 1])

    if arr == []:
        arr.append([n, 1])

    return arr


# a^n
def power(a, n, mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod


# n*(n-1)*...*(l+1)*l
def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n - 1
    while (tmp >= l):
        a = a * tmp % mod
        tmp -= 1
    return a

# Union Find
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):
        return {r: self.members(r) for r in self.roots()}

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

# 約数生成
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort()
    return divisors

inf = 10 ** 18
mod = 10 ** 9 + 7

n,k = lr()
p = lr()
c = lr()
visited = [True for i in range(n)]
list_dic = {}
dic_key = [[0,0] for i in range(n)]
count = 0
ans = 0

for i in range(n):
    if visited[i]:
        count+=1
        dic_key[i][0] = count
        add_list = [i+1]
        visited[i] = False
        tmp = p[i]-1
        pre = 0
        while visited[tmp]:
            pre+=1
            dic_key[tmp][0] = count
            dic_key[tmp][1] = pre
            visited[tmp] = False
            add_list.append(tmp+1)
            tmp = p[tmp]-1
        list_dic[count] = add_list
        pre_ans = 0
        length = len(add_list)
        a1 = [0]
        for m in range(2*length):
            a1.append(a1[-1]+c[add_list[m%length]-1])
        pre_total = a1[length]
        ret_ind = length-1
        for ind in range(1, ret_ind+1):
            for m in range(length):
                pre_ans = max(pre_ans, a1[m+ind]-a1[m])
        u = k//length
        if pre_total > 0:
            pre_ans+=(u*pre_total)
        ans = max(ans, pre_ans)
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] + Cs[i+j-l]
                    else:
                        M = Cs[j+i]-Cs[j]
                    if M > m:
                        m = M
            x = K // l
            max0 = c*x+m
        else:
            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)
    if Max < max0:
        Max = max0
print(Max)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

class Doubling:
    def __init__(self, lst, max_step):
        self.lst = lst
        self.max_step = max_step
        self.k = int(log2(max_step * 2 - 1)) + 1
        # print(self.k)
        self.D = self.create()

    def create(self):
        len_ = len(self.lst)
        D = [[-1] * len_ for _ in range(self.k)]
        D[0] = self.lst
        d = 2
        for i in range(1, self.k):
            for j in range(len_):
                D[i][j] = D[i - 1][D[i - 1][j]]
            d *= 2
        # print(D)
        return D

    def step(self, start, step):
        v = start
        for i in range(self.k, -1, -1):
            l = 1 << i
            if l <= step:
                v = self.D[i][v]
                # print(i, l)
                step -= l
        return v

def solve():
    N, K = MI()
    P = LI1()
    C = LI()

    ans = -INF
    for i in range(N):
        S = [0] * (N+1)
        used = [0] * N
        used[i] = 1
        mxs = [-INF] * (N+1)
        step = 0
        while 1:
            next = P[i]
            step = step + 1
            score = S[step-1] + C[next]
            S[step] = score
            mxs[step] = max(mxs[step-1], score)
            # ans_l = max(ans_l, S[step])
            if step == K:
                # print(mxs, mxs[K])
                ans = max(ans, mxs[K])
                break
            if used[next]:
                left = K - step
                # print(next, S, step, S[step], left)
                p = left // step
                q = left % step
                # print(mxs, p, q)
                plus = max(S[step] * p + max(0, mxs[q]), mxs[step])
                # ans = max(ans, max(mxs[step], S[step] + mxs[step] * p + mxs[q]))
                ans = max(ans, max(mxs[step], S[step] + max(0, plus)))
                break
            used[next] = 1
            i = next
    print(ans)

    
if __name__ == '__main__':
    solve()

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 = []
check = [True]*n
for i in range(1,n+1):
    if (check[i-1]==True):
        s = i
        sl = []
        tnp = i
        for j in range(n):
            tnp = p[tnp-1]
            check[tnp-1] = False
            sl.append(c[tnp-1])
            if (tnp==s):
                break
        l.append(sl)
#print(l)
ans = -float("inf")
for i in range(len(l)):
    if (len(l[i])<=k):
        if (sum(l[i])>0):
            x = k%len(l[i])
            if (x==0):
                tnp = 0
            else:
                tnp = -float("inf")
            for p in range(1,x+1):
                wa = sum(l[i][:p])
                tnp = max(tnp,wa)
                for j in range(len(l[i])):
                    wa -= l[i][j]
                    wa += l[i][(j+p)%len(l[i])]
                    tnp = max(tnp,wa)
            ans = max(ans, tnp + sum(l[i])*(k//len(l[i])) )
    tnp = -float("inf")
    for p in range(1,min(k,len(l[i]))+1):
        wa = sum(l[i][:p])
        tnp = max(tnp,wa)
        for j in range(len(l[i])):
            wa -= l[i][j]
            wa += l[i][(j+p)%len(l[i])]
            tnp = max(tnp,wa)
    ans = max(ans, tnp)
print(ans)

Submission status: Wrong Answer

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

ans=[]
for i in range(N):
    trace=[-1 for _ in range(N)]
    cand=[0]
    trace[i]=0
    pos=i
    cnt=1
    cond=False
    while cnt<=K:
        pos=P[pos]-1
        if trace[pos]==-1:
            cand.append(cand[-1]+C[pos])
            trace[pos]=cnt
            cnt+=1
        else:
            cond=True
            init=trace[pos]
            loop=cnt-init
            point=cand[-1]+C[pos]-cand[init]
            break
    if cond:
        cand.append(cand[init]+(K-init)//loop*point+max(cand[init+1:init+1+(K-init)%loop+1])-cand[init])
    ans.append(max(cand[1:]))
print(max(ans))