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):
        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
        
        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 = [0] + list(map(int,input().split()))
c = [0] + list(map(int,input().split()))
maxsc = -1E20
for s in range(1,n+1):
  x = s
  sc = [-1E20]
  i = 0
  while i<k:
    x = p[x]
    sc.append(sc[i]+c[x])
    i += 1
    if x == s:
      loop = i
      loopsc = sc[i]
      if loopsc > 0:
        baseup = loopsc * int((k-i)/loop)
        for j in range(loop):
          sc[j+1] += baseup
        for j in range((k-i)%loop):
          sc[j+1] += loopsc
      i=k
  maxsc = max(maxsc, max(sc))
print(maxsc)

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 start in range(1, N+1):
    visit = set()
    visit.add(start)
    now_point = 0
    max_point = point[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))
        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:
from itertools import accumulate

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

P = [p-1 for p in P]

check = [False] * n
loops = []

for i in range(n):
    if check[i]:
        continue
    check[i] = True
    next = P[i]
    tmp = [i]
    while next != i:
        check[next] = True
        tmp.append(next)
        next = P[next]
    loops.append(tmp)


ans = 0

for loop in loops:

    num = len(loop)
    sho = k // num
    r = k % num
    if r == 0:
        r = num
        sho -= 1
    L = [C[p] for p in loop]

    ans_tmp = 0

    ryaku = 0
    if sum(L) > 0:
        ryaku = sum(L) * sho

    L += L[:r]
    ACC = [0] + list(accumulate(L))

    for i in range(num):
            for j in range(i+1, i+r+1):
                ans_tmp = max(ans_tmp, ACC[j]-ACC[i]+ ryaku)

    ans = max(ans, ans_tmp, ryaku)

if ans == 0:
    print(max(C))
    exit()
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]


                if ss > 0:
                    p = left // loop_size
                    q = left % loop_size
                    ans = max(ans, S[step] + ss * p + 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:
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))

has_visited = [False]*N
score_max = -float('inf')

for i in range(N):
    if has_visited[i]:
        continue
    
    loop_val = []

    j = i
    while True:
        loop_val.append(C[j])
        has_visited[j] = True
        j = P[j] - 1
        if loop_val[0] == C[j]:
            break

    loop_length = len(loop_val)

    sm = 0
    for p in range(loop_length):
        sm += loop_val[p]
    
    rem = [0]*(loop_length**2)

    for k in range(loop_length):
        rem[k*loop_length] = loop_val[k % loop_length]
        for l in range(1, K % loop_length):
            rem[k*loop_length+l] = loop_val[(k+l) % loop_length] + rem[k*loop_length+l-1]

    res = 0

    if sm >= 0:
        res = sm * (K // loop_length) + max(rem)
    else:
        res = max(rem)
    
    if res == 0:
        res = max(loop_val)
    
    if score_max < res:
        score_max = res

print(score_max)

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 = []
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 = max(c)
import itertools
for i in x:
    n = k//len(i)
    ind = k%len(i)
    ii = i+i
    r = list(itertools.accumulate(ii))
    a = max(0,r[len(i)-1]*n)
    for j in range(len(i)):
        for k in range(1,min(len(i),k+1)):
            s = r[j+k]-r[j]
            if k<ind+1:
                ans = max(ans,a+s)
            ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

Solution code:

n, k = map(int, input().split())
k = k
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[1:min(roop+1, k+1)])
        #print(a[1:min(roop+1, k+1)])

    else:
        if k%roop  == 0:
            ans[i] = max(s * (k // roop) , s * (k // roop - 1) + max(a))
        else:
            ans[i] = max(s * (k // roop) + max(a[:k % roop+1]), s * (k // roop - 1) + max(a))
            #print(a[:k % roop+1])
print(max(ans))

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 = 0
    k = 0
    visited = [-1]*N
    for j in range(N):
        S += C[l]
        visited[l] = j
        l = P[l] - 1
        if visited[l] != -1:
            k = j - visited[l] + 1
            break
    cnt = K // k - (K % k == 0)
    a = K%k + (K % k == 0)*k
    l = i
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S > 0:
        m1 += cnt*S
    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())
Ps = list(map(int, input().split()))
Ps = [P-1 for P in Ps]
Cs = list(map(int, input().split()))

Sss = [[0]*N for _ in range(K)]
Sss[0] = Cs
for i in range(1, K):
    X = 0
    for j in range(N):
        X = Ps[X]
        Sss[i][j] = Sss[i-1][j] + Cs[X]
    X += 1
print(max(map(max,Sss)))

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):
    route = set()
    start, val, val0, count = i, 0, -float('inf'), 0
    while not start in route and count < k:
        route.add(start)
        start = p[start]-1
        val += c[start]
        val0 = max(val, val0)
        count += 1
    ans = max(ans, val0)
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()))
vals = [0 for _ in range(n)]
vals2 = [0 for _ in range(n)]
routes = [0 for _ in range(n)]
counts = [0 for _ in range(n)]
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:
        route.add(start)
        start = p[start]-1
        val += c[start]
        val0 = max(val, val0)
        count += 1
    vals[i] = val
    vals2[i] = val0
    counts[i] = count

