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:

from collections import defaultdict
INF = float('inf')
N, K = [int(x) for x in input().split()]
P = [0] + [int(x) for x in input().split()]
C = [0] + [int(x) for x in input().split()]

max_score = -INF
for init in range(1, N + 1):   # 初めの場所をiとする
    score = defaultdict(int)  # int/bool/list....
    # visited = defaultdict(init)  # int/bool/list....
    visited = [-1] * (N + 1)
    visited[init] = 0  # 何回移動後に着いたか？
    i = init
    max_init = -INF
    for k in range(1, K + 1):
        prev = i
        i = P[i]    # k回移動後に着くところ



        # if not visited[i]:
        if visited[i] < 0:  # まだ訪れてなかった
            visited[i] = k
            score[i] = score[prev] + C[i]
            max_init = max(max_init, score[i])
            continue

        loop_score = (score[prev] + C[i]) - score[i]
        loop_len = k - visited[i]

        score[i] = score[prev] + C[i]
        max_init = max(max_init, score[i])

        if k == K:
            break # これ以上移動できない

        start = i   # ループを開始するノード
        loop_num = (K - k) // loop_len # ループをあと何回回れるか
        loop_rem = (K - k) % loop_len

        if loop_rem == 0:
            loop_num -= 1
            loop_rem = loop_len

        jj = start
        temp = 0
        temp_max = 0
        for l in range(loop_rem):
            jj = P[jj]
            temp += C[jj]
            temp_max = max(temp_max, temp)

        # loop_max = temp_max + max(loop_num * loop_score, 0)
        loop_max = temp_max + loop_num * loop_score
        max_init = max(max_init, score[start] + loop_max)
        break

    max_score = max(max_score, max_init)

if max_score == -INF:
    max_score = max(C[1:])

print(max_score)

Submission status: Accepted

Solution code:
from itertools import accumulate
import sys
sys.setrecursionlimit(10**6)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

def dfs(G, v, p):
    seen[v] = True
    sc.append(c[v])

    for nv in G[v]:
        if nv == p:
            continue
        if seen[nv]:
            pos[0] = nv
            return

        dfs(G, nv, v)
        if pos[0] != -1:
            return


G = [[] for _ in range(n)]
for i in range(n):
    G[i].append(p[i]-1)

seen = [False]*n
ans = -float('inf')
for i in range(n):
    if seen[i] == False:
        pos = [-1]
        sc = []
        dfs(G, i, -1)

        if sc:
            sumsc = sum(sc)
            lenc = len(sc)
            for j in range(lenc):
                if j != 0:
                    sc = sc[1:] + [sc[0]]
                ac = list(accumulate(sc))
                
                if sumsc <= 0:
                    ans = max(ans, max(ac[:min(k, lenc)]))
                else:
                    if k%lenc == 0:
                        ans = max(ans, ac[-1]*(k//lenc - 1) + max(ac))
                    else:
                        ans = max(ans, ac[-1]*(k//lenc) + max(ac[:k%lenc]))
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))
INF = 10**18
ans = -INF
for i in range(N):
    arr = []
    tot = 0
    cnt = 0
    nex = i
    while cnt < K:
        nex = P[nex]
        tot += C[nex]
        arr.append(tot)
        cnt += 1
        if nex == i:
            break
    if cnt < K:
        cycle = cnt
        cycle_score = tot
        loop, amari = K//cycle, K%cycle
        for j in range(cycle):
            if j < amari:
                arr.append(cycle_score*loop+arr[j])
            else:
                arr.append(cycle_score*(loop-1)+arr[j])
    ans = max(ans, max(arr))
print(ans)

Submission status: Accepted

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

n, k = map(int, input().split())
parr = list(map(int, input().split()))
carr = list(map(int, input().split()))
scores = []

for i in range(n):
  cur = i
  # 1ループで通るノードの数とスコア
  roop_num = 0
  roop_score = 0
  while True:
    cur = parr[cur] - 1
    roop_num += 1
    roop_score += carr[cur]
    if cur == i:
      break
  tmp_max = -10**9
  # ループしたときにスコアが減るとき
  # kが1ループの回数より小さいとき
  if roop_score <= 0:
    score = 0
    max_iter = roop_num
  elif k <= roop_num:
    score = 0
    max_iter = k
  else:
    # ループする回数
    num = k // roop_num - 1
    score = roop_score*num
    max_iter = k - roop_num*num
  cur = i
  for _ in range(max_iter):
      cur = parr[cur] - 1
      score += carr[cur]
      if score > tmp_max:
        tmp_max = score
  scores += [tmp_max]

print(max(scores))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, k = LI()
p = LI()
c = LI()
C = []
S = []
for i in range(n):
    lst = [-1]*n
    cnt = 0
    idx = i
    s = 0
    while lst[idx] == -1:
        lst[idx] = cnt
        s += c[idx]
        cnt += 1
        idx = p[idx] - 1
    C.append(cnt)
    S.append(s)

if n >= k:
    ans = -10**10
    for i in range(n):
        cnt = 0
        ret = 0
        idx = p[i]
        while cnt < k:
            ret += c[idx-1]
            idx = p[idx-1]
            cnt += 1
            ans = max(ans, ret)
    print(ans)
else:
    ans = -10**10
    for i in range(n):
        if S[i] > 0:
            tmp = S[i] * (k // C[i])
            r = k % C[i]
            cnt = 0
            ret = 0
            idx = p[i]
            tmp -= S[i]
            r += C[i]
            while cnt < r:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, tmp + ret)
        else:
            cnt = 0
            ret = 0
            idx = p[i]
            while cnt < n:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, ret)
    print(ans)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def main():
    N, K = map(int, input().split())
    P = [0] + list(map(int, input().split()))
    C = [0] + list(map(int, input().split()))
    circle_scores = [0] * (N + 1)
    circle_times = [0] * (N + 1)

    checked = set()  # これがないと最悪O(N^2)になる。。。
    all_negative = True
    for i in range(1, N + 1):
        if i in checked: continue
        visited = set()
        now = i
        while now not in visited:
            visited.add(now)
            now = P[now]
            circle_scores[i] += C[now]
            circle_times[i] += 1
        for j in visited:
            circle_scores[j] = circle_scores[i]
            circle_times[j] = circle_times[i]
            checked.add(j)

    ans = max(C[1:])
    for i in range(1, N + 1):
        q, r = K // circle_times[i], K % circle_times[i]
        if q > 0: q, r = q - 1, r + circle_times[i]
        val = circle_scores[i] * q
        if circle_scores[i] <= 0:
            val = 0
            r = min(circle_times[i] - 1, K)
        now = P[i]
        add_val = C[now]
        add_max_val = C[now]
        for _ in range(r - 1):
            now = P[now]
            add_val += C[now]
            add_max_val = max(add_max_val, add_val)
        ans = max(ans, val + add_max_val)
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Accepted

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

N, K = map(int, input().split())
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))
ans = -float('inf')
for s in range(N):
    c = 0
    i = P[s]
    score = C[i]
    ans = max(ans, score)
    c += 1
    while i != s and c < K:
        i = P[i]
        score += C[i]
        ans = max(ans, score)
        c += 1
    if c == K or score <= 0:
        continue
    q = K // c
    score *= q - 1
    c *= q - 1
    while c < K:
        i = P[i]
        score += C[i]
        ans = max(ans, score)
        c += 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()))
