


The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains two space-separated integers ‘n’ and ‘t’; representing the number of tasks and the least units of time between any two same tasks respectively.
The second line of the test case contains a string ‘tasks’ consisting of the ‘n’ uppercase character of the English alphabet.
For each test case, print the minimum total units of time ninja will take to complete all ‘n’ tasks.
Print the output of each test case in a new line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= n <= 10^4
1 <= t <= 100
Where ‘T’ is the number of test cases and ‘n’ is the number of tasks and ‘t’ is the least units of time between any two same tasks.
Time Limit : 1 sec
The idea is to add all the tasks in the Priority Queue with their frequency (number of occurrences), higher is frequency higher should be its priority. In each round Ninja picks ‘t+1’ tasks with the highest frequency and completes them, if there is less than ‘t+1’ task, then ninja needs to be idle for the remaining time.
Let's suppose the maximum frequency (number of occurrences) of the task/character in string ‘tasks’ is ‘maxFreq’ and the number of tasks with that maximum frequency is ‘countMaxFreq’. We have ‘n’ tasks and a ninja wants at least ‘t’ unit of time between any two same tasks.
Now, we can make a ‘maxFreq-1’ group of the size ‘t’+1 ( the last group will not contain idle spaces, it will contain the tasks with maximum frequency only). Each group has a different task with maximum frequency and the remaining number of empty slots i.e ‘_’ (if there is less than ‘t’+1 such task). The total length of these ‘maxFreq’ groups will be (‘maxFreq’-1)*(t+1) + ‘countMaxFreq’. Here, ‘countMaxFreq’ tells the size of the last group. Note, the units of time required is equal to the total length of these ‘maxFreq’ groups.
For example, Let there be two tasks ‘A’ and ‘B’ having maximum frequency 3. And ‘t’ = 2.
Then, we can arrange these tasks in order AB_AB_AB, where _ represent the time when a ninja is idle. Since the maximum frequency of a task (in this case ‘A’ and ‘B’) is 3, there will be 3 groups. The size of the first two groups will be equal to ‘t’+1, which is 3 ( denoting (AB_)(AB_)). The last group won’t contain the idle spaces and will only contain the characters left which are the characters with maximum frequency, AB in this case, which gives size 2. So,it takes takes at least (3-1)*(2+1) + 2 = 8 units of time.
After placing at most ‘t’+1. tasks with the highest frequency, we can place all the remaining tasks in empty slots (the time when a ninja is idle), If all the empty slots get filled then we can increase the size of groups. Thus answer will be maximum of ‘n’ and (‘maxFreq’-1)*(t+1) + ‘countMaxFreq’. The answer will be ‘n’ when all empty slots get filled
The implementation can be done as follow -: