jainyatn's blog

By jainyatn, history, 3 hours ago, In English

I solved problem B "Replace Character" using frequency manipulation.

My understanding is:

  • We need to perform exactly one operation: s[i] = s[j]
  • The objective is to minimize the number of distinct permutations.
  • The statement also says we can output ANY permutation of the resulting string.

So instead of modifying the original string directly, I:

  1. Find the character with minimum frequency.
  2. Find the character with maximum frequency.
  3. Decrease the minimum frequency by 1.
  4. Increase the maximum frequency by 1.
  5. Print any permutation using the modified frequencies.

For example: abc -> cbc and since any permutation is allowed, printing bcc should also be valid.

However, this solution gets WA on hidden tests.

Code:

#include<bits/stdc++.h>
using namespace std;

int main(){
    int t;cin>>t;

    while(t--){
        int n;
        cin>>n;

        string s;
        cin>>s;

        map<char,int>m;

        for(int i=0;i<n;i++){
            auto it = m.find(s[i]);

            if(it == m.end()){
                m[s[i]] = 1;
            }
            else{
                m[s[i]]++;
            }
        }

        char maxi = s[0];
        char mini = s[0];

        for(auto it : m){

            if(it.second >= m[maxi]){
                maxi = it.first;
            }

            if(it.second < m[mini]){
                mini = it.first;
            }
        }

        m[mini]--;
        m[maxi]++;

        for(auto it : m){
            for(int j=0;j<it.second;j++){
                cout<<it.first;
            }
        }

        cout<<endl;
    }

    return 0;
}

Can someone point out the failing case or explain what condition I am missing?

  • Vote: I like it
  • -2
  • Vote: I do not like it

»
82 minutes ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

When I submit your code, I found this in the checker comment:
wrong answer. At most one character should differ from the original string (test case 1)

You are getting this because bcc is not the solution for abc. Although it is the string that has the smallest distinct permutations, but you can't get bcc from abc in only one operation.

  • »
    »
    25 minutes ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    but bcc is a valid permutation of cbc(explained in the question when explaining the 1st example). and also it written that we can output permutations

    • »
      »
      »
      5 minutes ago, hide # ^ |
      Rev. 2  
      Vote: I like it 0 Vote: I do not like it

      But you can't get bcc from abc! Please remember that you can only do the operation only once