Harvard
Time limit10sMemory limit128 MB
Assign each variable of a program with nested repeats to a memory bank within capacity to minimize access and select costs.
- Level
Hard8 of 10
- Topics
- Backtracking, Dynamic programming, Recursion
- Solved
- No attempts yet
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 into a bank and a bit that selects which bank is used.
- If , bank is referenced.
- If , 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 banks of bytes each. To reach location you can either issue one instruction with and , or first set the BSR to and then issue an instruction with and . The first way is faster because it needs no BSR update.
Now suppose, with the same memory, you must reach location . Only one way works: set the BSR to (unless it already holds ), then issue an instruction with and .
A program is a sequence of operations. Each operation is one of:
- a variable reference, written , where is a positive integer, or
- a repetition, written , where is a positive integer and is any program; it is equivalent to running exactly 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 and (, ): is the number of memory banks and is the number of variables that fit in one bank. The second line is a non-empty program of at most space-separated elements (each , , and counts as one element).
You may assume:
- In a repetition , .
- In a repetition , the body is non-empty.
- In a variable reference , .
- The total number of variable references made by one execution of the program is at most .
Output
Print the minimum number of instructions needed to run the program.