Six-Digit Documents
InterviewTime limit2sMemory limit1024 MB
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 documents. The -th document is available on the corporate network by its six-digit integer identifier .
An inversion in the -th digit is a pair of indices and such that and the -th digit of is strictly greater than the -th digit of . The complexity of an array of six-digit numbers 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 by positions to the left is the array .
Help Valery choose the cyclic shift of the original array with the minimum complexity.
Input
The first line contains an integer , the number of documents to check (). Each of the next lines contains six digits, the identifier . All 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.