/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 532.0 KiB
#3 Accepted 1ms 532.0 KiB
#4 Accepted 2ms 532.0 KiB
#5 Accepted 2ms 532.0 KiB
#6 Accepted 3ms 532.0 KiB
#7 Accepted 4ms 532.0 KiB
#8 Accepted 4ms 532.0 KiB
#9 Accepted 3ms 532.0 KiB
#10 Accepted 5ms 532.0 KiB
#11 Accepted 5ms 532.0 KiB
#12 Accepted 5ms 532.0 KiB
#13 Accepted 5ms 532.0 KiB
#14 Accepted 5ms 320.0 KiB
#15 Accepted 5ms 324.0 KiB

Code

/*
 *   Copyright (c) 2025 Emon Thakur
 *   All rights reserved.
 */
#include<bits/stdc++.h>
using namespace std;
void ans(int rem,int n,char last,vector<int>&cnt)
{
    if(rem==0) return;
    for(char ch='a';ch<='z';ch++)
    {
        if((!cnt[ch-'a']) || ch==last) continue;
        cnt[ch-'a']--;
        int mx = 0;
        for(int i=0;i<26;i++) mx=max(mx,cnt[i]);
        if(mx <= rem/2)
        {
            cout<<ch;
            ans(rem-1,n,ch,cnt);
            break;
        }
        cnt[ch-'a']++;
    }
}

void solve()
{
    string s; cin >> s;
    int n = s.size();
    int mx =0;
    vector<int>cnt(26,0);
    for(auto e:s) cnt[e-'a']++;

    for(int i=0;i<26;i++)
    {
        if(cnt[i] > (n+1)/2) 
        {
            cout<<-1<<'\n';
            return;
        }
        mx = max(mx , cnt[i]);
    }
    ans(n,n,'A',cnt);
    cout<<'\n';
}
int main()
{
    ios::sync_with_stdio(false); cin.tie(nullptr);
    int t; cin >> t; while(t--) solve();
}

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-10 10:09:55
Judged At
2025-07-10 10:09:55
Judged By
Score
100
Total Time
5ms
Peak Memory
532.0 KiB