// Try Codeforces
// author: Leonardone @ NEETSDKASU

fn main() {
    let mut stdin = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut stdin).unwrap();
    let mut stdin = stdin.split_whitespace();
    let mut get = || stdin.next().unwrap();
    macro_rules! get {
        () => (get().parse::<i64>().unwrap());
        ($t:ty) => (get().parse::<$t>().unwrap()); }

    let mut field = vec![vec![]; 9];
    for i in 0..9 {
        for _ in 0..3 {
            field[i].push(get().as_bytes());
        }
    }
    let y = (get!(usize) - 1) % 3;
    let x = (get!(usize) - 1) % 3;

    let mut c = 0;
    for i in 0..3 {
        for &ch in &field[y*3+i][x][..] {
            if ch == b'.' {
                c += 1;
            }
        }
    }
    if c == 0 {
        for i in 0..9 {
            for j in 0..3 {
                if j > 0 { print!(" "); }
                for k in 0..3 {
                    let ch = field[i][j][k];
                    if ch == b'.' {
                        print!("!");
                    } else {
                        print!("{}", ch as char);
                    }
                }
            }
            println!();
            if i % 3 == 2 { println!(); }
        }
        return;
    }
    for i in 0..9 {
        for j in 0..3 {
            if j > 0 { print!(" "); }
            for k in 0..3 {
                let ch = field[i][j][k];
                if ch == b'.' && j == x && i / 3 == y {
                    print!("!");
                } else {
                    print!("{}", ch as char);
                }
            }
        }
        println!();
        if i % 3 == 2 { println!(); }
    }
}

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

    let p = input.bytes().position(|b| b'0' <= b && b <= b'9').unwrap();

    let grid: Vec<_> = input.as_bytes()[0..p].iter().filter_map(|&b| match b {
        b'.' => Some(Cell::Empty),
        b'x' => Some(Cell::Chip1),
        b'o' => Some(Cell::Chip2),
        _ => None,
    }).collect();

    let check = |x: usize, y: usize, grid: &Vec<Cell>| {
        let x_off = 27 * x;
        let y_off = 3 * y;
        let mut it = grid[x_off + y_off..].iter().take(3)
            .chain(grid[x_off + y_off + 9..].iter().take(3))
            .chain(grid[x_off + y_off + 18..].iter().take(3));

        !it.all(|cell| match *cell {
            Cell::Empty => false,
            _ => true,
        })
    };

    let mut it = input[p..].split_whitespace();
    let x: usize = it.next().unwrap().parse::<usize>().unwrap() - 1;
    let y: usize = it.next().unwrap().parse::<usize>().unwrap() - 1;

    let bx = x % 3;
    let by = y % 3;

    let ans: Vec<_> = if !check(bx, by, &grid) {
        grid.into_iter().map(|cell| match cell {
            Cell::Empty => Cell::Possible,
            _ => cell,
        }).collect()
    } else {
        grid.into_iter().enumerate().map(|(i, cell)| {
            let x = i / 9;
            let y = i % 9;
            match cell {
                Cell::Empty if x / 3 == bx && y / 3 == by => Cell::Possible,
                _ => cell,
            }
        }).collect()
    };

    let mut ans_str = Vec::with_capacity(2 * p);

    for (i, cell) in ans.into_iter().enumerate() {
        let next = match cell {
            Cell::Empty => b'.',
            Cell::Chip1 => b'x',
            Cell::Chip2 => b'o',
            Cell::Possible => b'!',
        };

        ans_str.push(next);

        if i % 27 == 26 {
            ans_str.push(b'\n');
        }
        if i % 9 == 8 {
            ans_str.push(b'\n');
        } else if i % 3 == 2 {
            ans_str.push(b' ');
        }
    }

    let ans = String::from_utf8(ans_str).unwrap();

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

#[derive(Debug)]
enum Cell {
    Empty,
    Chip1,
    Chip2,
    Possible,
}

#[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;

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 mut field: Vec<Vec<char>> = (0..11).map(|_| util::line().chars().collect()).collect();
    let (mut y, mut x) = get!(usize, usize);

    y -= 1;
    x -= 1;

    let ry = y - 3 * (y / 3);
    let rx = x - 3 * (x / 3);

    let sy = 4 * ry;
    let sx = 4 * rx;

    if (sy..sy + 3).all(|y1| (sx..sx + 3).all(|x1| field[y1][x1] != '.')) {
        for v in field.iter_mut() {
            for c in v.iter_mut() {
                if *c == '.' {
                    *c = '!';
                }
            }
        }
    } else {
        for y1 in sy..sy + 3 {
            for x1 in sx..sx + 3 {
                if field[y1][x1] == '.' {
                    field[y1][x1] = '!';
                }
            }
        }
    }

    for line in &field {
        println!(
            "{}",
            line.iter()
                .map(|c| c.to_string())
                .collect::<Vec<_>>()
                .join("")
        );
    }
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU

fn main() {
    let mut stdin = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut stdin).unwrap();
    let mut stdin = stdin.split_whitespace();
    let mut get = || stdin.next().unwrap();
    macro_rules! get {
        () => (get().parse::<i64>().unwrap());
        ($t:ty) => (get().parse::<$t>().unwrap()); }

    let mut field = vec![vec![]; 9];
    for i in 0..9 {
        for _ in 0..3 {
            field[i].push(get().as_bytes());
        }
    }
    let y = (get!(usize) - 1) % 3;
    let x = (get!(usize) - 1) % 3;

    let mut c = 0;
    for i in 0..3 {
        for &ch in &field[y*3+i][x][..] {
            if ch == b'.' {
                c += 1;
            }
        }
    }
    if c == 0 {
        for i in 0..9 {
            for j in 0..3 {
                if j > 0 { print!(" "); }
                for k in 0..3 {
                    let ch = field[i][j][k];
                    if ch == b'.' {
                        print!("!");
                    } else {
                        print!("{}", ch as char);
                    }
                }
            }
            println!();
        }
        return;
    }
    for i in 0..9 {
        for j in 0..3 {
            if j > 0 { print!(" "); }
            for k in 0..3 {
                let ch = field[i][j][k];
                if ch == b'.' && j == x && i / 3 == y {
                    print!("!");
                } else {
                    print!("{}", ch as char);
                }
            }
        }
        println!();
    }
}

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

    let p = input.bytes().position(|b| b'0' <= b && b <= b'9').unwrap();

    let grid: Vec<_> = input.as_bytes()[0..p].iter().filter_map(|&b| match b {
        b'.' => Some(Cell::Empty),
        b'x' => Some(Cell::Chip1),
        b'o' => Some(Cell::Chip2),
        _ => None,
    }).collect();

    let check = |x: usize, y: usize, grid: &Vec<Cell>| {
        let x_off = 27 * x;
        let y_off = 3 * y;
        let mut it = grid[x_off + y_off..].iter().take(3)
            .chain(grid[x_off + y_off + 9..].iter().take(3))
            .chain(grid[x_off + y_off + 18..].iter().take(3));

        !it.all(|cell| match *cell {
            Cell::Empty => false,
            _ => true,
        })
    };

    let mut it = input[p..].split_whitespace();
    let x: usize = it.next().unwrap().parse::<usize>().unwrap() - 1;
    let y: usize = it.next().unwrap().parse::<usize>().unwrap() - 1;

    let bx = x % 3;
    let by = y % 3;

    let ans: Vec<_> = if !check(bx, by, &grid) {
        grid.into_iter().map(|cell| match cell {
            Cell::Empty => Cell::Possible,
            _ => cell,
        }).collect()
    } else {
        grid.into_iter().enumerate().map(|(i, cell)| {
            let x = i / 9;
            let y = i % 9;
            match cell {
                Cell::Empty if x / 3 == bx && y / 3 == by => Cell::Possible,
                _ => cell,
            }
        }).collect()
    };

    let mut ans_str = Vec::with_capacity(2 * p);

    for (i, cell) in ans.into_iter().enumerate() {
        let next = match cell {
            Cell::Empty => b'.',
            Cell::Chip1 => b'x',
            Cell::Chip2 => b'o',
            Cell::Possible => b'!',
        };

        ans_str.push(next);

        if i % 9 == 8 {
            ans_str.push(b'\n');
        } else if i % 3 == 2 {
            ans_str.push(b' ');
        }
    }

    let ans = String::from_utf8(ans_str).unwrap();

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

#[derive(Debug)]
enum Cell {
    Empty,
    Chip1,
    Chip2,
    Possible,
}


fn main() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("input: read line failed");
    let number = input.trim().parse::<i32>().expect("number: parse to usize failed");

    let vec = vec![
        hp_judge(0, number),
        hp_judge(1, number),
        hp_judge(2, number),
    ];

    let outcome = great_hp(vec);

    println!("{} {}", outcome.0, outcome.1);

}

fn great_hp(hp_vec: Vec<(i32, i32)>) -> (i32, String) {
    let mut best_hp = (i32::default(), i32::default());

    for item in hp_vec.iter() {
        if item.1 > best_hp.1 {
            best_hp = *item;
        }
    }

    convert(best_hp)
}

fn hp_judge(offset: i32, number: i32) -> (i32, i32) {
    ( offset, grade_estimation(number + offset) )
}

fn grade_estimation(hp: i32) -> i32 {
    let reminder = hp % 4;

    match reminder {
        0 => { 0 },
        1 => { 3 },
        2 => { 1 },
        3 => { 2 },
        _ => { -1 },

    }
}

fn convert(hp: (i32, i32)) -> (i32 ,String) {
    match hp.1 {
        0 => { (hp.0, String::from("D")) },
        3 => { (hp.0, String::from("A")) },
        1 => { (hp.0, String::from("C")) },
        2 => { (hp.0, String::from("B")) },
        _ => { (hp.0, String::from("Err")) },
    }
}

macro_rules! parse {
    () => {{
        let mut buffer = String::new();
        std::io::stdin().read_line(&mut buffer).expect("Could not fetch value from stdin");
        buffer.trim().parse().expect("Could not convert input")
    }};
}

fn main() {
    let hp: u32 = parse!();
    let current_category = hp % 4;
    match current_category {
        0 => println!("1 A"),
        1 => println!("0 A"),
        2 => println!("1 B"),
        3 => println!("2 A"),
        _ => unreachable!("Since mod 4 this should not be reachable"),
    };
}

