If recruits learn these maneuvers through constant practice, they will be able to carry them out more easily in battle itself.
- Vegetius, Epitome of Military Science, Book I, Chapter 26
The army you command must change formations as the battle unfolds. However, if changing formations requires many commands, the army may struggle to respond to a sudden change in battle. You want to identify weaknesses in formation changes and improve the training.
The units are numbered through . Each formation places the units in a line and is represented by their numbers in order from the left flank to the right flank. One command can swap the positions of two neighboring units.
You are given the formations you have prepared. For each formation, find the maximum, over the other formations, of the minimum number of commands needed to change to that formation. Intermediate formations do not have to appear in the given list.
The first line contains integers and , separated by a space.
Each of the next lines contains unit numbers for a formation in order from the left flank to the right flank, separated by spaces.
Print the answer for each formation on its own line, in the given order.
In the first example, changing between the first and second formations requires at least commands. Changing between the first and third requires at least commands, and changing between the second and third requires at least commands.
In the second example, swapping the middle unit and the unit at the right end once changes one formation into the other.