There is a binary string $$$t$$$ of length $$$10^{100}$$$, and initally all of its bits are $$$\texttt{0}$$$. You are given a binary string $$$s$$$, and perform the following operation some times:   Select some substring of $$$t$$$, and replace it with its XOR with $$$s$$$.$$$^\dagger$$$  After several operations, the string $$$t$$$ has exactly two bits $$$\texttt{1}$$$; that is, there are exactly two distinct indices $$$p$$$ and $$$q$$$ such that the $$$p$$$-th and $$$q$$$-th bits of $$$t$$$ are $$$\texttt{1}$$$, and the rest of the bits are $$$\texttt{0}$$$. Find the lexicographically largest$$$^\ddagger$$$ string $$$t$$$ satisfying these constraints, or report that no such string exists.$$$^\dagger$$$ Formally, choose an index $$$i$$$ such that $$$0 \leq i \leq 10^{100}-|s|$$$. For all $$$1 \leq j \leq |s|$$$, if $$$s_j = \texttt{1}$$$, then toggle $$$t_{i+j}$$$. That is, if $$$t_{i+j}=\texttt{0}$$$, set $$$t_{i+j}=\texttt{1}$$$. Otherwise if $$$t_{i+j}=\texttt{1}$$$, set $$$t_{i+j}=\texttt{0}$$$.$$$^\ddagger$$$ A binary string $$$a$$$ is lexicographically larger than a binary string $$$b$$$ of the same length if in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a bit $$$\texttt{1}$$$ and the corresponding bit in $$$b$$$ is $$$\texttt{0}$$$.

The only line of each test contains a single binary string $$$s$$$ ($$$1 \leq |s| \leq 35$$$).

If no string $$$t$$$ exists as described in the statement, output -1. Otherwise, output the integers $$$p$$$ and $$$q$$$ ($$$1 \leq p < q \leq 10^{100}$$$) such that the $$$p$$$-th and $$$q$$$-th bits of the lexicographically maximal $$$t$$$ are $$$\texttt{1}$$$.

NoteIn the first test, you can perform the following operations. $$$$$$\texttt{00000}\ldots \to \color{red}{\texttt{1}}\texttt{0000}\ldots \to \texttt{1}\color{red}{\texttt{1}}\texttt{000}\ldots$$$$$$In the second test, you can perform the following operations. $$$$$$\texttt{00000}\ldots \to \color{red}{\texttt{001}}\texttt{00}\ldots \to \texttt{0}\color{red}{\texttt{011}}\texttt{0}\ldots$$$$$$In the third test, you can perform the following operations. $$$$$$\texttt{00000}\ldots \to \color{red}{\texttt{1111}}\texttt{0}\ldots \to \texttt{1}\color{red}{\texttt{0001}}\ldots$$$$$$It can be proven that these strings $$$t$$$ are the lexicographically largest ones.In the fourth test, you can't make a single bit $$$\texttt{1}$$$, so it is impossible.

// 長さ10^100 な文字列Tがある、最初全部0
// 文字列S が与えられる
// S を T のどこかにxorするみたいなことができる
// 1が二つとなるように操作する時出来上がるTの辞書順最大を求めて
//
// |S| <= 35
//
// なんかサンプル4ですごい数が出てきてる
//
// 不可能な場合って何？
// 0のみ、不可能
// それ以外で不可能な場合は？
// わからん
// 1一つ, 2つ
// 詰めて置けばいい
// ３つ以上？
// 最初の1は確定する
// というの最初を使うと最初の１は確定するし、使わないで得られた答えはスライドさせてより大きくできる
// 残った部分になんかxorしていく感じ
// やれることが前からxorしていくことしかないが
//
// S の最初、最後の0を削っておく
// なんかコンパニオン行列をかけまくって (0, 0, ..., 1) になる最小の数
// みたいな問題になる
// 線形代数ゲー？ようわからん
// S の1文字目の1を削ったやつをs, 単位ベクトルをe_i と置く
// k = |S| - 1 として
//
// s * mat [s, e_1, .., e_{k - 1}] ^n = e_k
//
// となるようなn の最小値、ないならそれ報告
// 離散対数？
// ちょっと間に合わない感
// いや2^18 程度なら間に合ってもいいんじゃ
// 間に合ってもいい気はするがなんか BS-GS に持ち込めない
// 上の前処理すると A は逆行列を持つようになる
//
// s A^n = e_k
// s A^(qx + r) = e_k
// s A^(qx) = e_k A^(-r)
// これはいけそう
//
// ところで、最小性が問題になるが
// まあなんとかなるでしょ多分

use std::collections::*;
use std::io::Write;

type Map<K, V> = BTreeMap<K, V>;
type Set<T> = BTreeSet<T>;
type Deque<T> = VecDeque<T>;

fn run(mut s: Vec<u8>) -> Option<(usize, usize)> {
    s.iter_mut().for_each(|s| *s -= b'0');
    let c = s.iter().filter(|s| **s == 1).count();
    if c == 0 {
        return None;
    }
    let f = s.iter().position(|s| *s == 1).unwrap();
    if c == 1 {
        return Some((f, f + 1));
    }
    let mut s = s;
    s.drain(..=f);
    while s.last().map_or(false, |c| *c == 0) {
        s.pop();
    }
    let s = s;
    let k = s.len();
    let mut a = vec![vec![0u8; k]; k];
    for (i, s) in s.iter().enumerate() {
        a[0][i] = *s;
    }
    for i in 1..k {
        a[i][i - 1] = 1;
    }
    let inv_a = inverse_matrix(a.clone()).unwrap();
    let mut right = vec![0; k];
    right[k - 1] = 1u8;
    let sq = 1 << (k / 2 + 1);
    let mut map = Map::new();
    for i in 0..=sq {
        map.entry(right.clone()).or_insert(i);
        let mut next = vec![0; k];
        for (right, inv_a) in right.iter().zip(inv_a.iter()) {
            for (next, inv_a) in next.iter_mut().zip(inv_a.iter()) {
                *next ^= *right & *inv_a;
            }
        }
        right = next;
    }
    let mul = |a: &[Vec<u8>], b: &[Vec<u8>]| -> Vec<Vec<u8>> {
        let mut c = vec![vec![0; k]; k];
        for (c, a) in c.iter_mut().zip(a.iter()) {
            for (a, b) in a.iter().zip(b.iter()) {
                for (c, b) in c.iter_mut().zip(b.iter()) {
                    *c ^= *a & *b;
                }
            }
        }
        c
    };
    let mut mat = vec![vec![0; k]; k];
    for i in 0..k {
        mat[i][i] = 1;
    }
    for i in (0..20).rev() {
        mat = mul(&mat, &mat);
        if sq >> i & 1 == 1 {
            mat = mul(&mat, &a);
        }
    }
    let rad = mat;
    let mut mat = vec![vec![0; k]; k];
    for i in 0..k {
        mat[i][i] = 1;
    }
    for i in 0..=sq {
        let mut b = vec![0; k];
        for (s, mat) in s.iter().zip(mat.iter()) {
            for (b, mat) in b.iter_mut().zip(mat.iter()) {
                *b ^= *s & *mat;
            }
        }
        if let Some(v) = map.get(&b) {
            return Some((f, sq * i + v + f + k));
        }
        mat = mul(&mat, &rad);
    }
    None
}

fn inverse_matrix(mut mat: Vec<Vec<u8>>) -> Option<Vec<Vec<u8>>> {
    let n = mat.len();
    assert!(mat.iter().all(|mat| mat.len() == n));
    for (i, mat) in mat.iter_mut().enumerate() {
        mat.resize(2 * n, 0);
        mat[n + i] = 1;
    }
    for i in 0..n {
        let x = (i..n).find(|x| mat[*x][i] != 0)?;
        mat.swap(i, x);
        let a = std::mem::take(&mut mat[i]);
        for mat in mat.iter_mut().filter(|mat| !mat.is_empty()) {
            let mul = mat[i];
            for (mat, a) in mat[i..].iter_mut().zip(a[i..].iter()) {
                *mat ^= mul & *a;
            }
        }
        mat[i] = a;
    }
    Some(mat.iter().map(|a| Vec::from(&a[n..])).collect())
}

fn main() {
    input! {
        s: bytes,
    }
    if let Some((a, b)) = run(s) {
        println!("{} {}", a + 1, b + 1);
    } else {
        println!("-1");
    }
}

// ---------- begin input macro ----------
// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
#[macro_export]
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_export]
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_export]
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 ----------


A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≤ i ≤ n) such that pi = i.Your task is to count the number of almost identity permutations for given numbers n and k.

The first line contains two integers n and k (4 ≤ n ≤ 1000, 1 ≤ k ≤ 4).

Print the number of almost identity permutations for given n and k.

#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, BinaryHeap};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_imports)]
use std::io::stdin;

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 main() {
    let (n, k) = get!(u64, u64);

    let mut ans = 1;

    if k > 1 {
        for i in 2..k + 1 {
            let u = (n - i + 1..n + 1).fold(1, |a, b| a * b);
            let d = (1..i + 1).fold(1, |a, b| a * b);

            let c = u / d;

            ans += c * [1, 2, 9][(i - 2) as usize];
        }
    }

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

fn main() {
    let v: Vec<i64> = vec![1,0,1,2,9];
    let mut ri = ReadIn::new();
    let tp = ri.int2();
    let mut ans:i64 = 1;
    for kk in 2..tp.1+1 {
        ans += cal(tp.0 as i64, kk as i64) * v[(kk as usize)] ;
    }
    println!("{}", ans)
}

fn cal(n: i64, k: i64) -> i64{
    let mut up: i64 = 1;
    let mut down: i64 = 1;
    for kk in 0..k {
        up = up * (n - kk);
        down = down * (1 + kk);
    }
    up / down
}

use std::iter::Map;
use std::str::SplitWhitespace;
use std::io::stdin;
use std::mem::forget;

pub struct ReadIn(pub String);

impl ReadIn {
    pub fn new() -> ReadIn {
        ReadIn(String::new())
    }
    fn read_i32(s: &str) -> i32 {
        s.parse().unwrap()
    }
    pub fn read_line(&mut self) {
        self.0.clear();
        forget(stdin().read_line(&mut self.0));
    }
    pub fn ints(&mut self) -> Map<SplitWhitespace, fn(&str) -> i32> {
        self.read_line();
        self.0.split_whitespace().map(ReadIn::read_i32)
    }
    pub fn int(&mut self) -> i32 {
        self.ints().next().unwrap()
    }
    pub fn int2(&mut self) -> (i32, i32) {
        let mut it = self.ints();
        (it.next().unwrap(), it.next().unwrap())
    }
}


Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.

The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.

Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO". Remember, that each plate must touch the edge of the table.

NoteThe possible arrangement of the plates for the first sample is:

#[allow(unused_imports)]
use std::io::{stdin, Read, StdinLock};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::str::FromStr;
#[allow(unused_imports)]
use std::collections::{HashSet, HashMap};
#[allow(unused_imports)]
use std::vec::Vec;

#[allow(dead_code)]
const INF: i32 = 1000_000_000;
#[allow(dead_code)]
const INFLL: i64 = 1000_000_000_000_000_000;

struct Scanner<'a> {
    cin: StdinLock<'a>,
}

impl<'a> Scanner<'a> {
    #[allow(dead_code)]
    fn new(cin: StdinLock<'a>) -> Scanner<'a> {
        Scanner {cin: cin}
    }

    #[allow(dead_code)]
    fn read1<T: FromStr>(&mut self) -> Option<T> {
        let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
                    .skip_while(|c| c.is_whitespace())
                    .take_while(|c| !c.is_whitespace())
                    .collect::<String>();
        token.parse::<T>().ok()
    }

    #[allow(dead_code)]
    fn read<T: FromStr>(&mut self) -> T {
        self.read1().unwrap()
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin);
    let n: i32 = sc.read();
    let r1: f64 = sc.read();
    let r2: f64 = sc.read();
    if n > 1 {
        let theta = std::f64::consts::PI / (n as f64);
        let mr: f64 = r1 * theta.sin() / (1.0 + theta.sin());
        //println!("{} <-> {}", mr, r2);
        match r2 <= mr + 0.0000000001 {
            false => println!("NO"),
            _                 => println!("YES"),
        }
    } else {
        if r2 <= r1 {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contest started and Vasya submitted the problem d minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs p points t minutes after the contest started, you get  points. Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.

The first line contains four integers a, b, c, d (250 ≤ a, b ≤ 3500, 0 ≤ c, d ≤ 180).  It is guaranteed that numbers a and b are divisible by 250 (just like on any real Codeforces round).

Output on a single line:  "Misha" (without the quotes), if Misha got more points than Vasya. "Vasya" (without the quotes), if Vasya got more points than Misha. "Tie" (without the quotes), if both of them got the same number of points.

//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" });
}

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"),
    }
}

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::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 / 250 * c);
    let vasya = std::cmp::max(3 * b / 10, b / 250 * d);

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


Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.Neko has two integers $$$a$$$ and $$$b$$$. His goal is to find a non-negative integer $$$k$$$ such that the least common multiple of $$$a+k$$$ and $$$b+k$$$ is the smallest possible. If there are multiple optimal integers $$$k$$$, he needs to choose the smallest one.Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?

The only line contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

Print the smallest non-negative integer $$$k$$$ ($$$k \ge 0$$$) such that the lowest common multiple of $$$a+k$$$ and $$$b+k$$$ is the smallest possible. If there are many possible integers $$$k$$$ giving the same value of the least common multiple, print the smallest one.

NoteIn the first test, one should choose $$$k = 2$$$, as the least common multiple of $$$6 + 2$$$ and $$$10 + 2$$$ is $$$24$$$, which is the smallest least common multiple possible.

use std::io;

fn gcd(mut u: u64, mut v: u64) -> u64 {
    if u == 0 {
        return v;
    }
    if v == 0 {
        return u;
    }

    let mut shift = 0;
    let mut aux : [u64; 2] = [(u | v), 1];
    while aux[0] & aux[1] == 0 {
        shift += 1;
        aux[1] <<= 1;
    }
    u >>= shift;
    v >>= shift;

    while u & 1 == 0 {
        u >>= 1;
    }

    loop {
        while v & 1 == 0 {
            v >>= 1;
        }

        if u > v {
            aux[0] = v;
            v = u;
            u = aux[0];
        }
        v -= u;

        if v == 0 {
            break;
        }
    }
    u << shift
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("failed to read input");
    let mut input_iter = input.split_whitespace();
    let a = input_iter.next().unwrap().parse::<u64>().unwrap();
    let b = input_iter.next().unwrap().parse::<u64>().unwrap();

    let md = if a > b { a - b } else { b - a };
    let sqrt_md = (md as f64).sqrt() as u64 + 1;
    let mut lcm_min = 4 * a * b;
    let mut min_k = 0;
    let mut vec = Vec::new();
    for i in (1..=sqrt_md).filter(|x| md % x == 0) {
        vec.push(md / i);

        let mut k = a % i;
        if k != 0 {
            k = i - k;
        }

        let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));
        if lcm < lcm_min {
            lcm_min = lcm;
            min_k = k;
        }
    }
    if md != 0 {
        for i in vec {
            let mut k = a % i;
            if k != 0 {
                k = i - k;
            }

            let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));
            if lcm < lcm_min {
                lcm_min = lcm;
                min_k = k;
            }
        }
    }

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

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("failed to read input");
    let mut input_iter = input.split_whitespace();
    let a = input_iter.next().unwrap().parse::<u32>().unwrap();
    let b = input_iter.next().unwrap().parse::<u32>().unwrap();

    let md = if a > b { a - b } else { b - a };
    let mut k = a % md;
    if k != 0 {
        k = md - k;
    }

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

use std::io;

fn gcd(mut u: u32, mut v: u32) -> u32 {
    if u == 0 {
        return v;
    }
    if v == 0 {
        return u;
    }

    let mut shift = 0;
    let mut aux : [u32; 2] = [(u | v), 1];
    while aux[0] & aux[1] == 0 {
        shift += 1;
        aux[1] <<= 1;
    }
    u >>= shift;
    v >>= shift;

    while u & 1 == 0 {
        u >>= 1;
    }

    loop {
        while v & 1 == 0 {
            v >>= 1;
        }

        if u > v {
            aux[0] = v;
            v = u;
            u = aux[0];
        }
        v -= u;

        if v == 0 {
            break;
        }
    }
    u << shift
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("failed to read input");
    let mut input_iter = input.split_whitespace();
    let a = input_iter.next().unwrap().parse::<u32>().unwrap();
    let b = input_iter.next().unwrap().parse::<u32>().unwrap();

    let md = if a > b { a - b } else { b - a };
    let sqrt_md = (md as f64).sqrt() as u32 + 1;
    let mut lcm_min = 4 * a * b;
    let mut min_k = 0;
    let mut vec = Vec::new();
    for i in (1..=sqrt_md).filter(|x| md % x == 0) {
        vec.push(md / i);

        let mut k = a % i;
        if k != 0 {
            k = i - k;
        }

        let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));
        if lcm < lcm_min {
            lcm_min = lcm;
            min_k = k;
        }
    }
    if md != 0 {
        for i in vec {
            let mut k = a % i;
            if k != 0 {
                k = i - k;
            }

            let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));
            if lcm < lcm_min {
                lcm_min = lcm;
                min_k = k;
            }
        }
    }

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


Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.

