A and B and Interesting Substrings

CodeForces - 519D