/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 2ms 532.0 KiB
#2 Accepted 5ms 532.0 KiB
#3 Accepted 5ms 532.0 KiB
#4 Accepted 5ms 320.0 KiB
#5 Accepted 5ms 532.0 KiB
#6 Accepted 5ms 564.0 KiB
#7 Accepted 5ms 580.0 KiB
#8 Accepted 5ms 532.0 KiB
#9 Accepted 5ms 508.0 KiB
#10 Accepted 5ms 512.0 KiB
#11 Accepted 5ms 532.0 KiB
#12 Accepted 5ms 504.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;

void solve(int cs) {
  string s;
  cin >> s;
  int cnt[26] {}, n = s.size();
  for (auto &c : s) cnt[c - 'a'] += 1;
  string ans;
  while (ans.size() < n) {
    bool changed = false;
    for (int i = 0; i < 26; i++) {
      if (cnt[i] > 0 && (ans.size() == 0 || ans.back() != (i + 'a'))) {
        ans += (i + 'a');
        cnt[i] -= 1;
        int rem = n - ans.size();
        bool fail = false;
        for (int j = 0; j < 26; j++) {
          if (i != j) {
            if ((rem + 1) / 2 < cnt[j]) {
              fail = true;
              break;
            }
          } else if (cnt[j] > rem / 2) {
            fail = true;
            break;
          }
        }
        if (fail) {
          ans.pop_back();
          cnt[i] += 1;
        } else {
          changed = true;
          break;
        }
      }
    }
    if (changed == false) {
      break;
    }
  }
  if (ans.size() < n) cout << "-1\n";
  else cout << ans << "\n";
}

int32_t main() {
  cin.tie(0) -> sync_with_stdio(0);
  int t = 1;
  cin >> t;
  for (int i = 1; i <= t; i++) {
    solve(i);
  }
  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 16:38:52
Judged At
2025-07-14 16:38:52
Judged By
Score
100
Total Time
5ms
Peak Memory
580.0 KiB