// https://codeforces.com/contest/1293/problem/D
//
#![allow(unused_imports)]
use std::io::*;
use std::io::Write;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

// Input macros.
// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };

    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, [ next / $t:tt ]) => {
        {
            let len = read_value!($iter, usize);
            (0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
        }
    };

    ($iter:expr, switch) => {
        {
            let ty = read_value!($iter, i32);
            if ty == 1 {
                vec![ty, read_value!($iter, i32), read_value!($iter, i32)]
            } else if ty == 2 {
                vec![ty, read_value!($iter, i32)]
            } else {
                vec![ty, read_value!($iter, i32)]
            }
        }
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! read_line {
    ($t:tt) => {
        {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s.trim_right().parse::<$t>().unwrap()
        }
    }
}

#[allow(unused_macros)]
macro_rules! dvec {
    ($t:expr ; $len:expr) => {
        vec![$t; $len]
    };

    ($t:expr ; $len:expr, $($rest:expr),*) => {
        vec![dvec!($t; $($rest),*); $len]
    };
}

#[allow(unused_macros)]
macro_rules! ifv {
    ($t:expr, $a:expr, $b: expr) => {
        if $t { $a } else { $b }
    }
}

#[allow(unused_macros)]
macro_rules! fill {
    ($t:expr, $v:expr) => {
        for i in 0..$t.len() {
            $t[i] = $v;
        }
    };
}

#[allow(unused_macros)]
macro_rules! join {
    ($t:expr, $glue:expr) => {
        $t.into_iter().map(|w| w.to_string()).collect::<Vec<_>>().join($glue)
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

// ===

const MAX_CORD: i128 = 1e18 as i128;

fn solve(mut limit: i128, start: usize, p1: usize, p2: usize, p3: usize, cost: &Vec<Vec<i128>>) -> i32 {
    if limit < 0 {
        return -10000;
    }
    let mut count = 1;
    let mut now = start;
    while now != p1 {
        let t = ifv!(now < p1, now+1, now-1);
        if limit < cost[now][t] {
            return count;
        }
        count += 1;
        limit -= cost[now][t];
        now = t;
    }
    assert_eq!(now, p1);
    assert_ne!(now, p2);
    if limit < cost[now][p2] {
        return count;
    }
    limit -= cost[now][p2];
    count += 1;
    now = p2;

    while now != p3 {
        let t = ifv!(now < p3, now+1, now-1);
        if limit < cost[now][t] {
            return count;
        }
        count += 1;
        limit -= cost[now][t];
        now = t;
    }
    count
}

fn main() {
    input! {
        x0: i128, y0: i128, ax: i128, ay: i128, bx: i128, by: i128,
        sx: i128, sy: i128, limit: i128
    };

    let mut points = vec![(x0, y0)];
    loop {
        let (lx, ly) = *points.last().unwrap();
        if lx > MAX_CORD || ly > MAX_CORD {
            break;
        }
        points.push((lx*ax+bx, ly*ay+by));
    }
    let n = points.len();

    let mut first_cost = vec![];
    for i in 0..n {
        first_cost.push((sx-points[i].0).abs() + (sy-points[i].1).abs());
    }
    let mut pp_cost = dvec!(0; n, n);
    for i in 0..n {
        for j in 0..n {
            pp_cost[i][j] = (points[i].0-points[j].0).abs() + (points[i].1-points[j].1).abs();
        }
    }

    // debug!(points);
    // debug!(first_cost);

    assert!(n >= 2);

    let mut best = 0;
    for s in 0..n {
        if s < n-1 {
            for l in 0..=s {
                best = max(best, solve(limit - first_cost[s], s, l, s+1, n-1, &pp_cost));
            }
        }
        if s >= 1 {
            for l in s..n {
                best = max(best, solve(limit - first_cost[s], s, l, s-1, 0, &pp_cost));
            }
        }
    }

    println!("{}", best);
}


#![allow(unknown_lints)]
#![allow(unused_imports, unused_macros, non_snake_case, bare_trait_objects)]
#![allow(renamed_and_removed_lints, redundant_field_names)]
use std::cmp::Ordering::{self, Greater, Less};
use std::cmp::{max, min};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::error::Error;
use std::io::{self, BufReader, BufWriter, Read, Write};
use text_scanner::{scan, scan_iter, scanln, scanln_iter};
use utils::adj4_iter;

fn cost((x0, y0): (i64, i64), (x1, y1): (i64, i64)) -> i64 {
    (x0 - x1).abs() + (y0 - y1).abs()
}

fn run() {
    // WARNING: usize is 32bit!
    let x0: i64 = scan();
    let y0: i64 = scan();
    let ax: i64 = scan();
    let ay: i64 = scan();
    let bx: i64 = scan();
    let by: i64 = scan();
    let xs: i64 = scan();
    let ys: i64 = scan();
    let t: i64 = scan();

    let limit = 2_000_000_000_000_000_0;
    assert!(limit * 100 > 0);
    let mut cur_x = x0;
    let mut cur_y = y0;
    let mut vertexes = Vec::new();
    loop {
        vertexes.push((cur_x, cur_y));
        cur_x = cur_x * ax + bx;
        cur_y = cur_y * ay + by;
        if cur_x > limit || cur_y > limit {
            break;
        }
    }

    let n = vertexes.len();
    let mut ans = 0;
    for _ in 0..2 {
        for c in 0..n {
            let mut cost_a = 0;
            let mut get_a = 0;
            for a in (0..c + 1).rev() {
                let from = if a == c { (xs, ys) } else { vertexes[a + 1] };
                let to = vertexes[a];
                cost_a += cost(from, to);
                if cost_a > t {
                    break;
                }
                get_a += 1;

                ans.set_max(get_a);

                let mut cost_b = 0;
                let mut get_b = 0;
                for b in c + 1..n {
                    let from = if b == c + 1 {
                        vertexes[a]
                    } else {
                        vertexes[b - 1]
                    };
                    let to = vertexes[b];
                    cost_b += cost(from, to);
                    if cost_b + cost_a > t {
                        break;
                    }
                    get_b += 1;
                    ans.set_max(get_a + get_b);
                }
            }
        }
        vertexes.reverse();
    }

    println!("{}", ans);
}

fn main() {
    std::thread::Builder::new()
        .name("run".to_string())
        .stack_size(256 * 1024 * 1024)
        .spawn(run)
        .unwrap()
        .join()
        .unwrap()
}

//{{{ utils
pub mod utils {
    static DY: [isize; 8] = [0, 1, 0, -1, 1, -1, 1, -1];
    static DX: [isize; 8] = [1, 0, -1, 0, 1, 1, -1, -1];

    fn try_adj(
        y: usize,
        x: usize,
        dy: isize,
        dx: isize,
        h: usize,
        w: usize,
    ) -> Option<(usize, usize)> {
        let ny = y as isize + dy;
        let nx = x as isize + dx;
        if ny >= 0 && nx >= 0 {
            let ny = ny as usize;
            let nx = nx as usize;
            if ny < h && nx < w {
                Some((ny, nx))
            } else {
                None
            }
        } else {
            None
        }
    }

    pub struct Adj4 {
        y: usize,
        x: usize,
        h: usize,
        w: usize,
        r: usize,
    }

    impl Iterator for Adj4 {
        type Item = (usize, usize);

        fn next(&mut self) -> Option<Self::Item> {
            loop {
                if self.r >= 4 {
                    return None;
                }

                let dy = DY[self.r];
                let dx = DX[self.r];
                self.r += 1;

                if let Some((ny, nx)) = try_adj(self.y, self.x, dy, dx, self.h, self.w) {
                    return Some((ny, nx));
                }
            }
        }
    }

    pub fn adj4_iter(y: usize, x: usize, h: usize, w: usize) -> Adj4 {
        Adj4 {
            y: y,
            x: x,
            h: h,
            w: w,
            r: 0,
        }
    }
}
pub mod text_scanner {
    use std;
    #[derive(Debug)]
    pub enum Error {
        IoError(std::io::Error),
        EncodingError(std::string::FromUtf8Error),
        ParseError(String),
        Eof,
    }

    impl std::fmt::Display for Error {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            match *self {
                Error::IoError(ref e) => writeln!(f, "IO Error: {}", e),
                Error::EncodingError(ref e) => writeln!(f, "Encoding Error: {}", e),
                Error::ParseError(ref e) => writeln!(f, "Parse Error: {}", e),
                Error::Eof => writeln!(f, "EOF"),
            }
        }
    }

    impl std::error::Error for Error {
        // dummy implementation for 1.15.1
        fn description(&self) -> &str {
            "description() is deprecated; use Display"
        }
    }

    pub fn read_line() -> Option<String> {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        fread_line(&mut stdin).expect("IO error")
    }

    pub fn scan<T: FromTokens>() -> T {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        fscan(&mut stdin).expect("IO error")
    }

    pub fn scanln<T: FromTokens>() -> T {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        fscanln(&mut stdin).expect("IO error")
    }

    pub fn scan_iter<T: FromTokens>() -> ScanIter<T> {
        ScanIter {
            item_type: std::marker::PhantomData,
        }
    }

    pub fn scanln_iter<T: FromTokens>() -> ScanlnIter<T> {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock();
        let s = fread_line(&mut stdin)
            .expect("IO error")
            .unwrap_or_else(String::new);
        ScanlnIter {
            cursor: std::io::Cursor::new(s),
            item_type: std::marker::PhantomData,
        }
    }

    pub fn fread_line<R: std::io::BufRead>(r: &mut R) -> Result<Option<String>, std::io::Error> {
        let mut buf = String::new();
        let length = r.read_line(&mut buf)?;
        if let Some('\n') = buf.chars().last() {
            buf.pop();
        }
        if let Some('\r') = buf.chars().last() {
            buf.pop();
        }
        if length == 0 {
            Ok(None)
        } else {
            Ok(Some(buf))
        }
    }

    pub fn fscan<R: std::io::Read, T: FromTokens>(reader: &mut R) -> Result<T, Error> {
        let mut tokenizer = Tokenizer::new(reader);
        FromTokens::from_tokens(&mut tokenizer)
    }

    pub fn fscanln<R: std::io::BufRead, T: FromTokens>(reader: &mut R) -> Result<T, Error> {
        let s = match fread_line(reader) {
            Ok(Some(s)) => s,
            Ok(None) => return Err(Error::Eof),
            Err(e) => return Err(Error::IoError(e)),
        };
        let mut bytes = s.as_bytes();
        let mut tokenizer = Tokenizer::new(&mut bytes);
        FromTokens::from_tokens(&mut tokenizer)
    }

    pub fn fscan_iter<R: std::io::Read, T: FromTokens>(reader: &mut R) -> FscanIter<R, T> {
        FscanIter {
            tokenizer: Tokenizer::new(reader),
            item_type: std::marker::PhantomData,
        }
    }

    pub fn fscanln_iter<R: std::io::BufRead, T: FromTokens>(
        reader: &mut R,
    ) -> Result<ScanlnIter<T>, Error> {
        let s = match fread_line(reader) {
            Ok(Some(s)) => s,
            Ok(None) => "".to_string(),
            Err(e) => return Err(Error::IoError(e)),
        };
        Ok(ScanlnIter {
            cursor: std::io::Cursor::new(s),
            item_type: std::marker::PhantomData,
        })
    }

    pub struct ScanIter<T>
    where
        T: FromTokens,
    {
        item_type: std::marker::PhantomData<T>,
    }

    impl<T: FromTokens> Iterator for ScanIter<T> {
        type Item = T;

        fn next(&mut self) -> Option<Self::Item> {
            let stdin = std::io::stdin();
            let mut stdin = stdin.lock();
            let mut tokenizer = Tokenizer::new(&mut stdin);
            match FromTokens::from_tokens(&mut tokenizer) {
                Err(Error::Eof) => None,
                r => Some(r.expect("IO error")),
            }
        }
    }

    pub struct FscanIter<'a, R, T>
    where
        R: std::io::Read + 'a,
        T: FromTokens,
    {
        tokenizer: Tokenizer<'a, R>,
        item_type: std::marker::PhantomData<T>,
    }

    impl<'a, R: std::io::Read, T: FromTokens> Iterator for FscanIter<'a, R, T> {
        type Item = Result<T, Error>;

        fn next(&mut self) -> Option<Self::Item> {
            match FromTokens::from_tokens(&mut self.tokenizer) {
                Err(Error::Eof) => None,
                r => Some(r),
            }
        }
    }

    pub struct ScanlnIter<T>
    where
        T: FromTokens,
    {
        cursor: std::io::Cursor<String>,
        item_type: std::marker::PhantomData<T>,
    }

    impl<'a, T: FromTokens> Iterator for ScanlnIter<T> {
        type Item = T;

        fn next(&mut self) -> Option<Self::Item> {
            let mut tokenizer = Tokenizer::new(&mut self.cursor);
            match FromTokens::from_tokens(&mut tokenizer) {
                Err(Error::Eof) => None,
                r => Some(r.expect("IO error")),
            }
        }
    }

    pub trait FromTokens
    where
        Self: Sized,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error>;
    }

    macro_rules! from_tokens_primitives {
    ($($t:ty),*) => { $(
        impl FromTokens for $t {
            fn from_tokens(tokenizer: &mut Iterator<Item = Result<String, Error>>) -> Result<Self, Error> {
                let token = tokenizer.next();
                match token {
                    Some(s) => s?
                        .parse::<$t>()
                        .map_err(|e| Error::ParseError(format!("{}", e))),
                    None => Err(Error::Eof),
                }
            }
        }
    )* }
}

    from_tokens_primitives! {
        String,
        bool,
        f32,
        f64,
        isize,
        i8,
        i16,
        i32,
        i64,
        usize,
        u8,
        u16,
        u32,
        u64
    }

    impl FromTokens for Vec<char> {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok(String::from_tokens(tokenizer)?.chars().collect())
        }
    }

    impl<T1, T2> FromTokens for (T1, T2)
    where
        T1: FromTokens,
        T2: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((T1::from_tokens(tokenizer)?, T2::from_tokens(tokenizer)?))
        }
    }

    impl<T1, T2, T3> FromTokens for (T1, T2, T3)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
            ))
        }
    }

    impl<T1, T2, T3, T4> FromTokens for (T1, T2, T3, T4)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
        T4: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
                T4::from_tokens(tokenizer)?,
            ))
        }
    }

    impl<T1, T2, T3, T4, T5> FromTokens for (T1, T2, T3, T4, T5)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
        T4: FromTokens,
        T5: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
                T4::from_tokens(tokenizer)?,
                T5::from_tokens(tokenizer)?,
            ))
        }
    }

    impl<T1, T2, T3, T4, T5, T6> FromTokens for (T1, T2, T3, T4, T5, T6)
    where
        T1: FromTokens,
        T2: FromTokens,
        T3: FromTokens,
        T4: FromTokens,
        T5: FromTokens,
        T6: FromTokens,
    {
        fn from_tokens(
            tokenizer: &mut Iterator<Item = Result<String, Error>>,
        ) -> Result<Self, Error> {
            Ok((
                T1::from_tokens(tokenizer)?,
                T2::from_tokens(tokenizer)?,
                T3::from_tokens(tokenizer)?,
                T4::from_tokens(tokenizer)?,
                T5::from_tokens(tokenizer)?,
                T6::from_tokens(tokenizer)?,
            ))
        }
    }

    struct Tokenizer<'a, R: std::io::Read + 'a> {
        reader: &'a mut R,
    }

    impl<'a, R: std::io::Read> Tokenizer<'a, R> {
        pub fn new(reader: &'a mut R) -> Self {
            Tokenizer { reader: reader }
        }

        pub fn next_token(&mut self) -> Result<Option<String>, Error> {
            use std::io::Read;
            let mut token = Vec::new();
            for b in self.reader.by_ref().bytes() {
                let b = b.map_err(Error::IoError)?;
                match (is_ascii_whitespace(b), token.is_empty()) {
                    (false, _) => token.push(b),
                    (true, false) => break,
                    (true, true) => {}
                }
            }
            if token.is_empty() {
                return Ok(None);
            }
            String::from_utf8(token)
                .map(Some)
                .map_err(Error::EncodingError)
        }
    }

    impl<'a, R: std::io::Read> Iterator for Tokenizer<'a, R> {
        type Item = Result<String, Error>;
        fn next(&mut self) -> Option<Self::Item> {
            match self.next_token() {
                Ok(Some(s)) => Some(Ok(s)),
                Ok(None) => None,
                Err(e) => Some(Err(e)),
            }
        }
    }

    fn is_ascii_whitespace(b: u8) -> bool {
        // Can use u8::is_ascii_whitespace once removing support of 1.15.1
        match b {
            b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
            _ => false,
        }
    }
}

