A - Yet Another AB Problem 解説 by evima
To minimize the number of operations, we want to perform more operations on characters where \(S_i \neq T_i\).
Let’s take out only the characters where \(S_i \neq T_i\) from \(T\) from left to right, and create a string \(U\) by replacing \(T_i\) with (
if it’s A
, and with )
if it’s B
.
For example, if \(S\) is BAABA
and \(T\) is AABBB
, then \(U\) will be ())
.
Now, if \(U\) is a valid sequence of parentheses, then the answer will be half of \(|U|\). We just need to perform operations that correspond to the matching pairs in the parentheses sequence.
Otherwise, we need to determine the minimum number of (
to insert at the leftmost position where \(T_i\) is A
, and the minimum number of )
to insert at the rightmost position where \(T_i\) is B
, in order to make it a valid sequence of parentheses. (There are cases where it is not possible to make it a valid sequence of parentheses depending on the leftmost position where \(T_i\) is A
or the rightmost position where \(T_i\) is B
, and in those cases, the answer is \(-1\).)
The minimum number of insertions needed can be determined greedily by inserting as many (
as needed at the beginning and then as many )
as needed at the end.
投稿日時:
最終更新: