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 sys
from itertools import accumulate

input = sys.stdin.readline


class UnionFind:
    """Union Find class.

    "Path compression" and "Union by rank" are used.

    References:
        <https://en.wikipedia.org/wiki/Disjoint-set_data_structure>
    """

    def __init__(self, N):
        self.N = N
        self.__make_set()

    def __make_set(self):
        self._parent = list(range(self.N + 1))
        self._rank = [0] * (self.N + 1)
        self._size = [1] * (self.N + 1)

    def find(self, x):
        if self._parent[x] != x:
            self._parent[x] = self.find(self._parent[x])
        return self._parent[x]

    def union(self, x, y):
        x_root = self.find(x)
        y_root = self.find(y)

        if x_root == y_root:
            return

        x_rank = self._rank[x_root]
        y_rank = self._rank[y_root]
        if x_rank > y_rank:
            self._parent[y_root] = x_root
            self._size[x_root] += self._size[y_root]
        elif x_rank < y_rank:
            self._parent[x_root] = y_root
            self._size[y_root] += self._size[x_root]
        else:
            self._parent[y_root] = x_root
            self._rank[x_root] += 1
            self._size[x_root] += self._size[y_root]

    def same_set(self, x, y):
        return self.find(x) == self.find(y)

    def size(self, x):
        return self._size[self.find(x)]


def main():
    N, K = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))

    uf = UnionFind(N)
    for i, p in enumerate(P, 1):
        uf.union(i, p)

    ans = -float("inf")
    visited_cc = set()
    for i in range(1, N + 1):
        cc = uf.find(i)
        if cc in visited_cc:
            continue
        visited_cc.add(cc)

        CC = []
        j = P[i - 1]
        while True:
            CC.append(C[j - 1])
            if i == j:
                break
            j = P[j - 1]
        n_CC = len(CC)
        loop_cost = sum(CC)
        CC = list(accumulate([0] + CC * 2))

        if K < n_CC:
            cost = [-float("inf")] * n_CC
            for n_move in range(1, K):
                for j in range(n_CC):
                    tmp = CC[j + n_move] - CC[j]
                    cost[n_move - 1] = max(cost[n_move - 1], tmp)
            res = max(cost)
        else:
            cost = [-float("inf")] * n_CC
            for n_move in range(1, n_CC):
                for j in range(n_CC):
                    tmp = CC[j + n_move] - CC[j]
                    cost[n_move - 1] = max(cost[n_move - 1], tmp)
            q, r = divmod(K, n_CC)
            if loop_cost > 0:
                if r > 0:
                    res = max(loop_cost * q + max(cost[:r]), loop_cost * (q - 1) + max(cost))
                else:
                    res = max(loop_cost * q, loop_cost * (q - 1) + max(cost))
            else:
                res = max(cost)

        ans = max(ans, res)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
N, K = map(int, input().split())
P = tuple(map(int, input().split()))
C = tuple(map(int, input().split()))

G = [{} for _ in range(N)]
for i, p in enumerate(P):
    G[i][p-1] = C[p-1]

K = min(10 ** 3, K)
ans = -(10 ** 9 + 1)
todo = deque()
for s in range(N):
    todo.clear()
    todo.extend((p, 1, c) for p, c in G[s].items())
    while todo:
        p, count, point = todo.popleft()
        ans = max(ans, point)
        if count == K:
            break
        for np, c in G[p].items():
            todo.append((np, count + 1, point + c))
print(ans)

Submission status: Wrong Answer

Solution code:
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import itertools

n, k = list(map(int, input().split(" ")))
#n, k = 10, 33
p = list(map(int, input().split(" ")))
c = list(map(int, input().split(" ")))
#p = [9, 1, 6, 7, 8, 4, 3, 2, 10, 5]
#c = [8, 10, -2, 7, -3, -5, -4, 1, 6, 9]

