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


ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not nice.Now, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him?

The first and only line of the input contains a single string s (1 ≤ |s| ≤ 50 000), the word that ZS the Coder remembers. Each character of the string is the uppercase letter of English alphabet ('A'-'Z') or is a question mark ('?'), where the question marks denotes the letters that ZS the Coder can't remember.

If there is no way to replace all the question marks with uppercase letters such that the resulting word is nice, then print  - 1 in the only line. Otherwise, print a string which denotes a possible nice word that ZS the Coder learned. This string should match the string from the input, except for the question marks replaced with uppercase English letters. If there are multiple solutions, you may print any of them.

NoteIn the first sample case, ABCDEFGHIJKLMNOPQRZTUVWXYS is a valid answer beacuse it contains a substring of length 26 (the whole string in this case) which contains all the letters of the English alphabet exactly once. Note that there are many possible solutions, such as ABCDEFGHIJKLMNOPQRSTUVWXYZ or ABCEDFGHIJKLMNOPQRZTUVWXYS.In the second sample case, there are no missing letters. In addition, the given string does not have a substring of length 26 that contains all the letters of the alphabet, so the answer is  - 1.In the third sample case, any string of length 26 that contains all letters of the English alphabet fits as an answer.

use std::io::prelude::*;
use std::io;
use std::str;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [-1i32; 26];
    let mut laschr : Vec<char> = vec![];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for (i, ch) in s.chars().enumerate() {
        laschr.push(ch);

        match ch {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i as i32;
            }
        }

        if i > 25 {
            match laschr.remove(0) {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and store the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if laspos[j] != -1 && i - (laspos[j] as usize) < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string
        if count + wildcd >= 26 {

            let mut output = String::new();

            for chr in s.chars().take(i-25) {
                //print 'A' in the question mark spots before the substring
                match chr {
                    '?' => {
                        output.push('A');
                    },
                    c => {
                        output.push(c);
                    }
                }
            }

            for chr in s.chars().skip(i-25) {

                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        output.push(letters.pop().unwrap_or('Z'));
                    },
                    c => {
                        output.push(c);
                    }
                }
            }

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

    }

    println!("-1");
}

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

fn main(){

    let cs: Vec<char> = get_line().chars().collect();
    let len = cs.len();

    if len < 26 {
        println!("-1");
        return;
    }

    for i in 0..len-25 {
        let mut freq: Vec<usize> = vec![0;26];
        for j in i..i+26 {
            if cs[j] == '?' {
                continue;
            }
            let c = cs[j] as usize - 'A' as usize;
            freq[c] += 1;
        }

        if freq.iter().any(|&x: &usize| x > 1) {
            continue;
        }

        for j in 0..i {
            print!("{}", if cs[j] == '?' { 'A' } else { cs[j] })
        }

        for j in i..i+26 {
            if cs[j] != '?' {
                print!("{}", cs[j]);
            } else {
                for k in 0..26 {
                    if freq[k] == 0 {
                        print!("{}", (k as u8 + 'A' as u8) as char);
                        freq[k] = 1;
                        break;
                    }
                }
            }
        }

        for j in i+26..len {
            print!("{}", if cs[j] == '?' { 'A' } else { cs[j] })
        }
        return;
    }

    println!("-1")
}

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

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

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

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

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

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

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

#![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 checked_sub(a : usize, b : usize) -> usize {
   if b > a {
      println!("Checked sub failed!, {}, {}", a, b);
   }
   a - b
}

