You are given a string consisting of lowercase English letters and an integer .
You may choose at most pairwise disjoint substrings of . For each chosen substring, independently rearrange its characters into nondecreasing alphabetical order.
Your goal is to make the entire string sorted in nondecreasing alphabetical order.
Find the minimum possible sum of the lengths of the chosen substrings. If is already sorted, you may choose no substrings, with a total length of .
The first line contains the number of test cases .
Each test case is given in the following format:
For each test case, output one integer: the minimum possible sum of the lengths of the chosen substrings.
Sorting positions through produces the sorted string abcdefghi, with total length . The letters at positions and must exchange places, and so must the letters at positions and . With only one chosen substring, it has to cover all positions from through .
Sort the substring at positions through and the substring at positions through . Their total length is , and every position that changes is covered.
Sorting the whole string gives abcde, with cost . The letters a and e have to move between the two ends, so no shorter chosen substring can be sufficient.
Sort positions through and positions through . The resulting string is abcdefghijklmn, and the total length is . With only two substrings, at least two of the three separated unsorted parts must be covered together; joining the first two has the smallest cost.
Sort positions through , positions through , and positions through . These substrings have total length and make the whole string sorted.