fn main() {
    let mut x = String::new();
    std::io::stdin().read_line(&mut x).unwrap();
    let x: u8 = x.trim().parse().unwrap();

    let (a, category) = match x % 4 {
        0 => (1, 'A'),
        1 => (0, 'A'),
        2 => (1, 'B'),
        3 => (2, 'A'),
        _ => unreachable!()
    };

    println!("{} {}", a, category);
}

//spnauti-rusT
use std::io::*;
use std::str::{self,*};
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_macros)]
macro_rules! m {
    ($c:tt, $x:expr, $y:expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
#[allow(unused_macros)]
macro_rules! l {
    ($($v:ident),* = $i:ident.$f:ident $a:tt) => {
        $( let $v = $i.$f$a; )*
    };
    ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {
        $( let $v:$t = $i.$f$a; )*
    };
}
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 f(&mut self) ->    f64 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn sk(&mut self, n: usize) { self.it.nth(n - 1); }
    fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> {
        self.ip(n).into_iter()
    }
    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 ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
        self.vp(n).into_iter()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}
//------------------- End rusT

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

    let x = input.u();
    let a = [3,0,2,1];
    let mut soli = 0;
    let mut sola = a[x % 4];
    for i in 1..=2 {
        let x = x + i;
        if m!(<,sola,a[x % 4]) {
            soli = i;
        }
    }
    println!("{} {}", soli, (sola + b'A') as char);
}

use std::collections::HashMap;

fn read_string() -> String {
    let mut string: String = String::new();

    std::io::stdin().read_line(&mut string)
        .ok()
        .expect("Error read line!");
    return string;
}

fn main() {

    let hp : i32 = read_string().trim().parse().ok().expect("not int");

    let mut category : HashMap<i32, &str> = HashMap::new();
    category.insert(1, "0 A");
    category.insert(3, "2 A");
    category.insert(2, "1 B");
    category.insert(0, "1 A");
    println!("{}", category[&(hp % 4)]);
}

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
struct Score{
    grade: String,
    score: i32
}

fn calculate_grade(grade: i32) -> String{
    let mut words : String;
    match grade {
        1 => words = String::from("A"),
        2 => words = String::from("C"),
        3 => words = String::from("B"),
        _ => words = String::from("D")
    }
    words
}

fn main() {
    let mut t: String = String::new();
    std::io::stdin().read_line(&mut t).expect("input");
    let counter:Vec<i32> = t.trim()
        .split_whitespace()
        .map(|x| x.parse::<i32>().expect("Not an Integer!"))
        .collect();

    let mut list_of_score : Vec<Score> = Vec::new();
    for i in 0..3{
        list_of_score.push( Score {
            score: i ,
            grade: calculate_grade((counter[0] + i) % 4)
        })
    }
    list_of_score.sort();
    println!("{} {}", list_of_score[0].score, list_of_score[0].grade);
}

// Template adapted from submissions by https://codeforces.com/profile/EbTech

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

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

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

    let x: u8 = cin.read();
    let (a, b) = match x % 4 {
        1 => (0, 'A'),
        3 => (2, 'A'),
        2 => (1, 'B'),
        0 => (1, 'A'),
        _ => unreachable!(),
    };

    writeln!(cout, "{} {}", a, b).unwrap();
}

use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

