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 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)
    # maxxans = max(maxxans, actualcircle*summ[i][-1])
    for krem in range(1, min(n-1, k)+1):
        cnt = len(lis[i])
        rem = krem%cnt
        for j in range(len(lis[i])):
            tot = summ[i][-1]
            tempans = tot*(krem//cnt)
            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])

    if actualcircle > 0:
        for krem in range(0, k%len(lis[i])+1):
            cnt = len(lis[i])
            rem = krem%cnt
            for j in range(len(lis[i])):
                tot = summ[i][-1]
                tempans = tot*actualcircle
                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:

def max2(x,y):
    return x if x > y else y

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

off = max(C)
m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    S = []
    k = 0
    visited = [-1]*N
    for r in range(N):
        S.append(C[l])
        visited[l] = r
        l = P[l] - 1
        if visited[l] != -1:
            k = r - visited[l] + 1
            break
    r += 1
    S1 = sum(S[r - k:])
    S2 = sum(S[:r - k])
    cnt = (K - (r - k)) // k - (K % k == 0)
    a = K%k + (K % k == 0)*k
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S1 > 0:
        m1 += cnt*S1 + S2
    m2 = max2(m1, m2)

print(m2)
"""
4 10
2 1 4 3
1 2 3 -1
"""

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
prev=[0 for i in range(N)]
for i in range(N):
    prev[P[i]-1]=i
DP=[[0 for j in range(N)] for i in range(N)]
start=[[0 for j in range(N)] for i in range(N)]
for j in range(N):
    DP[0][j]=C[j]
    start[0][j]=j
syuki=[N for j in range(N)]
for i in range(1,N):
    for j in range(N):
        DP[i][j]=DP[i-1][prev[j]]+C[j]
        start[i][j]=start[i-1][prev[j]]
        if start[i][j]==j:
            syuki[j]=min(syuki[j],i)
ite=[max(DP[syuki[j]-1][j],0) for j in range(N)]
dist=[0 for j in range(N)]
for i in range(N):
    for k in range(syuki[i]-1):
        dist[i]=max(dist[i],K//syuki[i]*ite[i]+DP[k][i]-C[i])
print(max(dist))

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 st in range(N):
  now = st+1
  temp=[0]
  while(P[now-1] != st+1):
    temp.append(temp[-1]+C[P[now-1]-1])
    now = P[now-1]
    temp.append(temp[-1]+C[P[now-1]-1])
    if len(temp)>=K+1:
      ans=max(ans, max(temp[1:K+1]))
      continue
    if temp[-1]<=0:
      ans = max(ans, (max(temp[1:])))
    elif K%(len(temp)-1)!=0:
      t=temp[-1]*(K//(len(temp)-1))
      t+=max(temp[:1+K%(len(temp)-1)])
      ans=max(ans, t)
    else:
      t=temp[-1]*(K//(len(temp)-1))-temp[-1]
      t+=max(temp)
      ans=max(ans,t)
		
print(int(ans))

Submission status: Wrong Answer

Solution code:
#import numpy as np
#import math
#from decimal import *
#from numba import njit

#@njit
def main():
    N,K = map(int, input().split())
    P = list(map(lambda s: int(s)-1, input().split()))
    C = list(map(int, input().split()))

    m = min(C)
    loop = [(-1,[]) for _ in range(N)]
    for i in range(N):
        if loop[i][0] == -1:
            n = i
            visited = [-1]*N
            c = 0
            S = []
            while visited[n] < 0:
                loop[n] = (0,0)
                visited[n] = c
                c += 1
                n = P[n]
                if len(S) == 0:
                    S += C[n],
                else:
                    S += (S[-1] + C[n]),
                
            p = n
            if visited[n] > 0:
                loopS = list(map(lambda a: a-S[visited[n]-1], S[visited[n]:]))
            else:
                loopS = S
            loop[p] = (len(loopS), loopS)
            p = P[p]
            c = 1
            while p != n:
                loopS = list(map(lambda a: a-loopS[0], loopS[1:])) + [loopS[-1]]
                loop[p] = (len(loopS), loopS)
                c += 1
                p = P[p]

        pre = 0
        n = i
        c = 0
        if loop[i][0] == 0:
            while loop[n][0] == 0 and c < K:
                pre += C[P[n]]
                m = max(m, pre)
                c += 1
                n = P[n]
        
        count = (K - c) // loop[n][0]
        rest = (K - c) % loop[n][0]
        l = loop[n][1][:rest]
        r = loop[n][1][rest:]
        if len(l) > 0:
            m = max(m, max(l)+loop[n][1][-1]*count + pre)
        if len(r) > 0:
            m = max(m, max(r)+loop[n][1][-1]*(count-1) + pre)

    print(m)

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

route = {}
point = {}

for idx, p in enumerate(P):
    route[idx+1] = p
    point[p] = C[p-1]

all_max = point[1]
for origin_start in range(1, N+1):
    visit = set()
    visit.add(origin_start)
    now_point = 0
    max_point = point[origin_start]
    start = origin_start
    # print(start)
    for k in range(K):
        now_point += point[start]
        max_point = max(max_point, now_point)
        start = route[start]
        if start in visit:
            break
        visit.add(start)
    # print(k, now_point, start, K % k)
    if now_point >= 0:
        now_point *= (K // (k+1))
        start = origin_start
        for k in range(K % (k+1)):
            now_point += point[start]
            max_point = max(max_point, now_point)
            start = route[start]
    # print(k, start, now_point)

    all_max = max(max_point, all_max)
print(all_max)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]

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

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)

        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

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

u = UnionFind(N)
for i in range(N):
    u.union(i,P[i]-1)

ans = max(C)
for i in range(N):
    s = i
    x = 0
    for j in range(min(N,K)):
        s = P[s]-1
        x += C[s]
        ans = max(ans,x)

for i in range(N):
    l = []
    for j in range(N):
        if u.find(i)==u.find(j):
            l.append(C[j])
    x = sum(l)*(K//len(l))
    for j in range(K%len(l)):
        s = P[s]-1
        x += C[s]
        ans = max(ans,x)

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 = -10**9-1
for i in range(N) :
    t = 1
    j = P[i]-1
    l = C[j]
    ans = max(ans,l)
    while j != i and K > t:
        j = P[j] - 1
        l += C[j]
        t += 1
        ans = max(ans,l)
    
    if l >= 0 and K > t :
        c = (K-t)//t 
        d = (K-t)%t
        l += l*c
        ans = max(ans,l)
        for _ in range(d) :
            j = P[j] - 1
            l += C[j]
            ans = max(ans,l)

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()))
    
    
max_value = -(10**10)
visited = []
C_got_list = []
for first_m in range(1, N+1):
  if first_m in visited:
    continue
  now_m = first_m
  C_got = []
  for i in range(N):
    now_m = P[now_m-1]
    C_got.append(C[now_m-1])
    visited.append(now_m)
    if now_m == first_m:
      break
  C_got_list.append(C_got)

for C_got in C_got_list:
  partial_max = -(10**10)
  max_mod = K % len(C_got)
  max_mod = len(C_got) if max_mod == 0 else max_mod
  for i in range(len(C_got)):
    C_got_circle = C_got[i:]+C_got[:i]
    for j in range(max_mod):
      partial_max = max(partial_max, sum(C_got_circle[:j+1]))
  sum_C = sum(C_got)
  if sum_C <= 0:
    max_value = max(max_value, partial_max)
  else:
    if K%len(C_got) == 0:
      max_value = max(max_value, (K // len(C_got)) * sum(C_got))
    else:
      max_value = max(max_value, (K // len(C_got)) * sum(C_got) + partial_max)
print(max_value)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
ap = list(map(int, input().split()))
cp = list(map(int, input().split()))

score = []

for m in range(n):
  p = m
  s = []
  ss = 0
  np = -1
  if cp[ap[p]-1] < 0:
    continue
  while np != m:
    np = ap[p]-1
    ss = ss + cp[np]
    p = np
    s.append(ss)
  score.append(s)

max_s = -(10**9)
for m in range(len(score)):
  loop = int((k - 1) / len(score[m]))
  sl = score[m][-1] * loop
  if sl < 0:
    sl = 0
  sm = score[m][0]
  y = k % len(score[m])
  if y == 0:
    y = len(score[m])
  for j in range(y):
    sm = max(sm, score[m][j])
  max_s = max(max_s, sm + sl)

print(max_s)

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 = -10000000000

if K <= N:
    for i in range(N):
        count = 0
        tmp_point = 0
        nv = i
        while count < K:
            nvv = P[nv]
            nvv -= 1
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
    print(ans)
else:
    loop = [0]*N
    for i in range(N):
        count = 0
        check = [False]*N
        tmp_point = 0
        nv = i
        while True:
            nvv = P[nv]
            nvv -= 1
            if check[nvv] == True:
                break
            check[nvv] = True
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
        loop[i] = [tmp_point, count, i]
    loop.sort(reverse=True)
    #print(loop)
    new_ans = -10000000
    for value, counter, key in loop:
        if value < 0:
            break
        shou = K//counter
        amari = K%counter
        tmp_ans = value*shou
        new_ans = max(new_ans, tmp_ans)
        count = 0
        nv = key
        while count < amari:
            nvv = P[nv]
            nvv -= 1
            tmp_ans += C[nvv]
            count += 1
            nv = nvv
            new_ans = max(new_ans, tmp_ans)
        
    #print(max(max(loop),ans , new_ans))
    print(max(loop[0][0], ans, new_ans))

Submission status: Wrong Answer

Solution code:
def get_max_sum(l):
    l2 = l + l
    _max = sum(l)
    for i in range(len(l)):
        for j in range(i + 1, len(l)+i+1):
            if _max < sum(l2[i:j]):
                _max = sum(l2[i:j])
    return _max

def get_max_subsum(l, n):
    l2 = l + l
    l2_sums = [sum(l2[i:i+n]) for i in range(len(l))]
    return max(l2_sums)


N, K = map(int, input().split())

Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

idx_list = []
score_list = []
flag = 0
for i in range(N):
    for item in idx_list:
       if i in item:
           flag = 1
    if flag == 1:
        flag = 0
        continue
    pos = i
    idxs = [pos]
    scores = [Cs[pos]]
    while not Ps[pos] - 1 in idxs:
        pos = Ps[pos] - 1
        idxs.append(pos)
        scores.append(Cs[pos])
    idx_list.append(idxs)
    score_list.append(scores)

max_val = max([sum(x) for x in score_list])
if max_val < 0:
    for item in score_list:
        if max_val < get_max_sum(item):
            max_val = get_max_sum(item)
    print(max_val)
else:
    positive_list = [x for x in score_list if sum(x) > 0]
    for item in positive_list:
        temp = sum(item)*(K//len(item)) + get_max_subsum(item, K % len(item))
        if temp > max_val:
            max_val = temp
    print(max_val)

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

p = [i-1 for i in p]
import numpy as np
tuuka_id = []

point_list = []

for mass in range(n):
  score = 0
  scorelist = []
  move_cnt = 0
  st_mass = mass
  if mass in tuuka_id:
    continue
  
  tuuka_id.append(mass)
  while True:
    mass = p[mass]
    #print(mass, c[mass])
    tuuka_id.append(mass)
    score += c[mass]
    scorelist.append( c[mass] )
    move_cnt += 1
    
    if mass == st_mass:
      break
  k_res = k % move_cnt
  if k_res == 0:
    k_res = move_cnt
    
  scorel2 = scorelist + scorelist

  res_val = max([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )])
  if k_res == 0:
    point = max(0, score * max(0,(k // move_cnt-1))) + res_val
  else:
    point = max(0, score * max(0,(k // move_cnt))) + res_val
  point_list.append( point )
print(max(point_list))

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 = -10000000

if K <= N:
    for i in range(N):
        count = 0
        tmp_point = 0
        nv = i
        while count < K:
            nvv = P[nv]
            nvv -= 1
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
    print(ans)
else:
    loop = [0]*N
    for i in range(N):
        count = 0
        check = [False]*N
        tmp_point = 0
        nv = i
        while True:
            nvv = P[nv]
            nvv -= 1
            if check[nvv] == True:
                break
            check[nvv] = True
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
        loop[i] = [tmp_point, count, i]
    loop.sort(reverse=True)
    #print(loop)
    new_ans = -10000000
    for value, counter, key in loop:
        if value < 0:
            break
        shou = K//counter
        amari = K%counter
        if amari == 0:
            new_ans = max(new_ans, value*shou)
            amari = counter
            shou -= 1
        tmp_ans = value*shou    
        new_ans = max(new_ans, tmp_ans)
        count = 0
        nv = key
        while count < amari:
            nvv = P[nv]
            nvv -= 1
            tmp_ans += C[nvv]
            count += 1
            nv = nvv
            new_ans = max(new_ans, tmp_ans)
        
    print(max(loop[0][0], ans, new_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) :
    t = 1
    j = P[i]-1
    l = C[j]
    ans = max(ans,l)
    while j != i and K > t:
        j = P[j] - 1
        l += C[j]
        t += 1
        ans = max(ans,l)
    
    if l >= 0 and K > t :
        c = (K-t)//t 
        d = (K-t)%t
        l += l*c
        ans = max(ans,l)
        for _ in range(d) :
            j = P[j] - 1
            l += C[j]
            ans = max(ans,l)

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

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
    extra = k - cnt
    nxt = p[nxt]
    if extra < cnt:
        for j in range(extra):
            score += c[nxt]
            ans = max(ans, score)
            #print("ans = ", ans, "score_tmp = ", score_tmp, "nxt = ", nxt, "c[nxt] = ", c[nxt])
            nxt = p[nxt]
    else:
        a = extra // cnt
        score += score * a
        ans = max(ans, score)
        for j in range(extra - a * cnt):
            score += c[nxt]
            ans = max(ans, score)
            nxt = p[nxt]

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

p = [i-1 for i in p]
#print(c,p)
import numpy as np
tuuka_id = []
pt_cycle = []

point_list = []

for mass in range(n):
  score = 0
  scorelist = []
  move_cnt = 0
  st_mass = mass
  if mass in tuuka_id:
    continue
  
  tuuka_id.append(mass)
  while True:
    mass = p[mass]
    #print(mass, c[mass])
    tuuka_id.append(mass)
    score += c[mass]
    scorelist.append( c[mass] )
    move_cnt += 1
    
    if mass == st_mass:
      pt_cycle.append([score, move_cnt, scorelist])
      break
  k_res = k % move_cnt
  
  scorel2 = scorelist + scorelist
  if k_res == 0:
    k_res = move_cnt
  res_val = max([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )])
  #print([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )])
  #print(max([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )]))
  #print( score, max(0,(k // move_cnt-1)), res_val)
  if k_res == 0:
    point = max(0, score * max(0,(k // move_cnt-1))) + res_val
  else:
    point = max(0, score * max(0,(k // move_cnt))) + res_val
  point_list.append( point )
print(max(point_list))

Submission status: Wrong Answer

Solution code:
import sys
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
last=k%n
by_last=k//n
sum1=sum(c)
cnt=sum1*by_last
if sum1<0:
  for i in range(n):
    ans=0
    nxt=i
    for j in range(n):
        nxt=p[nxt]-1
        ans+=c[nxt]
        cnt=max(ans,cnt)
  print(cnt)
  sys.exit()
else:
  for i in range(n):
    ans=sum1*by_last
    nxt=i
    for j in range(last):
      nxt=p[nxt]-1

      ans+=c[nxt]
      cnt=max(ans,cnt)
  print(cnt)

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

DP=[[C[P[n]]] for n in range(N)]

for start in range(N):
    visited=set()
    cur=P[start]
    while cur not in visited:
        visited.add(cur)
        cur = P[cur]
        DP[start].append(C[cur]+DP[start][-1])


for n in range(N):
    DP[n]=DP[n][:-1]

ans=-float("inf")

for start in range(N):
    #pattern1(先に進んでからloopする)
    tmp_max=-float("inf")
    tmp_idx=None

    for i in reversed(range(min(K,len(DP[start])))):
        if tmp_max<DP[start][i]:
            tmp_max=DP[start][i]
            tmp_idx=i


    K_=K-tmp_idx-1
    if K_>=len(DP[start]) and DP[start][-1]>0:
        loop_cnt=K_//len(DP[start])
        tmp_max+=loop_cnt*DP[start][-1]

    ans=max(ans,tmp_max)

    #pattern2(loopしてから余を加算
    if DP[start][-1]>0:
        if K>=len(DP[start]) and DP[start][-1]>0:
           loop_cnt=K//len(DP[start])
           tmp_max=loop_cnt*DP[start][-1]

        max_stop=0
        for i in range(K%len(DP[start])):
            max_stop=DP[start][i]
        tmp_max+=max_stop
        ans=max(ans,tmp_max)
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**20
for start in range(N):
    now = P[start]
    tmp = C[now]
    ans = max(ans, tmp)
    c = K-1
    k = 1
    kick = [tmp]
    step = None
    kick_tmp = None
    x = True
    if now == start:
        step = k
        kick_tmp = tmp
        x = False
    while c > 0 and k < N and x:
        now = P[now]
        tmp += C[now]
        ans = max(ans, tmp)
        c -= 1
        k += 1
        kick.append(tmp)
        if now == start:
            step = k
            kick_tmp = tmp
            break
    if step != None and K%step != 0:
        ans = max(ans, kick_tmp*(K//step)+max(kick[:K%step]))
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
P = [-1]+list(map(int,input().split()))
C = [-1]+list(map(int,input().split()))
visited = [True]+[False]*n
circles = []
for i in range(1,n+1):
    if not visited[i]:
        pre = i
        visited[i]=True
        s = [C[i]]
        while P[i] != pre:
            s.append(C[P[i]])
            visited[P[i]] = True
            i = P[i]
        circles.append((s,sum(s)))
# print(circles)
anslist = []

for ci in circles:
    ci_ans = 0
    if ci[1] > 0:
        ci_ans += ci[1]*(k//len(ci[0]))
    maxi = -10**9
    for start in range(len(ci[0])):
        ci2 = (ci[0]*2)[start:(start+len(ci[0]))]
        point = 0
        for i in range(min(k%len(ci[0]),len(ci[0]))):
            point += ci2[i]
            maxi = max(maxi,point)
    ci_ans += maxi
    anslist.append(ci_ans)
print(max(anslist))

Submission status: Wrong Answer

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

F=[0]*N
I=[0]*N
CN=[0]*N

for i in range(N):
  around=0
  cnt=0
  A=[]
  if F[i]==0:
    F[i]=1
    around+=1
    cnt+=C[i]
    nex=P[i]-1
    A.append(i)
    while F[nex]==0:
      A.append(nex)
      F[nex]=1
      around+=1
      cnt+=C[nex]
      nex=P[nex]-1
    for j in A:
      I[j]=around
      CN[j]=cnt
#print(F)
#print(I)
#print(CN)
ans=-(10**9)*2
for i in range(N):
  cnt=C[i]
  #動かす回数が一周に満たない時
  if K+1<I[i]:
    d=0
    nex=i
    for j in range(K+1):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  #動かす回数が一周を超えるとき
  elif CN[i]<0:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  else:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
    acnt=cnt
    bcnt=C[i]
    syuukai=(K+1)//I[i]
    nokori=(K+1)%I[i]
    syuukai-=1
    nokori+=I[i]
    bcnt+=syuukai*CN[i]
    d=0
    nex=i
    for j in range(nokori-1):
      d+=C[nex]
      nex=P[nex]-1
      bcnt=max(d,bcnt)
    cnt=max(acnt,bcnt)
  ans=max(ans,cnt)
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=-10**9

for i in range(1,n+1):
    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-1]
    
    if k<=co:
        ans=max(ans,max(x[j] for j in range(1,k+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:
n,k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))

tokuten = []
zan = p[:]
while len(zan) != 0:
    loop = []
    start = zan.pop()
    loop.append(c[start-1])
    next = p[start-1]
    zan.remove(next)
    while start != next:
        loop.append(c[next-1])
        next = p[next-1]
        if next in zan:
            zan.remove(next)
    tokuten.append(loop)

ans = -10e10
for loop in tokuten:
    tmp = 0
    le = len(loop)
    su = sum(loop)
    if le < k:
        if su > 0:
            tmp += (k//le)*su
            amari = k%le
            ma = -10e10
            lplp = loop + loop
            for i in range(1,amari+1):
                for j in range(1,le+1):
                    ma = max(ma,sum(lplp[j:j+i]))
            tmp += ma
            ans = max(ans,tmp)
        if su <= 0:
            ma = -10e10
            lplp = loop + loop
            for i in range(1,le+1):
                for j in range(1,le+1):
                    ma = max(ma,sum(lplp[j:j+i]))
            ans = max(ans,ma)
    else:
        ma = -10e10
        lplp = loop + loop
        for i in range(1,k+1):
                for j in range(1,le+1):
                    ma = max(ma,sum(lplp[j:j+i]))
        ans = max(ans,ma)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import collections as cl
import sys


def II():
    return int(sys.stdin.readline())


def MI():
    return map(int, sys.stdin.readline().split())


def LI():
    return list(map(int, sys.stdin.readline().split()))


def main():
    n, k = MI()
    p = LI()
    c = LI()

    hairetu = [[0] for i in range(n)]
    for i in range(n):
        next_idx = i + 1
        for times in range(1, n + 1):
            next_idx = p[next_idx - 1]
            hairetu[i].append(hairetu[i][times - 1] + c[next_idx - 1])
            if next_idx == i + 1:
                break

    lengths = [0] * n
    one_roop = list(map(lambda x: x[-1], hairetu))

    for i in range(n):
        lengths[i] = len(hairetu[i]) - 1

    maxs = list(map(lambda x: max(x, 0), one_roop))
    anss = [-1 * 10 ** 18]*n
    for i in range(n):
        length = lengths[i]
        amari = k % length
        shou = k // length
        maxs[i] = shou * maxs[i]

        for j in range(1, max(2, amari + 1)):
            anss[i] = max(maxs[i] + hairetu[i][j], anss[i])

    print(max(*anss))


main()