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:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
dic = {}
for i in range(1, n+1):
  dic[i] = [p[i-1], c[i-1]]
INF = 10**20
ans = -INF
for j in range(1, n+1):
  state = [True] * 5001
  max_score = -INF
  max_idx = 0
  score = 0
  now = dic[j][0]
  cnt = 0
  lst = []
  flg = True
  for _ in range(k):
    if not state[now]:
      flg = False
      break
    score += dic[now][1]
    cnt += 1
    if max_score < score:
      max_score = score
      max_idx = cnt
    lst.append(score)
    state[now] = False
    now = dic[now][0]
  if score <= 0 or flg:
    ans = max(max_score, ans)
  else:
    q = k // cnt
    r = k % cnt
    if r >= max_idx:
      x = score * q + max_score
      ans = max(ans, x)
    else:
      if q >= 1:
        if r == 0:
          x = score * (q - 1) + max_score
          ans = max(ans, x)
        else:
          x = score * (q - 1) + max_score
          y = score * q + max(lst[:r])
          ans = max(ans, x, y)
      else:
        ans = max(ans, max_score)
print(ans)

Submission status: Accepted

Solution code:
n, k = list(map(int, input().split()))
# 先頭に0番要素を追加すれば、配列の要素番号と入力pが一致する
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))

ans = -float('inf')
# 開始ノードをsi
for si in range(1, n+1):

    # 閉ループのスコアを取り出す
    x = si
    s = list()  # ノードの各スコアを保存
    #s_len = 0
    tot = 0     # ループ1周期のスコア
    while 1:
        x = p[x]
        s.append(c[x])
        #s[s_len] = c[x]
        #s_len += 1
        tot += c[x]
        if (x == si): break # 始点に戻ったら終了
    
    # siを開始とする閉ループのスコア(s)を全探
    s_len = len(s)
    t = 0
    for i in range(s_len):
        t += s[i]   # i回移動したときのスコア
        if (i+1 > k): break # 移動回数の上限を超えたら終了
        # 1周期のスコアが正ならば、可能な限り周回する
        if tot > 0:
            e = (k-(i+1))//s_len # 周回数
            now = t + tot*e      # i回移動と周回スコアの合計
        else:
            now = t
        ans = max(ans, now)

print(ans)

Submission status: Accepted

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

# D - Moving Piece
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

# 問題文とインデックスの位置を揃える
P.insert(0, 0)
C.insert(0, 0)

# マス目を周期ごとに分割する
groups = []
appeared = set()

for i in range(1, N + 1):
	if not i in appeared:
		group = []
		s = set()
		j = i

		while not j in s:
			group.append(j)
			s.add(j)
			appeared.add(j)
			j = P[j]

		groups.append(group)

minus_max = -sys.maxsize
ans = minus_max

