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 find(vals,l):
    ans = -float('inf')
    for i in range(len(vals)//2):
        curr = vals[i+l-1]
        if i-1 >= 0:
            curr -= vals[i-1]

        ans = max(ans,curr)

    #print(ans,l)
    return ans

def dfs(edges,node,k,costs,visited):
    nodes = []
    stack = [node]
    while stack:
        node = stack.pop()
        if node not in visited:
            visited.add(node)
            nodes.append(node)
            stack.append(edges[node])

    vals = []
    for node in nodes:
        vals.append(costs[node-1])

    vals.extend(vals)
    for i in range(1,len(vals)):
        vals[i] += vals[i-1]

    total = vals[-1]//2
    if total >= 0:
        ans = total*(k//(len(vals)//2))
    else:
        ans = 0

    max_val = -float('inf')
    #print('here',len(vals)//2,total)
    val = -float('inf')
    if k >= len(vals)//2:
        for i in range(1,(len(vals)//2)+1):
            max_val = max(max_val,find(vals,i))

    val = -float('inf')
    #print(total)
    k %= (len(vals)//2)
    
    for i in range(1,k+1):
        val = max(val,find(vals,i))

    return max(max_val,ans+val)

def main():
    n,k = map(int,input().split())
    perm = list(map(int,input().split()))
    costs = list(map(int,input().split()))
    edges = [-1]*(n+1)
    for i in range(n):
        edges[i+1] = perm[i]

    ans = -float('inf')
    visited = set()
    for i in range(1,n+1):
        if i not in visited:
            ans = max(ans,dfs(edges,i,k,costs,visited))

    print(ans)

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()))
loop_flags = [False] * N
loops = []
for i in range(N):
    if loop_flags[i]:
        continue
    next_cell = i
    loop = []
    while not loop_flags[next_cell]:
        loop_flags[next_cell] = True
        loop.append(C[next_cell])
        next_cell = P[next_cell] - 1
    if loop:
        loops.append(loop)
# print(loops)

ans = -float('inf')
for loop in loops:
    sum_score = 0
    for l in loop:
        sum_score += l
    if sum_score > 0:
        sum_val = sum_score * (K // len(loop))
        remain_K = K % len(loop)
    else:
        sum_val = 0
        remain_K = min(len(loop), K)
    for i in range(1, len(loop)):
        if i > remain_K:
            break
        target = sum_val
        for j in range(i):
            target += loop[j]
        ans = max(target, ans)
        for j in range(len(loop)):
            target = target - loop[j] + loop[(i + j) % len(loop)]
            ans = max(target, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
*p, = map(int, input().split())
p = [v - 1 for v in p]
*c, = map(int, input().split())
minc = float('-inf')

ans = minc


def get_loop(i):
    pos = i
    cnt = 0
    cur_score = 0
    while cnt == 0 or pos != i:
        pos = p[pos]
        cur_score = cur_score + c[pos]
        cnt += 1
    return cnt, cur_score

# print(get_loop(2))

def solve(pos, k):
    score = minc
    cur_score = 0
    loop_length, loop_score = get_loop(pos)
    if k >= loop_length and loop_score > 0:
        # print("%s: %s // %s, %s, %s" % (i, k, loop_length, cur_score, max_loop_score))
        cur_score = loop_score * ((k - loop_length) // loop_length)
        score = max(cur_score, score)
        k = k % loop_length + 1
    else:
        k = min(k, loop_length)
    # print('rem k', k, "cur_score", cur_score)
    for _ in range(k):
        pos = p[pos]
        cur_score += c[pos]
        score = max(cur_score, score)
    # print("%s: %s" % (i, score))
    return score

for i in range(n):
    ans = max(ans, solve(i, k))
print(ans)

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 << 80


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)-1:
                j = i
                max_val = -INF
                iter = 0
                done = False
                while iter <= K:
                    if j >= len(loop):j=0
                    if (i != j and j) or done:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    if not j ==1:
                        iter += 1
                    if done : break
                    if i == j: done = True
                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 += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

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**9

for i in range(n):
    m=i
    co=0
    an=0
    for j in range(n):
        m=p[m]-1
        co+=1
        if m==i:
            break      
    m=i
    x=[0 for j in range(co+1)]
    for j in range(co):
        m=p[m]-1
        x[j+1]=x[j]+c[m]
    
    if k<=co:
        ans=max(ans,max(x[j] for j in range(1,co+1)))
    else:
        if x[-1]<0:
            ans=max(ans,max(x[j] for j in range(1,co+1)))
        else:
            an+=x[-1]*(k//co)
            
   
            if k%co!=0:
        
                ans=max(ans,an+max(x[j] for j in range(1,k%co+1)))
            else:
                ans=max(ans,an)
    
        
    
print(ans)

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 = [-1] * N
        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)

                # print(mxs, p, q, mxs[step])
                # 現在の最高得点で打ち切る
                ans = max(ans, mxs[step])
                # print(next, S, STEP, step, STEP[next])
                if STEP[next] == -1:
                    loop_size = step
                    pre_idx = 0
                else:
                    loop_size = len(S[STEP[next]:S[step]])
                    pre_idx = STEP[next]
                ss = S[step] - S[pre_idx]

                p = left // loop_size
                q = left % loop_size

                # さらにスコアを伸ばす
                if p > 0:
                    ans = max(ans, S[step] + max(0, mxs[step]))
                    ans = max(ans, S[step] + ss * p + max(0, mxs[q]))
                else:
                    ans = max(ans, S[step] + max(0, mxs[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
            STEP[next] = i
            used[next] = 1
            i = next
    print(ans)

    
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
def main():
    INF = 10 ** 20
    N, K = list(map(int, input().split()))
    P = list(map(lambda x: int(x) - 1, input().split()))
    C = list(map(int, input().split()))
    # P のループの最初を検索しておく
    loop_list = list()
    visited = [0] * N
    for i in range(N):
        if visited[i] == 1:
            continue
        start = i
        size = 0
        sum_c = 0
        while visited[i] == 0:
            visited[i] = 1
            size += 1
            sum_c += C[i]
            i = P[i]
        loop_list.append((start, size, sum_c))
    # 各ループごとに考える
    ans = - INF
    for start, size, sum_c in loop_list:
        MAX_LEN = K % size
        if MAX_LEN == 0:
            MAX_LEN = size
        # 2順ループを作っておく
        CUMSUM_CC = [0] * (2 * size)
        cur_index = P[start]
        CUMSUM_CC[0] = C[P[start]]
        for i in range(1, 2 * size):
            cur_index = P[cur_index]
            CUMSUM_CC[i] += C[cur_index] + CUMSUM_CC[i - 1]
        # 最大MAX_LENの連続部分列での最大スコア
        max_score = - INF
        for left in range(2 * size):
            for right in range(left, min(2 * size, left + MAX_LEN)):
                s = CUMSUM_CC[right]
                if left > 0:
                    s -= CUMSUM_CC[left - 1]
                max_score = max(max_score, s)
        if sum_c > 0:
            max_score += sum_c * ((K - 1) // size)
        ans = max(ans, max_score)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import math

n,k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
nex = 0
ans = 0
maxa = 0

if all(i < 0 for i in c):
    print(max(c))
    exit()

if n > k:
    for i in range(n):
        nex = i
        ans = 0

        for j in range(k):
            ans += c[p[nex]-1]
            if maxa < ans:
                maxa = ans
            nex = p[nex]-1
else:
    if sum(c) < 0:
        for i in range(n):
            nex = i
            ans = 0

            for j in range(n):
                ans += c[p[nex]-1]
                if maxa < ans:
                    maxa = ans
                nex = p[nex]-1
    else:
        for i in range(n):
            nex = i
            ans = sum(c)*math.floor(k/n)
            for j in range(k%n):
                ans += c[p[nex]-1]
                if maxa < ans:
                    maxa = ans
                nex = p[nex]-1

print(maxa)

Submission status: Wrong Answer

Solution code:
def segfunc(x,y):
  return x+y

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

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

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

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

    def sum(self, l, r): #これで[l,r)から取り出す。
        l += self._n
        r += self._n
        l_val = r_val = self._unit
        while l < r:
            if l & 1:
                l_val = self._dot(l_val, self._tree[l])
                l += 1
            if r & 1:
                r -= 1
                r_val = self._dot(self._tree[r], r_val)
            l >>= 1
            r >>= 1
        return self._dot(l_val, r_val)


N,K = map(int,input().split())
P = list(map(int,input().split()))
for i in range(N):
  P[i]-=1
#print(P)
C = list(map(int,input().split()))
Flag = True
for c in C:
  if c >= 0:
    Flag = False
    break
if Flag:
  print(max(C))
  exit()
L = []
visited = set([])
for i in range(N):
  if i in visited:
    continue
  now = i
  temp = []
  while now not in visited:
    nxt = P[now]
    visited.add(now)
    temp.append(C[nxt])
    now = nxt
  L.append(temp)
#print(L)
INF = float("inf")
ans = 0
for X in L:
  n = len(X)
  #print(X)
  Tree = SegmentTree(X, segfunc, 0)
  A = sum(X)
  T = [0 for _ in range(n+1)]
  for i in range(n+1): #i個選ぶ
    nokori = n-i
    temp = INF
    #print(i,nokori)
    for j in range(nokori+1):
      #print(j,j+i)
      tt = Tree.sum(j,j+i)
      #print(tt)
      temp = min(temp,tt)
    #print(temp)
    T[-1-i] = A-temp
    #print(T[i])
  if A <= 0:
    hani = min(K+1,n+1)
    tmp = max(T[:hani])
    ans = max(ans,tmp)
  else:
    hani = K%n+1
    loop = K//n
    #print(loop,T)
    tmp = max(T[:hani])+loop*A
    ans = max(ans,tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
import os
import sys
from io import BytesIO, IOBase

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

def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7

Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()


n,k = Ri()
a = Ri(); a = [i-1 for i in a]
c = Ri()

lis = []
vis = [False]*n
for i in range(n):
    if not vis[i]:
        temp = []
        nex = i
        while True:
            temp.append(c[nex])
            vis[nex] = True
            nex = a[nex]
            if vis[nex] : break
        lis.append(temp)
summ = []
# print(lis)

for i in range(len(lis)):
    temp = [0]*(len(lis[i]) + 1)
    for j in range(len(lis[i])):
        temp[j+1] = temp[j] + lis[i][j]
    summ.append(temp[:])

# print(summ)
maxxans= -INF
for i in range(len(lis)):
    actualcircle = k//len(lis[i])
    # print(actualcircle)
    for krem in range(1, min(n-1, k)+1):
        tot = summ[i][-1]
        cnt = len(lis[i])
        tempans = tot*(krem//cnt)
        rem = krem%cnt
        for j in range(len(lis[i])):
            if j + rem -1 >= cnt:
                temp = summ[i][-1] - summ[i][j]
                totrem = rem - ((cnt-1) - j +1)
                temp += summ[i][totrem]
                maxxans = max(maxxans, temp + tempans)
            else:
                maxxans = max(maxxans, tempans + summ[i][j+rem] - summ[i][j])
        tempans = tot*actualcircle
        maxxans = max(maxxans, actualcircle* tot)
        if krem <= k%len(lis[i]):
            # print(tempans)
            for j in range(len(lis[i])):
                if j + rem -1 >= cnt:
                    temp = summ[i][-1] - summ[i][j]
                    totrem = rem - ((cnt-1) - j +1)
                    temp += summ[i][totrem]
                    maxxans = max(maxxans, temp + tempans)
                else:
                    maxxans = max(maxxans, tempans + summ[i][j+rem] - summ[i][j])
            # print(maxxans)
print(maxxans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
used = [0]*n
c = list(map(int,input().split()))
ans = -float("INF")
def calc(x):
    l = []
    now = x
    score = 0
    while used[now] == 0:
        used[now] = 1
        l.append(c[now])
        now = p[now]-1
    S = sum(l)
    le = len(l)
    if S > 0 and k > le:
        score += (k//le-1)*S
        mod = k%le+le
        now = 0
        for i in range(le):
            cal = 0
            for j in range(mod):
                cal += l[(i+j)%le]
                now = max(now,cal)
        return score+now
    else:
        mod = min(le,k)
        now = 0
        for i in range(le):
            cal = 0
            for j in range(mod):
                cal += l[(i+j)%le]
                now = max(now,cal)
        return score+now
    
for i in range(n):
    if used[i] == 0:
        ans = max(ans,calc(i))
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')

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

LIM = - (10 ** 9 + 1)

ans = LIM
for i in range(N):
    res = [0] * (N + 1)
    seen = [0] * N
    k = 0
    pos = i
    while True:
        if seen[pos]:
            break
        if k >= K:
            break
        seen[pos] = 1
        pos = P[pos] - 1
        k += 1
        # print("k: {} pos: {}".format(k, pos))
        res[k] = res[k-1] + C[pos]
    # print("i: {} k: {} res: {}".format(i, k, res))

    res[0] = LIM
    ans = max(ans, max(res))
    if k < K:
        # kのループが存在する
        if res[k] > 0:
            q, mod = divmod(K, k)
            tmp_ans = (res[k] * q) + res[mod]
            ans = max(ans, tmp_ans)
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
import sys

input = sys.stdin.buffer.readline

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

kouho = []

used = [False] * (n)
for i in range(n):
    if used[i]:
        continue
    now = i
    cnt = 0
    res = 0
    route = []
    while True:
        if used[now]:
            break
        route.append(C[P[now] - 1])
        used[now] = True
        nex = P[now] - 1
        cnt += 1
        res += C[nex]
        now = nex
    kouho.append((res, cnt, route))

ans = -(10 ** 20)
for res, cnt, route in kouho:
    num = len(route)
    kaisu = min(k, num)
    temp2 = -(10 ** 20)
    route += route
    ACR = list(accumulate([0] + route))
    for shiten in range(num):
        for kosuu in range(1, kaisu + 1):
            temp3 = ACR[kosuu + shiten] - ACR[shiten]
            temp2 = max(temp2, temp3)
    ans = max(ans, temp2)
    if res > 0 and k >= cnt:
        temp1 = res * (k // cnt)
        kaisu = k % cnt
        for shiten in range(num):
            for kosuu in range(1, kaisu + 1):
                temp3 = ACR[kosuu + shiten] - ACR[shiten]
                temp2 = max(temp2, temp3)
        ans = max(ans, temp1 + temp2)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
k2=k%n
p = list(map(int, input().split()))
c= list(map(int, input().split()))
alist = [[p[i],c[i]] for i in range(n)]
blist=[0]*n
clist=[0]*n
dlist=[0]*n
for i in range(n):
  cnt=0
  cnt2=0
  x=p[i-1]
  zlist=[]
  while x not in zlist:
    zlist.append(x)
    cnt+=c[x-1]
    cnt2+=1
    x=p[x-1]
  blist[i]=cnt
  clist[i]=cnt2
for i in range(n):
  cnt=0
  cnt2=-10000000000000000000
  num=i
  for j in range((n-1)%clist[i]+1):
    cnt+=c[num-1]
    cnt2=max(cnt,cnt2)
    num=p[num-1]
  dlist[i]=cnt2
elist=[0]*n
for i in range(n):
  elist[i]=max(dlist[i],dlist[i]+blist[i]*n//clist[i])
print(max(elist))

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
l1 = list(map(int,input().split()))
l2 = list(map(int,input().split()))
num = 0
num_l = []
ans_sum = 0
ans = []
ans_l = []
ans_l1 = []
for i in range(N):
  num = i + 1
  checker = False
  while checker == False:
    num = l1[num - 1]
    ans_sum += l2[num - 1]
    num_l.append(ans_sum)
    if num == i + 1:
      checker = True
  ans.append(num_l)
  num_l = []
  ans_sum = 0
for i in range(N):
  if ans[i][-1] <= 0:
    ans_l.append(max(ans[i]))
  else:
    ans_l1 = [ans[i][j] for j in range(K % len(ans[i]))]
    ans_l.append(ans[i][-1] * (K // len(ans[i])) + max(ans_l1,default=0))
print(max(ans_l))

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
k2=k%n
p = list(map(int, input().split()))
c= list(map(int, input().split()))
alist = [[p[i],c[i]] for i in range(n)]
blist=[0]*n
clist=[0]*n
dlist=[0]*n
for i in range(n):
  cnt=0
  cnt2=0
  x=p[i-1]
  zlist=[]
  while x not in zlist:
    zlist.append(x)
    cnt+=c[x-1]
    cnt2+=1
    x=p[x-1]
  blist[i]=cnt
  clist[i]=cnt2
for i in range(n):
  cnt=0
  cnt2=-10000000000000000000
  num=i
  for j in range((n-1)%clist[i]+1):
    cnt+=c[num-1]
    cnt2=max(cnt,cnt2)
    num=p[num-1]
  dlist[i]=cnt2
elist=[0]*n
for i in range(n):
  elist[i]=max(dlist[i],dlist[i]+blist[i]*n//clist[i])
print(max(elist))
print(dlist)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N,K=(int(x) for x in input().rstrip('\n').split())
Ps = [int(x)-1 for x in input().rstrip('\n').split()]
Cs = [int(x) for x in input().rstrip('\n').split()]
res = -10**9-1
for i in range(N):
  next = Ps[i]
  cycle = Cs[next]
  steps =[cycle]
  for _ in range(K):
    next = Ps[next]
    cycle += Cs[next]
    steps.append(cycle)
    if next == i:
      if cycle>0:
        if K%len(steps)!=0:
          now = (K//len(steps))*cycle+max(steps[:K%len(steps)])
          if now>res:
            res = now
          break
        else:
          now =(K//len(steps))*cycle
          if now>res:
            res = now
          break
      else:
        now = max(steps)
        if now>res:
          res = now
        break
    if len(steps)==K:
      now = max(steps)
      if now>res:
        res = now
print(res)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
N, K = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
weight = []
visited = [0]*N
ans = - float('inf')

def dfs(u, cnt, w):
  w += [C[u]]
  visited[u] = 1
  v = P[u]
  if visited[v] != 1:
    dfs(v, cnt+1, w)
  else:
    return

for i in range(N):
  weight = []
  visited = [0]*N
  dfs(i, 1, weight)
  if len(weight) > K:
    tmp = 0
    for j in range(K):
      weight[j+1] += weight[j]
    tmp = max(weight)
    if tmp == 0:
      tmp = weight[0]
    ans = max(ans, tmp)
  else:
    s = sum(weight)
    if s > 0:
      ans = max(ans, (K//len(weight))*s + sum(weight[:K%len(weight)]))
    else:
      tmp = 0
      for j in range(len(weight)-1):
        weight[j+1] += weight[j]
      tmp = max(weight)
      if tmp == 0:
        tmp = weight[0]
      ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = [0 for _ in range(n)]

for i in range(n):
    route = set()
    start = i
    val = 0
    val0 = -float('inf')
    count = 0
    while not start in route or count < k:
        route.add(start)
        start = p[start]-1
        val += c[start]
        val0 = max(val, val0)
        count += 1
    ans[i] = val0
    
print(max(ans))

Submission status: Wrong Answer

Solution code:
def segfunc(x,y):
  return x+y

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

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

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

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

    def sum(self, l, r): #これで[l,r)から取り出す。
        l += self._n
        r += self._n
        l_val = r_val = self._unit
        while l < r:
            if l & 1:
                l_val = self._dot(l_val, self._tree[l])
                l += 1
            if r & 1:
                r -= 1
                r_val = self._dot(self._tree[r], r_val)
            l >>= 1
            r >>= 1
        return self._dot(l_val, r_val)


N,K = map(int,input().split())
P = list(map(int,input().split()))
for i in range(N):
  P[i]-=1
#print(P)
C = list(map(int,input().split()))
Flag = True
for c in C:
  if c >= 0:
    Flag = False
    break
if Flag:
  print(max(C))
  exit()
L = []
visited = set([])
for i in range(N):
  if i in visited:
    continue
  now = i
  temp = []
  while now not in visited:
    nxt = P[now]
    visited.add(now)
    temp.append(C[nxt])
    now = nxt
  L.append(temp)
#print(L)
INF = float("inf")
ans = 0
for X in L:
  n = len(X)
  #print(X)
  Tree = SegmentTree(X, segfunc, 0)
  A = sum(X)
  T = [0 for _ in range(n+1)]
  for i in range(n+1): #i個選ぶ
    nokori = n-i
    temp = INF
    #print(i,nokori)
    for j in range(nokori+1):
      #print(j,j+i)
      tt = Tree.sum(j,j+i)
      #print(tt)
      temp = min(temp,tt)
    #print(temp)
    T[-1-i] = A-temp
    #print(T[i])
  if A <= 0:
    hani = min(K+1,N)
    tmp = max(T[:hani])
    ans = max(ans,tmp)
  else:
    hani = K%n+1
    loop = K//n
    #print(loop,T)
    tmp = max(T[:hani])+loop*A
    ans = max(ans,tmp)
print(ans)