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: Accepted

Solution code:
#!/usr/bin/env python3
def main():
    N, K = map(int, input().split())
    P = [int(x) - 1 for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -10 ** 9
    for start in range(N):
        # ループを探索
        now = start
        cycle = []
        total = 0
        for _ in [0] * N:  # while Trueでもおｋ
            now = P[now]
            cycle.append(C[now])
            total += C[now]
            if now == start:
                break
        # 最大スコアを探索
        length = len(cycle)
        score = 0
        for move in range(length):
            score += cycle[move]
            # 移動回数 >= Kなら，ループ途中でも探索終了
            if move >= K:
                break
            # ループを周回するので，それを利用して探索を省略
            res = score
            if total > 0:
                laps = (K - (move + 1)) // length
                res += total * laps
            ans = max(ans, res)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    INF = 10**9
    n,k = map(int,input().split())
    P = [0] + list(map(int,input().split()))
    C = [0] + list(map(int,input().split()))

    scores = [0]*n

    for s in range(1,n+1):
        start = s
        dp = [-INF]*(n+1)
        dp[0] = 0
        for i in range(n):
            p = P[s]
            dp[i+1] = dp[i] + C[p]
            
            if start == p:
                break
            s = p
        if k <= i+1:
            scores[start-1] = max(dp[1:k+1])
        elif dp[i+1]<=0:
            scores[start-1] = max(dp[1:])
        else:
            r = k%(i+1)
            q = k//(i+1)
            if r>0:
                scores[start-1] = max(max(dp[1:r+1])+dp[i+1]*q, max(dp[1:]))
            else:
                scores[start-1] = dp[i+1]*(q-1)+max(dp[1:])

    print(max(scores))
main()

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18

for saisyo in range(1,n+1):
    tensuulist=[]
    genzaiti=saisyo

    while(True):
        genzaiti=p[genzaiti]
        tensuulist.append(c[genzaiti])
        if genzaiti==saisyo:
            break

    goukei=sum(tensuulist)
    nagasa=len(tensuulist)
    kaisuu=k
    syou=kaisuu//nagasa
    amari=kaisuu%nagasa

    tensuu=0
    nokorikaisuu=0

    if goukei<=0:
        for i in range(nagasa):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)
    else:
        if 3*nagasa<kaisuu:
            tensuu+=goukei*(syou-1)
            nokorikaisuu=nagasa+amari
            for i in range(nokorikaisuu):
                tensuu+=tensuulist[(i%nagasa)]
                ans=max(ans,tensuu)
        else:
            for i in range(kaisuu):
                tensuu+=tensuulist[(i%nagasa)]
                ans=max(ans,tensuu)

print(ans)

Submission status: Accepted

Solution code:
import sys
def main():
  input = sys.stdin.readline
  n, k = map(int , input().split())
  p_list = list(map(int, input().split()))
  c_list = list(map(int, input().split()))
  res = -float('inf')
  
  for s in range(n):
    S = []
    i = p_list[s] - 1
    S.append(c_list[i])
    while i != s:
      i = p_list[i]-1
      S.append(S[-1] + c_list[i])
    if k <= len(S):
      score = max(S[:k])
    elif S[-1] <= 0:
      score = max(S)
    else:
      score1 = S[-1] * (k//len(S) - 1)
      score1 += max(S)
      
      score2 = S[-1] * (k//len(S))
      r = k%len(S)
      if r!=0:
        score2 += max(0, max(S[:r]))
      score = max(score1, score2)
    res = max(res, score)
  print(res)
      

if (__name__=='__main__'):
  main()

Submission status: Accepted

Solution code:
from math import log2
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))

k-=1

m=int(log2(k)) if 1<k else 1
nxt=[[0]*n for _ in range(m+1)]
point=[[0]*n for _ in range(m+1)]
for i in range(n):
  p[i]-=1
  nxt[0][i]=p[i]
  point[0][i]=c[p[i]]
