Codeforces Round 915 (Div. 2)
C
Largest Subsequence
Codeforces
1400
原题
← BD →
翻译中…

Given is a string $s$ of length $n$. In one operation you can select the lexicographically largest$^\dagger$ subsequence of string $s$ and cyclic shift it to the right$^\ddagger$.

翻译中…

Your task is to calculate the minimum number of operations it would take for $s$ to become sorted, or report that it never reaches a sorted state.

翻译中…

$^\dagger$A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:

翻译中…
  • $a$ is a prefix of $b$, but $a \ne b$;
  • In the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
翻译中…

$^\ddagger$By cyclic shifting the string $t_1t_2\ldots t_m$ to the right, we get the string $t_mt_1\ldots t_{m-1}$.

翻译中…

Input

翻译中…

Each test consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. The description of the test cases follows.

翻译中…

The first line of each test case contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the string $s$.

翻译中…

The second line of each test case contains a single string $s$ of length $n$, consisting of lowercase English letters.

翻译中…

It is guaranteed that sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.

翻译中…

Output

翻译中…

For each test case, output a single integer — the minimum number of operations required to make $s$ sorted, or $-1$ if it's impossible.

翻译中…

Note

翻译中…

In the first test case, the string $s$ is already sorted, so we need no operations.

翻译中…

In the second test case, doing one operation, we will select cb and cyclic shift it. The string $s$ is now abc which is sorted.

翻译中…

In the third test case, $s$ cannot be sorted.

翻译中…

In the fourth test case we will perform the following operations:

翻译中…
  • The lexicographically largest subsequence is zca. Then $s$ becomes abzc.
  • The lexicographically largest subsequence is zc. Then $s$ becomes abcz. The string becomes sorted.
翻译中…

Thus, we need $2$ operations.

翻译中…

样例

Input #1
6
5
aaabc
3
acb
3
bac
4
zbca
15
czddeneeeemigec
13
cdefmopqsvxzz
Output #1
0
1
-1
2
6
0
InputCopy OutputCopy
题目信息
题号
1905C
时间限制
1 s
内存限制
256 MB
标签
贪心
字符串

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。