Problem:
Score: 500 points

Problem Statement

N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.

The preliminary stage consists of several rounds, which will take place as follows:

All the N contestants will participate in the first round.

When X contestants participate in some round, the number of contestants advancing to the next round will be decided as follows:

The organizer will choose two consecutive digits in the decimal notation of X, and replace them with the sum of these digits. The number resulted will be the number of contestants advancing to the next round.

For example, when X = 2378, the number of contestants advancing to the next round will be 578 (if 2 and 3 are chosen), 2108 (if 3 and 7 are chosen), or 2315 (if 7 and 8 are chosen).

When X = 100, the number of contestants advancing to the next round will be 10, no matter which two digits are chosen.

The preliminary stage ends when 9 or fewer contestants remain.

Ringo, the chief organizer, wants to hold as many rounds as possible.
Find the maximum possible number of rounds in the preliminary stage.

Since the number of contestants, N, can be enormous, it is given to you as two integer sequences d_1, \ldots, d_M and c_1, \ldots, c_M, which means the following: the decimal notation of N consists of c_1 + c_2 + \ldots + c_M digits, whose first c_1 digits are all d_1, the following c_2 digits are all d_2, \ldots, and the last c_M digits are all d_M.

Constraints

1 \leq M \leq 200000

0 \leq d_i \leq 9

d_1 \neq 0

d_i \neq d_{i+1}

c_i \geq 1

2 \leq c_1 + \ldots + c_M \leq 10^{15}

Input

Input is given from Standard Input in the following format:

M
d_1 c_1
d_2 c_2
:
d_M c_M

Output

Print the maximum possible number of rounds in the preliminary stage.

Sample Input 1

2
2 2
9 1

Sample Output 1

3

In this case, N = 229 contestants will participate in the first round. One possible progression of the preliminary stage is as follows:

229 contestants participate in Round 1, 49 contestants participate in Round 2, 13 contestants participate in Round 3, and 4 contestants advance to the finals.

Here, three rounds take place in the preliminary stage, which is the maximum possible number.

Sample Input 2

3
1 1
0 8
7 1

Sample Output 2

9

In this case, 1000000007 will participate in the first round.

Solution in Rust (1.15.1) (judge verdict: Accepted)

// SNIPPET read
pub trait Readable {
    type Output;
    fn words_count() -> usize;
    fn read_words(words: &[&str]) -> Result<Self::Output, String>;
}
#[macro_export]
macro_rules! readable {
    ( $t:ty, $words_count:expr, |$words:ident| $read_words:expr ) => {
        impl Readable for $t {
            type Output = $t;
            fn words_count() -> usize { $words_count }
            fn read_words($words: &[&str]) -> Result<$t, String> {
                Ok($read_words)
            }
        }
    };
}
readable!((), 1, |_ss| ());
readable!(String, 1, |ss| ss[0].to_string());
impl Readable for char {
    type Output = char;
    fn words_count() -> usize { 1 }
    fn read_words(words: &[&str]) -> Result<char, String> {
        let chars: Vec<char> = words[0].chars().collect();
        if chars.len() == 1 {
            Ok(chars[0])
        } else {
            Err(format!("cannot parse `{}` as a char", words[0]))
        }
    }
}
pub struct Chars();
impl Readable for Chars {
    type Output = Vec<char>;
    fn words_count() -> usize { 1 }
    fn read_words(words: &[&str]) -> Result<Vec<char>, String> {
        Ok(words[0].chars().collect())
    }
}
macro_rules! impl_readable_for_ints {
    ( $( $t:ty )* ) => { $(
        impl Readable for $t {
            type Output = Self;
            fn words_count() -> usize { 1 }
            fn read_words(words: &[&str]) -> Result<$t, String> {
                use std::str::FromStr;
                <$t>::from_str(words[0]).map_err(|_| {
                    format!("cannot parse `{}` as {}", words[0], stringify!($t))
                })
            }
        }
    )* };
}
impl_readable_for_ints!(i8 u8 i16 u16 i32 u32 i64 u64 isize usize f32 f64);
macro_rules! define_one_origin_int_types {
    ( $new_t:ident $int_t:ty ) => {
        #[allow(non_camel_case_types)]
        pub struct $new_t;
        impl Readable for $new_t {
            type Output = $int_t;
            fn words_count() -> usize { 1 }
            fn read_words(words: &[&str]) -> Result<Self::Output, String> {
                <$int_t>::read_words(words).map(|n| n-1)
            }
        }
    };
    ( $new_t:ident $int_t:ty; $( $inner_new_t:ident $inner_int_t:ty );* ) => {
        define_one_origin_int_types!($new_t $int_t);
        define_one_origin_int_types!($($inner_new_t $inner_int_t);*);
    };
}
define_one_origin_int_types!(u8_ u8; u16_ u16; u32_ u32; u64_ u64; usize_ usize);
macro_rules! impl_readable_for_tuples {
    ( $t:ident $var:ident ) => ();
    ( $t:ident $var:ident; $( $inner_t:ident $inner_var:ident );* ) => {
        impl_readable_for_tuples!($($inner_t $inner_var);*);
        impl<$t: Readable, $($inner_t: Readable),*> Readable
            for ($t, $($inner_t),*)
        {
            type Output = ( <$t>::Output, $(<$inner_t>::Output),* );
            fn words_count() -> usize {
                let mut n = <$t>::words_count();
                $(
                    n += <$inner_t>::words_count();
                )*
                n
            }
            #[allow(unused_assignments)]
            fn read_words(words: &[&str]) ->
                Result<Self::Output, String>
            {
                let mut start = 0;
                let $var = <$t>::read_words(
                    &words[start .. start+<$t>::words_count()]
                )?;
                start += <$t>::words_count();
                $(
                    let $inner_var =
                        <$inner_t>::read_words(
                            &words[start .. start+<$inner_t>::words_count()]
                        )?;
                    start += <$inner_t>::words_count();
                )*
                Ok(( $var, $($inner_var),* ))
            }
        }
    };
}
impl_readable_for_tuples!(T8 x8; T7 x7; T6 x6; T5 x5; T4 x4; T3 x3; T2 x2; T1 x1);
pub trait ReadableFromLine {
    type Output;
    fn read_line(line: &str) -> Result<Self::Output, String>;
}
fn split_into_words(line: &str) -> Vec<&str> {
    #[allow(deprecated)]
    line.trim_right_matches('\n').split_whitespace().collect()
}
impl<T: Readable> ReadableFromLine for T {
    type Output = T::Output;
    fn read_line(line: &str) -> Result<T::Output, String> {
        let words = split_into_words(line);
        if words.len() != T::words_count() {
            return Err(format!("line `{}` has {} words, expected {}",
                               line, words.len(), T::words_count()));
        }
        T::read_words(&words)
    }
}
macro_rules! impl_readable_from_line_for_tuples_with_from_iterator {
    ( $u:ident : $( + $bound:path )* => $seq_in:ty, $seq_out:ty; $t:ident $var:ident ) => {
        impl<$u: Readable> ReadableFromLine for $seq_in
        where
            <$u as Readable>::Output: Sized $(+ $bound)*
        {
            type Output = $seq_out;
            fn read_line(line: &str) -> Result<$seq_out, String> {
                let n = $u::words_count();
                let words = split_into_words(line);
                if words.len() % n != 0 {
                    return Err(format!("line `{}` has {} words, expected multiple of {}",
                                       line, words.len(), n));
                }
                let mut result = Vec::new();
                for chunk in words.chunks(n) {
                    match $u::read_words(chunk) {
                        Ok(v) => result.push(v),
                        Err(msg) => {
                            let flagment_msg = if n == 1 {
                                format!("word {}", result.len())
                            } else {
                                let l = result.len();
                                format!("words {}-{}", n*l + 1, (n+1) * l)
                            };
                            return Err(format!(
                                "{} of line `{}`: {}", flagment_msg, line, msg
                            ));
                        }
                    }
                }
                Ok(result.into_iter().collect())
            }
        }
        impl<T: Readable, $u: Readable> ReadableFromLine for (T, $seq_in)
        where
            <$u as Readable>::Output: Sized $(+ $bound)*
        {
            type Output = (T::Output, $seq_out);
            fn read_line(line: &str) -> Result<Self::Output, String> {
                let n = T::words_count();
                #[allow(deprecated)]
                let trimmed = line.trim_right_matches('\n');
                let words_and_rest: Vec<&str> = trimmed.splitn(n + 1, ' ').collect();
                if words_and_rest.len() < n {
                    return Err(format!("line `{}` has {} words, expected at least {}",
                                       line, words_and_rest.len(), n));
                }
                let words = &words_and_rest[..n];
                let empty_str = "";
                let rest = words_and_rest.get(n).unwrap_or(&empty_str);
                Ok((T::read_words(words)?, <$seq_in>::read_line(rest)?))
            }
        }
    };
    ( $u:ident : $( + $bound:path )* => $seq_in:ty, $seq_out:ty;
      $t:ident $var:ident, $( $inner_t:ident $inner_var:ident ),+ ) => {
        impl_readable_from_line_for_tuples_with_from_iterator!(
            $u: $(+ $bound)* => $seq_in, $seq_out; $($inner_t $inner_var),+
        );
        impl<$t: Readable, $($inner_t: Readable),+ , $u: Readable> ReadableFromLine
            for ($t, $($inner_t),+ , $seq_in)
        where
            <$u as Readable>::Output: Sized $(+ $bound)*
        {
            type Output = ($t::Output, $($inner_t::Output),+ , $seq_out);
            fn read_line(line: &str) -> Result<Self::Output, String> {
                let mut n = $t::words_count();
                $(
                    n += $inner_t::words_count();
                )+
                #[allow(deprecated)]
                let trimmed = line.trim_right_matches('\n');
                let words_and_rest: Vec<&str> = trimmed.splitn(n + 1, ' ')
                    .collect();
                if words_and_rest.len() < n {
                    return Err(
                        format!("line `{}` has {} words, expected at least {}",
                                line, words_and_rest.len(), n)
                    );
                }
                let words = &words_and_rest[..n];
                let empty_str = "";
                let rest = words_and_rest.get(n).unwrap_or(&empty_str);
                let ($var, $($inner_var),*) =
                    <($t, $($inner_t),+)>::read_words(words)?;
                Ok(($var, $($inner_var),* , <$seq_in>::read_line(rest)?))
            }
        }
    };
}
#[macro_export]
macro_rules! readable_collection {
    ($u:ident => $collection_in:ty, $collection_out:ty) => {
        impl_readable_from_line_for_tuples_with_from_iterator!(
            $u: => $collection_in, $collection_out;
            T8 x8, T7 x7, T6 x6, T5 x5, T4 x4, T3 x3, T2 x2, T1 x1
        );
    };
    ($u:ident : $( $bound:path ),* => $collection_in:ty, $collection_out:ty) => {
        impl_readable_from_line_for_tuples_with_from_iterator!(
            $u: $(+ $bound)* => $collection_in, $collection_out;
            T8 x8, T7 x7, T6 x6, T5 x5, T4 x4, T3 x3, T2 x2, T1 x1
        );
    }
}
readable_collection!(U => Vec<U>, Vec<U::Output>);
readable_collection!(
    U => std::collections::VecDeque<U>, std::collections::VecDeque<U::Output>
);
readable_collection!(
    U: Eq, std::hash::Hash => std::collections::HashSet<U>, std::collections::HashSet<U::Output>
);
readable_collection!(
    U: Ord => std::collections::BTreeSet<U>, std::collections::BTreeSet<U::Output>
);
readable_collection!(
    U: Ord => std::collections::BinaryHeap<U>, std::collections::BinaryHeap<U::Output>
);
pub fn read<T: ReadableFromLine>() -> T::Output {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    T::read_line(&line).unwrap()
}
#[macro_export]
macro_rules! read {
    () => {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
    };
    ( $pat:pat = $t:ty ) => {
        let $pat = read::<$t>();
    };
    ( $( $pat:pat = $t:ty ),+ ) => {
        read!(($($pat),*) = ($($t),*));
    };
}
#[macro_export]
macro_rules! readls {
    ( $( $pat:pat = $t:ty ),+ ) => {
        $(
            read!($pat = $t);
        )*
    };
}
pub fn readx<T: ReadableFromLine>() -> Vec<T::Output> {
    use std::io::{self, BufRead};
    let stdin = io::stdin();
    let result = stdin.lock().lines().map(|line_result| {
        let line = line_result.expect("read from stdin failed");
        T::read_line(&line).unwrap()
    }).collect();
    result
}
#[macro_export]
macro_rules! readx_loop {
    ( |$pat:pat = $t:ty| $body:expr ) => {
        {
            use std::io::BufRead;
            let stdin = std::io::stdin();
            for line in stdin.lock().lines() {
                let line = line.expect("read from stdin failed");
                let $pat = <$t>::read_line(&line).unwrap();
                $body
            }
        }
    };
    ( |$($pat:pat = $t:ty),*| $body:expr ) => {
        readx_loop!(|($($pat),*) = ($($t),*)| $body);
    };
}
pub fn readn<T: ReadableFromLine>(n: usize) -> Vec<T::Output> {
    use std::io::{self, BufRead};
    let stdin = io::stdin();
    let result: Vec<T::Output> = stdin.lock().lines().take(n).map(|line_result| {
        let line = line_result.expect("read from stdin failed");
        T::read_line(&line).unwrap()
    }).collect();
    if result.len() < n {
        panic!("expected reading {} lines, but only {} lines are read",
               n, result.len());
    }
    result
}
#[macro_export]
macro_rules! readn_loop {
    ( $n:expr, |$pat:pat = $t:ty| $body:expr ) => {
        {
            use std::io::BufRead;
            let stdin = std::io::stdin();
            let mut lock = stdin.lock();
            for _ in 0..$n {
                let mut line = String::new();
                lock.read_line(&mut line).expect("read from stdin failed");
                let $pat = <$t>::read_line(&line).unwrap();
                $body
            }
        }
    };
    ( $n:expr, |$($pat:pat = $t:ty),*| $body:expr ) => {
        readn_loop!($n, |($($pat),*) = ($($t),*)| $body);
    };
}
pub trait Words {
    fn read<T: Readable>(&self) -> T::Output;
}
impl<'a> Words for [&'a str] {
    fn read<T: Readable>(&self) -> T::Output {
        T::read_words(self).unwrap()
    }
}
impl<'a> Words for &'a str {
    fn read<T: Readable>(&self) -> T::Output {
        T::read_words(&[self]).unwrap()
    }
}

