The only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king.Check the king's moves here https://en.wikipedia.org/wiki/King_(chess).  King moves from the position e4

The only line contains the king's position in the format "cd", where 'c' is the column from 'a' to 'h' and 'd' is the row from '1' to '8'.

Print the only integer x — the number of moves permitted for the king.

fn main() {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).expect("Error");
    let letter = line.chars().nth(0).expect("Error");
    let number = line.chars().nth(1).expect("Error");
    let array = [letter, number];

    fn boundary(a: char) -> bool {
        match a {
            'a' | 'h' | '1' | '8' => true,
            _ => false,
        }
    }
    let cnt = array.iter().map(|x| boundary(*x)).filter(|x| *x).count();

    let res = match cnt {
        0 => 8,
        1 => 5,
        2 => 3,
        _ => unreachable!(),
    };
    println!("{}", res);
}

use std::io;

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

    io::stdin().read_line(&mut guess)
        .expect("Failed to read whatever you enter");

    let first = guess.chars().nth(0).unwrap();
    let second = guess.chars().nth(1).unwrap();
    let mut allow = 8;
    let mut left_or_rigt_most = false;

    if first == 'a' || first == 'h' {
        left_or_rigt_most = true;
        allow -= 3;
    }

    if second == '1' || second == '8' {
        if left_or_rigt_most {
            allow -= 2;
        } else {
            allow -= 3;
        }
    }

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

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

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

struct Scanner {
   buffer : std::collections::VecDeque<String>
}

impl Scanner {

   fn new() -> Scanner {
      Scanner {
         buffer: std::collections::VecDeque::new()
      }
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {

      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      let front = self.buffer.pop_front().unwrap();
      front.parse::<T>().ok().unwrap()
   }
}

fn main() {
   let mut s = Scanner::new();
   let input = s.next::<String>();
   let mut iter = input.chars();
   let column = iter.next().unwrap();
   let row = iter.next().unwrap();

   if column == 'a' || column == 'h' {
      if row == '1' || row == '8' {
         println!("3");
      } else {
         println!("5");
      }
   } else if row == '1' || row == '8' {
      if column == 'a' || column == 'h' {
         println!("3");
      } else {
         println!("5");
      }
   } else {
      println!("8");
   }
}

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

macro_rules! debug(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

struct Scanner {
   buffer : std::collections::VecDeque<String>
}

impl Scanner {

   fn new() -> Scanner {
      Scanner {
         buffer: std::collections::VecDeque::new()
      }
   }

   fn next<T : std::str::FromStr >(&mut self) -> T {

      if self.buffer.len() == 0 {
         let mut input = String::new();
         std::io::stdin().read_line(&mut input).ok();
         for word in input.split_whitespace() {
            self.buffer.push_back(word.to_string())
         }
      }

      let front = self.buffer.pop_front().unwrap();
      front.parse::<T>().ok().unwrap()
   }
}

fn main() {
   let mut s = Scanner::new();
   let input : String = s.next();
   println!("8");
}


The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".

The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.

Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.

use std::io::stdin;
fn main() {
    let mut text = String::new();
    stdin().read_line(&mut text).unwrap();
    let text: Vec<&str> = text.trim().split_whitespace().collect();
    let mut value = 0;

    let mut val: Vec<String> = vec![];
    let a = text[0].chars().collect::<Vec<char>>();
    let b = text[1].chars().collect::<Vec<char>>();
    let mut text1 = String::new();
    for x in &a {
        text1.push(*x);
        let mut text2 = String::new();

        for y in &b {
            text2.push(*y);
            val.push(text1.clone() + &text2[..]);
        }
    }
    val.sort();
    println!("{}", val[0]);
}

use std::io::stdin;
fn main() {
    let mut text = String::new();
    stdin().read_line(&mut text).unwrap();
    let text: Vec<&str> = text.trim().split_whitespace().collect();

    let mut val: Vec<String> = vec![];
    let a = text[0].chars().collect::<Vec<char>>();
    let b = text[1].chars().collect::<Vec<char>>();
    let mut text1 = String::new();
    if a.len() > 1 {
        for x in &a[1..] {
            if x < &b[0] {
                text1.push(*x);
            } else {
                break;
            }
        }
    }
    val.sort();
    println!("{}{}{}", a[0], text1, b[0]);
}

use std::io;

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

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

    let parts: Vec<&str> = input.trim().split(' ').collect();
    let mut logins: Vec<String> = vec![];

    for i in 1..(parts[0].len()+1) {
        for j in 1..(parts[1].len()+1) {
            let mut login = String::new();
            login.push_str(&parts[0][0..i]);
            login.push_str(&parts[1][0..j]);
            logins.push(login);
        }
    }

    logins.sort();

    println!("{}", logins[0]);
}


Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second — v0 + a pages, at third — v0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v1 pages per day.Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.Help Mister B to calculate how many days he needed to finish the book.

First and only line contains five space-separated integers: c, v0, v1, a and l (1 ≤ c ≤ 1000, 0 ≤ l < v0 ≤ v1 ≤ 1000, 0 ≤ a ≤ 1000) — the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.

Print one integer — the number of days Mister B needed to finish the book.

NoteIn the first sample test the book contains 5 pages, so Mister B read it right at the first day.In the second sample test at first day Mister B read pages number 1 - 4, at second day — 4 - 11, at third day — 11 - 12 and finished the book.In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.

#[macro_export]
macro_rules! scanln {
  ($($var:ident : $ty:path),+) => {
    $(let $var: $ty;)+
    {
      use std::io;
      let mut __buf = String::new();
      io::stdin().read_line(&mut __buf).unwrap();
      let mut eles = __buf.split_whitespace();
      $($var = Scan::scan(&mut eles);)+
    }
  }
}

pub trait Scan {
  fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator<Item=&'a str>;
}

macro_rules! impl_scan_single {
  ($ty:ty) => {
    impl Scan for $ty {
      fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator<Item=&'a str> {
        let next = eles.next().unwrap();
        match next.parse() {
          Ok(res) => res,
          Err(_) => panic!()
        }
      }
    }
  }
}

