/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 2ms 320.0 KiB
#2 Accepted 2ms 324.0 KiB
#3 Accepted 3ms 324.0 KiB
#4 Accepted 5ms 808.0 KiB
#5 Accepted 168ms 5.625 MiB
#6 Accepted 34ms 1.117 MiB
#7 Accepted 111ms 5.418 MiB
#8 Accepted 142ms 5.41 MiB

Code

#include <bits/stdc++.h>
using namespace std;
#define SC               scanf
#define PF               printf
#define ull              unsigned long long
#define ld               long double
#define F                first
#define S                second
#define pb               push_back
#define sort_a(a)        sort(a.begin(),a.end());
#define sort_d(a)        sort(a.rbegin(),a.rend());
#define READ(f)          freopen(f, "r", stdin)
#define WRITE(f)         freopen(f, "w", stdout)
#define rev(s)           reverse(s.begin(),s.end())
#define P(ok)            cout << (ok ? "YES\n": "NO\n")
#define __Heart__              ios_base :: sync_with_stdio(false); cin.tie(NULL);
#define ll long long
typedef pair< ll , ll>                   PII;
char indexToChar(int index) {
    return 'a' + index;
}
void solve()
{
    int n , m , freq[26] ; cin >> n >> m ;
    for(int i = 0 ; i < 26 ; i++) freq[i] = 0 ;
    string s ; cin  >> s ;
    map < int , set < int > > mp ;
    set < int > st ;
    for(int i = 0 ; i < n ; i++){
        int ch = s[i] - 'a' ;
        freq[ch]++ ;
        mp[ch].insert(-i) ;
        st.insert(ch) ;
    }
    for(auto it : st){
            if(!m) break ;
         //   cout << "before swapping " << indexToChar(it) << " --> " << s << endl ;

        vector < pair <int , int > > v ;
        int i = 0 ;
        while(freq[it] && i < n && m){
          //  cout << freq[it] << " " << indexToChar(it) << " --> " << i << " " << m << endl ;
            int ch = s[i]- 'a' ;
            if(it == ch) freq[it]--;
            else if(it < ch){
                m-- ;
                freq[it]-- ;
                v.pb({ch , i}) ;
            }
            i++ ;
        }
        sort_d(v) ;
       // for(auto it : v) cout << it.F ; cout << endl ;
        int j = 0 ;
        for(auto kt : mp[it]){
         if(j == v.size()) break ;
        // cout << " swaping.... " << indexToChar(it) << " " << " pos " <<  kt << " " << v[j].S << endl ;
         if(-kt > v[j].S){
            swap(s[-kt] , s[v[j++].S]) ;
            mp[v[j - 1].F].erase(-v[j - 1].S) ;
            mp[v[j - 1].F].insert(kt) ;
         }
         }

        //  cout << "after swapping " << indexToChar(it) << "--> " << s << endl ;
    }
    cout << s << "\n" ;


}
int main()
{
     __Heart__
     int t ; cin >> t ; while(t--) solve() ;
}

Information

Submit By
Type
Submission
Problem
P1058 Lexicographically Smallest String
Language
C++20 (G++ 13.2.0)
Submit At
2024-08-22 23:27:17
Judged At
2024-11-11 03:05:51
Judged By
Score
100
Total Time
168ms
Peak Memory
5.625 MiB