Tools of the Trade
Time limit1sMemory limit256 MB
Assign each soldier one stocked weapon to minimize the sum of rank positions in their preference lists.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path
- Solved
- No attempts yet
Problem
King Theoden pulled his people back into Helm's Deep to meet the raids on his land and the threat from Saruman. The armory does not hold enough weapons of each type to give every soldier the weapon they handle best, so the quartermaster has to hand out the stock in the way that leaves the army fighting as well as it can.
Every soldier has a ranking of all weapon types, written from the weapon that soldier handles best to the one they handle worst. A soldier who receives the weapon in position of their own ranking adds to the total inexperience, where the best weapon sits at position . A soldier whose ranking is ABCD adds when given C and when given B. Each soldier receives exactly one weapon, and a weapon type can be handed out at most as many times as the armory holds copies of it. Find the smallest total inexperience.
Input
The first line holds the number of test cases, which is at most .
The first line of each test case holds the number of weapon types and the number of soldiers (, ).
The next lines each hold a character and an integer . is the uppercase letter that stands for a weapon type, and is the number of copies in the armory (). The letters are distinct.
The next lines each hold one soldier's ranking, a string of all weapon letters written from the weapon that soldier handles best to the one they handle worst.
The armory always holds at least weapons in total, so every soldier can be armed. The sum of over all test cases is at most .
Output
For each test case, print the smallest total inexperience on its own line.