pub trait SetMinMax {
    fn set_min(&mut self, v: Self) -> bool;
    fn set_max(&mut self, v: Self) -> bool;
}

impl<T> SetMinMax for T
where
    T: PartialOrd,
{
    fn set_min(&mut self, v: T) -> bool {
        *self > v && {
            *self = v;
            true
        }
    }
    fn set_max(&mut self, v: T) -> bool {
        *self < v && {
            *self = v;
            true
        }
    }
}

#[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
pub struct Reverse<T>(pub T);

impl<T: PartialOrd> PartialOrd for Reverse<T> {
    #[inline]
    fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }

    #[inline]
    fn lt(&self, other: &Self) -> bool {
        other.0 < self.0
    }
    #[inline]
    fn le(&self, other: &Self) -> bool {
        other.0 <= self.0
    }
    #[inline]
    fn ge(&self, other: &Self) -> bool {
        other.0 >= self.0
    }
    #[inline]
    fn gt(&self, other: &Self) -> bool {
        other.0 > self.0
    }
}

impl<T: Ord> Ord for Reverse<T> {
    #[inline]
    fn cmp(&self, other: &Reverse<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}

#[derive(PartialEq, PartialOrd, Debug, Copy, Clone, Default)]
pub struct Num(pub f64);

impl Eq for Num {}

impl Ord for Num {
    fn cmp(&self, other: &Num) -> Ordering {
        self.0
            .partial_cmp(&other.0)
            .expect("unexpected NaN when compare")
    }
}

// See https://docs.rs/superslice/1.0.0/superslice/trait.Ext.html
pub trait SliceExt {
    type Item;

    fn lower_bound(&self, x: &Self::Item) -> usize
    where
        Self::Item: Ord;

    fn lower_bound_by<'a, F>(&'a self, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering;

    fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord;

    fn upper_bound(&self, x: &Self::Item) -> usize
    where
        Self::Item: Ord;

    fn upper_bound_by<'a, F>(&'a self, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering;

    fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord;
}

impl<T> SliceExt for [T] {
    type Item = T;

    fn lower_bound(&self, x: &Self::Item) -> usize
    where
        T: Ord,
    {
        self.lower_bound_by(|y| y.cmp(x))
    }

    fn lower_bound_by<'a, F>(&'a self, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering,
    {
        let s = self;
        let mut size = s.len();
        if size == 0 {
            return 0;
        }
        let mut base = 0usize;
        while size > 1 {
            let half = size / 2;
            let mid = base + half;
            let cmp = f(unsafe { s.get_unchecked(mid) });
            base = if cmp == Less { mid } else { base };
            size -= half;
        }
        let cmp = f(unsafe { s.get_unchecked(base) });
        base + (cmp == Less) as usize
    }

    fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord,
    {
        self.lower_bound_by(|e| f(e).cmp(k))
    }

    fn upper_bound(&self, x: &Self::Item) -> usize
    where
        T: Ord,
    {
        self.upper_bound_by(|y| y.cmp(x))
    }

    fn upper_bound_by<'a, F>(&'a self, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> Ordering,
    {
        let s = self;
        let mut size = s.len();
        if size == 0 {
            return 0;
        }
        let mut base = 0usize;
        while size > 1 {
            let half = size / 2;
            let mid = base + half;
            let cmp = f(unsafe { s.get_unchecked(mid) });
            base = if cmp == Greater { base } else { mid };
            size -= half;
        }
        let cmp = f(unsafe { s.get_unchecked(base) });
        base + (cmp != Greater) as usize
    }

    fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize
    where
        F: FnMut(&'a Self::Item) -> K,
        K: Ord,
    {
        self.upper_bound_by(|e| f(e).cmp(k))
    }
}

//}}}


use std::io::{self, BufRead};

fn main() {
    let stdin = io::stdin();
    let mut table = String::new();
    let mut hand = String::new();

    stdin.lock().read_line(&mut table).unwrap();
    stdin.lock().read_line(&mut hand).unwrap();

    let table = table.as_bytes();
    let hand = hand.trim().split(" ");
    for card in hand {
        let card = card.as_bytes();
        if card[0] == table[0] || card[1] == table[1] {
            println!("YES");
            return;
        }
    }
    println!("NO");
}


use std::io::{self, BufRead, BufWriter, StdinLock, Write};

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = stdin.lock();
    let mut out = BufWriter::new(stdout.lock());

    let table = scan.next();
    let hand = scan.next();

    writeln!(
        out,
        "{}",
        if {
            let bytes = table.as_bytes();
            hand.contains(bytes[0] as char) || hand.contains(bytes[1] as char)
        } {
            "YES"
        } else {
            "NO"
        }
    )
    .ok();
}

trait Scan {
    fn next(&mut self) -> String;
}

impl<'a> Scan for StdinLock<'a> {
    fn next(&mut self) -> String {
        let mut buf = String::with_capacity(15);
        self.read_line(&mut buf).unwrap();
        return buf;
    }
}


use std::io;

fn main() {
  let mut ti = String::new();
  io::stdin().read_line(&mut ti).unwrap();
  let mut hi = String::new();
  io::stdin().read_line(&mut hi).unwrap();

  let t = ti.as_bytes();
  let h: Vec<&str> = hi.split_terminator(" ").collect();
  for i in 0..5 {
    let h = h[i].as_bytes();
    if (h[1] == t[1]) || (h[0] == t[0]) {
      println!("YES");
      return;
    }
  }
  println!("NO");
}


use std::io;

fn can_play(table: &str, hand: Vec<&str>) -> &'static str {
    for card in hand.iter() {
        let mut table_chars = table.chars();
        let mut card_chars = card.chars();

        if table_chars.nth(0).unwrap() == card_chars.nth(0).unwrap()
            || table_chars.nth(0).unwrap() == card_chars.nth(0).unwrap()
        {
            return "YES";
        }
    }

    "NO"
}

pub fn solution() -> io::Result<()> {
    let mut table = String::new();
    let mut hand = String::new();

    io::stdin().read_line(&mut table)?;
    io::stdin().read_line(&mut hand)?;
    let hand: Vec<&str> = hand.trim().split(" ").collect();

    println!("{}", can_play(&table, hand));
    Ok(())
}

fn main() {
    solution();
}


fn main() {
    let mut card_on_table = String::new();
    std::io::stdin().read_line(&mut card_on_table).expect("CARD_ON_TABLE::Read line failed!");

    let mut cards_in_hand = String::new();
    std::io::stdin().read_line(&mut cards_in_hand).expect("CARDS_IN_HAND::Read line failed!");

    let mut card = card_on_table.trim().chars();
    let suit = card.next().expect("SUIT::Not exist next char!");
    let rank = card.next().expect("RANK::Not exist next char!");

    let can_play = cards_in_hand.contains(suit) || cards_in_hand.contains(rank);

    match can_play {
        true => println!("YES"),
        false => println!("NO"),
    }
}


#[allow(unused_imports)]
use std::cmp::{min,max};
#[allow(unused_imports)]
use std::collections::{BTreeMap,BTreeSet};
#[allow(unused_imports)]
use std::ops::*;
#[allow(unused_imports)]
use std::collections::BinaryHeap;

#[allow(unused_macros)]
macro_rules! ite {
    ($c:expr, $t:expr, $f:expr) => {{
        if $c { $t } else { $f }
    }};
}

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
#[macro_export]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

#[macro_export]
macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

#[macro_export]
macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        s: chars,
        ts: [chars; 5],
    }
    let mut res = false;
    for i in 0..5 {
        if s[0] == ts[i][0] || s[1] == ts[i][1] {
            res = true;
        }
    }
    println!("{}", ite!(res, "YES", "NO"));
}

use std::io::BufRead;
use std::io;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R:BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len,complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len-1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T:str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            }
            else {
                self.update_buf();
            }
        }
    }
}

use std::fmt::Display;
#[allow(dead_code)]
fn write_vec<T: Display>(xs: &Vec<T>) {
    if xs.len() == 0 {
        println!();
        return;
    }
    print!("{}", xs[0]);
    for i in 1..xs.len() {
        print!(" {}", xs[i]);
    }
    println!();
}


use std::io;

fn get_line() -> io::Result<String> {
	let mut buffer = String::new();
	io::stdin().read_line(&mut buffer)?;
	Ok(buffer)
}

fn main() {
	let input = get_line().unwrap();
	let card = input.trim().as_bytes();
	let input = get_line().unwrap();
	let hand: Vec<&[u8]> = input.split_whitespace().map(|s| s.as_bytes()).collect();
	let mut play = "NO";
	for i in 0..hand.len() {
		if card[0] == hand[i][0] || card[1] == hand[i][1] {
			play = "YES";
			break;
		}
	}
	print!("{}", play);
}


fn main() {
    let mut card = String::new();
    std::io::stdin().read_line(&mut card)
        .expect("Error  input");
    let card_chars: Vec<char> = card.chars().collect();
    let mut hand = String::new();
    std::io::stdin().read_line(&mut hand)
        .expect("Error  input");
    let hand_chars: Vec<Vec<char>> = hand.split(' ').map(|s| s.chars().collect()).collect();

    for c in hand_chars {
        if c[0] == card_chars[0] || c[1] == card_chars[1] {
            println!("YES");
            std::process::exit(0);
        }
    }
    println!("NO");
}


use std::io;
use std::io::Stdin;
use std::str::FromStr;

fn read_line(stdin : &Stdin, line : &mut String) {
    match stdin.read_line(line) {
        Ok(_) => return,
        Err(msg) => panic!("Could not read line! Message: {}.", msg),
    }
}

fn parse_t<T : FromStr>(s : &str) -> T {
    match s.trim().parse() {
        Ok(y) => y,
        Err(_) => panic!("Could not read from string!"),
    }
}

fn read_t<T : FromStr>(stdin : &Stdin) -> T {
    let mut line = String::new();
    read_line(stdin, &mut line);
    parse_t(&line)
}

fn read_ts<T : FromStr>(stdin : &Stdin, ts : &mut Vec<T>) {
    let mut line = String::new();
    read_line(stdin, &mut line);
    let word_iter = line.split_whitespace();
    for word in word_iter {
        let x = parse_t(word);
        ts.push(x);
    }
}

fn cost_to_one(n : u64, k : u64, a : u64, b : u64) -> u64 {
    let mut c = 0;
    let mut x = n;
    if k == 1 {
        c = (x - 1) * a;
    } else {
        loop {
            if x < 1 {
                panic!("x is less than 1!");
            } else if x == 1 {
                break;
            } else if x < k {
                c = c + (a * (x - 1));
                x = 1;
            } else {
                let q = x / k;
                let r = x % k;
                let cost_div = b;
                let cost_sub = a * ((q * k) - q);
                if r == 0 {
                    if cost_div <= cost_sub {
                        c = c + cost_div;
                    } else {
                        c = c + cost_sub;
                    }
                    x = q;
                } else {
                    c = c + (r * a);
                    x =  x - r;
                }
            }
        }
    }
    c
}

fn main() {
    let stdin = io::stdin();
    let n = read_t(&stdin);
    let k = read_t(&stdin);
    let a = read_t(&stdin);
    let b = read_t(&stdin);
    println!("{}", cost_to_one(n, k, a, b));
}


use std::io;

fn main() {
    let n = getint();
    let k = getint();
    let a = getint();
    let b = getint();

    println!("{}",find_min_cost(n,k,a,b,0));
}

fn getint() -> i64 {
    let mut inpstr = String::new();
    io::stdin().read_line(&mut inpstr).expect("Could not read integer");
    let number = inpstr.trim().parse::<i64>();

    number.unwrap()

}

//Implements greedy algorithm, acc is the accumulator
fn find_min_cost(n : i64, k: i64, a : i64, b : i64, acc: i64) ->  i64 {
    let rem = n%k;

    if rem != 0 && n > k {
        return find_min_cost(n - rem, k, a, b, acc+ a*rem);
    }

    let quo = n/k;

    if quo > 0 && quo*a + b < n*a {
        return find_min_cost(quo, k, a, b, acc+ b);
    }

    (n-1)*a + acc
}


#![allow(unused_imports, unused_macros, dead_code)]
use std::f64::*;
use std::cmp::*;
use std::collections::*;

macro_rules! dump{
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

const INF: i64 = 0x3f3f3f3f3f3f3f3f;
const MOD: i64 = 1000000007;
const NOTHING: usize = std::usize::MAX;
const DX: [usize; 4] = [1, 0, std::usize::MAX, 0];
const DY: [usize; 4] = [0, 1, 0, std::usize::MAX];

fn main() {
    let mut n: i64 = readln();
    let k: i64 = readln();
    let a: i64 = readln();
    let b: i64 = readln();

    if k == 1 {
        println!("{}", a * (n - 1));
        return;
    }

    let mut res: i64 = 0;
    while n >= k {
        let r = n % k;
        if r > 0 {
            res += a * r;
            n -= r;
        } else {
            res += min(a * (n - n / k), b);
            n /= k;
        }
    }
    res += a * (n - 1);

    println!("{}", res);

}

trait Read {
    fn read(s: &str) -> Self;
}

fn readln<T: Read>() -> T {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    T::read(buf.trim_right())
}

macro_rules! read_impl{
    ($($t:ty)*) => ($(
        impl Read for $t {
            fn read(s: &str) -> $t{
                s.parse().unwrap()
            }
        }
    )*)
}
read_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }

impl Read for String {
    fn read(s: &str) -> Self {
        s.to_string()
    }
}

impl Read for Vec<char> {
    fn read(s: &str) -> Self {
        s.chars().collect()
    }
}

impl<T: Read> Read for Vec<T> {
    fn read(s: &str) -> Self {
        s.split_whitespace().map(T::read).collect()
    }
}

impl<A: Read, B: Read> Read for (A, B) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]))
    }
}

impl<A: Read, B: Read, C: Read> Read for (A, B, C) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))
    }
}

impl<A: Read, B: Read, C: Read, D: Read> Read for (A, B, C, D) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]), D::read(tokens[3]))
    }
}


#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(overflowing_literals)]
#![allow(unused_must_use)]
#![allow(non_camel_case_types)]

use std::collections::*;
use std::io::*;
use std::cmp::{max, min, Ordering};
use std::f64::consts::*;
use std::mem::{swap, size_of_val, size_of};
use std::fs::File;
use std::rc::*;
use std::ascii::*;
use std::ops::*;
use std::num::*;
use std::process::*;
//use std::ptr::*;
use std::iter::{once, repeat};

const INF: i32 = std::i32::MAX;
const LINF: i64 = std::i64::MAX;
const MOD: usize = 1000000007;

struct Input<Buf: BufRead> {
	buffer: Buf,
}

impl<Buf: BufRead> Input<Buf> {
	fn read_char(&mut self) -> char {
		let mut x = [255u8];
		self.buffer.read(&mut x).expect("EOF");
		x[0] as char
	}
	fn read_line(&mut self) -> String {
		let mut v = Vec::new();
		let mut x = [255u8];
		self.buffer.read(&mut x).expect("EOF");
		while x[0] < b' ' && x[0] != 255u8 {
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		while x[0] >= b' ' && x[0] != 255u8 {
			v.push(x[0]);
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		String::from_utf8(v).unwrap()
	}

	fn read_word(&mut self) -> String {
		let mut v = Vec::new();
		let mut x = [255u8];
		self.buffer.read(&mut x).expect("EOF");
		while x[0] <= b' ' && x[0] != 255u8 {
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		while x[0] > b' ' && x[0] != 255u8 {
			v.push(x[0]);
			x[0] = 255u8;
			self.buffer.read(&mut x).expect("EOF");
		}
		String::from_utf8(v).unwrap()
	}
}

macro_rules! read {
    () => {};
	($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect("Parsing error"));
	($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect("Parsing error")),*));
}
fn gcd<T>(mut a: T, mut b: T) -> T
	where T: ShrAssign + BitAnd<Output=T> + Ord + From<u8> + Clone + SubAssign + ShlAssign<usize> + Copy
{
	let one = T::from(1);
	let zero = T::from(0);
	let mut ans = 0;
	if a < b {
		swap(&mut a, &mut b);
	}
	while b > zero {
		if (a & one > zero) && (b & one > zero) {
			a -= b;
		} else if a & one > zero {
			b >>= one;
		} else if b & one > zero {
			a >>= one;
		} else {
			ans += 1;
			a >>= one;
			b >>= one;
		}
		if a < b {
			swap(&mut a, &mut b);
		}
	}
	a <<= ans;
	a
}

fn powmod<X, Y>(mut base: X, mut exp: Y, mm: X) -> X
	where X: Copy + Clone + Mul<Output=X> + Rem<Output=X> + From<u8>,
	      Y: ShrAssign + Copy + Clone + BitAnd<Output=Y> + From<u8> + Ord
{
	let mut res = X::from(1);
	while exp > Y::from(0) {
		if exp & Y::from(1) > Y::from(0) {
			res = res * base % mm;
		}
		base = base * base % mm;
		exp >>= Y::from(1);
	}
	res
}

fn main() {
	match std::env::var("home") {
		Ok(_x) => {
			let mut inf = Input { buffer: BufReader::new(File::open("input.txt").expect("File not found")) };
			let stdout = stdout();
			let ostr = stdout.lock();
			let mut ouf = BufWriter::new(ostr);
			solve(&mut inf, &mut ouf);
		}
		Err(_e) => {
			let stdin = stdin();
			let istr = stdin.lock();
			let mut inf = Input { buffer: BufReader::new(istr) };
			let stdout = stdout();
			let ostr = stdout.lock();
			let mut ouf = BufWriter::new(ostr);
			solve(&mut inf, &mut ouf);
		}
	}
}

fn solve<Inner: BufRead, Output: Write>(inf: &mut Input<Inner>, ouf: &mut Output) {
	let (mut n, k, a, b) = read!(inf,i64,i64,i64,i64);
	if k == 1 {
		writeln!(ouf, "{}", (n - 1) * a);
		return;
	}
	let mut ans = 0i64;
	while n > 1 {
		if n < k {
			ans += (n - 1) * a;
			break;
		}
		ans += (n % k) * a;
		n -= n % k;

		ans += min(b, (n - n / k) * a);
		n /= k;
	}
	writeln!(ouf, "{}", ans);
}


fn main() {
    let mut input = String::new();
    use std::io::prelude::*;
    use std::io;
    io::stdin().read_to_string(&mut input).unwrap();

    let mut it = input.split_whitespace();

    let n: u64 = it.next().unwrap().parse().unwrap();
    let k: u64 = it.next().unwrap().parse().unwrap();
    let a: u64 = it.next().unwrap().parse().unwrap();
    let b: u64 = it.next().unwrap().parse().unwrap();

    if k == 1 {
        let ans = (n - 1) * a;
        println!("{}", ans);
        return;
    }

    let mut x = n;

    let mut ans = 0;

    loop {
        let rem = x % k;
        if rem > 0 {
            x -= rem;
            ans += rem * a;
        } else {
            let q = x / k;
            let y = std::cmp::min((k - 1) * q * a, b);

            ans += y;
            x = q;
        }
        if x == 1 {
            println!("{}", ans);
            break;
        } else if x == 0 {
            println!("{}", ans - a);
            break;
        }
    }
}


#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Formatter};
use std::io::*;
use std::ops::*;
use std::*;

// -----------------------------------------------
// Framework
// -----------------------------------------------

#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($t:ty) =>
        (rl().parse::<$t>().unwrap());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($arg:expr),*) => {
        #[cfg(debug_assertions)]
        {
            let entries = [$(&stringify!([$arg]:), &$arg as &Debug),*];
            stderr().write_fmt(format_args!("{:#?}\n", entries)).unwrap();
        }
    };
}

#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.trim_right().to_owned()
}

trait IteratorExt: Iterator + Sized {
    fn vec(self) -> Vec<Self::Item> {
        self.collect()
    }
}

impl<T: Iterator> IteratorExt for T {}

// -----------------------------------------------
// Solution
// -----------------------------------------------

pub fn main() {
    let n = read!(i64);
    let k = read!(i64);
    let A = read!(i64);
    let B = read!(i64);

    let mut x = n;
    let mut s = 0;
    if k == 1 {
        s = (x - 1) * A;
    } else {
        while x > 1 {
            if x < k {
                s += (x - 1) * A;
                break;
            }

            let r = x % k;
            if r != 0 {
                x -= r;
                s += r * A;
                continue;
            }

            let q = x / k;
            s += min((x - q) * A, B);
            x = q;
        }
    }

    println!("{}", s);
    return;
}


const N: usize = 19;

