#P35. [KBC002C] Sequence 3

[KBC002C] Sequence 3

Source

This problem is moved from Long Long OJ (Copyright by Google Inc.). All rights reserved.

Adapted from: https://luogu.com.cn/problem/P13026

Attention

is the hard version of this problem.

Problem Description

Given a sequence aa of nn integers, you need to add digits at the end of the integers in order to make the sequence strictly increasing.

Adding digit t (0t9)t\ (0\le t\le 9) at the end of a number xx can be represented as xx×10+tx\leftarrow x\times10+t.

Find the minimum number of digits to be added.

Input Format

The first line consists of an integer nn.

The following nn lines consists of nn integers a1,a2,,ana_1,a_2,\ldots,a_n.

Output Format

Output the minimum number of digits to be added.

Samples

4
20
1
45
132
4

Sample Explanation

After adding digits, the sequence becomes a=[20,199,459,1329]a=[20,199,459,1329].

Note that this is not the only possible solution.

Data Range

For 70%70\% of the test cases:

  • 1n1031 \le n \le 10^3.
  • 1ai1091 \le a_i \le 10^9.

For the remaining 30%30\% of the test cases:

  • 1n1051 \le n \le 10^5.
  • All the numbers in a\bm a are equal.
  • 1ai1091 \le a_i \le 10^9.