Official

C - Insert and Erase A Editorial by en_translator


Since each operation either inserts or deletes an A to/from \(S\), we want to consider consecutive As and the letters other than A. To this end, let us define a string \(S'\) and a sequence \(A_S\) as follows:

  • \(S'\): the string obtained by extracting all characters in \(S\) that are not A, and concatenating them in their original order.
  • \(A_S\): the sequence obtained by splitting \(S\) at the positions where the letters other than A occur, and enumerating the number of As contained in each block. More formally, when \(S'\) has a length \(n\), the sequence \(A_S\) has a length \((n + 1)\), whose \(i\)-th element \(A_S(i)\) is defined as follows:
    • If \(i= 1\): the number of occurrences of A before the first occurrence of a letter other than A in \(S\).
    • If \(2 \leq i \leq n\): the number of occurrences of A between the \((i-1)\)-th and \(i\)-th occurrences of letters other than A in \(S\).
    • If \(i= n+1\): the number of occurrences of A after the last occurrence of a letter other than A in \(S\).
    • If \(S'\) is empty, define \(A_S(1)=|S|\).

For example, if \(S=\) ABAAACAA, then \(S'=\) BC and \(A_S=(1,3,2)\).

For the string \(T\), we also define \(T'\) and \(A_T\) likewise.

Now let us observe how \(S'\) and \(A_S\) are affected by the operations. We notice the following facts:

  • The operation does not change \(S'\).
  • Performing the former operation increments \(A_S(i)\) by one for some \(i\).
  • Performing the latter operation decrements \(A_S(i)\) by one for some \(i\).

Conversely, one can increment or decrement \(A_S(i)\) for any \(i\) in one operation (while keeping \(S'\) the same).

Hence, the answer to the problem is as follows:

  • If \(S'\neq T'\), then \(S\) cannot be made equal to \(T\).
  • If \(S'= T'\), then the answer is the sum of \(|A_S(i) - A_T(i)|\) over all \(i\ (1\leq i\leq |S'|+1)\).

Sample code (C++):

#include <bits/stdc++.h>

using namespace std;

pair<string, vector<int>> decompose(const string &s) {
    string t;
    vector<int> v;
    int cnt = 0;
    for (char c: s) {
        if (c == 'A') {
            ++cnt;
        } else {
            t += c;
            v.push_back(cnt);
            cnt = 0;
        }
    }
    v.push_back(cnt);
    return {t, v};
}

int main() {
    string s, t;
    cin >> s >> t;
    auto [ss, sv] = decompose(s);
    auto [ts, tv] = decompose(t);
    if (ss != ts) {
        cout << -1 << endl;
        return 0;
    }
    int ans = 0;
    for (int i = 0; i < (int) sv.size(); i++) {
        ans += abs(sv[i] - tv[i]);
    }
    cout << ans << endl;
}

posted:
last update: