#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
void solve(){
int n;
string s;
cin >> n >> s;
s = ' ' + s;
vector<int> vec;
vec.push_back(n);
for(int i = n - 1; i >= 1; i--){
if(s[i] >= s[vec.back()]) vec.push_back(i);//字典序最大的子序列一定是单调不增的
}
reverse(vec.begin(), vec.end());
int cnt = 0;
int res = 0;
string t;
for(auto x : vec){
if(s[x] == s[vec[0]]) cnt++;
t += s[x];
}
int m = vec.size();
res = m - cnt;
reverse(t.begin(), t.end());
for(int i = 0; i < m; i++){
int pos = vec[i];
char ch = t[i];
s[pos] = ch;
}
if(is_sorted(s.begin() + 1, s.end())){
cout << res << '\n';
}
else cout << "-1\n";
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while(T--){
solve();
}
return 0;
}
给定一个字符串s,可以进行一些操作:每次操作,找出s字典序最大的子序列,并将该子序列右移一位,求使s有序的最少操作次数
C++解决单调非递减子序列问题
最新推荐文章于 2024-01-26 17:41:57 发布
文章描述了一个使用C++编写的算法,解决给定字符串中找到最长的单调非递减子序列的问题。通过输入整数n和字符串s,计算并输出满足条件的子序列长度。
1861

被折叠的 条评论
为什么被折叠?



