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:
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

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

# ------------------- fast io --------------------
from math import gcd, ceil



def prod(a):
    ans = 1
    for each in a:
        ans = (ans * each)
    return ans

def lcm(a, b): return a * b // gcd(a, b)


def binary(x, length=16):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y
from math import inf

for _ in range(int(input()) if not True else 1):
    #n = int(input())
    n, k = map(int, input().split())
    #a, b = map(int, input().split())
    #c, d = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    ans = -inf
    for i in range(n):
        st = set()
        st.add(i)
        cur = i
        x = []
        while p[cur]-1 not in st:
            cur = p[cur]-1
            st.add(cur)
            x += [c[cur]]
        x += [c[p[cur]-1]]

        pre = [0]*len(x)
        pre[0] = x[0]
        for i in range(1, len(x)):
            pre[i] = pre[i-1] + x[i]
        if len(x) >= k:
            ans = max(ans, max(pre[:k]))
        else:
            kc = k
            anss = 0
            if pre[-1] > 0:
                anss += pre[-1]*(kc // len(x))
                kc = kc % len(x)
                if kc:
                    anss += max(pre[:kc])
                ans = max(ans, anss, max(pre)+(pre[-1]*((kc // len(x))-1)))
            else:
                ans = max(ans, max(pre))
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
from itertools import accumulate #list(accumulate(A))

N, K = mi()
P = li()
C = li()
ans = -float('inf')

for i in range(N):
    score = 0
    ind = i
    his = []
    while True:
        #ans = max(ans, score)
        #his.append(score)
        ind = P[ind] - 1
        #score += C[ind]
        his.append(C[ind])
        if ind == i:
            #print(his)
            his = list(accumulate(his))
            L = len(his)
            if K > L:
                if sum(his) >= 0:
                    if not K%L:
                        ans = max(ans, his[-1] * (K//L))
                    else:
                        ans = max(ans, max(his[:K%L]) + his[-1] * (K//L))
                else:
                    ans = max(ans, max(his))
            else:
                ans = max(ans, max(his))
            break

print(ans)

Submission status: Wrong Answer

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

ans = -float('inf')

for start in range(N):
    loop_len = 1
    pos = P[start]
    score = C[pos]
    scores = [score]
    while pos != start:
        loop_len += 1
        pos = P[pos]
        score += C[pos]
        scores.append(score)
    loops = (K-1)//loop_len
    cand = max(0, score * loops)
    cand += max(scores[:(K-loop_len * loops)+1])
    ans = max(ans, cand)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N, K = map(int, input().split())
    P = tuple(map(lambda x: int(x) - 1, input().split()))
    C = tuple(map(int, input().split()))
    ans = -10**18

    for i in range(N):
        k = K
        D = [[0, 0] for i in range(N)]
        x = i
        X, Y = 0, 0
        count = 0
        score = 0
        for j in range(K):
            if D[P[x]][0] == 0:
                score += C[P[x]]
                D[P[x]][0] = score
                D[P[x]][1] = count
                x = P[x]
                count += 1
            else:
                X = D[P[x]][0] - C[P[x]]
                score -= X
                L = (count - D[P[x]][1])
                k -= D[P[x]][1]
                score *= k // L
                l = K % L
                score += X
                ans = max(ans, score)
                for i in range(N):
                    if D[i][1] <= l + D[P[x]][1] - 1:
                        ans = max(ans, score + D[i][0] - X)
                break
            ans = max(ans, score)
    print(ans)


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

ans = -float('inf')

for start in range(N):
    loop_len = 1
    pos = P[start]
    score = C[pos]
    scores = [score]
    while pos != start:
        loop_len += 1
        pos = P[pos]
        score += C[pos]
        scores.append(score)
    loops = (K-1)//loop_len
    cand = max(0, score * loops)
    cand += max(scores[:(K-loop_len * loops+1)])
    ans = max(ans, cand)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

def main():
    N, K = map(int, input().split())
    P = [0] + list(map(int, input().split()))
    C = [0] + list(map(int, input().split()))
    circle_scores = [0] * (N + 1)
    circle_times = [0] * (N + 1)
    max_scores = [0] * (N + 1)
    # max_scores_times = [0] * N

    for i in range(1, N + 1):
        visited = set()
        now = i
        while now not in visited:
            visited.add(now)
            now = P[now]
            circle_scores[i] += C[now]
            circle_times[i] += 1
            if max_scores[i] < circle_scores[i]:
                # max_scores_times[i] = circle_times[i]
                max_scores[i] = circle_scores[i]
    #print("circle_scores={}".format(circle_scores))
    #print("circle_times={}".format(circle_times))
    #print("max_scores={}".format(max_scores))

    if max_scores == [0] * (N + 1):
        print(max(C[1:]))
        return


    ans = 0
    for i in range(1, N + 1):
        q, r = K // circle_times[i], K % circle_times[i]
        #print("q={}, r={}".format(q, r))
        val = circle_scores[i] * q
        if circle_scores[i] <= 0:
            val = 0
            r = K - 1
        add_val = 0
        add_max_val = 0
        now = i
        for _ in range(r):
            now = P[now]
            add_val += C[now]
            add_max_val = max(add_max_val, add_val)
            #print("add_val={}, add_max_val={}".format(add_val, add_max_val))
        #print(i, val, add_max_val)
        ans = max(ans, val + add_max_val)
    print(ans)



if __name__ == "__main__":
    main()

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

ans = 0
for i in range(N):
    score = C[P[i]-1]
    pos = P[i]-1
    for j in range(K-1):
        score += C[P[pos]-1]
        pos = P[pos]-1
    #if K>N:
        #score +=sum(C)*int(K/N)
    
    if i==0:
        ans = score
    else:
        ans = max(ans, score)

print(ans)

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

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
uf = UnionFind(N)
for i in range(N):
    uf.union(i, P[i]-1)

ans = -float("inf")
for x in uf.all_group_members().values():
    n = len(x)
    m_score = [-float("inf")] * (n+1)
    # K <= N のmax_scoreを求める。
    sum_c = 0
    for i in x:
        tmp_score = 0
        tmp_pos = i
        sum_c += C[i]
        for j in range(n):
            tmp_pos = P[tmp_pos]
            tmp_pos -= 1
            tmp_score += C[tmp_pos]
            m_score[j+1] = max(tmp_score, m_score[j+1])
    if K <= n:
        ans = max(ans, max(m_score[:K+1]))
    elif sum_c <= 0:
        ans = max(max(m_score), ans)
    else:
        ans = max(sum_c * (K//n) + max(m_score[:(K%n)+1]), ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)

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

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 in range(n):
        uf.union(i, p[i]-1)
    G = [[] for _ in range(uf.group_count())]
    idx = 0
    st = set()
    for i in range(n):
        if not i in st:
            x = i
            while not x in st:
                G[idx].append(c[x])
                st.add(x)
                x = p[x] - 1
            idx += 1
    ans = max(c) #1回動かした時の最大
    for i in range(len(G)):
        sum_g = sum(G[i])
        tmp_k = k
        if sum_g > 0:
            tmp = sum_g * (tmp_k // len(G[i]))
            tmp_k %= len(G[i])
            csum = [0]
            for v in G[i]:
                csum.append(v)
            for v in G[i]:
                csum.append(v)
            for j in range(len(csum)-1):
                csum[j+1] += csum[j]
            tmp_tmp = 0
            for j in range(len(G[i])):
                for l in range(1, tmp_k+1):
                    if tmp_tmp < csum[j+l] - csum[j]:
                        tmp_tmp = csum[j+l] - csum[j]
            tmp += tmp_tmp
            if ans < tmp:
                ans = tmp
        else:
            tmp_k = len(G[i])-1
            csum = [0]
            for v in G[i]:
                csum.append(v)
            for v in G[i]:
                csum.append(v)
            for j in range(len(csum)-1):
                csum[j+1] += csum[j]
            for j in range(len(G[i])):
                for l in range(1, tmp_k+1):
                    if ans < csum[j+l] - csum[j]:
                        ans = csum[j+l] - csum[j]
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    (n,k),p,c=[[*map(int,t.split())]for t in open(0)]
    m=-10**18
    for i in range(n):
        s=i
        t=1
        x=c[s]
        while p[s]-1!=i:
            s=p[s]-1
            t+=1
            x+=c[s]
        if x>0:
            a=k//t*x
            if a>m:m=a
            s=i
            for _ in range(k%t):
                s=p[s]-1
                a+=c[s]
                if a>m:m=a
        else:
            a=0
            s=i
            for _ in range(min(k,t)):
                s=p[s]-1
                a+=c[s]
                if a>m:m=a
    print(m)
main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N, K = map(int, input().split())
    P = tuple(map(lambda x: int(x) - 1, input().split()))
    C = tuple(map(int, input().split()))
    ans = -10**18

    for i in range(N):
        k = K
        D = [[0, 0] for i in range(N)]
        x = i
        X, Y = 0, 0
        count = 0
        score = 0
        for j in range(K):
            if D[P[x]][0] == 0:
                score += C[P[x]]
                D[P[x]][0] = score
                D[P[x]][1] = count
                x = P[x]
                count += 1
            else:
                X = D[P[x]][0] - C[P[x]]
                score -= X
                L = (count - D[P[x]][1])
                k -= D[P[x]][1]
                score *= k // L
                l = K % L
                score += X
                ans = max(ans, score)
                for i in range(N):
                    if D[i][1] <= l + D[P[x]][1] - 1:
                        ans = max(ans, score + D[i][0] - X)
                break
        ans = max(ans, score)
    print(ans)


main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def solve():
    ans = -inf
    for si in range(n):
        cs = [0]
        i = si
        for cnt in range(k):
            i = pp[i]
            cs.append(cs[-1] + cc[i])
            if i == si: break
        if len(cs) == k + 1 or cs[-1] <= 0: cur = max(cs[1:])
        else:
            d = len(cs) - 1
            c = k // d
            r = k - d * c
            cur = cs[-1] * c + cs[r]
        ans = max(ans, cur)
    print(ans)

inf=10**16
n,k=MI()
pp=LI1()
cc=LI()
solve()

Submission status: Wrong Answer

Solution code:
n, k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
ans = -10**18
for now in range(n):
	ruisekiwa = []
	tansaku = set()
	for i in range(n+1):
		targ = p[now]-1
		if len(ruisekiwa) >= 1:
			ruisekiwa.append(c[targ]+ruisekiwa[-1])
		else:
			ruisekiwa.append(c[targ])
		if targ in tansaku:
			break
		now = targ
		tansaku.add(targ)
	#print(ruisekiwa)
	if len(ruisekiwa) >= k-1:
		tr = max(ruisekiwa[:k])
		#print(tr)
		ans = max(ans, tr)
	else:
		if ruisekiwa[0] < ruisekiwa[-1]:
			#print(ruisekiwa[-1]-ruisekiwa[0])
			ms = (k//(len(ruisekiwa)-1))*(ruisekiwa[-1]-ruisekiwa[0])
			#print(ms)
			if k%(len(ruisekiwa)-1) >= 1:
				tr = max(max(ruisekiwa[:k%(len(ruisekiwa)-1)])+ms, max(ruisekiwa)+ms-(ruisekiwa[-1]-ruisekiwa[0]))
			else:
				tr = ms
			#print(tr)
			ans = max(ans, tr)
		else:
			tr = max(ruisekiwa)
			ans = max(ans, tr)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


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

    ans = -INF
    for i in range(N):
        seen = [False] * N
        s = 0
        s_max = -INF
        scores = []
        k = 0

        while k < K and not seen[i]:
            seen[i] = True
            s += C[P[i]]
            scores.append(s)
            if s_max < s:
                s_max = s
            i = P[i]
            k += 1

        if k == K and ans < s_max:
            ans = s_max
        elif scores[-1] > 0:
            tmp = max(s_max, scores[-1] * (K // k) + max(0, max(scores[: K % k], default=0)))
            if ans < tmp:
                ans = tmp
        else:
            if ans < s_max:
                ans = s_max

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    (n,k),p,c=[[*map(int,t.split())]for t in open(0)]
    m=-10**18
    for i in range(n):
        s=i
        t=1
        x=c[s]
        while p[s]-1!=i:
            s=p[s]-1
            t+=1
            x+=c[s]
        if x>0:
            a=k//t*x
            if a>m:m=a
            s=i
            for _ in range(k%t):
                s=p[s]-1
                a+=c[s]
                if a>m:m=a
        else:
            a=0
            s=i
            for _ in range(t):
                s=p[s]-1
                a+=c[s]
                if a>m:m=a
    print(m)
main()

Submission status: Wrong Answer

Solution code:
(N, K) = [int(x) for x in input().split()]
P = [int(x) - 1 for x in input().split()]  # 0 indexed
C = [int(x) for x in input().split()]


inf = float("inf")


def getScore(K):
    best = [-inf for i in range(N)]
    pos = list(range(N))
    score = [0 for i in range(N)]
    for k in range(K):
        nextPos = [0 for i in range(N)]
        for j in range(N):
            nextPos[P[j]] = pos[j]
            score[pos[j]] += C[P[j]]
        pos = nextPos
        best = [max(best[i], score[i]) for i in range(N)]
    return best, score


cycleLen = 0
pos = list(range(N))
while True:
    pos2 = [0 for i in range(N)]
    for i in range(N):
        pos2[P[i]] = pos[i]
    cycleLen += 1
    pos = pos2
    if pos == list(range(N)):
        break

numCycles, K = divmod(K, cycleLen)


best1, score1 = getScore(cycleLen)
if all(x < 0 for x in best1):
    print(max(best1))
    exit()

best2, score2 = getScore(K)

print(max(score1[i] * numCycles + max(0, best2[i]) for i in range(N)))

Submission status: Wrong Answer

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

ans = -float('inf')

for start in range(N):
    loop_len = 1
    pos = P[start]
    score = C[pos]
    scores = [score]
    while pos != start:
        loop_len += 1
        pos = P[pos]
        score += C[pos]
        scores.append(score)
    loops = (K-1)//loop_len
    cand = max(0, score * loops)
    cand += max(scores[:(K-loop_len * loops)])
    ans = max(ans, cand)
print(ans)

Submission status: Wrong Answer

Solution code:
def solve(n,x,k):
  ans=-10**20
  d=((k-1)//n)*sum(x)
  if k>n:ans=d
  s=0
  for i in x[:(k-1)%n+1]:
    s+=i
    ans=max(ans,s+d,s)
  return ans

n,k=map(int,input().split())
p=list(map(lambda x:int(x)-1,input().split()))
c=list(map(int,input().split()))
ans=-10**20
for i in range(n):
  x=[c[i]]
  j=p[i]
  while i!=j:
    x.append(c[j])
    j=p[j]
  x=x[1:]+[x[0]]
  ans=max(ans,solve(len(x),x,k))
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

score = 0
count = 0
i = 0
for _ in range(N):
  i = P[i]-1
  count += C[i]
k = K%N
score = (K//N)*count
if score < 0:
  score = 0
  if k == 0:
    k = 1
max_v = -10**9
for i in range(N):
  v = 0
  j = i
  for _ in range(k):
    j = P[j]-1
    v += C[j]
    max_v = max(max_v, v)


print(score+max_v)

Submission status: Wrong Answer

Solution code:
import sys

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
    n, k = nm()
    p = nl()
    c = nl()
    seen = [0] * n
    ans = max(c)
    for i in range(n):
        if seen[i]:
            continue
        g = list()
        v = i
        while not seen[v]:
            g.append(c[v])
            seen[v] = 1
            v = p[v] - 1
        m = len(g)
        for i in range(1, m):
            g[i] += g[i-1]
        if k <= m:
            for i in range(m):
                for j in range(i+1, i+k+1):
                    cur = 0
                    if j >= m:
                        cur += g[-1]
                        j -= m
                    cur += g[j] - g[i]
                    if ans < cur:
                        ans = cur
        else:
            for i in range(m):
                for j in range(i+1, i+m+1):
                    cur = 0
                    if j >= m:
                        cur += g[-1]
                        j -= m
                    cur += g[j] - g[i]
                    if g[-1] > 0:
                        cur += g[-1] * ((k - (j-i)%m)//m)
                    if ans < cur:
                        ans = cur
    print(ans)
    return

solve()

Submission status: Wrong Answer

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

def max2(x,y):
    return x if x > y else y

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

res = 0
k = K%N
cnt = K//N
S = sum(C)
if S > 0:
    res += cnt*S
off = max(C)


m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    for j in range(k):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    m2 = max2(m1, m2)
print(res + m2)

Submission status: Wrong Answer

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

ans=[]
for i in range(N):
    trace=[-1 for _ in range(N)]
    cand=[0]
    trace[i]=0
    pos=i
    cnt=1
    cond=False
    while cnt<=K:
        pos=P[pos]-1
        if trace[pos]==-1:
            cand.append(cand[-1]+C[pos])
            trace[pos]=cnt
            cnt+=1
        else:
            cond=True
            init=trace[pos]
            loop=cnt-init
            point=cand[-1]+C[pos]-cand[init]
            break
    if cond:
        cand.append(cand[init]+(K-init)//loop*point+cand[init+(K-init)%loop]-cand[init])
    ans.append(max(cand[1:]))
print(max(ans))

Submission status: Wrong Answer

Solution code:
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

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

# ------------------- fast io --------------------
from math import gcd, ceil



def prod(a):
    ans = 1
    for each in a:
        ans = (ans * each)
    return ans

def lcm(a, b): return a * b // gcd(a, b)


def binary(x, length=16):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y
from math import inf

for _ in range(int(input()) if not True else 1):
    #n = int(input())
    n, k = map(int, input().split())
    #a, b = map(int, input().split())
    #c, d = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    ans = -inf
    for i in range(n):
        st = set()
        st.add(i)
        cur = i
        x = []
        while p[cur]-1 not in st:
            cur = p[cur]-1
            st.add(cur)
            x += [c[cur]]
        x += [c[p[cur]-1]]

        pre = [0]*len(x)
        pre[0] = x[0]
        for i in range(1, len(x)):
            pre[i] = pre[i-1] + x[i]
        if len(x) >= k:
            ans = max(ans, max(pre[:k]))
        else:
            kc = k
            anss = 0
            if pre[-1] > 0:
                anss += pre[-1]*(kc // len(x))
                kc = kc % len(x)
                if kc:
                    anss += max(pre[:kc])
                ans = max(ans, anss, max(pre))
            else:
                ans = max(ans, max(pre))
    print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
L = []
S = set()
for i in range(N):
    if i in S:
        continue
    L.append([C[i]])
    S.add(i)
    tmp = i
    Next = P[i] - 1
    while Next != tmp:
        S.add(Next)
        L[-1].append(C[Next])
        Next = P[Next] - 1

ans = 0

for l in L:
    score = 0
    k = len(l)
    SUM = sum(l)
    l = [0] + l + l
    if SUM > 0:
        score = SUM * (K // k)
        m = K % k
        for i in range(2 * k):
            l[i+1] += l[i]
        for i in range(k):
            for j in range(i+1, i+m+1):
                ans = max(ans, score + l[j] - l[i])
        if K // k >= 1:
            score = SUM * (K // k - 1)
            m = k
            for i in range(2 * k):
                l[i+1] += l[i]
            for i in range(k):
                for j in range(i+1, i+m+1):
                    ans = max(ans, score + l[j] - l[i])
    else:
        m = k
        for i in range(2 * k):
            l[i+1] += l[i]
        for i in range(k):
            for j in range(i+1, i+m+1):
                ans = max(ans, score + l[j] - l[i])

if ans == 0:
    ans = max(C)

print(ans)