Cemented strings

3.8

10 votes
String Algorithms, Algorithms, Hashing Algorithm
Problem

Bob is a construction worker who does mathematics for increasing his efficiency. He is working on a site and has buckets of cement lined up with different characters marked upon them. He has a strict command from the senior that he cannot change the order of the buckets.

Before starting his work, he has been given a string of length in which the character at position () gives us the mark on the bucket. He can only carry one bucket at a time and bring it back to the base site. In each round, he has a criterion on which bucket to pick up. He will take the bucket with the smallest character marked upon it () and if there are multiple buckets with the smallest character, then he will take the one closest to the base.

The cost of picking up a bucket is the number of buckets he passes through while walking from the site to get (the bucket which he picks is also included). In each round, the cost accumulates. Find the final cost incurred by Bob while completing his job.

Input format

  • The first line consists of an integer  denoting the number of test cases.
  • The following lines consist of an integer denoting the number of baskets.
  • The next line contains a string of length where () denotes the mark on the bucket.

Output format

Print the accumulation cost for each test case separated by a new line.

Constraints

The sum of over all test cases does not exceed 106.

Sample Input
1
5
badce
Sample Output
7
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation
  • badce - Firstly Bob takes the second basket with mark 'a' and adds 2 to the cost.
  • bdce - Then he takes the first basket with the mark 'b' and adds 1 to the cost.
  • dce - Then he takes the second basket with the mark 'c' and adds 2 to the cost.
  • de - Again he takes the first basket with the mark 'd' and adds 1 to the cost.
  • e - Again he takes the first basket with the mark 'e' and adds 1 to the cost.

The total cost becomes 7 units.

Editor Image

?