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 bisect
import sys
import math
from collections import deque
from heapq import heappush, heappop

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29

DIV = (10**9) + 7
#DIV = 998244353

def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            self.fac = fac
            self.finv = finv
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % DIV) % DIV

    return CONV()


def cumsum(As):
    s = 0
    for a in As:
        s += a
        yield s


sys.setrecursionlimit(200005)


def dijkstra(G,start=0):
    heap = []
    cost = [INF]*len(G)
    heappush(heap,(0,start))
    while len(heap)!=0:
        c,n = heappop(heap)
        if cost[n] !=INF:
            continue
        cost[n]=c
        for e in G[n]:
            ec,v = e
            if cost[v]!=INF:
                continue
            heappush(heap,(ec+c,v))
    return cost


def main():
    N,K = isRaw()
    Ps = isRaw()
    Cs = isRaw()
    ans = -INF
    for n in range(N):
        curPos = n
        cycles =[]
        visited = {}
        lastCost = 0
        vidx = 0
        loopStart = -1
        while True:
            visited[curPos] = vidx
            cycles.append(lastCost+Cs[curPos])
            curPos= Ps[curPos]-1
            lastCost = cycles[-1]
            if curPos in visited:
                loopStart = visited[curPos]
                break
        
        lc = len(cycles)

        divK = K//lc
        score = 0
        
        if cycles[-1]>0:
            score+=cycles[-1]*divK
        
        if K%lc ==0:
            score += max(cycles)
        else:
            score += max(cycles[:K % lc])

        ans = max(score,ans)
    print (ans)

         
main()

Submission status: Wrong Answer

Solution code:
import math


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N, K = read_ints()
    P = [p-1 for p in read_ints()]
    C = read_ints()

    max_score = -math.inf
    for i in range(N):
        cycle_score = C[i]
        scores = [0, C[i]]
        j = P[i]
        k = K
        while k > 1 and i != j:
            cycle_score += C[j]
            scores.append(cycle_score)
            j = P[j]
            k -= 1
        cycle_size = len(scores)-1
        cycle_count = K//cycle_size
        max_score = max(max_score, max(scores[1:]), cycle_score*cycle_count+max(scores[:K%cycle_size+1]))
    return max_score


if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

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

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 s in range(N):
    c = 0
    i = P[s]
    score = C[i]
    ans = max(ans, score)
    c += 1
    while i != s and c < K:
        i = P[i]
        score += C[i]
        ans = max(ans, score)
        c += 1
    if c == K:
        continue
    q, r = divmod(K, c)
    score *= q
    ans = max(ans, score)
    if r == 0:
        continue
    c = 0
    i = P[s]
    score += C[i]
    ans = max(ans, score)
    c += 1
    while c < r:
        i = P[i]
        score += C[i]
        c += 1
        ans = max(ans, score)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math

def calcweight_bellman_ford(N_vertices, start, edges, times, cost, inf):
    is_confirmed = [False] * N_vertices

    distances = [inf] * N_vertices
    distances[start] = 0
    flag_updated = True
    """
    edges: [start, dest, cost] -> [cost, start, end]
    """
    moved = [0] * N_vertices
    for time in range(times+2):
        for edge in edges:
            left = edge[1]
            dest = edge[2]
            cost = edge[0]
            if(distances[left] == inf or moved[left] >= times+2):
                continue

            if(distances[dest] > distances[left] + cost ):
                distances[dest] = distances[left] + cost
                moved[dest] = moved[left]+1

    if(moved[-1]==2):
        distances[-1] = cost * (-1)

    return distances