# 周期ごとにハイスコアを算出
for group in groups:
	n = len(group)

	# スタート位置を1マスずつズラす
	for g in group:
		score = 0
		max_score = minus_max
		scores = []
		scores.append(minus_max)
		Pi = P[g]

		for j in range(n):
			score += C[Pi]
			max_score = max(max_score, score)
			scores.append(max_score)
			Pi = P[Pi]

		if K > n and score > 0:
			s = scores[K % n] + score * (K // n)
			ans = max(ans, s)

			s = scores[n] + score * (K // n - 1)
			ans = max(ans, s)
		elif K > n:
			ans = max(ans, scores[n])
		else:
			ans = max(ans, scores[K])

print(ans)

Submission status: Accepted

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

# D - Moving Piece
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

# 問題文とインデックスの位置を揃える
P.insert(0, 0)
C.insert(0, 0)

# マス目を周期ごとに分割する
groups = []
appeared = set()

for i in range(1, N + 1):
	if not i in appeared:
		group = []
		s = set()
		j = i

		while not j in s:
			group.append(j)
			s.add(j)
			appeared.add(j)
			j = P[j]

		groups.append(group)

MIN = -sys.maxsize
ans = MIN

# 周期ごとにハイスコアを算出
for group in groups:
	n = len(group)

	# スタート位置を1マスずつズラす
	for g in group:
		score = 0
		max_score = MIN
		scores = []
		scores.append(MIN)
		Pi = P[g]

		for j in range(n):
			score += C[Pi]
			max_score = max(max_score, score)
			scores.append(max_score)
			Pi = P[Pi]

		if K > n and score > 0:
			s = scores[K % n] + score * (K // n)
			ans = max(ans, s)

			s = max_score + score * (K // n - 1)
			ans = max(ans, s)
		elif K > n:
			ans = max(ans, max_score)
		else:
			ans = max(ans, scores[K])

print(ans)

Submission status: Accepted

Solution code:
#! /usr/bin/env python3
import sys
sys.setrecursionlimit(10**9)


INF=10**20
def solve(N: int, K: int, P: "List[int]", C: "List[int]"):
    ans = -INF
    for i in range(N):
        start = i + 1 
        stack = [start]
        score_his = [0]
        scores = 0
        depth = 1
        seen = {}
        while stack:
            if depth > K: break
            current = stack.pop()
            
            if current in seen:
                loop_start_depth = seen[current]
                loop_end_depth = depth - 1 
                loop_scores = score_his[-1] - score_his[loop_start_depth-1]
                loop_len = loop_end_depth - loop_start_depth + 1
                if loop_scores < 0: break
 
                # print(start,score_his)
                # print(loop_start_depth,loop_end_depth,loop_scores,loop_len)
                
                rest_count = K - depth + 1
                available_loop_count = rest_count // loop_len
                res1 = (available_loop_count-1) * loop_scores + scores
 
                # print("a",rest_count,available_loop_count,res1)
                
                res2 = res1
                rest_loop_len = rest_count % loop_len + loop_len
 
                # print("b",rest_loop_len)
                ress = [res1,res2]
                for j in range(rest_loop_len):
                    score = C[P[current-1]-1]
                    res2 += score
                    ress.append(res2)
                    current = P[current-1]
 
                # print("ress",ress)
                score_his.append(max(ress))
 
                break
 
            
            score = C[P[current-1]-1]
            scores += score
            score_his.append(scores)
 
            seen[current] = depth
            stack.append(P[current-1])
 
            depth += 1
        
        ans = max(ans,max(score_his[1:]))
    
    print(ans)
 
 
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    C = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, P, C)



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

g = [v for v in range(n + 1)]
s = [0] * (n + 1)
r = [0] * (n + 1)
seen = set()
for i in range(1, n + 1):
    if i in seen:
        s[i] = s[g[i]]
        r[i] = r[g[i]]
        continue
    ni = i
    sm = 0
    cnt = 0
    while True:
        ni = p[ni]
        sm += c[ni]
        cnt += 1
        g[ni] = i
        seen.add(ni)
        if ni == i:
            break
    s[i] = sm
    r[i] = cnt

ans = -(10 ** 9 + 1)
for i in range(1, n + 1):
    ni = i
    sm = 0
    cnt = 0
    while True:
        ni = p[ni]
        sm += c[ni]
        cnt += 1
        ans = max(ans, sm, sm + (k - cnt) // r[i] * s[i])
        if ni == i or cnt == k:
            break
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from collections import defaultdict

sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


def debug(*x):
    print(*x, file=sys.stderr)


def solve(N, K, PS, CS):
    PS = [x - 1 for x in PS]
    CS = [CS[PS[i]] for i in range(N)]
    visited = {}
    loops = []
    loopScore = []
    for i in range(N):
        loop = []
        c = 0
        while i not in visited:
            visited[i] = True
            c += CS[i]
            i = PS[i]
            loop.append(i)
        if loop:
            loops.append(loop)
            loopScore.append(c)

    pos = list(range(N))
    ret = -INF
    for i, loop in enumerate(loops):
        if loopScore[i] > 0:
            baseScore = loopScore[i] * (K // len(loop))
            r = K % len(loop)
            if r == 0:
                r = len(loop)
                baseScore -= loopScore[i]
            maxscore = 0
            scores = defaultdict(int)
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores.values()))
            ret = max(maxscore + baseScore, ret)
        else:
            r = len(loop)
            maxscore = -INF
            scores = defaultdict(int)
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores.values()))
            ret = max(maxscore, ret)

    return ret


def main():
    # parse input
    N, K = map(int, input().split())
    PS = list(map(int, input().split()))
    CS = list(map(int, input().split()))
    print(solve(N, K, PS, CS))


# tests
T1 = """
5 2
2 4 5 1 3
3 4 -10 -8 8
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
8
"""

T2 = """
2 3
2 1
10 -7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
13
"""

T3 = """
3 3
3 1 2
-1000 -2000 -3000
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1000
"""

T4 = """
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
29507023469
"""

T5 = """
3 1000
2 3 1
1 0 2
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
1001
"""

T6 = """
3 1000
2 3 1
1 1 -3
"""
TEST_T6 = """
>>> as_input(T6)
>>> main()
2
"""

T7 = """
4 1000
2 1 4 3
1 1 -10000 10000
"""
TEST_T7 = """
>>> as_input(T7)
>>> main()
10000
"""

T8 = """
4 1000
2 1 4 3
1 1 -10000 10001
"""
TEST_T8 = """
>>> as_input(T8)
>>> main()
10500
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


def debug(*x):
    print(*x, file=sys.stderr)


def solve0(N, K, PS, CS):
    PS = [x - 1 for x in PS]
    debug(": PS", PS)
    CS = [CS[PS[i]] for i in range(N)]
    PSS = [PS]
    CSS = [CS]
    prevPS = PS
    prevCS = CS
    for i in range(30):
        PS2 = [prevPS[prevPS[i]] for i in range(N)]
        CS2 = [prevCS[i] + prevCS[prevPS[i]] for i in range(N)]
        PSS.append(PS2)
        CSS.append(CS2)
        prevPS = PS2
        prevCS = CS2

    score = [0] * N
    pos = list(range(N))
    length = [0] * N
    maxbit = K.bit_length() - 1
    for i in range(maxbit, -1, -1):
        # debug(": i", i)
        # debug(": 2**i", 2**i)
        # debug(": CSS[i]", CSS[i])
        # debug(": PSS[i]", PSS[i])
        # debug(": score", score)
        # debug(": length", length)
        for j in range(N):
            # debug(": length[j] + 2 ** i <= K", length[j] + 2 ** i <= K)
            # debug(": CSS[i][pos[j]]", CSS[i][pos[j]])
            if length[j] + 2 ** i <= K and CSS[i][pos[j]] > 0:
                # debug("add: j", j)
                score[j] += CSS[i][pos[j]]
                pos[j] = PSS[i][pos[j]]
                length[j] += 2 ** i
            # if CSS[i][j] > score[j]:
            #     # debug("reset: j", j)
            #     # debug(": CSS[i][i], score[j]", CSS[i][i], score[j])
            #     pos[j] = PSS[i][j]
            #     score[j] = CSS[i][j]
            #     length[j] = 2 ** i

    # debug("finish: score", score)
    ret = max(score)
    if ret == 0:
        ret = max(CS)
    return ret


def solve(N, K, PS, CS):
    PS = [x - 1 for x in PS]
    CS = [CS[PS[i]] for i in range(N)]
    visited = {}
    loops = []
    loopScore = []
    for i in range(N):
        loop = []
        c = 0
        while i not in visited:
            visited[i] = True
            c += CS[i]
            i = PS[i]
            loop.append(i)
        if loop:
            loops.append(loop)
            loopScore.append(c)
    # debug(": loops", loops)
    # debug(": loopScore", loopScore)
    scores = [0] * N
    pos = list(range(N))
    from collections import defaultdict

    ret = 0
    for i, loop in enumerate(loops):
        if loopScore[i] > 0:
            baseScore = loopScore[i] * (K // len(loop))
            r = K % len(loop)
            if r == 0:
                r = len(loop)
                baseScore -= loopScore[i]
                # debug("r==0: baseScore", baseScore)
            maxscore = 0
            scores = defaultdict(int)
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores.values()))
                # debug("posi: maxscores", scores)
            ret = max(maxscore + baseScore, ret)
        else:
            r = len(loop)
            maxscore = -INF
            scores = defaultdict(int)
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                # debug("neg: scores", scores)
                maxscore = max(maxscore, max(scores.values()))
            ret = max(maxscore, ret)

    if ret == 0:
        ret = max(CS)
    return ret


def main():
    # parse input
    N, K = map(int, input().split())
    PS = list(map(int, input().split()))
    CS = list(map(int, input().split()))
    print(solve(N, K, PS, CS))


# tests
T1 = """
5 2
2 4 5 1 3
3 4 -10 -8 8
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
8
"""

T2 = """
2 3
2 1
10 -7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
13
"""

T3 = """
3 3
3 1 2
-1000 -2000 -3000
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1000
"""

T4 = """
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
29507023469
"""

T5 = """
3 1000
2 3 1
1 0 2
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
1001
"""

T6 = """
3 1000
2 3 1
1 1 -3
"""
TEST_T6 = """
>>> as_input(T6)
>>> main()
2
"""

T7 = """
4 1000
2 1 4 3
1 1 -10000 10000
"""
TEST_T7 = """
>>> as_input(T7)
>>> main()
10000
"""

T8 = """
4 1000
2 1 4 3
1 1 -10000 10001
"""
TEST_T8 = """
>>> as_input(T8)
>>> main()
10001
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()

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
    loop = accum[l-1]
    accum=[0]+accum
    for x in range(1,l+1):
        if loop<=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 sys
readline = sys.stdin.readline

def solve():
    N, K = map(int, readline().split())
    P = [v - 1 for v in map(int, readline().split())]
    C = list(map(int, readline().split()))


    ans = -10**10

    for i in range(N):
        moves = 1
        cur = P[i]
        score = C[cur]
        ans = max(score, ans)
        visited = {cur: (moves, score)}

        while P[cur] not in visited and moves < K:
            cur = P[cur]
            moves += 1
            score += C[cur]
            visited[cur] = (moves, score)

            ans = max(ans, score)
        
        if moves == K:
            continue
        
        cur = P[cur]
        moves += 1
        score += C[cur]

        T = moves - visited[cur][0]
        D = score - visited[cur][1]

        if D < 0:
            continue
        
        nloops = K - moves
        moves += T * (nloops // T)
        score += D * (nloops // T)

        ans = max(ans, score)

        while moves < K:
            cur = P[cur]
            moves += 1
            score += C[cur]
            ans = max(ans, score)
    
    print(ans)

solve()

Submission status: Accepted

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

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
ans = -10**18

for i in range(N):
    now = i
    visit = [False]*N
    visit[now] = True
    l = []
    
    while True:
        nex = P[now]-1
        l.append(C[nex])
        
        if visit[nex]:
            break
        
        visit[nex] = True
        now = nex
    
    s = sum(l)
    acc = 0
    
    for j in range(min(K, len(l))):
        acc += l[j]
        ans = max(ans, acc+max(0, (K-j-1)//len(l)*s))

print(ans)

Submission status: Accepted

Solution code:
import os
import sys
import math
import heapq
from decimal import *
from io import BytesIO, IOBase
from collections import defaultdict, deque

def r():
    return int(input())
def rm():
    return map(int,input().split())
def rl():
    return list(map(int,input().split()))

n,k = rm()
p = rl()
p = [0]+p
c = rl()
c = [0]+c
b = [-1]*(n+1)
give=0
ans=-math.inf

for i in range(1,n+1):
    a=i
    lenn=1
    add=c[i]
    while p[a]!=i:
        add+=c[p[a]]
        lenn+=1
        a=p[a]
    if add<0:
        add=0
    addAgain=0
    a=i
    for j in range(lenn):
        if j>k:
            break
        addAgain+=c[a]
        ans = max(ans, addAgain+add*((k-j-1)//lenn))
        a = p[a]

print(ans)

Submission status: Accepted

Solution code:
def solve():
  ans = -float('inf')
  N, K = map(int, input().split())
  P = list(map(lambda x:int(x)-1, input().split()))
  C = list(map(int, input().split()))
  for i in range(N):
    score = 0
    now = i
    visited = [-1]*N
    scores = [0]*N
    visited[now] = 0
    for j in range(1,K+1):
      now = P[now]
      score += C[now]
      ans = max(ans, score)
      if visited[now]>=0:
        cyc = j - visited[now]
        up = score - scores[now]
        break
      scores[now] = score
      visited[now] = j
    else:
      continue
    if up<=0:
      continue
    cnt = j+1
    if K-cyc>=j:
      score += (K-cyc-j)//cyc * up
      ans = max(ans, score)
      cnt += (K-cyc-j)//cyc*cyc
    for j in range(cnt,K+1):
      now = P[now]
      score += C[now]
      ans = max(ans, score)
  return ans
print(solve())

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
p.insert(0, 0)
c.insert(0, 0)
visit = [0] * (n + 1)
cyclelist = []
for i in range(1, n + 1):
    if visit[i] == 0:
        a = [c[i]]
        visit[i] = 1
        while visit[p[i]] == 0:
            i = p[i]
            visit[i] = 1
            a.append(c[i])
        cyclelist.append(a)
ans = -1145141919810
for cycle in cyclelist:
    s = sum(cycle)
    l = len(cycle)
    a = 0
    if l < k and s > 0:
        a = s * ((k - 1) // l)
    now = 0
    x = k % l
    if x == 0:
        x = l
    for i in range(min(k, l)):
        now += cycle[i]
        for j in range(l):
            now += cycle[(i + j + 1) % l] - cycle[j]
            if i < x:
                ans = max(ans, a + now)
            else:
                ans = max(ans, now)
print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    N, K = [int(x) for x in input().strip().split()]
    P = [int(x)-1 for x in input().strip().split()]
    C = [int(x) for x in input().strip().split()]
    ans = -float('inf')
    f_cnt = [0] * N
    f_score = [0] * N
    for i in range(N):
        if f_cnt[i]:
            continue
        flag = [False] * N
        j = i
        cnt = 0
        score = 0
        while not flag[j]:
            flag[j] = True
            score += C[j]
            cnt += 1
            j = P[j]
        for j in range(N):
            if flag[j]:
                f_cnt[j] = cnt
                f_score[j] = score
    # print(*f_cnt)
    # print(*f_score)

    def f(cur, cnt):
        ret = -float('inf')
        ret_ = 0
        if f_score[cur] >= 0:
            ret_ += f_score[cur] * (cnt // f_cnt[cur] - 1)
            cnt = cnt % f_cnt[cur] + f_cnt[cur]
            ret = ret_
        else:
            cnt = min(cnt, f_cnt[cur])

        while cnt:
            # print('  cur = {}, cnt = {}, ret = {}'.format(cur, cnt, ret_))
            cur = P[cur]
            ret_ += C[cur]
            ret = max(ret, ret_)
            cnt -= 1

        return ret

    for i in range(N):
        # print('i = {}'.format(i))
        ans = max(ans, f(i, K))
    
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

lim = 60
nex = [[0] * N for _ in range(lim)]
val = [[0] * N for _ in range(lim)]
cnd = [[0] * N for _ in range(lim)]

for i in range(N):
    nex[0][i] = P[i] - 1
    val[0][i] = C[i]
    cnd[0][i] = C[i]

for d in range(lim - 1):
    for i in range(N):
        nex[d + 1][i] = nex[d][nex[d][i]]
        val[d + 1][i] = val[d][i] + val[d][nex[d][i]]
        cnd[d + 1][i] = max(cnd[d][i], val[d][i] + cnd[d][nex[d][i]])

res = -10 ** 9
for i in range(N):
    sum_ = 0
    offset = i
    for d in reversed(range(lim)):
        if K & 1 << d:
            res = max(res, sum_ + cnd[d][offset])
            sum_ += val[d][offset]
            offset = nex[d][offset]

print(res)

Submission status: Accepted

Solution code:
from collections import deque
it = lambda: list(map(int, input().strip().split()))


def maximise(L, R, cycle):
    cur = 0
    ans = max(cycle)
    queue = deque([0])
    dp = [0] * (2 * L + 1)
    for i, num in enumerate(cycle + cycle):
        j = i + 1
        cur += num
        while queue and j - queue[0] > R:
            queue.popleft()
        if queue:
            ans = max(ans, cur - dp[queue[0]])
        while queue and dp[queue[-1]] >= cur:
            queue.pop()
        queue.append(j)
        dp[j] = cur
    return ans


def get(K, cycle):
    L = len(cycle)
    T = sum(cycle)

    if K > L:
        B = (K - 1) // L
        R = K - B * L
    else:
        B = 0
        R = K
    return max(maximise(L, K, cycle), maximise(L, R, cycle) + max(0, B * T))


def solve():
    # square labelled from 1 to N
    N, K = it()
    P = it()
    C = it()

    for i in range(N):
        P[i] -= 1

    cycles = []
    seen = [False] * N
    for i in range(N):
        if not seen[i]:
            cycle = []
            first = curr = i
            while True:
                seen[curr] = True
                cycle.append(C[curr])
                curr = P[curr]
                if curr == first:
                    break
            cycles.append(cycle)
    
    # print(cycles)
    ans = float('-inf')
    for cycle in cycles:
        ans = max(ans, get(K, cycle))
    return ans


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

Submission status: Accepted

Solution code:
INF=10**20

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

array=list(map(int,input().split()))
P=[]
C=list(map(int,input().split()))
for i in array:
    P.append(i-1)

ans=-1*INF

for i in range(N):
    v=i
    cycle_sum=0
    cycle_cnt=0

    while(True):
        cycle_cnt+=1
        cycle_sum+=C[v]
        v=P[v]
        if v==i:
            break

    path=0
    cnt=0

    while(True):
        cnt+=1
        path+=C[v]

        if cnt>K:
            break

        num=(K-cnt)//cycle_cnt
        score=path+max(0,cycle_sum)*num
        ans=max(ans,score)

        v=P[v]
        if v==i:
            break

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

for i in range(n):
    p[i] -= 1

v = [False] * n
roop = []

for i in range(n):
    if not v[i]:
        tmp = [i]
        while True:
            t = p[tmp[-1]]
            v[t] = True
            if tmp[0] == t:
                break
            else:
                tmp.append(t)
        roop.append(tmp)

s = []

for li in roop:
    s1 = 0
    for i in li:
        s1 += c[i]
    s.append(s1)

s2 = []

for li in roop:
    tmp = [0]
    for i in li:
        tmp.append(tmp[-1] + c[i])
    for i in li:
        tmp.append(tmp[-1] + c[i])
    s2.append(tmp)

v2 = [-1] * n

for i,li in enumerate(roop):
    for j in li:
        v2[j] = i

ans = -10**20

for i,li in enumerate(roop):
    t = -10**20
    if s[i] <= 0:
        for j in range(len(li)):
            for k1 in range(j+1, j + 1 + min(k, len(li))):
                t = max(t, s2[i][k1] - s2[i][j])
        ans = max(ans, t)
    else:
        for cnt in range(min(len(li), k)+1):
            for j in range(len(li)):
                if k >= cnt:
                    t = max(t, s2[i][cnt+j] - s2[i][j] + s[i] * ((k - cnt) // len(li)))
        ans = max(ans, t)

print(ans)

Submission status: Accepted

Solution code:
#D - Moving_piece
N,K = map(int,input().split())
P =[]
C =[]
P = list(map(int,input().split()))
C = list(map(int,input().split()))

score_output = -1000000000
i = 0
for i in range(N):
    ichi = i
    score = 0
    step  = 0
    loop  = 0
    score_max = -1000000000
    while True:
        step  += 1
        score += C[ichi]
        ichi   = (P[ichi] -1)
        if i ==  (P[ichi] -1):
            score += C[ichi]
            break
        
    path = 0
    cnt  = 0
    
    while True:
        cnt  += 1
        path += C[ichi]
        
        if cnt > K:
            break
        
        loop = int((K - cnt) / (step+ 1))
        if score > 0:
            score_max = path + loop * score
        else:
            score_max = path
        if score_max > score_output:
            score_output = score_max

        ichi   = P[ichi]-1
        if i == (P[ichi] -1):
            break
# 出力
print(score_output)