pub fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let x = i.read::<u32>();

    let (a, b) = solve(x);
    writeln!(o, "{} {}", a, b).unwrap();
}
fn solve(x: u32) -> (u32, char) {
    fn to_category(x: u32) -> char {
        match x % 4 {
            1 => 'A',
            3 => 'B',
            2 => 'C',
            0 => 'D',
            _ => unreachable!(),
        }
    }
    [0, 1, 2]
        .iter()
        .map(|&a| (a, to_category(x + a)))
        .min_by_key(|&(_a, c)| c)
        .unwrap()
}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            let mut consume = 0;
            loop {
                self.r.consume(consume);
                let b = self.r.fill_buf().unwrap();
                assert!(b.len() != 0);
                if let Some(p) = b.iter().position(|&x| x.is_ascii_whitespace()) {
                    self.b.extend_from_slice(&b[..p]);
                    consume = p + 1;
                    break;
                }
                self.b.extend_from_slice(b);
                consume = b.len();
            }
            self.r.consume(consume);
            consume_ws(&mut self.r);
            &self.b
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            let end = self
                .b
                .iter()
                .rposition(|x| !x.is_ascii_whitespace())
                .map(|idx| idx + 1)
                .unwrap_or(0);
            &self.b[..end]
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpIn>(&mut self) -> T {
            T::read_from(self)
        }

        pub fn read_vec<T: CpIn>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
        pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {
            CpIter {
                r: self,
                n: n,
                _pd: Default::default(),
            }
        }
    }
    pub struct CpIter<'a, R: BufRead + 'a, T> {
        r: &'a mut CpReader<R>,
        n: usize,
        _pd: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            if self.n == 0 {
                None
            } else {
                self.n -= 1;
                Some(self.r.read())
            }
        }
    }

    pub trait CpIn {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpIn for u64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpIn for i64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }
    impl CpIn for char {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            let b = r.r.fill_buf().unwrap()[0] as char;
            r.r.consume(1);
            let s = r.r.fill_buf().unwrap()[0];
            assert!(s == b' ' || s == b'\n');
            r.r.consume(1);
            b
        }
    }

    macro_rules! cpin_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpIn),*> CpIn for ($($t),*) {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::read_from(r)),*)
                }
            }
        };
    }

    macro_rules! cpin_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpIn for $t_self {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::read_from(r) as $t_self
                }
            }
        };
    }
    macro_rules! cpin_parse {
        ($t:ty) => {
            impl CpIn for $t {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }
    cpin_cast!(usize, u64);
    cpin_cast!(u32, u64);
    cpin_cast!(u16, u64);
    cpin_cast!(i32, i64);
    cpin_cast!(i16, i64);
    cpin_cast!(i8, i64);

    cpin_parse!(f64);

    cpin_tuple!(T1, T2);
    cpin_tuple!(T1, T2, T3);
    cpin_tuple!(T1, T2, T3, T4);
    cpin_tuple!(T1, T2, T3, T4, T5);

    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let mut idx = 0;
            let buf_len;
            {
                let buf = r.fill_buf().unwrap();
                buf_len = buf.len();
                assert!(buf_len != 0);
                while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {
                    value = value * 10 + (buf[idx] - b'0') as u64;
                    idx += 1;
                }
            }
            if idx < buf_len {
                r.consume(idx);
                consume_ws(r);
                return value;
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let (consume, sign) = match r.fill_buf().unwrap()[0] {
            b'+' => (true, 1),
            b'-' => (true, -1),
            _ => (false, 1),
        };
        if consume {
            r.consume(1);
        }
        read_u64_fast(r) as i64 * sign
    }
    fn consume_ws<R: BufRead>(r: &mut R) {
        let mut c = 0;
        loop {
            r.consume(c);
            let b = r.fill_buf().unwrap();
            if b.len() == 0 {
                return;
            }
            if let Some(p) = b.iter().position(|&x| !x.is_ascii_whitespace()) {
                c = p;
                break;
            }
            c = b.len();
        }
        r.consume(c);
    }

}

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 get_class(x: usize) -> usize {
    let classes = [0usize, 2, 3, 1];
    return classes.iter().position(|&v| v == (x % 4)).unwrap();
}

fn _main() {
    let mut scan = Scan::new();
    let x: usize = scan.next();
    let mut maxclass = get_class(x);
    let mut maxb = 0;
    for &step in [1usize, 2].iter() {
        let current_class = get_class(x + step);
        if current_class > maxclass {
            maxclass = current_class;
            maxb = step;
        }
    }
    println!("{} {}", maxb, ['D', 'C', 'B', 'A'][maxclass]);
}

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


use std::io;
use std::str::FromStr;
use std::num::ParseIntError;
use std::ops::Index;

struct RevBinary {
    data: Vec<bool>,
}

impl FromStr for RevBinary {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let i = s.parse::<u32>()?;

        Ok(RevBinary::new(i))
    }
}

impl Index<usize> for RevBinary {
    type Output = bool;

    fn index(&self, i: usize) -> &Self::Output {
        &self.data[self.data.len() - i - 1]
    }
}

impl RevBinary {
    fn new(x : u32) -> RevBinary {
        let mut y = x;
        let mut bin : Vec<bool> = Vec::new();
        while y != 0 {
           bin.push(if y % 2 == 1 { true } else { false });
           y /= 2;
        }
        RevBinary {
            data: bin,
        }
    }

    fn size(&self) -> usize {
        self.data.len()
    }
}

fn process_node(all: &Vec<RevBinary>, ind: Vec<usize>, depth: usize, k: u32) -> u32 {
    let mut result : u32 = ind.iter().take(k as usize).map(|&x| all[x].size() - depth).sum::<usize>() as u32;

    if result == 0 {
        return 0;
    }

    let new_ind : (Vec<usize>, Vec<usize>) = ind.iter().filter(|&&x| all[x].size() > depth).partition(|&&x| all[x][depth]);
    if new_ind.0.len() >= k as usize {
        result = result.min(process_node(&all, new_ind.0, depth + 1, k));
    }
    if result != 0 && new_ind.1.len() >= k as usize {
        result = result.min(process_node(&all, new_ind.1, depth + 1, k));
    }
    result
}

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 n = input_iter.next().unwrap().parse::<usize>().unwrap();
    let k = input_iter.next().unwrap().parse::<u32>().unwrap();
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("failed to read input");
    let mut a = buffer.split_whitespace().map(|x| x.parse::<RevBinary>().unwrap()).collect::<Vec<RevBinary>>();
    a.sort_by(|a, b| a.size().cmp(&b.size()));

    println!("{}", process_node(&a, (0..n).collect::<Vec<usize>>(), 0, k));
}

use std::io;
use std::str::FromStr;
use std::num::ParseIntError;
use std::ops::Index;

struct RevBinary {
    data: Vec<bool>,
}

impl FromStr for RevBinary {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let i = s.parse::<u32>()?;

        Ok(RevBinary::new(i))
    }
}

impl Index<usize> for RevBinary {
    type Output = bool;

    fn index(&self, i: usize) -> &Self::Output {
        &self.data[self.data.len() - i - 1]
    }
}

impl RevBinary {
    fn new(x : u32) -> RevBinary {
        let mut y = x;
        let mut bin : Vec<bool> = Vec::new();
        while y != 0 {
           bin.push(if y % 2 == 1 { true } else { false });
           y /= 2;
        }
        RevBinary {
            data: bin,
        }
    }

    fn size(&self) -> usize {
        self.data.len()
    }
}

fn process_node(all: &Vec<RevBinary>, ind: Vec<usize>, depth: usize, k: u32) -> u32 {
    let mut result : u32 = ind.iter().take(k as usize).map(|&x| all[x].size() - depth).sum::<usize>() as u32;

    let mut new_ind0 : Vec<usize> = Vec::new();
    let mut new_ind1 : Vec<usize> = Vec::new();
    for i in ind.iter().filter(|&&x| all[x].size() > depth) {
        if all[*i][depth] {
            new_ind1.push(*i);
        } else {
            new_ind0.push(*i);
        }
    }
    if new_ind0.len() >= k as usize {
        result = result.min(process_node(&all, new_ind0, depth + 1, k));
    }
    if new_ind1.len() >= k as usize {
        result = result.min(process_node(&all, new_ind1, depth + 1, k));
    }
    result
}

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 n = input_iter.next().unwrap().parse::<usize>().unwrap();
    let k = input_iter.next().unwrap().parse::<u32>().unwrap();
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("failed to read input");
    let mut a = buffer.split_whitespace().map(|x| x.parse::<RevBinary>().unwrap()).collect::<Vec<RevBinary>>();
    a.sort_by(|a, b| a.size().cmp(&b.size()));

    println!("{}", process_node(&a, (0..n).collect::<Vec<usize>>(), 0, k));
}

use std::io;
use std::str::FromStr;
use std::num::ParseIntError;
use std::ops::Index;

struct RevBinary {
    data: Vec<bool>,
}

impl FromStr for RevBinary {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let i = s.parse::<u32>()?;

        Ok(RevBinary::new(i))
    }
}

impl Index<usize> for RevBinary {
    type Output = bool;

    fn index(&self, i: usize) -> &Self::Output {
        &self.data[self.data.len() - i - 1]
    }
}

impl RevBinary {
    fn new(x : u32) -> RevBinary {
        let mut y = x;
        let mut bin : Vec<bool> = Vec::new();
        while y != 0 {
           bin.push(if y % 2 == 1 { true } else { false });
           y /= 2;
        }
        RevBinary {
            data: bin,
        }
    }

    fn size(&self) -> usize {
        self.data.len()
    }
}

fn process_node(all: &Vec<RevBinary>, ind: Vec<usize>, depth: usize, k: u32) -> u32 {
    let mut result : u32 = ind.iter().take(k as usize).map(|&x| all[x].size() - depth).sum::<usize>() as u32;

    if result != 0 {
        let mut new_ind0 : Vec<usize> = Vec::new();
        let mut new_ind1 : Vec<usize> = Vec::new();
        for i in ind.iter().filter(|&&x| all[x].size() > depth) {
            if all[*i][depth] {
                new_ind1.push(*i);
            } else {
                new_ind0.push(*i);
            }
        }
        if new_ind0.len() >= k as usize {
            result = result.min(process_node(&all, new_ind0, depth + 1, k));
        }
        if result != 0 && new_ind1.len() >= k as usize {
            result = result.min(process_node(&all, new_ind1, depth + 1, k));
        }
    }
    result
}

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 n = input_iter.next().unwrap().parse::<usize>().unwrap();
    let k = input_iter.next().unwrap().parse::<u32>().unwrap();
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("failed to read input");
    let mut a = buffer.split_whitespace().map(|x| x.parse::<RevBinary>().unwrap()).collect::<Vec<RevBinary>>();
    a.sort_by(|a, b| a.size().cmp(&b.size()));

    println!("{}", process_node(&a, (0..n).collect::<Vec<usize>>(), 0, k));
}

#[allow(unused_imports)]
use std::cmp::{Ordering};

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

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

#[allow(unused_imports)]
use std::iter::FromIterator;

#[allow(unused_macros)]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::min($x, min!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::max($x, max!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! get {
    ([$t: ty]) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::<Vec<_>>()
        }
    };
    ([$t: ty];$n: expr) => {
        (0..$n).map(|_|get!([$t])).collect::<Vec<_>>()
    };
    ($t: ty) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t: ty),*) => {
        {
            let mut line = 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<_>>()
    };
}

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

const BIG_STACK_SIZE: bool = true;

#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}

fn solve() {
    let (n,k) = get!(usize, usize);
    let a = get!([usize]);
    let mut map = BTreeMap::new();
    for e in a {
        let mut e = e;
        let mut count = 0;
        while e > 0 {
            let entry = map.entry(e).or_insert(BinaryHeap::new());
            entry.push(count);
            if entry.len() > k {
                entry.pop();
            }
            count += 1;
            e /= 2;
        }
    }
    let mut mn = std::usize::MAX;
    for (_, v) in map {
        if v.len() == k {
            mn = min!(mn,v.into_iter().sum::<usize>());
        }
    }
    println!("{}", mn);
}

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

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

