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: Runtime Error

Solution code:
when NimMajor <= 0 and NimMinor <= 18: import future else: import sugar

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
when defined release: {.checks: off.}

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
from typetraits import arity
from sequtils import map, mapIt, newSeqWith, toSeq
from strutils import split, parseInt, parseFloat, parseBool, parseEnum, parseBiggestInt
when NimMajor == 0 and NimMinor >= 14: from strutils import parseBiggestUInt

import macros

from terminal import setForegroundColor, ForegroundColor, resetAttributes
proc warn(message: string) =
  when not defined release:
    stderr.setForegroundColor(fgYellow)
    stderr.write("注意: ")
    stderr.resetAttributes
    stderr.writeLine message

when not declared parseBiggestUInt:
  proc parseBiggestUInt(s: string): uint64 = uint64(parseInt(s))
when not declared SomeFloat:
  type SomeFloat = float | float64 | float32
when not defined nimHasRunnableExamples:
  template runnableExamples*(body: untyped) = discard

proc parseT(s: string; T: typedesc): auto =
  ## `parse` 系関数のジェネリック版
  ## `T` が `SomeOrdinal | SomeFloat` (subranges を含む) でない場合，そのまま `s` を返す
  runnableExamples:
    doAssert parseT("12", int) == 12
    doAssert parseT("12", uint) == 12
    doAssert parseT("12", int64) == 12
    doAssert parseT("12", float32) == 12.0
    doAssert parseT("Yes", bool) == true

  when T is SomeSignedInt: cast[T](parseBiggestInt(s))
  elif T is SomeUnsignedInt: cast[T](parseBiggestUInt(s))
  elif T is SomeFloat: cast[T](parseFloat(s))
  elif T is enum: parseEnum[T](s)
  elif T is bool: parseBool(s)
  elif T is char: s[0]
  else: s

proc unpackWithParse*(input: openArray[string]; T: typedesc[tuple]): T =
  ## 文字列配列を `T` で指定された `tuple` に `parse` しながら変換する
  runnableExamples:
    let t = unpackWithParse(@["1", "1", "1", "1", "1"], 4, tuple[a: int8, b: uint32, c: float64, d: bool])
    doAssert int8 is t.a.type and t.a == 1
    doAssert uint32 is t.b.type and t.b == 1
    doAssert float64 is t.c.type and t.c == 1.0
    doAssert bool is t.d.type and t.d == true
    doAssert tuple[a: int8, b: uint32, c: float64, d: bool] is t.type

  var i = 0
  for x in result.fields:
    if i > input.high:
      warn "元の配列の長さが " & $T.arity & " 未満だから，一部デフォルト値になってるよ"
      break
    x = parseT(input[i], x.type)
    i.inc
  result

proc input(T: typedesc[string]): string = stdin.readLine
proc input(T: typedesc[SomeOrdinal | SomeFloat | char]): auto = input(string).parseT(T)
proc input(T: typedesc[seq[string]]): auto = input(string).split
proc input(T: typedesc[seq[char]]): auto = toSeq(input(string).items)
proc input[E: SomeOrdinal | SomeFloat](T: typedesc[seq[E]]): auto = input(seq[string]).mapIt(it.parseT(E.type))
proc input(T: typedesc[tuple]): auto = input(seq[string]).unpackWithParse(T)

proc toTupleType(parTuple: NimNode): NimNode {.compileTime.} =
  ## `nnkPar` で表現されてる名前付きタプルを `tuple[]` 形式に変換する
  ## `nnkPar` が名前付きタプルじゃない場合は，そのまま返す
  runnableExamples:
    static:
      doAssert((quote do: (a: int, b: float)).toTupleType == (quote do: tuple[a: int, b: float]))
      doAssert((quote do: (a, b: int)).toTupleType == (quote do: tuple[a, b: int]))
      doAssert((quote do: (int, int)).toTupleType == (quote do: (int, int)))
      doAssert((quote do: ()).toTupleType == (quote do: ()))

  if parTuple.len == 0 or parTuple.findChild(it.kind == nnkExprColonExpr) == nil: # () or (T, U, ...)
    result = parTuple
  else:
    result = newTree(nnkTupleTy)
    var identDefs = newTree(nnkIdentDefs)
    for field in parTuple:
      if field.kind == nnkIdent: # (a, b, ..., x: T)  の a, b, ... 部分 (x 以外)
        identDefs.add(field)
      field.copyChildrenTo(identDefs)
      if field.kind != nnkIdent: # (..., x: T, y: ...) の x: T 部分
        identDefs.add(newEmptyNode())
        result.add(identDefs)
        identDefs = newTree(nnkIdentDefs)