// SNIPPET dbg
#[macro_export]
#[cfg(local)]
macro_rules! dbg {
    () => {
        {
            use std::io::{self, Write};
            writeln!(io::stderr(), "{}: dbg", line!()).unwrap();
        }
    };
    ($e: expr) => {
        {
            use std::io::{self, Write};
            let result = $e;
            writeln!(io::stderr(), "{}: {} = {:?}",
                     line!(), stringify!($e), result)
                .unwrap();
            result
        }
    }
}
#[macro_export]
#[cfg(not(local))]
macro_rules! dbg {
    () => {};
    ($e: expr) => { $e }
}

// END SNIPPETS

fn collapse2(d1: u8, d2: u8) -> (u8, u64) {
    let s = d1 + d2;
    if s < 10 {
        (s, 1)
    } else {
        let (d, n) = collapse2(s/10, s%10);
        (d, 1+n)
    }
}

fn collapse(mut ds: Vec<u8>) -> (u8, u64) {
    if ds.len() == 1 {
        return (ds[0], 0);
    }

    let d1 = ds.pop().unwrap();
    let d2 = ds.pop().unwrap();
    let (next, n1) = collapse2(d1, d2);
    ds.push(next);
    let (d, n2) = collapse(ds);
    (d, n1+n2)
}

#[test]
fn test_col() {
    assert_eq!(collapse(vec![2, 3, 7, 8]), (2, 5));
}

fn collapse_rep(d: u8, n: u64) -> (u8, u64) {
    if n == 1 {
        return (d, 0);
    }

    let (d_sub, n_sub) = collapse_rep(d, n/2);
    let (d1, rem1) = collapse2(d_sub, d_sub);
    if n % 2 == 0 {
        (d1, n_sub * 2 + rem1)
    } else {
        let (d2, rem2) = collapse2(d1, d);
        (d2, n_sub * 2 + rem1 + rem2)
    }
}

fn main() {
    read!();
    let digits = readx::<(u8, u64)>();
    let mut ds = Vec::new();
    let mut ans = 0u64;
    for (d, n) in digits {
        let (d, n) = collapse_rep(d, n);
        ds.push(d);
        ans += n;
    }
    let (_, n) = collapse(ds);
    println!("{}", ans + n);
}