const INF:usize= 2 << 30;

fn rec(cur: usize, u: usize, k: usize, cnt: &Vec<usize>, ans: &mut Vec<usize>) -> Vec<usize> {
    // debug!(cur, u, k);
    let mut v = vec![0; 20];
    if cur > u {
        return v;
    }
    let v1 = rec(cur*2, u, k, cnt, ans);
    let v2 = rec(cur*2+1, u, k, cnt, ans);
    v[0] = cnt[cur];

    let mut temp = min(k, cnt[cur]);
    let mut cost = 0;
    for i in 0..19 {
        v[i+1] = v1[i] + v2[i];
        if k - temp > 0 {
            cost += (i+1) * min(k-temp, v[i+1]);
            temp += min(k-temp, v[i+1]);
        }
    }
    if temp == k {
        ans[cur] = cost;
    }
    v
}

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,
      aa: [usize; n],
    }
    let mut m = *aa.iter().max().unwrap();
    let mut cnt = vec![0; m+1];
    let mut ans = vec![INF; m+1];
    for a in aa {
        cnt[a] += 1;
    }
    rec(1, m, k, &cnt, &mut ans);
    let ans = ans.iter().min().unwrap();
    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);
}

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

    //}
}

/*

*/

use std::rc::Rc;

struct Scanner<T: std::io::Read> {
    reader: Rc<T>,
    buffer: [u8; 4096],
    position: usize,
    size: usize
}

impl<T: std::io::Read> Scanner<T> {
    const SPACES: [i32; 4] = [
        ' ' as i32,
        '\n' as i32,
        '\t' as i32,
        '\r' as i32];
    const ZERO: i32 = '0' as i32;
    const NINE: i32 = '9' as i32;
    const NEG: i32 = '-' as i32;
    const EOF: i32 = -1;

    fn new(reader: T) -> Scanner<T> {
        Scanner {
            reader: Rc::new(reader),
            buffer: [0; 4096],
            position: 0,
            size: 0
        }
    }

    fn read_block(&mut self) {
        self.size = Rc::get_mut(&mut self.reader).unwrap().read(&mut self.buffer).unwrap();
        self.position = 0;
    }

    fn read_char(&mut self) -> i32 {
        if self.position >= self.size {
            self.read_block();
            if self.position >= self.size {
                return Scanner::<T>::EOF;
            }
        }

        let ch = self.buffer[self.position];
        self.position += 1;

        ch as i32
    }

    fn read_char_skip_ws(&mut self) -> i32 {
        let mut ch = self.read_char();
        while ch != Scanner::<T>::EOF && Scanner::<T>::SPACES.contains(&ch) {
            ch = self.read_char();
        }

        if ch == Scanner::<T>::EOF {
            return Scanner::<T>::EOF;
        }

        return ch;
    }

    fn read_int(&mut self) -> Option<i32> {
        let mut ch = self.read_char_skip_ws();
        if ch == Scanner::<T>::EOF {
            return None;
        }

        let mut negative = false;
        if ch == Scanner::<T>::NEG {
            negative = true;
            ch = self.read_char();
        }

        let mut result = 0;
        while ch != Scanner::<T>::EOF && ch >= Scanner::<T>::ZERO && ch <= Scanner::<T>::NINE {
            result = result * 10 + ch - Scanner::<T>::ZERO;
            ch = self.read_char();
        }

        Some(if negative {
            -result
        } else {
            result
        })
    }
}

impl Scanner<std::io::Stdin> {
    fn new_stdin() -> Scanner<std::io::Stdin> {
        Scanner::new(std::io::stdin())
    }
}

fn main() {
    let mut reader = Scanner::new_stdin();

    let n = reader.read_int().unwrap() as usize;
    let k = reader.read_int().unwrap();
    let mut a: Vec<i32> = Vec::with_capacity(n);
    for _ in 0..n {
        a.push(reader.read_int().unwrap());
    }

    let amax = *a.iter().max().unwrap();
    let mut c: Vec<i32> = vec![0; (amax + 1) as usize];
    for x in a.iter() {
        c[*x as usize] += 1;
    }
    for i in 1..=amax as usize {
        c[i] += c[i - 1];
    }

    let mut ans = std::i32::MAX;
    for val in 1..=amax {
        let mut rest = k;
        let mut curr_ans = 0;
        let mut depth = 0;

        while rest > 0 {
            let low = val << depth;
            if low > amax {
                break;
            }

            let mut high = low + (1 << depth) - 1;
            if high > amax {
                high = amax;
            }
            let depth_cnt = c[high as usize] - c[(low - 1) as usize];

            if depth_cnt <= rest {
                curr_ans += depth_cnt * depth;
                rest -= depth_cnt;
                depth += 1;
            } else {
                curr_ans += rest * depth;
                rest = 0;
            }
        }

        if rest > 0 {
            continue;
        }

        if curr_ans < ans {
            ans = curr_ans;
        }
    }

    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_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);
}

use std::io;
const Z: usize = 200000;