ans = -10**9
for i in range(n):
    scores = [0]
    seen = set([i])
    now = i
    loop = False
    for _ in range(k):
        now = p[now]-1
        scores.append(c[now])
        if now in seen:
            loop = True
            break
        seen.add(now)
    for i in range(len(scores)-1):
        scores[i+1] += scores[i]
    tmp = max(scores[1:])
    ans = max(ans, tmp)
    if (not loop) or scores[-1]<=0:
        continue
    tmp = scores[-1]*(k//(len(scores)-1))
    rem = k%(len(scores)-1)
    tmp += max(scores[:rem+1])
    ans = max(ans, tmp)
    tmp = scores[-1]*(k//(len(scores)-1)-1)
    tmp += max(scores)
    ans = max(ans, tmp)
print(ans)

Submission status: Accepted

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

vis = [False] * N
ans = [-float('inf')] * N

for root in range(N):
    if vis[root]:
        continue
    vis[root] = True

    cycle = [root]
    costs = [C[root]]
    u = P[root]
    vis[u] = True
    while u != root:
        cycle.append(u)
        costs.append(C[u])
        u = P[u]
        vis[u] = True

    # print('-' * 10)
    # print(cycle)
    # print(costs)

    L = len(cycle)
    S = sum(costs)
    for i, v in enumerate(cycle):
        cnt = 0
        for step in range(1, min(L, K) + 1):
            cnt += costs[(i + step) % L]
            val1 = cnt
            val2 = cnt + (K - step) // L * S
            ans[v] = max(ans[v], val1, val2)

print(max(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**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(2*co)]
    for j in range(2*co-1):
        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[co]<=0:
            ans=max(ans,max(x[j] for j in range(1,co+1)))
        else:
            f=max(0,(k//co)-1)
            an+=x[co]*f
            s=k-f*co
            ans=max(ans,an+max(x[j] for j in range(1,s+1)))
            
            
            
            
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
D = [-1]*n
ans = -float("inf")
for i, p in enumerate(P):
    ans = max(ans, C[p])
    temp = p
    res = C[p]
    cnt = 1
    while temp != i and cnt < k:
        temp = P[temp]
        res += C[temp]
        cnt += 1
        ans = max(ans, res)
    D[i] = (cnt, res)
for i in range(n):
    a, b = D[i]
    ans = max(ans, b)
    if a == k:
        continue
    if b < 0:
        continue
    temp = b * (k//a-1)
    rest = k%a+a
    now = i
    for _ in range(rest):
        now = P[now]
        temp += C[now]
        ans = max(ans, temp)
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()))
seen = set()
circuits = []

for x in range(N):
    cir = []
    point = 0
    while True:
        if x in seen: 
            if cir != []: circuits.append((cir,point))
            break
        seen.add(x)
        point += C[x]
        cir.append(x)
        x = P[x] - 1
ans = -1000000000000
for x in circuits:
    tmp = 0
    if  K >= len(x[0]) * 2: 
        if x[1] > 0: tmp = (K // len(x[0]) - 1) * x[1]
        r = K % len(x[0]) + len(x[0])
    else:
        r = K
    for y in x[0]:
        tmp2 = 0
        for _ in range(r):
            y = P[y] - 1
            tmp2 += C[y]
            ans = max(ans, tmp + tmp2)
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

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]

# Pの要素の中で循環するモノ同士をまとめる
sep = []
visited = [0] * n
for i in range(n):
  s = i
  box = []
  while visited[s] == 0:
    box.append(s)
    visited[s] = 1
    s = P[s]
  if box != []:
    sep.append(box)

ans = - 10 ** 19
for sp in sep:
  SB = defaultdict(int)
  sumC = sum([C[i] for i in sp]) 
  sn = len(sp)

  if sumC > 0:
    d, mk = divmod(k, sn)
    if d > 0:
      pscore = (d - 1) * sumC
      mk += sn 
    else:
      pscore = 0
  else:
    mk = min(k, sn * 2)
    pscore = 0

  for p in sp: 
    cnt = 0
    score = 0
    mv = - 10 ** 19
    s = p
    while cnt < mk:
      score += C[s]
      s = P[s]
      cnt += 1
      mv = max(mv, score)
    
    SB[p] = mv

  ans = max(ans, max(SB.values()) + pscore)
  
print(ans)

Submission status: Accepted

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

ans = -10**29
for start in range(N):
    now = start
    point = 0
    for j in range(K):
        now = P[now]
        point += C[now]
        ans = max(ans, point)
        if now == start:
            break
    loop_cnt = j+1
    left_k = K - loop_cnt
    if point < 0: continue
    tmp = point
    point *= left_k // loop_cnt + 1
    point -= tmp
    ans = max(ans, point)
    for j in range(left_k%loop_cnt+loop_cnt):
        now = P[now]
        point += C[now]
        ans = max(ans, point)

print(ans)

Submission status: Accepted

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

pList = list(map(int,input().split()))

cList = list(map(int,input().split()))

cSum = sum(cList)
p = dict()
c = dict()

for i in range(n):
    p[i] = pList[i]
    c[i] = cList[i]

highScore = min(cList)
for i in range(n):
    count = 0
    zahyou = i
    score = 0
    zumi =zahyou
    loop = False
    while count < k:
        if not(loop):
            if zahyou == zumi and count != 0:
                loop = True
                if score > 0:
                    score += score * ((k // count) - 2)
                    count += ((k // count) - 2) * count
                else:
                    break
        zahyou = p[zahyou] - 1
        score += c[zahyou]
        count += 1
        if highScore < score:
            highScore = score

print(highScore)

Submission status: Accepted

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

ans=-float("inf")

for start in range(N):
    cur=P[start]
    scores=[C[cur]]
    for _ in range(K):
        if cur==start:
            break
        cur = P[cur]
        scores.append(C[cur]+scores[-1])


    
    #no_loop_sum= max(scores[:K])
    #remain_hops=K-scores.index(no_loop_sum)-1
    #if scores[-1]>0:
    #    loops=remain_hops//len(scores)
    #else:
    #    loops=0
    #ans=max(ans,no_loop_sum+scores[-1]*loops)

    
    for goal in range(len(scores)):
        no_loop_sum=scores[goal]
        remain_hops=K-goal-1
        #remain_hops=K-1

        if scores[-1]>0:
            loops=remain_hops//len(scores)
        else:
            loops=0
        ans=max(ans,no_loop_sum+scores[-1]*loops)
print(ans)

Submission status: Accepted

Solution code:
def roop(i,K):
    n=i
    ma=[-1]*N
    ma[n]=0
    point=0
    maxp=-10**30
    cnt=0
    isroop=False
    while cnt<K:
        cnt+=1
        n=P[n]
        point+=C[n]
        ma[n]=point
        maxp=max(maxp,point)
        if n==i:
            isroop=True
            break
    if not isroop:
        return maxp
    
    allpoint=(K//cnt)*point
    K%=cnt
    lastpoint=0
    j=0
    n=i
    lastp=0
    while(j<K):
       j+=1
       n=P[n]
       lastp+=C[n]
       lastpoint=max(lastpoint,lastp)
    return max([allpoint+lastpoint,allpoint-point+maxp,maxp])

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

ans=-10**30
for i in range(N):
    ans=max(ans,roop(i,K))
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
plst = list(map(int, input().split()))
clst = list(map(int, input().split()))
check = [False for _ in range(n)]
loop_s = []
for i in range(n):
    if check[i]:
        continue
    check[i] = True
    loop = []
    start = i
    while 1:
        loop.append(clst[i])
        i = plst[i] - 1
        check[i] = True
        if i == start:
            break
    loop_s.append(loop)

ans = -10 ** 20
for loop in loop_s:
    ans_tmp = 0
    l = len(loop)
    kk = k
    if l < k:
        ans_tmp = max(0, sum(loop) * (k // l - 1))
        kk = k % l + l
    tmp2 = -10 ** 20
    for i in range(l):
        tmp3 = 0
        for j in range(kk):
            pos = (i + j) % l
            tmp3 += loop[pos]
            tmp2 = max(tmp2, tmp3)
    ans = max(ans_tmp + tmp2, ans)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
from queue import deque
readline = sys.stdin.buffer.readline
from collections import Counter
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def accumurate(l):
    ret = [0] * len(l)
    ret[0] = l[0]

    for i in range(1, len(l)):
        ret[i] = ret[i - 1] + l[i]

    return ret


def main():

    n, k = geta(int)
    p = [0] + list(geta(int))
    c = [0] + list(geta(int))

    inf = 1 << 32

    used = [False] * (n + 1)
    ans = -inf

    for i in range(1, n + 1):

        if used[i]:
            continue
        else:
            used[i] = True

        c_loop = []
        j = p[i]
        c_loop += [c[j]]

        while j != i:
            used[j] = True
            j = p[j]
            c_loop += [c[j]]

        n_loop = len(c_loop)
        cs_loop = accumurate(c_loop + c_loop)
        tot_loop = cs_loop[n_loop - 1]

        _jmax = min(k, n_loop)

        for _i in range(n_loop):
            for _j in range(1, _jmax + 1):
                _tmp = cs_loop[_j + _i] - cs_loop[_i]

                if tot_loop > 0 and k > _j:
                    _tmp += (k - _j) // n_loop * tot_loop

                if ans < _tmp:
                    ans = _tmp

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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 = [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
  sc[0] = -1e20
  maxsc = max(maxsc, max(sc))
print(maxsc)

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):
    hoge = []
    p = i
    s = 0
    for j in range(K):
        p = P[p]-1
        s += C[p]
        hoge.append(s)
        ans = max(ans,s)
        if p == i:
            s *= (K-1)//len(hoge)
            s += max(hoge[0:(K-1)%len(hoge)+1])
            ans = max(ans,s)
            break
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
import sys

input = sys.stdin.buffer.readline

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

kouho = []

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

ans = -(10 ** 20)
for res, cnt, route in kouho:
    kaisu = min(k, cnt)
    temp2 = -(10 ** 20)
    route += route
    ACR = list(accumulate([0] + route))
    for shiten in range(cnt):
        for kosuu in range(1, kaisu + 1):
            temp3 = ACR[kosuu + shiten] - ACR[shiten]
            if res > 0 and k >= cnt:
                temp3 += (k - kosuu) // cnt * res
            temp2 = max(temp2, temp3)
    ans = max(ans, temp2)
    # print(ans)
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()))

frag, loop, lsum = set(), [], []
for i in range(n):
    if i in frag:
        continue
    now, tmpl, tmps = i, [], 0
    while (now not in frag):
        frag.add(now), tmpl.append(now)
        now = p[now] - 1
        tmps += c[now]
    else:
        loop.append(tmpl * 2)
        lsum.append(tmps)

lacc = []
for l in loop:
    tmp = [0]
    for li in l[1:]: 
        tmp.append(tmp[-1] + c[li])
    lacc.append(tmp)

ans = min(c)
for l, la, ls in zip(loop, lacc, lsum):
    llen = len(l) // 2
    for cnt in range(1, min(llen, k) + 1):
        for i in range(len(l) - cnt - 1):
            tmp = la[i + cnt] - la[i]
            tmp2 = ls * (k // llen - (cnt > k % llen))
            ans = max(ans, tmp, tmp + tmp2)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
from queue import deque
readline = sys.stdin.buffer.readline
from collections import Counter
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def accumurate(l):
    ret = [0] * len(l)
    ret[0] = l[0]

    for i in range(1, len(l)):
        ret[i] = ret[i - 1] + l[i]

    return ret


def main():
    n, k = geta(int)
    p = [0] + list(geta(int))
    c = [0] + list(geta(int))

    inf = 1 << 32

    used = [False] * (n + 1)

    ans = -inf

    for i in range(1, n + 1):

        if used[i]:
            continue
        else:
            used[i] = True

        c_loop = []
        j = p[i]
        c_loop += [c[j]]

        while j != i:
            used[j] = True
            j = p[j]
            c_loop += [c[j]]

        n_loop = len(c_loop)
        c_loop += c_loop
        cs_loop = accumurate(c_loop)
        tot_loop = cs_loop[n_loop - 1]

        _jmax = k if k < n_loop else n_loop

        _ans = -inf
        _len = 0
        for _i in range(n_loop):
            for _j in range(1, _jmax + 1):
                _tmp = cs_loop[_j + _i] - cs_loop[_i]

                if tot_loop > 0 and k > _j:
                    _tmp += (k - _j) // n_loop * tot_loop

                if _ans < _tmp:
                    _ans = _tmp

        if ans < _ans:
            ans = _ans

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

ans=-float("inf")

for start in range(N):
    cur=P[start]
    scores=[C[cur]]
    for _ in range(K):
        if cur==start:
            break
        cur = P[cur]
        scores.append(C[cur]+scores[-1])

    for goal in range(len(scores)):
        no_loop_sum=scores[goal]
        remain_hops=K-goal-1

        if scores[-1]>0:
            loops=remain_hops//len(scores)
        else:
            loops=0
        ans=max(ans,no_loop_sum+scores[-1]*loops)
print(ans)

Submission status: Accepted

Solution code:
def find(vals,l):
    ans = -float('inf')
    for i in range(len(vals)//2):
        curr = vals[i+l-1]
        if i-1 >= 0:
            curr -= vals[i-1]

        ans = max(ans,curr)

    #print(ans,l)
    return ans

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

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

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

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

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

        if total >= 0:
            max_val += ans-total

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

    return max(max_val,ans+val)

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

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

    print(ans)

main()

Submission status: Accepted

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

frag, loop, lcnt = set(), [], []
for i in range(n):
    if i in frag:
        continue
    now, tmpl, tmpc = i, [], 0
    while (now not in frag):
        frag.add(now), tmpl.append(now)
        now = p[now] - 1
        tmpc += c[now]
    else:
        loop.append(tmpl * 2)
        lcnt.append(tmpc)

lacc = []
for l in loop:
    tmp = [0]
    for li in l[1:]: 
        tmp.append(tmp[-1] + c[li])
    lacc.append(tmp)

ans = min(c)
for l, la, lc in zip(loop, lacc, lcnt):
    llen = len(l) // 2
    num = k % llen
    for cnt in range(1, min(llen + 1, k + 1)):
        for i in range(len(l) - cnt - 1):
            tmp = la[i + cnt] - la[i]
            tmp2 = tmp + lc * (k // llen - (cnt > num))
            ans = max(ans, tmp, tmp2)
print(ans)

Submission status: Accepted

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



def main():
    n, k = map(int, input().split())
    p = [int(x)-1 for x in input().split()]
    c = list(map(int, input().split()))
    
    doubling = [[0]*n for i in range(31)]
    doubling_max = [[0]*n for i in range(31)]
    place = [[0]*n for i in range(31)]
    
    ans = -1000000000
    for i in range(n):
        sub = c[p[i]]
        if sub >= 0:
            break
        if ans < sub:
            ans = sub
        if i == n-1:
            print(ans)
            sys.exit()
            
    
    for i in range(31):
        if i == 0:
            for j in range(n):
                doubling[i][j] = c[p[j]]
                place[i][j] = p[j]
            continue
        for j in range(n):
            place[i][j] = place[i-1][place[i-1][j]]
            doubling[i][j] = doubling[i-1][j]+doubling[i-1][place[i-1][j]]
    
    for i in range(31):
        if i == 0:
            for j in range(n):
                doubling_max[i][j] = doubling[i][j]
            continue
        for j in range(n):
            doubling_max[i][j] = max(doubling_max[i-1][j], doubling[i-1][j]+doubling_max[i-1][place[i-1][j]])
    
    ans = 0
    judge = []
    key = 0
    while k:
        if k%2:
            judge.append(key)
        k //= 2
        key += 1
    judge.reverse()
    
    for i in range(n):
        pl = i
        key = 0
        for j in range(len(judge)):
            if ans < key+doubling_max[judge[j]][pl]:
                ans = key+doubling_max[judge[j]][pl]
            key += doubling[judge[j]][pl]
            pl = place[judge[j]][pl]
        

    print(ans)
        
    


    
    
if __name__ == "__main__":
    main()