Official

D - Take ABC Editorial by en_translator


You can get accepted by simply simulating the operation described in the problem statement, but a naive implementation would cost \(\Theta(N^2)\) time, which may lead to a “execution time limit exceeded” (TLE) verdict, so careful implementation is required.

For example, a data structure that stores the string \(S\) may require a large cost to remove a character from the string, as it may shift the characters toward the front to fill the gap. (For example, if you remove from \(S = S_1S_2S_3S_4S_5\) the second character \(S_2\), the character that used to be \(S_3\) should now become \(S_2\), \(S_4\) become \(S_3\), and \(S_5\) become \(S_4\).) This operation requires at worst \(\Theta(N)\) time (when removing the first character of \(S\)). If you repeat it, the overall simulation may cost \(\Theta(N^2)\) time for some input strings.

Instead, we can use a stack to simulate the operation by the following procedure, so that the problem is solved in a total of \(O(N)\) time.

Prepare an empty stack. For each character \(S\) from its initial one in order, push it to the top of the stack. In the process, every time the characters at the top of the stack form ABC (i.e. if the topmost character (the character pushed the last time) is C, the second topmost one is B, and the third is A), pop the three characters ABC from the stack.)

The following is sample code of this problem in C++ language.

#include <iostream>
using namespace std;

int main(void)
{
  string s, ans;
  cin >> s;
  
  for(auto c : s){
    ans += c;
    if(ans.size() >= 3 && ans.substr(ans.size()-3) == "ABC") ans.erase(ans.end()-3, ans.end());
  }
  cout << ans << endl;
  
  return 0;
}

posted:
last update: