Kitchen Knobs

Given n seven-digit knobs, find the fewest range rotations (each turning a contiguous block by the same amount) so every knob reads its maximum-power digit.

Hard8GreedyImplementationDynamic programmingArrayNo attempts yetTime limit3sMemory limit512 MB

Problem

You are cooking on a gigantic stove in a large fast food restaurant. The stove has nn heating elements in a row, numbered 11 through nn from left to right. Each element is operated by its own control knob. The knobs are a bit unusual: seven non-zero digits are written at equal spacing around each knob, and the power of the element is the integer you get by reading those digits clockwise, starting at the top of the knob.

The picture shows the starting positions of the knobs in the first sample input.

In a single step you can rotate one or more consecutive knobs by any number of positions in either direction. All knobs rotated in one step move by the same number of positions in the same direction.

Find the smallest number of steps needed to set every heating element to its maximum possible power.

Input

The first line contains the number of heating elements nn (1n5011 \le n \le 501).

The jj-th of the next nn lines contains the initial power xjx_j of the jj-th heating element. Each xjx_j consists of exactly seven non-zero digits.

Output

Print the minimal number of steps on one line.

Hint

In the first sample, one way to reach the maximum power is to rotate knobs 22 through 33 by three positions counterclockwise, rotate knob 33 by three positions counterclockwise, then rotate knobs 44 through 66 by two positions clockwise.