for i in range(n):
    val = vals[i]*(k//counts[i])
    val0 = -float('inf')
    start = i
    for j in range(k%counts[i]):
        start = p[start]-1
        val += c[start]
        val0 = max(val, val0)
    ans[i] = max(val, vals2[i], val0)
print(max(ans))

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してから余を加算
    tmp_max=-float("inf")

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

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]
    d=0
    nex=i
    for j in range(nokori-1):
      d+=C[nex]
      nex=P[nex]-1
      bcnt=max(d,bcnt)
    bcnt+=syuukai*CN[i]
    cnt=max(acnt,bcnt)
  ans=max(ans,cnt)
print(ans)

Submission status: Wrong Answer

Solution code:
def resolve():
    n, k = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    P = list(map(lambda x: x - 1, P))
    score = -10**16
    for i in range(n):
        p_back = []
        s_back = []
        keiro = []
        x = i
        s = 0
        for j in range(k):
            keiro.append(x)
            p_back.append(C[x])
            s += C[P[x]]
            s_back.append(s)
            x = P[x]
            if x in keiro:
                b = sum(p_back)
                if b > 0:
                    s = max(s_back)
                    idx = s_back.index(s)
                    s += b * ((k - idx - 1) // len(keiro))
                    if s > score:
                        score = s
                else:
                    if max(s_back) > score:
                        score = max(s_back)
                break

    print(score)

resolve()

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
r=min(c)
for i in range(n):
	q=i
	s=0
	d=[0]*n
	for j in range(min(n,k)):
		q=p[q]-1
		s+=c[q]
		d[j]=s
		if s>r:r=s
	l=k//n
	if l>1:r+=l*max(0,max(d))
print(r)

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()))
maxsc = 0
for s in range(1,n+1):
  x = s
  sc = [0]
  i = 0
  while i<k:
    x = p[x]
    sc.append(sc[i]+c[x])
    i += 1
    if x == s:
      loop = i
      loopsc = sc[i]
      if loopsc > 0:
        baseup = loopsc * int((k-i)/loop)
        for j in range(loop):
          sc[j+1] += baseup
        for j in range((k-i)%loop):
          sc[j+1] += loopsc
      i=k
  maxsc = max(maxsc, max(sc))
print(maxsc)

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 >= 2 * 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 + loop_length
    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:
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:
    weight = weight[:K]
    tmp = 0
    for j in range(K-1):
      weight[j+1] += weight[j]
    tmp = max(weight)
    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)
      ans = max(ans, tmp)
