/ SeriousOJ /

Record Detail

Accepted


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

Code

#pragma GCC optimize("O3,unroll-loops")
#include<bits/stdc++.h>
using namespace std;

#define fastio() ios_base::sync_with_stdio(false);cin.tie(nullptr);


const int N = 26 ;

bool ok(char c , vector <int> &cnt , int len) {
  int mx = 0 ;
  int at = 0 ;
  for(int i = 0 ; i < N ; i ++) {
    if(c - 'a' == i) continue ;
    mx = max(mx , cnt[i]) ;
  }
  return (mx <= (len + 1) / 2) ;
}

void solve() {
       
     
      string s ;
      cin >> s ;
      int n = s.size() ;
      string ans(n + 1 , '?') ;
      vector <int> cnt(N) ;
      for(int i = 0 ; i < n ; i ++) {
        cnt[s[i] - 'a'] ++ ;
      }
      
      for(int i = 0 ; i < n ; i ++) {
        char c = '?' ;
        int mx = 0 ;
        char cmx = '?' ;
        int fre = 0 ;
        for(char pos = 'a' ; pos <= 'z' ; pos ++) {
          if(cnt[pos - 'a'] == 0) continue ;
          if(pos == ans[i]) continue ;
          if(cnt[pos - 'a'] > mx) {
            mx = cnt[pos - 'a'] ;
            cmx = pos ;
          } else if(mx == cnt[pos - 'a']) fre ++ ;
          if(c == '?') c = pos ;
        }
        if(ok(c , cnt , n - i - 1)) {
          ans[i + 1] = c ;
          cnt[c - 'a'] -- ;
        } else if(ok(cmx , cnt , n - i - 1)) {
          ans[i + 1] = cmx ;
          cnt[cmx - 'a'] -- ;
        } else {
          cout << -1 << endl ;
          return ;
        }
      }
      for(int i = 1 ; i <= n ; i ++) cout << ans[i] ;
      cout << endl; 
}









int32_t main() {

    fastio();
    int t = 1;
    cin >> t;
    while (t--) solve();
}

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:38:31
Judged At
2025-07-14 17:38:31
Judged By
Score
100
Total Time
3ms
Peak Memory
532.0 KiB