Pekka's Student Years
Time limit1sMemory limit1024 MB
Two trains of N cars each hold matched cargo types; shifting either train one car forward costs one unit, so find the minimum total shifts to align and unload all cars.
- Level
Medium6 of 10
- Topics
- Greedy, Two pointers, Implementation
- Solved
- No attempts yet
Problem
Pekka has grown up, become a student, and works part-time unloading railway cars when he is not studying. He has to move the goods from one train to another train standing next to it on a parallel track.
We know what goods are in each car of the first train and what goods must be in each car of the second train. The goods from any car of the first train can easily be moved onto the car of the second train standing opposite it with a conveyor. The problem is that the order of the cars in the first train may not match the order of the cars in the second train.
To put the goods from a car of the first train into the correct car of the second train, Pekka can shift either train by the length of one car, but only forward, downhill, and he must drink a can of energy drink each time he does so.
Pekka cares a lot about his health and does not want to overuse the energy drink. Help Pekka find the minimum number of cans of the drink he needs to drink in order to move all the goods from the first train.
The following holds:
- All cars have the same length.
- Each type of goods has a specific word as its name ("
Oil", "Wood", and so on). - The number of cars of the first train carrying goods of any given type equals the number of cars of the second train that are to receive goods of that same type.
- There may be several cars of the first train carrying goods of the same type. Any of them can be moved into the corresponding cars of the second train, but each must be moved in full.
- If a car of the first train carrying a certain type of goods comes opposite a car of the second train meant for that type of goods, Pekka may either carry out the transfer or refuse to do so.
- Initially the trains stand so that the first car of the first train is opposite the first car of the second train, and the last car of the first train is opposite the last car of the second train.
Input
The first line of the input contains the number of cars in the trains, (). The next lines describe the cars of the first train in the order in which they are coupled. Each line contains the name of the goods in the corresponding car. A name consists of 1 to 10 uppercase and lowercase Latin letters. Names are considered equal if they match with case taken into account (for example, "Oil" and "oil" are different goods). After that come lines describing the cars of the second train in the same way.
Output
Print the minimum number of cans of energy drink Pekka needs in order to carry out the loading.