fn main() {
   let mut s = Scanner::new();
   let buffer : String = s.next();
   let mut input = buffer.into_bytes();

   let mut set : [i32; 30] = [0; 30];
   let mut count = 0;
   let mut left = 0;
   let mut right = 26;
   let b = 'A' as usize;

   if input.len() < 26 {
      println!("-1");
      return;
   }

   for i in left..right {
      let c = input[i] as char;
      let k = input[i] as usize;
      if c == '?' {
         count += 1;
         set[26] += 1;
      } else {

         if set[checked_sub(k, b)] == 0 {
            count += 1;
         }
         set[checked_sub(k, b)] += 1;
      }
   }

   let mut tail = input[left] as usize;
   for i in right..input.len() {
      let c = input[i] as char;
      let k = input[i] as usize;

      if count == 26 {
         break;
      }

      if tail == '?' as usize {
         set[26] -= 1;
         count -= 1;
      } else {
         set[checked_sub(tail, b)] -= 1;
         if set[checked_sub(tail, b)] == 0 {
            count -= 1;
         }
      }

      if c == '?' {
         count += 1;
         set[26] += 1;
      } else {
         if set[checked_sub(k, b)] == 0 {
            count += 1;
         }
         set[checked_sub(k, b)] += 1;
      }

      left += 1;
      right += 1;
      tail = input[left] as usize;
   }

   if count == 26 {

      for i in 0..left {
         let c = input[i] as char;
         if c == '?' {
            input[i] = 'A' as u8;
         }
      }

      for i in left..right {
         let c = input[i] as char;
         if c == '?' {
            for j in 0..27 {
               if set[j] == 0 {
                  let k = j as u8;
                  input[i] = k + b as u8;
                  set[j] = 1;
                  break;
               }
            }
         }
      }

      for i in right..input.len() {
         let c = input[i] as char;
         if c == '?' {
            input[i] = 'A' as u8;
         }
      }

      for i in input.iter() {
         print!("{}", *i as char);
      }
      println!("");
   } else {
      println!("-1");
   }
}

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

fn main() {
   let mut buffer : String = String::new();
   stdin().read_line(&mut buffer).ok();
   let mut input = buffer.trim().to_string().into_bytes();

   let mut set : [i32; 30] = [0; 30];
   let mut count = 0;
   let mut left = 0;
   let mut right = 26;
   let b = 'A' as usize;

   if input.len() < 26 {
      println!("-1");
      return;
   }

   for i in left..right {
      let c = input[i] as char;
      let k = input[i] as usize;
      if c == '?' {
         count += 1;
         set[26] += 1;
      } else {

         if set[k - b] == 0 {
            count += 1;
         }
         set[k - b] += 1;
      }
   }

   let mut tail = input[left] as usize;
   for i in right..input.len() {
      let c = input[i] as char;
      let k = input[i] as usize;

      if count == 26 {
         break;
      }

      if tail == '?' as usize {
         set[26] -= 1;
         count -= 1;
      } else {
         set[tail - b] -= 1;
         if set[tail - b] == 0 {
            count -= 1;
         }
      }

      if c == '?' {
         count += 1;
         set[26] += 1;
      } else {
         if set[k - b] == 0 {
            count += 1;
         }
         set[k - b] += 1;
      }

      left += 1;
      right += 1;
      tail = input[left] as usize;
   }

   if count == 26 {

      for i in 0..left {
         let c = input[i] as char;
         if c == '?' {
            input[i] = 'A' as u8;
         }
      }

      for i in left..right {
         let c = input[i] as char;
         if c == '?' {
            for j in 0..27 {
               if set[j] == 0 {
                  let k = j as u8;
                  input[i] = k + b as u8;
                  set[j] = 1;
                  break;
               }
            }
         }
      }

      for i in right..input.len() {
         let c = input[i] as char;
         if c == '?' {
            input[i] = 'A' as u8;
         }
      }

      for i in input.iter() {
         print!("{}", *i as char);
      }
      println!("");
   } else {
      println!("-1");
   }
}