proc seqInputCall(bracketTree: NimNode): NimNode {.compileTime.} =
  ## `seq[N, seq[M, ..., [seq[T]]...]]` を `newSeqWith(N, newSeqWith(M, ..., input(seq[T])...))` にする

  if bracketTree.kind != nnkBracketExpr:
    case bracketTree.kind:
      of nnkPar: # x: (Field0: ...)
        result = newCall("input", bracketTree.toTupleType)
      else: # x: T
        result = newCall("input", bracketTree)
  else:
    case bracketTree.len:
      of 2: # seq[N, ... seq[T] ...] の seq[T]
        if bracketTree[^1].kind == nnkBracketExpr:
          error("seq[seq[T]] みたいな書き方はできないって言ったでしょ！ seq[N, seq[T]] みたいに書き直してっ")
        result = newCall("input", bracketTree)
      of 3: # それ以外 (seq[N, ...])
        result = newCall("newSeqWith", bracketTree[1], seqInputCall(bracketTree[^1]))
      else:
        error("変な入力があるよ")

proc appendedProcCallBlocks(procCalls: NimNode; i: int): NimNode =
  ## `procCalls[i]` の関数呼び出しを
  ## .. code-block:: Nim
  ##   block:
  ##     var it = procCall(...)
  ## という形に変換しながらつなげていく
  ## 最後だけは
  ## .. code-block:: Nim
  ##   block:
  ##     var it = lastProcCall(...)
  ##     it
  ## というようにして `it` を返すようにする

  let it = ident("it")
  let procCall = procCalls[i]
  result = newStmtList(quote do:
    var `it` = `procCall`
  )
  if i == procCalls.len - 1: # 最後の要素だけは it を返すようにする
    result.add(it)
  else:
    result.add(appendedProcCallBlocks(procCalls, i + 1))
  result = newBlockStmt(result)

proc inputsImpl(pre, post: NimNode): NimNode {.compileTime.} =
  ## pre で指定された変数に post の結果を入れる

  # input() 部分の生成
  var inputCall: NimNode
  case pre.kind:
    of nnkPar: # (x, y, ...): ...
      result = newTree(nnkVarTuple)
      pre.copyChildrenTo(result)
      result.add(newEmptyNode())
      case post[0].kind:
        of nnkPar: # (x, y, ...): (T, T, ...)
          inputCall = newCall("input", post[0].toTupleType)
        of nnkTupleTy: # (x, y, ...): tuple[Field0: ...]
          inputCall = newCall("input", post)
        else: # (x, y, ...): T
          var parTupleTy = newTree(nnkPar)
          for _ in 0..<pre.len: parTupleTy.add(post[0]) # (int, int, int, ...) みたいなのを作ってる
          inputCall = newCall("input", parTupleTy)
    else: # x: ...
      result = newTree(nnkIdentDefs).add(pre).add(newEmptyNode())
      case post[0].kind:
        of nnkPar: # x: (Field0: ...)
          inputCall = newCall("input", post[0].toTupleType)
        of nnkBracketExpr:
          inputCall = seqInputCall(post[0])
        else: # x: T
          inputCall = newCall("input", post[0])

  # 関数部分の生成（ある場合）と結合
  if post.len > 1:
    let it = ident("it")
    var itStmts = when NimMajor == 0 and NimMinor < 17: newStmtList(quote do: (var `it` = `inputCall`)) # 入力の読み込み
                  else: newStmtList(quote do: (var `it` {.used.} = `inputCall`))
    itStmts.add(appendedProcCallBlocks(post, 1)) # 関数の適用
    result.add(newTree(nnkStmtListExpr, newBlockStmt(itStmts))) # 結合
  else:
    result.add(inputCall) # 結合

