#P7792. Keymaster’s Endless Challenge

    ID: 20978 Type: Default 1000ms 256MiB

Keymaster’s Endless Challenge

Keymaster’s Endless Challenge

Sisyphus is given n keys by the master locksmith. Each key is attached on a circular pendant in a fixed order. The keys are numbered from 1 to n, and key i can open door vi (each key opens exactly one door, and the v values form a permutation of {1,…,n}).

Sisyphus is taken into a circular room that has exactly n locked doors numbered 1 to n. He must unlock and then re‐lock each door. He proceeds along the wall in a fixed direction. When he reaches a door, his process is as follows:

  1. He looks at the key at the front (i.e. the leftmost key) on his pendant. He tries to open the door with that key.
  2. If the key does not match the door (i.e. if the door number does not equal the key’s designated door), he counts this as a wrong attempt, moves the key from the front to the back of the pendant, and then tries again with the new front key.
  3. This repeats until he finds the key that opens the door. When he finds the correct key, he unlocks and re-locks the door. The correct key is not rotated; it remains in place for the next door.

The doors are attempted in cyclic order: the first door he successfully opens is labeled 1, the second is labeled 2, …, and after door n he goes back to door 1 and so on. After his k-th successful unlocking, Sisyphus wonders:

"If only I knew how many times I put a wrong key in a door lock up to now!"

Your task is to compute the total number of wrong key attempts by the time of the k-th successful unlocking.

The answer may require simulating the process, but due to the cyclic nature, an efficient solution is possible by detecting cycles in the order of keys.

Note: All formulas must be given in LaTeX format. For instance, the fact that the target door during the process is given by $d= ((i-1) \mod n)+1$ for the $i$-th unlocking.

inputFormat

The first line contains two integers n and k ($1 \leq n \leq 10$, small for simulation purposes, and k is a positive integer), where n is the number of keys (and doors) and k is the number of successful unlockings.

The second line contains n integers $v_1, v_2, \dots, v_n$, which form a permutation of {1, 2, …, n}. Here, $v_i$ is the door that the $i$-th key can unlock.

outputFormat

Output a single integer --- the total number of wrong key attempts made until the k-th successful unlocking.

sample

3 3
2 1 3
5

</p>