The first line contains four space-separated integers s1, s2, s3, s4 (1 ≤ s1, s2, s3, s4 ≤ 109) — the colors of horseshoes Valera has. Consider all possible colors indexed with integers.

Print a single integer — the minimum number of horseshoes Valera needs to buy.

//! http://codeforces.com/contest/228/problem/A

fn main() {
  use std::io;
  let mut buf = String::new();
  io::stdin().read_line(&mut buf).unwrap();
  let mut ns: Vec<u32> = buf.split(" ")
    .map(|str| str.trim().parse::<u32>().unwrap())
    .collect();
  ns.sort();
  let mut last = 0;
  let mut shoes = 0;
  for n in ns {
    if n != last { shoes += 1; last = n; }
  }
  println!("{}", 4 - shoes);
}

#[allow(unused)] use std::io::*;
#[allow(unused)] use std::collections::*;
#[allow(unused)] use std::mem::*;
#[allow(unused)] use std::num::*;
#[allow(unused)] use std::cmp::*;
#[allow(unused)] use std::thread::*;
#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{
    let mut inp = String::new(); stdin().read_line(&mut inp).ok();
    let s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).collect();
    let mut cnt : usize = 0;
    fn next<T>(cnt: &mut usize, p: &Vec<&str>) -> T where T:std::str::FromStr
    { *cnt += 1; p[*cnt-1].parse().ok().unwrap() }
    ($(next::<$x>(&mut cnt, &s)), +)
    }}; }
#[allow(unused)] macro_rules! arr { ($($n:expr, $T:ty), +) => {{
    let mut inp = String::new(); stdin().read_line(&mut inp).ok();
    let mut s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0);
    ($({let mut v = Vec::new(); v.reserve(($n) as usize);
        for _ in 0..$n { let t = s.next(); if t == None { break; }
        v.push(t.unwrap().parse::<$T>().unwrap()); } v }),+)
    }}; }
///////////////////////////////////////////////////////////////////////////////

fn main()
{
    let mut a = arr!(4usize, i32);
    a.sort_by(|x, y| x.cmp(&y));
    println!("{}", (1..4).filter(|&x| a[x] == a[x-1]).count());
}

fn input_split() -> Vec<u64> {
    let mut buf = String::with_capacity(7);
    std::io::stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|elem| elem.parse().unwrap())
        .collect()
}

fn main() {
    let mut shoes = input_split();
    shoes.sort_unstable();
    shoes.dedup();
    println!("{}", 4 - shoes.len());
}

//spnauti-rust
struct WordReader {
    it : std::vec::IntoIter<String>,
}
#[allow(dead_code)]
impl WordReader {
    fn new<T: std::io::Read>(mut reader: T) -> WordReader {
        let mut s = String::new();
        reader.read_to_string(&mut s).unwrap();
        WordReader { it : s
            .split_ascii_whitespace()
            .map(String::from).collect::<Vec<_>>()
            .into_iter()
        }
    }
    fn from_stdin() -> WordReader {
        WordReader::new(std::io::stdin())
    }
    fn s(&mut self) -> String {
        self.it.next().unwrap()
    }
    fn ab(&mut self) -> Vec<u8> {
        self.it.next().unwrap().into_bytes()
    }
    fn i(&mut self) -> i32 {
        self.it.next().unwrap().parse().unwrap()
    }
    fn ai(&mut self, n: usize) -> Vec<i32> {
        let mut a = Vec::with_capacity(n);
        for _ in 0..n { a.push(self.i()); }
        a
    }
}

fn main() {
    let mut input = WordReader::from_stdin();
    let mut a = input.ai(4);
    a.sort();
    a.dedup();
    let sol = 4 - a.len();
    println!("{}", sol);
}

#[allow(unused_imports)]
use std::cmp::{min,max};
use std::collections::{*};
use std::io::{BufWriter, stdin, stdout, Write};
const BITS: usize = 19;

#[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();
        }
    }
}

fn main() {
    let mut scanner = Scanner::default();
    let mut s: BTreeSet<u64> = BTreeSet::new();
    for i in 1..=4 {
    	s.insert(scanner.next());
    }
    println!["{}", 4 - s.len()];
}

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

fn main() {
    let stdin = io::stdin();
    let mut iterator = stdin.lock().lines();

    let line = iterator.next().unwrap().unwrap();
    let colors: Vec<&str> = line
        .split_whitespace()
        .collect();

    let unique: HashSet<_> = colors.iter().cloned().collect();

    let unique_count: i32 = unique.len() as i32;
    println!("{}", (unique_count-4).abs());
}

use std::collections::HashSet;
use std::io::stdin;

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

    let line: Vec<i32> = line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let mut lista_sin_repetidos = HashSet::new();

    for i in line {
        lista_sin_repetidos.insert(i);
    }

    println!("{}", 4 - lista_sin_repetidos.len());
}

// {{{ by shik

use std::io;

#[allow(dead_code)]
fn gets() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

#[allow(unused_macros)]
macro_rules! R {
    ( $ty:ty, ... ) => {
        gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::<Vec<_>>()
    };
    ( $($ty:ty),* ) => {{
        let line = gets();
        let mut it = line.split_whitespace();
        ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )
    }}
}

#[allow(unused_macros)]
macro_rules! W {
    ( $x:expr ) => {{
        println!("{}", $x);
    }};
    ( $x:expr, $($xs:expr),* ) => {{
        print!("{} ", $x);
        W!($($xs),*);
    }}
}

#[allow(unused_macros)]
macro_rules! join {
    ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }
}

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

// }}}

fn main() {
    let mut ns = R!(usize, ...);
    ns.sort();
    ns.dedup();
    println!("{}", 4 - ns.len());
}

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

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

// -----------------------------------------------

#[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)]
        $(writeln!(stderr(), "{} = {:?}", stringify!($arg), $arg).unwrap());*
    };
}

#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    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
// -----------------------------------------------

fn main() {
    let input = rl();

    let mut s = HashSet::new();

    input
        .split(" ")
        .for_each(|t| {
            s.insert(t);
        });

    println!("{}", 4-s.len());

	return;
}

use std::collections::HashSet;
use std::io::*;

fn reads<T: std::str::FromStr>(i: &mut StdinLock) -> Vec<T> {
    let mut s = String::new();
    i.by_ref().read_line(&mut s).ok();
    s.trim()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn main() {
    // initialize stdin
    let sin = std::io::stdin();
    let mut sin = sin.lock();
    let sin = &mut sin;
    let input: Vec<u64> = reads(sin);

    let mut set = HashSet::new();

    for c in input {
        set.insert(c);
    }

    println!("{}", 4 - set.len());
}

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

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_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 read_i64(stdin: &Stdin) -> i64 {
    let mut line = String::new();
    read_line(&stdin, &mut line);
    match line.trim().parse() {
        Ok(i) => i,
        Err(e) => {
            panic!("Could not read i64!");
        }
    }
}

fn main() {
    let stdin = io::stdin();
    let mut v:Vec<i64>= vec![];
    read_ts(&stdin, &mut v);
    let mut hs = HashSet::new();
    for i in v {
        hs.insert(i);
    }
    println!("{}", 4 - hs.len());
}

// https://codeforces.com/problemset/problem/228/A
use std::io;
use std::collections::HashSet;

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

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

    let words: Vec<i64> =
        line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let mut horseshoes = HashSet::new();

    for item in words {
        horseshoes.insert(item);
    }

    println!("{}", 4-horseshoes.len());

}

use std::io::{self, prelude::*};

#[allow(unused_must_use)]
#[allow(unused_assignments)]
#[allow(unused_variables)]
fn solve<B: BufRead, W: Write>(mut scan: Scanner<B>, mut w: W) {
    let mut input: Vec<i64> = scan.get_vector(4);

    input.sort();
    input.dedup();
    let ans: usize = 4 -input.len();

    writeln!(w, "{}", ans);
}

fn main() {
    let stdin = io::stdin();
    let stdout = io::stdout();
    let reader = Scanner::new(stdin.lock());
    let writer = io::BufWriter::new(stdout.lock());
    solve(reader, writer);
}
#[allow(dead_code)]
fn vector_to_str<T: ToString>(vector: &Vec<T>, separator: &str) -> String {
    use std::fmt::Write;
    let mut ans = String::new();
    for line in vector.iter() {
        write!(&mut ans, "{}{}", line.to_string(), separator).unwrap();
    }
    ans
}
#[allow(dead_code)]
fn matrix_to_str<T: ToString>(matrix: &Vec<Vec<T>>, separator: &str) -> String {
    use std::fmt::Write;
    let mut ans = String::new();
    for line in matrix.iter() {
        for elem in line.iter() {
            write!(&mut ans, "{}{}", elem.to_string(), separator).unwrap();
        }
        write!(&mut ans, "\n").unwrap();
    }
    ans
}
pub struct Scanner<B> {
    reader: B,
    buf_str: Vec<u8>,
    buf_iter: std::str::SplitWhitespace<'static>,
}
impl<B: BufRead> Scanner<B> {
    pub fn new(reader: B) -> Self {
        Self {
            reader,
            buf_str: Vec::new(),
            buf_iter: "".split_whitespace()
        }
    }
    pub fn token<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader.read_until(b'\n', &mut self.buf_str).expect("Failed read");
            self.buf_iter = unsafe {
                let slice = std::str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_whitespace()) }
        }
    }
    pub fn get_matrix<T: std::str::FromStr>(&mut self, m: usize, n: usize) -> Vec<Vec<T>> {
        // m rows and n columns
        let mut ans: Vec<Vec<T>> = Vec::with_capacity(m);
        for i in 0..m {
            ans.push(Vec::with_capacity(n));
            for _ in 0..n {
                ans[i].push(self.token::<T>());
            }
        }
        ans
    }
    pub fn get_vector<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        let mut ans: Vec<T> = Vec::with_capacity(n);
        for _ in 0..n {
            ans.push(self.token::<T>());
        }
        ans
    }
}

use std::str::FromStr;

fn read_str() -> String {
    let mut buffer: String = String::new();
    std::io::stdin().read_line(&mut buffer).expect("Error");
    buffer.trim().to_string()
}

fn read_hash<T: FromStr + std::cmp::Eq + std::hash::Hash>() -> std::collections::HashSet<T> {
    read_str()
        .split_whitespace()
        .map(|value| value.parse::<T>().ok().expect("Error"))
        .collect()
}

fn main() {
    let shoes: std::collections::HashSet<u32> = read_hash();
    print!("{}", 4 - shoes.len());
}

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 main() {
    let mut scan = Scan::new();
    let a: usize = scan.next();
    let b: usize = scan.next();
    let c: usize = scan.next();
    let d: usize = scan.next();
    let eq: [bool;3]  = [a==b || a==c || a==d, b==c || b==d, c==d];
    let result: usize = eq.iter().map(|&x| (x as usize))
        .fold(0,|sum, x| sum+x);
    println!("{}", result);
}

use std::collections::BTreeSet;
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_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 main() {
    let stdin = io::stdin();
    let mut cols : Vec<u64> = vec![];
    read_ts(&stdin, &mut cols);
    let mut distinct_cols = BTreeSet::new();
    for c in cols {
        distinct_cols.insert(c);
    }
    println!("{}", 4 - distinct_cols.len());
}

use std::collections::HashSet;

fn main() {
    let a: HashSet<u32> = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let ws = buf.split_whitespace();
        ws.map(|c| c.parse().unwrap()).collect()
    };

    println!("{}", 4 - a.len());
}

fn readln() -> Vec<i32> {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line.split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect()
}
fn main() {
    let mut colors = readln();
    colors.sort();

    let mut ans = 0;

    for i in 1..4 {
        if colors[i - 1] == colors[i] {
            ans += 1;
        }
    }

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

fn main() {
	let mut inp = String::new();
	std::io::stdin().read_line(&mut inp).unwrap();
	let inp: Vec<i32> = inp
		.split_whitespace()
		.map(|x| x.parse::<i32>().unwrap())
		.collect();

	let mut exist: Vec<i32> = vec![];
	let mut ans = 0;
	for i in inp {
		if exist.contains(&i) {
			ans += 1;
		} else {
			exist.push(i);
		}
	}
	println!("{}", ans);
}

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

#[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();
        }
    }
}

fn main() {
    let mut scan = Scanner::default();
    let out = &mut BufWriter::new(stdout());

	let n = 4;
    let mut p = (0..n).map(|_| scan.next::<u64>()).collect::<Vec<u64>>();
    p.sort();
    p.dedup();

    writeln!(out, "{}", n - p.len()).expect("fail");
}


There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers.There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulting segment will have the same number of odd and even integers.Cuts separate a sequence to continuous (contiguous) segments. You may think about each cut as a break between two adjacent elements in a sequence. So after cutting each element belongs to exactly one segment. Say, $$$[4, 1, 2, 3, 4, 5, 4, 4, 5, 5]$$$ $$$\to$$$ two cuts $$$\to$$$ $$$[4, 1 | 2, 3, 4, 5 | 4, 4, 5, 5]$$$. On each segment the number of even elements should be equal to the number of odd elements.The cost of the cut between $$$x$$$ and $$$y$$$ numbers is $$$|x - y|$$$ bitcoins. Find the maximum possible number of cuts that can be made while spending no more than $$$B$$$ bitcoins.

First line of the input contains an integer $$$n$$$ ($$$2 \le n \le 100$$$) and an integer $$$B$$$ ($$$1 \le B \le 100$$$) — the number of elements in the sequence and the number of bitcoins you have. Second line contains $$$n$$$ integers: $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 100$$$) — elements of the sequence, which contains the equal number of even and odd numbers

Print the maximum possible number of cuts which can be made while spending no more than $$$B$$$ bitcoins.

NoteIn the first sample the optimal answer is to split sequence between $$$2$$$ and $$$5$$$. Price of this cut is equal to $$$3$$$ bitcoins.In the second sample it is not possible to make even one cut even with unlimited number of bitcoins.In the third sample the sequence should be cut between $$$2$$$ and $$$3$$$, and between $$$4$$$ and $$$5$$$. The total price of the cuts is $$$1 + 1 = 2$$$ bitcoins.

use std::io::stdin;
use std::collections::HashSet;

fn read_line<'a>() -> Result<String, Box<std::error::Error>> {
    let mut line = String::new();
    stdin().read_line(&mut line)?;

    Ok(line.trim().to_owned())
}

fn main() -> Result<(), Box<std::error::Error>> {
    let line = read_line()?;
    let mut nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap());

    let _ = nums.next().unwrap();
    let mut b = nums.next().unwrap();

    let line = read_line()?;

    let nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<_>>();

    let evency = nums
        .iter()
        .map(|n| if n % 2 == 0 { 1 } else { -1 })
        .collect::<Vec<_>>();

    let mut split_points = HashSet::new();
    let mut s = 0;

    for (i, e) in evency[..evency.len() - 1].iter().enumerate() {
        s += e;

        // println!("{}, {}, {}", i, s, e);

        if s == 0 {
            split_points.insert(i);
        }
    }

    let mut diffs = nums
        .iter()
        .zip(&nums[1..])
        .map(|(&prev, &curr)| (curr - prev).abs())
        .enumerate()
        .collect::<Vec<_>>();

    diffs.sort_unstable_by_key(|&(_, diff)| diff);

    // println!("diffs: {:?}", diffs);
    // println!("split_points: {:?}", split_points);

    let mut ans = 0;

    for (i, diff) in diffs {
        if split_points.contains(&i) && b >= diff {
            // println!("split at {}, price {}, current budget: {}", i, diff, b);

            ans += 1;
            b -= diff;
        }
    }

    println!("{}", ans);

    Ok(())
}

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

fn cut( accum: &Vec<(i64,i64)>, nums: &Vec<i64>, s: usize, e: usize ) -> (i64,i64) {
    //println!("cut range: {},{}", s,e);
    for idx in s..e {
        let b = ( accum[e-1].0 - accum[idx].0, accum[e-1].1 - accum[idx].1 );
        let a = if s > 0 {
            ( accum[idx].0 - accum[s-1].0, accum[idx].1 - accum[s-1].1 )
        } else {
            ( accum[idx].0, accum[idx].1 )
        };
        //println!("idx:{}, a: {:?}, b: {:?}", idx, a, b );
        if b.0 == b.1 && b.0 != 0 && a.0 == a.1 && a.0 != 0 {
            //make a cut between (idx, idx+1)
            //println!("make a cut between {}, {}", idx, idx+1 );
            return (idx as i64,idx as i64 + 1)
        }
    }
    return (-1,-1)
}

fn main() {

    use std::collections::{HashMap,HashSet, BinaryHeap};

    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    handle.read_to_string(&mut buffer).unwrap();

    let input_strs = buffer.split_whitespace().map( |x| x.parse::<i64>().unwrap() ).collect::< Vec<i64> >();

    let n = *input_strs.iter().nth(0).unwrap();
    let b = *input_strs.iter().nth(1).unwrap();

    let nums = input_strs.iter().skip(2).cloned().collect::< Vec<i64> >();

    //println!( "{:?}", nums );

    let mut eo = nums.iter().map( |x| if *x % 2 == 0 { true } else { false } ).collect::<Vec< bool >>();

    let mut count_e = 0;
    let mut count_o = 0;
    let accum = eo.iter().enumerate().map(|(k,x)| {
        if *x == true { count_e += 1; } else { count_o += 1; }
        ( count_e, count_o )
    } ).collect::< Vec< (i64,i64) > >();

    //println!( "{:?}", accum );

    let mut cut_idxs = cut( &accum, &nums, 0, nums.len() );
    let mut accum_cost = 0;
    let mut num_cuts = 0;

    let mut possible_cuts = vec![];
    loop {
        if cut_idxs.0 == -1 || cut_idxs.1 == -1 {
            break;
        }
        let cost_cut = (nums[cut_idxs.0 as usize] - nums[cut_idxs.1 as usize]).abs();

        cut_idxs = cut( &accum, &nums, cut_idxs.1 as usize, nums.len() );
        possible_cuts.push( ( cost_cut, cut_idxs ) );
    }

    possible_cuts.sort();

    // println!( "{:?}", possible_cuts );

    for i in possible_cuts.iter() {
        if accum_cost + i.0 <= b {
            accum_cost += i.0;
            num_cuts += 1;
        } else {
            break;
        }
    }

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

use std::io::stdin;
use std::collections::HashSet;

fn read_line<'a>() -> Result<String, Box<std::error::Error>> {
    let mut line = String::new();
    stdin().read_line(&mut line)?;

    Ok(line.trim().to_owned())
}

fn main() -> Result<(), Box<std::error::Error>> {
    let line = read_line()?;
    let mut nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap());

    let _ = nums.next().unwrap();
    let mut b = nums.next().unwrap();

    let line = read_line()?;

    let nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<_>>();

    let evency = nums
        .iter()
        .map(|n| if n % 2 == 0 { 1 } else { -1 })
        .collect::<Vec<_>>();

    let mut split_points = HashSet::new();
    let mut s = 0;

    for (i, e) in evency[..evency.len() - 1].iter().enumerate() {
        s += e;

        // println!("{}, {}, {}", i, s, e);

        if s == 0 {
            split_points.insert(i);
        }
    }

    let mut diffs = nums
        .iter()
        .zip(&nums[1..])
        .map(|(&prev, &curr)| (prev - curr).abs())
        .enumerate()
        .collect::<Vec<_>>();

    diffs.sort_unstable_by_key(|&(_, diff)| diff);

    // println!("diffs: {:?}", diffs);
    // println!("split_points: {:?}", split_points);

    let mut ans = 0;

    for (i, diff) in diffs {
        if split_points.contains(&(i + 1)) && b >= diff {
            ans += 1;
            b -= diff;
        }
    }

    println!("{}", ans);

    Ok(())
}

use std::io::stdin;
use std::collections::HashSet;

fn read_line<'a>() -> Result<String, Box<std::error::Error>> {
    let mut line = String::new();
    stdin().read_line(&mut line)?;

    Ok(line.trim().to_owned())
}

fn main() -> Result<(), Box<std::error::Error>> {
    let line = read_line()?;
    let mut nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap());

    let _ = nums.next().unwrap();
    let mut b = nums.next().unwrap();

    let line = read_line()?;

    let nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<_>>();

    let evency = nums
        .iter()
        .map(|n| if n % 2 == 0 { 1 } else { -1 })
        .collect::<Vec<_>>();

    let mut split_points = HashSet::new();
    let mut s = 0;

    for (i, e) in evency[..evency.len() - 1].iter().enumerate() {
        s += e;

        // println!("{}, {}, {}", i, s, e);

        if s == 0 {
            split_points.insert(i);
        }
    }

    let mut diffs = nums
        .iter()
        .zip(&nums[1..])
        .map(|(&prev, &curr)| (prev - curr).abs())
        .enumerate()
        .collect::<Vec<_>>();

    diffs.sort_unstable_by_key(|&(_, diff)| diff);

    // println!("diffs: {:?}", diffs);
    // println!("split_points: {:?}", split_points);

    let mut ans = 0;

    for (i, diff) in diffs {
        if split_points.contains(&(i + 1)) && b > diff {
            ans += 1;
            b -= diff;
        }
    }

    println!("{}", ans);

    Ok(())
}

use std::io::stdin;
use std::collections::HashSet;

fn read_line<'a>() -> Result<String, Box<std::error::Error>> {
    let mut line = String::new();
    stdin().read_line(&mut line)?;

    Ok(line.trim().to_owned())
}

fn main() -> Result<(), Box<std::error::Error>> {
    let line = read_line()?;
    let mut nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap());

    let _ = nums.next().unwrap();
    let mut b = nums.next().unwrap();

    let line = read_line()?;

    let nums = line
        .split(' ')
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<_>>();

    let evency = nums
        .iter()
        .map(|n| if n % 2 == 0 { 1 } else { -1 })
        .collect::<Vec<_>>();

    let mut split_points = HashSet::new();
    let mut s = 0;

    for (i, e) in evency[..evency.len() - 1].iter().enumerate() {
        s += e;

        // println!("{}, {}, {}", i, s, e);

        if s == 0 {
            split_points.insert(i);
        }
    }

    let mut diffs = nums
        .iter()
        .zip(&nums[1..])
        .map(|(&prev, &curr)| (curr - prev).abs())
        .enumerate()
        .collect::<Vec<_>>();

    diffs.sort_unstable_by_key(|&(_, diff)| diff);

    println!("diffs: {:?}", diffs);
    println!("split_points: {:?}", split_points);

    let mut ans = 0;

    for (i, diff) in diffs {
        if split_points.contains(&i) && b >= diff {
            println!("split at {}, price {}, current budget: {}", i, diff, b);

            ans += 1;
            b -= diff;
        }
    }

    println!("{}", ans);

    Ok(())
}


Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of money she will have to spend to make n rides?

The single line contains four space-separated integers n, m, a, b (1 ≤ n, m, a, b ≤ 1000) — the number of rides Ann has planned, the number of rides covered by the m ride ticket, the price of a one ride ticket and the price of an m ride ticket.

Print a single integer — the minimum sum in rubles that Ann will need to spend.

NoteIn the first sample one of the optimal solutions is: each time buy a one ride ticket. There are other optimal solutions. For example, buy three m ride tickets.

use std::io::{self, prelude::*, Write};
use std::str;
use std::string::String;
use std::vec::Vec;

use std::cmp;

#[allow(unused_must_use)]
fn run<B: BufRead, W: Write>(mut reader: Scanner<B>, mut writer: W) {
    let total_number_of_trips: i32 = reader.next();
    let number_of_trips_with_special_ticket: i32 = reader.next();
    let one_trip_price: i32 = reader.next();
    let special_ticket_price: i32 = reader.next();

    let number_of_special_tickets_bought: i32 = total_number_of_trips / number_of_trips_with_special_ticket;
    let mut total_cost: i32 = number_of_special_tickets_bought * special_ticket_price;
    let remaining_trips_needed: i32 = total_number_of_trips % number_of_trips_with_special_ticket;
    if remaining_trips_needed > 0 {
        total_cost += cmp::min(remaining_trips_needed * one_trip_price, special_ticket_price);
    }

    total_cost = cmp::min(total_cost, total_number_of_trips * one_trip_price);

    writeln!(writer, "{}", total_cost);
}

fn main() {
    let stdin = io::stdin();
    let stdout = io::stdout();

    let reader = Scanner::new(stdin.lock());
    let writer = io::BufWriter::new(stdout.lock());
    run(reader, writer);
    io::stdout().flush().unwrap();
}

pub struct Scanner<B> {
    reader: B,
    buffer_string: Vec<u8>,
    buffer_iterator: str::SplitWhitespace<'static>,
}

impl <B: BufRead> Scanner<B> {
    pub fn new(reader: B) -> Self {
        return Self {
            reader,
            buffer_string: Vec::new(),
            buffer_iterator: "".split_whitespace()
        };
    }

    pub fn next<T: str::FromStr>(&mut self) -> T {
        loop {
            //if buffer already exists, just use existing buffer
            if let Some(token) = self.buffer_iterator.next() {
                return token.parse().ok().expect("Fail to parse token");
            }

            //get new line
            self.buffer_string.clear();
            self.reader.read_until(b'\n', &mut self.buffer_string).expect("Failed to read");

            //split by white space
            self.buffer_iterator = unsafe {
                let slice = str::from_utf8_unchecked(&self.buffer_string);
                std::mem::transmute(slice.split_whitespace())
            };
        }
    }

    pub fn next_line(&mut self) -> String {
        //reset buffer
        self.buffer_iterator = "".split_whitespace();
        self.buffer_string.clear();

        let mut input: String = String::new();
        self.reader.read_line(&mut input).expect("Failed to read line");
        return input.trim().to_string();
    }
}

fn input_split() -> Vec<u32> {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|elem| elem.parse().unwrap())
        .collect()
}

fn main() {
    let (n, m, a, b) = {
        let temp = input_split();
        (temp[0], temp[1], temp[2], temp[3])
    };

    if m * a > b {
        println!("{}", (n / m) * b + b.min((n % m) * a));
    } else {
        println!("{}", n * a);
    }
}

//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 }
    }};
}
struct WordReader {
    it : std::vec::IntoIter<String>,
}
#[allow(dead_code)]
impl WordReader {
    fn new<T: std::io::Read>(mut reader: T) -> WordReader {
        let mut s = String::new();
        reader.read_to_string(&mut s).unwrap();
        WordReader {
            it : s.split_ascii_whitespace().map(String::from)
            .collect::<Vec<_>>().into_iter()
        }
    }
    fn from_stdin() -> WordReader {
        WordReader::new(std::io::stdin())
    }
    fn s(&mut self) -> String {
        self.it.next().unwrap()
    }
    fn ab(&mut self) -> Vec<u8> {
        self.it.next().unwrap().into_bytes()
    }
    fn i(&mut self) -> i32 {
        self.it.next().unwrap().parse().unwrap()
    }
    fn ai(&mut self, n: usize) -> Vec<i32> {
        let mut a = Vec::with_capacity(n);
        for _ in 0..n { a.push(self.i()); }
        a
    }
}

fn main() {
    let mut input = WordReader::from_stdin();
    let n = input.i();
    let m = input.i();
    let a = input.i();
    let b = input.i();
    let p = n / m;
    let q = n % m;
    let val = [a*n, a*q+b*p, b*(p+1)];
    let sol = val.iter().min().unwrap();
    println!("{}", sol);
}

// 2018-10-12 09:00
fn main() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().split(" ").map(|s| s.parse::<i32>().unwrap()).collect()
    };
    let (n, m, a, b) = (v[0], v[1], v[2], v[3]);

    if b / m >= a {
        println!("{:?}", a * n);
    } else {
        if n % m * a > b {
            println!("{:?}", (n as f32 / m as f32).ceil() as i32 * b);

        } else {
            println!("{:?}", (n / m) * b + n % m * a);
        }

    }
}

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(),
            )+
        )
    }}
}

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() {
    let (n,m,a,b) = readln!(i32,i32,i32,i32);
    let r1 = n*a;
    let r2 = b*((n+m-1)/m);
    let r3 = b*(n/m) + a*(n%m);
    println!("{}", std::cmp::min(r1,std::cmp::min(r2,r3)));
}

// {{{ by shik

use std::io;

#[allow(dead_code)]
fn gets() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

#[allow(unused_macros)]
macro_rules! R {
    ( $ty:ty, ... ) => {
        gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::<Vec<_>>()
    };
    ( $($ty:ty),* ) => {{
        let line = gets();
        let mut it = line.split_whitespace();
        ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )
    }}
}

#[allow(unused_macros)]
macro_rules! W {
    ( $x:expr ) => {{
        println!("{}", $x);
    }};
    ( $x:expr, $($xs:expr),* ) => {{
        print!("{} ", $x);
        W!($($xs),*);
    }}
}

#[allow(unused_macros)]
macro_rules! join {
    ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }
}

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

// }}}

use std::cmp;

fn main() {
    let (n, m, a, b) = R!(usize, usize, usize, usize);
    println!("{}", cmp::min(n*a, cmp::min((n%m)*a + (n/m)*b, (n+m-1)/m*b)));
}

use std::io;
use std::cmp::min;

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

  let x: Vec<i32> = s.trim()
    .split_whitespace()
    .map(|x| x.parse().unwrap())
    .collect();

  let n = x[0];
  let m = x[1];
  let a = x[2];
  let b = x[3];

  let ans =
  min(  a*n,
  min(  b*(n/m + 1),
        b*(n/m) + a*(n%m)
  ));

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

use std::io;
use std::cmp::min;

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

  let x: Vec<i32> = s.trim()
    .split_whitespace()
    .map(|x| x.parse().unwrap())
    .collect();

  let n = x[0];
  let m = x[1];
  let a = x[2];
  let b = x[3];

  if m * a <= b {
    println!("{}", a*n);
  } else {
    if m > n {
      println!("{}", min(b, a*n));
    } else {
      if a*(n%m) < b {
        println!("{}", b*(n/m)+a*(n%m));
      } else {
        println!("{}", b*(n/m+1));
      }
    }
  }
}

use std::io::*;

fn reads<T: std::str::FromStr>(i: &mut StdinLock) -> Vec<T> {
    let mut s = String::new();
    i.by_ref().read_line(&mut s).ok();
    s.trim()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn main() {
    // initialize stdin
    let sin = std::io::stdin();
    let mut sin = sin.lock();
    let sin = &mut sin;

    let params: Vec<u32> = reads(sin);

    let n = params[0];
    let m = params[1];
    let a = params[2];
    let b = params[3];

    let ans = if a * m < b {
        n * a
    } else {
        let base = n / m;
        let remain = n % m;
        (base * b) + std::cmp::min(remain * a, b)
    };

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

// https://codeforces.com/problemset/problem/466/A
use std::io;

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

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

    let words: Vec<i64> =
        line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = words[0];
    let m = words[1];
    let a = words[2];
    let b = words[3];

    let sale: f64 = b as f64/m as f64;

    if sale < a as f64 {
        let mut ans = (n as f64/m as f64).floor() as i64*b;
        let minima = std::cmp::min((n%m)*a, b);
        ans += minima;
        println!("{}", ans);
    } else {
        println!("{}", n*a);
    }
}

#[allow(unused_imports)]
use std::cmp;
#[allow(unused_imports)]
use std::collections::BTreeSet;
#[allow(unused_imports)]
use std::collections::HashSet;
use std::fs::File;
use std::io::Read;
#[allow(unused_imports)]
use std::mem;
use std::fmt::Display;

#[allow(dead_code)]
fn pow_speedy_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;
}

#[allow(dead_code)]
fn comb(n: usize, k: usize, m: i64, frac: &[i64], frac_inv: &[i64]) -> i64 {
    let mut ret = 1i64;
    if n < k {
        return 0;
    }
    ret *= frac[n] * frac_inv[n - k];
    ret %= m;
    ret *= frac_inv[k];
    ret %= m;
    ret
}

#[allow(dead_code)]
fn show1dvec<T : Display>(v : &Vec<T>) {
    let n = v.len();
    for i in 0..n - 1 {
        print!("{} " , v[i]);
    }
    println!("{} " , v[n - 1]);
}

#[derive(Debug)]
struct Piece {
    mark: char,
    y: i32,
    x: i32,
}

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 n: i32 = iter.next().unwrap().parse().unwrap();
    let m: i32 = iter.next().unwrap().parse().unwrap();
    let a: i32 = iter.next().unwrap().parse().unwrap();
    let b: i32 = iter.next().unwrap().parse().unwrap();

    println!("{}", cmp::min(cmp::min(n * a, (n + m - 1) / m * b), (n % m) * a + (n / m) * b));

    // let n = iter.next().unwrap().parse().unwrap();

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

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 _main() {
    let mut scan = Scan::new();
    let n: isize = scan.next();
    let m: isize = scan.next();
    let a: isize = scan.next();
    let b: isize = scan.next();
    if a*m <= b {
        println!("{}", a*n);
    } else {
        let mut result = (n/m)*b;
        if b <= a*(n%m) { result += b; }
        else {            result += (n%m)*a; }
        println!("{}", result);
    }
}

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

use std::cmp::min;
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_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 main() {
    let stdin = io::stdin();
    let mut n_m_a_b : Vec<usize> = vec![];
    read_ts(&stdin, &mut n_m_a_b);
    let n = n_m_a_b[0];
    let m = n_m_a_b[1];
    let a = n_m_a_b[2];
    let b = n_m_a_b[3];
    let cost_1 = n * a;
    let cost_2 = ((n / m) * b) + min((n % m) * a, b);
    let min_cost = min(cost_1, cost_2);
    println!("{}", min_cost);
}

fn solve() {
    let (n, m, a, b) = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let v: Vec<i32> = buf.split_whitespace().map(|x| x.parse().unwrap()).collect();
        (v[0], v[1], v[2], v[3])
    };

    let mut ans = 0;
    if b < m * a {
        let d = n / m;
        ans += d * b;
        if b < a * (n - d * m) {
            ans += b;
        } else {
            ans += (n - d * m) * a;
        }
    } else {
        ans += n * a;
    }
    println!("{}", ans);
}

fn main() {
    // let t: u32 = {
    //     let mut buf = String::new();
    //     std::io::stdin().read_line(&mut buf).unwrap();
    //     buf.trim_end().parse().unwrap()
    // };

    solve();
    // for _ in 0..t {}
}

// use rand::Rng;

use std::collections::*;
use std::io;

fn trim_newline(s: &mut String) {
    if s.ends_with('\n') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}
macro_rules! parse_input {
    ($t:ident) => {{
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line).unwrap();
        trim_newline(&mut input_line);
        input_line.parse::<$t>().unwrap()
    }};
}

