CodeForces – Problem 798B – Mike and strings

Solving problems in CodeForces usually never works out as expected somehow – if I tend to overestimate the problem, I am able to solve it within 10 minutes and if I underestimate it, I stay about 1 hour on a simple one.

Something similar happened today as well – I have taken a look at the second problem of round 410.
cs

The problem looked a bit trivial:

Mike has n strings s1, s2, …, sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string “coolmike“, in one move he can transform it into the string “oolmikec“.

Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?

Input

The first line contains integer n (1 ≤ n ≤ 50) — the number of strings.

This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don’t exceed 50.

Output

Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.

From the very beginning I was quite sure what to do – simply to compare the strings in 3 nested loops and then to take the lowest score or -1 if it appears. However, it was not that easy, due to two things – first – I was ashamed to forget, that strings are given by reference and I lost some 15 minutes on that looking for my mistakes. The second error was where I lost most of the time. In my code I am using a function named GetMoveables, where I calculate the number of movements needed for String A to become String B, if possible. However, I have somehow not paid attention to the way the parameters were called. Thus, I was calling intRes = GetMoveables(liStr[i], liStr[k]); which was giving me wrong result in only one of the sample tests. I did not find the problem easily and I thought that I had made some kind of an error in the string comparison. However, after lots of printing on the console, I have managed to find it and the code passed all the tests from the first submission.

Here comes the code:

Quite ok.

About

VBA Developer

Tagged with: ,