56102023-08-08 11:42:13TomaSajtDiana and Numberscpp17Wrong answer 0/10027ms13940 KiB
#include <bits/stdc++.h>
using namespace std;

int length_without(const string& s, int i, int j) {
  int result = 0;
  bool was_not_null = false;
  for (int k = 0; k < s.size(); k++) {
    if (k != i && k != j) {
      was_not_null |= s[k] != '0';
      result += was_not_null;
    }
  }
  return result;
}

void write_without(const string& s, int i, int j) {
  bool was_not_null = false;
  for (int k = 0; k < s.size(); k++) {
    if (k != i && k != j) {
      was_not_null |= s[k] != '0';
      if (was_not_null) {
        cout << s[k];
      }
    }
  }
  cout << (was_not_null ? "\n" : "-1\n");
}

void task() {
  string s;
  cin >> s;
  int sum = 0;
  for (auto e : s) {
    sum += e - '0';
  }
  if (sum % 3 == 0) {
    cout << s << '\n';
    return;
  }
  for (int i = 0; i < s.size(); i++) {  // one digit - best
    if ((s[i] - '0') % 3 == sum % 3 && (i + 1 == s.size() || s[i] < s[i + 1])) {
      write_without(s, i, i);
      return;
    }
  }
  array<int, 3> best = {-1, 0, 0};           // length, without
  for (int i = s.size() - 1; i >= 0; i--) {  // one digit - last
    if ((s[i] - '0') % 3 == sum % 3) {
      best = {length_without(s, i, i), i, i};
      break;
    }
  }
  for (int i = 0; i + 1 < s.size(); i++) {  // two digits - best
    if ((s[i] - '0') % 3 && s[i] < s[i + 1]) {
      for (int j = i + 1; j < s.size(); j++) {
        if ((s[j] - '0') % 3 && (j + 1 == s.size() || s[j] < s[j + 1])) {
          best = max(best, {length_without(s, i, j), i, j});
          return;
        }
      }
      for (int j = s.size() - 1; j > i; j--) {
        if ((s[j] - '0') % 3) {
          best = max(best, {length_without(s, i, j), i, j});
          return;
        }
      }
    }
  }
  for (int i = s.size() - 1; i >= 1; i--) {  // two digits - last
    if ((s[i] - '0') % 3) {
      for (int j = i - 1; j >= 0; j--) {
        if ((s[j] - '0') % 3) {
          best = max(best, {length_without(s, i, j), i, j});
          break;
        }
      }
      break;
    }
  }
  write_without(s, best[1], best[2]);
}

int main() {
  cin.sync_with_stdio(0);
  cin.tie(0);

  int n;
  cin >> n;
  while (n--) task();
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1828 KiB
subtask20/9
2Wrong answer3ms1880 KiB
3Wrong answer2ms1964 KiB
subtask30/12
4Wrong answer3ms2232 KiB
5Wrong answer3ms2220 KiB
6Wrong answer3ms2556 KiB
7Wrong answer3ms2788 KiB
8Wrong answer3ms2832 KiB
9Wrong answer3ms3048 KiB
subtask40/27
10Wrong answer19ms4736 KiB
subtask50/52
11Wrong answer8ms4592 KiB
12Wrong answer26ms5896 KiB
13Accepted25ms7416 KiB
14Wrong answer25ms8596 KiB
15Wrong answer17ms9048 KiB
16Wrong answer27ms10752 KiB
17Accepted17ms11632 KiB
18Wrong answer17ms11956 KiB
19Accepted17ms12908 KiB
20Accepted25ms13940 KiB
21Wrong answer3ms13736 KiB
22Wrong answer3ms13616 KiB
23Wrong answer3ms13616 KiB
24Wrong answer3ms13620 KiB
25Wrong answer3ms13620 KiB
26Wrong answer2ms13624 KiB