Tools of the Trade

No attempts yetTime limit1sMemory limit256 MB

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 NN weapon types, written from the weapon that soldier handles best to the one they handle worst. A soldier who receives the weapon in position kk of their own ranking adds kk to the total inexperience, where the best weapon sits at position 00. A soldier whose ranking is ABCD adds 22 when given C and 11 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 2020.

The first line of each test case holds the number of weapon types NN and the number of soldiers MM (1N261 \le N \le 26, 1M2001 \le M \le 200).

The next NN lines each hold a character CC and an integer TT. CC is the uppercase letter that stands for a weapon type, and TT is the number of copies in the armory (1T10001 \le T \le 1000). The NN letters are distinct.

The next MM lines each hold one soldier's ranking, a string of all NN weapon letters written from the weapon that soldier handles best to the one they handle worst.

The armory always holds at least MM weapons in total, so every soldier can be armed. The sum of MM over all test cases is at most 10001000.

Output

For each test case, print the smallest total inexperience on its own line.