Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

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


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

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

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

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

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


ans = -10**20
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cum = list(itertools.accumulate(scores * 2))
    st = SegmentTree(cum, max, -10**20)
    ans = max([ans] + [
        st.query(start2 + 1, start2 + 1 + min(cyclelen, K)) - cum[start2]
        for start2 in range(cyclelen)
    ])
    cycle, residue = divmod(K, cyclelen)
    if cum[-1] > 0 and cycle > 0:
        v1 = cum[-1] * cycle // 2
        v2 = max(
            st.query(start2, start2 + residue + 1) - cum[start2]
            for start2 in range(cyclelen))
        ans = max(ans, v1 + v2)
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()))
root=[]
mi=set(range(n))
while mi:
  v=mi.pop()
  r=[c[v]]
  while p[v]-1 in mi:
    r.append(c[p[v]-1])
    mi.discard(p[v]-1)
    v=p[v]-1
  root.append(r)
inf=float('inf')
ans=-inf
for r in root:
  ansr=-inf
  k1=k%len(r)
  k0=k//len(r)
  cr=[0]
  tmp=0
  for ri in r:
    tmp+=ri
    cr.append(tmp)
  sumr=cr[-1]
  for ri in r:
    tmp+=ri
    cr.append(tmp)
  for i in range(len(r)):
    for j in range(i,i+min(k,len(r))):
      ansr=max(ansr,cr[j+1]-cr[i])
  ans=max(ans,ansr)
  if sumr>0:
    ansr=0
    for i in range(len(r)):
      for j in range(i,i+k1):
        ansr=max(ansr,cr[j+1]-cr[i])    
    ans=max(ans,ansr+sumr*k0)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for _ in range(N):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (circle_length, circle_score)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for i in range(1, circle_length+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = 0
    tmp_score = 0
    for _ in range(1, (K%circle_length)+1):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
        if i == K:
            return max_score + tmp_max_score
    return max_score + tmp_max_score

tot_max = -10**10
for i in range(N):
    circle_length, circle_score = f(i)
    max_score1 = f1(i, circle_length)
    max_score2 = f2(i, circle_length, circle_score)
    max_score = 0
    if max_score1 < max_score2:
        max_score = max_score2
    else:
        max_score = max_score1
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
root=[]
mi=set(range(n))
while mi:
  v=mi.pop()
  r=[c[v]]
  while p[v]-1 in mi:
    r.append(c[p[v]-1])
    mi.discard(p[v]-1)
    v=p[v]-1
  root.append(r)
inf=float('inf')
ans=-inf
for r in root:
  ansr=-inf
  k1=k%len(r)
  k0=k//len(r)
  cr=[0]
  tmp=0
  for ri in r:
    tmp+=ri
    cr.append(tmp)
  sumr=cr[-1]
  for ri in r:
    tmp+=ri
    cr.append(tmp)
  if sumr<0:
    for i in range(len(r)):
      for j in range(i,i+min(k,len(r))):
        ansr=max(ansr,cr[j+1]-cr[i])
    ans=max(ans,ansr)
  else:
    for i in range(len(r)):
      for j in range(i,i+k1):
        ansr=max(ansr,cr[j+1]-cr[i])
    ans=max(ans,ansr+sumr*k0)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for _ in range(N):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (circle_length, circle_score)

def f1(s, circle_length):
    tmp = s
    max_score = -10**10
    tmp_score = 0
    for _ in range(circle_length):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if max_score < tmp_score:
            max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
    return max_score

def f2(s, circle_length, circle_score):
    max_score = circle_score * (K//circle_length)
    tmp = s
    tmp_max_score = 0
    tmp_score = 0
    for _ in range(K%circle_length):
        tmp = P[tmp]
        tmp_score += C[tmp]
        if tmp_max_score < tmp_score:
            tmp_max_score = tmp_score
        if tmp_score < 0:
            tmp_score = 0
    max_score += tmp_max_score
    return max_score

tot_max = -10**10
for i in range(N):
    circle_length, circle_score = f(i)
    max_score1 = f1(i, circle_length)
    max_score2 = f2(i, circle_length, circle_score)
    max_score = 0
    if max_score1 < max_score2:
        max_score = max_score2
    else:
        max_score = max_score1
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

Solution code:
N, K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
def f(s):
    tmp = s
    circle_length = 0
    circle_score = 0
    for _ in range(N):
        tmp = P[tmp]
        circle_length += 1
        circle_score += C[tmp]
        if s == tmp:
            return (circle_length, circle_score)
tot_max = -10**10
for i in range(N):
    circle_length, circle_score = f(i)
    max_score = -10**10
    if circle_score < 0:
        tmp = i
        max_score = -10**10
        tmp_score = 0
        for _ in range(circle_length):
            tmp = P[tmp]
            tmp_score += C[tmp]
            if max_score < tmp_score:
                max_score = tmp_score
            if tmp_score < 0:
                tmp_score = 0
    else:
        max_score = circle_score * (K//circle_length)
        tmp = i
        tmp_max_score = 0
        tmp_score = 0
        for _ in range(K%circle_length):
            tmp = P[tmp]
            tmp_score += C[tmp]
            if tmp_max_score < tmp_score:
                tmp_max_score = tmp_score
            if tmp_score < 0:
                tmp_score = 0
        max_score += tmp_max_score
    if max_score > tot_max:
        tot_max = max_score
print(tot_max)

Submission status: Wrong Answer

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

maxpoints=[]
points=[]

for i in range(n):
    gone=set([])
    now=i
    next=p[now]
    point=c[next]
    maxpoint=[point]
    gone.add(i)

    for j in range(n+1):
        now=next
        next=p[now]
        if next in gone:
            point+=c[next]
            maxpoint.append(max(maxpoint[-1],point))
            maxpoints.append(maxpoint)
            points.append(point)
            break
        point+=c[next]
        gone.add(now)
        maxpoint.append(max(maxpoint[-1],point))
        #print(gone)
#print(maxpoints)
#print(points)

ans=-float('inf')

for i in range(n):
    if k<=len(maxpoints[i]):
        temp=maxpoints[i][k-1]
    elif points[i]<=0:
        temp=maxpoints[i][-1]
    else:
        times=k//len(maxpoints[i])
        rem=k%len(maxpoints[i])
        temp=points[i]*times
        if rem!=0:
            temp+=maxpoints[i][rem-1]
    ans=max(temp,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

INF = 10**18
score = -INF
for st in range(n):
    lc = 0 # lap count
    lap_c = 0 # lap cost
    nx = st
    while True:
        lc += 1
        lap_c += C[nx]
        nx = P[nx]
        if nx == st: break

    # print('lc {} '.format(lc))
    # print('lap_c {} '.format(lap_c))

    sum_c = 0
    cnt = 0
    while True:
        cnt += 1
        if k < cnt: break
        sum_c += C[nx]
        cost = lap_c * ((k - cnt) // lc) + sum_c
        score = max(score, cost)
        nx = P[nx]
        if nx == st: break

print(score)

# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)

    k =  K - (K//len(d)*len(d))
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(j,k,len(d))
    if K > len(d):
        val = (K//len(d)-1) * sum(d)
        ans = max(ans,val)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)
            #print(j)
        #print(K//len(d)-1,len(d),K)

print(ans)

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
    if K >= len(d):
        val = (K//len(d)-1) * sum(d)
        #ans = max(ans,val)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)
        #print(K//len(d)-1,len(d),K)

print(ans)

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
    if K > len(d):
        val = (K//len(d)-1) * sum(d)
        #ans = max(ans,val)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)
        #print(K//len(d)-1,len(d),K)

print(ans)

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
    if K > 2*len(d):
        val = (K//len(d)-1) * sum(d)
        ans = max(ans,val)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)
        #print(K//len(d)-1,len(d),K)

print(ans)

Submission status: Wrong Answer

Solution code:
def examA():
    S = SI()
    ans = 0
    if "R" in S:
        ans = 1
    if "RR" in S:
        ans = 2
    if "RRR" in S:
        ans = 3
    print(ans)
    return

def examB():
    N = I()
    L = LI()
    L.sort()
    cnt = 0
    for i in range(N):
        for j in range(i+1,N):
            for k in range(j+1,N):
                if L[i]==L[j]:
                    continue
                if L[j]==L[k]:
                    continue
                if L[i]+L[j]>L[k]:
                    cnt += 1
    ans = cnt
    print(ans)
    return

def examC():
    X, K, D = LI()
    if X<0:
        X = -X
    ans = inf
    if X>K*D:
        ans = X-K*D
        print(ans)
        return

    K -= X//D
    X -= D * (X//D)

    ans = X
    if K>0:
        if K%2==1:
            ans = abs(X-D)
    print(ans)
    return


def examD():
    N, K = LI()
    P = LI()
    C = LI()

    B = [i for i in range(N)]
    for i, p in enumerate(P):
        p -= 1
        B[i] = p

    locat_doubling = [[0] * N for _ in range(31)]
    score_doubling = [[0] * N for _ in range(31)]

    for i in range(N):
        locat_doubling[0][i] = i
        locat_doubling[1][B[i]] = i
        score_doubling[0][i] = 0
        score_doubling[1][B[i]] = C[i]
    for k in range(2, 31):
        for i in range(N):
            locat_doubling[k][i] = locat_doubling[k - 1][locat_doubling[k - 1][i]]
            score_doubling[k][i] = score_doubling[k - 1][i] + score_doubling[k - 1][locat_doubling[k - 1][i]]

    score = [[-inf for i in range(31)] for _ in range(N)]
    locate = [[i, i] for i in range(N)]
    ans = max(C)
    for i in range(N):
        score[i][0] = 0

    if ans <= 0:
        print(ans)
        return

    for k in range(30)[::-1]:
        for i in range(N):
            if score[i][k] < 0:
                continue
            # print(score[i],locate[i])
            if score_doubling[k + 1][locate[i][1]] > 0:
                score[i][1] += score_doubling[k + 1][locate[i][1]]
                locate[i][1] = locat_doubling[k + 1][locate[i][1]]

        if K & (1 << k) > 0:
            for i in range(N):
                if score[i][k] < score[i][0]:
                    score[i][k] = score[i][0]
                    locate[i][k] = locate[i][0]
                score[i][0] += score_doubling[k + 1][locate[i][0]]
                locate[i][0] = locat_doubling[k + 1][locate[i][0]]

    for s in score:
        ans = max(ans, s[0], s[1])
    print(ans)
    return

def examD2():
    N, K = LI()
    P = LI()
    C = LI()
    checked = [False]*N
    cycle = [[0]*2 for _ in range(N)]

    ans = max(C)
    if ans<=0:
        print(ans)
        return

    for i in range(N):
        if checked[i]:
            continue
        used = [False]*N
        v = i
        cnt = 0
        score = 0
        cycle_use = set()

        while(not used[v]):
            used[v] = True
            cnt += 1
            score += C[v]
            cycle_use.add(v)
            v = P[v]-1

        for i in cycle_use:
            cycle[i] = [cnt, score]
            checked[i] = True

    for i in range(N):
        c,s = cycle[i]
        if s<0:
            continue
        cur = s * ((K-c)//c)
        rest = K - c * ((K-c)//c)
        if ans<cur:
            ans = cur
        now = i
        for _ in range(rest):
            cur += C[now]
            now = P[now] - 1
            if ans<cur:
                ans = cur

    print(ans)
    return

def examE():
    R, C, K = LI()
    V = [[-inf]*C for _ in range(R)]
    for _ in range(K):
        r,c,v = LI()
        V[r-1][c-1] = v
    dp0 = [[0]*(C+1) for _ in range(R+1)]
    dp1 = [[0]*(C+1) for _ in range(R+1)]
    dp2 = [[0]*(C+1) for _ in range(R+1)]
    dp3 = [[0]*(C+1) for _ in range(R+1)]

    for r in range(R):
        for c in range(C):
            v = V[r][c]
            if 0<v:
                dp0[r+1][c+1] = max(dp0[r+1][c],dp0[r][c+1],dp1[r][c+1],dp2[r][c+1],dp3[r][c+1])
                dp1[r+1][c+1] = max(dp1[r+1][c],dp0[r+1][c]+v,dp0[r][c+1]+v,dp1[r][c+1]+v,dp2[r][c+1]+v,dp3[r][c+1]+v)
                dp2[r+1][c+1] = max(dp2[r+1][c],dp1[r+1][c]+v)
                dp3[r+1][c+1] = max(dp3[r+1][c],dp2[r+1][c]+v)
            else:
                dp0[r+1][c+1] = max(dp0[r+1][c],dp0[r][c+1],dp1[r][c+1],dp2[r][c+1],dp3[r][c+1])
                dp1[r+1][c+1] = dp1[r+1][c]
                dp2[r+1][c+1] = dp2[r+1][c]
                dp3[r+1][c+1] = dp3[r+1][c]

    ans = max(dp0[R][C],dp1[R][C],dp2[R][C],dp3[R][C])
    print(ans)
    return

def examF():
    N = I()
    S = ["" for _ in range(N)]
    C = [0 for _ in range(N)]
    for i in range(N):
        s, c = LSI()
        S[i] = s
        C[i] = c

    ans = 0
    print(ans)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examD2()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
    if K > len(d):
        val = (K//len(d)-1) * sum(d)
        ans = max(ans,val)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)


print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    INF = 10**9
    n,k = map(int,input().split())
    P = [0] + list(map(int,input().split()))
    C = [0] + list(map(int,input().split()))

    scores = [0]*n

    for s in range(1,n+1):
        start = s
        dp = [-INF]*(n+1)
        dp[0] = 0
        for i in range(n):
            p = P[s]
            dp[i+1] = dp[i] + C[p]
            
            if start == p:
                break
            s = p
        if k <= i+1:
            scores[start-1] = max(dp[1:k+1])
        elif dp[i+1]<=0:
            scores[start-1] = max(dp[1:])
        else:
            r = k%(i+1)
            q = k//(i+1)
            if r>0:
                scores[start-1] = max(max(dp[1:r+1])+dp[i+1]*q, max(dp[1:]))
            else:
                scores[start-1] = max(dp[i+1]*q, max(dp[1:]))

    print(max(scores))
main()

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
    if K >= len(d):
        val = (K//len(d)-1) * sum(d)
        ans = max(ans,val)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)

print(ans)

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
    if K > len(d):
        val = (K//len(d)-1) * sum(d)
        for j in range(len(d)):
            val += d[j]
            ans = max(ans,val)

print(ans)

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(min(K,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = 0
    val += (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
print(ans)

Submission status: Wrong Answer

Solution code:
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()))
ans = max(C)
for i in range(N):
    p = i
    d = []
    while True:
        p = P[p]
        d.append(C[p])
        if p == i:
            break
    #print(d,sum(d))
    val = 0
    for j in range(len(d)):
        val += d[j]
        ans = max(ans,val)
        #print(val,i,j)
    k = K % len(d)
    val = 0
    val += (K//len(d)) * sum(d)
    ans = max(ans,val)
    #print(val,K//len(d),k)
    for j in range(min(k,len(d))):
        val += d[j]
        ans = max(ans,val)
        #print(ans,i,j)
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()))

max_point = -(10**9)

if sum(C)>0:
    print("SUM:"+str(sum(C)))
    M = K//N
    K = K%N 
    for i in range(N):
        point = 0
        p_num = P[i]
        for j in range(K):
            point += C[p_num-1]
            p_num = P[p_num-1]
            if max_point < point:
                max_point = point
                print(max_point) 
    max_point = max_point + sum(C)*M
    
elif sum(C)<=0:
    for i in range(N):
        point = 0
        p_num = P[i]
        for j in range(K):
            point += C[p_num-1]
            p_num = P[p_num-1]
            if max_point < point:
                max_point = point            

print(max_point)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18

for saisyo in range(1,n+1):
    tensuulist=[]
    genzaiti=saisyo

    while(True):
        genzaiti=p[genzaiti]
        tensuulist.append(c[genzaiti])
        if genzaiti==saisyo:
            break

    goukei=sum(tensuulist)
    nagasa=len(tensuulist)
    kaisuu=k

    tensuu=0
    nokorikaisuu=0

    if goukei<=0:
        for i in range(nagasa):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)
    else:
        tensuu+=goukei*(kaisuu//nagasa)
        nokorikaisuu=kaisuu-(kaisuu//nagasa)*nagasa
        ans=max(ans,tensuu)

        if nokorikaisuu>0:
            for i in range(nokorikaisuu):
                tensuu+=tensuulist[i]
                ans=max(ans,tensuu)

print(ans)

Submission status: Wrong Answer

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

import copy
import numpy as np
D = copy.deepcopy(P)

ans = []
while(len(D)>0):
    s = D.pop(0)
    a = [P.index(s)]
    n = s
    while(True):
        n = P[n-1]
        D.pop(D.index(n))
        a.append(P.index(n))
        if n-1 == a[0]:
            break
    ans.append(a)

GrandMax = -np.inf
for a in ans:
    score = np.roll([C[aa] for aa in a],1)
    loop = sum(score)
    Max = -np.inf
    MaxS,MaxG = 0,0
    for i in range(len(a)):
        for j in range(len(a)):
            if i <= j:
                s = sum(score[i:j+1])
            else:
                s = sum(score[j:])+sum(score[:i+1])
            if s > Max:
                Max = s
                MaxS,MaxG = i,j
                lenM = MaxG-MaxS+1 if MaxS < MaxG else len(a) - (MaxG-MaxS)
    ansMax = -np.inf
    if loop > 0:
        l = (K-(lenM)) // len(a) 
        am = (K-(lenM)) % len(a)
        tMax = l*loop + Max
        ansMax = tMax
        for u in range(am):
            tMax += score[i-u-1]
            if tMax > ansMax:
                ansMax = tMax
    else:
        ansMax = Max        

    if GrandMax < ansMax:
        GrandMax = ansMax
print(GrandMax)

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

import copy
import numpy as np
D = copy.deepcopy(P)

ans = []
while(len(D)>0):
    s = D.pop(0)
    a = [P.index(s)]
    n = s
    while(True):
        n = P[n-1]
        D.pop(D.index(n))
        a.append(P.index(n))
        if n-1 == a[0]:
            break
    ans.append(a)

GrandMax = -np.inf
for a in ans:
    score = np.roll([C[aa] for aa in a],1)
    loop = sum(score)
    Max = -np.inf
    MaxS,MaxG = 0,0
    for i in range(len(a)):
        for j in range(len(a)):
            if i <= j:
                s = sum(score[i:j+1])
            else:
                s = sum(score[j:])+sum(score[:i+1])
            if s > Max:
                Max = s
                MaxS,MaxG = i,j
                lenM = MaxG-MaxS+1 if MaxS < MaxG else len(a) - (MaxG-MaxS)
    ansMax = -np.inf
    if loop > 0:
        l = (K-(lenM)) // len(a) 
        am = (K-(lenM)) % len(a)
        print(l,am)
        tMax = l*loop + Max
        ansMax = tMax
        for u in range(am):
            tMax += score[i-u-1]
            if tMax > ansMax:
                ansMax = tMax
    else:
        ansMax = Max        

    if GrandMax < ansMax:
        GrandMax = ansMax
print(GrandMax)