Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

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


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -float('inf')
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cycle, residue = divmod(K, cyclelen)
    scores *= 2
    scores = list(itertools.accumulate(scores))
    st = SegmentTree(scores, max, -float('inf'))
    ans = max([ans] + [
        st.query(start2 + 1, start2 + min(K, cyclelen) + 1) - scores[start2]
        for start2 in range(cyclelen)
    ])
    scorelastcycle = scores[-1] * cycle // 2
    if cycle > 0:
        d = max(
            st.query(start2 + 1, start2 + residue + 1) - scores[start2]
            for start2 in range(cyclelen))
        scorelastcycle += d
    ans = max(ans, scorelastcycle)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
ps = list(map(int, input().split()))
cs = list(map(int, input().split()))
#memo = [[0]*(n+1)for _ in range(n+1)]
#for i in range(1,n+1):
    #memo[i][0] = [i,0]

to_do = []
res = -float('inf')
for i in range(1,n+1):
    tmp_idx = i
    tmp_val = 0
    tmp_dic = {i:(0,0,i)}
    for j in range(1,n+1):
        #tmp_idx,tmp_val = ps[memo[i][j-1][0]-1],memo[i][j-1][1]+cs[ps[memo[i][j-1][0]-1]-1]
        #memo[i][j] = [tmp_idx,tmp_val]
        tmp_idx = ps[tmp_idx-1]
        tmp_val += cs[tmp_idx-1]
        res = max(res,tmp_val)
        if tmp_idx not in tmp_dic:
            tmp_dic[tmp_idx] = (j,tmp_val,tmp_idx)
        else:
            if tmp_val > tmp_dic[tmp_idx][1]:
                to_do.append([i,tmp_dic[tmp_idx][0],tmp_dic[tmp_idx][2],tmp_dic[tmp_idx][1],j-tmp_dic[tmp_idx][0],tmp_val-tmp_dic[tmp_idx][1]])
            else:
                break

if k <= n:
    print(res)
else:
    for do in to_do:
        itr = (k - do[1]) // do[4]
        remain = k - do[1] - do[4] * itr
        tmp_res = do[3] + itr * do[5]
        res = max(res,tmp_res)
        now = do[2]
        for i in range(remain):
            now = ps[now-1]
            tmp_res += cs[now-1]
            res = max(res, tmp_res)
    print(res)

Submission status: Wrong Answer

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

max_score = -1 * float('inf')

