CF1905C.Largest Subsequence
普及/提高-
通过率:0%
AC君温馨提醒
该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。
题目描述
Given is a string s of length n . In one operation you can select the lexicographically largest † subsequence of string s and cyclic shift it to the right ‡ .
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.
† 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=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 .
‡ By cyclic shifting the string t1t2…tm to the right, we get the string tmt1…tm−1 .
输入格式
Each test consists of multiple test cases. The first line contains a single integer t ( 1≤t≤104 ) — 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≤n≤2⋅105 ) — 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⋅105 .
输出格式
For each test case, output a single integer — the minimum number of operations required to make s sorted, or −1 if it's impossible.
输入输出样例
输入#1
6 5 aaabc 3 acb 3 bac 4 zbca 15 czddeneeeemigec 13 cdefmopqsvxzz
输出#1
0 1 -1 2 6 0
说明/提示
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.