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

ans=C[P[1]]+0
for i in range(1, N+1):
  count=0
  ima=i+0
  kako=[[None, None] for _ in range(N+1)]
  kako[i]=[0, 0]
  while count<K:
    if kako[P[ima]]!=[None, None]:
      if kako[P[ima]][1]<kako[ima][1]+C[P[ima]]:
        atonanshu=(K-count-1)//((count+1)-kako[P[ima]][0])
        atonanho=(K-count-1)%((count+1)-kako[P[ima]][0])
        agatta=kako[ima][1]+C[P[ima]]-kako[P[ima]][1]
        
        kako[P[ima]]=[count+1+atonanshu*((count+1)-kako[P[ima]][0]), kako[ima][1]+C[P[ima]]+agatta*atonanshu]
        count=count+1+atonanshu*((count+1)-kako[P[ima]][0])
        ima=P[ima]+0
        for _ in range(atonanho):
          kako[P[ima]]=[count+1, kako[ima][1]+C[P[ima]]]
          ima=P[ima]+0
          count+=1
      break
    else:
      kako[P[ima]]=[count+1, kako[ima][1]+C[P[ima]]]
      ima=P[ima]+0
      count+=1
      
  if kako[i][0]==0:
    kako[i]=[None, None]
  ans=max(ans, max([k[1] for k in kako if k[1] is not None]))
  
print(ans)

Submission status: Wrong Answer

Solution code:
#Problem D
N, K= list(map(int,input().split()))
P = list(map(int,input().split()))
C = list(map(int,input().split()))
pos = 0

sub = []
anss = []

if all([i < 0 for i in C]):
    b = sorted(C)
    print(b[-1])
    exit()

for i in range(N):
    ans = 0
    pos = i+1
    for j in range(N):
        ans += C[pos-1]
        sub.append(ans)
        pos = P[pos-1]
    anss.append(max(sub))

        
time = K//N
print(time*max(anss))

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):
    s = 0
    j = i
    for k in range(K):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)
        if j==i: break
    rem = K - (k+1)
    if rem == 0: continue
    d,m = divmod(rem, k+1)
    s *= (d+1)
    ans = max(ans, s)
    for k in range(m):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    s = input().split(' ')
    n = int(s[0])
    k = int(s[1])
    p = [int(i) - 1 for i in input().split(' ')]
    c = [int(i) for i in input().split(' ')]

    circles = {}
    paths = {}

    for i in range(n):
        path = []
        visited = set()
        j = i
        while True:
            if j in circles:
                paths[i] = (path, j)
                break
            else:
                if j in visited:
                    index = path.index(j)
                    circles[j] = path[index:]
                    paths[i] = (path[:index], j)
                    break
                else:
                    path.append(j)
                    visited.add(j)
                    j = p[j]
    ans = None

    # print(paths)
    # print(circles)

    for x in range(n):
        path, circleNum = paths[x]
        circle = circles[circleNum]
        if k <= len(path):
            points = 0
            for i in path[:k]:
                points += c[p[i]]
                if ans is None:
                    ans = points
                ans = max(ans, points)
        elif k <= len(path) + len(circle):
            points = 0
            for i in path + circle[:k-len(path)]:
                points += c[p[i]]
                if ans is None:
                    ans = points
                ans = max(ans, points)
        else:
            points = sum(c[p[i]] for i in path)
            circlePoints = sum(c[p[i]] for i in circle)
            numCircle, remaining = (k - len(path)) // len(circle), (k - len(path)) % len(circle)
            if circlePoints >= 0:
                points = 0
                for i in path:
                    points += c[p[i]]
                    if ans is None:
                        ans = points
                    ans = max(ans, points)
                points += (numCircle * circlePoints)
                if ans is None:
                    ans = points
                ans = max(ans, points)
                for i in circle[:remaining]:
                    points += c[p[i]]
                    if ans is None:
                        ans = points
                    ans = max(ans, points)
            else:
                points = 0
                for i in path:
                    points += c[p[i]]
                    if ans is None:
                        ans = points
                    ans = max(ans, points)
                # points += (numCircle * circlePoints)
                if ans is None:
                    ans = points
                ans = max(ans, points)
                for i in circle:
                    points += c[p[i]]
                    if ans is None:
                        ans = points
                    ans = max(ans, points)

    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(n):
    p[i] -= 1
c = list(map(int,input().split()))
if max(c) <= 0:
    print(max(c))
    exit()
