1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
#include <iostream>

using namespace std;

int compare(const string &a, const string &b) {
    if (a.size() > b.size()) {
        return 1;
    }
    if (a.size() < b.size()) {
        return -1;
    }
    for (int i = 0; i < a.size(); i++) {
        if (a[i] != b[i]) {
            return a[i] - b[i];
        }
    }
    return 0;
}

int compareToFirstDiff(const string &bigger, const string &smaller) {
    for (int i = 0; i < smaller.size(); i++) {
        int result = bigger[i] - smaller[i];
        if (result != 0) {
            return result;
        }
    }
    return 0;
}

void increment(string &source, uint from) {
    const uint lastIdx = source.size() - 1;
    if (source[lastIdx] != '9') {
        source[lastIdx] = source[lastIdx] + 1;
        return;
    }

    int idx = lastIdx;
    while (idx > from && source[idx] == '9') {
        idx -= 1;
    }

    if (idx == from && source[idx] == '9') {
        source.replace(idx, source.size() - idx, source.size() - idx, '0');
        source += '0';
        return;
    }

    source[idx] = source[idx] + 1;
    idx += 1;
    source.replace(idx, source.size() - idx, source.size() - idx, '0');
}

uint step(string &current, const string &next) {
    int comparison = compare(current, next);
    if (comparison < 0) {
        current.assign(next);
        return 0;
    }
    if (comparison == 0) {
        current += '0';
        return 1;
    }

    int prefixesComparison = compareToFirstDiff(current, next);

    if (prefixesComparison == 0) {
        increment(current, next.size());
    } else {
        current.replace(0, next.size(), next);
        current.replace(next.size(), current.size() - next.size(), current.size() - next.size(), '0');
        if (prefixesComparison > 0) {
            current += '0';
        }
    }
    return current.size() - next.size();
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int size;
    cin >> size;
    string current;
    current.reserve(200001);
    cin >> current;
    unsigned long long counter = 0;
    string next;

    for (int i = 1; i < size; i++) {
        cin >> next;
        counter += step(current, next);

    }

    cout << counter << endl;

    return 0;
}