fn uints() -> Vec<usize> {
    let mut buf = String::new();
	io::stdin().read_line(&mut buf);
	buf
    .split_ascii_whitespace()
    .map(str::parse::<usize>)
    .collect::<Result<Vec<usize>, _>>()
    .unwrap()
}

fn solve(k: usize, a: Vec<usize>) -> usize {
    let mut t: Vec<Vec<_>> = vec![Vec::new(); Z + 1];
    for mut x in a {
        let mut cnt = 0;
        loop {
            t[x].push(cnt);
            cnt += 1;
            if x == 0 {
                break;
            } else {
                x /= 2;
            }
        }
    }
    for mut v in t.iter_mut() {
        v.sort();
    }
    t.iter()
        .filter(|w| w.len() >= k)
        .map(|w| (&w[..k]).iter().sum::<usize>())
        .min()
        .unwrap()
}

fn main() {
    if let [_, k] = &uints()[..2] {
        println!("{}", solve(*k, uints()));
    }
}

use std::io;
use std::str::FromStr;
use std::num::ParseIntError;
use std::ops::Index;

struct RevBinary {
    data: Vec<bool>,
}

impl FromStr for RevBinary {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let i = s.parse::<u32>()?;

        Ok(RevBinary::new(i))
    }
}

impl Index<usize> for RevBinary {
    type Output = bool;

    fn index(&self, i: usize) -> &Self::Output {
        &self.data[self.data.len() - i - 1]
    }
}

impl RevBinary {
    fn new(x : u32) -> RevBinary {
        let mut y = x;
        let mut bin : Vec<bool> = Vec::new();
        while y != 0 {
           bin.push(if y % 2 == 1 { true } else { false });
           y /= 2;
        }
        RevBinary {
            data: bin,
        }
    }

    fn size(&self) -> usize {
        self.data.len()
    }
}

fn process_node(all: &Vec<RevBinary>, ind: Vec<usize>, depth: usize, k: u32) -> u32 {
    let mut result : u32 = ind.iter().take(k as usize).map(|&x| all[x].size() - depth).sum::<usize>() as u32;

    let mut new_ind0 : Vec<usize> = Vec::new();
    let mut new_ind1 : Vec<usize> = Vec::new();
    for i in ind.iter().filter(|&&x| all[x].size() > depth) {
        if all[*i][depth] {
            new_ind1.push(*i);
        } else {
            new_ind0.push(*i);
        }
    }
    if new_ind0.len() >= k as usize {
        result = result.min(process_node(&all, new_ind0, depth + 1, k));
    }
    if new_ind1.len() >= k as usize {
        result = result.min(process_node(&all, new_ind1, depth + 1, k));
    }
    result
}

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 n = input_iter.next().unwrap().parse::<usize>().unwrap();
    let k = input_iter.next().unwrap().parse::<u32>().unwrap();
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("failed to read input");
    let a = buffer.split_whitespace().map(|x| x.parse::<RevBinary>().unwrap()).collect::<Vec<RevBinary>>();

    println!("{}", process_node(&a, (0..n).collect::<Vec<usize>>(), 0, k));
}

#[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: [usize; n],
    }
    aa.sort();

    let mut ans: u64 = 1 << 60;
    for t in 0..n+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::io;

fn shift_count(mut from: i32, to: i32) -> i32 {
    let mut cnt = 0;
    while from > to {
        cnt += 1;
        from /= 2;
    }
    cnt
}

fn normalize(id: usize, input: &Vec<i32>) -> Vec<i32> {
    let norm_val = input[id];
    let mut normalized: Vec<i32> = input
        .iter()
        .map(|x| {
            if x < &norm_val {
                20000000
            } else {
                shift_count(*x, norm_val)
            }
        })
        .collect();

    normalized.sort_unstable();
    normalized
}

fn cost(normalized: &Vec<i32>, cnt: u8) -> i32 {
    normalized
        .iter()
        .take(cnt as usize)
        .fold(0, |acc, x| acc + x)
}

fn main() {
    let mut inp = String::new();
    io::stdin().read_line(&mut inp).unwrap();
    let line: Vec<u8> = 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 input: Vec<i32> = inp
        .split_whitespace()
        .map(|x| x.trim().parse::<i32>().unwrap())
        .collect();

    let mut norm_matrix: Vec<Vec<i32>> = Vec::with_capacity(input.len());

    let mut min_cost = std::i32::MAX;
    for i in 0..n {
        let norm = normalize(i as usize, &input);
        let c = cost(&norm, k);
        if c < min_cost {
            min_cost = c;
        }

        norm_matrix.push(norm);
    }

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

#![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;
        let mut m = 1i64;
        while m < 1000000 {
            let v = map.entry(m).or_insert(vec![]);
            v.sort();
            if v.len() < k { m*=2; continue; }
            let mut cnt = 0i64;
            for i in 0..k {
                cnt += v[i];
            }
            ans = min(ans, cnt);
            m *= 2;
        }
        for i in 0..n {
            let v = map.entry(a[i]).or_insert(vec![]);
            v.sort();
            if v.len() < k { continue; }
            let mut cnt = 0i64;
            for j in 0..k {
                cnt += v[j];
            }
            ans = min(ans, cnt);
        }

        println!("{}", ans);

    //}
}

/*

*/

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