ans = 0
for begin in range(n):
    i = p[begin]
    s = c[i]
    round = 1
    score = 0
    kk = 0
    while i != begin:
        i = p[i]
        s += c[i]
        round += 1
    if s > 0 and k >= round:
        score += s * (k//round)
        kk = k - round * (k//round)
    elif k >= round:
        kk = round
    else:
        kk = k
    smax = 0
    now = 0
    i = begin
    while kk > 0:
        i = p[i]
        now += c[i]
        smax = max(now, smax)
        kk -= 1
    score += smax
    ans = max(ans, score)

print(ans)

Submission status: Wrong Answer

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n,k = readInts()
P = readInts()
C = readInts()
dic = defaultdict(int)
for i in range(n):
    dic[i+1] = P[i]
ans = -float('inf')
for start in range(n):
    nya = deque()
    root = defaultdict(int)
    pya = start+1
    cnt = 0
    SUM = 0
    while root[dic[pya]] == 0 and cnt < k:
        pya = dic[pya]
        nya.append(C[pya-1])
        cnt += 1
        SUM += C[pya-1]
        root[pya] = 1
        ans = max(ans,SUM)
    if cnt < k:# まだ満たない
        need = k-cnt
        nl = len(nya)
        sumnya = sum(nya)
        a = need//nl
        if sumnya > 0:
            SUM += sumnya * a
        ans = max(ans,SUM)
        nokori = need - nl*a
        for idx in range(nokori):
            SUM += nya[idx]
            ans = max(ans,SUM)
    else:
        ans = max(ans,SUM)
print(ans)

Submission status: Wrong Answer

Solution code:

n, k = map(int, input().split())
p = [0] * n
c = [0] * n
a = [0] * (n+1)
ans = [0] * n

p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
    s = 0
    x = i
    roop = 0
    for j in range(n):
        s += c[x]
        a[j+1] = s
        x = p[x] - 1
        if x == i:
            roop = j + 1
            break
    if s < 0:
        ans[i] = max(a[:min(roop, n)])
    else:
        ans[i] = max(s * (k // roop) + max(a[:1+k % roop]), s * (k // roop - 1) + max(a))
print(max(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 = -10 ** 100
for i in range(n):
    d = [-1] * n
    d[i] = 0
    res = 0
    t = i
    cnt = 1
    while d[p[t] - 1] == -1:
        cnt += 1
        d[p[t] - 1] = d[t] + 1
        t = p[t] - 1
        res += c[t]
        ans = max(ans, res)
    t = p[t] - 1
    res += c[t]
    K = k - d[t]
    rt = 0
    if k < d[t] + cnt * 2:
        t = i
        co = 0
        for i in range(k):
            t = p[t] - 1
            co += c[t]
            ans = max(ans, co)
    else:
        q = i
        for i in range(d[t]):
            q = p[q] - 1
            rt += c[q]
        re = 0
        r = 0
        for i in range(K % cnt):
            t = p[t] - 1
            r += c[t]
            re = max(r, re)
        ans = max(ans, res * (K // cnt) + rt + re)
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 = min(C)
for i in range(N):
  s = 0
  m = [0 for i in range(N+1)]
  t = i
  step = 0
  while step < K:
    step += 1
    t = P[t] - 1
    s += C[t]
    m[step-1] = s
    if t == i:
      break
  #print(i, s, step, K // step)
  #Case_1 : [1,step]
  for j in range(step):
    ans = max(ans, m[j])
  #Case_2 : max(s, 0) * (K // step) + mod_max 1 ~ K//step : round
  if K % step == 0:
    mod_max = 0
    for j in range(step):
      mod_max = max(mod_max, m[j])
    ans = max(ans, mod_max + max(s, 0) * ((K // step)-1))
  else:
    mod_max = 0
    for j in range(K % step):
      mod_max = max(mod_max, m[j])
    ans = max(ans, mod_max + max(s, 0) * (K // step))

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()))
for i in range(N):
    P[i] -= 1

ans = -10**10
for i in range(N):
    T = []
    Check = [0]*N
    move = i
    count = 1
    while(True):
        if Check[move] != 0:
            break
        Check[move] = count
        T.append(C[P[move]])
        move = P[move]
        count += 1
    s = Check[move] - 1
    result_1 = -10**10
    total = 0
    for j in range(min(s, K)):
        total += T[j]
        result_1 = max(result_1, total)
    result_2 = -10**10
    total = 0
    for j in range(min(len(T), K)):
        total += T[j]
        result_2 = max(result_2, total)
    if K >= len(T):
        result_3 = 0
        result_3 += sum(T[:s])
        result_3 += sum(T[s:])*((K - len(T[:s])) // len(T[s:]))
        result_4 = result_3
        total = result_3
        for j in range((K - len(T[:s])) % len(T[s:])):
            total += T[j]
            result_3 = max(result_3, total)
        total = result_4
        for j in T[s:][::-1]:
            total -= j
            result_4 = max(result_4, total)
    if K >= len(T):
        if result_4 != 0:
            ans = max([result_1, result_2, result_3, result_4, ans])
        else:
            ans = max([result_1, result_2, result_3, ans])
        ans = max([result_1, result_2, ans])
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  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

#####MakeDivisors######
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)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N,K = IL()
P = IL()
C = IL()

data = []
loopdata = []
oneloop = []
for i in range(N):
  temp = [-INF]
  step = 1
  flag = [0 for i in range(N)]
  now = P[i]-1
  score = C[now]
  best = score
  temp.append(best)
  flag[now] = step
  while True:
    step += 1
    now = P[now]-1
    if flag[now]:
      loopdata.append([flag[now],step])
      score += C[now]
      best = max(best,score)
      temp.append(best)
      oneloop.append(score-temp[flag[now]])
      break
    score += C[now]
    best = max(best,score)
    temp.append(best)
    flag[now] = step
  data.append(temp)

best = -INF
for i in range(N):
  if K < loopdata[i][1]:
    best = max(best,max(data[i][:K]))
  else:
    if oneloop[i]<0:
      best = max(best,max(data[i]))
    else:
      mod = loopdata[i][1]-loopdata[i][0]
      k = K - (loopdata[i][0]-1)
      p = (k-1)//mod
      q = k-p*mod
      score = -INF

      for j in range(len(data[i])-1):
        if j < loopdata[i][0]:
          score = max(score,data[i][j])
        else:
          if j <= (loopdata[i][0]-1)+q:
            score = max(score,data[i][j]+oneloop[i]*p)
          else:
            score = max(score,data[i][j]+oneloop[i]*(p-1))
      best = max(best,score)
print(best)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
for i in range(n):
    p[i] -= 1
c = list(map(int,input().split()))
reach = [False]*n
x = []
cx = []
for i in range(n):
    if reach[i]:continue
    buf = [c[i]]
    nexti = p[i]
    while nexti!=i:
        buf.append(c[nexti])
        reach[nexti] = True
        nexti = p[nexti]
    x.append(buf)
ans = []
for i in x:
    n = k//len(i)
    a = sum(i)*n
    ind = k%len(i)
    ii = i+i
    for j in range(len(i)):
        for k in range(1,ind+2):
            ans.append(a+sum(ii[j:j+k]))
        for k in range(1,min(k+1,len(i))):
            ans.append(sum(ii[j:j+k]))
print(max(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()))


scores=[0]*N
ans=max(scores)

for i in range(K):
    scores=[C[P[j]-1]+scores[P[j]-1] for j in range(N)]
    ans=max(ans,max(scores))
    
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(x) for x in input().split()]
temp = [int(x) for x in input().split()]
p = [-1]
for x in temp:
    p.append(x)
c = [-1]
temp = [int(x) for x in input().split()]
for x in temp:
    c.append(x)

ans = -int(1e12)
# print(p)
# print(c)
# print()
for i in range(1, N+1):
    # print("i: ", i)
    visited = [False] * (N+1)
    cur_sum = 0
    cur_box = i
    l = 0
    k = K
    while k > 0:
        if visited[cur_box]:
            break
        cur_sum += c[p[cur_box]]
        ans = max(ans, cur_sum)
        visited[cur_box] = True
        cur_box = p[cur_box]
        k -= 1
        l += 1
        # print(cur_sum)
    if k != 0 and cur_sum > 0:
        cur_sum = (cur_sum * (K // l))
        ans = max(ans, cur_sum)
        k = K % l
        while k > 0:
            cur_sum += c[p[cur_box]]
            ans = max(ans, cur_sum)
            cur_box = p[cur_box]
            k -= 1
            # print(cur_sum)
    
    # print("i:", i , ", sum:", cur_sum)
print(ans)

Submission status: Wrong Answer

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

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

unvisited = list(range(N))
cycles = []
while unvisited:
    cycles.append([])
    start = unvisited.pop(0)
    cycles[-1].append(C[start])
    temp = P[start]-1
    while temp in unvisited:
        unvisited.remove(temp)
        cycles[-1].append(C[temp])
        temp = P[temp]-1

maxsums = []
for cycle in cycles:
    doublecycle = cycle*2
    Kdiv = K // len(cycle)
    Krem = (K-1) % len(cycle) + 1
    maxsum = -10**9
    for i in range(Krem):
        for j in range(len(cycle)):
            maxsum = max(maxsum,sum(doublecycle[j:j+i+1]))
    cyclesum = sum(cycle)
    if cyclesum > 0:
        if Krem == len(cycle):
            maxsums.append(cyclesum*(Kdiv-1) + maxsum)
        else:
            maxsums.append(cyclesum * Kdiv + maxsum)
    else: maxsums.append(maxsum)

print(max(maxsums))

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

S = []
for i in range(N):
    p, si = i, [0]
    ps = set()
    while P[p] not in ps:
        p = P[p]
        ps.add(p)
        si.append(si[-1] + C[p])
    si = si[1:]
    S.append(si)


ans = -float('inf')
for i in range(N):
    if K >= len(si):
        ans = max(ans, max(S[i]), S[i][-1] * (K // len(S[i])) + max(S[i][:(K % len(S[i]))] + [0]))
    else:
        ans = max(ans, max(S[i][:K]))

print(ans)

Submission status: Wrong Answer

Solution code:
n,k= list(map(int, input().strip().split()))
p= list(map(int, input().strip().split()))
c= list(map(int, input().strip().split()))
q=[[] for i in range(n)]
o=[[] for i in range(n)]
for i in range(n):
    q[i].append(i+1)
for i in range(n):
    while q[i].count(i+1)==1:
        l=len(q[i])
        q[i].append(p[q[i][l-1]-1])
        o[i].append(c[q[i][-1]-1])
for i in range (n):
    for j in range(1,len(o[i])):
        o[i][j]+=o[i][j-1]
cost=[0]*n
for i in range(n):
    cost[i]=o[i][-1]*(k//len(o[i]))
    if k%len(o[i])>0:
        cost[i]+=o[i][k%len(o[i])-1]
print(max(cost))

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

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

    cycless = [[] for _ in range(N)]
    useds = [0] * N
    for no in range(N):
        if useds[no]: continue
        x = no
        while True:
            useds[x] = 1
            cycless[no].append(Cs[x])
            x = Ps[x]
            if x == no:
                break

#    for no in range(N):
#        print('# no:', no, '/ cycless[no]:', cycless[no], file=sys.stderr)

    ans = -float('inf')
    for no in range(N):
        if not cycless[no]: continue
        L = len(cycless[no])
        accCycles = list(accumulate([0]+cycless[no]+cycless[no]+cycless[no]))
        sumC = sum(cycless[no])
#        print('\n# no:', no, '/ sumC:', sumC, file=sys.stderr)
        if sumC > 0:
            num = K//L
            if num > 0:
                num -= 1
                if num == 0:
                    fr = 1
                else:
                    fr = 0
                score = -float('inf')
                K = L + K%L
                for M in range(fr, K+1):
                    for st in range(L):
                        s = accCycles[st+M] - accCycles[st]
                        if s > score:
                            score = s
                score += sumC * num
            else:
                score = -float('inf')
#                K = K if K <= L else L
                for M in range(1, K+1):
                    for st in range(L):
                        s = accCycles[st+M] - accCycles[st]
                        if s > score:
                            score = s
        else:
            score = -float('inf')
            K = K if K <= L else L
            for M in range(1, K+1):
                for st in range(L):
                    s = accCycles[st+M] - accCycles[st]
                    if s > score:
                        score = s
        if score > ans:
            ans = score
#        print('# no:', no, '/ score:', score, file=sys.stderr)

    print(ans)


solve()

Submission status: Wrong Answer

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

R = [False] * (N+1)
S = []

for st in range(1, N+1):
    if R[st]: continue
    loop = []
    x = st
    while not R[x]:
        loop.append(C[x])
        R[x] = True
        x = P[x]

    L = len(loop)
    K0 = K//L
    K1 = K%L

    T = [0]
    for c in loop: T.append(T[-1]+c)
    tot = T[-1]

    smax = smax_l = -10**15
    for i in range(L):
        for j in range(i, L):
            l = j-i+1
            if l==L: continue
            
            ss = T[j+1]-T[i]
            smax = max(smax, ss)
            smax = max(smax, tot-ss)
            if l  <=K1: smax_l = max(smax_l, ss)
            if L-l<=K1: smax_l = max(smax_l, tot-ss)

    s = smax_l + K0*max(0,tot)
    if K0>0: s = max(s, smax+(K0-1)*max(0,tot))
    S.append(s)

print(max(S))

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()))
INF = 10**18
ans = -INF
for i in range(N):
    arr = []
    tot = 0
    rest = K
    visited = {}
    visited[i] = rest
    nex = i
    while rest:
        nex = P[nex]
        tot += C[nex]
        arr.append(tot)
        rest -= 1
        if nex in visited:
            loop = visited[nex]-rest
            #print("visited", loop, arr)
            if tot > 0:
                tot += (rest//loop)*tot
                arr.append(tot)
                rest = rest%loop
            else:
                rest = min(rest, loop)
            while rest:
                nex = P[nex]
                tot += C[nex]
                arr.append(tot)
                rest -= 1
            break
        else:
            visited[nex] = rest
    #print(i, arr)
    ans = max(ans, max(arr))
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    N,K=list(map(int,sys.stdin.readline().split()))
    P=list(map(int,sys.stdin.readline().split()))
    C=list(map(int,sys.stdin.readline().split()))

    output=-10**20

    lst=[[0]*(N+1) for _ in range(N)]
    for i in range(N):
        st=set()
        now=i
        count=0
        score=0
        if K==1:
            output=max(output,C[P[i]-1])
            continue

        while True:
            count+=1
            now=P[now]-1

            if now in st:
                count-=1
                break
    
            lst[i][count]=lst[i][count-1]+C[now]
            st.add(now)
            
            if count==K:
                break
        
        if lst[i][count]>0 and K>=count:
            if K%count:
                s=lst[i][count]*(K//count)+max(lst[i][1:K%count+1])
            else:
                s=lst[i][count]*(K//count)
        else:
            s=max(lst[i][1:count+1])
        output=max(output,s)

    print(output)

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()))
ans=-10**10
for i in range(n):
	K=k
	score=0
	pre_score=0
	visit=[0]*n
	now=i
	cnt=0
	while visit[now]==0:
		cnt+=1
		visit[now]=1
		now=p[now]-1
		pre_score+=c[now]
		if cnt!=1:
			score=max(score,pre_score)
		else:
			score=pre_score
		K-=1
		if K==0:
			break
	ans=max(score,ans)
	if K==0:
		continue
	loop=[0]
	NOW=now
	#NOWはループ元
	for j in range(n):
		now=p[now]-1
		loop.append(loop[-1]+c[now])
		if NOW==now:
			break
	pre_score2=pre_score
	pre_score2+=max(loop[:min(K+1,len(loop))])
	score=max(ans,pre_score2)
	pre_score+=max(loop[-1],0)*(K//(len(loop)-1))
	K%=(len(loop)-1)
	pre_score+=max(loop[:K+1])
	score=max(score,pre_score)
	ans=max(ans,score)
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
input=stdin.readline
n,k=map(int,input().split())
arr=[0]+list(map(int,input().split()))
cost=[0]+list(map(int,input().split()))
ma=-10000000000000000000
for i in range(1,n+1):
    m=1
    cur=arr[i]
    co=cost[cur]
    l=[0,co]
    ma = max(ma, l[-1])
    while(m<k and cur!=i):
        cur=arr[cur]
        co=cost[cur]
        l.append(l[-1]+co)
        m += 1
        ma=max(ma,l[-1])
    ma = max(ma, l[-1] * (k//m) + l[k%m])
print(ma)

Submission status: Wrong Answer

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  N,K=LI()
  P=LI()
  P=[0]+P
  C=LI()
  C=[0]+C

  l=[[0] for _ in range(N)]
  check=[[False]*(N+1) for _ in range(N)]
  roop=[]
  for i in range(N):
    zahyo=i+1
    check[i][zahyo]=True
    f=False
    for j in range(N+1):
      zahyo=P[zahyo]
      if check[i][zahyo] and not f:
        roop.append(j+1)
        f=True
      score=C[zahyo]
      l[i].append(l[i][-1]+score)
  # print(l)
  # print(roop)

  ans=-inf
  for i in range(N):
    roop_count=roop[i]
    if K<=roop_count:
      ans=max(ans,max(l[i][1:K+1]))
    else:
      ans=max(ans,max(l[i][1:K+1]))
      if l[i][roop_count]>0:
        c=K//roop_count
        _ans=c*l[i][roop_count]
        k=K%roop_count
        _ans+=max(l[i][1:k+1]+[0])
        ans=max(ans,_ans)

  return ans

# main()
print(main())