macro_rules! split_input {
    ($t:ident) => {{
        parse_input!(String)
            .split(" ")
            .map(|z| z.parse::<$t>().unwrap())
            .collect::<Vec<$t>>()
    }};
}

fn main() {
    let a = split_input!(u64);
    let n = a[0];
    let single = a[2];
    let group = a[3];
    let group_count = a[1];
    let mut best = single * n;
    best = std::cmp::min(best, ((n + (group_count - 1)) / group_count) * group);
    let other = n / group_count * group;
    let rem = n % group_count;
    best = std::cmp::min(other + rem * single, best);

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

// use rand::Rng;

use std::collections::*;
use std::io;

fn trim_newline(s: &mut String) {
    if s.ends_with('\n') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}
macro_rules! parse_input {
    ($t:ident) => {{
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line).unwrap();
        trim_newline(&mut input_line);
        input_line.parse::<$t>().unwrap()
    }};
}

macro_rules! split_input {
    ($t:ident) => {{
        parse_input!(String)
            .split(" ")
            .map(|z| z.parse::<$t>().unwrap())
            .collect::<Vec<$t>>()
    }};
}

fn main() {
    let a = split_input!(u64);
    let n = a[0];
    let single = a[2];
    let group = a[3];
    let group_count = a[1];
    let mut best = single * n;
    best = std::cmp::min(best, ((n + (group_count - 1)) / group_count) * group);

    let other = n / group_count * group;
    let rem = n % group_count;

    best = std::cmp::min(other + rem * single, best);
    best = std::cmp::min(other + group, best);

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

use std::io::stdin;

fn read_line() -> String {
    let mut input = String::new();
    stdin().read_line(&mut input).expect("Failed to read line!");
    input
}

fn main() {
    let input1 = read_line();
    let line1: Vec<&str> = input1.split(" ").collect();
    let n = line1[0].trim().parse::<i32>().unwrap();
    let m = line1[1].trim().parse::<i32>().unwrap();
    let a = line1[2].trim().parse::<i32>().unwrap();
    let b = line1[3].trim().parse::<i32>().unwrap();

    let costs: i32;
    if b <= a {
        costs = f32::ceil(n as f32 / m as f32) as i32 * b;
    } else if b / m < a {
        if m > n {
            if n * a > b {
                costs = b;
            } else {
                costs = n * a;
            }
        } else {
            costs = (n % m) * a + f32::floor(n as f32 / m as f32) as i32 * b
        }
    } else {
        costs = n * a;
    }
    println!("{}", costs);
}

use std::io::{self, prelude::*, Write};
use std::str;
use std::string::String;
use std::vec::Vec;

use std::cmp;

#[allow(unused_must_use)]
fn run<B: BufRead, W: Write>(mut reader: Scanner<B>, mut writer: W) {
    let total_number_of_trips: i32 = reader.next();
    let number_of_trips_with_special_ticket: i32 = reader.next();
    let one_trip_price: i32 = reader.next();
    let special_ticket_price: i32 = reader.next();

    let number_of_special_tickets_bought: i32 = total_number_of_trips / number_of_trips_with_special_ticket;
    let mut total_cost: i32 = number_of_special_tickets_bought * special_ticket_price;
    let remaining_trips_needed: i32 = total_number_of_trips % number_of_trips_with_special_ticket;
    if remaining_trips_needed > 0 {
        total_cost += cmp::min(remaining_trips_needed * one_trip_price, special_ticket_price);
    }

    writeln!(writer, "{}", total_cost);
}

fn main() {
    let stdin = io::stdin();
    let stdout = io::stdout();

    let reader = Scanner::new(stdin.lock());
    let writer = io::BufWriter::new(stdout.lock());
    run(reader, writer);
    io::stdout().flush().unwrap();
}

pub struct Scanner<B> {
    reader: B,
    buffer_string: Vec<u8>,
    buffer_iterator: str::SplitWhitespace<'static>,
}

impl <B: BufRead> Scanner<B> {
    pub fn new(reader: B) -> Self {
        return Self {
            reader,
            buffer_string: Vec::new(),
            buffer_iterator: "".split_whitespace()
        };
    }

    pub fn next<T: str::FromStr>(&mut self) -> T {
        loop {
            //if buffer already exists, just use existing buffer
            if let Some(token) = self.buffer_iterator.next() {
                return token.parse().ok().expect("Fail to parse token");
            }

            //get new line
            self.buffer_string.clear();
            self.reader.read_until(b'\n', &mut self.buffer_string).expect("Failed to read");

            //split by white space
            self.buffer_iterator = unsafe {
                let slice = str::from_utf8_unchecked(&self.buffer_string);
                std::mem::transmute(slice.split_whitespace())
            };
        }
    }

    pub fn next_line(&mut self) -> String {
        //reset buffer
        self.buffer_iterator = "".split_whitespace();
        self.buffer_string.clear();

        let mut input: String = String::new();
        self.reader.read_line(&mut input).expect("Failed to read line");
        return input.trim().to_string();
    }
}

use std::io::{self, prelude::*, Write};
use std::str;
use std::string::String;
use std::vec::Vec;

#[allow(unused_must_use)]
fn run<B: BufRead, W: Write>(mut reader: Scanner<B>, mut writer: W) {
    let total_number_of_trips: i32 = reader.next();
    let number_of_trips_with_special_ticket: i32 = reader.next();
    let one_trip_price: i32 = reader.next();
    let special_ticket_price: i32 = reader.next();

    let number_of_special_tickets_bought: i32 = total_number_of_trips / number_of_trips_with_special_ticket;
    let mut total_cost: i32 = number_of_special_tickets_bought * special_ticket_price;
    let remaining_trips_needed: i32 = total_number_of_trips % number_of_trips_with_special_ticket;
    if remaining_trips_needed > 0 {
        total_cost += remaining_trips_needed * one_trip_price;
    }

    writeln!(writer, "{}", total_cost);
}

fn main() {
    let stdin = io::stdin();
    let stdout = io::stdout();

    let reader = Scanner::new(stdin.lock());
    let writer = io::BufWriter::new(stdout.lock());
    run(reader, writer);
    io::stdout().flush().unwrap();
}

pub struct Scanner<B> {
    reader: B,
    buffer_string: Vec<u8>,
    buffer_iterator: str::SplitWhitespace<'static>,
}

impl <B: BufRead> Scanner<B> {
    pub fn new(reader: B) -> Self {
        return Self {
            reader,
            buffer_string: Vec::new(),
            buffer_iterator: "".split_whitespace()
        };
    }

    pub fn next<T: str::FromStr>(&mut self) -> T {
        loop {
            //if buffer already exists, just use existing buffer
            if let Some(token) = self.buffer_iterator.next() {
                return token.parse().ok().expect("Fail to parse token");
            }

            //get new line
            self.buffer_string.clear();
            self.reader.read_until(b'\n', &mut self.buffer_string).expect("Failed to read");

            //split by white space
            self.buffer_iterator = unsafe {
                let slice = str::from_utf8_unchecked(&self.buffer_string);
                std::mem::transmute(slice.split_whitespace())
            };
        }
    }

    pub fn next_line(&mut self) -> String {
        //reset buffer
        self.buffer_iterator = "".split_whitespace();
        self.buffer_string.clear();

        let mut input: String = String::new();
        self.reader.read_line(&mut input).expect("Failed to read line");
        return input.trim().to_string();
    }
}

fn input_split() -> Vec<u16> {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    buf.trim()
        .split_whitespace()
        .map(|elem| elem.parse().unwrap())
        .collect()
}

fn main() {
    let (n, m, a, b) = {
        let temp = input_split();
        (temp[0], temp[1], temp[2], temp[3])
    };

    if m * a > b {
        println!("{}", (n / m) * b + b.min((n % m) * a));
    } else {
        println!("{}", n * a);
    }
}

// 2018-10-12 09:00
fn main() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().split(" ").map(|s| s.parse::<i32>().unwrap()).collect()
    };
    let (n, m, a, b) = (v[0], v[1], v[2], v[3]);

    if b / m >= a {
        println!("{:?}", a * n);
    } else {
        println!("{:?}", (n as f32 / m as f32).ceil() as i32 * b);
    }
}

// 2018-10-12 09:00
fn main() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().split(" ").map(|s| s.parse::<i32>().unwrap()).collect()
    };
    let (n, m, a, b) = (v[0], v[1], v[2], v[3]);

    if b / m >= a {
        println!("{:?}", a * n);
    } else {
        println!("{:?}", n / m * b + n % m * a);
    }
}

