Problem:


Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:ans=max(ans,max(0,k//L-1)*S+max(max(cycle[:k]),max(cycle[:k%L+1])+S*(L>k)))
print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:ans=max(ans,max(0,k//L-1)*S+max(max(cycle),max(cycle[:k%L+1])+S))
print(ans)

Submission status: Wrong Answer

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

gs = []
done = set()
for i in range(N):
    if i in done:
        continue
    path = {i}
    cur = P[i]
    while cur not in path:
        path.add(cur)
        cur = P[cur]
    gs.append(path)
    done |= path

ans = -10 ** 10
for g in gs:
    gscore = sum(C[i] for i in g)
    for i in g:
        n = 1
        p = C[i]
        ans = max(ans, p, p + max(0, gscore) * (K - n) // len(g))
        cur = P[i]
        while cur != i:
            n += 1
            p += C[cur]
            ans = max(ans, p, p + max(0, gscore) * (K - n) // len(g))
            cur = P[cur]
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np
from itertools import chain


# 一つのループの中で最大値を求める
# len(loop) Kは1以上
def max_in_loop(loop, K):

    loop = np.array(loop, dtype=np.int64)
    loop_sum = loop.sum()
    # 繰り返し部分の数を数える
    repeat_n = K // loop.size
    # 繰り返し部分が正の場合、repeat_n 回繰り返した値を加算する
    if repeat_n > 0:
        if loop_sum > 0:
            repeat_sum = repeat_n * loop_sum
        else:
            repeat_sum = 0
    else:
        repeat_sum = 0

    # 繰り返し以外の部分の最大長さ
    k_max = K % loop.size

    # 繰り返し部分以外の最大値を求める

    # 繰り返し部以外の部分の長さが 0 のとき
    if repeat_n > 0:
        max_val = -float("inf")
    else:
        # 最低 1 つは選ばないといけないので
        # 繰り返し部分がないときは、
        # それ以外の部分は 0 にできない
        max_val = -9

    # 繰り返し部分の合計値を計算するための
    # アキュムレータ
    acc = np.zeros(loop.size)

    # 繰り返し部分以外の長さが1〜k_max のとき
    # (ずらし量が 0, kmax - 1)
    for k in range(0, k_max):
        n = loop.size - k
        acc[:n] += loop[k : loop.size]
        acc[n:] += loop[0:k]
        # print("k=", k, " acc=", acc)
        max_val = max(max_val, acc.max())

    # repeat_sum を加えてここまでの max_valを
    # 求めておく
    max_val += repeat_sum

    # 繰り返しを一回減らせるなら
    # 一回へらして
    # 繰り返し部分以外の長さがk_max+1, loop.size-1 のとき
    # (ずらし量が kmax,loop.size - 2)
    if repeat_n > 0:
        if loop_sum > 0:
            repeat_sum -= loop_sum
        for k in range(k_max, loop.size - 1):
            n = loop.size - k
            acc[:n] += loop[k : loop.size]
            acc[n:] += loop[0:k]
            max_val = max(max_val, acc.max() + repeat_sum)

    # print("  max_val=", max_val)
    return max_val


def solve(N: int, K: int, P: "List[int]", C: "List[int]"):
    # 簡単のためインデックスを 0 からにする
    # (使用済みは -1 を入れる)
    P = [i - 1 for i in P]
    answer = -float("inf")
    for i0 in range(N):
        if P[i0] == -1:
            continue
        loop = []
        i = i0
        while P[i] != -1:
            loop.append(C[i])
            i_next = P[i]
            P[i] = -1
            i = i_next
        val = max_in_loop(loop, K)
        if answer < val:
            answer = val

    return int(answer)


def main():
    tokens = chain(*(line.split() for line in sys.stdin))
    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]"
    answer = solve(N, K, P, C)
    print(answer)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<=0:ans=max(ans,max(cycle[1:k+1]))
    else:ans=max(ans,k//L*S+max(cycle[:k%L+1]))
print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=[int(i)-1for i in input().split()]
c=list(map(int,input().split()))
ans=-10**9
for i in range(n):
    start=i
    cycle=[0]
    for _ in range(n):
        i=p[i]
        cycle+=[cycle[-1]+c[i]]
        if i==start:break
    S,L=cycle[-1],len(cycle)-1
    if S<0:ans=max(ans,max(cycle[1:k+1]))
    else:ans=max(ans,k//L*S+max(cycle[:k%L+1]))
print(ans)

Submission status: Wrong Answer

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

#ループ探し
l = [0] * 5010
counter = 0
for i in range(N):
    P[i] = P[i]-1
    l[i] = []
for i in range(N):
    if P[i] == -1:
        continue
    else:
        a = i
        while True:
            #print(P, a)
            if P[a] != -1:
                l[counter].append(C[a])
                n = P[a]
                P[a] = -1
                a = n
            else:
                counter += 1
                break

print("8")

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(lambda x: int(x) - 1, input().split()))
c = list(map(int, input().split()))
    
visited = [False] * n
ans = max(c)

for i in range(n):
    if visited[i]:
        continue
    arr = []
    u = i
    while not visited[u]:
        arr.append(c[u])
        visited[u] = True
        u = p[u]
    s = sum(arr) * (k // len(arr))
    rem = k % len(arr)
    arr += arr
    pref_sum = [0]
    for i in arr:
            pref_sum.append(pref_sum[-1] + i)
            
    for f in range(len(arr) // 2):
        # ans = max(ans, s + sum(arr[f:f + rem])) 
        ans = max(ans, s + pref_sum[f + rem] - pref_sum[f])
        for g in range(f + 1, len(arr) + 1):
            if g - f > k:
                break
            # ans = max(ans, sum(arr[f:g])) 
            ans = max(ans, pref_sum[g] - pref_sum[f])
print(ans)

Submission status: Wrong Answer

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

def solve(u):
    ans = c[p[u]]
    pos = [-1] * n
    score = [-1] * n
    tk = k
    cur_pos, cur_sum = 0, 0
    while tk > 0 and pos[u] == -1:
        pos[u] = cur_pos
        score[u] = cur_sum
        u = p[u]
        cur_pos += 1
        cur_sum += c[u]
        ans = max(ans, cur_sum)
        tk -= 1
    cycle_length = cur_pos - pos[u]
    cycle_sum = cur_sum - score[u]
    # print(cur_sum, ans, cycle_length, cycle_sum)  
    
    if cycle_sum <= 0:
        return ans
    
    cur_sum += cycle_sum * (tk // cycle_length)
    ans = max(ans, cur_sum)
    tk %= cycle_length
    while tk > 0:
        u = p[u]
        cur_sum += c[u]
        ans = max(ans, cur_sum)
        tk -= 1
    return ans

# print(list((solve(i), i) for i in range(n))) 
print(max(solve(i) for i in range(n)))

Submission status: Wrong Answer

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

def solve(u):
    ans = c[p[u]]
    pos = [-1] * n
    score = [-1] * n
    tk = k
    cur_pos, cur_sum = 0, 0
    while tk > 0 and pos[p[u]] == -1:
        u = p[u]
        cur_pos += 1
        cur_sum += c[u]
        ans = max(ans, cur_sum)
        pos[u] = cur_pos
        score[u] = cur_sum
        tk -= 1
    cycle_length = cur_pos - pos[p[u]] + 1
    cycle_sum = cur_sum - score[p[u]] + c[p[u]]
    # print(cur_sum, ans, cycle_length, cycle_sum) 
    
    if cycle_sum <= 0:
        return ans
    
    cur_sum += cycle_sum * (tk // cycle_length)
    ans = max(ans, cur_sum)
    tk %= cycle_length
    while tk > 0:
        u = p[u]
        cur_sum += c[u]
        ans = max(ans, cur_sum)
        tk -= 1
    return ans

# print(list((solve(i), i) for i in range(n))) 
print(max(solve(i) for i in range(n)))

Submission status: Wrong Answer

Solution code:
import copy
N,K=map(int,input().split())
List_p=list(map(int,input().split()))
List_c=list(map(int,input().split()))
l=[]
number=[i for i in range(N)]
sub=copy.copy(List_c)
l.append(sub)
for i in range(N):
    number[i]=List_p[number[i]]
    sub[i]+=List_c[number[i]-1]
    l.append(sub)
j=[]
for i in range(len(l)):
    j.append(max(l[i]))
s=0
for i in range(len(List_c)):
    s+=List_c[i]
if s>=0:
    if K<=N:
        ans=j[1]
        for i in range(2,K+1):
            ans=max(ans,j[i])
        print(ans)
    else:
        ans=j[1]
        for i in range(2,N+1):
            ans=max(ans,j[i])
        print(ans+s*(K//N))
else:
    if K<=N:
        ans=j[1]
        for i in range(2,K+1):
            ans=max(ans,j[i])
        print(ans)
    else:
        ans=j[1]
        for i in range(2,N+1):
            ans=max(ans,j[i])
        print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate 

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**18-1
seen = [False]*N
for i in range(N):
    if seen[i]:
        continue
    loop = []
    now = i
    while seen[now] == False:
        seen[now] = True
        loop.append(C[now])
        now = P[now]
    loop_size = len(loop)
    loop_score = sum(loop)
    cumsum = [0]+list(accumulate(loop+loop))
    for j in range(1, loop_size+1):
        for l in range(loop_size+1):
            r = l+j
            subseq = cumsum[r] - cumsum[l]
            ans = max(ans, subseq, subseq+loop_score*(max(K-j, 0)//loop_size))
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate 

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**18-1
seen = [False]*N
for i in range(N):
    if seen[i]:
        continue
    loop = []
    now = i
    while seen[now] == False:
        seen[now] = True
        loop.append(C[now])
        now = P[now]
    loop_size = len(loop)
    loop_score = sum(loop)
    cumsum = [0]+list(accumulate(loop+loop))
    for j in range(1, loop_size+1):
        for l in range(loop_size+1):
            r = l+j
            subseq = cumsum[r] - cumsum[l]
            ans = max(ans, subseq, subseq+loop_score*((K-j)//loop_size))
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate 

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**18-1
seen = [False]*N
for i in range(N):
    if seen[i]:
        continue
    loop = []
    now = i
    while seen[now] == False:
        seen[now] = True
        loop.append(C[now])
        now = P[now]
    loop_size = len(loop)
    loop_score = sum(loop)
    print(loop)
    cumsum = [0]+list(accumulate(loop+loop))
    print(cumsum)
    for j in range(1, loop_size+1):
        for l in range(loop_size+1):
            r = l+j
            subseq = cumsum[r] - cumsum[l]
            ans = max(ans, subseq, subseq+loop_score*((K-j)//loop_size))
print(ans)

Submission status: Wrong Answer

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

ans = -10**18

for i in range(N):
    tmp_score = 0
    pos = i
    # ループになるまで移動
    for j in range(1, N+1):
        pos = P[pos]-1
        if K >= j:
            tmp_score += C[pos]
            ans = max(ans,tmp_score)
        if pos == i:
            break
    
    div = K // j
    mod = K % j

    if K > j:
        tmp_score *= div
        ans = max(ans,tmp_score)
        # 端数ぶん移動
        # mod=0 のときは移動しない
        for _ in range(1, mod+1):
            pos = P[pos]-1
            tmp_score += C[pos]
            ans = max(ans,tmp_score)

print(ans)

Submission status: Wrong Answer

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

ans = -10**18

for i in range(N):
    tmp_score = 0
    pos = i
    # ループになるまで移動
    for j in range(1, N+1):
        pos = P[pos]-1
        if K >= j:
            tmp_score += C[pos]
            ans = max(ans,tmp_score)
        if pos == i:
            break
    
    div = K // j
    mod = K % j

    if K >= j:
        tmp_score *= div
        ans = max(ans,tmp_score)
        # 端数ぶん移動
        # mod=0 のときは移動しない
        for _ in range(1, mod+1):
            pos = P[pos]-1
            tmp_score += C[pos]
            ans = max(ans,tmp_score)

print(ans)

Submission status: Wrong Answer

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

ans = -10**18

for i in range(N):
    tmp_score = 0
    pos = i
    # ループになるまで移動
    for j in range(1, K+1):
        pos = P[pos]-1
        tmp_score += C[pos]
        ans = max(ans,tmp_score)
        if pos == i:
            break
    
    div = K // j
    mod = K % j

    if j <= K:
        tmp_score *= div
        ans = max(ans,tmp_score)
        # 端数ぶん移動
        # mod=0 のときは移動しない
        for _ in range(1, mod+1):
            pos = P[pos]-1
            tmp_score += C[pos]
            ans = max(ans,tmp_score)

print(ans)

Submission status: Wrong Answer

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

ans = -10**18

for i in range(N):
    tmp_score = 0
    pos = i
    # ループになるまで移動
    for j in range(1, K+1):
        pos = P[pos]-1
        tmp_score += C[pos]
        ans = max(ans,tmp_score)
        if pos == i:
            break
    
    div = K // j
    mod = K % j

    tmp_score *= div
    ans = max(ans,tmp_score)
    # 端数ぶん移動
    # mod=0 のときは移動しない
    for _ in range(1, mod+1):
        pos = P[pos]-1
        tmp_score += C[pos]
        ans = max(ans,tmp_score)

print(ans)

# ans の更新は毎回 max でとってるので
# ループを途中まで移動するのが答え(最大になる) の場合も対応できてる

Submission status: Wrong Answer

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

ans = -10**18

for i in range(N):
    tmp_score = 0
    pos = i
    # ループになるまで移動
    for j in range(1, K+1):
        pos = P[pos]-1
        tmp_score += C[pos]
        ans = max(ans,tmp_score)
        if pos == i:
            break
    
    div = K // j
    mod = K % j

    tmp_score *= div
    ans = max(ans,tmp_score)
    # 端数ぶん移動
    for _ in range(mod+1):
        pos = P[pos]-1
        tmp_score += C[pos]
        ans = max(ans,tmp_score)        
print(ans)