fn main() {
    let mut input = String::new();
    use std::io::{self, prelude::*};
    io::stdin().read_to_string(&mut input).unwrap();

    let n: u64 = input.trim().parse().unwrap();

    let fact: Vec<u64> = std::iter::once(1).chain((1..N).scan(1, |state, x| {
        *state *= x as u64;
        Some(*state)
    })).collect();

    let mut dl = Vec::with_capacity(N);

    let mut t = n;
    while t > 0 {
        let r = t % 10;
        dl.push(r);
        t /= 10;
    }

    let mut ms = [0; 10];
    for d in dl {
        ms[d as usize] += 1;
    }

    let binc = |k: usize, n: usize| -> u64 {
        fact[n] / fact[k] / fact[n - k]
    };

    let cnt = |ms: &[usize; 10], c: usize, zc: usize| -> u64 {
        if c == 0 {
            0
        } else {
            let mut ret_val = fact[c];
            for &c in &ms[1..] {
                ret_val /= fact[c];
            }
            ret_val *= binc(ms[0], c + zc - 1);
            ret_val
        }
    };

    let mut curc = 0;
    let mut curzc = 0;

    let first = {
        let mut t = [0; 10];
        if ms[0] > 0 {
            t[0] = 1;
            curzc += 1;
        }
        for (&c, t) in ms.iter().zip(t.iter_mut()).skip(1) {
            if c > 0 {
                *t = 1;
                curc += 1;
            }
        }
        t
    };

    let mut ans = 0;
    let mut cur = first;
    'outer: loop {
        let c = cnt(&cur, curc, curzc);
        ans += c;
        for di in 0..10 {
            if cur[di] == ms[di] {
                if di == 9 {
                    break 'outer;
                }
                if di == 0 {
                    curzc -= cur[di] - first[di];
                } else {
                    curc -= cur[di] - first[di];
                }
                cur[di] = first[di];
            } else {
                cur[di] += 1;
                if di == 0 {
                    curzc += 1;
                } else {
                    curc += 1;
                }
                break;
            }
        }
    }

    println!("{}", ans);
}


// 991E
use std::io;

fn main() {
    let mut a = String::new();
    io::stdin().read_line(&mut a).unwrap();
    let a = a.trim();

    let mut counts = [0u64; 10];

    for c in a.chars() {
        counts[c.to_digit(10).unwrap() as usize] += 1;
    }

    let mut fa = [0u64; 30];

    let with_zero = count(&mut counts, 0, &mut fa);
    let mut correct = with_zero;
    if counts[0] > 0 {
        counts[0] -= 1;
        correct -= count(&mut counts, 0, &mut fa);
        if counts[0] > 0 {
            counts[0] = 0;
            correct -= count(&mut counts, 0, &mut fa);
        }
    }
    println!("{}", correct);
}

fn factorial(n: u64, fa: &mut [u64]) -> u64 {
    if n == 0 {
        fa[n as usize] = 1;
    } else if fa[n as usize] == 0 {
        fa[n as usize] = factorial(n - 1, fa) * n;
    }
    return fa[n as usize];
}

fn count(counts: &mut [u64], change_here: usize, fa: &mut [u64]) -> u64 {
    if change_here == 10 {
        // All numbers are fixed now
        let numerator = factorial(counts.iter().sum(), fa);
        let mut denominator = 1;
        for c in counts {
            denominator *= factorial(*c, fa);
        }
        return numerator / denominator;
    }

    if counts[change_here] == 0 {
        return count(counts, change_here + 1, fa);
    }

    let mut add = 0;
    for i in 1..(counts[change_here] + 1) {
        counts[change_here] = i;
        add += count(counts, change_here + 1, fa);
    }
    return add;
}


#[allow(unused_imports)]
use std::io::stdin;

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>
}
impl Scanner {
    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            stdin().read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

use std::collections::HashMap;
use std::cmp::min;

fn main() {
    let mut scan = Scanner::default();
    let n: usize = scan.next();
    let k: usize = scan.next();
    let a: Vec<u64> = (0..n).map(|_| scan.next::<u64>()).collect();
    let mut to_reach: HashMap<u64, Vec<u64>> = HashMap::new();
    for x in &a {
        let mut y = x.clone();
        let mut div = 0;
        while y > 0 {
            if !to_reach.contains_key(&y) {
                to_reach.insert(y.clone(), vec![]);
            }
            let v: &mut Vec<u64> = to_reach.get_mut(&y).unwrap();
            v.push(div);
            y /= 2;
            div += 1;
        }
    }
    let mut ans = std::u64::MAX;
    for v in to_reach.values_mut() {
        if v.len() < k {
            continue;
        }
        v.sort();
        ans = min(ans, v[0..k].iter().sum::<u64>());
    }
    println!("{}", ans);
}


#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]

use std::char::*;
use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;

macro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);}}
macro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
macro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
macro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

use std::f64;

fn min<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { a }
    else { b }
}

fn max<T: PartialOrd>(a:T, b:T) -> T {
    if a < b { b }
    else { a }
}

use std::hash::Hash;
fn inc<T: Hash+Ord>(map:&mut BTreeMap<T,i64>, key:T) {
    let count = map.entry(key).or_insert(0);
    *count += 1;
}

fn digit(ch: char) -> i64 {
    return (ch as u8 - b'0') as i64
}

const MAX:usize = 30;
const INF:i64 = std::i64::MAX;
const MOD:i64 = 1e9 as i64 + 7;

fn gcd(x:i64, y:i64) -> i64 {
    if y==0 { return x; }
    gcd(y, x%y)
}

fn main() {
    //let t:usize = read();

    //'outer: for _ in 0..t {
        let n:usize = read();
        let k:usize = read();
        let a:Vec<i64> = (0..n).map(|_| read()).collect();

        let mut map = HashMap::new();
        for i in 0..n {
            let mut b = a[i];
            let mut j = 0;
            while b != 0 {
                let v = map.entry(b).or_insert(vec![]);
                v.push(j);
                j += 1;
                b /= 2;
            }
        }
        //debug!(map);

        let mut ans = INF;

        for (_,v) in &mut map {
            v.sort();
            if v.len() < k { continue; }
            let mut cnt = 0;
            for i in 0..k {
                cnt += v[i];
            }
            ans = min(ans,cnt);
        }

        println!("{}", ans);

    //}
}

/*

*/


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn run() {
    input! {
        n: usize,
        k: usize,
        a: [usize; n],
    }
    let m = 200_000;
    let mut cnt = vec![0; m + 1];
    for &a in a.iter() {
        cnt[a] += 1;
    }
    let mut ans = 20 * n;
    let mut s = vec![vec![]; m + 1];
    let mut sum = vec![0; m + 1];
    for i in (0..=m).rev() {
        for _ in 0..cnt[i] {
            s[i].push(0);
        }
        s[i].sort();
        while s[i].len() > k {
            if let Some(v) = s[i].pop() {
                sum[i] -= v;
            }
        }
        if s[i].len() >= k {
            ans = std::cmp::min(ans, sum[i]);
        }
        if i > 0 {
            while let Some(v) = s[i].pop() {
                s[i / 2].push(v + 1);
                sum[i / 2] += v + 1;
            }
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}


#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*);
    }
}

#[allow(unused_imports)]
use std::cmp::{min, max};
#[allow(unused_imports)]
use std::io::{stdout, stdin, BufWriter, Write};

fn main() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (write!(out,$($format)*).unwrap());
    }

    input!{
      n: usize,
      k: usize,
      mut aa: [u64; n],
    }
    aa.sort();
    let mut m: u64 = *aa.iter().max().unwrap();
    let mut ans: u64 = 1 << 60;
    for t in 0..m+1 {
        let mut temp = 0;
        let mut ok = 0;

        for i in 0..n {
            let mut a = aa[i];
            let mut cnt = 0;
            if a < t {
                continue;
            }

            while a > t {
                a/=2;
                cnt += 1;
            }
            if t == a {
                temp += cnt;
                ok += 1;
                if ok == k {
                    break;
                }
            }
        }

        if ok == k {
            ans = min(ans, temp);
        }
    }
    puts!("{}\n", ans);
}


use std::collections::HashMap;
use std::io;

fn lvl(mut x: i32) -> i8 {
    let mut res: i8 = 0;

    while x > 1 {
        res += 1;
        x >>= 1;
    }

    res
}

fn main() {
    let mut inp = String::new();
    io::stdin().read_line(&mut inp).unwrap();
    let line: Vec<i32> = inp
        .split_whitespace()
        .map(|x| x.trim().parse().unwrap())
        .collect();
    let (_n, k) = (line[0], line[1]);

    inp.clear();
    io::stdin().read_line(&mut inp).unwrap();

    let mut input: Vec<(i32, i8, i8)> = inp
        .split_whitespace()
        .map(|x| {
            let xx = x.trim().parse::<i32>().unwrap();
            (xx, lvl(xx), 0)
        })
        .collect();

    let mut min_steps: i32 = std::i32::MAX;
    loop {
        input.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap());

        //
        let mut eq_map: HashMap<i32, i32> = HashMap::new();

        // count equal
        input
            .iter()
            .for_each(|x| *eq_map.entry(x.0).or_insert(0) += 1);

        eq_map.keys().for_each(|key| {
            if *eq_map.get(key).unwrap() >= k {
                //   push equal to separate vector
                let mut eq_vec: Vec<i32> = input
                    .iter()
                    .filter(|x| &x.0 == key)
                    .map(|x| x.2 as i32)
                    .collect();

                //   sort vector
                eq_vec.sort_unstable();
                //   take(k).sum()
                min_steps = std::cmp::min(min_steps, eq_vec.iter().take(k as usize).sum());
            }
        });

        // all on first level
        if input.iter().all(|x| x.1 == 0) {
            break;
        }

        //println!("steps: {}; lvls: {:?}", min_steps, input);

        let mut f: &mut (i32, i8, i8) = &mut input[0];

        f.0 >>= 1;
        f.1 -= 1;
        f.2 += 1;
    }

    //println!("lvls: {:?}", input);
    print!("{}", min_steps);
    //println!("steps: {}", min_steps);
}


