/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 572.0 KiB
#2 Time Exceeded ≥1100ms ≥532.0 KiB
#3 Time Exceeded ≥1100ms ≥532.0 KiB

Code

#include<bits/stdc++.h>
using namespace std;
#define ll long long int 

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
   ll tc;
    cin>>tc;
    while(tc--)
    {
        string s;
        cin>>s;
        unordered_map<char,ll>mp;
        for(int i=0;i<s.size();i++)
            mp[s[i]]++;
        ll n=s.size();
        ll c=0;
        for(auto it:mp)
        {
            if(it.second>(n+1)/2)
            {
                c=1;
                break;
            }
        }
        if(c==1)
            cout<<-1<<"\n";
        else
        {
            string k;
            unordered_map<char,ll>sp;
            sp=mp;
            while(1)
            {
                if(sp.size()==0)
                    break;
                ll c=0;
                for(char ch='a';ch<='z';ch++)
                {
                    if(k.size()==0 && mp[ch]>0)
                    {
                        k+=ch;
                        mp[ch]--;
                        if(mp[ch]==0)
                            sp.erase(ch);
                        c=1;
                        break;
                        
                    }
                    else if(k.size()>0 && k[k.size()-1]!=ch && mp[ch]>0)
                    {
                        k+=ch;
                        mp[ch]--;
                        if(mp[ch]==0)
                            sp.erase(ch);
                        c=1;
                        break;
                    }
                }
                if(c==0 && sp.size()==1 && mp[k[k.size()-1]]==1)
                {
                    string d;
                    ll id=0;
                   for(int i=0;i<k.size();i++)
                   {
                       if(k[i]==k[k.size()-1])
                       {
                           id=i;
                           break;
                       }
                   }
                    for(int i=0;i<id-1;i++)
                        d+=k[i];
                    d+=k[k.size()-1];
                    for(int i=id-1;i<k.size();i++) d+=k[i];
                    k=d;
                    sp.erase(k[k.size()-1]);
                    break;
                }
                if(sp.size()==0) break;
                
            }
            cout<<k<<"\n";
        }
    }
    
    
}

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-15 20:55:49
Judged At
2025-07-15 20:55:49
Judged By
Score
0
Total Time
≥1100ms
Peak Memory
≥572.0 KiB