The city of Palembang is separated by Musi River into two zones. Let’s call them zone and zone .
Each zone consists of exactly buildings along the respective side of the river, conveniently numbered through . The distance between every pair of adjacent buildings is unit of distance. The width of the river is unit of distance as well. Building in zone is located on exactly the opposite side of building in zone .
citizens live and work in the city. Citizen ’s house is in zone , building , while his office is in zone , building . If a citizen must cross the river to go from his house to his office, he must take a boat. This has been uncomfortable, so the government has decided to build at most bridges over the river, so that the citizens can go to work by driving. Each bridge must be built exactly between two opposite buildings in the two zones. The bridges must be strictly perpendicular to the river. The bridges must not overlap each other.
Let be the minimum distance citizen has to drive to go from his house to his office, after the government has built at most bridges. Help the government build the bridges in such a way that the sum is minimized.
The first line contains two integers and . Each of the next lines contains four tokens , , , and .
A single line containing the minimum sum of the distances.
Sample Input 1
1 5 B 0 A 4 B 1 B 3 A 5 B 7 B 2 A 6 B 1 A 7
Sample Output 1
Sample Input 2
2 5 B 0 A 4 B 1 B 3 A 5 B 7 B 2 A 6 B 1 A 7
Sample Output 2
This is the illustration for both sample inputs.
Here is one possible solution for sample input 1. The pink stripe segment denotes a bridge.
And this is a possible solution for sample input 2:
For each subtask,
- and will be either a character
Aor a character
- More than one house or office (or combination of both) can be located in the same building.