Problem solution · C++

ABC120 C — Unification

ABC120 C — Unification: a C++ solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to michimani AtCoder Solutions.

Technique
Stack-based processing
Source
michimani AtCoder Solutions
Length
37 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Stack-based processing

For ABC120 C — Unification, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 37 lines of C++ from the credited upstream file abc120_c.cpp.
  • The implementation keeps its working state in language-native values and containers.
  • 1 loop block detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from michimani AtCoder Solutions by michimani and is used under the MIT licence.

Full codeABC120 C — Unification · C++C++
Use this to learn the idea, then write your own version.
#include <iostream>#include <stack> using namespace std; int main() {    string s;    cin >> s;     unsigned long n = s.length();    unsigned long cur = 1;    unsigned int ans = 0;    stack<unsigned long> prev_stack;    prev_stack.push(0);     while (cur < n) {        unsigned long prev = prev_stack.top();        prev_stack.pop();         if (s[cur] != s[prev]) {            ans += 2;            cur++;             if (prev_stack.empty()) {                cur++;                prev_stack.push(cur - 1);            }            continue;        }         cur++;        prev_stack.push(prev);        prev_stack.push(cur - 1);    }     cout << ans << endl;}

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