Ankit_132

C

Dec 16th, 2023
636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define _test   int _TEST; cin>>_TEST; while(_TEST--)
  6.  
  7. int main()
  8. {
  9.     _test
  10.     {
  11.         int n;
  12.         string s;
  13.         cin >> n >> s;
  14.  
  15.         vector<int> cnt(26);
  16.         for(auto e : s)
  17.             cnt[e - 'a']++;
  18.  
  19.         vector<int> v(n);
  20.  
  21.         string t;
  22.         for(int i = 0; i < n; i++)
  23.         {
  24.             char mmax = 'a';
  25.             for(char ch = 'a'; ch <= 'z'; ch++)
  26.             {
  27.                 if(cnt[ch - 'a'] > 0)
  28.                     mmax = ch;
  29.             }
  30.  
  31.             if(s[i] == mmax)
  32.             {
  33.                 t.push_back(mmax);
  34.                 v[i] = 1;
  35.             }
  36.  
  37.             cnt[s[i] - 'a']--;
  38.         }
  39.  
  40.         int ans = 0;
  41.         for(int i = 25; i >= 0; i--)
  42.         {
  43.             if(count(t.begin(),t.end(),i + 'a') > 0)
  44.             {
  45.                 ans -= count(t.begin(),t.end(),i + 'a');
  46.                 break;
  47.             }
  48.         }
  49.  
  50.         for(int i = 0; i < n; i++)
  51.         {
  52.             if(v[i])
  53.             {
  54.                 ans++;
  55.                 s[i] = t.back();
  56.                 t.pop_back();
  57.             }
  58.         }
  59.  
  60.         if(is_sorted(s.begin(),s.end()))
  61.             cout<<ans<<"\n";
  62.         else
  63.             cout<<-1<<"\n";
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment