Harvard

No attempts yetTime limit10sMemory limit128 MB

Problem

The term "Harvard architecture" describes a computer that keeps its instructions and its data in physically separate memories. The name comes from the Harvard Mark I, delivered by IBM in 1944, which stored instructions on paper tape and data in relays.

Some modern microcontrollers also use a Harvard architecture, though without paper tape or relays. Data memory is divided into banks, and every bank holds the same number of data items. Each data-referencing instruction carries a byte offset ff into a bank and a bit aa that selects which bank is used.

  • If a=0a = 0, bank 00 is referenced.
  • If a=1a = 1, the bank named by the bank select register (BSR) is referenced.

Assume every instruction takes the same amount of time, and that a separate instruction can load a value into the BSR.

For example, suppose there are 44 banks of 88 bytes each. To reach location 55 you can either issue one instruction with a=0a = 0 and f=5f = 5, or first set the BSR to 00 and then issue an instruction with a=1a = 1 and f=5f = 5. The first way is faster because it needs no BSR update.

Now suppose, with the same memory, you must reach location 2020. Only one way works: set the BSR to 22 (unless it already holds 22), then issue an instruction with a=1a = 1 and f=4f = 4.

A program is a sequence of operations. Each operation is one of:

  • a variable reference, written ViV_i, where ii is a positive integer, or
  • a repetition, written Rn P ER_n\ \langle P\rangle\ E, where nn is a positive integer and PP is any program; it is equivalent to running PP exactly nn times in a row.

You may freely choose which bank each variable is mapped to, as long as no bank holds more than its allowed number of variables. Given the number and size of the banks and a program to run, choose the mapping that minimizes the running time, and report that time: the total number of instructions executed (memory references plus BSR loads). The BSR starts undefined and changes only when an instruction explicitly loads it.

Input

The input is a single test case on two lines. The first line has two integers bb and ss (1b131 \le b \le 13, 1s131 \le s \le 13): bb is the number of memory banks and ss is the number of variables that fit in one bank. The second line is a non-empty program of at most 10001000 space-separated elements (each RnR_n, ViV_i, and EE counts as one element).

You may assume:

  • In a repetition RnR_n, 1n1061 \le n \le 10^6.
  • In a repetition Rn P ER_n\ \langle P\rangle\ E, the body PP is non-empty.
  • In a variable reference ViV_i, 1imin(bs,13)1 \le i \le \min(b \cdot s, 13).
  • The total number of variable references made by one execution of the program is at most 101210^{12}.

Output

Print the minimum number of instructions needed to run the program.