/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 540.0 KiB
#2 Wrong Answer 1ms 540.0 KiB
#3 Wrong Answer 2ms 516.0 KiB

Code

#include<bits/stdc++.h>
#define endl        '\n'
#define F           first
#define S           second
#define pb          push_back
#define yes         cout<<"YES\n"
#define no          cout<<"NO\n"
#define all(x)      x.begin(),x.end()
#define allr(x)     x.rbegin(),x.rend()
#define error1(x)   cerr<<#x<<" = "<<(x)<<endl
#define error2(a,b) cerr<<"("<<#a<<", "<<#b<<") = ("<<(a)<<", "<<(b)<<")\n";
#define coutall(v)  for(auto &it: v) cout << it << " "; cout << endl;
using namespace std;
using ll = long long;
using ld = long double;

void solve() {
    ll n, m;
    string s1;
    cin >> n >> m >> s1;

    string s2 = s1;
    sort(all(s2));
    if(n <= m + 1) {
        cout << s2 << endl;
        return;
    }
    
    auto Val = [&] (char ch) -> int {
        return ch - 'a'; 
    };

    map<int, int> mp;
    for(int i = 0; i < n; i++) {
        mp[Val(s1[i])] += 1;
    }

    vector<set<int>> g(31);
    bool vis[31];
    auto dfs = [&](auto&& self, int u) -> int {
        // cerr << char(u + 'a') << ", ";
        vis[u] = 1;
        int mn = 30;
        if(mp[u] > 0) mn = min(mn, u);
        for(auto &v: g[u]) {
            if(vis[v]) continue;
            mn = min(mn, self(self, v));
        }
        return mn;
    };

    for(int i = 0; i < n; i++) {
        if(s1[i] == s2[i] && mp[Val(s1[i]) > 0]) {
            mp[Val(s1[i])] -= 1;
            continue;
        }
        // Case1
        memset(vis, 0, sizeof vis);
        // cerr << "=== " << i << " ====\n";
        int free = dfs(dfs, Val(s1[i]));
        // cerr << endl;
        char ch1 = free + 'a';

        // Case2
        char ch2 = 'z';
        for(auto &[ii, jj]: mp) {
            char tmp = 'a' + ii;
            if(jj > 0) ch2 = min(ch2, tmp);
        }
        // cerr << i << " = " << ch1 << " - " << ch2 << endl;
        if(m > 0 && Val(ch2) < free) {
            g[Val(ch2)].insert(Val(s1[i]));
            s1[i] = ch2;
            --m;
        }
        else {
            g[Val(ch1)].insert(Val(s1[i]));
            s1[i] = ch1;
        }
        mp[Val(s1[i])] -= 1;
    }
    cout << s1 << endl;
    return;
}

int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    int tc = 1;
    cin >> tc;
    for (int t = 1; t <= tc; t++) {
        // cout << "Case " << t << ": ";
        solve();
    }
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1058 Lexicographically Smallest String
Language
C++17 (G++ 13.2.0)
Submit At
2024-11-11 15:17:13
Judged At
2024-11-11 15:17:14
Judged By
Score
5
Total Time
2ms
Peak Memory
540.0 KiB