/ SeriousOJ /

Record Detail

Accepted


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

Code

#include<bits/stdc++.h>
using namespace std;
const long long M=1e6+1,MOD=1e9+7;
typedef long long ll;


int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t=1;
   
    cin>>t;
    while(t--){
    	string s;
    	cin>>s;
    	int n=(int)s.size();
    	vector<int>fre(26,0);
    	for(int i=0;i<n;i++)fre[s[i]-'a']++;
    	int cur=0;
    	for(int i=0;i<26;i++)cur=max(cur,fre[i]);
    	int rem=n-cur;
    	if(cur-rem>1){
    		cout<<-1<<"\n";
    		continue;
    	}
    	vector<int>res(n+2,-1);
    	int baki=n;
    	for(int i=1;i<=n;i++){
    		int cur_mx=0;
    		for(int j=0;j<26;j++)cur_mx=max(cur_mx,fre[j]);
    		rem=baki-cur_mx;
    		if(cur_mx>rem){
    			for(int j=0;j<26;j++){
    				if(fre[j]==cur_mx){
    					res[i]=j;
    					fre[j]--;
    					break;
    				}
    			}
    		}
    		else{
    			for(int j=0;j<26;j++){
    				if(fre[j] && res[i-1]!=j){
    					res[i]=j;
    					fre[j]--;
    					break;
    				}
    			}
    		}
    		baki--;
    	}
    	for(int i=1;i<=n;i++)cout<<(char)('a'+res[i]);
    	cout<<"\n";
    	
    	}
    	
    	   
    return 0;
 
}

Information

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