use std::io::prelude::*;
use std::io;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [(s.len()); 26];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for i in 0..(s.len()) {
        match s.chars().skip(i).next().unwrap() {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i;
            }
        }

        if i > 26 {
            match s.chars().skip(i-26).next().unwrap() {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if i - laspos[j] < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string.
        if count + wildcd >= 26 {
            for chr in s.chars().skip(i-25).take(26) {
                match chr {
                    '?' => {
                        print!("{}", letters.pop().unwrap_or('?'));
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }
            println!("");
            return;
        }

    }

    println!("-1");
}

use std::io::prelude::*;
use std::io;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [(s.len()+27); 26];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for i in 0..(s.len()) {
        match s.chars().skip(i).next().unwrap() {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i;
            }
        }

        if i > 26 {
            match s.chars().skip(i-26).next().unwrap() {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if i - laspos[j] < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string.
        if count + wildcd >= 26 {
            for chr in s.chars().skip(i-25).take(26) {
                match chr {
                    '?' => {
                        print!("{}", letters.pop().unwrap_or('?'));
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }
            println!("");
            return;
        }

    }

    println!("-1");
}

use std::io::prelude::*;
use std::io;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [-1i32; 26];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for i in 0..(s.len()) {
        match s.chars().skip(i).next().unwrap() {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i as i32;
            }
        }

        if i > 26 {
            match s.chars().skip(i-26).next().unwrap() {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if laspos[j] != -1 && i - (laspos[j] as usize) < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string.
        if count + wildcd >= 26 {
            for chr in s.chars().skip(i-25).take(26) {
                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        print!("{}", letters.pop().unwrap_or('?'));
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }
            println!("");
            return;
        }

    }

    println!("-1");
}

use std::io::prelude::*;
use std::io;
use std::str;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [-1i32; 26];
    let mut laschr : Vec<char> = vec![];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for (i, ch) in s.chars().enumerate() {
        laschr.push(ch);

        match ch {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i as i32;
            }
        }

        if i > 26 {
            match laschr.remove(0) {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if laspos[j] != -1 && i - (laspos[j] as usize) < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string
        if count + wildcd >= 26 {

            let mut output = String::new();

            for chr in s.chars().take(i-25) {
                //print 'A' in the question mark spots before the substring
                match chr {
                    '?' => {
                        output.push('A');
                    },
                    c => {
                        output.push(c);
                    }
                }
            }

            for chr in s.chars().skip(i-25) {

                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        output.push(letters.pop().unwrap_or('Z'));
                    },
                    c => {
                        output.push(c);
                    }
                }
            }

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

    }

    println!("-1");
}

use std::io::prelude::*;
use std::io;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [-1i32; 26];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for i in 0..(s.len()) {
        match s.chars().skip(i).next().unwrap() {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i as i32;
            }
        }

        if i > 26 {
            match s.chars().skip(i-26).next().unwrap() {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if laspos[j] != -1 && i - (laspos[j] as usize) < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string.
        if count + wildcd >= 26 {

            for chr in s.chars().take(i-25) {
                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        print!("A");
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }

            for chr in s.chars().skip(i-25).take(26) {
                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        print!("{}", letters.pop().unwrap_or('?'));
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }

            for chr in s.chars().skip(i) {
                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        print!("A");
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }
            println!("");
            return;
        }

    }

    println!("-1");
}

use std::io::prelude::*;
use std::io;
use std::str;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [-1i32; 26];
    let mut laschr : Vec<char> = vec![];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for (i, ch) in s.chars().enumerate() {
        laschr.push(ch);

        match ch {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i as i32;
            }
        }

        if i > 26 {
            match laschr.remove(0) {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if laspos[j] != -1 && i - (laspos[j] as usize) < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string
        if count + wildcd >= 26 {

            let mut output = String::new();

            for chr in s.chars().take(i-25) {
                //print 'A' in the question mark spots before the substring
                match chr {
                    '?' => {
                        output.push('A');
                    },
                    c => {
                        output.push(c);
                    }
                }
            }

            for chr in s.chars().skip(i-25).take(26) {

                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        output.push(letters.pop().unwrap_or('?'));
                    },
                    c => {
                        output.push(c);
                    }
                }
            }

            for chr in s.chars().skip(i+1) {

                //print 'Z' in the question mark spots after the substring
                match chr {
                    '?' => {
                        output.push('Z');
                    },
                    c => {
                        output.push(c);
                    }
                }
            }
            println!("{}", output);
            return;
        }

    }

    println!("-1");
}

use std::io::prelude::*;
use std::io;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [-1i32; 26];
    let mut laschr : Vec<char> = vec![];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for (i, ch) in s.chars().enumerate() {
        laschr.push(ch);

        match ch {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i as i32;
            }
        }

        if i > 26 {
            match laschr.remove(0) {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if laspos[j] != -1 && i - (laspos[j] as usize) < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string.
        if count + wildcd >= 26 {

            for chr in s.chars().take(i-25) {
                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        print!("A");
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }

            for chr in s.chars().skip(i-25).take(26) {

                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        print!("{}", letters.pop().unwrap_or('?'));
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }

            for chr in s.chars().skip(i+1) {

                //print missing letters in the question mark spots
                match chr {
                    '?' => {
                        print!("A");
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }
            println!("");
            return;
        }

    }

    println!("-1");
}

use std::io::prelude::*;
use std::io;

fn main() {
    let stdin = io::stdin();
    let mut s = stdin.lock().lines().next().unwrap().unwrap();

    is_nice_word(&s);
}

fn is_nice_word(s: &String) {

    // list of the last position each letter A-Z was seen
    let mut laspos = [-1i32; 26];
    //how many wildcards '?' there were in the last 26 characters
    let mut wildcd = 0;

    for i in 0..(s.len()) {
        match s.chars().skip(i).next().unwrap() {
            '?' => {
                wildcd += 1;
            },
            chr => {
                laspos[((chr as u8) - ('A' as u8)) as usize] = i as i32;
            }
        }

        if i > 26 {
            match s.chars().skip(i-26).next().unwrap() {
                '?' => {
                    wildcd -= 1;
                },
                _ => ()
            }
        }

        // count how many letters occur in the last 26 characters and remember the ones that didn't
        // also keep track of how many wildcards we have seen
        let mut count = 0;
        let mut letters : Vec<char>= vec![];
        for j in 0..26 {
            if laspos[j] != -1 && i - (laspos[j] as usize) < 26 {
                count += 1;
            } else {
                letters.push((('A' as u8) + j as u8) as char);
            }
        }

        //If we have seen enough characters and wildcards, print out the string.
        if count + wildcd >= 26 {
            for chr in s.chars().skip(i-25).take(26) {
                match chr {
                    '?' => {
                        print!("{}", letters.pop().unwrap_or('?'));
                    },
                    c => {
                        print!("{}", c);
                    }
                }
            }
            println!("");
            return;
        }

    }

    println!("-1");
}

#![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 set = [0; 27];
   let mut count = 0;
   let mut left = 0;
   let mut right = 26;

   for i in input.chars().take(26) {
      let k = i as usize;
      let b = 'A' as usize;
      if i == '?' {
         count += 1;
         set[26] += 1;
      } else {
         if set[k - b] == 0 {
            count += 1;
         }
         set[k - b] += 1;
      }
   }

   let mut ans : String = input[left..right].to_string();

   let mut tail = input.chars().nth(1).unwrap() as usize;
   for i in input.chars().skip(26) {
      let k = i as usize;
      let b = 'A' as usize;

      if count == 26 {
         ans = input[left..right].to_string();
         break;
      }

      if tail == '?' as usize {
         set[26] -= 1;
         count -= 1;
      } else {
         set[tail - b] -= 1;
         if set[tail - b] == 0 {
            count -= 1;
         }
      }

      if i == '?' {
         count += 1;
         set[26] += 1;
      } else {
         if set[k - b] == 0 {
            count += 1;
         }
         set[k - b] += 1;
      }

      tail = k;
      left += 1;
      right += 1;
   }

   let mut filled : String = String::new();

   for i in ans.chars() {
      let b = 'A' as u8;
      if i == '?' {
         for j in 0..27 {
            if set[j] == 0 {
               let k = j as u8;
               filled.push((k + b) as char);
               set[j] = 1;
               break;
            }
         }
      } else {
         filled.push(i);
      }
   }

   if count == 26 {
      println!("{}", filled);
   } else {
      println!("-1");
   }
}

#![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 set = [0; 27];
   let mut count = 0;
   let mut left = 0;
   let mut right = 26;

   for i in input.chars().take(26) {
      let k = i as usize;
      let b = 'A' as usize;
      if i == '?' {
         count += 1;
         set[26] += 1;
      } else {
         if set[k - b] == 0 {
            count += 1;
         }
         set[k - b] += 1;
      }
   }

   let mut tail = input.chars().nth(left).unwrap() as usize;
   for i in input.chars().skip(26) {
      let k = i as usize;
      let b = 'A' as usize;

      if count == 26 {
         break;
      }

      if tail == '?' as usize {
         set[26] -= 1;
         count -= 1;
      } else {
         set[tail - b] -= 1;
         if set[tail - b] == 0 {
            count -= 1;
         }
      }

      if i == '?' {
         count += 1;
         set[26] += 1;
      } else {
         if set[k - b] == 0 {
            count += 1;
         }
         set[k - b] += 1;
      }

      left += 1;
      right += 1;
      tail = input.chars().nth(left).unwrap() as usize;
   }

   let mut filled : String = String::new();

   if count == 26 {
      for i in input.chars().take(left) {
         if i == '?' {
            filled.push('A');
         } else {
            filled.push(i);
         }
      }

      for i in input.chars().skip(left).take(right) {
         let b = 'A' as u8;
         if i == '?' {
            for j in 0..27 {
               if set[j] == 0 {
                  let k = j as u8;
                  filled.push((k + b) as char);
                  set[j] = 1;
                  break;
               }
            }
         } else {
            filled.push(i);
         }
      }

      for i in input.chars().skip(left + right) {
         if i == '?' {
            filled.push('A');
         } else {
            filled.push(i);
         }
      }

      println!("{}", filled);
   } else {
      println!("-1");
   }
}


On a chessboard with a width of $$$n$$$ and a height of $$$n$$$, rows are numbered from bottom to top from $$$1$$$ to $$$n$$$, columns are numbered from left to right from $$$1$$$ to $$$n$$$. Therefore, for each cell of the chessboard, you can assign the coordinates $$$(r,c)$$$, where $$$r$$$ is the number of the row, and $$$c$$$ is the number of the column.The white king has been sitting in a cell with $$$(1,1)$$$ coordinates for a thousand years, while the black king has been sitting in a cell with $$$(n,n)$$$ coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates $$$(x,y)$$$...Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates $$$(x,y)$$$ first will win.Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the $$$(a,b)$$$ cell, then in one move he can move from $$$(a,b)$$$ to the cells $$$(a + 1,b)$$$, $$$(a - 1,b)$$$, $$$(a,b + 1)$$$, $$$(a,b - 1)$$$, $$$(a + 1,b - 1)$$$, $$$(a + 1,b + 1)$$$, $$$(a - 1,b - 1)$$$, or $$$(a - 1,b + 1)$$$. Going outside of the field is prohibited.Determine the color of the king, who will reach the cell with the coordinates $$$(x,y)$$$ first, if the white king moves first.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^{18}$$$) — the length of the side of the chess field. The second line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x,y \le n$$$) — coordinates of the cell, where the coin fell.

