Accepted
Code
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while(t>0){
t--;
string s;
cin >> s;
int l=s.size();
vector<int> bk(26,0);
for(auto &nx : s){
bk[nx-'a']++;
}
string res;
for(int i=0;i<l;i++){
for(int k=0;k<26;k++){
if(!res.empty()){
if(res.back()-'a' == k){
if(k==25){
res="-1";
break;
}
continue;
}
}
if(bk[k]==0){
if(k==25){
res="-1";
break;
}
continue;
}
bk[k]--;
int rem=l-i-1;
bool ok=true;
for(int j=0;j<26;j++){
if(k==j){
if(bk[j]>(rem)/2){ok=false; break;}
}
else{
if(bk[j]>(rem+1)/2){ok=false; break;}
}
}
if(!ok){
if(k==25){
res="-1";
break;
}
bk[k]++;
continue;
}
res.push_back('a'+k);
break;
if(k==25){
res="-1";
break;
}
}
if(res=="-1"){break;}
}
cout << res << "\n";
}
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 15:41:25
- Judged At
- 2025-07-14 15:41:25
- Judged By
- Score
- 100
- Total Time
- 5ms
- Peak Memory
- 764.0 KiB