macro inputs*(body: untyped): untyped =
  ## 入力を受け取る
  ## 宣言の後に `it` を用いた式を（`y` みたいに用いなくてもいいんだけど）いくつでもかくことができ，
  ## その返り値が変数の値となる
  ## 式中で型が変わってもいい（下の例の `u`, `y` とか見たいな感じ）
  ##
  ## .. code-block:: Nim
  ##   inputs:
  ##     a: int
  ##     b: string
  ##     c: (x: char, y: float)
  ##     d: tuple[x: char, y: float]
  ##     e: (u, v: BiggestInt)
  ##     f: tuple[u, v: int]
  ##     g: seq[int]
  ##     h: seq[a, seq[int]]
  ##     i: seq[a, (s, t: int)]
  ##     (j, k, l): int
  ##     (m, n): (char, float)
  ##     o: seq[a, string]
  ##     (p): int
  ##     q: seq[int]; it.sorted(system.cmp)
  ##     r: seq[float]; it.sorted(cmp).filterIt(it > 0)
  ##     s: seq[char]
  ##     t: seq[2, seq[a, int]]
  ##     u: string; parseInt(it); abs(-it)
  ##     (_, v): (a: char, b: char)
  ##     (w, x): tuple[a, b: char]
  ##     y: int; "hoge"

  expectKind(body, nnkStmtList)
  result = newTree(nnkStmtList)
  var letSection = newTree(nnkLetSection)
  for decl in body:
    case decl[0].kind:
      of nnkIdent: # x: ...
        letSection.add(inputsImpl(decl[0], decl[1]))
      of nnkPar:
        expectMinLen(decl[0], 1)
        if decl[0].len == 1: # (x): ... これは x: ... と同じ扱いにしたい
          letSection.add(inputsImpl(decl[0][0], decl[1]))
        else: # (x, y, ...): ...
          letSection.add(inputsImpl(decl[0], decl[1]))
      else:
        expectKind(decl[0], {nnkIdent, nnkPar})

  result.add(letSection)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
proc `ceilDiv`*[T](x, y: T): T = x div y + ord(x mod y != 0)
proc `//=`*(x: var SomeInteger; y: SomeInteger) = x = x div y
proc `%=`*(x: var SomeInteger; y: SomeInteger) = x = x mod y
proc `<?=`*[T](x: var T; y: T) = x = min(x, y)
proc `>?=`*[T](x: var T; y: T) = x = max(x, y)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
proc withIndex*[T](s: openArray[T]): seq[tuple[i: int, v: T]] =
  (0..s.high).mapIt((it, s[it]))

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
template countIt*[T](a: openArray[T]; pred: untyped): int =
  var result = 0
  for it {.inject.} in items(a):
    if pred: result.inc
  result

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
proc reversed*(s: string): string =
  result = newString(s.len)
  for i, c in s: result[s.len - i - 1] = c

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
from sequtils import newSeqWith, allIt

template newSeqWithImpl[T](lens: seq[int]; init: T; currentDimension, lensLen: static[int]): untyped =
  when currentDimension == lensLen:
    newSeqWith(lens[currentDimension - 1], init)
  else:
    newSeqWith(lens[currentDimension - 1], newSeqWithImpl(lens, init, currentDimension + 1, lensLen))

template newSeqWith*[T](lens: varargs[int]; init: T): untyped =
  assert(lens.allIt(it > 0))
  newSeqWithImpl(@lens, init, 1, lens.len)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
when not defined(release):
  template stderrEcho*(x: varargs[string, `$`]) =
    for v in x:
      stderr.write(v)
    stderr.writeLine ""

  template stderrEcho*[T](x: seq[seq[T]]) =
    for v in x: stderrEcho v

  template stderrEcho*(x: seq[string]) =
    for v in x: stderrEcho v
else:
  template stderrEcho*(x: untyped) = discard

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
inputs:
  (N, K): int
  P: seq[int]; it.mapIt(it - 1)
  C: seq[int]

var result = int.low
for s in 0..<N:
  var
    now = P[s]
    score = C[now]
    k = 1
  result >?= score
  while now != s and k < K:
    now = P[now]
    score += C[now]
    result >?= score
    k.inc
  score *= K div k
  result >?= score
  for _ in 0..<(K mod k):
    now = P[now]
    score += C[now]
    result >?= score
  result >?= score

echo result

Submission status: Runtime Error