In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower).

NoteAn example of the race from the first sample where both the white king and the black king move optimally: The white king moves from the cell $$$(1,1)$$$ into the cell $$$(2,2)$$$. The black king moves form the cell $$$(4,4)$$$ into the cell $$$(3,3)$$$. The white king moves from the cell $$$(2,2)$$$ into the cell $$$(2,3)$$$. This is cell containing the coin, so the white king wins.  An example of the race from the second sample where both the white king and the black king move optimally: The white king moves from the cell $$$(1,1)$$$ into the cell $$$(2,2)$$$. The black king moves form the cell $$$(5,5)$$$ into the cell $$$(4,4)$$$. The white king moves from the cell $$$(2,2)$$$ into the cell $$$(3,3)$$$. The black king moves from the cell $$$(4,4)$$$ into the cell $$$(3,5)$$$. This is the cell, where the coin fell, so the black king wins.  In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins.

fn dist(x:i64,y:i64,x1:i64,y1:i64) -> i64{
    return std::cmp::max((x-x1).abs(), (y-y1).abs());
}

fn read_line() -> Vec<i64>{
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).unwrap();
    return input.trim().split(" ").map(|x|{x.parse::<i64>().unwrap()}).collect();
}

fn main(){
    let WHITE = "White";
    let BLACK = "Black";
    let mut line = read_line();
    let n = line[0];
    line = read_line();
    let (x,y) = (line[0],line[1]);
    if dist(1,1,x,y)<=dist(n,n,x,y){
        println!("{}",WHITE);
    }else{
        println!("{}",BLACK);
    }
}

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

    let mut it = input.split_whitespace();

    let n: u64 = it.next().unwrap().parse().unwrap();
    let x: u64 = it.next().unwrap().parse().unwrap();
    let y: u64 = it.next().unwrap().parse().unwrap();

    let sum = x + y;
    let answer = if sum > n + 1 {
        Answer::Black
    } else {
        Answer::White
    };

    match answer {
        Answer::Black => {
            println!("Black");
        }
        Answer::White => {
            println!("White");
        }
    };
}