for j in range(m):
  for i in range(n):
    nxt[j+1][i]=nxt[j][nxt[j][i]]
    point[j+1][i]=point[j][i]+point[j][nxt[j][i]]
min_nk=min(n,k)
ans=-10**18
for s in range(n):
  pla=p[s]
  cur=c[pla]
  if ans<cur:
    ans=cur
  for _ in range(min_nk):
    pla=p[pla]
    cur+=c[pla]
    if ans<cur:
      ans=cur
  if n<k:
    pla=p[s]
    cur=c[pla]
    for i in range(m+1):
      if (k-n)&(1<<i):
        cur+=point[i][pla]
        pla=nxt[i][pla]
    res=cur
    for _ in range(n):
      pla=p[pla]
      cur+=c[pla]
      if res<cur:
        res=cur
    if ans<res:
      ans=res
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ans=-10**18
flag=dict()
for i in range(n):
    if i in flag:
        continue
    cur=i
    accum=[]
    flag[cur]=0
    s=0
    while flag[cur]<2:
        cur=p[cur]-1
        s+=c[cur]
        accum.append(s)
        if cur not in flag:
            flag[cur]=0
        else:
            flag[cur]+=1
    l=len(accum)//2
    accum=[0]+accum
    #print(accum)
    for x in range(1,l+1):
        if accum[x+l-1]-accum[x-1]<=0 or k//l<1:
            ans=max(ans,max(accum[x:x+min(k,l)])-accum[x-1])
        else:
            a=max(accum[x:x+l-1])-accum[x-1]
            d=accum[x+l-1]-accum[x-1]
            if k%l!=0:
                b=max(accum[x:x+k%l])-accum[x-1]
                ans=max(ans,max(k//l*d,k//l*d+b,(k//l-1)*d+a))
            else:
                b=max(accum[x:x+l-1])-accum[x-1]
                ans=max(ans,max(k//l*d,(k//l-1)*d+a))
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
from numba import njit

@njit('i8(i8,i8,i8[:],i8[:],i8)', cache=True)
def get_max_score(N, K, plist, slist, max_score):
    for start in range(N):

        total_score_in_loop = 0
        score_loop = []
        now = start
        while True:
            now = plist[now]
            total_score_in_loop += slist[now]
            score_loop.append(slist[now])
            if now == start:
                break
        
        rem_score, loop_score = 0, 0
        for idx in range(1, len(score_loop)+1):
            rem_score += score_loop[idx-1]
            if total_score_in_loop > 0:
                loop_score = ((K - idx) // len(score_loop)) * total_score_in_loop
            max_score = max(max_score, rem_score + loop_score)
    return max_score

def main():
    N, K = map(int, input().split())
    plist = np.array([i-1 for i in map(int, input().split())], dtype='int64')
    slist = np.array([i for i in map(int, input().split())], dtype='int64')
    max_score = -10**15
    max_score = get_max_score(N, K, plist, slist, max_score)
    print(max_score)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np
from numba import njit

@njit('i8(i8,i8,i8[:],i8[:],i8)', cache=True)
def main(N, K, plist, slist, max_score):
    for start in range(N):

        total_score_in_loop = 0
        score_loop = []
        now = start
        while True:
            now = plist[now]
            total_score_in_loop += slist[now]
            score_loop.append(slist[now])
            if now == start:
                break
        
        rem_score, loop_score = 0, 0
        for idx in range(1, len(score_loop)+1):
            rem_score += score_loop[idx-1]
            if total_score_in_loop > 0:
                loop_score = ((K - idx) // len(score_loop)) * total_score_in_loop
            max_score = max(max_score, rem_score + loop_score)
    return max_score


N, K = map(int, input().split())
plist = np.array([i-1 for i in map(int, input().split())], dtype='int64')
slist = np.array([i for i in map(int, input().split())], dtype='int64')
max_score = -10**15
max_score = main(N, K, plist, slist, max_score)
print(max_score)

Submission status: Accepted

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

ans = -10**18
for start in range(N):
    now = start
    cycle = [0]

    while True:
        now = P[now] - 1
        cycle.append(cycle[-1] + C[now])

        if now == start: break

    L = len(cycle)-1
    if cycle[-1] < 0 or K <= L:
        score = max(cycle[1:min(L+1,K)+1])
    else:
        score1 = cycle[-1]*(K//L) + max(cycle[:K%L+1])
        score2 = cycle[-1]*(K//L-1) + max(cycle)
        score = max(score1, score2)

    ans = max(ans, score)

print(ans)

Submission status: Accepted

Solution code:
(n,k),p,c,*a=[[*map(int,t.split())]for t in open(0)]
while n:
 n-=1;s,x,*l=0,n;f=j=k
 while f:x=p[x]-1;s+=c[x];l+=s,;f=x!=n
 for t in l[:k]:j-=1;a+=[t+j//len(l)*s*(s>0)]
print(max(a))

Submission status: Accepted

Solution code:
(n,k),p,c=[[*map(int,t.split())]for t in open(0)]
a=-9e9
while n:
 n-=1;s,x,*l=0,n;f=j=k
 while f:x=p[x]-1;s+=c[x];l+=s,;f=x!=n
 for t in l[:k]:j-=1;a=max(a,t+j//len(l)*s*(s>0))
print(a)

Submission status: Accepted

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


def solve(start):
    loop = []
    llen = 0
    lsum = 0
    reach = [0]*n

    now = start
    while True:
        nxt = P[now]-1
        loop.append(now)
        llen += 1
        lsum += C[now]
        reach[now] = 1
        if reach[nxt]:
            break
        now = nxt
    
    if lsum <= 0 or llen >= k:
        res = -10 ** 20
        s = 0
        now = start
        for i in range(min(llen, k)):
            s += C[now]
            res = max(res, s)
            now = P[now]-1
        return res
    else:
        s = lsum * (k // llen)
        now = start
        for i in range(k % llen):
            s += C[now]
            now = P[now]-1
        j = loop.index(now)
        res = -10**20
        for i in range(llen):
            j -= 1
            res = max(res, s)
            s -= C[loop[j]]
        return res


def solver():
    ans = -10 ** 20
    for i in range(n):
        ans = max(ans, solve(i))
    return ans


print(solver())

Submission status: Accepted

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
INF = 10**10
def main(N, K, P, C):
    ans = max(C)
    for i in range(N):
        used = [False] * N
        now = 0
        mx = -INF
        cnt = 0
        while True:
            if used[i] or cnt >= K:
                break
            used[i] = True
            i = P[i] - 1
            now += C[i]
            mx = max(mx, now)
            cnt += 1
        tmp = max(mx, now)
        if now > 0:
            cycle, mod = divmod(K, cnt)
            if cycle > 1:
                tmp = max(tmp, now * (cycle - 1) + mx)
            t = now * cycle
            tmp = max(tmp, t)
            for j in range(mod):
                i = P[i] - 1
                t += C[i]
                tmp = max(tmp, t)
        ans = max(ans, tmp)
    print(ans)

if __name__ == '__main__':
    input = sys.stdin.readline
    N, K = map(int, input().split())
    *P, = map(int, input().split())
    *C, = map(int, input().split())
    main(N, K, P, C)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys 
from itertools import accumulate
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N, K = map(int, readline().split())
P = [0] + list(map(int,readline().split()))
C = [0] + list(map(int,readline().split()))

ans = -10 ** 10
for i in range(1,N+1):
    l = 1
    j = P[i]
    s = C[j]
    ans = max(ans, s) #iを始まりとして
    while j != i:     # 1周期もしないときの最大値
        j = P[j]
        s += C[j]
        l += 1
        if K >= l:
            ans = max(ans, s)
    
    c = 1
    j = P[j]
    t = C[j]
    ans = max(ans, t + ((K - c) // l) * s) # 1回と周期分
    
    while j != i:
        j = P[j]
        t += C[j]
        c += 1
        if K >= c:
            ans = max(ans, t + ((K - c) // l) * s) # c回と周期分
print(ans)

Submission status: Accepted

Solution code:
import math


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N, K = read_ints()
    P = [p-1 for p in read_ints()]
    C = read_ints()

    max_score = -math.inf
    for i in range(N):
        cycle_score = C[i]
        scores = [0, C[i]]
        j = P[i]
        k = K
        while k > 1 and i != j:
            cycle_score += C[j]
            scores.append(cycle_score)
            j = P[j]
            k -= 1
        cycle_size = len(scores)-1
        cycle_count = K//cycle_size
        max_score = max(max_score, max(scores[1:]))
        if cycle_count != 0:
            max_score = max(max_score,
                            cycle_score*cycle_count+max(scores[:K%cycle_size+1]),
                            cycle_score*(cycle_count-1)+max(scores[1:]))
    return max_score


if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict #すべてのkeyが用意されてる defaultdict(int)で初期化
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal  #変換後の末尾桁を0や0.01で指定
  #Decimal((str(0.5)).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
from functools import lru_cache
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#ソート、"a"+"b"、再帰ならPython3の方がいい
#######ここから天ぷら########


n,k=map(int,input().split())
P=list(map(int,input().split()))
P=[i-1 for i in P]
C=list(map(int,input().split()))
ans=-inf
for i in range(n):
    now=i
    total=0
    roop= 0
    po=deque([0])
    for kai in range(1,k+1):
        now=P[now]
        total += C[now]
        roop+=1
        po.append(total)
        ans=max(ans, total)
        if now == i:
            la= kai;break

    else: continue
    if total<0 : continue
    po=list(po)
    ans=max(ans, total* (k//roop) + max(po[:k%roop+1]), total*(k//roop-1) + max(po))
    #print(total, roop,po ,ans)
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
 
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
cycles, check = [], [False]*n
for pi in p:
    if not check[pi-1]:
        curr, cycle = pi, []
        check[pi-1] = True
        while pi != p[curr-1]:
            check[curr-1] = True
            cycle.append(c[curr-1])
            curr = p[curr-1]
        check[curr-1] = True
        cycles.append(cycle + [c[curr-1]])
 
scores = []
for cycle in (np.array(cycle) for cycle in cycles):
    for i in range(cycle.size):
        cum = np.roll(cycle, i).cumsum()
        if cum[-1] > 0 and k > cycle.size:
            scores.append(cum[-1]*(k//cycle.size-1) + np.concatenate([cum, cum[:k % cycle.size]+cum[-1]]).max())
        else:
            scores.append(cum[:min(k, cum.size)].max())
print(max(scores))

Submission status: Accepted

Solution code:
import numpy as np


def parse():
    _, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    pc = {i: (pi - 1, ci) for i, (pi, ci) in enumerate(zip(p, c))}
    return k, pc


def read_split():
    k, pc = parse()
    lst = [[]]
    lst[0].append(pc.pop(0))
    while True:
        if not pc:
            break
        p, _ = lst[-1][-1]
        if p in pc:
            pcj = pc.pop(p)
            lst[-1].append(pcj)
        else:
            j = next(iter(pc.keys()))
            pcj = pc.pop(j)
            lst.append([pcj])
    return k, [np.array([ls[1] for ls in lst_], dtype=np.long) for lst_ in lst]


def inner(n, k, s, sim):
    if sim.shape[1] == 1:
        return sim.max()
    if k < n or s <= 0:
        return sim.max()
    div = k // n
    mod = k % n
    if mod == 0:
        return s * (div - 1) + sim.max()
    else:
        return s * div + sim[:, :mod].max()


def main():
    k, data_set = read_split()
    result = min([d.min() for d in data_set])
    for data in data_set:
        n = data.size
        rep = np.repeat(data[None], 2, axis=0).flatten()
        sim = np.array([np.cumsum(rep[i:i+min(k, n)]) for i in range(n)])
        cand = inner(n, k, data.sum(), sim)
        result = max(result, cand)
    print(result)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import numpy as np


def parse():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    pc = {i: (pi - 1, ci) for i, (pi, ci) in enumerate(zip(p, c))}
    return k, pc


def split_simple():
    k, pc = parse()
    lst = [[]]
    lst[0].append(pc.pop(0))
    while True:
        if not pc:
            break
        p, _ = lst[-1][-1]
        if p in pc:
            pcj = pc.pop(p)
            lst[-1].append(pcj)
        else:
            j = next(iter(pc.keys()))
            pcj = pc.pop(j)
            lst.append([pcj])
    return k, [np.array([ls[1] for ls in lst_], dtype=np.long) for lst_ in lst]


def inner(n, k, s, sim):
    # print(sim)
    # print(s)
    if sim.shape[1] == 1:
        return sim.max()
    if k < n or s <= 0:
        return sim.max()
    div = k // n
    mod = k % n
    # print(k, n, div, mod)
    if mod == 0:
        return max(s * div, s * (div - 1) + sim.max())
    try:
        return max(s * div + sim[:, :mod].max(), s * (div - 1) + sim[:, :mod].max())
    except ValueError:
        print(mod)
        print(sim)
        print(sim.shape)
        raise


def main():
    k, data_set = split_simple()
    result = min([d.min() for d in data_set])
    for data in data_set:
        n = data.size
        rep = np.repeat(data[None], 2, axis=0).flatten()
        # sim_ = np.array([[rep[i:i+p].sum()
        #                  for p in range(1, min(k, n) + 1)] for i in range(n)])
        sim = np.array([np.cumsum(rep[i:i+min(k, n)]) for i in range(n)])
        # print((sim == sim_).all())
        cand = inner(n, k, data.sum(), sim)
        result = max(result, cand)
    print(result)


if __name__ == "__main__":
    main()

Submission status: Accepted

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()))
PP=[0]*n
A=[0]*n
V=[0]*n
for i in range(n):
  if V[i]==1:
    continue
  B=[i]
  c=1
  j=i
  p=C[i]
  while P[j]!=i:
    j=P[j]
    B.append(j)
    c=c+1
    p=p+C[j]
  for j in B:
    A[j]=c
    PP[j]=p
ans=-10**10
for i in range(n):
  if PP[i]<0:
    aans=0
    f=0
  else:
    if k//A[i]-1>0:
      aans=(k//A[i]-1)*PP[i]
      f=1
    else:
      aans=0
      f=2
  l=i
  aaans=-10**10
  if f==0:
    for j in range(min(k,A[i])):
      aans=aans+C[P[l]]
      l=P[l]
      if aans>aaans:
        aaans=aans
  elif f==1:
    for j in range(k%A[i]+A[i]):
      aans=aans+C[P[l]]
      l=P[l]
      if aans>aaans:
        aaans=aans
  else:
    for j in range(min(k,2*A[i])):
      aans=aans+C[P[l]]
      l=P[l]
      if aans>aaans:
        aaans=aans
  if aaans>ans:
    ans=aaans
print(ans)

Submission status: Accepted

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 = int(-1e9)

for loop in loops:

    num = len(loop)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]
    ans_tmp = int(-1e9)
    sumL = sum(L)
    by_loop = max(sumL, 0) * div
    if k > num and sumL <= 0:
        r = num
    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] + by_loop)

    ans = max(ans, ans_tmp)
print(ans)

Submission status: Accepted

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

def main():
    N, K = map(int, input().rstrip().split())
    P = list(map(int, input().rstrip().split()))
    P = list(map(lambda x: x -1, P))
    C = list(map(int, input().rstrip().split()))
    ans = -10**18
    for i in range(N):
        x = i
        s = []
        total = 0
        while(True):
            x = P[x]
            s.append(C[x])
            total += C[x]
            if x == i:
                break
        l = len(s)
        t = 0
        for j in range(l):
            t += s[j]
            if j + 1 > K:
                break
            now = t
            if total > 0:
                e = (K - j - 1) // l
                now += total * e
            ans = max(ans, now)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

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)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]
    ans_tmp = 0 
    by_loop = max(sum(L), 0) * div
    if k>num and by_loop == 0:
      r = num
    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] + by_loop)
 
    ans = max(ans, ans_tmp)
if ans == 0:
    ans = max(C)
print(ans)

Submission status: Accepted

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


ps = list(map(int, input().split()))
cs = list(map(int, input().split()))

graphs = []
vGraphs = []
flags = [False]*n
sumDict = dict()
for i in range(len(ps)):
    p = ps[i]
    index = p - 1
    if flags[index]:
        continue

    current = set()
    values = set()
    currentIndex = index
    while True:
        if flags[currentIndex]:
            break

        current.add(currentIndex)
        values.add(cs[currentIndex])
        flags[currentIndex] = True
        nextIndex = ps[currentIndex] - 1
        currentIndex = nextIndex
    graphs.append(current)
    vGraphs.append(values)

answer = -float('inf')
for i in range(n):

    searchI = 0
    loopSum = 0
    nextIndex = i
    loopCount = 0
    while True:
        nextIndex = ps[nextIndex] - 1
        loopSum += cs[nextIndex]
        loopCount += 1
        if nextIndex == i:
            break

    total = loopSum

    currentSum = 0
    count = 0
    ci = i
    while True:
        count += 1
        if count > k:
            break
        loop = (k - count) // loopCount
        multi = max(0, total) * loop

        ci = ps[ci] - 1

        currentV = cs[ci]
        currentSum += currentV

        answer = max(answer, multi + currentSum)
        if ci == i:
            break

print(answer)

Submission status: Accepted

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)
    div = k // num
    r = k % num
    if r == 0:
        r = num
        div -= 1
    L = [C[p] for p in loop]
    ans_tmp = 0  
    sumL = sum(L)
    by_loop = max(sumL, 0) * div
    if k>num and sumL <= 0:
      r = num
    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] + by_loop)
 
    ans = max(ans, ans_tmp)
if ans == 0:
    ans = max(C)
print(ans)

Submission status: Accepted

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):
    score = []
    check = [0] * n
    now = i
    cycle = 0
    for _ in range(k):
        go = p[now] - 1
        if check[go] == 1:
            break
        now = go
        if len(score) == 0:
            score.append(c[now])
        else:
            score.append(score[-1] + c[now])
        check[now] = 1
        cycle += 1

    t = k // cycle
    m = k % cycle

    sum_cycle = score[-1]
    if m == 0:
        ans = max(sum_cycle * t, sum_cycle * (t - 1) + max(score), max(score), ans)
    else:
        ans = max(sum_cycle * t + max(score[:m]), sum_cycle * (t - 1) + max(score), max(score), ans)

print(ans)

Submission status: Accepted

Solution code:
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]

def f(v, K):
    if K == 0:
        return 0
    if max(v) < 0:
        return max(v)

    n = len(v)
    X = [0]
    for i in range(n):
        X.append(X[-1] + v[i])

    ans = -(10 ** 10)
    for i in range(n + 1):
        for j in range(i):
            if i - j > K:
                continue
            ans = max(ans, X[i] - X[j])
    return(ans)

X = [False for _ in range(N)]
ans = -(10 ** 10)

for i in range(N):
    if X[i]:
        continue
    t = i
    v = []
    while X[t] is False:
        X[t] = True
        v.append(C[t])
        t = P[t]

    n = len(v)
    if K > n:
        s = sum(v)
        x = f(v * 2, n)
        if s > 0:
            a = s * (K // n - 1) + max(s + f(v * 2, K % n), x)
        else:
            a = x
    else:
        a = f(v * 2, K)
    ans = max(a, ans)

print(ans)

Submission status: Accepted

Solution code:
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


X = [False for _ in range(N)]

V = []
for i in range(N):
    if X[i]:
        continue
    t = i
    v = []
    while X[t] is False:
        X[t] = True
        v.append(C[t])
        t = P[t]
    V.append(tuple(v))

def f(v, K):
    if K == 0:
        return 0
    if max(v) < 0:
        return max(v)
    n = len(v)

    X = [0]
    for i in range(n):
        X.append(X[-1] + v[i])
    ans = -100000000000
    for i in range(n + 1):
        for j in range(i):
            if i - j > K:
                continue
            ans = max(ans, X[i] - X[j])
    return(ans)

ans = -100000000000
for v in V:
    n = len(v)
    if K > n:
        s = sum(v)
        if s > 0:
            x = s * (K // n) + f(v * 2, K % n)
            y = s * (K // n - 1) + f(v * 2, n)
            a = max(x, y)
        else:
            a = f(v * 2, n)
    else:
        a = f(v * 2, K)
    ans = max(a, ans)

print(ans)

Submission status: Accepted

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

ans = -10**9-1
for i in range(N):
    seen = [-1]*N
    cumsum = [0]*(N+1)
    now = i
    j = 0
    while seen[now] == -1:
        seen[now] = 1
        now = P[now]
        cumsum[j+1] = cumsum[j] + C[now]
        j += 1
    loop_size = j
    if K <= loop_size:
        ans = max([ans] + cumsum[1:K+1])
    else:
        if cumsum[loop_size] > 0:
            loop_n = K//loop_size - 1
            cumsum2 = cumsum[0:loop_size+1] + [x + cumsum[loop_size] for x in cumsum[1:loop_size+1]]
            score = cumsum[loop_size]*loop_n + max(cumsum2[0:loop_size+K%loop_size+1])
            ans = max(ans, score)
        else:
            ans = max([ans] + cumsum[1:loop_size+1])
print(ans)

Submission status: Accepted

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

# Cを書き換える
C = [0] * N
for i in range(N):
    P[i] -= 1
    C[i] = _c[P[i]]

m = 31 # bit数

# ダブリング
vertex = list()
score = list()
vertex.append(P)
score.append(C)
for b in range(1, m+1):
    p_bth = [0] * N
    c_bth = [0] * N
    for i in range(N):
        p_bth[i] = vertex[b-1][vertex[b-1][i]]
        c_bth[i] = score[b-1][i] + score[b-1][vertex[b-1][i]]
    vertex.append(p_bth)
    score.append(c_bth)

# 桁DP
MIN = -(1 << 63) 
prv = [[MIN, 0] for _ in range(N)]
nxt = [[MIN, MIN] for _ in range(N)] 
for b in range(m, -1, -1):
    for i in range(N):
        if (K >> b) & 1:
            nxt[vertex[b][i]][0] = max(nxt[vertex[b][i]][0], prv[i][0] + score[b][i])
            nxt[vertex[b][i]][1] = max(nxt[vertex[b][i]][1], prv[i][1] + score[b][i])
            nxt[i][0] = max(nxt[i][0], prv[i][0], prv[i][1])
        else:
            nxt[vertex[b][i]][0] = max(nxt[vertex[b][i]][0], prv[i][0] + score[b][i])
            nxt[i][0] = max(nxt[i][0], prv[i][0])
            nxt[i][1] = max(nxt[i][1], prv[i][1])
    prv, nxt = nxt, prv

ans = max(max(x) for x in prv)
if ans == 0:
    ans = max(C)

print(ans)