max_score = 0
for start_position in range(1, len(p)+1):
    score = 0
    now_position = start_position
    for i in range(len(p)):
        now_position = p[now_position-1]
        score += c[now_position - 1]
        max_score = max(max_score, score)
        if now_position == start_position:
            # 2 shuume ikou
            if score <= 0:
                # shukai surukatinasi
                break
            else:
                # shukaino
                nokori_idou_kaisuu = k - (i+1)
                nokori_shukai_kaisuu = nokori_idou_kaisuu // (i+1)
                score += (nokori_shukai_kaisuu * score)
                max_score = max(score, max_score)

                nokori_idou_kaisuu = nokori_idou_kaisuu - (nokori_shukai_kaisuu * (i+1))
                now_position = start_position
                for i in range(nokori_idou_kaisuu):
                    now_position = p[now_position-1]
                    score += c[now_position-1]
                    max_score = max(max_score, score)
                break

if max_score == 0:
    print(max(c))
else:
    print(max_score)

Submission status: Wrong Answer

Solution code:
import numpy

n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
b=[False]*len(p)

l=[]
for i in range(len(p)):
    rootp=p[i]-1
    if not b[rootp]:
        b[rootp]=True
        ll=[c[rootp]]
        nextp=p[rootp]-1
        while nextp!=rootp:
            b[nextp]=True
            ll.append(c[nextp])
            nextp=p[nextp]-1
        ll.extend(ll)
        l.append(ll)

answer=0