enum Answer {
    Black,
    White,
}

fn dist(x: i64, y: i64) -> i64 {
    return std::cmp::min(x, y) + (x - y).abs();
}

fn read_line() -> Vec<i64> {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    return buf.trim().split(" ").map(|x| { x.parse::<i64>().unwrap() }).collect();
}

fn main() {
    let l1 = read_line();
    let l2 = read_line();
    let n: i64 = l1[0];
    let x: i64 = l2[0];
    let y: i64 = l2[1];
    let d1 = dist(x, y);
    let d2 = dist(n - x + 1, n - y + 1);
    if d2 < d1 {
        println!("Black");
    } else {
        println!("White");
    }
}


Daenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains ai soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1, 2}, {3, 4}, {4, 5}, {5, 6} or {7, 8}.  A row in the airplane Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats.Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.

The first line contains two integers n and k (1 ≤ n ≤ 10000, 1 ≤ k ≤ 100) — the number of rows and the number of groups of soldiers, respectively. The second line contains k integers a1, a2, a3, ..., ak (1 ≤ ai ≤ 10000), where ai denotes the number of soldiers in the i-th group. It is guaranteed that a1 + a2 + ... + ak ≤ 8·n.

If we can place the soldiers in the airplane print "YES" (without quotes). Otherwise print "NO" (without quotes). You can choose the case (lower or upper) for each letter arbitrary.