use std::io::*;
use std::ops::*;

#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
struct Clock {
    time: i32,
}

impl Clock {
    pub fn new (hh: i32, mm: i32) -> Self {
        Self {
            time: Clock::hhmm_to_time(hh, mm)
        }
    }
    pub fn hh(&self) -> i32 {
        self.time / 60
    }
    pub fn mm(&self) -> i32 {
        self.time % 60
    }
    fn hhmm_to_time(hh: i32, mm: i32) -> i32 {
        hh * 60 + mm
    }
    fn time_to_hhmm(t: i32) -> (i32, i32) {
        (t / 60, t % 60)
    }
}

impl Sub<i32> for Clock {
    type Output = Clock;
    fn sub(mut self, m: i32) -> Clock {
        let day = 24 * 60;
        let m = m % day;
        self.time = (self.time + day - m) % day;
        self
    }
}

fn find_lucky(c: &Clock) -> bool {
    if c.hh() / 10 == 7 || c.hh() % 10 == 7 || c.mm() / 10 == 7 || c.mm() % 10 == 7 {
        true
    } else {
        false
    }
}

fn main() {
    let mut input = String::new();
    stdin().read_line(&mut input).expect("Can't read input");
    let x: i32 = input.trim().parse().expect("Can't parse input");
    input.clear();
    stdin().read_line(&mut input).expect("Cant' read input");
    let mut hm = input.split_whitespace().map(|s| s.parse().expect("Can't parse intput"));
    let hh: i32 = hm.next().unwrap();
    let mm = hm.next().unwrap();
    let mut c = Clock::new(hh, mm);
    let mut n = 0;
    loop {
        if find_lucky(&c) {
            println!("{}", n);
            break;
        }
        c = c - x;
        n += 1;
    }

}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};
mod util {
    use std::io::stdin;
    use std::str::FromStr;
    use std::fmt::Debug;
    #[allow(dead_code)]
    pub fn line() -> String {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    }
    #[allow(dead_code)]
    pub fn gets<T: FromStr>() -> Vec<T>
    where
        <T as FromStr>::Err: Debug,
    {
        let mut line: String = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|t| t.parse().unwrap())
            .collect()
    }
}
#[allow(unused_macros)]
macro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }

fn luckey(h: usize, m: usize) -> bool {
    m % 10 == 7 || h % 10 == 7
}

fn main() {
    let x = get!(usize);
    let (mut h, mut m) = get!(usize, usize);

    let mut ans = 0;
    while !luckey(h, m) {
        let mut subh = false;
        if x > m {
            subh = true;
            m = m + 60 - x;
        } else {
            m -= x;
        }

        if subh {
            if h == 0 {
                h = 23;
            } else {
                h -= 1;
            }
        }

        ans += 1;
    }

    println!("{}", ans);
}


#![allow(unused_imports)]
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::str::FromStr;
use std::collections::{VecDeque, HashMap};
use std::ops::Sub;

fn main() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let x = get_numbers(&line)[0];
    line.clear(); input.read_line(&mut line).unwrap();
    let nums = get_numbers(&line);

    let get_up = Time::new(nums[0], nums[1]);

    let mut snoozed = 0;
    let mut cur_time = get_up;
    while cur_time.lucky() == false {
        cur_time = cur_time - x;
        snoozed += 1;
        //println!("{} -> {}:{}", snoozed, cur_time.hh, cur_time.mm);
    }

    println!("{}", snoozed);
}

#[derive(Debug, Clone, Copy)]
struct Time {
    hh: u8,
    mm: u8,
}

impl Time {
    fn new(hour: u8, min: u8) -> Time {
        Time {
            hh: hour,
            mm: min,
        }
    }

    fn lucky(&self) -> bool {
        // 7 cannot be appear in the 10s spot so we only have to check ones
        self.mm % 10 == 7 || self.hh % 10 == 7
    }
}

impl Sub<u8> for Time {
    type Output = Time;

    fn sub(self, mins: u8) -> Time {
        if mins <= self.mm {
            Time { hh: self.hh, mm: self.mm - mins }
        } else if self.hh >= 1 {
            Time { hh: self.hh - 1, mm: self.mm + 60 - mins }
        } else {
            // going back a day
            Time { hh: 23, mm: self.mm + 60 - mins }
        }
    }
}

/*
 * Utility Functions
 */

// get numbers from line seperated by spaces
fn get_numbers<T>(line: &str) -> Vec<T>
    where T: FromStr,
          <T as std::str::FromStr>::Err: std::fmt::Debug,
{
    line.split_whitespace()
        .map(|chunk| chunk.parse::<T>().expect("failed to parse"))
        .collect()
}


use std::io::{BufReader, stdin};

fn main() {
    let mut reader = stdin();
    let mut s = String::new();
    reader.read_line(&mut s).unwrap();
    let N = s.trim_right().parse::<i32>().unwrap();
    s.clear();
    reader.read_line(&mut s).unwrap();
    let A = s.trim_right().parse::<i32>().unwrap();
    s.clear();
    reader.read_line(&mut s).unwrap();
    let B = s.trim_right().parse::<i32>().unwrap();
    s.clear();
    reader.read_line(&mut s).unwrap();
    let C = s.trim_right().parse::<i32>().unwrap();

    let mut ans = 0;
    let mut loc = 0;
    for x in 1..N {
        if loc == 0 {   // rabbit
            if A > B {
                ans = ans + B;
                loc = 2;
            } else {
                ans = ans + A;
                loc = 1;
            }
        } else if loc == 1 {    // owl
            if A > C {
                ans = ans + C;
                loc = 2;
            } else {
                ans = ans + A;
                loc = 0;
            }
        } else {    // eeyore
            if B > C  {
                ans = ans + C;
                loc = 1;
            } else {
                ans = ans + B;
                loc = 0;
            }
        }
    }

    println!("{}", ans);
}


use std::io::stdin;
use std::io::prelude::*;
use std::iter::*;
use std::str::SplitWhitespace;
use std::cmp::min;

fn main() {
    let mut input = InRead::new();
    let n = input.int();
    let a = input.int();
    let b = input.int();
    let c = input.int();
    let x = min(a, b);
    let res = if n == 1 { 0 } else { x + min(x, c) * (n - 2) };
    println!("{}", res);
}

struct InRead(String);

impl InRead {
    fn new() -> InRead {
        InRead(String::new())
    }
    fn get_line(self: &mut Self) {
        self.0.clear();
        stdin().read_line(&mut self.0);
    }
    fn parse_int(s: &str) -> i32 { s.parse().unwrap() }
    fn ints(self: &mut Self) -> Map<SplitWhitespace, fn(&str) -> i32> {
        self.get_line();
        self.0.split_whitespace().map(InRead::parse_int)
    }
    fn int_vec(self: &mut Self) -> Vec<i32> { self.ints().collect() }
    fn int(self: &mut Self) -> i32 { self.ints().next().unwrap() }
}


use std::io;
use std::str::FromStr;

use std::io::prelude::*;
use std::io::BufReader;
use std::cmp::{max, min};

fn get_line() -> String {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input
}

fn get_vec<T>() -> Vec<T>
where T: FromStr,
      <T as FromStr>::Err: std::fmt::Debug,
{
    get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()
}

const N: i64 = 998_244_353;

fn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        (a, 1, 0)
    } else {
        let (d0, x0, y0) = extended_euclid(b, a % b);
        (d0, y0, x0 - a / b * y0)
    }
}

fn main() {
    let n: usize = get_line().trim().parse().unwrap();
    let a: usize = get_line().trim().parse().unwrap();
    let b: usize = get_line().trim().parse().unwrap();
    let c: usize = get_line().trim().parse().unwrap();

    let min_d = min(min(a,b), c);

    let ans = match n {
        1 => 0,
        _ => min(a, b) + (n - 2) * min_d,
    };

    println!("{}", ans);
}


fn read_int() -> u64 {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed");
    let x = input.trim().parse::<u64>().unwrap();
    x
}

fn main(){
    let n = read_int();
    let a = read_int();
    let b = read_int();
    let c = read_int();

    let mut location = "R";
    let mut dist = 0;
    let mut meals = 1;
    while meals < n{
        let trip = match location {
            "R" => {
                if a < b{
                    location = "O";
                    a
                }else{
                    location = "E";
                    b
                }
            },
            "E" => {
                if c < b{
                    location = "O";
                    c
                }else{
                    location = "R";
                    b
                }
            },
            "O" => {
                if a < c{
                    location = "R";
                    a
                }else{
                    location = "E";
                    c
                }
            },
            _ => {break},
        };
        meals = meals + 1;
        dist = dist + trip;
    }
    println!("{}", dist);
}


fn read_int() -> u64 {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Failed");
    let x = input.trim().parse::<u64>().unwrap();
    input.clear();
    x
}

