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: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, K = MAP()
P = LIST()
C = LIST()

check = [0]*N 
score = []

i = 0
while 1:
	while i < N and check[i]:
		i += 1
	if i == N:
		break

	tmp = []
	while check[i] == 0:
		check[i] = 1
		i = P[i]-1
		tmp.append(C[i])
	score.append(tmp)

ans = -INF
for x in score:
	x_acc = list(accumulate([0] + x + x))
	n = len(x)
	tmp_max = -INF

	for i, j in combinations(range(2*n+1), 2):
		if j-i <= min(K, n):
			if tmp_max < x_acc[j]-x_acc[i]:
				tmp_max = x_acc[j]-x_acc[i]
				cnt = j-i
	tmp_ans = -INF

	if 0 >= x_acc[n]:
		tmp_ans = tmp_max

	else:
		if cnt <= K%n:
			tmp_ans = x_acc[n]*(K//n) + tmp_max
		else:
			tmp_max2 = 0
			for i, j in combinations(range(2*n+1), 2):
				if j-i <= K%n:
					if tmp_max2 < x_acc[j]-x_acc[i]:
						tmp_max2 = x_acc[j]-x_acc[i]
			tmp_ans = max(x_acc[n]*(K//n-1)+tmp_max, x_acc[n]*(K//n) + tmp_max2)

	ans = max(ans, tmp_ans)

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

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

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
k -= 1
for j in range(n):
    now = P[j] - 1
    r = D[U.root(now)]
    m = U.get_size(now)
    ret = C[now]
    ans = max(ans, ret)
    if k // m and r >= 0:
        ret += k // m * r
        ans = max(ans, ret)
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ans = max(ans, ret)
    ret = C[now]
    for l in range(min(m, k)):
        now = P[now] - 1
        ret += C[now]
        ans = max(ans, ret)

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

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

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
k -= 1
for j in range(n):
    now = P[j] - 1
    r = D[U.root(now)]
    m = U.get_size(now)
    ret = C[now]
    ans = max(ans, ret)
    if k // m and r >= 0:
        ret += k // m * r
        ans = max(ans, ret)
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ans = max(ans, ret)
    else:
        for l in range(min(m, k)):
            now = P[now] - 1
            ret += C[now]
            ans = max(ans, ret)

print(ans)

Submission status: Accepted

Solution code:
INF=10**9
f=lambda:[*map(int,input().split())]
n,k=f()
p,c=f(),f()
p=[*map(lambda x:x-1,p)]
tp=[[*range(n)] for _ in range(n+1)]
tc=[[0]*n for _ in range(n+1)]
lt=[0]*n
lc=[0]*n
for i in range(n):
  for j in range(n):
    t=p[tp[i][j]]
    tp[i+1][j]=t
    tc[i+1][j]=tc[i][j]+c[t]
    if t==j and lt[j]==0:
      lt[j]=i+1
      lc[j]=tc[i+1][j]
a=-INF
for i in range(n):
  if lc[i]<1 or k<=lt[i]:
    for j in range(min(lt[i],k)):
      a=max(a,tc[j+1][i])
  else:
    for j in range(lt[i]):
      t=k//lt[i]*lc[i]+tc[j+1][i]
      if k%lt[i]<j+1: t-=lc[i]
      a=max(a,t)
print(a)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, K = MAP()
P = LIST()
C = LIST()

check = [0]*N 
score = []

i = 0
while 1:
	while i < N and check[i]:
		i += 1
	if i == N:
		break

	tmp = []
	while check[i] == 0:
		check[i] = 1
		i = P[i]-1
		tmp.append(C[i])
	score.append(tmp)

ans = -INF
for x in score:
	x_acc = list(accumulate([0] + x*3))
	n = len(x)

	if x_acc[n] <= 0:
		tmp_ans = 0
		l = min(K, n)
	else:
		tmp_ans = x_acc[n]*(max(0, K//n-1))
		l = min(K%n+n, K)
	tmp_max = -INF

	for i, j in combinations(range(3*n+1), 2):
		if j-i <= l:
			if tmp_max < x_acc[j]-x_acc[i]:
				tmp_max = x_acc[j]-x_acc[i]
	tmp_ans += tmp_max
	ans = max(ans, tmp_ans)

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007



class UnionFind:
    def __init__(self, n):
        # 負  : 根であることを示す。絶対値はランクを示す
        # 非負: 根でないことを示す。値は親を示す
        self.table = [-1] * n
        self.size = [1] * n
        # self.group_num = n

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

    def get_size(self, x):
        r = self.root(x)
        return self.size[r]

    def is_same(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y):
        r1 = self.root(x)
        r2 = self.root(y)
        if r1 == r2:
            return
        # ランクの取得
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.size[r1] += self.size[r2]
            if d1 == d2:
                self.table[r1] -= 1
        else:
            self.table[r1] = r2
            self.size[r2] += self.size[r1]
        # self.group_num -= 1

n, k = LI()
P = LI()
C = LI()
U = UnionFind(n)
for i in range(n):
    U.union(P[i] - 1, i)

D = defaultdict(int)
for i in range(n):
    D[U.root(i)] += C[i]

ans = -INF
k -= 1
for j in range(n):
    r = D[U.root(j)]
    m = U.get_size(j)
    now = P[j] - 1
    ret_max = C[now]
    ret = C[now]
    if k // m and r >= 0:
        for l in range(k % m):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
        ret_max += k // m * r
    else:
        for l in range(min(m, k)):
            now = P[now] - 1
            ret += C[now]
            ret_max = max(ret_max, ret)
    ans = max(ans, ret_max)

print(ans)

Submission status: Accepted

Solution code:
n, k =map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
roop = []
seen = [0 for  _ in range(n)]
count = 0
for i in range(n):
    if seen[i]>0:
        continue
    else:
        count+=1
        seen[i] = count
        roop.append([c[i]])
        t = i
        while i!=p[t]-1:
            seen[p[t]-1]=count
            roop[-1].append(c[p[t]-1])
            t = p[t]-1
#print(seen)
#print(roop)
ans = max(c)

for i in roop:
    #print(ans)
    
    s = sum(i)
    ii = i+i
    #print(ii)
    if len(i)>=k:
        for j in range(1, k+1):
            temp = sum(ii[:j])
            for l in range(len(i)):
                if l!=0:
                    temp+=ii[l+j-1]
                    temp-=ii[l-1]
                    #temp = sum(ii[l:l+j])
                #print(i, j, l, temp)
                ans  = max(ans, temp)
    else:
        for j in range(1, len(i)+1):
            temp=  sum(ii[:j])
            for l in range(len(i)):
                if l != 0:
                    temp+=ii[l+j-1]
                    temp-=ii[l-1]
                #print(temp)
                if s>0:
                    temp1 = temp+s*((k-j)//len(i))
                else:
                    temp1 = temp
                
                #print(i, j, l, temp)
                ans  = max(ans, temp)
                ans  = max(ans, temp1)
            
print(ans)

Submission status: Accepted

Solution code:
from numba import jit
@jit
def main():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    ans = -10**10
    
    for i in range(n):
        start, count = i, 1
        val = c[start]
        while p[start]-1 != i:
            start = p[start]-1
            count += 1
            val += c[start]

        start = i
        if val > 0:
            a = (k//count-1)*val
            ans = max(a, ans)
            num = k%count+count
        else:
            a = 0
            num = min(k, count)

        for _ in range(num):
            start = p[start]-1
            a += c[start]
            ans = max(a, ans)
    print(int(ans))

main()

Submission status: Accepted

Solution code:
def solve():
    from collections import defaultdict
    class UnionFind():
        def __init__(self, n):
            self.n = n
            self.par = [-1] * n

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

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

            if x == y:
                return

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

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

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

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

    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    mp = defaultdict(int)
    uf = UnionFind(n)

    for i in range(n):
        uf.unite(i, p[i] - 1)

    for i in range(n):
        mp[uf.find(i)] += c[i]# 根にループ一周のポイントを加算

    ans = -10 ** 14
    for i in range(n):
        roop = uf.size(i) # ループに関連する要素数
        times = (k - 1) // roop if mp[uf.find(i)] > 0 else 0# 一周後のポイントが正ならループ回数をストック
        over = max(min(roop, k - roop * times), 1)# 最終周の移動数
        tmp = 0
        s = -10 ** 10
        idx = i
        for j in range(over):# 最終周のポイント最大値
            tmp += c[idx]
            s = max(s, tmp)
            idx = p[idx] - 1
        s += times * mp[uf.find(i)]# 最終週までの累積ポイント加算
        ans = max(ans, s)
    print(ans)


solve()

Submission status: Accepted

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


ans=-float('inf')


x=[0]*n
for i in range(n):
    if x[i]==0:
        x[i]=1
        y=p[i]-1
        # 累積和を格納
        aa=[0,c[i]]
        # ２周させる
        life=2
        for j in range(2*n+2):
            x[y]=1
            if life>0:
                aa.append(aa[-1]+c[y])
                y=p[y]-1
                if y==i:
                    life-=1
            else:
                break
        # 各回数での取れるスコアの最大値
        x1=(len(aa)-1)//2

        a=[-float('inf')]*(x1+1)

        for ii in range(len(aa)-1):
            for j in range(ii+1,len(aa)):
                if j-ii<=x1:
                    a[j - ii] = max(a[j - ii], aa[j] - aa[ii])

        v=k//x1
        w=k%x1

        if v==0:
            ans=max(ans,max(a[:k+1]))

        elif v==1:

            ans = max(ans, max(a), v * aa[x1] + max(a[:w + 1]))
        else:
            ans=max(ans,max(a),v * aa[x1] + max(a[:w + 1]),(v-1)*aa[x1]+max(a))





print(ans)

Submission status: Accepted

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

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(n):
    uf.union(i,p[i]-1)

ma = float('INF')*(-1)
listcase = []
cc=0
for i in uf.roots():
    st = uf.members(i)[0]
    listcase.append([])
    while True:
        listcase[cc].append(c[st])
        st=p[st]-1
        if st == uf.members(i)[0]:
            break
    cc+=1

for i in listcase:
    m = len(i)
    i2=i*2
    su = 0
    if sum(i)>0:
        su = sum(i)*(k//m)
    m2 = k%m
    if m2==0 and su>0:
        m2=m
        su-=sum(i)
    elif m2==0:
        m2=m
    if sum(i)<=0:
        m2=m
    for l in range(m):
        dp=[float('INF')*(-1)]*(m*2)
        dp[l]=i2[l]
        for j in range(l+1,l+m2):
            dp[j]=max(dp[j-1]+i2[j],i2[j])
        ma = max(ma,su+max(dp))
print(ma)

Submission status: Accepted

Solution code:
from collections import Counter
from heapq import heapify, heappop, heappush
from itertools import accumulate


def solve(n, k, ppp, ccc):
    NINF = -(10 ** 18)
    ans = NINF

    checked = [False] * n
    for s in range(n):
        if checked[s] == True:
            continue
        checked[s] = True
        scores = [ccc[ppp[s]]]
        v = ppp[s]
        while v != s:
            scores.append(ccc[ppp[v]])
            checked[v] = True
            v = ppp[v]

        l = len(scores)
        d, m = divmod(k, l)
        loop = sum(scores)

        if d > 0:
            d -= 1
            m += l

        scores += scores * 2
        scores.insert(0, 0)
        acc = list(accumulate(scores))

        base = max(0, loop * d)

        range_max = [-a for a in acc[1:m + 1]]
        available_max = Counter(range_max)
        heapify(range_max)
        for i in range(l):
            while available_max[range_max[0]] == 0:
                heappop(range_max)
            ans = max(ans, base - range_max[0] - acc[i])
            old = -acc[i + 1]
            new = -acc[i + m + 1]
            available_max[old] -= 1
            available_max[new] += 1
            heappush(range_max, new)

    return ans


n, k = map(int, input().split())
ppp = list(map(int, input().split()))
ppp = [p - 1 for p in ppp]
ccc = list(map(int, input().split()))

print(solve(n, k, ppp, ccc))

Submission status: Accepted

Solution code:
from collections import deque
import sys, copy,itertools
input = sys.stdin.readline

n, k = map(int,input().split())
#P = list(map(int,input().split()))
P = list(map(lambda x : int(x) - 1, input().split())) #ひとつづつずらす
C = list(map(int,input().split()))
SCORE = [0]*(n+1)

max_score = -10**12
for i in range(n):
  x = i
  TEMPMAX = [-10**9] * (n+1)
  for j in range(1, n+1):
    SCORE[j] = SCORE[j-1] + C[P[x]]
    TEMPMAX[j]= max(TEMPMAX[j-1], SCORE[j])
    x = P[x]
    if x == i:
      break
  if j >= k:
    max_score = max(max_score,TEMPMAX[k])
  elif SCORE[j] < 0:
    max_score = max(max_score, TEMPMAX[j])
  else:
    m = k//j
    a = SCORE[j] *(m-1) + TEMPMAX[j]
    b = SCORE[j] *m + TEMPMAX[k % j]
    max_score = max(max_score, a, b)
print(max_score)

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect

n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
check=[-1]*n
finalans=-10**20
for i in range(n):
    if check[i]!=-1:
        continue
    loop=[i]
    now=i
    while p[now]!=i+1:
        check[now]=1
        loop.append(p[now]-1)
        now=p[now]-1
    L=len(loop)
    point=[0]*(L*2)
    point[0]=c[loop[0]]
    for j in range(1,L*2):
        if j<L:
            point[j]=point[j-1]+c[loop[j]]
        else:
            point[j]=point[j-1]+c[loop[j-L]]
    m=-10**20
    if point[L-1]>0:
        r=k%L
        if r==0:
            r=L
        for j in range(1,r+1):
            for t in range(j-1,j+L-1):
                cand=point[t]-point[t-j] if t-j>=0 else point[t]
                m=max(m,cand)
        ans=point[L-1]*(k//L)+m if r!=L else point[L-1]*((k//L)-1)+m
    else:
        for j in range(1,L+1):
            for t in range(j-1,j+L-1):
                cand=point[t]-point[t-j] if t-j>=0 else point[t]
                m=max(m,cand)
        ans=m
    finalans=max(ans,finalans)   
print(finalans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
n, k = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))


def dfs(i):
    if 0 <= visited[i]:
        return
    visited[i] = idx
    cycle.append(i)
    global csum
    csum += C[i]
    dfs(P[i])


visited = [-1]*n
idx = 0
cycles = []
for i in range(n):
    if 0 <= visited[i]:
        continue
    cycle = []
    csum = 0
    dfs(i)
    cycles.append((cycle, csum))
    idx += 1


INF = 10**18
ans = -INF
for i in range(n):
    cycle, csum = cycles[visited[i]]
    cmem = len(cycle)

    if 0 < csum:
        a, b = divmod(k, cmem)
        scoreA = csum*(a-1)
        b += cmem
        score = 0
        scoreB = 0
        for _ in range(b):
            i = P[i]
            score += C[i]
            if scoreB < score:
                scoreB = score
        X = scoreA+scoreB
    else:
        b = min(k, cmem)
        score = 0
        INF = 10**18
        X = -INF
        for _ in range(b):
            i = P[i]
            score += C[i]
            if X < score:
                X = score

    if ans < X:
        ans = X
print(ans)

Submission status: Accepted

Solution code:
import numpy as np


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

    seen = set()
    loop_list = []
    for start in range(n):
        v = start
        loop = []
        while v not in seen:
            seen.add(v)
            loop.append(c[v])
            v = p[v]
        seen.add(v)
        if loop:
            loop_list.append(np.array(loop))

    ans = min(c)
    for loop in loop_list:
        loop_len = len(loop)
        loop_num = k // loop_len
        loop_mod = k % loop_len
        loop_sum = sum(loop)
        table = np.zeros((loop_len, loop_len), dtype=int)
        table[0] = loop.cumsum()
        table[:, -1] = loop_sum
        for i in range(loop_len - 1):
            table[i + 1, :-1] = (table[i] - loop[i])[1:]
        ans = max(table[:, :min(loop_len, k)].max(), ans)
        if loop_num > 0:
            ans = max(loop_sum * (loop_num - 1) + table[:, :loop_len].max(), ans)
            if loop_mod > 0:
                ans = max(loop_sum * loop_num + table[:, :loop_mod].max(), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import accumulate


def solve(n, k, ppp, ccc):
    NINF = -(10 ** 18)
    ans = NINF

    checked = [False] * n
    for s in range(n):
        if checked[s] == True:
            continue
        checked[s] = True
        scores = [ccc[ppp[s]]]
        v = ppp[s]
        while v != s:
            scores.append(ccc[ppp[v]])
            checked[v] = True
            v = ppp[v]

        l = len(scores)
        d, m = divmod(k, l)
        loop = sum(scores)

        if d > 0:
            d -= 1
            m += l

        scores += scores * 2
        scores.insert(0, 0)
        acc = list(accumulate(scores))
        tmp = max(max(acc[i + 1:i + m + 1]) - acc[i] for i in range(l))
        ans = max(ans, tmp, loop * d + tmp)

    return ans


n, k = map(int, input().split())
ppp = list(map(int, input().split()))
ppp = [p - 1 for p in ppp]
ccc = list(map(int, input().split()))

print(solve(n, k, ppp, ccc))

Submission status: Accepted

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

E=[]
color=["white" for _ in range(N)]
for i in range(N):
    if color[i]=="white":
        index,F=i,[]
        while 1:
            if color[index]=="white":
                color[index]="black"
                index=P[index]-1
                F.append(C[index])
            else:break
        E.append(F)

ans=-float("inf")
for A in E:
    length=len(A)
    if sum(A)<0:
        A=A*2
        for i in range(length):
            point=0
            for j in range(min(K,length)):
                point +=A[i+j]
                ans=max(ans,point)
    else:
        div,mod=divmod(K,length)
        base=(div-1)*sum(A)
        A=A*3
        for i in range(length):
            point=0
            for j in range(mod+length):
                point +=A[i+j]
                ans=max(ans,base+point)
print(ans)

Submission status: Accepted

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

points = list()
for i in range(N):
    sum = 0
    now = P[i]
    result = list()
    flag = True
    for j in range(N):
        sum += C[now]
        result.append(sum)
        if now == i:
            break
        if j == N-1 and now != i:
            flag = False
        now = P[now]

    if flag:
        points.append(result)
    else:
        # iスタートでiに戻るループが存在しない
        points.append([-int(1e19)])

ans = -int(1e19)

for i in range(len(points)):
    now = i
    tmpp = 0
    k = K
    while points[now][0] == -int(1e19):
        now = P[now]
        tmpp += C[now]
        k -= 1
        ans = max(ans, tmpp)

    cir = len(points[now])
    cir_point = points[now][cir-1]

    if k <= cir:
        for j in range(k):
            ans = max(ans, points[now][j] + tmpp)
    else:
        if cir_point > 0:
            lm = k // cir - 1
            for j in range(cir):
                ans = max(ans, points[now][j] + lm * cir_point + tmpp)
            for j in range(k % cir):
                ans = max(ans, points[now][j] + (lm + 1) * cir_point + tmpp)
        else:
            for j in range(cir):
                ans = max(ans, points[now][j] + tmpp)

print(ans)

Submission status: Accepted

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

P = list(map(lambda x:x-1, P))

ans = -float('inf')
for si in range(N):
    s = []
    tot = 0
    x = si
    while True:
        x = P[x]
        s.append(C[x])
        tot += C[x]
        if x==si:
            break
    l = len(s)
    now = 0
    t = 0
    for i in range(l):
        if i+1 > K: break
        t += s[i]
        now = t
        if tot >0:
            e = (K-(i+1))//l
            now += tot * e
        ans = max(ans, now)


print(ans)