NoteIn the first sample, Daenerys can place the soldiers like in the figure below:  In the second sample, there is no way to place the soldiers in the plane since the second group soldier will always have a seat neighboring to someone from the first group.In the third example Daenerys can place the first group on seats (1, 2, 7, 8), and the second group an all the remaining seats.In the fourth example she can place the first two groups on seats (1, 2) and (7, 8), the third group on seats (3), and the fourth group on seats (5, 6).

use std::io::stdin;
use std::cmp::*;

fn main() {
    let (n, _) = {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        let mut it = input.split_whitespace().map(|k| k.parse::<usize>().unwrap());
        (it.next().unwrap(), it.next().unwrap())
    };

    let mut a = String::new();
    stdin().read_line(&mut a).unwrap();
    let a = a.split_whitespace().map(|k| k.parse::<usize>().unwrap());
    let (mut a1, mut a2, mut a4) = a.fold((0, 0, 0), |(a1, a2, a4), ai| (a1 + ai % 2, a2 + ai % 4 - ai % 2, a4 + ai - ai % 4));

    let mut s4 = 4 * n;
    let mut s2 = 4 * n;

    let tmp = min(a2, s2);
    a2 -= tmp;
    s2 -= tmp;
    let tmp = min(a2, s4 / 2);
    a2 -= tmp;
    s4 -= tmp;
    let tmp = min(2 * a2, s4);
    a2 -= tmp / 2;
    s4 -= tmp;
    let tmp = min(a4, s4);
    a4 -= tmp;
    s4 -= tmp;
    let tmp = min(a4, s2);
    a4 -= tmp;
    s2 -= tmp;
    let tmp = min(a1, s4 / 2);
    a1 -= tmp;
    let tmp = min(a1, s2 / 2);
    a1 -= tmp;

    if a1 + a2 + a4 > 0 {
        println!("NO");
    } else {
        println!("YES");
    }
}

use std::io::stdin;

fn main() {
    let (n, _) = {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        let mut it = input.split_whitespace().map(|k| k.parse::<usize>().unwrap());
        (it.next().unwrap(), it.next().unwrap())
    };

    let mut a = String::new();
    stdin().read_line(&mut a).unwrap();
    let a = a.split_whitespace().map(|k| k.parse::<usize>().unwrap());
    let (a1, a2, a4) = a.fold((0, 0, 0), |(a1, a2, a4), ai| (a1 + ai % 2, a2 + ai % 4 / 2, a4 + ai / 4));

    if a2 <= 3 * n && a2 + a1 <= 4 * n && 4 * a4 + 2 * a2 + 2 * a1 <= 8 * n {
        println!("YES");
    } else {
        println!("NO");
    }
}

use std::io::stdin;

fn main() {
    let (n, _) = {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        let mut it = input.split_whitespace().map(|k| k.parse::<usize>().unwrap());
        (it.next().unwrap(), it.next().unwrap())
    };

    let mut a = String::new();
    stdin().read_line(&mut a).unwrap();
    let a = a.split_whitespace().map(|k| k.parse::<usize>().unwrap());
    let (al, n_al) = a.fold((0, 0), |(al, n_al), ai| (al + ai % 2, n_al + ai / 2));

    if  al + n_al <= n * 4 {
        println!("YES");
    } else {
        println!("NO");
    }
}