Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

Solution code:
import sys
from io import StringIO
import unittest


def resolve():
    n, k = map(int, input().split())
    p = [0] + list(map(int, input().split()))
    c = [0] + list(map(int, input().split()))

    loop_list = []
    ans = -1 * 10 ** 9

    for i in range(len(p)):
        if i == 0:
            loop_list.append([[0, 0]]) # score, length
        else:
            tmp_score = c[i]
            tmp_length = 1
            j = i
            tmp_loop_list = [tmp_score]

            while i != p[j]:
                j = p[j]
                tmp_score += c[j]
                tmp_length += 1
                tmp_loop_list.append(tmp_score)

            loop_list.append(tmp_loop_list)

    for i, sub_loop_list in enumerate(loop_list):
        if i == 0:
            pass
        else:
            loop_score = sub_loop_list[-1]
            loop_length = len(sub_loop_list)
            tmp_ans = 0

            if loop_score > 0 and k > loop_length:
                tmp_ans += (k // loop_length) * loop_score
                remain_cnt = k - (k // loop_length) * loop_length

                if remain_cnt == 0:
                    pass
                else:
                    tmp_ans += max(sub_loop_list[0:remain_cnt])
            else:
                tmp_ans = max(sub_loop_list)

            if ans < tmp_ans:
                ans = tmp_ans

    print(ans)




class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """5 2
2 4 5 1 3
3 4 -10 -8 8"""
        output = """8"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """2 3
2 1
10 -7"""
        output = """13"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """3 3
3 1 2
-1000 -2000 -3000"""
        output = """-1000"""
        self.assertIO(input, output)

    def test_入力例_4(self):
        input = """10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719"""
        output = """29507023469"""
        self.assertIO(input, output)


if __name__ == "__main__":
    # unittest.main()
    resolve()

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

P = [p-1 for p in P]

check = [False] * n
loops = []

for i in range(n):
    if check[i]:
        continue
    check[i] = True
    next = P[i]
    tmp = [i]
    while next != i:
        check[next] = True
        tmp.append(next)
        next = P[next]
    loops.append(tmp)

# print(loops)

ans = 0

for loop in loops:

    num = len(loop)
    sho = k // num
    r = k % num
    if r == 0:
        r = num
    L = [C[p] for p in loop]

    ans_tmp = 0

    ryaku = 0
    if sum(L) > 0:
        ryaku = sum(L) * sho

    L += L
    ACC = [0] + list(accumulate(L))
    for i in range(num):
        for j in range(1, r+1):
            ans_tmp = max(ans_tmp, ACC[i+j]-ACC[i]+ ryaku)

    ans = max(ans, ans_tmp)
if ans == 0:
    print(max(C))
    exit()
print(ans)

Submission status: Wrong Answer

Solution code:
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))

dic_s={}
dic_i={}

for i in range(1,n+1):
    if not i in dic_i:
        dic_s[i]=0
        j=i
        while not j in dic_i:
            dic_i[j]=1
            j=p[j-1]
            dic_s[i]+=1

ans=-float('inf')
for i in dic_s.keys():
    lst_c=[]
    # print(i)
    for j in range(dic_s[i]):
        i=p[i-1]
        lst_c.append(c[i-1])
    # print(lst_p)
    # print(lst_c)
    # print(i)
    cnt=0
    sm=sum(lst_c)
    lst=lst_c+lst_c
    if sm>0 and k>=dic_s[i]:
        cnt+=sm*(k//dic_s[i])
        cnt2=-float('inf')
        for j in range(dic_s[i]):
            tmp=0
            for l in range(k%dic_s[i]):
                tmp+=lst[j+l]
                cnt2=max(cnt2,tmp)
        ans=max(ans,cnt+cnt2)

    # else:
        # lst=lst_c+lst_c
    cnt2=-float('inf')
    for j in range(dic_s[i]):
        tmp=0
        for l in range(min(k,dic_s[i])):
            tmp+=lst[j+l]
            cnt2=max(cnt2,tmp)
        # print(cnt2)
    ans=max(ans,cnt2)

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

cycles = []
cycleSums = []
visited = [False]*N
for i, p in enumerate(Ps):
    if visited[i]:
        continue
    cycle = []
    now = i
    S = 0
    while not visited[now]:
        visited[now] = True
        now = Ps[now] - 1
        cycle.append(Cs[now])
        S += Cs[now]
    cycles.append(cycle)
    cycleSums.append(S)

ans = float('-inf')
for cycle, cycleSum in zip(cycles, cycleSums):
    L = len(cycle)
    cycle = cycle + cycle
    DPL = ((K-1) % L + 1) + 1
    M = float('-inf')
    dp = [None]*DPL
    dp[0] = 0
    for c in cycle:
        ndp = [None]*DPL
        ndp[0] = 0
        for i in range(1, DPL):
            if dp[i-1] is None:
                break
            tmp = dp[i-1] + c
            ndp[i] = 0 if 0 > tmp else tmp
            M = M if M > tmp else tmp
        dp = ndp
    if cycleSum > 0:
        if K % L != 0:
            tmp = cycleSum * (K // L) + M
        else:
            tmp = cycleSum * ((K // L)-1) + M
    else:
        tmp = M
    ans = ans if ans > tmp else tmp

print(ans)

Submission status: Wrong Answer

Solution code:
def roop(i,K):
    isroop=False
    last=[-1]*N
    lastcnt=[-1]*N
    n=i
    last[n]=0
    lastcnt[n]=0
    roopp=-1#ループ1回のポイント
    cnt=0#
    rs=-1#ループ開始
    maxp=-10**30
    point=0
    while(True):
        cnt+=1
        n=P[n]
        point+=C[n]
        maxp=max(maxp,point)
        if last[n]!=-1:
            roopp=point-last[n]
            syuki=cnt-last[n]#ループ周期
            isroop=True
            rs=n
            start=last[n]
            break
        last[n]=point
        lastcnt[n]=cnt
        if cnt==K:
            break
    if not isroop:
        return  maxp
    K-=lastcnt[rs]
    allpoint=(K//syuki)*roopp
    K%=syuki
    j=0
    n=rs
    point=0
    maxpp=0
    while(j<K):
        j+=1
        n=P[n]
        point+=C[n]
        maxpp=max(maxpp,point)
    if rs!=i:
        return max([start,start+allpoint,start+allpoint+maxpp])
    else:
        return max([allpoint,allpoint+maxpp,maxp])
        
        
        

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

ans=-10**30
for i in range(N):
    r=roop(i,K)
    ans=max(ans,r)
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()))

S = []
for i in range(N):
    p, si = i, [0]
    ps = set()
    while P[p] not in ps:
        p = P[p]
        ps.add(p)
        si.append(si[-1] + C[p])
    si = si[1:]
    S.append(si)


ans = -float('inf')
for i in range(N):
    if K >= len(si):
        ans = max(ans, max(S[i]), S[i][-1] * (K // len(S[i])) + max(S[i][:(K % len(S[i]))] + [0]))
    else:
        ans = max(ans, max(S[i]))

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 = -1000000000
for i in range(N):
  cost = 0
  S = []
  x = P[i] - 1
  l = 1
  while 1:
    cost += C[x]
    S.append(cost)
    if x == i:
      break
    l += 1
    x = P[x] - 1
  if cost > 0:
    if K % l != 0:
      ans = max(ans, cost * (K // l) + max(S[:K % l]))
    else:
      ans = max(ans, cost * (K // l))
  else:
    ans = max(ans, max(S))
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 = float('-inf')

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(pos, k):
    score = minc
    cur_score = 0
    loop_length, loop_score = get_loop(pos)
    if k >= loop_length 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, loop_length)
    # 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 = list(map(int, input().split()))
C = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1

ans = -10**10
for i in range(N):
    T = []
    Check = [0]*N
    move = i
    count = 1
    while(True):
        if Check[move] != 0:
            break
        Check[move] = count
        T.append(C[P[move]])
        move = P[move]
        count += 1
    s = Check[move] - 1
    result_1 = -10**10
    total = 0
    for j in range(min(s, K)):
        total += T[j]
        result_1 = max(result_1, total)
    result_2 = -10**10
    total = 0
    for j in range(min(len(T), K)):
        total += T[j]
        result_2 = max(result_2, total)
    if K >= len(T):
        result_3 = 0
        result_3 += sum(T[:s])
        result_3 += sum(T[s:])*((K - len(T[:s])) // len(T[s:]))
        result_4 = result_3
        total = result_3
        for j in range((K - len(T[:s])) % len(T[s:])):
            total += T[j]
            result_3 = max(result_3, total)
        total = result_4
        for j in T[s:][::-1]:
            total -= j
            result_4 = max(result_4, total)
    if K >= len(T):
        ans = max([result_1, result_2, result_3, result_4, ans])
    else:
        ans = max([result_1, result_2, ans])
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 (0, N):
    P[i] = P[i]-1

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

uf = UnionFind(N)

for i in range (0, N):
    uf.union(i, P[i])

D = list(uf.all_group_members().values())
A = [0]*N

for i in range (0, len(D)):
    V = D[i]
    sV = 0
    for l in range (0, len(V)):
        sV+=C[V[l]]
        if sV >= 0:
            for j in range (0, len(V)):
                V = D[i]
                W = V[j:N]+V[0:j]
                if K%len(V)> 0:
                    extramatrix = [0]*(K%len(V))
                    for k in range (0, K%len(V)):
                        extramatrix[k]=C[W[k]]
                    for k in range (1, K%len(V)):
                        extramatrix[k]+= extramatrix[k-1]
                    extra = max(extramatrix)
                else:
                    extra = 0
                A[V[j]] = sV*(K//len(V))+extra
        else:
            for j in range (0, len(V)):
                V = D[i]
                W = V[j:N]+V[0:j]
                if K%len(V)> 0:
                    extramatrix = [0]*(K%len(V))
                    for k in range (0, K%len(V)):
                        extramatrix[k]=C[W[k]]
                    for k in range (1, K%len(V)):
                        extramatrix[k]+= extramatrix[k-1]
                    extra = max(extramatrix)
                else:
                    extramatrix = [0]*(len(V))
                    for k in range (0, len(V)):
                        extramatrix[k]=C[W[k]]
                    for k in range (1, len(V)):
                        extramatrix[k]+= extramatrix[k-1]
                    extra = max(extramatrix)
                A[V[j]] = extra

print(max(A))

Submission status: Wrong Answer

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

Scores = [0]*N
ans = 0

for k in range(K):
    P_new = []
    for i in range(N):
        Scores[i] += C[P[i]-1]
        P_new.append(P[P[i]-1])
    ans = max(max(Scores),ans)
    P = P_new
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n,k = na()
p = na()
c = na()

s = set(range(n))

ans = 0
loops = []
while s:
    loop = [0]
    a = s.pop()
    while True:
        loop.append(loop[-1]+c[p[a]-1])
        if p[a]-1 not in s:
            break
        a = p[a]-1
        s.discard(a)
    loops.append(loop[1:])

ans = -1000000000000000
for tmp in loops:
    kk = k
    if k > len(tmp): kk = len(tmp) if k%len(tmp)==0 else k%len(tmp)
    loop = [0]+tmp+[tmp[-1]+u for u in tmp]
    x = -1000000000
    for i in range(1,kk+1):
        for j in range(len(tmp)+1):
            x = max(x,loop[j+i]-loop[j])
    if k > len(tmp) and tmp[-1] > 0:
        x += tmp[-1]*(k//len(tmp))
    ans = max(ans,x)

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

ans = 0
for i in range(N):
    score = 0
    
    pos = [P[i]-1]
    for j in range(N-1):
        if pos.count(P[pos[j]]-1)==0:
            pos.append(P[pos[j]]-1)
        else:
            break
            
    for j in range(K%len(pos)):
        score += C[pos[j]]
    
    if K > len(pos):
        sc = 0
        for j in pos:
            sc += C[j]
        score += sc * int(K/len(pos))
    
    if i == 0:
        ans = score
    else:
        ans = max(ans,score)

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

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  #このwhileはせいぜい5000
  while True:
    if masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    if ans22<=ans:
      ans22=ans
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=(k//count)*ans
    for i in range(k-(k//count)*count):
      ans+=c[now_mas-1]
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  elif junkan_flag==True and ans<0:
    return max(ans,ans22)
  else:
    return max(ans,ans22)
hantei=0
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ <= hantei:
    answ=hantei
print(answ)

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 = [p-1 for p in P]

D = [[-10**18]*(n+1) for _ in range(n)]
for i in range(n):
    D[i][0] = 0
Q = [0]*n
A = [0]*n
for i in range(n):
    pos = i
    for j in range(n):
        D[i][j+1] = C[P[pos]]+D[i][j]
        pos = P[pos]
        if pos == i:
            break
    Q[i] = D[i][j+1]
    A[i] = j+1
#print(D)
#print(Q)
#print(A)


ans = -10**18

for i in range(n):
    if k < A[i]:
        for j in range(A[i]):
            ans = max(D[i][j+1], ans)
    else:
        if D[i][0] > Q[i]:
            for j in range(A[i]):
                ans = max(D[i][j+1], ans)
        else:
            q, r = divmod(k, A[i])
            temp = (q-1)*Q[i]
            if q-1 != 0:
                ans = max(temp, ans)
            for j in range(A[i]):
                ans = max(D[i][j+1]+temp, ans)
            temp = q*Q[i]
            ans = max(temp, ans)
            for j in range(r):
                ans = max(D[i][r]+temp, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

N, K = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))
# print()
# print(*P)
# print(*C)
x = 0
used = [0] * N
path = defaultdict(list)
score = defaultdict(list)
for i in range(N):
    if used[i]:
        continue
    x = i
    while used[x] == 0:
        used[x] = 1
        path[i].append(x)
        score[i].append(C[x])
        x = P[x]
ans = -float('inf')
for r in path:
    pa, sc, le = path[r], score[r], len(path[r])
    # print(pa, sc, le)
    for i in range(le-1):
        sc[i+1] += sc[i]
    if sc[-1] <= 0:
        m = -float('inf')
        for i in range(len(pa)):
            for j in range(i+1, len(pa)):
                if j - i <= K:
                    m = max(m, sc[j] - sc[i])
                if le - j + i <= K:
                    m = max(m, sc[-1] - sc[j] + sc[i])
        ans = max(ans, m)
    else:
        k = K % le
        m = -float('inf')
        for i in range(le):
            for j in range(i+1, le):
                if j - i <= k:
                    m = max(m, sc[j] - sc[i])
                if le - j + i <= k:
                    m = max(m, sc[-1] - sc[j] + sc[i])
        ans = max(ans, m + sc[-1] * (K // le))

        k = min(le, K)
        m = -float('inf')
        for i in range(le):
            for j in range(i+1, le):
                if j - i <= k:
                    m = max(m, sc[j] - sc[i])
                if le - j + i <= k:
                    m = max(m, sc[-1] - sc[j] + sc[i])
        if (K // le) > 1:
            ans = max(ans, m + sc[-1] * ((K // le) - 1))
        else:
            ans = max(ans, m)
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# map(int, input().split())
def junkan_max_score_limitK(junkan, ruiseki, K):
    return max(ruiseki[1:K+1])

def junkan_max_score(junkan, C, K):
    ruiseki = [0]
    for i in range(len(junkan)):
        if i < len(junkan)-1:
            j = junkan[i+1]
        else:
            j = junkan[0]
        ruiseki.append(ruiseki[-1]+C[j])

    n_junkan = int(K/len(junkan))
    if n_junkan == 0 or ruiseki[-1] <= 0:
        if K%len(junkan) != 0:
            base_score = 0
        else:
            base_score = junkan_max_score_limitK(junkan, ruiseki, len(junkan))
    else:
        base_score = n_junkan*ruiseki[-1]

    nokori_K = K-(n_junkan*len(junkan))
    if nokori_K == 0:
        return base_score
    else:
        return base_score+junkan_max_score_limitK(junkan, ruiseki, nokori_K)

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

p_junkan = {i:[i] for i in range(N)}

for i, lst in p_junkan.items():
    j = P[i]-1
    while j != i:
        lst.append(j)
        j = P[j]-1


junkan_max = [junkan_max_score(lst, C, K) for i,lst in p_junkan.items()]
print(max(junkan_max))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
ps = list(map(int, input().split()))
cs = list(map(int, input().split()))
ps = [p-1 for p in ps]
visited = [False] * n
from collections import deque
ds = []
sums = []
for i in range(n):
    if visited[i]: continue
    q = deque([])
    q.append(i)
    s = cs[i]
    d = [i]
    while len(q) > 0:
        u = q.popleft()
        visited[u] = True
        nx = ps[u]
        if visited[nx]: continue
        d.append(nx)
        q.append(nx)
        s += cs[nx]
    sums.append(s)
    ds.append(d)

# print(ds,sums)
from itertools import accumulate
def calcmax(d,s,k,cs):
    cnt = 0
    l = len(d)
    div, rest_ = divmod(k-1, l)
    rest_ += 1
    if s > 0:
        cnt += div*s
    d2 = d*2
    mx = - 1<<50
    c_ = [cs[j] for j in d2]
    acc = list(accumulate([0]+c_))
    for rest in range(1,rest_+1):
        for i in range(rest,l*2+1):
            c = acc[i] - acc[i-rest]
            mx = max(mx, c)
    # print(d,cnt,mx)
    return cnt + mx

ans = -1 << 50
for d,s in zip(ds,sums):
    # print("aaa",d,s)
    c = calcmax(d,s,k,cs)
    ans = max(ans,c)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

# https://note.nkmk.me/python-union-find/

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 = ns()
    p = na1()
    c = na()

    uf = UnionFind(n)
    for i, pi in enumerate(p):
        uf.union(i, pi)

    cycledist = [[-INF for _ in range(2)] for __ in range(n)]
    for lis in uf.all_group_members().values():
        if cycledist[lis[0]][0] != -INF:
            continue
        tmp = 0
        l = len(lis)
        for idx in lis:
            tmp += c[idx]
            cycledist[idx][1] = l
        for idx in lis:
            cycledist[idx][0] = tmp

    ans = -INF

    for i in range(n):
        tmp_ans = cycledist[i][0] * (k // cycledist[i][1])

        tmp = 0
        idx = i
        for _ in range(n):
            tmp += c[p[idx]]
            idx = p[idx]
            if _ < k % cycledist[i][1]:
                ans = max(ans, tmp, tmp + tmp_ans)
            else:
                ans = max(ans, tmp)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n,k = readInts()
P = readInts()
C = readInts()
dic = defaultdict(int)
for i in range(n):
    dic[i+1] = P[i]
ans = -float('inf')
for start in range(n):
    nya = deque()
    root = defaultdict(int)
    pya = start+1
    cnt = 0
    SUM = 0
    while root[dic[pya]] == 0 and cnt < k:
        pya = dic[pya]
        nya.append(C[pya-1])
        cnt += 1
        SUM += C[pya-1]
        root[pya] = 1
        ans = max(ans,SUM)
    if cnt < k:# まだ満たない
        need = k-cnt
        nl = len(nya)
        sumnya = sum(nya)
        a = need//nl
        if sumnya > 0:
            SUM += sumnya * a
        nokori = need - nl*a
        for idx in range(nokori):
            SUM += nya[idx]
            ans = max(ans,SUM)
    else:
        ans = max(ans,SUM)
print(ans)

Submission status: Wrong Answer

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

q=K//N
r=K%N
sumall=sum(Cs)
l=[]
for ist in range(N):
    Pi=Ps[ist]
    t_max=0
    t_max_i=-1
    t_sum=0
    for imv in range(r):
        t_sum+=Cs[Pi]
        if t_sum>t_max:
            t_max=t_sum
            t_max_i=imv
        Pi=Ps[Pi]
    #l.append((t_max,t_max_i))
    l.append(t_max)

ans=0
if sumall > 0:
    ans+=sumall*q

m=max(l)
if m<=0:
    if sumall<0 or q==0:
        m=max(Cs)
    else:
        m=0

ans+=m
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))

def do():
    n,k=INTM()
    P=LIST()
    C=LIST()
    lp=[]
    sc=[]
    check=[False]*n
    ans=-(10**9+1)
    le=0
    for i in range(n):
        #print(i)
        tl=[]
        tc=[]
        if check[i]==False:
            templ=P[i]-1
            tempc=C[i]
            check[i]=True
            while not(templ in tl):
                check[templ]=True
                tl.append(templ)
                tc.append(tempc)
                tempc=C[templ]
                templ=P[templ]-1
                
        else:
            continue
        lp.append(tl)
        sc.append(tc)
    
    l=len(lp)
    for i in range(l):
        loop=lp[i]
        score=sc[i]
        cycle=sum(score)
        score=score+score
        #print(lp,score)
        if cycle>=0:
            #flg=1
            remain = k %len(loop)
            cym=0
            for j in range(len(loop)):
                for ii in range(remain):
                    cym=max(sum(score[j:j+ii+1]),cym)
            ans=max(k//len(loop)*cycle+cym,ans)
        else:
            #flg=2
            cym=-(10**9+1)
            for j in range(len(loop)):
                for ii in range(min(k,len(loop))):
                    cym=max(sum(score[j:j+ii+1]),cym)
            ans=max(cym,ans)
            
        #print(ans)
    
    if ans==0:
        ans=max(C)
    print(ans)
    
    
if __name__ == '__main__':
    do()