const INF:usize= 2 << 30;

fn rec(cur: usize, u: usize, k: usize, cnt: &Vec<usize>, ans: &mut Vec<usize>) -> Vec<usize> {
    debug!(cur, u, k);
    let mut v = vec![0; 20];
    if cur > u {
        return v;
    }
    let v1 = rec(cur*2, u, k, cnt, ans);
    let v2 = rec(cur*2+1, u, k, cnt, ans);
    v[0] = cnt[cur];

    let mut temp = cnt[cur];
    let mut cost = 0;
    for i in 0..19 {
        v[i+1] = v1[i] + v2[i];
        if k - temp > 0 {
            cost += (i+1) * min(k-temp, v[i+1]);
            temp += min(k-temp, v[i+1]);
        }
    }
    if temp == k {
        ans[cur] = cost;
    }
    v
}

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,
      aa: [usize; n],
    }
    let mut m = *aa.iter().max().unwrap();
    let mut cnt = vec![0; m+1];
    let mut ans = vec![INF; m+1];
    for a in aa {
        cnt[a] += 1;
    }
    rec(1, m, k, &cnt, &mut ans);
    let ans = ans.iter().min().unwrap();
    puts!("{}\n", ans);
}


#![allow(unused_variables)]
#![allow(unused_must_use)]

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

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

    let n: usize = input.next();
    let mut a: Vec<usize> = input.iter().take(n).collect();
    a.sort();
    let mut cur = Vec::new();
    let mut ans = 0usize;
    for x in a {
        if !cur.iter().any(|&y| x % y == 0) {
            cur.push(x);
            ans += 1;
        }
    }
    puts!("{}\n", ans);
}

struct Input<R> {
    lines: io::Lines<R>,
    cur: String,
    split: std::str::SplitAsciiWhitespace<'static>, //'
}

impl<R: BufRead> Input<R> {
    fn new(reader: R) -> Input<R> {
        use std::mem::transmute;

        let mut lines = reader.lines();
        let cur = lines.next().unwrap().unwrap();
        let split = unsafe { transmute(cur.split_ascii_whitespace()) };
        Input { lines, cur, split }
    }
    fn update(&mut self) {
        use std::mem::transmute;
        self.cur = self.lines.next().unwrap().unwrap();
        unsafe { self.split = transmute(self.cur.split_ascii_whitespace()) };
    }
    fn next<F: std::str::FromStr>(&mut self) -> F {
        loop {
            if let Some(thing) = self.split.next() {
                return thing.parse().ok().unwrap();
            }
            self.update();
        }
    }
    fn iter<I: std::str::FromStr>(&mut self) -> InputIter<R, I> {
        InputIter {
            input: self,
            _phantom: std::marker::PhantomData,
        }
    }
}

struct InputIter<'a, R, I> {
    input: &'a mut Input<R>,
    _phantom: std::marker::PhantomData<I>,
}

impl<'a, R, I> Iterator for InputIter<'a, R, I>
where
    R: BufRead,
    I: std::str::FromStr,
{
    type Item = I;
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.input.next())
    }
}

// ######### contest shortcuts
#![allow(unused_imports, dead_code, unused_variables)]
use std::io::{stdin, stdout, BufWriter, BufReader, Read, Write};
use std::cmp;

#[derive(Default)]
struct Scanner (Vec<String>,);

impl Scanner {
    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.0.pop() {
                return token.parse().ok().expect("Failed parse");
            }
            let mut input = String::new();
            stdin().read_line(&mut input).expect("Failed read");
            self.0 = input.split_whitespace().rev()
                .map(String::from).collect();
        }
    }
}
// ## END ## contest shortcuts

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

    let n = scan.next::<usize>();
    // let mut a = scan.next::<String>();
    let a: Vec<u32> = (0..n)
        .map(|_| scan.next::<u32>())
        .collect();
    let mut s_a: Vec<_> = a.iter()
        .map(|e| e.clone())
        .enumerate()
        .collect();
    s_a.sort_by_key(|&(_, e)| e);
   // println!("{:?}", s_a);
    let mut marks = vec![false; n];
    let mut colors = 0usize;
    for &(j, e) in s_a.iter() {
        if marks[j] { continue; }
        colors += 1;

        for (i, ae) in a.iter().enumerate(){
            if marks[i] == false && ae % e == 0 {
                marks[i] = true;
                // println!("{:?}", e);
            }
        }
    }
    write!(out, "{}", colors).ok();
}

//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,
        a: [u32; n],
    }
    let mut n = n;
    let mut a = a;
    let mut ans = 0;
    while n > 0 {
        a.sort();
        let v = a[0];
        let mut b = vec![];
        for i in 1..n {
            if a[i] % v != 0 {
                b.push(a[i]);
            }
        }
        a = b;
        n = a.len();
        ans += 1;
    }
    println!("{}", ans);
}

fn main() {
    run();
}

//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,
        a: [u32; n],
    }
    let mut a = a;
    let mut ans = 0;
    while a.len() > 0 {
        ans += 1;
        let v = *a.iter().min().unwrap();
        a = a.into_iter().filter(|a| *a % v != 0).collect();
    }
    println!("{}", ans);
}

fn main() {
    run();
}