Under construction

Still being built. Things may change

Six-Digit Documents

Interview

Time limit2sMemory limit1024 MB

Summary
Given n six-digit identifiers, find the cyclic shift that minimizes the total number of inversions summed over all six digit positions.
Level

Medium5 of 10

Topics
Array, Prefix sum, Implementation
Solved
No attempts yet

Statement

Valery, an accountant, is checking inconsistencies in accounting reports. He has to check exactly nn documents. The ii-th document is available on the corporate network by its six-digit integer identifier a_ia\_i.

An inversion in the kk-th digit is a pair of indices ii and jj such that i<ji < j and the kk-th digit of a_ia\_i is strictly greater than the kk-th digit of a_ja\_j. The complexity of an array of six-digit numbers {a_i}\{a\_i\} is the total number of inversions across all six digit positions.

Valery knows that the lower the complexity of the identifiers, the less time he spends typing them into the address bar. The set of documents is fixed, and reordering them freely is risky because he might skip some documents by mistake. The only change he is allowed to make is to shift the order cyclically by several positions. A cyclic shift of the array a_1,a_2,…,a_na\_1, a\_2, \ldots, a\_n by tt positions to the left is the array a_t+1,a_t+2,…,a_n,a_1,a_2,…,a_ta\_{t+1}, a\_{t+2}, \ldots, a\_n, a\_1, a\_2, \ldots, a\_t.

Help Valery choose the cyclic shift of the original array with the minimum complexity.

Input

The first line contains an integer nn, the number of documents to check (1⩽n⩽100 0001 \leqslant n \leqslant 100\,000). Each of the next nn lines contains six digits, the identifier a_ia\_i. All a_ia\_i are distinct. Identifiers may start with zero.

Output

Print a single integer: the minimum complexity over all cyclic shifts of the array of identifiers.

Hint

In the first sample, it pays to shift one position to the left, so the number 177013 comes first. Then each of the first four digit positions has one inversion, and the last two have none.

In the second sample, the order is already optimal with three inversions: one each in the first, fourth, and sixth digit positions.

Examples2

  1. Example 1

    Input
    3
    277659
    177013
    314836
    
    Expected output
    4
    
  2. Example 2

    Input
    3
    250401
    185217
    296632
    
    Expected output
    3