if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )

    edges = [ [] for _ in range(N+2) ]
    for i in range(N):
        edges[0].append([0, i]) #[cost, edge]
    for i in range(1, N+1):
        edges[i].append([0, N+1])
    for i in range(N):
        edges[i].append([ CList[i]*(-1), PList[i] ])
    """
    N, K= map(int, input().strip().split() )
    PList = list( map(int, input().strip().split() ) )
    CList = list( map(int, input().strip().split() ) )
    inf = 10**6

    N_vertices = 2+N

    edges3 = []
    costs = []
    for i in range(N):
        edges3.append([ CList[i]*(-1), i+1, PList[i] ])
        costs.append(CList[i])
    cost = max(costs)
    for i in range(N):
        edges3.append([0, 0, i+1]) #[cost, start, end]
    for i in range(1, N+1):
        edges3.append([0, i, N+1])



    weights =calcweight_bellman_ford(N_vertices, 0, edges3, K, cost, inf)


    print( (-1) * weights[-1])

Submission status: Wrong Answer

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

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


    max_score = -10 ** 20

    _K = K
    for i in range(N):
        K = _K
        cur = i
        score = 0
        mscore = -10 ** 10
        visited = {cur: (-1, 0)}
        
        move  = 0
        for j in range(K):
            if P[cur] in visited:
                break
            else:
                cur = P[cur]
                score += C[cur]
                visited[cur] = (j, score)
                max_score = max(max_score, score)
                move += 1
        
        if move == K:
            pass
        else:
            t = P[cur]
            T = j - visited[t][0]
            score += C[t]
            delta = score - visited[t][1]
            K -= 1

            K -= j
            n = K // T
            score += n * delta
            K -= T * n
            cur = t
            for j in range(K):
                cur = P[cur]
                score += C[cur]
                max_score = max(max_score, score)
    print(max_score)
solve()

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:
            if 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]
            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:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
C = [int(i) for i in input().split()]

ret = -float('inf')
done = set()
for n in range(N) :
  if n in done : continue
    
  cur = n
  s = C[cur]
  done.add(cur)
  loop = [n]
  while not P[cur] in done :
    cur = P[cur]
    done.add(cur)
    loop.append(cur)
    s += C[cur]
  
  if s <= 0:
    for i in loop :
      cur = i
      x = 0
      for _ in range(min(len(loop), K)) :
        cur = P[cur]
        x += C[cur]
        ret = max(ret, x)
  else :
    d = 0
    if K > 2 * len(loop) :
      d = s * (K // len(loop) - 2)
      K = K % len(loop) + 2 * len(loop)
      
    for i in loop :
      cur = i
      x = 0
      for _ in range(K) :
        cur = P[cur]
        x += C[cur]
        ret = max(ret, x + d)
      
print(ret)

Submission status: Wrong Answer

Solution code:
from collections import deque
import collections

mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]

N,K = MI()
P = LI()
C = LI()
max = 0
for i in range(N):
  start = i+1
  now = start
  score = 0
  time = 0
  while(time < K):
    time += 1
    score += C[P[now-1]-1]
    now = P[now-1]
    if(score > max):
      max = score
    if(start == now):break
print(max)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [float('-inf')] + list(map(int, input().split()))
ans = max(C)
for start in range(1, N+1):
    now = start
    score = 0
    c_list = []
    for k in range(1, K+1):
        now = P[now]
        cost = C[now]
        score += cost
        c_list += [cost]
        ans = max(ans, score)
        if now == start:
            Kmk = K-k
            score = score + score * (Kmk // len(c_list))
            ans = max(score, ans)
            for i in range(Kmk % len(c_list)):
                score += c_list[i]
                ans = max(score, ans)
            break
        

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 h in range(N):
                    if D[h][1] <= l + D[P[x]][1] - 1:
                        ans = max(ans, score + D[h][0] - X)
                break
            if score > ans:
                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=-10**18

for i in range(N):
    cnt=K
    pos=i
    tmp=[0]
    base=C[pos]
    while cnt and P[pos]!=i:
        pos=P[pos]
        tmp.append(tmp[-1]+C[pos])
        base+=C[pos]
        cnt-=1
    if base>0:
        test=base*(K//len(tmp))
        cnt=K%len(tmp)
        if cnt:
            ttt=max(tmp[j] for j in range(1,cnt+1))
            if test:
                ttt=max(ttt,0)
            test+=ttt
        ans=max(ans,test)
    else:
        tmp.append(tmp[-1]+C[i])
        cnt=min(K,len(tmp)-1)
        if cnt:
            test=max(tmp[j] for j in range(1,cnt+1))
            ans=max(ans,test)

print(ans)

Submission status: Wrong Answer

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

ans=[]
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+max(cand[init:init+(K-init)%loop+1])-cand[init])
    ans.append(max(cand[1:]))
print(max(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()))
p.insert(0, 0)
c.insert(0, 0)
now = 0
add = 0
ans = 0

for i in range(1,n+1):
    now = i
    add = 0
    for j in range(k):
        now = p[now]
        add += c[now]
        if add > ans:
          	ans = add
     
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()))
for i in range(N):
  P[i]-=1
INF=-(10**20)
X=[[INF]*(N+1) for i in range(N)]
Y=[0]*N
Z=[0]*N
R=[0]*N
S=set()
V=0
for i in range(N):
  S=set()
  V=i
  S.add(i)
  for j in range(N):
    V=P[V]
    if V in S:
      Z[i]=V
      break
  X[i][0]=0
  for j in range(N):
    Y[i]+=1
    V=P[V]
    X[i][j+1]=X[i][j]+C[V]
    if Z[i]==V:
      R[i]=X[i][j+1]
      break
A=INF
Q=0
T=0
U=0
D=0
E=0
for i in range(N):
  D=K
  V=i
  E=0
  for j in range(min(N,K)):
    if Z[i]==V:
      break
    V=P[V]
    E+=C[V]
    D-=1
  i=V
  D,K=K,D
  if R[i]<=0:
    for j in range(1,min(N,K)+1):
      A=max(A,X[i][j]+E)
  else:
    Q=R[i]*max((K//Y[i])-1,0)
    T=0
    U=INF
    V=i
    for j in range(min((K%Y[i])+Y[i],K)):
      V=P[V]
      T+=C[V]
      U=max(T,U)
    Q+=T
    A=max(A,Q+E)
  D,K=K,D
print(A)

Submission status: Wrong Answer

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

ans = -10**9
for i in range(1,N+1):
    p = i
    k = K
    max_score = -10**9
    score = 0
    visited = set([p])
    visited_lst = [p]
    score_lst = [0]
    while 0 < k:
        score += C[P[p]]

        max_score = max(max_score,score)
        score_lst.append(score)
        p = P[p]
        k -= 1
        # print(score)
        if p in visited:
            idx = visited_lst.index(p)
            l = len(score_lst)-1-idx
            if 0 < score-score_lst[idx]:
                # print(p,k,score,visited_lst,score_lst,score-score_lst[idx])
                score += (score-score_lst[idx])*(k//l)
                k %= l
                visited = set([p])
                visited_lst = [p]
                score_lst = [score]
                # print(k,score)
            else:
                break
        else:
            visited.add(p)
            visited_lst.append(p)
        # print(score,score_lst,visited_lst)
    # print(i,max_score)
    ans = max(ans,max_score)
print(ans)

Submission status: Wrong Answer

Solution code:
from math import floor,ceil,sqrt
import fractions
from collections import deque
import itertools
import collections
from heapq import *
#RRR...WWW...にしたい
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
suctable=[]
scoretable=[[0 for _ in range(N)] for _ in range(N)]
cyclesum=[]
for i in range(N):
    suctable.append(P[i]-1)
for i in range(N):
    #scoretable[i][0]=C[i]
    suc=suctable[i]
    l=[0]*N
    flag=0
    l[suc]=1
    for j in range(N-1):
        scoretable[i][j+1]=scoretable[i][j]+C[suc]
        suc=suctable[suc]
        if (l[suc]==0)and(flag==0):
            l[suc]=1
        else:
            flag=1
    #print(l)
    num=0
    num2=0
    for j in range(N):
        if l[j]==1:
            num=num+C[j]
            num2=num2+1
    cyclesum.append([num,num2])
#print(scoretable,cyclesum)
ma=-float("inf")
for i in range(N):
    if cyclesum[i][0]<=0:
        ma=max(ma,max(scoretable[i][1:(min(N,K+1))]))
    else:
        n=0
        if K<cyclesum[i][1]:
            n=max(scoretable[i][1:(min(N,K+1))])
        else:
            n = cyclesum[i][0] * (K // cyclesum[i][1])+max(scoretable[i][:(K%cyclesum[i][1])+1])
        ma=max(ma,n)
print(ma)

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 _ 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 + max(cs[:r+1])
        #print(cs)
        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)
			#print(len(ruisekiwa))
			if k%(len(ruisekiwa)-1) >= 1:
				tr = max(max(ruisekiwa[:k%(len(ruisekiwa)-1)])+ms, max(ruisekiwa)+ms-(ruisekiwa[-1]-ruisekiwa[0]))
			else:
				tr = max(ruisekiwa)+ms-(ruisekiwa[-1]-ruisekiwa[0])
			ans = max(ans, tr)
		else:
			tr = max(ruisekiwa)
			ans = max(ans, tr)
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)])
    ans = max(ans, cand)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10**6)
input = sys.stdin.readline

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

    ans = -float('inf')
    for n in range(N):
        m = n
        ans_tmp = 0
        cnt = 0
        repeat_flag = False
        for k in range(K):
            nxt = P[m]
            score = C[nxt-1]
            ans_tmp += score
            ans = max(ans, ans_tmp)
            m = nxt-1
            cnt += 1
            if m == n:
                repeat_flag = True
                break
        if not repeat_flag:
            continue
        divK = K//cnt
        if ans_tmp <= 0:
            continue
        repeat_ans_tmp = ans_tmp * divK
        for k in range(K%cnt):
            nxt = P[m]
            score = C[nxt-1]
            repeat_ans_tmp += score
            ans = max(ans, repeat_ans_tmp)
            m = nxt-1

    print(ans)


if __name__ == "__main__":
    main()

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

flag = [False for i in range(n + 1)]
r = []
num = 1
while num < n + 1:
    if flag[num] == False:
        temp = [c[num]]
        flag[num] = True
        num2 = p[num]
        while flag[num2] == False:
            flag[num2] = True
            temp.append(c[num2])
            num2 = p[num2]
        else:
            r.append(temp)
            num += 1
    else:
        num += 1
ans = -float("inf")
for i in r:
    temp = sum(i)
    sum_i = [0]
    for j in range(len(i)):
        sum_i.append(sum_i[-1] + i[j])
    for j in range(len(i)):
        sum_i.append(sum_i[j + 1] + temp)
    num1 = k % len(i)
    num2 = k // len(i)
    ans0 = -float("inf")
    if num2 >= 1:
        temp2 = -float("inf")
        for j in range(1, len(i)):
            for l in range(len(i)):
                temp2 = max(temp2, sum_i[l + j] - sum_i[l])
        ans0 = max(temp2, temp2 + temp * (num2 - 1))
    temp3 = -float("inf")
    for j in range(1, num1 + 1):
        for l in range(len(i)):
            temp3 = max(temp3, sum_i[l + j] - sum_i[l])
    ans0 = max(ans0, temp3, temp3 + temp * num2)
    ans = max(ans, ans0)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
*p, = map(int, input().split())
p = [v - 1 for v in p]
*c, = map(int, input().split())
minc = min(c)

ans = minc


def get_loop(i):
    pos = i
    cnt = 0
    cur_score = 0
    while cnt == 0 or pos != i:
        pos = p[pos]
        cur_score = cur_score + c[pos]
        cnt += 1
    return cnt, cur_score

# print(get_loop(2))

def solve(i, k):
    score = minc
    cur_score = 0
    pos = i
    loop_length, loop_score = get_loop(i)
    if k // loop_length > 0 and loop_score > 0:
        # print("%s: %s // %s, %s, %s" % (i, k, loop_length, cur_score, max_loop_score))
        cur_score = loop_score * (k // loop_length)
        score = max(cur_score, score)
        k %= loop_length
    else:
        k = min(k, n)
    # print('rem k', k, "cur_score", cur_score)
    for _ in range(k):
        pos = p[pos]
        cur_score += c[pos]
        score = max(cur_score, score)
    # print("%s: %s" % (i, score))
    return score

for i in range(n):
    ans = max(ans, solve(i, k))
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()))
X = -float('inf')
for i in range(1, N+1):
    now = i
    point_i = 0
    K_i = K
    while True:
        now = P[now]
        point_i += C[now]
        K_i -= 1
        X = max(X, point_i)
        if K_i == 0:
            break
        if now == i:
            roop = K - K_i
            roop_n = K // roop
            roop_r = K % roop
            point_i = point_i * roop_n
            X = max(X, point_i)
            if roop_r > 0:
                for j in range(roop_r):
                    now = P[now]
                    point_i += C[now]
                    X = max(X, point_i)
            break
print(X)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
INF = 10**18

n, k = map(int, input().split())
p = [int(item) - 1 for item in input().split()]
c = [int(item) for item in input().split()]
visited = [0] * n
cycles = []

for i in range(n):
    if visited[i]:
        continue
    nc = []
    v = i
    visited[v] = True
    nc.append(c[v])
    while not visited[p[v]]:
        v = p[v]
        visited[v] = True
        nc.append(c[v])
    cycles.append(nc)

ans = -INF 
for cycle in cycles:
    length = len(cycle)
    c_num = (k - 1) // length
    total = max(0, sum(cycle) * c_num)
    rest = k - (c_num * length)
    cycle = cycle + cycle
    for l in range(length):
        total_rest = 0
        for diff in range(rest):
            total_rest += cycle[l + diff]
            ans = max(ans, total + total_rest)

print(ans)

Submission status: Wrong Answer

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

N,K=(int(x) for x in input().rstrip('\n').split())
Ps = [int(x)-1 for x in input().rstrip('\n').split()]
Cs = [int(x) for x in input().rstrip('\n').split()]
res = -10**9-1
for i in range(N):
  next = Ps[i]
  cycle = [Cs[next]]
  for _ in range(K):
    next = Ps[next]
    cycle.append(Cs[next])
    if next == i:
      if sum(cycle)>0:
        now = (K//(len(cycle)))*sum(cycle)+sum(cycle[:(K%(len(cycle)))])
      else:
        now = Cs[Ps[i]]
      if now>res:
        res = now
      break
print(res)

Submission status: Wrong Answer

Solution code:
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

def maxsubarraysum(x):
    ans = -inf
    s = 0
    n = len(x)
    for i in range(n):
        s = max(x[i],s+x[i])
        ans = max(ans,s)
    return ans


def fun(x,k):
    ans = -inf
    x += x
    n = len(x)
    for i in range(1,k+1):
        s = 0
        for j in range(i):
            s += x[j]
        l = 0
        for j in range(i,n):
            ans = max(ans,s)
            s += x[j]
            s -= x[l]
            l += 1
        ans = max(ans,s)
    return ans 

def solve():
    
    # for _ in range(ii()):

        


    n,k = mi()
    p = li()
    c = li()

    vis = [0]*(n+1)
    a = []
    for i in range(n):
        if vis[i]:
            continue
        x = []
        j = i
        while(vis[j]==0):
            vis[j] = 1
            x.append(c[p[j]-1])
            j = p[j]-1
        a.append(x)
    

    ans = -inf

    for i in a:
        s = sum(i)
        # print(i)
        n = len(i)
        if n > k:
            s1 = fun(i,k)
        else:
            s1 = maxsubarraysum(i) 

        if(k > n):
            s2 = (k//n)*s
            s2 += fun(i,k%n)
            s1=max(s1,s2)
        ans = max(ans,s1)
    print(ans)
















        
if __name__ =="__main__":

    if path.exists('input.txt'):
        sys.stdin=open('input.txt', 'r')
        sys.stdout=open('output.txt','w')
    else:
        input=sys.stdin.readline
    solve()