Official

A - Dial Up Editorial by evima


Let us count the number of times we shift \(a\). It is obviously \(0\) if \(T\) consists of \(S_1\) only.

Assume otherwise. If \(S\) does not have a character that is not \(S_1\), the answer is \(-1\).

Assume \(S\) has such a character, and let \(x\) and \(y\) be its leftmost and rightmost positions, respectively. When such a character occurs in \(T\) for the first time, we need to shift \(a\) to bring the \(x\)-th or \(y\)-th character to the beginning.

What will we do if a character equal to \(S_1\) occurs later in \(T\)? It turns out we just need to shift \(a\) once to bring a character equal to \(S_1\) to the beginning, because of how \(x\) and \(y\) were chosen.

By reusing this argument, from then on, each time we need a character different from the last, we can shift \(a\) once to bring such a character to the beginning of \(a\), which is obviously the fewest number of moves possible. Therefore, the only choice we need to make is to use the \(x\)-th character or the \(y\)-th one. The fewer number of moves used in these two scenarios is the answer.

The time complexity of this solution is \(O(N+M)\).

posted:
last update: