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:
#!/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))

    ret = 0
    for i, loop in enumerate(loops):
        if loopScore[i] > 0:
            baseScore = loopScore[i] * (K // len(loop))
            r = K % len(loop)
            maxscore = 0
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores))
            ret = max(maxscore + baseScore, ret)
        else:
            r = len(loop)
            maxscore = -INF
            from collections import defaultdict
            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)

    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
"""


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


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: Wrong Answer

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 = [-INF] * N
    pos = list(range(N))

    ret = 0
    for i, loop in enumerate(loops):
        if loopScore[i] > 0:
            baseScore = loopScore[i] * (K // len(loop))
            r = K % len(loop)
            maxscore = 0
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores))
            ret = max(maxscore + baseScore, ret)
        else:
            r = len(loop)
            maxscore = 0
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores))
            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
"""


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


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: Wrong Answer

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

    ret = 0
    for i, loop in enumerate(loops):
        if loopScore[i] > 0:
            baseScore = loopScore[i] * (K // len(loop))
            r = K % len(loop)
            maxscore = 0
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores))
            ret = max(maxscore + baseScore, ret)
        else:
            r = len(loop)
            maxscore = 0
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores))
            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
"""


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


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: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

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

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

nk = input().split()
N = int(nk[0])
K = int(nk[1])

p = input().split()
p = [int(e) for e in p]
c = input().split()
c = [int(e) for e in c]
ans = 0
oneSum = 0
for i in range(N):
    oneSum += c[i]

if oneSum > 0:
    ans += oneSum*int(K/N)


K = K%N

oneMax = -99999999999

for start in range(N):
    tmpSum = 0
    i = start
    for k in range(K):
        tmpSum += int(c[i])
        i = p[i]-1
        if tmpSum > oneMax:
            oneMax = tmpSum

ans += oneMax

if ans == -99999999999:
    ans = max(c)

print(ans)

Submission status: Wrong Answer

Solution code:

#"""
N, K = [int(n) for n in input().split(" ")]
Ps = [int(n) for n in input().split(" ")]
Cs = [int(n) for n in input().split(" ")]
#"""
"""
N = 10
K = 58345
Ps = [9, 1, 6, 7, 8, 4, 3, 2, 10, 5]
Cs = [695279662, 988782657, -119067776, 382975538, -151885171, -177220596, -169777795, 37619092, 389386780, 980092719]
"""
"""
N = 3
K = 3
Ps = [3, 1, 2]
Cs = [-1000,-2000,-3000]
"""

circles = []
already = {}
for p in range(N):
    if p not in already:
        tmp = []
        nowp = p
        while nowp not in tmp:
            tmp.append(nowp)
            already[nowp] = 1
            nowp = Ps[nowp] - 1
        circles.append(tmp)

#print(circles)

finalResult = -100000000000

def getCircleScore(circle, start, kk):
    #print(circle, start, kk)
    s = 0
    for k in range(kk):
        index = start + k
        if index >= len(circle):
            index = index % len(circle)
        s += Cs[circle[index]]
    return s

"""
maxCircle = []
maxCircleScore = -10000000000
maxIndex = 0
for circle in circles:
    CircleSum = sum([Cs[n] for n in circle])
    if maxCircleScore <= CircleSum:
        maxCircleScore = CircleSum
        maxCircle = circle
"""
#for circle in [maxCircle]:
for circle in circles:
    
    CircleSum = sum([Cs[n] for n in circle])
    #print(circle, CircleSum)
    score = 0
    if CircleSum > 0:
        score = K // len(circle) * CircleSum

    K = K % len(circle)
    if K == 0:
        K = len(circle)

    maxScore = -100000000000
    for start in range(len(circle)):
        #print("start", start)
        for kk in range(1, K+1):
            s = getCircleScore(circle, start, kk)
            #print(s)
            if maxScore <= s:
                maxScore = s

    final = score + maxScore

    if final >= finalResult:
        finalResult = final

print(finalResult)

Submission status: Wrong Answer

Solution code:
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n,k=map(int,input().split())
P = list(map(int,input().split()))
for i in range(n):P[i] -= 1
C = list(map(int,input().split()))
max_val = -inf
for i in range(n):
  now = i
  point = 0
  max_point = -inf
  j = k
  data = [[-1]*2 for i in range(n)]
  while j >0:
    j-=1
    now = P[now]
    point += C[now]
    max_point = max(max_point,point)
    if data[now][0] == -1:
      data[now][0] = j
      data[now][1] = point
    else:
      if j == 0:break
      elif point - data[now][1] > 0:
        point += (point - data[now][1]) * ((j-1)//(data[now][0]-j))
        if j % (data[now][0]-j) != 0:j %= (data[now][0]-j)
        else :j == (data[now][0]-j)
      else:
        if j % (data[now][0]-j) != 0:j %= (data[now][0]-j)
        else :j == (data[now][0]-j)
      # print(i,j,point)
    max_point = max(max_point,point)
    # print(point)

  max_val = max(max_val,max_point)
  # print(max_point,i)
  # print(data)
  # print(max_point)
  # print(max_point,point)
print(max_val)
# print(const,max_val,k)
# print(l*const)

Submission status: Wrong Answer

Solution code:
#コマがマスiにあればコマをPiに移動させる
#このときスコアに+Cpiされる
def sugoroku():
    n,k=map(int,input().split())
    p=list(map(int,input().split()))
    c=list(map(int,input().split()))
    maxn=-10**15
    if k<=n:
        for i in range(n):
            ans=0
            koma=p[i]-1
            for _ in range(k):
                ans+=c[koma]
                koma=p[koma]-1
                maxn=max(ans,maxn)
        print(maxn)
        return

    else:
        suml=sum(c)
        if suml>0:
            ck=k%n
            loop=k//n
            for i in range(n):
                ans=0
                koma=p[i]-1
                for _ in range(ck):    
                    ans+=c[koma]
                    koma=p[koma]-1
                    maxn=max(ans,maxn)
            maxn=loop*suml+maxn
            print(maxn)
            return

        else: 
            for i in range(n):
                ans=0
                koma=p[i]-1
                for _ in range(n):    
                    ans+=c[koma]
                    koma=p[koma]-1
                    maxn=max(ans,maxn)
            print(maxn)
            return
sugoroku()

Submission status: Wrong Answer

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

check_list = [0] * (N + 1)

ans = min(C)


def search_max(p_list, n):
    result = min(p_list)
    point_list = p_list[:] + p_list[:] + p_list[:]
    for j in range(0, len(p_list)):
        total = 0
        for k in range(j, j + n):
            total += point_list[k]
            if total > result:
                result = total
    return result


for i in range(1, N + 1):
    if check_list[i] == 0:
        buf = i
        p = 0
        point = []

        while check_list[buf] == 0:
            check_list[buf] = 1
            buf = P[buf]
            p += C[buf]
            point.append(C[buf])

        len_p = len(point)
        division, mod = divmod(K, len_p)

        if p > 0:
            if len_p < K:
                max_p_total = search_max(point, len_p + mod)
                division -= 1
            else:
                max_p_total = search_max(point, K)
            point_buf = p * division + max_p_total
        else:
            if len_p <= K:
                max_p_total = search_max(point, len_p)
            else:
                max_p_total = search_max(point, K)
            point_buf = max_p_total

        if ans < point_buf:
            ans = point_buf

print(ans)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
Ps=[int(e)-1 for e in input().split()]
Cs=list(map(int,input().split()))

# グループ分け
nvst=set(Ps)
grps=[]
while len(nvst) > 0:
    s=set()
    score=0
    Pi=Pst=nvst.pop()

    s.add(Pi)
    while True:
        Pi =Ps[Pi]
        score += Cs[Pi]
        if Pi == Pst:
            break
        nvst.remove(Pi)
        s.add(Pi)
    grps.append((s,score))
#print(grps)

# ---
ans=-10**9
for grp in grps:
    s,score=grp
    n=len(s)
    
    q=K//n
    r=K%n
    #sumall=sum(Cs)
    l=[]
    for ist in s:
        Pi=Ps[ist]
        t_max=0
        t_max_i=-1
        t_sum=0
        for imv in range(r):
            t_sum+=Cs[Pi]
            if t_sum>=t_max:
                t_max=t_sum
                t_max_i=imv
            Pi=Ps[Pi]
        l.append((t_max,t_max_i))
        #l.append(t_max)

    ans_tmp=0
    if score > 0:
        ans_tmp+=score*q

    m,im=max(l)
    if m==0 and im==-1:
        if score<0 or q==0:
            m=max(Cs)
        else:
            m=0
    ans_tmp+=m

    if ans_tmp > ans:
        ans = ans_tmp 
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()))