impl_scan_single!(u8);
impl_scan_single!(u16);
impl_scan_single!(u32);
impl_scan_single!(u64);
impl_scan_single!(usize);
impl_scan_single!(i8);
impl_scan_single!(i16);
impl_scan_single!(i32);
impl_scan_single!(i64);
impl_scan_single!(isize);
impl_scan_single!(f32);
impl_scan_single!(f64);
impl_scan_single!(String);

const __IMPL_SCAN_FOR_VEC: () = {
  use std::str::FromStr;
  impl<T> Scan for Vec<T> where T: FromStr {
    fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator<Item=&'a str> {
      eles.map(|str| match str.parse() {
        Ok(res) => res,
        Err(_) => panic!()
      }).collect()
    }
  }
};

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

fn main() {
  scanln!(c: u32, v0: u32, v1: u32, a: u32, l: u32);
  let mut speed = v0;
  let mut pages = 0;
  let mut days = 0;
  loop {
    days += 1;
    pages += speed;
    if pages >= c { break; }
    speed = std::cmp::min(speed + a, v1);
    pages -= l;
  }
  println!("{}", days);
}


Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the n-th point. Two points with coordinates (x1, 0) and (x2, 0) should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any).  Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.

The first line contains a single integer n (1 ≤ n ≤ 103). The second line contains n distinct integers x1, x2, ..., xn ( - 106 ≤ xi ≤ 106) — the i-th point has coordinates (xi, 0). The points are not necessarily sorted by their x coordinate.

In the single line print "yes" (without the quotes), if the line has self-intersections. Otherwise, print "no" (without the quotes).

NoteThe first test from the statement is on the picture to the left, the second test is on the picture to the right.

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

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

    fn next_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    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 line = self.next_line();
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

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

fn interval(a: isize, b: isize) -> (isize, isize) {
    (a.min(b), a.max(b))
}

fn clash(inter1: (isize, isize), inter2: (isize, isize)) -> bool {
    inter1.0 < inter2.0 && inter2.0 < inter1.1 && inter1.1 < inter2.1
        || inter2.0 < inter1.0 && inter1.0 < inter2.1 && inter2.1 < inter1.1
}

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    let arr: Vec<isize> = scan.next_n(n);
    let mut inters: Vec<(isize, isize)> = vec![];
    for i in 1..arr.len() {
        let current = interval(arr[i], arr[i - 1]);
        for &inter in &inters {
            if clash(current, inter) {
                println!("yes");
                return;
            }
        }
        inters.push(current);
    }
    println!("no");
}

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_line(&self) -> String {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("Fail to read");
        line
    }

    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 line = self.next_line();
            self.buffer = line.split_whitespace().map(String::from).collect();
        }
    }

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

fn interval(a: isize, b: isize) -> (isize, isize) {
    (a.min(b), a.max(b))
}

fn clash(inter1: (isize, isize), inter2: (isize, isize)) -> bool {
    inter1.0 < inter2.0 && inter1.1 < inter2.1 || inter2.0 < inter1.0 && inter2.1 < inter1.1
}

fn _main() {
    let mut scan = Scan::new();
    let n: usize = scan.next();
    let arr: Vec<isize> = scan.next_n(n);
    let mut inters: Vec<(isize, isize)> = vec![];
    for i in 1..arr.len() {
        let current = interval(arr[i], arr[i - 1]);
        for &inter in &inters {
            if clash(current, inter) {
                println!("yes");
                return;
            }
        }
        inters.push(current);
    }
    println!("no");
}

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


Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.The game is played on the following field.  Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (xl, yl) in some small field, the next move should be done in one of the cells of the small field with coordinates (xl, yl). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.

