#P4749. Maximal Heating Power

    ID: 17993 Type: Default 1000ms 256MiB

Maximal Heating Power

Maximal Heating Power

You are cooking on a gigantic stove at a large fast‐food restaurant. The stove contains n heating elements arranged in a line and numbered from 1 to n (left to right). Each element is operated by its control knob. The knobs are a bit unusual: each knob is marked with seven nonzero digits evenly distributed around a circle. The power of a heating element is equal to the positive integer obtained by reading the digits on its control knob clockwise starting from the top.

In a single step, you can rotate one or more consecutive knobs by any number of positions in the same direction. However, all knobs rotated in one step must be rotated by the same number of positions in that step.

For each knob, you may rotate it by a certain number of positions so that the new configuration displays the maximal possible integer (when compared in the usual way). Note that because the digits are arranged in a circle, each knob has seven possible readings. In particular, if s is the 7-digit string currently showing (with s[0] at the top), then a clockwise rotation by r (with 0 ≤ r ≤ 6) changes its reading to \[ s[(-r)\bmod 7] s[(-r+1)\bmod 7] \cdots s[(-r+6)\bmod 7] \] which is interpreted as a positive integer. You are allowed, for each knob, to choose any rotation that yields the maximal possible reading. Your task is to determine the smallest number of rotation steps required to set all heating elements to their maximal power.

Note: You may choose different maximal rotations for different knobs if there are several rotations that yield the same maximum integer, with the goal of minimizing the total number of steps.

inputFormat

The first line contains an integer n (1 ≤ n ≤ 105), the number of heating elements. Each of the next n lines contains a string of 7 digits (each digit is between 1 and 9) representing the digits on the corresponding knob in clockwise order, with the first character being the digit currently at the top.

outputFormat

Output a single integer—the minimal number of steps required to set all heating elements to show their maximal possible power.

sample

3
1234567
1234567
1234567
1

</p>