fn main(){
    let n = read_int();
    let a = read_int();
    let b = read_int();
    let c = read_int();

    let mut location = 0;
    let mut dist = 0;
    let mut meals = 1;
    while meals < n{
        let trip = match location {
            0 => { // rabbit
                if a < b{
                    location = 2;
                    a
                }else{
                    location = 1;
                    b
                }
            },
            1 => { // eeyore
                if c < b{
                    location = 2;
                    c
                }else{
                    location = 0;
                    b
                }
            },
            2 => { // owl
                if a < c{
                    location = 0;
                    a
                }else{
                    location = 1;
                    c
                }
            },
            _ => {break},
        };
        meals = meals + 1;
        dist = dist + trip;
    }
    println!("{}", dist);
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn run() {
    input! {
        x: i64,
        y: i64,
        z: i64,
    }
    let mut ans = 2 * z;
    let v = std::cmp::min(x, y);
    ans += 2 * v;
    if x > v {
        ans += 1;
    }
    if y > v {
        ans += 1;
    }
    println!("{}", ans);
}

fn main() {
    run();
}


fn main() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("input: read line failed");
    let vec = input.trim().split_whitespace().map(|item| {
        item.parse::<usize>().expect("item: parse to usize failed")
    }).collect::<Vec<usize>>();

    let (a_amount, b_amount, ab_amount) = (vec[0], vec[1], vec[2]);

    let length = 2 * ab_amount
        +  2 * min(a_amount, b_amount)
        + if max(a_amount, b_amount) - min(a_amount, b_amount) > 0 { 1 } else { 0 };
    println!("{}", length);

}

fn min(one: usize, another: usize) -> usize {
    if one < another { one } else { another }
}

fn max(one: usize, another: usize) -> usize {
    if one > another { one } else { another }
}


use std::cmp;
use std::fs::File;
use std::io::Read;

// fn pow_speedt_with_mod(mut p: i64, mut q: i64, m: i64) -> i64 {
//     p %= m;
//     let mut r = p;
//     let mut ret: i64 = 1;
//     while q > 0 {
//         ret *= if q % 2 == 1 {r} else {1};
//         r *= r;
//         r %= m;
//         q /= 2;
//         ret %= m;
//     }
//     return ret;
// }

fn main() {
    let inputstatus = 1;

    let mut buf = String::new();
    let filename = "inputrust.txt";

    if inputstatus == 0 {
        let mut f = File::open(filename).expect("file not found");
        f.read_to_string(&mut buf)
            .expect("something went wrong reading the file");
    } else {
        std::io::stdin().read_to_string(&mut buf).unwrap();
    }

    let mut iter = buf.split_whitespace();
    let a: i64 = iter.next().unwrap().parse().unwrap();
    let b: i64 = iter.next().unwrap().parse().unwrap();
    let c: i64 = iter.next().unwrap().parse().unwrap();

    let ans = if a == b {
        a + b + 2 * c
    } else {
        2 * cmp::min(a, b) + 1 + 2 * c
    };

    println!("{}", ans);

    // if p + 1 >= m

    // println!("{}", n);
    // println!("{}", k);
    // println!("{:?}", num);
    // println!("{:?}", cum_num);
}


use std::io;
use std::str;

pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

impl<R: io::BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: vec![],
        }
    }

    pub fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn egcd(a: i64, b: i64) -> (i64, i64, i64) {
    if b == 0 {
        return (a, 1, 0);
    }
    let (g, x1, y1) = egcd(b, a % b);
    (g, y1, x1 - (a / b) * y1)
}

fn ceil_div(num: i64, denom: i64) -> i64 {
    (num + denom - 1).div_euclid(denom)
}

// Check if the diophantine equation a * x + b * y = c has non-negative solutions.
fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
    let a: i64 = scan.token();
    let b: i64 = scan.token();
    let c: i64 = scan.token();
    let (g, xg, yg) = egcd(a, b);
    if c % g == 0 {
        let x0 = xg * c / g;
        let y0 = yg * c / g;
        // xk = x0 + k * b / g
        // yk = y0 - k * a / g
        // xk >= 0 and yk >= 0
        // After solving for k:
        let ans = (y0 * g).div_euclid(a) - ceil_div(-x0 * g, b) + 1;
        if ans > 0 {
            writeln!(out, "Yes").ok();
        } else {
            writeln!(out, "No").ok();
        }
    } else {
        writeln!(out, "No").ok();
    }
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    solve(&mut scan, &mut out);
}


//! https://codeforces.com/contest/633/problem/A

use std::io;

#[derive(Clone, Copy)]
struct Solution(i32, i32);

fn main() {
    let mut inp = String::new();
    io::stdin().read_line(&mut inp).unwrap();
    let mut iter = inp.trim().split_whitespace();
    let a: i32 = iter.next().unwrap().parse().unwrap();
    let b: i32 = iter.next().unwrap().parse().unwrap();
    let c: i32 = iter.next().unwrap().parse().unwrap();

    println!("{}", match find_if_poss(a, b, c) {
        true => "Yes",
        false => "No"
    })
}

fn gcd(a: i32, b: i32) -> (Solution, i32) {
    if a == 0 {
        (Solution(0, 1), b)
    } else {
        let (Solution(x1, y1), g) = gcd(b % a, a);
        (Solution(y1 - (b / a) * x1, x1), g)
    }
}

fn find_one(a: i32, b: i32, c: i32) -> Option<(Solution, i32)> {
    let (Solution(x, y), g) = gcd(a.abs(), b.abs());
    if c % g != 0 {
        None
    } else {
        let mult = c / g;

        let x = get_sign(a) * mult * x;
        let y = get_sign(b) * mult * y;

        Some((Solution(x, y), g))
    }
}

fn get_sign(i: i32) -> i32 {
    if i < 0 { -1 } else { 1 }
}

fn shift_solution(sol: Solution, ag: i32, bg: i32, offset: i32) -> Solution {
    Solution(sol.0 + bg * offset, sol.1 - ag * offset)
}

fn find_if_poss(a: i32, b: i32, c: i32) -> bool {
    match find_one(a, b, c) {
        Some((mut sol, g)) => {
            let sign_a = get_sign(a);
            let sign_b = get_sign(b);

            let maxx = c/a;
            let maxy = c/b;

            let a = a / g;
            let b = b / g;

            let minx_offset = -sol.0/b;
            sol = shift_solution(sol, a, b, minx_offset);
            if sol.0 < 0 {
                sol = shift_solution(sol, a, b, sign_b);
            }
            if sol.0 > maxx {
                return false;
            }
            let lx1 = sol.0;

            let maxx_offset = (maxx - sol.0)/b;
            sol = shift_solution(sol, a, b, maxx_offset);
            if sol.0 > maxx {
                sol = shift_solution(sol, a, b, -sign_b);
            }
            let rx1 = sol.0;

            let miny_offset = sol.1/a;
            sol = shift_solution(sol, a, b, miny_offset);
            if sol.1 < 0 {
                sol = shift_solution(sol, a, b, -sign_a);
            }
            if sol.1 > maxy {
                return false;
            }
            let mut lx2 = sol.0;

            let maxy_offset = (sol.1 - maxy) / a;
            sol = shift_solution(sol, a, b, maxy_offset);
            if sol.1 > maxy {
                sol = shift_solution(sol, a, b, sign_a);
            }
            let mut rx2 = sol.0;

            if lx2 > rx2 {
                let temp = lx2;
                lx2 = rx2;
                rx2 = temp;
            }

            let lx = if lx1 > lx2 { lx1 } else { lx2 };
            let rx = if rx1 < rx2 { rx1 } else { rx2 };

            if lx > rx {
                return false;
            }

            let count = (rx - lx)/b.abs() + 1;

            count > 0
        },
        None => false
    }
}


//spnauti-rust
#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
use std::io::*;
use std::str::*;
use std::fmt::Debug;
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).unwrap();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn vi(&mut self, n: usize) -> Vec<i32> {
        self.vp::<i32>(n)
    }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

fn main() {
    let mut bin = String::new();
    let mut input = WordReader::from_stdin(&mut bin);

    let a = input.i();
    let b = input.i();
    let c = input.i();
    println!("{}", 3 * b.min(a + 1).min(c - 1));
}


#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, StdoutLock, Write};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_macros)]
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }
#[allow(dead_code)]
pub fn with_bufwriter<F: FnOnce(BufWriter<StdoutLock>) -> ()>(f: F) {
    let out = stdout();
    let writer = BufWriter::new(out.lock());
    f(writer)
}
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) } ; }
#[allow(dead_code)]
fn main() {
    input!{
        y: u64,
        b: u64,
        r: u64,
    }
    let mut mr = r;
    let mut mb = r - 1;
    let mut my = r - 2;
    if b < mb {
        my = b - 1;
        mb = b;
        mr = b + 1;
    }
    if y < my {
        my = y;
        mb = y + 1;
        mr = y + 2;
    }
    println!("{}", my + mb + mr);
}


use std::io;