use std::io;
use std::cmp::min;

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

  let x: Vec<i32> = s.trim()
    .split_whitespace()
    .map(|x| x.parse().unwrap())
    .collect();

  let n = x[0];
  let m = x[1];
  let a = x[2];
  let b = x[3];

  if m * a <= b {
    println!("{}", a*n);
  } else {
    if m > n {
      println!("{}", min(b, a*n));
    } else {
      println!("{}", b*(n/m)+a*(n%m));
    }
  }
}

// https://codeforces.com/problemset/problem/466/A
use std::io;

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

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

    let words: Vec<f64> =
        line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = words[0];
    let m = words[1];
    let a = words[2];
    let b = words[3];

    let sale: f64 = b/m;

    if sale < a {
        println!("{}", (n/m).floor()*b + (n%m)*a);
    }
}

// https://codeforces.com/problemset/problem/466/A
use std::io;

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

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

    let words: Vec<f64> =
        line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = words[0];
    let m = words[1];
    let a = words[2];
    let b = words[3];

    let sale: f64 = b/m;

    if sale < a {
        println!("{}", (n/m).floor()*b + (n%m)*a);
    } else {
        println!("{}", n*a);
    }
}

// https://codeforces.com/problemset/problem/466/A
use std::io;

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

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

    let words: Vec<f64> =
        line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = words[0];
    let m = words[1];
    let a = words[2];
    let b = words[3];

    let sale: f64 = b/m;

    if sale < a {
        println!("{}", (n/m).floor()*b + (n%m)*a);
    } else {
        println!("{}", a);
    }
}

#[allow(unused_imports)]
use std::cmp;
#[allow(unused_imports)]
use std::collections::BTreeSet;
#[allow(unused_imports)]
use std::collections::HashSet;
use std::fs::File;
use std::io::Read;
#[allow(unused_imports)]
use std::mem;
use std::fmt::Display;

#[allow(dead_code)]
fn pow_speedy_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;
}

#[allow(dead_code)]
fn comb(n: usize, k: usize, m: i64, frac: &[i64], frac_inv: &[i64]) -> i64 {
    let mut ret = 1i64;
    if n < k {
        return 0;
    }
    ret *= frac[n] * frac_inv[n - k];
    ret %= m;
    ret *= frac_inv[k];
    ret %= m;
    ret
}

#[allow(dead_code)]
fn show1dvec<T : Display>(v : &Vec<T>) {
    let n = v.len();
    for i in 0..n - 1 {
        print!("{} " , v[i]);
    }
    println!("{} " , v[n - 1]);
}

#[derive(Debug)]
struct Piece {
    mark: char,
    y: i32,
    x: i32,
}

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 n: i32 = iter.next().unwrap().parse().unwrap();
    let m: i32 = iter.next().unwrap().parse().unwrap();
    let a: i32 = iter.next().unwrap().parse().unwrap();
    let b: i32 = iter.next().unwrap().parse().unwrap();

    println!("{}", cmp::min(n * a, (n % m) * a + (n / m) * b));

    // let n = iter.next().unwrap().parse().unwrap();

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

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 _main() {
    let mut scan = Scan::new();
    let n: isize = scan.next();
    let m: isize = scan.next();
    let a: isize = scan.next();
    let b: isize = scan.next();
    if a*m <= b {
        println!("{}", a*n);
    } else {
        let mut result = (n/m)*b;
        if b <= a*(n%m) { result += 1; }
        else {            result += (n%m)*a; }
        println!("{}", result);
    }
}

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

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 _main() {
    let mut scan = Scan::new();
    let n: isize = scan.next();
    let m: isize = scan.next();
    let a: isize = scan.next();
    let b: isize = scan.next();
    if a*m <= b {
        println!("{}", a*n);
    } else {
        let result = n/m*b + n%m*a;
        println!("{}", result);
    }
}

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

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 _main() {
    let mut scan = Scan::new();
    let n: isize = scan.next();
    let m: isize = scan.next();
    let a: isize = scan.next();
    let b: isize = scan.next();
    if a*m <= b {
        println!("{}", a*n);
    } else {
        let result = (n/m)*b + (n%m)*a;
        println!("{}", result);
    }
}

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

use std::cmp::min;
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_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 main() {
    let stdin = io::stdin();
    let mut n_m_a_b : Vec<usize> = vec![];
    read_ts(&stdin, &mut n_m_a_b);
    let n = n_m_a_b[0];
    let m = n_m_a_b[1];
    let a = n_m_a_b[2];
    let b = n_m_a_b[3];
    let cost_1 = n * a;
    let cost_2 = ((n / m) * b) + ((n % m) * a);
    let min_cost = min(cost_1, cost_2);
    println!("{}", min_cost);
}

// use rand::Rng;

use std::collections::*;
use std::io;

fn trim_newline(s: &mut String) {
    if s.ends_with('\n') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}
macro_rules! parse_input {
    ($t:ident) => {{
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line).unwrap();
        trim_newline(&mut input_line);
        input_line.parse::<$t>().unwrap()
    }};
}

macro_rules! split_input {
    ($t:ident) => {{
        parse_input!(String)
            .split(" ")
            .map(|z| z.parse::<$t>().unwrap())
            .collect::<Vec<$t>>()
    }};
}

fn main() {
    let a = split_input!(u64);
    let n = a[0];
    let single = a[2];
    let group = a[3];
    let group_count = a[1];

    if (single * group_count) <= group {
        println!("{}", single * n);
    } else if group < single {
        println!("{}", (n + (group_count - 1)) / group_count * group);
    } else {
        println!("{}", n / group_count * group + (n % group_count) * single);
    }
}

// use rand::Rng;

use std::collections::*;
use std::io;

fn trim_newline(s: &mut String) {
    if s.ends_with('\n') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}
macro_rules! parse_input {
    ($t:ident) => {{
        let mut input_line = String::new();
        io::stdin().read_line(&mut input_line).unwrap();
        trim_newline(&mut input_line);
        input_line.parse::<$t>().unwrap()
    }};
}

macro_rules! split_input {
    ($t:ident) => {{
        parse_input!(String)
            .split(" ")
            .map(|z| z.parse::<$t>().unwrap())
            .collect::<Vec<$t>>()
    }};
}

fn main() {
    let a = split_input!(u64);
    let n = a[0];
    let single = a[2];
    let group = a[3];
    let group_count = a[1];

    if (single * group_count) <= group {
        println!("{}", single * n);
    } else {
        println!("{}", n / group_count * group + (n % group_count) * single);
    }
}

use std::io::stdin;

fn read_line() -> String {
    let mut input = String::new();
    stdin().read_line(&mut input).expect("Failed to read line!");
    input
}

fn main() {
    let input1 = read_line();
    let line1: Vec<&str> = input1.split(" ").collect();
    let n = line1[0].trim().parse::<i32>().unwrap();
    let m = line1[1].trim().parse::<i32>().unwrap();
    let a = line1[2].trim().parse::<i32>().unwrap();
    let b = line1[3].trim().parse::<i32>().unwrap();

    let costs: i32;
    if b / m < a {
        costs = (n % m) * a + f32::floor(n as f32 / m as f32) as i32 * b
    } else {
        costs = n * a;
    }
    println!("{}", costs);
}

use std::io::stdin;

fn read_line() -> String {
    let mut input = String::new();
    stdin().read_line(&mut input).expect("Failed to read line!");
    input
}

fn main() {
    let input1 = read_line();
    let line1: Vec<&str> = input1.split(" ").collect();
    let n = line1[0].trim().parse::<i32>().unwrap();
    let m = line1[1].trim().parse::<i32>().unwrap();
    let a = line1[2].trim().parse::<i32>().unwrap();
    let b = line1[3].trim().parse::<i32>().unwrap();

    let costs: i32;
    if b <= a {
        costs = f32::ceil(n as f32 / m as f32) as i32 * b;
    } else if b / m < a {
        costs = (n % m) * a + f32::floor(n as f32 / m as f32) as i32 * b
    } else {
        costs = n * a;
    }
    println!("{}", costs);
}

use std::io::stdin;

fn read_line() -> String {
    let mut input = String::new();
    stdin().read_line(&mut input).expect("Failed to read line!");
    input
}

fn main() {
    let input1 = read_line();
    let line1: Vec<&str> = input1.split(" ").collect();
    let n = line1[0].trim().parse::<i32>().unwrap();
    let m = line1[1].trim().parse::<i32>().unwrap();
    let a = line1[2].trim().parse::<i32>().unwrap();
    let b = line1[3].trim().parse::<i32>().unwrap();

    let costs: i32;
    if b <= a {
        costs = f32::ceil(n as f32 / m as f32) as i32 * b;
    } else if b / m < a {
        if m > n {
            if n * a > m * b {
                costs = m * b;
            } else {
                costs = n * a;
            }
        } else {
            costs = (n % m) * a + f32::floor(n as f32 / m as f32) as i32 * b
        }
    } else {
        costs = n * a;
    }
    println!("{}", costs);
}