First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell. The line after the table contains two integers x and y (1 ≤ x, y ≤ 9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right. It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable.

Output the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified.

NoteIn the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable.

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

// 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,
}


Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP.In general, different values of HP are grouped into $$$4$$$ categories:  Category $$$A$$$ if HP is in the form of $$$(4 n + 1)$$$, that is, when divided by $$$4$$$, the remainder is $$$1$$$;  Category $$$B$$$ if HP is in the form of $$$(4 n + 3)$$$, that is, when divided by $$$4$$$, the remainder is $$$3$$$;  Category $$$C$$$ if HP is in the form of $$$(4 n + 2)$$$, that is, when divided by $$$4$$$, the remainder is $$$2$$$;  Category $$$D$$$ if HP is in the form of $$$4 n$$$, that is, when divided by $$$4$$$, the remainder is $$$0$$$. The above-mentioned $$$n$$$ can be any integer.These $$$4$$$ categories ordered from highest to lowest as $$$A > B > C > D$$$, which means category $$$A$$$ is the highest and category $$$D$$$ is the lowest.While playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most $$$2$$$ (that is, either by $$$0$$$, $$$1$$$ or $$$2$$$). How much should she increase her HP so that it has the highest possible category?

The only line contains a single integer $$$x$$$ ($$$30 \leq x \leq 100$$$) — the value Tokitsukaze's HP currently.

Print an integer $$$a$$$ ($$$0 \leq a \leq 2$$$) and an uppercase letter $$$b$$$ ($$$b \in \lbrace A, B, C, D \rbrace$$$), representing that the best way is to increase her HP by $$$a$$$, and then the category becomes $$$b$$$. Note that the output characters are case-sensitive.

NoteFor the first example, the category of Tokitsukaze's HP is already $$$A$$$, so you don't need to enhance her ability.For the second example:  If you don't increase her HP, its value is still $$$98$$$, which equals to $$$(4 \times 24 + 2)$$$, and its category is $$$C$$$.  If you increase her HP by $$$1$$$, its value becomes $$$99$$$, which equals to $$$(4 \times 24 + 3)$$$, and its category becomes $$$B$$$.  If you increase her HP by $$$2$$$, its value becomes $$$100$$$, which equals to $$$(4 \times 25)$$$, and its category becomes $$$D$$$. Therefore, the best way is to increase her HP by $$$1$$$ so that the category of her HP becomes $$$B$$$.

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


The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    res
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

use std::f64;

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

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

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

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

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

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

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

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

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

        let mut ans = INF;

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

        println!("{}", ans);

    //}
}

/*

*/

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

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

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

// ここまで

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

fn main() {
    run();
}

#[allow(unused_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;
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;

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

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

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


You are given a sequence of integers $$$a_1, a_2, \dots, a_n$$$. You need to paint elements in colors, so that:   If we consider any color, all elements of this color must be divisible by the minimal element of this color.  The number of used colors must be minimized. For example, it's fine to paint elements $$$[40, 10, 60]$$$ in a single color, because they are all divisible by $$$10$$$. You can use any color an arbitrary amount of times (in particular, it is allowed to use a color only once). The elements painted in one color do not need to be consecutive.For example, if $$$a=[6, 2, 3, 4, 12]$$$ then two colors are required: let's paint $$$6$$$, $$$3$$$ and $$$12$$$ in the first color ($$$6$$$, $$$3$$$ and $$$12$$$ are divisible by $$$3$$$) and paint $$$2$$$ and $$$4$$$ in the second color ($$$2$$$ and $$$4$$$ are divisible by $$$2$$$). For example, if $$$a=[10, 7, 15]$$$ then $$$3$$$ colors are required (we can simply paint each element in an unique color).

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$), where $$$n$$$ is the length of the given sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$). These numbers can contain duplicates.

Print the minimal number of colors to paint all the given numbers in a valid way.

NoteIn the first example, one possible way to paint the elements in $$$3$$$ colors is:  paint in the first color the elements: $$$a_1=10$$$ and $$$a_4=5$$$,  paint in the second color the element $$$a_3=3$$$,  paint in the third color the elements: $$$a_2=2$$$, $$$a_5=4$$$ and $$$a_6=2$$$. In the second example, you can use one color to paint all the elements.In the third example, one possible way to paint the elements in $$$4$$$ colors is:  paint in the first color the elements: $$$a_4=4$$$, $$$a_6=2$$$ and $$$a_7=2$$$,  paint in the second color the elements: $$$a_2=6$$$, $$$a_5=3$$$ and $$$a_8=3$$$,  paint in the third color the element $$$a_3=5$$$,  paint in the fourth color the element $$$a_1=7$$$.

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

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

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