score = -float("inf")
for x in range(1,len(P)+1):
    k = K
    curr_score = 0
    seen = {}
    while k > 0:
        x = P[x-1]
        curr_score += C[x-1]
        score = max(score, curr_score)
        if x in seen:
            # print(seen)
            # print(curr_score)
            if seen[x][1] >= curr_score:
                break
            else:
                cycle_size = k - seen[x][0]
                gain = curr_score - seen[x][1]
                cycle_num = k // cycle_size - 1
                curr_score += gain * cycle_num
                k -= cycle_size * cycle_num
                while k > 0:
                    x = P[x-1]
                    curr_score += C[x-1]
                    score = max(score, curr_score)
                    k -= 1
                break                 
        else:
            seen[x] = (k, curr_score)
        k -= 1

print(score)

Submission status: Wrong Answer

Solution code:
import sys

# D - Moving Piece
def get_dp(count):
	global P
	global C
	global dp

	# すべてのスタート位置を試す
	for i in range(N):
		score = 0
		pi = P[i] - 1

		for j in range(count):
			score += C[pi]
			dp[j] = max(dp[j], score)
			pi = P[pi] - 1


def get_max_score(scores):
	dp = [[0, 0]]
	max_score = 0

	for i in range(len(scores)):
		m = max(scores[i])
		max_score = max(max_score, m)

		dp.append([max_score, m])

	return dp


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

if max(C) <= 0:
	print(max(C))
elif K <= N:
	dp = [-sys.maxsize] * K
	dp.insert(0, 0)
	get_dp(K)

	print(dp[K])
else:
	dp = [-sys.maxsize] * N
	dp.insert(0, 0)
	get_dp(N)

	sum_C = sum(C)

	if sum_C <= 0:
		print(dp[N])
	else:
		ans = 0

		for i in range(1, N + 1):
			score = dp[i] + ((K - i)//N) *sum_C
			ans = max(ans, score)

		print(ans)

Submission status: Wrong Answer

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

    ans = -1e18
    for i in range(N):
        node_set = set()
        n = P[i]
        score = 0
        t = []
        while n not in node_set:
            score += C[n-1]
            t.append(score)
            node_set.add(n)
            n = P[n-1]

        if K < len(t):
            max_t = max(t[:K])
        else:
            if t[-1] > 0:
                max_t = t[-1] * int(K / len(t)) + max([0] + t[:K%len(t)])
            else:
                max_t = max(t)
        ans = max(ans, max_t)

    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

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

check_list = [0] * (N + 1)

ans = min(C)


def search_max(p_list, n):
    result = min(p_list)
    point_list = p_list[:] + p_list[:]
    for j in range(0, len(p_list)):
        total = 0
        for k in range(j, j + n):
            total += point_list[k]
            if total > result:
                result = total
    return result


for i in range(1, N + 1):
    if check_list[i] == 0:
        buf = i
        p = 0
        point = []

        while check_list[buf] == 0:
            check_list[buf] = 1
            buf = P[buf]
            p += C[buf]
            point.append(C[buf])

        len_p = len(point)
        division, mod = divmod(K, len_p)

        if p > 0:
            if len_p <= K:
                max_p_all = search_max(point, len_p)
                max_p_total = search_max(point, mod)
                if max_p_total + p > max_p_all:
                    point_buf = p * division + max_p_total
                else:
                    point_buf = p * (division - 1) + max_p_all
            else:
                max_p_total = search_max(point, K)
                point_buf = p * division + max_p_total
        else:
            if len_p <= K:
                max_p_total = search_max(point, len_p)
            else:
                max_p_total = search_max(point, K)
            point_buf = max_p_total

        if ans < point_buf:
            ans = point_buf

print(ans)

Submission status: Wrong Answer

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

check_list = [0] * (N + 1)

ans = min(C)


def search_max(p_list, n):
    result = min(p_list)
    point_list = p_list[:] + p_list[:]
    for j in range(0, len(p_list)):
        total = 0
        for k in range(j, j + n):
            total += point_list[k]
            if total > result:
                result = total
    return result


for i in range(1, N + 1):
    if check_list[i] == 0:
        buf = i
        p = 0
        point = []

        while check_list[buf] == 0:
            check_list[buf] = 1
            buf = P[buf]
            p += C[buf]
            point.append(C[buf])

        len_p = len(point)
        division, mod = divmod(K, len_p)

        if p > 0:
            max_p_all = search_max(point, len_p)
            if len_p <= K:
                max_p_total = search_max(point, mod)
                if max_p_total + p > max_p_all:
                    point_buf = p * division + max_p_total
                else:
                    point_buf = p * (division - 1) + max_p_all
            else:
                max_p_total = search_max(point, K)
                point_buf = p * division + max_p_total
        else:
            if len_p <= K:
                max_p_total = search_max(point, len_p)
            else:
                max_p_total = search_max(point, K)
            point_buf = max_p_total

        if ans < point_buf:
            ans = point_buf

print(ans)