/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 324.0 KiB
#2 Wrong Answer 1ms 532.0 KiB
#3 Wrong Answer 2ms 324.0 KiB

Code

/*
 *Copyright (c) Swadheen Islam Robi (SIR01)
 *Created on Mon Jul 14 2025 8:45:49 PM
 */
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define pie 2*(acos(0.0))
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define pb push_back
#define endl "\n"
#define lcm(a,b) (a*b)/(__gcd<ll>(a,b))
#define mod 1000000007
#define srt(v) sort(v.begin(),v.end())
#define rsrt(v) sort(v.rbegin(),v.rend())
#define ALLAHU_AKBAR ios::sync_with_stdio(false); cin.tie(nullptr);

void sir()
{
    // Bismillahir Rahmanir Rahim 

    string s; cin>>s;
    ll n = s.length();

    map<char,ll>mp;
    for(auto &c:s)mp[c]++;
    
    //map<ll,ll>mp2;
    // for(auto &[c,cnt]:mp) mp2[cnt]++;

    vector<ll>cnt;
    cnt.pb(0ll);
    vector<pair<char,ll>>pr;
    ll mx = -1;
    ll sum = 0;
    for(auto &[c,x]:mp)
    {
        cnt.pb(x);
        pr.pb({c,x});
        sum += x;
        mx = max(mx, x);
    }
    // for(ll i=1; i<cnt.size(); i++)
    // {
    //     if(cnt[i]-cnt[i-1]>1 && cnt[i-1]!=1)
    //     {
    //         cout<<-1<<endl;
    //         return;
    //     }
    // }
    ll cover = sum-mx;
    if(mx-cover>1)
    {
        
        cout<<-1<<endl;
        return;
        
    }
    srt(pr);

    ll sz = pr.size();
    string ans ="";

    ll ind = 0;
    char last = pr[pr.size()-1].first;

    ll rem = sz;
    set<char>st; for(auto &[c,x]:mp) st.insert(c);

    while(1)
    {
        if(st.size()==0)
        {
            break;
        }
        char now = pr[ind].first;
        if(mp[now]>0)
        {
            ans += now;
            mp[now]--;
        }
        else{
            if(st.find(now)!=st.end()) st.erase(now);
        }
        ind++;
        ind%=sz;
    
    }
    if(n>1 && ans[n-1]==ans[n-2])
    {
        string ans2 = "";
        if(ans[0]!=ans[n-1]) 
        {
            ans2 += ans[n-1];
            ans2 += (ans.substr(0, n-1));
            cout<<ans2<<endl;
            return;
        }

        ans2="";
        for(ll i=n-2; i>=1; i--)
        {
            
            if(ans[i] != ans[n-1] && ans[i-1] != ans[n-1])
            {
                ans2 += ans.substr(0,i);
                ans2 += ans[n-1];
                ans2 += ans.substr(i,(n-1-i));
                cout<<ans2<<endl;
                return;
            }
        }
    }
    cout<<ans<<endl;



}

int main() {
    ALLAHU_AKBAR

    ll t = 1;
    cin>>t;
    while(t--)
    {
        sir();
    }
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Contest
Educational Round 1
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-14 17:57:16
Judged At
2025-07-14 17:57:16
Judged By
Score
0
Total Time
2ms
Peak Memory
532.0 KiB