for ll in l:
    res = numpy.cumsum(ll)
    s=res.tolist()
    maxn=0
    maxlength=10000
    
    if k>len(s)//2:
        for i in range(len(s)//2):
            if s[i]>=maxn:
                maxn=s[i]
                maxlength=min(maxlength,i+1)
        for i in range(1,len(s)//2+1):
            for j in range(len(s)//2):
                if s[i+j]-s[j]>=maxn:
                    maxn=s[i+j]-s[j]
                    maxlength=min(maxlength,i)
        
        ss=sum(ll)//2
        
        if ss>0:
            maxn+=((k-maxlength)//(len(s)//2))*ss
            
    else:
        for i in range(k):
            if s[i]>=maxn:
                maxn=s[i]
                maxlength=min(maxlength,i+1)
        for i in range(1,k+1):
            for j in range(len(s)//2):
                if s[i+j]-s[j]>=maxn:
                    maxn=s[i+j]-s[j]
                    maxlength=min(maxlength,i)
                
    answer=max(answer,maxn)
    
if answer==0:
    print(max(c))
else:
    print(answer)

Submission status: Wrong Answer

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

    score = [0]*(N)  # iから始めたときのスコア
    for i in range(N):
        s = i
        scos = [0]*N
        used = {s}
        lengt = 0
        ma = -(10**10)
        while lengt < K and P[s] not in used:
            s = P[s]
            scos[lengt+1] += scos[lengt] + C[s]
            used.add(s)
            lengt += 1
            ma = max(ma, scos[lengt])
        if K <= lengt:
            score[i] = max(scos[lengt], ma)
        else:
            cycle = scos[lengt] + C[i]
            score[i] = cycle * (K//(lengt+1))
            score[i] += scos[K % (lengt+1)]
            score[i] = max(score[i], ma)
    print(max(score))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

# ループを見つける(5000), 一周のスコアを確認
is_visit = [0 for _ in range(n)]
loop = []

def search(i, j):
    if is_visit[i] == 0:
        is_visit[i] = j
        l.append(i)
        search(p[i]-1, j)
    else:
        pass

loop_id = 1
for i in range(n):
    l = []
    search(i, loop_id)
    if len(l) != 0:
        loop.append(l)
        loop_id += 1
# print(loop)
# print(is_visit)
s_list = [0 for _ in range(len(loop))]
for i in range(len(s_list)):
    l = loop[i]
    s = 0
    for j in range(len(l)):
        s += c[l[j]]
    s_list[i] = s

ans = [0 for _ in range(n)]
for i in range(n):
    # i からはじめて最大スコア
    l = loop[is_visit[i]-1] # 所属するループ
    tmp1 = 0 # ループによるスコア
    tmp_k = k
    s = s_list[is_visit[i]-1]
    if s > 0 and k > 2*len(l):
        # 回るほどお得で一周より回れる
        tmp1 += s*(tmp_k//len(l))
        tmp_k -= (tmp_k//len(l))*len(l)
    elif s <= 0:
        tmp_k -= (tmp_k//len(l))*len(l)
        if tmp_k == 0:
            tmp_k = len(l)
    pointer = p[i]
    tmp2 = [c[pointer-1] for _ in range(tmp_k)] # 愚直に進んだ点数
    if tmp_k != 0:
        for j in range(1, tmp_k):
            # k回目までの累積和で最大を求める
            pointer = p[pointer-1]
            tmp2[j] = tmp2[j-1] + c[pointer-1]
    # print(i, l, s, tmp_k, tmp1, tmp2)
    if len(tmp2) != 0:
        ans[i] = tmp1 + max(tmp2)
    else:
        ans[i] = tmp1
# print(ans)
print(max(ans))

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

n, k = map(int, input().split())
p = [int(x) - 1 for x in input().split()]
c = [int(x) for x in input().split()]

ans = -float('inf')
for i in range(n):
    now = i
    c_sum = [0]
    s = set()
    cnt = 0
    while True:
        s.add(now)
        c_sum.append(c_sum[-1] + c[now])
        cnt += 1
        now = p[now]
        if now in s:
            break
    if k < cnt:
        if len(c_sum[1: k + 1]) > 0:
            ans = max(ans, max(c_sum[1: k + 1]))
    else:
        score = c_sum[-1]
        count = k // cnt
        k_ = k - count*cnt
        score *= count
        if len(c_sum[1: k_ + 1]) > 0:
            score += max(c_sum[1: k_ + 1])
        ans = max(ans, score)
        if len(c_sum[1:]) > 1:
            ans = max(ans, max(c_sum))
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = list(map(int,input().split()))
p = list(map(int,input().split()))
c = list(map(int,input().split()))
was = [False]*n
sums = []
for i in range(n):
    if not was[i]:
        iWas = [False]*n
        pos = i
        sumn = [c[i]]
        while not iWas[pos]:
            iWas[pos] = True
            was[pos] = True
            pos = p[pos]-1
            sumn+=[c[pos]]
        sumn = sumn[:-1]
        sums.append(sumn)
m = 0

for i in range(len(sums)):
    totS = sum(sums[i])
    l = len(sums[i])
    for g in range(len(sums[i])):
        arr = []
        s = 0
        for j in range(l):
            s+=sums[i][(g+j)%l]
            arr.append(s)

        if totS > 1:
            m = max(m,totS*(k//l)+max(arr[:l%k]+[0]))
        else:

            m = max(m, max(arr[:min(l,k)]))
print(m)

Submission status: Wrong Answer

Solution code:
import sys

ri = lambda: int(sys.stdin.readline())
rm = lambda: map(int, sys.stdin.readline().split())
rl = lambda: list(map(int, sys.stdin.readline().split()))

li = []
n, k = rm()
p = rl()
c = rl()
if all([x<0 for x in c]):
    print(max(c))
    exit()
for idx in range(n):
    if p[idx] != 0:
        tmp = []
        next_ = p[idx] - 1
        while p[next_] != 0:
            tmp.append(c[next_])
            p[idx] = 0
            idx = next_
            next_ = p[next_] - 1
        tmp.append(c[next_])
        p[idx] = 0
        if tmp:
            li.append(tmp)
max_ = 0
for lis in li:
    s = sum(lis)
    lenlis = len(lis)
    if k > lenlis and s > 0:
        c = k % lenlis
        if c == 0:
            max_ = max((k//lenlis * s), max_)
        else:
            lis += lis[:c]
            for i in range(lenlis):
                max_ = max(max_, sum(lis[i:i+c]) + (k//lenlis * s))
    else:
        for aaa in range(k):
            lis += lis[:aaa]
            for i in range(lenlis):
                max_ = max(max_, sum(lis[i:i+aaa]))
print(max_)

Submission status: Wrong Answer

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

def li():
    return [int(x) for x in input().split()]


N, K = li()
P = [0] + li()
C = [0] + li()
max_scores = [-10**12] * (N+10)
# for init_i in range(1, N+1):
#     i = init_i
#     scores = [-10**12] * (K+10)
#     scores[0] = 0
#     for l in range(1, K+1):
#         i = P[i]
#         scores[l] = scores[l-1] + C[i]
#     scores[0] = -10**12
#     max_scores[i] = max(scores)
print(max(max_scores))

Submission status: Wrong Answer

Solution code:
def main():
    n,k = map(int,input().split())
    p = list(map(int,input().split()))
    c = list(map(int,input().split()))
    vis = [0 for i in range(n)]
    grps = []
    g = 1
    for i in range(n):
        if vis[i] == 0:
            que = [i]
            vis[i] = g
            cnt = [i]
            while len(que)>0:
                st = que.pop(0)
                if vis[p[st]-1]!=0:
                    g += 1
                    grps.append(cnt)
                    break
                vis[p[st]-1] = g
                cnt.append(p[st]-1)
                que.append(p[st]-1)
    loop_sum = [0 for i in range(len(grps))]
    for i in range(len(grps)):
        s = 0
        for j in range(len(grps[i])):
            s += c[grps[i][j]]
        loop_sum[i] = s
        
    ans = -1 * float('inf')
    for i in range(len(grps)):
        g_len = len(grps[i])
        g_max = -1 * float('inf')
        for j in range(g_len):
            loop = k//g_len
            lost = k - loop*g_len
            if lost == 0:
                lost = g_len
                loop -= 1
            s = 0
            point = grps[i][j]
            for _ in range(lost):
                point = p[point]-1
                s += c[point]
                if s > g_max:
                    g_max = s
            s += loop * loop_sum[i]
            if ans < max(s,g_max):
                ans = max(s,g_max)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd
def maxSumSubSizek(arr, k): 
    n = len(arr)
    res = 0
    for i in range(k): 
        res += arr[i] 

    curr_sum = res 
    for i in range(k, n): 
        curr_sum += arr[i] - arr[i-k] 
        res = max(res, curr_sum) 
    return res 

def main():
    n,k = map(int, input().split())
    perm = [0] + list(map(int, input().split()))
    sqscore = [0] + list(map(int, input().split()))

    # start: 0 - (n-1).

    ans = -10**10
    visited = [0]*(n + 1)
    for i in range(1, n + 1):
        if not visited[i]:
            cycleScores = []
            j = i
            cycsum = 0
            maxsum = -10**10
            while not visited[j]:
                visited[j] = True
                score = sqscore[j]
                cycsum += score
                maxsum = max(maxsum, score)
                cycleScores.append(sqscore[j])
                j = perm[j]
            
            if maxsum <= 0:
                # All numbers are negative/0; take one step.
                ans = max(ans, maxsum)
            else:
                # positive numbers exist in cycle
                if k > len(cycleScores):
                    if cycsum <= 0:
                        msf = cycleScores[0]
                        for i in cycleScores[1:]:
                            msf = max(msf + i, i)
                            ans = max(ans, msf)
                    else:
                        # finish k/len(cycScores) cycles. Whatever is left, find subarray with max sum of that length
                        mult = k // len(cycleScores)

                        tempans = mult * cycsum
                        k -= mult * len(cycleScores)
                        
                        # find subarray of size k with in cycleScore with max Sum.
                        for step in range(1, k + 1):
                            ans = max(ans, tempans + maxSumSubSizek(cycleScores*2, step))
                else:
                    for step in range(1, k + 1):
                        ans = max(ans, maxSumSubSizek(cycleScores*2, step))
                    # k <= len(cycleScores)
    print(ans)


        




































# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
 
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    if all([c < 0 for c in C]):
        print(max(C))
        return
    visited = [0] * (n + 1)
    score = []
    d = {}
    for i, p in enumerate(P):
        d[i + 1] = p

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = d[p]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - 10 ** 10

    for s in score:
        tmp = 0
        le = len(s)
        if k > le:
            max_s = -10 ** 10
            div, mod = divmod(k, le)
            for i in range(le):
                tmp = 0
                for j in range(le):
                    p = i + j
                    if p >= le:
                        p -= le
                    if s[p] < 0:
                        max_s = max(tmp, max_s)
                        break
                    else:
                        tmp += s[p]
                else:
                    max_s = max(tmp, max_s)

            tmp = 0
            tmp += div * sum(s)
            s_r = s[-mod:] + s
            cum = np.cumsum(s_r)
            tmp += max([cum[mod - 1]] + [cum[i + mod] - cum[i]
                                         for i in range(le)])
            tmp = max(max_s, tmp)

        else:
            max_s = - 10 ** 10
            for i in range(le):
                tmp = 0
                for j in range(k):
                    p = i + j
                    if p >= le:
                        p -= le
                    if s[p] < 0:
                        max_s = max(tmp, max_s)
                        break
                    else:
                        tmp += s[p]
                else:
                    max_s = max(tmp, max_s)

            tmp = max_s
        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

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()))
# print(C)
ans = -float("inf")
hoge = K
for i in range(N):
    K = hoge
    start_point = i
    visited = set()
    ruisekiwa = [0]
    tmp = 0
    for j in range(min(K, N)):
        # とりあえず回数の許す限り次のマスへ行く
        # ループしているなら
        if P[start_point] in visited:
            break
        visited.add(P[start_point])
        ruisekiwa.append(ruisekiwa[-1]+C[P[start_point]])
        start_point = P[start_point]
    # ループが可能な場合
    if K > len(visited):
        # 可能な限りループする（最後の1回はループしない）
        tmp += ruisekiwa[-1]*(K//len(visited)-1)
        K %= len(visited)  # 余ったループ回数
        # 左側はもう1ループして，余力のループを行った場合．
        # 右側は最後の1ループを理想的なところで止めた場合
        # print("K %= N のあとの : ", K)
        if K != 0:
            tmp += max(ruisekiwa[-1]+max(ruisekiwa[1:K+1]), max(ruisekiwa[1:]))
        else:
            tmp += max(ruisekiwa)
        ans = max(ans, tmp)
    else:
        ans = max(ans, max(ruisekiwa[1:]))
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
c = tuple(map(int,input().split()))
for i in range(n):
  p[i] -= 1

ans = -10**9
v = [False for _ in range(n)]
for i in range(n):
  j = i
  if v[j]:
    continue
  r = []
  while(v[j] == False):
    r.append(j)
    v[j] = True
    j = p[j]
  s = 0
  rr = []
  f1 = True
  f2 = True
  for ri in r:
    s += c[ri]
    rr.append(c[ri])
    if c[ri] > 0:
      f1 = False
    if c[ri] < 0:
      f2 = False
  if s > 0:
  #if f2:
    k1 = k%len(r)
    k2 = k//len(r)
    rr = rr+rr
    now = 0
    for i in range(len(rr)-k1+1):
      now = max(sum(rr[i:i+k1]),now)
    now += s*k2
  else:
    if f1:
      now = -10**9
      for rri in rr:
        now = max(rri,now)
    else:
      rr = rr+rr
      a = 0
      b = 0
      now = -10**9
      while(b < len(rr)):
        if rr[a] <= 0:
          a += 1
          b += 1
        else:
          #print('a,b:',a,b)
          now = max(sum(rr[a:b+1]),now)
          b += 1
          if b-a >= k:
            a += 1
  #print(now,r)
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
from math import inf
input=stdin.readline
n,k=map(int,input().split())
arr=[0]+list(map(int,input().split()))
cost=[0]+list(map(int,input().split()))
ma=-inf
for i in range(1,n+1):
    m=1
    cur=arr[i]
    co=cost[cur]
    l=[0,co]
    ma = max(ma, l[-1])
    while(m<k and cur!=i):
        cur=arr[cur]
        co=cost[cur]
        l.append(l[-1]+co)
        m += 1
        ma=max(ma,l[-1])
    for j in range(k%m+1):
        ma = max(ma, l[-1] * (k//m) + l[j])
print(ma)

Submission status: Wrong Answer

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n, k = MAP()
p = LIST()
c = LIST()

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

ans = -inf
for i in range(n):
    visit = [inf]*n
    reg_score = [-inf]*n

    now = i
    count = 0
    score = 0
    while visit[now] == inf:
        visit[now] = count
        reg_score[now] = score
        count += 1
        now = p[now]
        score += c[now]

    x = visit[now]
    y = count - visit[now]
    X = reg_score[now]
    Y = score - reg_score[now]
    #print(i)
    #print(x, y, X, Y)

    #print(visit)
    #print(reg_score)

    for j in range(n):
        if visit[j] == inf:
            continue
        if j != i:
            tmp0 = reg_score[j]
            tmp1 = (k - x)//y * Y + reg_score[j]
            ans = max(ans, tmp0, tmp1)
        elif (k-x)//y>0:
            tmp0 = Y + reg_score[j]
            tmp1 = (k - x)//y * Y + reg_score[j]
            ans = max(ans, tmp0, tmp1)
        #print(i, j)
        #print(tmp0, tmp1)
        
        #if visit[j] == (k-x)%y + x:
        #    tmp = (k - x)//y * Y + reg_score[j]
        #    ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy

n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
#a = numpy.zeros((n, n), dtype=int)
tmp = 0
place = 0
ans = 0
for i in range(n):
    tmp = 0
    place = i
    if i == 0:
        ans = c[p[i] - 1]
    for j in range(k):
        tmp += c[p[place] - 1]
        #a[i][j] = tmp
        if ans < tmp:
            ans = tmp
        place = p[i] - 1
print(ans)

Submission status: Wrong Answer

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

#全ルートを列挙
start_kouho = list(range(1,N+1))
roots = []
while(start_kouho):
  s = start_kouho.pop(0)
  root_n = [s]
  while(1):
    _next = P[s-1]
    if not _next in root_n:
      root_n.append(_next)
      s = _next
    else:
      break
  start_kouho = sorted(list(set(start_kouho)-set(root_n)))
  roots.append(root_n)
#print(roots)

#それぞれ一周した時の得点point
#最大周回数saisyu　あまり行動数amakou
#あまり行動で
Maxes = []
for root in roots:
  point = sum([C[i-1] for i in root])
  saisyu = int(K/len(root))
  amakou = K-(saisyu*len(root))
  Plist = [C[i-1] for i in root]
  #print(root, point, saisyu, amakou, Plist)
  
  base = 0
  if sum(Plist) > 0:
    base = saisyu * sum(Plist)
  
  WPlist = Plist+Plist
  maxPoints = []
  for n in range(1, amakou+1):
    #print(n)
    #print(max([sum(WPlist[i:i+n]) for i in range(len(root))]))
    maxPoints.append(max([sum(WPlist[i:i+n]) for i in range(len(root))]))
  
  try:
    root_max_point = base + max(maxPoints)
  except:
    root_max_point = base
  
  if root_max_point == 0:
    root_max_point = max(Plist)
  #print(root_max_point)
  Maxes.append(root_max_point)

print(max(Maxes))

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
lis = [[0] * N for _ in range(N)]

for i in range(N):
    for j in range(N):
        if i > 0:
            lis[i][P[j]-1] = C[P[j]-1] + lis[i-1][j]
        else:
            lis[i][P[j]-1] = C[P[j]-1]

ans = -float('inf')
cnt = 0
if N >= K or sum(C) <= 0:
    K = K % N
    for l in lis:
        ans = max(ans,max(l))
        cnt +=1
        if cnt == K:
            break
else:
    div,K = divmod(K,N)
    K += 1
    tmp = [n * div for n in lis[-1]]
    lis = [[0] * N for _ in range(N)]
    lis[0] = tmp
    for i in range(1,N):
        for j in range(N):
            lis[i][P[j]-1] = C[P[j]-1] + lis[i-1][j]
    for l in lis:
        ans = max(ans,max(l))
        cnt +=1
        if cnt == K:
            break
print(ans)

Submission status: Wrong Answer

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
P = list(map(lambda x: x-1, P))

for i in range(N):
    visit = [False]*N
    now = i
    l = []
    visit[now] = True
    
    for j in range(N+10):
        nex = P[now]
        l.append(C[nex])
        
        if visit[nex]:
            break
        
        visit[nex] = True
        now = nex
    
    su = sum(l)
    
    if su>0:
        now = su*(K//len(l))
        rem = K-(K//len(l))*len(l)
        ans = max(ans, now)
        
        for j in range(rem):
            now += l[j]
            ans = max(ans, now)
    else:
        now = l[0]
        ans = max(ans, now)
        
        if K<len(l):
            for j in range(1, K):
                now += l[j]
                ans = max(ans, now)
        else:
            for j in range(1, len(l)):
                now += l[j];
                ans = max(ans, now)

print(ans)