print(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 K <= n: #一周もしない
    hani = K+1
    tmp = max(T[:hani])
    ans = max(ans,tmp)
  elif A <= 0: #一周はするがすると損
    #hani = n+1
    tmp = max(T)
    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:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
l = []
ans = []
for i in range(n):
    l.append(c[p[i]-1])
    x = p[i]-1
    while x != i and len(l) < k:
        l.append(l[-1] + c[p[x]-1])
        x = p[x]-1
    if len(l) < k:
        l.append(l[-1] + c[p[x]-1])
        x = p[x]-1
    y = len(l)
    while len(l) < y*10 and len(l) < k:
        l.append(l[-1] + c[p[x]-1])
        x = p[x] - 1
    ans.append(max(l))
    l = []
print(max(ans))

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
  while np != m:
    np = ap[p]-1
    ss = ss + cp[np]
    p = np
    s.append(ss)
  score.append(s)
print(score)

max_s = -(10**9)
for m in range(n):
  loop = int(k / len(score[m]))
  sl = score[m][-1] * loop
  if sl < 0:
    sl = 0
  sm = score[m][0]
  y = k % 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 = [int(n) for n in input().split(" ")]
Ps = [int(n) for n in input().split(" ")]
Cs = [int(n) for n in input().split(" ")]
#"""
"""
N = 10
K = 58345
Ps = [9, 1, 6, 7, 8, 4, 3, 2, 10, 5]
Cs = [695279662, 988782657, -119067776, 382975538, -151885171, -177220596, -169777795, 37619092, 389386780, 980092719]
"""
"""
N = 3
K = 3
Ps = [3, 1, 2]
Cs = [-1000,-2000,-3000]
"""

circles = []
already = {}
for p in range(N):
    if p not in already:
        tmp = []
        nowp = p
        while nowp not in tmp:
            tmp.append(nowp)
            already[nowp] = 1
            nowp = Ps[nowp] - 1
        circles.append(tmp)

#print(circles)

finalResult = -100000000000

def getCircleScore(circle, start, kk):
    #print(circle, start, kk)
    s = 0
    for k in range(kk):
        index = start + k
        if index >= len(circle):
            index = index % len(circle)
        s += Cs[circle[index]]
    return s

"""
maxCircle = []
maxCircleScore = -10000000000
maxIndex = 0
for circle in circles:
    CircleSum = sum([Cs[n] for n in circle])
    if maxCircleScore <= CircleSum:
        maxCircleScore = CircleSum
        maxCircle = circle
"""
#for circle in [maxCircle]:
for circle in circles:
    
    CircleSum = sum([Cs[n] for n in circle])
    #print(circle, CircleSum)
    score = 0
    if CircleSum > 0:
        score = K // len(circle) * CircleSum

    K = K % len(circle)
    if K == 0:
        K = len(circle)

    maxScore = -100000000000
    for start in range(len(circle)):
        #print("start", start)
        for kk in range(1, K+1):
            s = getCircleScore(circle, start, kk)
            #print(s)
            if maxScore <= s:
                maxScore = s

    final = score + maxScore

    if final >= finalResult:
        finalResult = final

print(finalResult)

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 >= 2 * 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:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    slow = s
    fast = s
    counter = 0
    for _ in range(N):
        slow = P[slow]
        fast = P[P[fast]]
        counter += 1
        if slow == fast:
            break
    # counter = m = lambda + k * myu
    # m = lambda(開始地点) +(m - lambda)
    # lambda進むとmyuの定数倍のmがlambdaから進んだ事になるのでそこがスタート地点
    # get lambda
    slow2 = slow
    slow_start = s
    counter = 0
    for _ in range(K):
        slow2 = P[slow2]
        slow_start = P[slow_start]
        counter += 1
        if slow2 == slow_start:
            break
    lam = counter
    slow3 = slow
    counter = 0
    for _ in range(K):
        slow3 = P[slow3]
        counter += 1
        if slow3 == slow:
            break
    myu = counter
    return (lam, myu)

maxsum = -10 ** 10
for s in range(N):
    lam, myu = f(s)
    tmpmaxs = -10 ** 10
    tmp = s
    tmpsum = 0
    for _ in range(K%myu):
        tmpsum += C[tmp]
        if tmpsum > tmpmaxs:
            tmpmaxs = tmpsum
        if tmpsum < 0:
            tmpsum = 0
        tmp = P[tmp]
    # tmpmaxsは循環しない時の最大値
    tmp = s
    cirsum = 0
    for _ in range(myu):
        cirsum += C[tmp]
        tmp = P[tmp]
    tot = 0
    if cirsum < 0:
        tot = tmpsum
    else:
        tot = tmpsum + (cirsum) * (K//myu)
    if maxsum < tot:
        maxsum = tot

print(maxsum)