for start_pos in range(N):
    step_score = [0] * N
    pos = start_pos
    loop_num = 0
    loop_sum = 0
    step = 0
    while (step < K):
        pos = P[pos]
        loop_sum += C[pos]
        step_score[step] = loop_sum
        step += 1
        if pos == start_pos:
            break
    loop_num = step
    step_max_score = max(step_score)
    if loop_num < K:
        if K // loop_num > 0:
            if K % loop_num != 0:
                step_max_score = max(
                    step_max_score,
                    max(step_score[:(K % loop_num)]) + loop_sum * (K // loop_num)
                )
            else:
                step_max_score = max(
                    step_max_score,
                    loop_sum * (K // loop_num)
                )
        if K // loop_num > 1:
            step_max_score = max(
                step_max_score,
                max(step_score) + loop_sum * (K // loop_num - 1)
            )
    max_score = max(step_max_score, max_score)
    #print(start_pos, step_max_score, max(step_score), loop_sum, loop_num)

print(max_score)

Submission status: Wrong Answer

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

points = list()
for i in range(N):
    sum = 0
    now = P[i]
    result = list()
    flag = True
    for j in range(N):
        sum += C[now]
        result.append(sum)
        if now == i:
            break
        if j == N-1 and now != i:
            flag = False
        now = P[now]

    if flag:
        points.append(result)
    else:
        # iスタートでiに戻るループが存在しない
        points.append([-int(1e19)])

ans = -int(1e19)

for i in range(len(points)):
    now = i
    tmpp = 0
    while points[now][0] == -int(1e19):
        now = P[now]
        tmpp += C[now]
        ans = max(ans, tmpp)

    cir = len(points[now])
    cir_point = points[now][cir-1]

    if K <= cir:
        for j in range(K):
            ans = max(ans, points[now][j] + tmpp)
    else:
        if cir_point > 0:
            for j in range(K % cir):
                ans = max(ans, points[now][j] + (K // cir) * cir_point + tmpp)

        for j in range(cir):
            ans = max(ans, points[now][j] + tmpp)

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
def main():
    import sys

    sys.setrecursionlimit(10 ** 4)

    def search_loop(now: int, loop: list):
        """iから探索を初めて，再びiに達するまでに通った点のスコアをリストとして返す"""
        seen[now] = True
        if now == i and loop:
            loops.append(loop)
            return
        loop.append(C[now])
        search_loop(P[now], loop)

    N, K = map(int, input().split())
    P = [int(x) - 1 for x in input().split()]
    C = [int(x) for x in input().split()]

    # ループを探す
    seen = [False] * N
    loops = []
    for i in range(N):
        if not seen[i]:
            search_loop(i, [])

    # ループごとの最大スコアを探す
    ans = -10 ** 9
    for loop in loops:
        length = len(loop)
        sum_loop = sum(loop)
        # ループ長よりも操作回数が多く，ループを周回すると得な場合
        if K > length and sum_loop > 0:
            res = sum_loop * (K // length)
            limit = K % length
        # そうじゃない場合
        else:
            res = 0
            limit = K

        loop_temp = loop * 2  # loopリストに同じloopリストを接続する
        for k in range(1, limit + 1):
            for i in range(length):
                ans = max(ans, sum(loop_temp[i:i + k]) + res)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
ps = list(map(int, input().split()))
cs = list(map(int, input().split()))
#memo = [[0]*(n+1)for _ in range(n+1)]
#for i in range(1,n+1):
    #memo[i][0] = [i,0]

to_do = []
res = -float('inf')
for i in range(1,n+1):
    tmp_idx = i
    tmp_val = 0
    tmp_dic = {i:(0,0,i)}
    for j in range(1,n+1):
        #tmp_idx,tmp_val = ps[memo[i][j-1][0]-1],memo[i][j-1][1]+cs[ps[memo[i][j-1][0]-1]-1]
        #memo[i][j] = [tmp_idx,tmp_val]
        tmp_idx = ps[tmp_idx-1]
        tmp_val += cs[tmp_idx-1]
        res = max(res,tmp_val)
        if tmp_idx not in tmp_dic:
            tmp_dic[tmp_idx] = (j,tmp_val,tmp_idx)
        else:
            if tmp_val > tmp_dic[tmp_idx][1]:
                to_do.append([i,tmp_dic[tmp_idx][0],tmp_dic[tmp_idx][2],tmp_dic[tmp_idx][1],j-tmp_dic[tmp_idx][0],tmp_val-tmp_dic[tmp_idx][1]])
            else:
                break

for do in to_do:
    itr = (k - do[1]) // do[4]
    remain = k - do[1] - do[4] * itr
    tmp_res = do[3] + itr * do[5]
    res = max(res,tmp_res)
    now = do[2]
    for i in range(remain):
        now = ps[now-1]
        tmp_res += cs[now-1]
        res = max(res, tmp_res)
print(res)

Submission status: Wrong Answer

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


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -float('inf')
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cycle, residue = divmod(K, cyclelen)
    scores *= 2
    scores = list(itertools.accumulate(scores))
    st = SegmentTree(scores, max, -float('inf'))
    ans = max([ans] + [
        st.query(start2 + 1, start2 + min(K, cyclelen) + 1) - scores[start2]
        for start2 in range(cyclelen)
    ])
    scorelastcycle = scores[-1] * cycle // 2
    if scorelastcycle > 0 and cycle > 0:
        d = 0
        for start2 in range(cyclelen):
            d = max(d, st.query(start2, start2 + residue + 1) - scores[start2])
        scorelastcycle += d
        ans = max(ans, scorelastcycle)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
n, k = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))


def dfs(i):
    if 0 <= visited[i]:
        return
    visited[i] = idx
    cycle.append(i)
    global csum
    csum += C[i]
    dfs(P[i])


visited = [-1]*n
idx = 0
cycles = []
for i in range(n):
    if 0 <= visited[i]:
        continue
    cycle = []
    csum = 0
    dfs(i)
    cycles.append((cycle, csum))
    idx += 1


INF = 10**18
ans = -INF
for i in range(n):
    cycle, csum = cycles[visited[i]]
    cmem = len(cycle)

    if 0 < csum:
        a, b = divmod(k, cmem)
        scoreA = csum*a
        score = 0
        INF = 10**18
        scoreB = -INF
        for _ in range(b):
            i = P[i]
            score += C[i]
            if scoreB < score:
                scoreB = score
        X = scoreA+scoreB
    else:
        b = min(k, cmem)
        score = 0
        INF = 10**18
        X = -INF
        for _ in range(b):
            i = P[i]
            score += C[i]
            if X < score:
                X = score

    if ans < X:
        ans = X
print(ans)

Submission status: Wrong Answer

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


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -float('inf')
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cycle, residue = divmod(K, cyclelen)
    scores *= 2
    scores = list(itertools.accumulate(scores))
    st = SegmentTree(scores, max, -float('inf'))
    ans = max([ans] + [
        st.query(start2, start2 + min(K, cyclelen) + 1) - scores[start2]
        for start2 in range(cyclelen)
    ])
    scorelastcycle = scores[-1] * cycle // 2
    if scorelastcycle > 0 and cycle > 0:
        d = 0
        for start2 in range(cyclelen):
            d = max(d, st.query(start2, start2 + residue + 1) - scores[start2])
        scorelastcycle += d
        ans = max(ans, scorelastcycle)
print(ans)

Submission status: Wrong Answer

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

step_score = [0] * N
max_score = -1 * float('inf')

for start_pos in range(N):
    pos = start_pos
    loop_num = 0
    loop_sum = 0
    step = 0
    while (step < K):
        pos = P[pos]
        loop_sum += C[pos]
        step_score[step] = loop_sum
        step += 1
        if pos == start_pos:
            break
    loop_num = step
    step_max_score = max(step_score)
    if loop_num < K:
        if K // loop_num > 0:
            if K % loop_num != 0:
                step_max_score = max(
                    step_max_score,
                    max(step_score[:(K % loop_num)]) + loop_sum * (K // loop_num)
                )
            else:
                step_max_score = max(
                    step_max_score,
                    loop_sum * (K // loop_num)
                )
        if K // loop_num > 1:
            step_max_score = max(
                step_max_score,
                max(step_score) + loop_sum * (K // loop_num - 1)
            )
    max_score = max(step_max_score, max_score)
    #print(start_pos, step_max_score, max(step_score), loop_sum, loop_num)

print(max_score)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
ps = list(map(int, input().split()))
cs = list(map(int, input().split()))
#memo = [[0]*(n+1)for _ in range(n+1)]
#for i in range(1,n+1):
    #memo[i][0] = [i,0]

to_do = []
res = -float('inf')
for i in range(1,n+1):
    tmp_idx = i
    tmp_val = 0
    tmp_dic = {i:(0,0,i)}
    for j in range(1,n+1):
        #tmp_idx,tmp_val = ps[memo[i][j-1][0]-1],memo[i][j-1][1]+cs[ps[memo[i][j-1][0]-1]-1]
        #memo[i][j] = [tmp_idx,tmp_val]
        tmp_idx = ps[tmp_idx-1]
        tmp_val += cs[tmp_idx-1]
        res = max(res,tmp_val)
        if tmp_idx not in tmp_dic:
            tmp_dic[tmp_idx] = (j,tmp_val,tmp_idx)
        else:
            if tmp_val > tmp_dic[tmp_idx][1]:
                to_do.append([i,tmp_dic[tmp_idx][0],tmp_dic[tmp_idx][2],tmp_dic[tmp_idx][1],j-tmp_dic[tmp_idx][0],tmp_val-tmp_dic[tmp_idx][1]])
            break

for do in to_do:
    itr = (k - do[1]) // do[4]
    remain = k - do[1] - do[4] * itr
    tmp_res = do[3] + itr * do[5]
    res = max(res,tmp_res)
    now = do[2]
    for i in range(remain):
        now = ps[now-1]
        tmp_res += cs[now-1]
        res = max(res, tmp_res)
print(res)

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

#各地点からN回移動したときのスコアをあらかじめ求める
score = [[0 for j in range(N + 1)] for i in range(N)]
loop = [None for _ in range(N)]

for i in range(N):
    tmp = i
    flag = False
    for j in range(1, N + 1):
        tmp = P[tmp]
        score[i][j] = score[i][j - 1] + C[tmp]
        if tmp == i and not flag:
            loop[i] = j
            flag = True

if K <= N:
    res = -10**20
    for i in range(N):
        for j in range(1, K + 1):
            res = max(res, score[i][j])
    print(res)

else:
    res = -10**20
    for i in range(N):
        for j in range(1, N + 1):
            res = max(res, score[i][j])
    for i in range(N):
        if score[i][loop[i]] >= 0:
            s = score[i][loop[i]] * (K // loop[i])
            for j in range(K % loop[i] + 1):
                res = max(res, s + score[i][j])
        else:
            s = score[i][loop[i]]
            for j in range(K % loop[i] + 1):
                res = max(res, s + score[i][j])
    print(res)

Submission status: Wrong Answer

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


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -float('inf')
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cycle, residue = divmod(K, cyclelen)
    scores *= 2
    scores = list(itertools.accumulate(scores))
    ans = max([ans] + scores[1:K + 1])
    st = SegmentTree(scores, max, -float('inf'))
    scorelastcycle = scores[-1] * cycle // 2
    if scorelastcycle > 0 and cycle > 0:
        d = 0
        for start2 in range(cyclelen):
            d = max(d, st.query(start2, start2 + residue + 1) - scores[start2])
        scorelastcycle += d
        ans = max(ans, scorelastcycle)
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()))
loop = []
visit = [False for i in range(n)]
for i in range(n):
    if visit[i]:
        continue
    tyu  = [i]
    now = i
    visit[i] = True
    while True:
        nex = p[now] - 1
        if nex == i:
            break
        visit[nex] = True
        tyu.append(nex)
        now = nex
    loop.append(tyu)

ans = []

for p in loop:
    kouho = []
    losum = 0
    lokz = len(p)
    kar = [0]
    for i in p:
        losum += c[i]
        kar.append(kar[-1] + c[i])
    
    if losum >= 0:
        kouho.append(losum*(k//lokz))
        for i in range(1,lokz+1):
            for j in range(1,lokz+1):
                if i < j:
                    amari = j - i
                    if amari <= k:
                        cou = losum*((k-amari)//lokz) + kar[j-2]-kar[i-1]
                elif i == j:
                    continue
                elif i > j:
                    amari = lokz - (i-j)
                    if amari <= k:
                        cou = losum*((k-amari)//lokz) + kar[j-1] + kar[-1] - kar[i-2]
                kouho.append(cou)
    elif losum < 0:
        for i in range(lokz):
            for j in range(lokz):
                if i <= j:
                    amari = j - i
                    if amari <= k:
                        cou = kar[j-2]-kar[i-1]
                elif i > j:
                    amari = lokz - (i-j)
                    if amari <= k:
                        cou = kar[j-1] + kar[-1] - kar[i-2]
                kouho.append(cou)
    ans.append(max(kouho))
print(max(ans))

Submission status: Wrong Answer

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

step_score = [0] * N
max_score = -1 * float('inf')

for start_pos in range(N):
    pos = start_pos
    loop_num = 0
    loop_sum = 0
    step = 0
    while (step < K and step < N):
        pos = P[pos]
        loop_sum += C[pos]
        step_score[step] = loop_sum
        step += 1
        if pos == start_pos:
            break
    loop_num = step
    step_max_score = max(step_score)
    if loop_num < K:
        if K // loop_num > 0:
            if K % loop_num != 0:
                step_max_score = max(
                    step_max_score,
                    max(step_score[:(K % loop_num)]) + loop_sum * (K // loop_num)
                )
            else:
                step_max_score = max(
                    step_max_score,
                    max(step_score) + loop_sum * (K // loop_num)
                )
        if K // loop_num > 1:
            step_max_score = max(
                step_max_score,
                max(step_score) + loop_sum * (K // loop_num - 1)
            )
    max_score = max(step_max_score, max_score)
    #print(start_pos, step_max_score, max(step_score), loop_sum, loop_num)

print(max_score)

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

#各地点からN回移動したときのスコアをあらかじめ求める
score = [[0 for j in range(N + 1)] for i in range(N)]
loop = [None for _ in range(N)]

for i in range(N):
    tmp = i
    flag = False
    for j in range(1, N + 1):
        tmp = P[tmp]
        score[i][j] = score[i][j - 1] + C[tmp]
        if tmp == i and not flag:
            loop[i] = j
            flag = True

if K <= N:
    res = -10**20
    for i in range(N):
        for j in range(1, K + 1):
            res = max(res, score[i][j])
    print(res)

else:
    res = -10**20
    for i in range(N):
        for j in range(1, N + 1):
            res = max(res, score[i][j])
    for i in range(N):

        s = score[i][loop[i]] * (K // loop[i])
        for j in range(K % loop[i] + 1):
            res = max(res, s + score[i][j])

    print(res)

Submission status: Wrong Answer

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


def main():
    [n, num] = [int(e) for e in si().split()]
    pl = [int(e) for e in si().split()]
    cl = [int(e) for e in si().split()]

    M = -1000000000*5000-1

    for i in range(n):
        vis, val = [0]*n, [0]*n
        flag, ith, k, idx, m = False, 0, num, i, 0
        while k > 0:
            idx = pl[idx]-1
            if not flag:
                ith += 1
                if vis[idx] != 0:
                    flag = True
                    cv = m-(val[idx]-cl[idx])
                    cn = ith-vis[idx]
                    rest = k//cn
                    if rest:
                        m += cv*rest
                        M = max(M, m)
                        k -= cn*rest
                else:
                    vis[idx] = ith
                    val[idx] = m+cl[idx]

            m += cl[idx]
            M = max(M, m)
            k -= 1
    print(M)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
ps = list(map(int, input().split()))
cs = list(map(int, input().split()))
memo = [[0]*(n+1)for _ in range(n+1)]

for i in range(1,n+1):
    memo[i][0] = [i,0]

to_do = []
res = -float('inf')
for i in range(1,n+1):
    tmp_dic = {i:(0,0,i)}
    for j in range(1,n+1):
        tmp_idx,tmp_val = ps[memo[i][j-1][0]-1],memo[i][j-1][1]+cs[ps[memo[i][j-1][0]-1]-1]
        memo[i][j] = [tmp_idx,tmp_val]
        res = max(res,tmp_val)
        if tmp_idx not in tmp_dic:
            tmp_dic[tmp_idx] = (j,tmp_val,tmp_idx)
        else:
            if tmp_val > tmp_dic[tmp_idx][1]:
                to_do.append([i,tmp_dic[tmp_idx][0],tmp_dic[tmp_idx][2],tmp_dic[tmp_idx][1],j-tmp_dic[tmp_idx][0],tmp_val-tmp_dic[tmp_idx][1]])
            break

for do in to_do:
    itr = (k - do[1]) // do[4]
    remain = k - do[1] - do[4] * itr
    tmp_res = do[3] + itr * do[5]
    res = max(res,tmp_res)
    now = do[2]
    for i in range(remain):
        now = ps[now-1]
        tmp_res += cs[now-1]
        res = max(res, tmp_res)
print(res)

Submission status: Wrong Answer

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

P = [P[i]-1 for i in range(N)]
ans = -float("inf")

for start in range(N):
    x = start
    pattern = []
    while True:
        x = P[x]
        pattern.append(x)
        if x == start:
            break

    pattern_len = len(pattern)
    total = 0
    for j in range(pattern_len):
        total += C[pattern[j]]

    #周期のトータルがマイナス収支の場合
    if total < 0:
        now = 0
        for j in range(pattern_len):
            now += C[pattern[j]]
            ans = max(now, ans)
    #収支のトータルがプラスの場合
    else:
        now = 0
        now += total * (K//pattern_len)
        ans = max(ans, now)
        for j in range(K%pattern_len):
            ans = max(now + C[pattern[j]], ans)

print(ans)