macro_rules! readln {
    () => {{
        use std::io;
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

fn main() {
    let (y, b, r) = readln!(i32, i32, i32);

    let (y1, b1, r1) = (y, y + 1, y + 2);
    let (y2, b2, r2) = (b - 1, b, b + 1);
    let (y3, b3, r3) = (r - 2, r - 1, r);

    if y1 <= y && b1 <= b && r1 <= r {
        println!("{}", y1 + b1 + r1);
    } else if y2 <= y && b2 <= b && r2 <= r {
        println!("{}", y2 + b2 + r2);
    } else {
        println!("{}", y3 + b3 + r3);
    }
}


struct Scan {
    buffer: std::collections::VecDeque<String>,
}

impl Scan {
    fn new() -> Scan {
        Scan {
            buffer: std::collections::VecDeque::new(),
        }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop_front() {
                break token.parse::<T>().ok().unwrap();
            }
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).expect("Fail to read");
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

    fn next_n<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }
}

fn _main() {
    let mut scan = Scan::new();
    let mut nums: Vec<usize> = scan.next_n(3);
    nums[0] = nums[0].min(nums[1] - 1);
    nums[1] = nums[1].min(nums[2] - 1).min(nums[0] + 1);
    nums[2] = nums[2].min(nums[1] + 1);
    nums[0] = nums[0].min(nums[1] - 1);
    println!("{}", nums[0] + nums[1] + nums[2]);
}

fn main() {
    std::thread::Builder::new()
        .stack_size(1 << 23)
        .spawn(_main)
        .unwrap()
        .join()
        .unwrap();
}


#[allow(unused_imports)]
use std::cmp::{min,max};
#[allow(unused_imports)]
use std::collections::{BTreeMap,BTreeSet};
#[allow(unused_imports)]
use std::ops::*;
#[allow(unused_imports)]
use std::collections::BinaryHeap;

#[allow(unused_macros)]
macro_rules! ite {
    ($c:expr, $t:expr, $f:expr) => {{
        if $c { $t } else { $f }
    }};
}

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
#[macro_export]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

#[macro_export]
macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

#[macro_export]
macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        x: i64,
        y: i64,
        z: i64,
    }
    let res = min(min(x+1,y),z-1) * 3;
    println!("{}", res);
}

use std::io::BufRead;
use std::io;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R:BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len,complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len-1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T:str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            }
            else {
                self.update_buf();
            }
        }
    }
}

use std::fmt::Display;
#[allow(dead_code)]
fn write_vec<T: Display>(xs: &Vec<T>) {
    if xs.len() == 0 {
        println!();
        return;
    }
    print!("{}", xs[0]);
    for i in 1..xs.len() {
        print!(" {}", xs[i]);
    }
    println!();
}


use std::io;
use std::str::FromStr;

fn get_nums() -> (usize, usize, usize, usize) {
    let mut input = String::new();

    io::stdin().read_line(&mut input).expect("");

    let v = input
        .trim()
        .split_whitespace()
        .map(|s| usize::from_str(s).unwrap())
        .collect::<Vec<_>>();

    (v[0], v[1], v[2], v[3])
}

fn main() {
    let (a, b, c, d) = get_nums();

    let misha = std::cmp::max(3 * a / 10, a - a / 250 * c);
    let vasya = std::cmp::max(3 * b / 10, b - b / 250 * d);

    if misha > vasya {
        println!("Misha");
    } else if misha < vasya {
        println!("Vasya");
    } else {
        println!("Tie");
    }
}


use std::cmp::Ordering;
use std::io::{self, BufRead};

fn score(p: i32, t: i32) -> i32 {
    std::cmp::max(3 * p / 10, p - p / 250 * t)
}

fn main() {
    let stdin = io::stdin();
    let line = stdin.lock().lines().next().unwrap().unwrap();
    let v: Vec<_> = line.split(" ").map(|x| x.parse::<i32>().unwrap()).collect();
    let (a, b, c, d) = (v[0], v[1], v[2], v[3]);
    let misha = score(a,c);
    let vasya = score(b,d);
    match vasya.cmp(&misha) {
        Ordering::Greater => println!("Vasya"),
        Ordering::Equal => println!("Tie"),
        Ordering::Less => println!("Misha"),
    }
}


//spnauti-rust
use std::io::*;
use std::str::*;
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::*;
#[allow(unused_imports)] use std::collections::*;

#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).ok();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn vi(&mut self, n: usize) -> Vec<i32> {
        self.vp::<i32>(n)
    }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

#[allow(dead_code)]
fn build_counting_hashmap<K: Eq + std::hash::Hash, T>(i: T) -> HashMap<K,usize>
    where T: Iterator<Item = K> {
    let mut m = HashMap::new();
    for k in i {
        let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };
        m.insert(k, n);
    }
    m
}

fn main() {
    let mut bin = String::new();
    let mut input = WordReader::from_stdin(&mut bin);

    let a = input.i();
    let b = input.i();
    let c = input.i();
    let d = input.i();
    println!("{}", match ((a * 3 / 10).max(a - a/250 * c)).cmp(&(b * 3 / 10).max(b - b/250 * d)) {
        Greater => "Misha",
        Less => "Vasya",
        Equal => "Tie",
    });
}


#[allow(unused_imports)]
use std::cmp::{max,min,Ordering};
#[allow(unused_imports)]
use std::collections::{HashMap,HashSet,VecDeque};

#[allow(unused_macros)]
macro_rules! readln {
    () => {{
        use std::io;

        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

#[allow(unused_macros)]
macro_rules! readvec {
    ( $t:ty ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        let mut result = Vec::new();
        for elem in input {
            result.push(elem.parse::<$t>().unwrap());
        }
        result
    }}
}

fn solve(a: i64, t: i64) -> i64 {
  return max((a*3)/10,a-(a/250)*t);
}

fn main() {
  let (a,b,c,d) = readln!(i64,i64,i64,i64);
  let p1 = solve(a,c);
  let p2 = solve(b,d);
  println!("{}",if p1 < p2 { "Vasya" } else if p1 > p2 { "Misha" } else { "Tie" });
}


// https://codeforces.com/problemset/problem/515/C
use std::io;
use std::collections::HashMap;

fn main() {
    let mut n = String::new();

    io::stdin()
        .read_line(&mut n)
        .unwrap();

    let _n: i64 = n.trim().parse().unwrap();

    let mut line = String::new();

    io::stdin()
        .read_line(&mut line)
        .unwrap();

    let line = line.trim();

    let mut a: Vec<char> = line.chars().collect();

    a.sort();
    a.reverse();

    let mut translate = HashMap::new();

    translate.insert('0',"");
    translate.insert('1',"");
    translate.insert('2',"2");
    translate.insert('3',"3");
    translate.insert('4',"322");
    translate.insert('5',"5");
    translate.insert('6',"53");
    translate.insert('7',"7");
    translate.insert('8',"7222");
    translate.insert('9',"7332");

    let mut ans = String::from("");

    for ch in a {
        //print!("{}", translate.get(&ch).unwrap());
        ans.push_str(translate.get(&ch).unwrap());
    }
    let mut fin: Vec<char> = ans.chars().collect();
    fin.sort();
    fin.reverse();
    println!("{}", fin.into_iter().collect::<String>());
}


// ---------- begin input macro ----------
// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
// ---------- end input macro ----------

fn run() {
    input! {
        _n: usize,
        s: bytes,
    }
    let mut cnt = vec![0; 4];
    let p = [2, 3, 5, 7];
    for c in s {
        let k = (c - b'0') as usize;
        match k {
            2 => cnt[0] += 1,
            3 => cnt[1] += 1,
            4 => {
                cnt[0] += 2;
                cnt[1] += 1;
            },
            5 => cnt[2] += 1,
            6 => {
                cnt[2] += 1;
                cnt[1] += 1;
            },
            7 => cnt[3] += 1,
            8 => {
                cnt[3] += 1;
                cnt[0] += 3;
            },
            9 => {
                cnt[3] += 1;
                cnt[1] += 2;
                cnt[0] += 1;
            },
            _ => (),
        }
    }
    for (p, c) in p.iter().zip(cnt.iter()).rev() {
        for _ in 0..*c {
            print!("{}", *p)
        }
    }
    println!();
}

fn main() {
    run();
}


#[allow(unused_imports)]
use std::cmp::{max,min};
#[allow(unused_imports)]
use std::collections::{HashMap,HashSet,VecDeque};

#[allow(unused_macros)]
macro_rules! readln {
    () => {{
        use std::io;

        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim().to_string()
    }};
    ( $t:ty ) => {{
        let input = readln!();
        input.parse::<$t>().unwrap()
    }};
    ( $( $t:ty ),+ ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        (
            $(
                input.next().unwrap().parse::<$t>().unwrap(),
            )+
        )
    }}
}

#[allow(unused_macros)]
macro_rules! readvec {
    ( $t:ty ) => {{
        let input = readln!();
        let mut input = input.split_whitespace();
        let mut result = Vec::new();
        for elem in input {
            result.push(elem.parse::<$t>().unwrap());
        }
        result
    }}
}

fn main() {
  readln!();
  let mut s = readln!();
  let mut v = s.into_bytes();
  v.sort();
  v = v.iter().map(|c|c-('0' as u8)).collect();
  let mut f = vec![0;10];
  v.iter().map(|x|for i in (2..(x+1)) {
    f[i as usize] += 1;
  }).count();
  f[2] += 2*f[4];
  f[4] = 0;
  f[2] += f[6];
  f[3] += f[6];
  f[6] = 0;
  f[2] += 3*f[8];
  f[8] = 0;
  f[3] += 2*f[9];
  f[9] = 0;
  let mut res = String::new();
  while f[7] > 0 {
    res.push('7');
    f[7] -= 1;
    f[2] -= 1; f[3] -= 1;
    f[5] -= 1;
    f[2] -= 2;
    f[3] -= 1;
    f[2] -= 1;
  }
  while f[5] > 0 {
    res.push('5');
    f[5] -= 1;
    f[2] -= 2;
    f[3] -= 1;
    f[2] -= 1;
  }
  while f[3] > 0 {
    res.push('3');
    f[3] -= 1;
    f[2] -= 1;
  }
  while f[2] > 0 {
    res.push('2');
    f[2] -= 1;
  }
  println!("{}",res);
}