Solution code:
X, K, D = map(int, input().split())
X_a = abs(X)
if X_a - K * D > D:
    print(X_a - K * D)
else:
    while X_a >= D:
        X_a -= D
        K -= 1
    if  K % 2 == 0:
        print(X_a)
    else:
        print(abs(X_a-D))

Submission status: Runtime Error

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

if max(c) < 0:
    res = max(c)
else:
    res = 0

for i in range(n):
    score = []
    s = 0
    pos = i
    visited = [False] * n
    while True:
        if visited[pos]:
            break

        visited[pos] = True
        s += c[p[pos]-1]
        score.append(s)
        pos = p[pos] - 1

    loop = len(score)

    if k < loop:
        res = max(res, max(score[:k]))
    elif score[-1] <= 0:
        res = max(res, max(score))
    else:
        res = max(res, score[-1] * (k // loop) + max(score[:k%loop]), score[-1] * (k // loop - 1) + max(score))

print(res)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <string>
#include <queue>
#include <deque>
#include <list>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <bitset>
#include <random>
#include <complex>
#include <assert.h>

using namespace std;
typedef long long ll;
#define endl '\n'

template<typename T>
inline bool chmin(T& x, T a) {
	if (x >= a) { x = a; return true; }
	return false;
}

template<typename T>
inline bool chmax(T& x, T a) {
	if (x <= a) { x = a; return true; }
	return false;
}

ll N, K;
ll ans = -1LL<<60;
void func(vector<ll>& v) {
	ll M = v.size();
	ll n = K / M;// n周する
	ll m0 = K % M;// +m個

	ll a = 0;// 和
	for (int i = 0; i < M; i++) {
		a += v[i];
	}

	vector<ll> res(M + 1, 0);
	for (int m = 0; m <= M; m++) {
		ll b = 0;
		ll c = -1LL << 60;
		for (int i = 0; i < m; i++) {
			b += v[i];
		}
		for (int i = 0; i < M; i++) {
			b += v[(i + m) % M] - v[i];
			chmax(c, b);
		}
		res[m] = c;
	}
	ll x = -1LL << 60;
	if (a > 0) {
		for (int i = 0; i < M; i++) {
			if (i > m0) {
				if (n > 0) {
					chmax(x, a * (n - 1) + res[i]);
				}
			}
			else {
				chmax(x, a * n + res[i]);
			}
		}
	}
	else {
		for (int i = 1; i <= min(M, K); i++) {
			chmax(x, res[i]);
		}
	}
	chmax(ans, x);
}

int main() {
	ios::sync_with_stdio(false);
	std::cin.tie(0);

	cin >> N >> K;
	vector<ll> p(N);
	vector<ll> c(N);
	vector<bool> b(N);
	for (int i = 0; i < N; i++) {
		cin >> p[i]; p[i]--;
		b[i] = false;
	}
	for (int i = 0; i < N; i++) {
		cin >> c[i];
	}

	for (int i = 0; i < N; i++) {
		if (b[i] == false) {
			vector<ll> temp;
			ll x = i;
			while (1) {
				b[x] = true;
				temp.push_back(c[x]);
				x = p[x];
				if (x == i) { break; }
			}
			func(temp);
		}
	}
	cout << ans << endl;

	return 0;
}

Submission status: Runtime Error

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

ans = -float('inf')
for i in range(N):
    cnt = 0
    k = 0
    done = set()
    S = []
    while i not in done:
        done.add(i)
        ni = P[i] - 1
        if len(S):
            S.append(S[-1] + C[ni])
        else:
            S.append(C[ni])
        i = ni
    if K <= len(S):
        score = max(S[:K])
    elif S[-1] <= 0:
        score = max(S)
    else:
        score = S[-1] * (K // len(S))
        r = K % len(S)
        score += max(0, max(S[:r]))
    ans = max(ans, score)
print(ans)

Submission status: Runtime Error

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

vl=[]
for i in range(1,K+1):
  for j in range(i):
    v=0
    for k in range(N):
      for x in range(j):
        v+=Cs[Ps[k]]
        k=Ps[k]
    vl.append(v)
    
    
print(v)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

def solve(start):
    loopcnt = 0
    loopsum = 0
    reached = [0]*n
    scoremax = [-10**20]
    scoresum = 0
    ans = 0
    now = start
    while True:
        reached[now] = 1
        nxt = P[now]-1
        loopcnt += 1
        loopsum += C[now]
        scoresum += C[now]
        scoremax.append(max(scoremax[-1], scoresum))
        if reached[nxt]:break
        now = nxt
    if loopsum < 0 or loopcnt > k:
        ans = max(scoremax[1:k])
    else:
        ans = max(loopsum * (k//loopcnt) + scoremax[k%loopcnt],-10**20)#,max(scoremax[1:]))
    return ans #- C[start]
ans = -10**20
for i in range(n):
    ans = max(ans, solve(i))
    # print(solve(i))

print(ans)

Submission status: Runtime Error

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n, k = map(int, readline().split())
    p = list(map(int, readline().split()))
    p = [x - 1 for x in p]
    c = list(map(int, readline().split()))
    ans = -INF

    for i in range(n):
        cur = i
        nx = -1
        cnt = 0
        score_dict = dict()
        score_dict[0] = 0
        score = 0
        rem = k
        while rem > 0 and nx != i:
            cnt += 1
            rem -= 1
            nx = p[cur]
            score += c[nx]
            score_dict[cnt] = score
            ans = max(ans, score)
            cur = nx

        if rem > 0 and score > 0:
            loop = (rem // cnt) - 1
            if loop > 0:
                score += score * loop
                rem -= loop * cnt
            for j in range(rem + 1):
                st = score + score_dict[j]
                ans = max(ans, st)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


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

    res = -f_inf
    for now in range(n):
        cnt = 0
        score = [0]
        visited = set()
        for j in range(k):
            next_now = P[now] - 1
            if next_now not in visited:
                score.append(score[-1] + C[next_now])
                visited.add(next_now)
                now = next_now
                cnt += 1
            else:
                break
        if k - cnt == 0:
            res = max(res, max(score[1:]))
        else:
            if score[-1] <= 0:
                res = max(res, max(score[1:]))
            else:
                q, r = divmod(k, cnt)
                res = max(res, max(score[1:r + 1]) + score[-1] * q)
    print(res)

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
//
#include <bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define lch (o << 1)
#define rch (o << 1 | 1)

typedef double db;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int, int> pint;
typedef tuple<int, int, int> tint;

const int N = 1e5 + 5;
const int INF = 0x3f3f3f3f;
const ll INF_LL = 0x3f3f3f3f3f3f3f3f;

int a[N], c[N];
bool vst[N];
vector<int> vec[N];

int main() {
	ios::sync_with_stdio(0);

	int n, lim;
	cin >> n >> lim;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	for (int i = 1; i <= n; i++)
		cin >> c[i];
	for (int i = 1; i <= n; i++) {
		if (vst[i]) continue;
		int o = i;
		while (!vst[o]) {
			vst[o] = 1;
			vec[i].push_back(o);
			o = a[o];
		}
	}

	ll ans = -INF_LL;
	for (int i = 1; i <= n; i++) {
		if (vec[i].empty()) continue;
		int siz = vec[i].size();
		static ll s[N];
		s[0] = 0;
		for (int j = 1; j <= siz; j++)
			s[j] = s[j + siz] = c[vec[i][j - 1]];
		for (int j = 1; j <= 2 * siz; j++)
			s[j] += s[j - 1];

		ll sum = s[siz];
		for (int j = 1; j <= min(siz, lim); j++) {
			ll maxs = -INF_LL;
			for (int k = 1; k <= siz; k++)
				maxs = max(maxs, s[k + j - 1] - s[k - 1]);
			if (sum > 0) maxs += sum * ((lim - j) / siz);
			ans = max(ans, maxs);
		}
	}
	cout << ans << endl;

	return 0;
}

Submission status: Runtime Error

Solution code:
from sys import exit

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

if max(c) < 0:
    print(max(c))
    exit()

res = 0
for i in range(n):
    score = []
    s = 0
    pos = i
    visited = [False] * n
    while True:
        if visited[pos]:
            break

        visited[pos] = True
        s += c[p[pos]-1]
        score.append(s)
        pos = p[pos] - 1

    loop = len(score)

    if k < loop:
        res = max(res, max(score[:k]))
    elif score[-1] <= 0:
        res = max(res, max(score))
    else:
        res = max(res, score[-1] * (k // loop) + max(score[:k%loop]))

print(res)

Submission status: Runtime Error

Solution code:
//
#include <bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define lch (o << 1)
#define rch (o << 1 | 1)

typedef double db;
typedef long long ll;
typedef unsigned int ui;
typedef pair<int, int> pint;
typedef tuple<int, int, int> tint;

const int N = 5000 + 5;
const int INF = 0x3f3f3f3f;
const ll INF_LL = 0x3f3f3f3f3f3f3f3f;

int a[N], c[N];
bool vst[N];
vector<int> vec[N];

int main() {
	ios::sync_with_stdio(0);

	int n, lim;
	cin >> n >> lim;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	for (int i = 1; i <= n; i++)
		cin >> c[i];
	for (int i = 1; i <= n; i++) {
		if (vst[i]) continue;
		int o = i;
		while (!vst[o]) {
			vst[o] = 1;
			vec[i].push_back(o);
			o = a[o];
		}
	}

	ll ans = -INF_LL;
	for (int i = 1; i <= n; i++) {
		if (vec[i].empty()) continue;
		int siz = vec[i].size();
		static ll s[N * 2];
		s[0] = 0;
		for (int j = 1; j <= siz; j++)
			s[j] = s[j + siz] = c[vec[i][j - 1]];
		for (int j = 1; j <= 2 * siz; j++)
			s[j] += s[j - 1];

		ll sum = s[siz];
		for (int j = 1; j <= min(siz, lim); j++) {
			ll maxs = -INF_LL;
			for (int k = 1; k <= siz; k++)
				maxs = max(maxs, s[k + j - 1] - s[k - 1]);
			if (sum > 0) maxs += sum * ((lim - j) / siz);
			ans = max(ans, maxs);
		}
	}
	cout << ans << endl;

	return 0;
}

Submission status: Runtime Error

Solution code:
x, k, d = [int(i) for i in input().split()]
x = abs(x)
if(x - k * d > 0):
    print(x - k * d)
else:
    moves_to_base_without_exceeding = x // d
    if(((moves_to_base_without_exceeding - k) % 2 == 0)):
        print(x % d)
    else:
        print(d - x % d)

Submission status: Runtime Error

Solution code:
def solve(shoki):
    global n,k,p,c
    sude=[-1]*n
    sude[shoki]=0
    ten=[0]
    now=shoki
    ishuu_kai=0
    ishuu_ten=0
    for i in range(n):
        now=p[now]
        if(sude[now]<0):
            sude[now]=i+1
            ten.append(ten[-1]+c[now])
        else:
            ten.append(ten[-1]+c[now])
            ishuu_kai=i+1-sude[now]
            ishuu_ten=ten[-1]-ten[sude[now]]
            break
    if(ishuu_ten>0):
        now=shoki
        for i in range(ishuu_kai):
            ten[i]+=((k-i)//ishuu_kai)*ishuu_ten
            now=p[now]
    if(k>ishuu_kai):
        return max(ten[1:])
    else:
        return max(ten[1:k])
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=[]
for i in range(n):
    ans.append(solve(i))

print(max(ans))

Submission status: Runtime Error

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

def calc_score(x):
    
    score = [0]
    cnt = 0
    visit = set()
    while not p[x] in visit:
        x = p[x]
        visit.add(x)
        score.append(score[-1] + c[x])
        cnt += 1
    if k<=cnt:
        return max(score[1:k+1])
    else:
        if score[-1]>0:
            return max(score[1:(k%cnt+1)]) + (k//cnt) * score[-1]
        else:
            return max(score[1:])

ans = max(calc_score(i) for i in range(n))
print(ans)

Submission status: Runtime Error

Solution code:
# n=int(input())
n,k=map(int,input().split())
P=list(map(int,input().split()))
P=[i-1 for i in P]
C=list(map(int,input().split()))
ans=-float("inf")
for i in range(n):
    dp=[-float("inf")]*(k+1)
    kai=0
    dp[kai]=C[P[i]]
    now=P[i]
    bef=i
    while 1:
        kai+=1
        if kai>=k:break
        dp[kai]= dp[kai-1]+C[P[now]]
        now=P[now]
    #if dp[0]==max(dp):dp[0]=-float("INF")
    ans=max(ans,max(dp))
print(ans)