use std::*;
use io::stdin;
use cmp::Ordering;
// use process::exit;
// use fs::File;
// use io::{BufRead, BufReader};

fn resolve_pool(
    s: &[bool], mut offset: usize, lhs: Vec<Val>, rhs: Vec<Val>,
    // f: &mut BufReader<File>,
) -> Result<(Vec<Val>, usize), FailReason> {
    // let mut line = String::new();
    // if f.read_line(&mut line).is_err() {
    //     exit(99)
    // }
    // let lmr: Vec<usize> = line
    //     .split(' ')
    //     // .filter_map(|x|
    //     //     if x.contains('\n') || x.contains('\r') {
    //     //         None
    //     //     } else {
    //     //         Some(x.parse::<usize>().unwrap())
    //     //     })
    //     .map(|x| {
    //         let x: String = x.chars().take_while(|c| !['\n', '\r'].contains(c)).collect();
    //         x.parse::<usize>().unwrap()
    //     })
    //     .collect();
    // assert_eq!(lmr.len(), 3);
    // let (l, m, r) = (lmr[0], lmr[1], lmr[2]);
    // assert_eq!(m - l, lhs.len());
    // assert_eq!(r - m, rhs.len());

    // let init_offset = offset;
    let mut l_ptr: usize = 0;
    let mut r_ptr: usize = 0;
    let mut next_pool = vec![];
    while l_ptr < lhs.len() && r_ptr < rhs.len() {
        // let l = &mut lhs[l_ptr];
        // let r = &mut rhs[r_ptr];
        let fst =
            if let Some(&c) = s.get(offset) {
                c
            } else {
                // dbg!(lhs);
                // dbg!(rhs);
                // exit(16);
                return Err(FailReason::NotEnoughMerges);
            };
        if !fst {
            next_pool.push(lhs[l_ptr]);
            // l.history.get_mut().push(false);
            // next_pool.push(Val {
            //     val: lhs[l_ptr].val,
            //     history: Cell::new(lhs[l_ptr].history.take()),
            // });
            l_ptr += 1;
        } else {
            next_pool.push(rhs[r_ptr]);
            // r.history.get_mut().push(true);
            // next_pool.push(Val {
            //     val: rhs[r_ptr].val,
            //     history: Cell::new(rhs[r_ptr].history.take()),
            // });
            r_ptr += 1;
        }
        offset += 1;
    }
    if l_ptr < lhs.len() {
        next_pool.extend(lhs[l_ptr..].iter())
        // for i in l_ptr..lhs.len() {
        //     lhs[i].history.get_mut().push(false);
        //     next_pool.push(Val {
        //         val: lhs[i].val,
        //         history: Cell::from(lhs[i].history.take()),
        //     })
        // }
    } else {
        next_pool.extend(rhs[r_ptr..].iter())
        // for i in r_ptr..rhs.len() {
        //     rhs[i].history.get_mut().push(true);
        //     next_pool.push(Val {
        //         val: rhs[i].val,
        //         history: Cell::from(rhs[i].history.take()),
        //     })
        // }
    }
    // let adv = offset - init_offset;
    // let mut line = String::new();
    // if f.read_line(&mut line).is_err() {
    //     exit(99)
    // }
    // let line: String = line.chars().take_while(|c| !['\n', '\r'].contains(c)).collect();
    // let act_adv =
    //     if let Ok(act_adv) = line.parse::<usize>() {
    //         act_adv
    //     } else {
    //         dbg!(line);
    //         exit(98)
    //     };
    // assert_eq!(adv, act_adv);

    Ok((next_pool, offset))
}

#[derive(Debug)]
enum FailReason {
    NotEnoughMerges,
    TooManyMerges,
}

type Val = usize;

// struct Val {
//     val: usize,
//     history: Cell<Vec<bool>>,
// }

fn solve(s: &[bool]) -> Vec<Val> {
    fn solve_with_assumed_size(
        s: &[bool], vals: Vec<Val>,
        // f: &mut BufReader<File>,
    ) -> Result<Vec<Val>, FailReason> {
        fn rec_resolve(
            mut rg: Vec<Val>,
            s: &[bool], offset: usize,
            // f: &mut BufReader<File>,
        ) -> Result<(Vec<Val>, usize), FailReason> {
            if rg.len() <= 1 {
                return Ok((rg, offset));
            }
            let lhs_upper = rg.len() >> 1;
            let rhs = rg.drain(lhs_upper..).collect();
            let lhs = rg;
            let res = rec_resolve(lhs, s, offset).unwrap();
            let (left_part_of_pool, offset) = res;
            let res = rec_resolve(rhs, s, offset).unwrap();
            let (right_part_of_pool, offset) = res;

            Ok(resolve_pool(s, offset, left_part_of_pool, right_part_of_pool)?)
        }

        // let merge_count = f64::log2(sz as f64) as usize;
        // let mut known_relations = vec![vec![None; vals.len()]; vals.len()];

        let (vals, offset) = rec_resolve(vals, s, 0)?;
        match offset.cmp(&s.len()) {
            Ordering::Less => Err(FailReason::TooManyMerges),
            Ordering::Greater => Err(FailReason::NotEnoughMerges),

            Ordering::Equal => {
                let mut ans = vec![0; vals.len()];
                for (i, pos) in vals.into_iter().enumerate() {
                    ans[pos] = i + 1;
                }
                Ok(ans)
            }
        }
    }

    let mut lower_bound = 2;
    let mut upper_bound = 1e5 as usize;
    // let mut lower_bound = upper_bound;
    let mut vals = Vec::with_capacity(upper_bound);
    for i in 0..upper_bound {
        vals.push(i)
        // vals.push(Val { val: i, history: Cell::new(vec![]) });
    }
    let mut prev_assumed_size = None;
    loop {
        // let f = File::open("C:\\Users\\nikol\\Documents\\Jupyter\\log.txt").unwrap();
        // let mut f = BufReader::new(f);
        let assumed_size = (|| {
            let assumed_size = lower_bound + (upper_bound - lower_bound) / 2;
            if let Some(prev_assumed_size) = prev_assumed_size {
                if assumed_size == prev_assumed_size {
                    return assumed_size + 1;
                }
            }
            assumed_size
        })();
        let mut vals_to_pass = vec![];
        for i in 0..assumed_size {
            vals_to_pass.push(i);
            // let val = &mut vals[i];
            // vals_to_pass.push(Val {
            //     val: val.val,
            //     history: Cell::new(val.history.get_mut().clone()),
            // })
        }
        match solve_with_assumed_size(s, vals_to_pass) {
            Ok(ans) => return ans,
            Err(FailReason::NotEnoughMerges) => {
                upper_bound = assumed_size;
            }
            Err(FailReason::TooManyMerges) => {
                lower_bound = assumed_size;
            }
        }
        prev_assumed_size = Some(assumed_size);
    }
}

fn main() {
    let mut buffer = String::new();
    stdin().read_line(&mut buffer);
    let buffer = Vec::from(buffer
        .chars()
        .filter_map(|x| {
            match x {
                '0' => Some(false),
                '1' => Some(true),
                _ => None
            }
        })
        .collect::<Vec<bool>>());
    let ans = solve(&buffer);
    println!("{}", ans.len());
    for v in ans {
        print!("{} ", v);
    }
}

Рассмотрим следующий код сортировки слиянием на языке Python: def sort(a):  n = len(a)  b = [0 for i in range(n)]  log = []  def mergeSort(l, r):    if r - l <;= 1:      return    m = (l + r) >> 1    mergeSort(l, m)    mergeSort(m, r)    i, j, k = l, m, l    while i <; m and j <; r:      if a[i] <; a[j]:        log.append('0')        b[k] = a[i]        i += 1      else:        log.append('1')        b[k] = a[j]        j += 1      k += 1    while i <; m:      b[k] = a[i]      i += 1      k += 1    while j <; r:      b[k] = a[j]      j += 1      k += 1    for p in range(l, r):      a[p] = b[p]  mergeSort(0, n)  return "".join(log)Как можно заметить, этот код использует логирование — важнейший инструмент разработки.Старший разработчик ВКонтакте Вася сгенерировал перестановку $$$a$$$ (массив из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$), дал её на вход функции sort и получил на выходе строку $$$s$$$. На следующий день строку $$$s$$$ Вася нашёл, а перестановка $$$a$$$ потерялась. Вася хочет восстановить любую перестановку $$$a$$$ такую, что вызов функции sort от неё даст ту же строку $$$s$$$. Помогите ему!

Ввод содержит непустую строку $$$s$$$, состоящую из символов 0 и 1.  В этой версии задачи для любого теста существует перестановка длины $$$16$$$, удовлетворяющая условию. Тем не менее, ваш ответ может иметь любую длину, в том числе отличную от $$$16$$$.

В первой строке выведите целое число $$$n$$$ — длину перестановки. Во второй строке выведите $$$n$$$ различных целых чисел $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$1 \le a_i \le n$$$) — элементы перестановки. Если существует несколько вариантов ответа, выведите любой из них.

use std::io;
use std::io::Write;

/**************************************************

    START OF TEMPLATE CODE

 *************************************************/
#[allow(unused_macros)]
macro_rules! dbg {
    ($first_val:expr, $($val:expr),+ $(,)?) => {
        eprint!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val);
        ($(eprint!(", {} = {:?}", stringify!($val), &$val)),+,);
        eprintln!();
    };
    ($first_val:expr) => {
        eprintln!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val);
    };
}

enum InputSource {
    Stdin,
    FromFile(Vec<String>),
}

struct Scanner {
    buffer: Vec<String>,
    input_source: InputSource,
}

impl Scanner {
    #[allow(dead_code)]
    fn new() -> Self {
        Self { buffer: vec![], input_source: InputSource::Stdin }
    }

    #[allow(dead_code)]
    fn new_file(filename: &str) -> Self {
        let file = std::fs::read_to_string(filename).unwrap();
        let mut lines: Vec<String> = file.lines().map(|line| String::from(line)).collect();
        lines.reverse();
        Self { buffer: vec![], input_source: InputSource::FromFile(lines) }
    }

    #[allow(dead_code)]
    fn i64(&mut self) -> i64 {
        self.next::<i64>()
    }

    #[allow(dead_code)]
    fn i32(&mut self) -> i32 {
        self.next::<i32>()
    }

    #[allow(dead_code)]
    fn usize(&mut self) -> usize {
        self.next::<usize>()
    }

    #[allow(dead_code)]
    fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.next::<T>()).collect()
    }

    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();
            match &mut self.input_source {
                | InputSource::Stdin => { std::io::stdin().read_line(&mut input).expect("Failed read"); }
                | InputSource::FromFile(lines) => {
                    let line = lines.pop().unwrap();
                    input = line;
                }
            }

            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }

    #[allow(dead_code)]
    fn string(&mut self) -> Vec<u8> {
        self.next::<String>().into_bytes()
    }
}

/**************************************************

    END OF TEMPLATE CODE

 *************************************************/

fn build(s: &[u8], it: &mut usize, nodes: &mut Vec<usize>, l: usize, r: usize) -> bool {
    if r - l <= 1 {
        return true;
    }
    let m = (l + r) >> 1;
    if !build(s, it, nodes, l, m) {
        return false;
    }
    if !build(s, it, nodes, m, r) {
        return false;
    }
    let mut i = l;
    let mut j = m;
    let mut b = vec![];
    while i < m && j < r {
        if *it == s.len() {
            return false;
        }
        if s[*it] == b'0' {
            b.push(nodes[i]);
            i += 1;
        } else if s[*it] == b'1' {
            b.push(nodes[j]);
            j += 1;
        } else {
            unreachable!();
        }
        *it += 1;
    }
    while i < m {
        b.push(nodes[i]);
        i += 1;
    }
    while j < r {
        b.push(nodes[j]);
        j += 1;
    }
    for (idx, &val) in b.iter().enumerate() {
        nodes[idx + l] = val;
    }
    true
}

pub fn main() {
    let stdout = io::stdout();
    let mut out = std::io::BufWriter::new(stdout.lock());
    let mut sc = Scanner::new();

    let s = sc.string();
    let mut left = 0;
    let mut right = 100_005;
    while right - left > 1 {
        let n = (left + right) >> 1;

        let mut it = 0;
        let mut nodes = (0..n).collect();
        if !build(&s, &mut it, &mut nodes, 0, n) {
            right = n;
        } else {
            if it == s.len() {
                writeln!(out, "{}", n).unwrap();
                let mut res = vec![0; n];
                for (idx, node) in nodes.iter().enumerate() {
                    res[*node] = idx + 1;
                }
                for r in &res {
                    write!(out, "{} ", r).unwrap();
                }
                return;
            }
            left = n;
        }
    }
    unreachable!();
}


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

use std::cmp::max;

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

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

fn main() {
    let s = get_line();
    let s = s.trim();
    let k: u8 = {
        get_line().trim().parse().unwrap()
    };

    let ans = if s.len() < k as usize {
        None
    } else {
        let mut is_there = vec![false; 26];
        for c in s.bytes() {
            let ind = c - b'a';
            let ind = ind as usize;
            is_there[ind] = true;
        }
        let cnt = is_there.into_iter().filter(|&p| p == true).count();
        Some(k - cnt as u8)
    };

    match ans {
        Some(ans) => println!("{}", ans),
        None => println!("impossible"),
    };
}

Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

use std::io;
fn main(){
    let mut s=String::new();
    io::stdin().read_line(&mut s).expect("Something went wrong");
    let s:&str=s.trim();
    let mut k=String::new();
    io::stdin().read_line(&mut k).expect("Something went wrong");
    let k:i32=k.trim().parse().expect("Something went wrong");
    if k>s.len() as i32{println!("impossible")}
    else{
        let s1:Vec<char>="abcdefghijklmnopqrstuvwxyz".chars().collect();
        let mut a:[i32;26]=[0;26];
        for c in s.chars(){
            let mut d:usize=25;
            let mut b:usize=0;
            let mut m:usize=(b+d)/2;
                while b<d-1{
                    m=(b+d)/2;
                    if c>s1[m]{b=m}
                else{d=m}
                }
            if d==1 && c=='a'{a[0]=1}
            else if a[d]==0{a[d]=1;}
        }
    let mut sum:i32=0;
    for f in 0..26{
        sum+=a[f];
    }
    if k-sum>0{println!("{}",k-sum)}
    else{println!("0")}
    }
}

[{'input': 'yandex\r\n6\r\n', 'output': ['0\r\n']}, {'input': 'yahoo\r\n5\r\n', 'output': ['1\r\n']}, {'input': 'google\r\n7\r\n', 'output': ['impossible\r\n']}, {'input': 'a\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'z\r\n2\r\n', 'output': ['impossible\r\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\r\n26\r\n', 'output': ['14\r\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\r\n26\r\n', 'output': ['12\r\n']}, {'input': 'a\r\n3\r\n', 'output': ['impossible\r\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\r\n4\r\n', 'output': ['1\r\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\r\n20\r\n', 'output': ['18\r\n']}, {'input': 'swmkwaruyv\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\r\n22\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abb\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'aaaa\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'yandex\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'aaabbbccc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'asdfgh\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'aab\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'mynameissako\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abcdef\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'abcdefg\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'abc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'asdafjsgljdllgjdgkl\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'yaay\r\n3\r\n', 'output': ['1\r\n']}, {'input': 'yaay\r\n4\r\n', 'output': ['2\r\n']}, {'input': 'zzzzzz\r\n2\r\n', 'output': ['1\r\n']}]


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

struct Problem {
    flags: String,
    seq1: String,
    seq2: String,
}

fn reverse_ascii_str(s: &mut str) {
    unsafe {
        let bytes = s.as_bytes_mut();
        bytes.reverse();
    }
}

fn trim_end_mut(s: &mut String) {
    s.truncate(s.trim_end().len());
}

fn consecutive_subsequences(s: &str, sub1: &str, sub2: &str) -> bool {
    if let Some((i, _)) = s.match_indices(sub1).next() {
        if let Some((j, _)) = s.rmatch_indices(sub2).next() {
            if i + sub1.len() <= j {
                return true
            }
        }
    }
    false
}

fn parse_problem<B: BufRead>(mut input: B) -> io::Result<Problem> {
    let mut prob = Problem { flags: String::new(),
                             seq1: String::new(),
                             seq2:String::new() };
    input.read_line(&mut prob.flags)?;
    input.read_line(&mut prob.seq1)?;
    input.read_line(&mut prob.seq2)?;
    trim_end_mut(&mut prob.flags);
    trim_end_mut(&mut prob.seq1);
    trim_end_mut(&mut prob.seq2);
    Ok(prob)
}

fn main() -> io::Result<()> {
    let mut problem = parse_problem(io::stdin().lock())?;
    let forward_possible = consecutive_subsequences(&mut problem.flags,
                                                    &mut problem.seq1,
                                                    &mut problem.seq2);
    reverse_ascii_str(&mut problem.flags);
    reverse_ascii_str(&mut problem.seq1);
    reverse_ascii_str(&mut problem.seq2);
    let backward_possible = consecutive_subsequences(&mut problem.flags,
                                                     &mut problem.seq1,
                                                     &mut problem.seq2);
    let out = match (forward_possible, backward_possible) {
        (true, true) => "both",
        (true, false) => "forward",
        (false, true) => "backward",
        (false, false) => "fantasy",
    };
    println!("{}", out);
    Ok(())
}

Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

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

struct Problem {
    flags: String,
    seq1: String,
    seq2: String,
}

fn reverse_ascii_str(s: &mut str) {
    unsafe {
        let bytes = s.as_bytes_mut();
        bytes.reverse();
    }
}

fn trim_end_mut(s: &mut String) {
    s.truncate(s.trim_end().len());
}

fn consecutive_subsequences(s: &str, sub1: &str, sub2: &str) -> bool {
    if let Some((i, _)) = s.match_indices(sub1).next() {
        if let Some((j, _)) = s.rmatch_indices(sub2).next() {
            if i + sub1.len() <= j {
                return true
            }
        }
    }
    false
}

fn parse_problem<B: BufRead>(mut input: B) -> io::Result<Problem> {
    let mut prob = Problem { flags: String::new(),
                             seq1: String::new(),
                             seq2:String::new() };
    input.read_line(&mut prob.flags)?;
    input.read_line(&mut prob.seq1)?;
    input.read_line(&mut prob.seq2)?;
    trim_end_mut(&mut prob.flags);
    trim_end_mut(&mut prob.seq1);
    trim_end_mut(&mut prob.seq2);
    Ok(prob)
}

fn main() -> io::Result<()> {
    let mut problem = parse_problem(io::stdin().lock())?;
    let forward_possible = consecutive_subsequences(&mut problem.flags,
                                                    &mut problem.seq1,
                                                    &mut problem.seq2);
    reverse_ascii_str(&mut problem.flags);
    let backward_possible = consecutive_subsequences(&mut problem.flags,
                                                     &mut problem.seq1,
                                                     &mut problem.seq2);
    let out = match (forward_possible, backward_possible) {
        (true, true) => "both",
        (true, false) => "forward",
        (false, true) => "backward",
        (false, false) => "fantasy",
    };
    println!("{}", out);
    Ok(())
}

[{'input': 'atob\r\na\r\nb\r\n', 'output': ['forward\r\n']}, {'input': 'aaacaaa\r\naca\r\naa\r\n', 'output': ['both\r\n']}, {'input': 'aaa\r\naa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'astalavista\r\nastla\r\nlavista\r\n', 'output': ['fantasy\r\n']}, {'input': 'abacabadabacaba\r\nabacaba\r\nabacaba\r\n', 'output': ['both\r\n']}, {'input': 'a\r\na\r\na\r\n', 'output': ['fantasy\r\n']}, {'input': 'ab\r\nb\r\na\r\n', 'output': ['backward\r\n']}, {'input': 'aaa\r\naaaa\r\naaaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'bbabbbbababbaabaabaa\r\nabb\r\nbaab\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['forward\r\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\r\nbbbb\r\nbbbbb\r\n', 'output': ['both\r\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\r\nabaabababaa\r\nabaabbaa\r\n', 'output': ['backward\r\n']}, {'input': 'aaaa\r\naaa\r\naa\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzzzz\r\nzzzz\r\n', 'output': ['fantasy\r\n']}, {'input': 'zzzz\r\nzz\r\nzz\r\n', 'output': ['both\r\n']}, {'input': 'aabaa\r\naab\r\nbaa\r\n', 'output': ['fantasy\r\n']}, {'input': 'aabaab\r\naba\r\nab\r\n', 'output': ['forward\r\n']}, {'input': 'aab\r\nb\r\naa\r\n', 'output': ['backward\r\n']}, {'input': 'abacaba\r\naca\r\nba\r\n', 'output': ['both\r\n']}]


use std::io::Read;

fn input(read_file: bool) -> String {
    if read_file {
        let mut file = std::fs::File::open("sample.txt").unwrap();
        let mut buf = String::new();
        file.read_to_string(&mut buf).unwrap();
        buf
    } else {
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf).unwrap();
        buf.trim_end().to_owned()
    }
}

fn solve(ws: &mut std::str::SplitWhitespace) {
    let n: usize = ws.next().unwrap().parse().unwrap();
    let xy: Vec<(i32, i32)> = (0..n)
        .map(|_| {
            (
                ws.next().unwrap().parse().unwrap(),
                ws.next().unwrap().parse().unwrap(),
            )
        })
        .collect();

    let mut ans = 100000;
    for i in 0..n {
        let mut s = std::collections::HashSet::new();
        for j in 0..n {
            s.insert(xy[j].0);
        }
        s.remove(&xy[i].0);
        ans = ans.min(s.len());
        s.clear();
        for j in 0..n {
            s.insert(xy[j].1);
        }
        s.remove(&xy[i].1);
        ans = ans.min(s.len());
    }
    println!("{}", ans);
}

fn main() {
    const READ_FROM_FILE: bool = false;

    let s = input(READ_FROM_FILE);
    let mut ws = s.split_whitespace();

    solve(&mut ws);
    // let t = ws.next().unwrap().parse().unwrap();
    // for _ in 0..t {}
}

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

use std::io::Read;

fn input(read_file: bool) -> String {
    if read_file {
        let mut file = std::fs::File::open("sample.txt").unwrap();
        let mut buf = String::new();
        file.read_to_string(&mut buf).unwrap();
        buf
    } else {
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf).unwrap();
        buf.trim_end().to_owned()
    }
}

fn solve(ws: &mut std::str::SplitWhitespace) {
    let n: usize = ws.next().unwrap().parse().unwrap();
    let points: Vec<(i32, i32)> = (0..n)
        .map(|_| {
            (
                ws.next().unwrap().parse().unwrap(),
                ws.next().unwrap().parse().unwrap(),
            )
        })
        .collect();

    let mut visited = vec![false; n];
    let mut q = std::collections::VecDeque::new();

    let mut ans = 0;
    for i in 0..n {
        if visited[i] {
            continue;
        }
        q.push_back(points[i]);
        visited[i] = true;
        while !q.is_empty() {
            let p = q.pop_front().unwrap();
            for j in 0..n {
                if points[j] == p {
                    visited[j] = true;
                    continue;
                }
                if visited[j] {
                    continue;
                }
                if p.0 == points[j].0 {
                    q.push_back(points[j]);
                } else if p.1 == points[j].1 {
                    q.push_back(points[j]);
                }
            }
        }
        ans += 1;
    }

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

fn main() {
    const READ_FROM_FILE: bool = false;

    let s = input(READ_FROM_FILE);
    let mut ws = s.split_whitespace();

    solve(&mut ws);
    // let t = ws.next().unwrap().parse().unwrap();
    // for _ in 0..t {}
}


use std::io::{stdin, stdout, Write, BufReader, BufRead, Read};

fn gcd(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        a %= b;
        let c = a;
        a = b;
        b = c;
    }
    return a;
}

fn solve(input: &mut BufRead, output: &mut Write) {
    let mut input = BufReader::new(input);

    let mut first = String::with_capacity(201);
    let mut second = String::with_capacity(201);

    input.read_line(&mut first).unwrap();
    input.read_line(&mut second).unwrap();

    let s = first.trim().as_bytes();
    let t = second.trim().as_bytes();

    let first = s.iter().position(|&it| it == t[0]).unwrap();
    let second = s.iter().rev().position(|&it| it == t[t.len() - 1]).unwrap();

    let mut answ = first.max(second);

    let mut pos = vec![first; t.len()];
    let mut pos_rev = vec![second; t.len()];

    let mut prev = first;
    for i in 0..t.len() {
        let pos1 = s.iter().skip(prev).position(|&it| it == t[i]).unwrap();
        prev += pos1;
        pos[i] = prev;
        prev += 1;
    }

    let mut rev = second;
    for i in (0..t.len()).rev() {
        let pos1 = s.iter().rev().skip(rev).position(|&it| it == t[i]).unwrap();
        rev += pos1;
        pos_rev[i] = rev;
        rev += 1;
    }

    for i in 0..t.len() - 1 {
        answ = answ.max((s.len() - pos_rev[i + 1] - 2) - pos[i])
    }

    answ = answ.max(s.len() - pos[pos.len() - 1] - 1);
    answ = answ.max(s.len() - pos_rev[0] - 1);

    writeln!(output, "{}", answ).unwrap();
}

fn main() {
    let stdin = stdin();
    let stdout = stdout();
    solve(&mut stdin.lock(), &mut stdout.lock());
}

#[cfg(test)]
mod tests {
    use std::fs::File;
    use solve;
    use std::io::BufReader;

    #[test]
    fn basic_test() {
        let mut f = BufReader::new("bbaba
bb
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "3\n");
    }

    #[test]
    fn basic_test2() {
        let mut f = BufReader::new("baaba
ab
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "2\n");
    }

    #[test]
    fn basic_test3() {
        let mut f = BufReader::new("abcde
abcde
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "0\n");
    }

    #[test]
    fn basic_test4() {
        let mut f = BufReader::new("asdfasdf
fasd
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "3\n");
    }

}

The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.

The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.

Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.

use std::io::{stdin, stdout, Write, BufReader, BufRead, Read};

fn gcd(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        a %= b;
        let c = a;
        a = b;
        b = c;
    }
    return a;
}

fn solve(input: &mut BufRead, output: &mut Write) {
    let mut input = BufReader::new(input);

    let mut first = String::with_capacity(201);
    let mut second = String::with_capacity(201);

    input.read_line(&mut first).unwrap();
    input.read_line(&mut second).unwrap();

    let s = first.trim().as_bytes();
    let t = second.trim().as_bytes();

    let first = s.iter().position(|&it| it == t[0]).unwrap();
    let second = s.iter().rev().position(|&it| it == t[t.len() - 1]).unwrap();

    let mut answ = first.max(second);

    let mut pos = vec![first; t.len()];
    let mut pos_rev = vec![second; t.len()];

    let mut prev = first;
    for i in 0..t.len() {
        let mut pos1 = 0;
        for j in prev..s.len() {
            if s[j] == t[i] {
                pos1 = j;
                break;
            }
        }
        prev = pos1;
        pos[i] = prev;
        prev += 1;
    }

    let mut rev = s.len() - 1 -second;
    for i in (0..t.len()).rev() {
        let mut pos1 = 0;
        for j in (0..=rev).rev() {
            if s[j] == t[i] {
                pos1 = j;
                break;
            }
        }
        rev = pos1;
        pos_rev[i] = rev;
        if rev > 0 {
            rev -= 1;
        }
    }

    for i in 0..t.len() - 1 {
        answ = answ.max(pos_rev[i + 1] - 1 - pos[i])
    }

    answ = answ.max(s.len() - pos[pos.len() - 1] - 1);
    answ = answ.max(pos_rev[0]);

    writeln!(output, "{}", answ).unwrap();
}

fn main() {
    let stdin = stdin();
    let stdout = stdout();
    solve(&mut stdin.lock(), &mut stdout.lock());
}

#[cfg(test)]
mod tests {
    use std::fs::File;
    use solve;
    use std::io::BufReader;

    #[test]
    fn basic_test() {
        let mut f = BufReader::new("bbaba
bb
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "3\n");
    }

    #[test]
    fn basic_test2() {
        let mut f = BufReader::new("baaba
ab
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "2\n");
    }

    #[test]
    fn basic_test3() {
        let mut f = BufReader::new("abcde
abcde
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "0\n");
    }

    #[test]
    fn basic_test4() {
        let mut f = BufReader::new("asdfasdf
fasd
".as_bytes());
        let mut buf: Vec<u8> = Vec::new();

        solve(&mut f, &mut buf);

        let res = String::from_utf8(buf).unwrap();
        assert_eq!(res, "3\n");
    }
}


fn main() {
    input!{
        n: usize,
        k: usize,
        mut a: [usize; n],
    };
    a.sort_unstable();
    let sum = a.iter().sum::<usize>();

    let check = |max: usize| {
        let mut l = 0;
        let (mut lsum, mut rsum) = (0, sum);
        for (r, &x) in a.iter().enumerate() {
            rsum -= x;
            while x - a[l] > max {
                lsum += a[l];
                l += 1;
            }
            let op = if l == 0 { 0 } else { l * (x - max) - lsum } + rsum - (n - 1 - r) * x;
            if op <= k {
                return true;
            }
        }

        let mut r = n - 1;
        (lsum, rsum) = (sum, 0);
        for (l, &x) in a.iter().enumerate() {
            lsum -= x;
            while a[r] - x > max {
                rsum += a[r];
                r -= 1;
            }
            let op = x * l - lsum + rsum - (n - 1 - r) * (x + max);
            if op <= k {
                return true;
            }
        }
        false
    };

    let (mut low, mut high) = (0, a[n - 1] - a[0]);
    while low < high {
        let mid = (high - low)/2 + low;
        if check(mid) {
            high = mid;
        } else {
            low = mid + 1;
        }
    }

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

mod io {
    use std::cell::RefCell;
    use std::io::*;

    std::thread_local! {
        pub static STDIN: RefCell<Stdin> = RefCell::new(stdin());
        pub static STDOUT: RefCell<BufWriter<Stdout>> = RefCell::new(BufWriter::new(stdout()));
    }

    #[macro_export]
    macro_rules! input {
        () => {};
        (mut $var:ident: $t:tt, $($rest:tt)*) => {
            let mut $var = __input_inner!($t);
            input!($($rest)*)
        };
        ($var:ident: $t:tt, $($rest:tt)*) => {
            let $var = __input_inner!($t);
            input!($($rest)*)
        };
        (mut $var:ident: $t:tt) => {
            let mut $var = __input_inner!($t);
        };
        ($var:ident: $t:tt) => {
            let $var = __input_inner!($t);
        };
    }

    #[macro_export]
    macro_rules! __input_inner {
        (($($t:tt),*)) => {
            ($(__input_inner!($t)),*)
        };
        ([$t:tt; $n:expr]) => {
            (0..$n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
        };
        ([$t:tt]) => {{
            let n = __input_inner!(usize);
            (0..n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
        }};
        (chars) => {
            __input_inner!(String).chars().collect::<Vec<_>>()
        };
        (bytes) => {
            __input_inner!(String).into_bytes()
        };
        (usize1) => {
            __input_inner!(usize) - 1
        };
        ($t:ty) => {
            $crate::io::STDIN.with(|r| {
                use std::io::BufRead;
                let r = r.borrow_mut();
                let mut r = r.lock();
                let mut s = vec![];
                loop {
                    let buf = r.fill_buf().unwrap();
                    if buf.is_empty() {
                        break;
                    }
                    if let Some(i) = buf.iter().position(u8::is_ascii_whitespace) {
                        s.extend_from_slice(&buf[..i]);
                        r.consume(i + 1);
                        if !s.is_empty() {
                            break;
                        }
                    } else {
                        s.extend_from_slice(buf);
                        let n = buf.len();
                        r.consume(n);
                    }
                }
                std::str::from_utf8(&s).unwrap().parse::<$t>().unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! println {
        () => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::writeln!(w.borrow_mut()).unwrap()
            })
        };
        ($($arg:tt)*) => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::writeln!(w.borrow_mut(), $($arg)*).unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! print {
        ($($arg:tt)*) => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::write!(w.borrow_mut(), $($arg)*).unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! flush {
        () => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                w.borrow_mut().flush().unwrap()
            })
        };
    }
}

You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ integers.You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $$$k$$$ times.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 10^{5}, 1 \le k \le 10^{14})$$$ — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.
The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$.

Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $$$k$$$ times.

fn main() {
    input!{
        n: usize,
        k: usize,
        mut a: [usize; n],
    };
    a.sort_unstable();
    let sum = a.iter().sum::<usize>();

    let check = |max: usize| {
        let mut l = 0;
        let (mut lsum, mut rsum) = (0, sum);
        for (r, &x) in a.iter().enumerate() {
            rsum -= x;
            while x - a[l] > max {
                lsum += a[l];
                l += 1;
            }
            let op = if l == 0 { 0 } else { l * (x - max) - lsum } + rsum - (n - 1 - r) * x;
            if op <= k {
                return true;
            }
        }

        let mut r = n - 1;
        lsum = sum;
        rsum = 0;
        for (l, &x) in a.iter().enumerate().rev() {
            lsum -= x;
            while a[r] - x > max {
                rsum += a[r];
                r -= 1;
            }
            let op = x * l - lsum + rsum - (n - 1 - r) * (x + max);
            if op <= k {
                return true;
            }
        }
        false
    };

    let (mut low, mut high) = (0, a[n - 1] - a[0]);
    while low < high {
        let mid = (high - low)/2 + low;
        if check(mid) {
            high = mid;
        } else {
            low = mid + 1;
        }
    }

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

mod io {
    use std::cell::RefCell;
    use std::io::*;

    std::thread_local! {
        pub static STDIN: RefCell<Stdin> = RefCell::new(stdin());
        pub static STDOUT: RefCell<BufWriter<Stdout>> = RefCell::new(BufWriter::new(stdout()));
    }

    #[macro_export]
    macro_rules! input {
        () => {};
        (mut $var:ident: $t:tt, $($rest:tt)*) => {
            let mut $var = __input_inner!($t);
            input!($($rest)*)
        };
        ($var:ident: $t:tt, $($rest:tt)*) => {
            let $var = __input_inner!($t);
            input!($($rest)*)
        };
        (mut $var:ident: $t:tt) => {
            let mut $var = __input_inner!($t);
        };
        ($var:ident: $t:tt) => {
            let $var = __input_inner!($t);
        };
    }

    #[macro_export]
    macro_rules! __input_inner {
        (($($t:tt),*)) => {
            ($(__input_inner!($t)),*)
        };
        ([$t:tt; $n:expr]) => {
            (0..$n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
        };
        ([$t:tt]) => {{
            let n = __input_inner!(usize);
            (0..n).map(|_| __input_inner!($t)).collect::<Vec<_>>()
        }};
        (chars) => {
            __input_inner!(String).chars().collect::<Vec<_>>()
        };
        (bytes) => {
            __input_inner!(String).into_bytes()
        };
        (usize1) => {
            __input_inner!(usize) - 1
        };
        ($t:ty) => {
            $crate::io::STDIN.with(|r| {
                use std::io::BufRead;
                let r = r.borrow_mut();
                let mut r = r.lock();
                let mut s = vec![];
                loop {
                    let buf = r.fill_buf().unwrap();
                    if buf.is_empty() {
                        break;
                    }
                    if let Some(i) = buf.iter().position(u8::is_ascii_whitespace) {
                        s.extend_from_slice(&buf[..i]);
                        r.consume(i + 1);
                        if !s.is_empty() {
                            break;
                        }
                    } else {
                        s.extend_from_slice(buf);
                        let n = buf.len();
                        r.consume(n);
                    }
                }
                std::str::from_utf8(&s).unwrap().parse::<$t>().unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! println {
        () => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::writeln!(w.borrow_mut()).unwrap()
            })
        };
        ($($arg:tt)*) => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::writeln!(w.borrow_mut(), $($arg)*).unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! print {
        ($($arg:tt)*) => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                std::write!(w.borrow_mut(), $($arg)*).unwrap()
            })
        };
    }

    #[macro_export]
    macro_rules! flush {
        () => {
            $crate::io::STDOUT.with(|w| {
                use std::io::Write;
                w.borrow_mut().flush().unwrap()
            })
        };
    }
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::io;
#[allow(unused_imports)]
use std::iter::*;
#[allow(unused_imports)]
use std::mem::*;
#[allow(unused_imports)]
use std::str::*;
#[allow(unused_imports)]
use std::usize;

// vec with some initial value
#[allow(unused_macros)]
macro_rules! vvec {
    ($($x:expr),+; $y:expr; $n:expr) => {{
        let mut v = vec![$y; $n];

        let mut it = v.iter_mut();
        $(
            *it.next().unwrap() = $x;
        )+

        v
    }}
}

#[allow(unused_macros)]
macro_rules! it {
    ($x:expr) => {
        once($x)
    };
    ($first:expr,$($x:expr),+) => {
        once($first).chain(
            it!($($x),+)
        )
    }
}

#[allow(unused_macros)]
macro_rules! pushed {
    ($c:expr, $x:expr) => {{
        let mut c = $c;
        c.push($x);
        c
    }};
}

#[allow(unused_macros)]
macro_rules! inserted {
    ($c:expr, $($x:expr),*) => {{
        let mut c = $c;
        c.insert($($x),*);
        c
    }};
}

#[allow(unused_macros)]
macro_rules! read_tuple {
    ($($t:ty),+) => {{
        let mut line = String::new();
        io::stdin().read_line(&mut line).unwrap();

        let mut it = line.trim()
            .split_whitespace();

        ($(
            it.next().unwrap().parse::<$t>().ok().unwrap()
        ),+)
    }}
}

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    line.trim().to_string().parse().ok().unwrap()
}

#[allow(dead_code)]
fn read_str() -> Vec<char> {
    read::<String>().chars().collect()
}

#[allow(dead_code)]
fn read_row<T: FromStr>() -> Vec<T> {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();

    line.trim()
        .split_whitespace()
        .map(|s| s.parse().ok().unwrap())
        .collect()
}

#[allow(dead_code)]
fn read_col<T: FromStr>(n: usize) -> Vec<T> {
    (0..n).map(|_| read()).collect()
}

#[allow(dead_code)]
fn read_mat<T: FromStr>(n: usize) -> Vec<Vec<T>> {
    (0..n).map(|_| read_row()).collect()
}

#[allow(dead_code)]
fn read_vec<R, F: FnMut() -> R>(n: usize, mut f: F) -> Vec<R> {
    (0..n).map(|_| f()).collect()
}

trait IterCopyExt<'a, T>: IntoIterator<Item = &'a T> + Sized
where
    T: 'a + Copy,
{
    fn citer(self) -> std::iter::Copied<Self::IntoIter> {
        self.into_iter().copied()
    }
}

impl<'a, T, I> IterCopyExt<'a, T> for I
where
    I: IntoIterator<Item = &'a T>,
    T: 'a + Copy,
{
}

trait IteratorExt: Iterator + Sized {
    fn sorted(self) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        Self::Item: std::cmp::Ord,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort();
        v.into_iter()
    }

    fn sorted_by<F>(self, f: F) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        F: FnMut(&Self::Item, &Self::Item) -> std::cmp::Ordering,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort_by(f);
        v.into_iter()
    }

    fn sorted_by_key<F, K>(self, f: F) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        F: FnMut(&Self::Item) -> K,
        K: std::cmp::Ord,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort_by_key(f);
        v.into_iter()
    }

    fn join(self, delim: &str) -> String
    where
        Self::Item: ToString,
    {
        self.enumerate().fold(String::new(), |s, (i, t)| {
            if i == 0 {
                s + &t.to_string()
            } else {
                s + delim + &t.to_string()
            }
        })
    }
}

impl<I> IteratorExt for I where I: Iterator {}

fn main() {
    const M: usize = 'z' as usize - 'a' as usize + 1;

    let (n, l, k) = read_tuple!(usize, usize, usize);
    let s = read_str();
    let nums = s.citer().fold(vec![0; M], |mut nums, c| {
        nums[c as usize - 'a' as usize] += 1;
        nums
    });

    let (words, ..) = nums.citer().enumerate().fold(
        (vec![vec![]; n], 0, 0, 0),
        |(mut words, i, st, j), (c, m)| {
            let (mut mm, i1, st1) = (i..l)
                .flat_map(|ii| (st..k).map(move |p| (ii, p)))
                .take(m)
                .fold((m, l, 0), |(mm, _, _), (ii, p)| {
                    words[p].push((c + 'a' as usize) as u8 as char);

                    (
                        mm - 1,
                        ii + (p + 1 - st) / (k - st),
                        (p + 1 - st) % (k - st) + st,
                    )
                });

            for jj in j..n {
                while words[jj].len() < l {
                    if mm == 0 {
                        return (words, i1, st1, jj);
                    }

                    words[jj].push((c + 'a' as usize) as u8 as char);
                    mm -= 1;
                }
            }

            return (words, i1, st1, n);
        },
    );

    use io::{BufWriter, Write};
    let stdout = io::stdout();
    let mut stdout = BufWriter::new(stdout.lock());
    for word in words {
        writeln!(stdout, "{}", word.citer().join("")).unwrap();
    }
}

Lucy likes letters. She studied the definition of the lexicographical order at school and plays with it.At first, she tried to construct the lexicographically smallest word out of given letters. It was so easy! Then she tried to build multiple words and minimize one of them. This was much harder!Formally, Lucy wants to make $$$n$$$ words of length $$$l$$$ each out of the given $$$n \cdot l$$$ letters, so that the $$$k$$$-th of them in the lexicographic order is lexicographically as small as possible.

The first line contains three integers $$$n$$$, $$$l$$$, and $$$k$$$ ($$$1\\le k \\le n \\le 1\\,000$$$; $$$1 \\le l \\le 1\\,000$$$) — the total number of words, the length of each word, and the index of the word Lucy wants to minimize.
The next line contains a string of $$$n \\cdot l$$$ lowercase letters of the English alphabet.

Output $$$n$$$ words of $$$l$$$ letters each, one per line, using the letters from the input. Words must be sorted in the lexicographic order, and the $$$k$$$-th of them must be lexicographically as small as possible. If there are multiple answers with the smallest $$$k$$$-th word, output any of them.

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::io;
#[allow(unused_imports)]
use std::iter::*;
#[allow(unused_imports)]
use std::mem::*;
#[allow(unused_imports)]
use std::str::*;
#[allow(unused_imports)]
use std::usize;

// vec with some initial value
#[allow(unused_macros)]
macro_rules! vvec {
    ($($x:expr),+; $y:expr; $n:expr) => {{
        let mut v = vec![$y; $n];

        let mut it = v.iter_mut();
        $(
            *it.next().unwrap() = $x;
        )+

        v
    }}
}

#[allow(unused_macros)]
macro_rules! it {
    ($x:expr) => {
        once($x)
    };
    ($first:expr,$($x:expr),+) => {
        once($first).chain(
            it!($($x),+)
        )
    }
}

#[allow(unused_macros)]
macro_rules! pushed {
    ($c:expr, $x:expr) => {{
        let mut c = $c;
        c.push($x);
        c
    }};
}

#[allow(unused_macros)]
macro_rules! inserted {
    ($c:expr, $($x:expr),*) => {{
        let mut c = $c;
        c.insert($($x),*);
        c
    }};
}

#[allow(unused_macros)]
macro_rules! read_tuple {
    ($($t:ty),+) => {{
        let mut line = String::new();
        io::stdin().read_line(&mut line).unwrap();

        let mut it = line.trim()
            .split_whitespace();

        ($(
            it.next().unwrap().parse::<$t>().ok().unwrap()
        ),+)
    }}
}

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    line.trim().to_string().parse().ok().unwrap()
}

#[allow(dead_code)]
fn read_str() -> Vec<char> {
    read::<String>().chars().collect()
}

#[allow(dead_code)]
fn read_row<T: FromStr>() -> Vec<T> {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();

    line.trim()
        .split_whitespace()
        .map(|s| s.parse().ok().unwrap())
        .collect()
}

#[allow(dead_code)]
fn read_col<T: FromStr>(n: usize) -> Vec<T> {
    (0..n).map(|_| read()).collect()
}

#[allow(dead_code)]
fn read_mat<T: FromStr>(n: usize) -> Vec<Vec<T>> {
    (0..n).map(|_| read_row()).collect()
}

#[allow(dead_code)]
fn read_vec<R, F: FnMut() -> R>(n: usize, mut f: F) -> Vec<R> {
    (0..n).map(|_| f()).collect()
}

trait IterCopyExt<'a, T>: IntoIterator<Item = &'a T> + Sized
where
    T: 'a + Copy,
{
    fn citer(self) -> std::iter::Copied<Self::IntoIter> {
        self.into_iter().copied()
    }
}

impl<'a, T, I> IterCopyExt<'a, T> for I
where
    I: IntoIterator<Item = &'a T>,
    T: 'a + Copy,
{
}

trait IteratorExt: Iterator + Sized {
    fn sorted(self) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        Self::Item: std::cmp::Ord,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort();
        v.into_iter()
    }

    fn sorted_by<F>(self, f: F) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        F: FnMut(&Self::Item, &Self::Item) -> std::cmp::Ordering,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort_by(f);
        v.into_iter()
    }

    fn sorted_by_key<F, K>(self, f: F) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        F: FnMut(&Self::Item) -> K,
        K: std::cmp::Ord,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort_by_key(f);
        v.into_iter()
    }

    fn join(self, delim: &str) -> String
    where
        Self::Item: ToString,
    {
        self.enumerate().fold(String::new(), |s, (i, t)| {
            if i == 0 {
                s + &t.to_string()
            } else {
                s + delim + &t.to_string()
            }
        })
    }
}

impl<I> IteratorExt for I where I: Iterator {}

fn main() {
    const M: usize = 'z' as usize - 'a' as usize + 1;

    let (n, l, k) = read_tuple!(usize, usize, usize);
    let s = read_str();
    let nums = s.citer().fold(vec![0; M], |mut nums, c| {
        nums[c as usize - 'a' as usize] += 1;
        nums
    });

    let (words, ..) = nums.citer().enumerate().fold(
        (vec![vec![]; n], 0, 0, 0),
        |(mut words, i, st, j), (c, m)| {
            let (mut mm, i1, st1) = (i..l)
                .flat_map(|ii| (st..k).map(move |p| (ii, p)))
                .take(m)
                .fold((m, i, st), |(mm, _, _), (ii, p)| {
                    words[p].push((c + 'a' as usize) as u8 as char);

                    (
                        mm - 1,
                        ii + (p + 1 - st) / (k - st),
                        (p + 1 - st) % (k - st) + st,
                    )
                });

            for jj in j..n {
                while words[jj].len() < l {
                    if mm == 0 {
                        return (words, i1, st1, jj);
                    }

                    words[jj].push((c + 'a' as usize) as u8 as char);
                    mm -= 1;
                }
            }

            return (words, i1, st1, n);
        },
    );

    use io::{BufWriter, Write};
    let stdout = io::stdout();
    let mut stdout = BufWriter::new(stdout.lock());
    for word in words {
        writeln!(stdout, "{}", word.citer().join("")).unwrap();
    }
}

[{'input': ['3 2 2\r\nabcdef\r\n'], 'output': ['ad\r\nbc\r\nef\r\n']}, {'input': ['2 3 1\r\nabcabc\r\n'], 'output': ['aab\r\nbcc\r\n']}, {'input': ['1 1 1\r\nd\r\n'], 'output': ['d\r\n']}, {'input': ['2 1 2\r\nxx\r\n'], 'output': ['x\r\nx\r\n']}, {'input': ['10 1 4\r\nmmmmmmmmmm\r\n'], 'output': ['m\r\nm\r\nm\r\nm\r\nm\r\nm\r\nm\r\nm\r\nm\r\nm\r\n']}, {'input': ['2 3 2\r\nbbcadc\r\n'], 'output': ['acd\r\nbbc\r\n']}, {'input': ['5 5 5\r\nuuuuuyyyyybbbbbqqqqqkkkkk\r\n'], 'output': ['bkquy\r\nbkquy\r\nbkquy\r\nbkquy\r\nbkquy\r\n']}, {'input': ['1 1 1\r\nz\r\n'], 'output': ['z\r\n']}, {'input': ['1 1 1\r\nv\r\n'], 'output': ['v\r\n']}, {'input': ['1 1 1\r\nb\r\n'], 'output': ['b\r\n']}, {'input': ['1 1 1\r\nn\r\n'], 'output': ['n\r\n']}, {'input': ['1 9 1\r\nddddddddd\r\n'], 'output': ['ddddddddd\r\n']}, {'input': ['1 9 1\r\notoeuhojt\r\n'], 'output': ['ehjooottu\r\n']}, {'input': ['1 9 1\r\nwmdjwkpwf\r\n'], 'output': ['dfjkmpwww\r\n']}, {'input': ['1 10 1\r\nlduuukmwxx\r\n'], 'output': ['dklmuuuwxx\r\n']}, {'input': ['1 97 1\r\neeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\r\n'], 'output': ['eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\r\n']}, {'input': ['1 98 1\r\nddzzdzzddzzzzzzdzdzzdzzzzddddzzdzddddddzzddddzdzzzdzdzddzddzdzdzdzzzzdzdzddzzzzdzzzzddzzdzzdzdddzz\r\n'], 'output': ['dddddddddddddddddddddddddddddddddddddddddddddzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\r\n']}, {'input': ['1 91 1\r\nyvphaxbrxwquqqstaislmlxjcshnhigbrbooagoirplbflfaiwkptchamaoxgvemqbprdbbzupgiivvssuuynqqtltf\r\n'], 'output': ['aaaaaabbbbbbbccdefffgggghhhhiiiiiijklllllmmmnnoooopppppqqqqqqrrrrsssssttttuuuuvvvvwwxxxxyyz\r\n']}, {'input': ['1 95 1\r\ntnyebggqacotqgitzqfhysnhlyuguqjdxnvttaeswgkfspvdftmqvaipklqqnttyqloqyeyzhvoiigiubceckggiidyhwuo\r\n'], 'output': ['aaabbcccdddeeeefffgggggggghhhhiiiiiiijkkklllmnnnnooooppqqqqqqqqqsssttttttttuuuuvvvvwwxyyyyyyyzz\r\n']}, {'input': ['9 1 9\r\neeeeeeeee\r\n'], 'output': ['e\r\ne\r\ne\r\ne\r\ne\r\ne\r\ne\r\ne\r\ne\r\n']}, {'input': ['10 1 3\r\navdtkzddkk\r\n'], 'output': ['a\r\nd\r\nd\r\nd\r\nk\r\nk\r\nk\r\nt\r\nv\r\nz\r\n']}, {'input': ['9 1 9\r\nkvmjkblhz\r\n'], 'output': ['b\r\nh\r\nj\r\nk\r\nk\r\nl\r\nm\r\nv\r\nz\r\n']}, {'input': ['10 1 10\r\nuucmshkhlo\r\n'], 'output': ['c\r\nh\r\nh\r\nk\r\nl\r\nm\r\no\r\ns\r\nu\r\nu\r\n']}, {'input': ['9 10 9\r\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n'], 'output': ['bbbbbbbbbb\r\nbbbbbbbbbb\r\nbbbbbbbbbb\r\nbbbbbbbbbb\r\nbbbbbbbbbb\r\nbbbbbbbbbb\r\nbbbbbbbbbb\r\nbbbbbbbbbb\r\nbbbbbbbbbb\r\n']}, {'input': ['9 10 5\r\nafdfhplzplgrnrgzpzplbdhnulrxplafgpgbzlablzhxuhblczlpgbczrbxcnrfgfxcbflrpdnlgfruzrczgzrgpbc\r\n'], 'output': ['afffffgggg\r\naggggghhhh\r\nalllllllll\r\nbbbbcccddl\r\nbbbbcccdff\r\nlnnnnppppp\r\npppprrrrrr\r\nrrruuuxxxx\r\nzzzzzzzzzz\r\n']}, {'input': ['10 9 2\r\nskpjgpwrqajrdnynybnsmybttmhkboiqlndqtghvqyorholdzwasytnvteawhahjfhjknhfobiifrtfrlbjkqyxgnc\r\n'], 'output': ['aabbbffff\r\naabbcddde\r\nggghhhhhh\r\nhiiijjjjj\r\nkkkklllmm\r\nnnnnnnnoo\r\nooppqqqqq\r\nrrrrrssst\r\ntttttvvww\r\nwxyyyyyyz\r\n']}, {'input': ['10 10 10\r\nhckmixocxnktmrsaiopejoifwiwskqktgljlgobztnpvlzfuxotiaquusgdbpzufrkxdejcznsjfyctfucwzkbzluyyelrohoacz\r\n'], 'output': ['aghhiiiiij\r\najjjkkkkkk\r\nalllllmmnn\r\nbnooooooop\r\nbppqqrrrss\r\nbsstttttuu\r\nccuuuuvwww\r\nccxxxxyyyz\r\ncdeezzzzzz\r\ncdefffffgg\r\n']}, {'input': ['92 1 71\r\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n'], 'output': ['x\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\n']}, {'input': ['94 1 27\r\nrxzjinajagadtnzsvnptwolcrfovnafwrrlxidrsppkgwfmwwwapjmvkddfobpwvtnvzgxmzkbhfxhjnjoisdxcrzdslkb\r\n'], 'output': ['a\r\na\r\na\r\na\r\na\r\nb\r\nb\r\nb\r\nc\r\nc\r\nd\r\nd\r\nd\r\nd\r\nd\r\nd\r\nf\r\nf\r\nf\r\nf\r\nf\r\ng\r\ng\r\ng\r\nh\r\nh\r\ni\r\ni\r\ni\r\nj\r\nj\r\nj\r\nj\r\nj\r\nk\r\nk\r\nk\r\nk\r\nl\r\nl\r\nl\r\nm\r\nm\r\nm\r\nn\r\nn\r\nn\r\nn\r\nn\r\nn\r\no\r\no\r\no\r\no\r\np\r\np\r\np\r\np\r\np\r\nr\r\nr\r\nr\r\nr\r\nr\r\nr\r\ns\r\ns\r\ns\r\ns\r\nt\r\nt\r\nt\r\nv\r\nv\r\nv\r\nv\r\nv\r\nw\r\nw\r\nw\r\nw\r\nw\r\nw\r\nw\r\nx\r\nx\r\nx\r\nx\r\nx\r\nz\r\nz\r\nz\r\nz\r\nz\r\n']}, {'input': ['97 1 24\r\neilqimmlqrvapwdtsqgpyfeapibnathmuwqajnwrlhzyiqetpcaqrlnjublrttucshnoldszvvmofrbetieobjeejqaygzgjr\r\n'], 'output': ['a\r\na\r\na\r\na\r\na\r\na\r\nb\r\nb\r\nb\r\nb\r\nc\r\nc\r\nd\r\nd\r\ne\r\ne\r\ne\r\ne\r\ne\r\ne\r\ne\r\nf\r\nf\r\ng\r\ng\r\ng\r\nh\r\nh\r\nh\r\ni\r\ni\r\ni\r\ni\r\ni\r\nj\r\nj\r\nj\r\nj\r\nj\r\nl\r\nl\r\nl\r\nl\r\nl\r\nl\r\nm\r\nm\r\nm\r\nm\r\nn\r\nn\r\nn\r\nn\r\no\r\no\r\no\r\np\r\np\r\np\r\np\r\nq\r\nq\r\nq\r\nq\r\nq\r\nq\r\nq\r\nr\r\nr\r\nr\r\nr\r\nr\r\nr\r\ns\r\ns\r\ns\r\nt\r\nt\r\nt\r\nt\r\nt\r\nt\r\nu\r\nu\r\nu\r\nv\r\nv\r\nv\r\nw\r\nw\r\nw\r\ny\r\ny\r\ny\r\nz\r\nz\r\nz\r\n']}, {'input': ['100 1 92\r\nxwcbimztwcyuckyappbkrddnxgnxqvmobveinzvvnseqxooecwrrdeuwzfzxvfkvguqrsofbbnhfcscxggpxzmruycgqfmnnoovd\r\n'], 'output': ['a\r\nb\r\nb\r\nb\r\nb\r\nb\r\nc\r\nc\r\nc\r\nc\r\nc\r\nc\r\nc\r\nd\r\nd\r\nd\r\nd\r\ne\r\ne\r\ne\r\ne\r\nf\r\nf\r\nf\r\nf\r\nf\r\ng\r\ng\r\ng\r\ng\r\ng\r\nh\r\ni\r\ni\r\nk\r\nk\r\nk\r\nm\r\nm\r\nm\r\nm\r\nn\r\nn\r\nn\r\nn\r\nn\r\nn\r\nn\r\no\r\no\r\no\r\no\r\no\r\no\r\np\r\np\r\np\r\nq\r\nq\r\nq\r\nq\r\nr\r\nr\r\nr\r\nr\r\nr\r\ns\r\ns\r\ns\r\nt\r\nu\r\nu\r\nu\r\nu\r\nv\r\nv\r\nv\r\nv\r\nv\r\nv\r\nv\r\nw\r\nw\r\nw\r\nw\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\nx\r\ny\r\ny\r\ny\r\nz\r\nz\r\nz\r\nz\r\nz\r\n']}]


#![allow(dead_code)]
#![allow(unused)]
// mod tree;
// mod dsu;
// mod binary_lifting;

use std::{env, fs, io, iter, mem, ops, ptr, thread, time, usize};
use std::borrow::{Borrow, BorrowMut};
use std::cell::{Cell, Ref, RefCell, RefMut, UnsafeCell};

use std::fmt::format;
use std::fs::read;
use std::hash::{Hash, Hasher};
use std::io::{BufWriter, stdin, stdout, StdoutLock, Write};
use std::mem::{ManuallyDrop, MaybeUninit};
use std::ops::Bound::Included;
use std::process::{id, Output};
use std::rc::{Rc, Weak};
use std::slice::Iter;
use std::str::FromStr;

const P: u64 = 342325337;

fn scan<T: std::str::FromStr>() -> T
{
    static mut BUFFER: Vec<String> = vec![];
    loop {
        if let Some(token) = unsafe { BUFFER.pop() } {
            return token.parse().ok().unwrap();
        }
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).ok();
        unsafe { BUFFER = input.split_whitespace().rev().map(String::from).collect(); }
    }
}

// fn solve<W: Write>(w: &mut W) {
//
// }
// fn main() {
//
//     let stdout = io::stdout();
//     let mut writer = io::BufWriter::new(stdout.lock());
//     let mut n: usize = 1;
//     if multi {
//         n = scan();
//     }
//     for _ in 0..n {
//         solve(&mut writer);
//     }
// }

struct Solution {

}

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>
}

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode {
            next: None,
            val
        }
    }
}

// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None
        }
    }
}

const MULTI: bool = false;

use std::collections::{BinaryHeap, BTreeMap, BTreeSet, HashMap, HashSet, LinkedList, VecDeque};
use std::cmp::{max, min, Ordering, Reverse};
use std::time::UNIX_EPOCH;

fn solve<W: Write>(w: &mut W) {
    let n: usize = scan();
    let mut x: Vec<usize> = vec![];
    for i in 0..n {
        x.push(scan());
    }
    x.sort();

    let mut ans_min = 1;
    let mut ans_max = 1;

    let mut min_set = HashSet::new();
    for i in 0..n {
        if x[i] == x[n - 1] {
            if !min_set.contains(&x[i]) && !min_set.contains(&(x[i] - 1)) {
                min_set.insert(x[i]);
            }
        } else {
            if !min_set.contains(&x[i]) && !min_set.contains(&(x[i] + 1)) {
                min_set.insert(x[i] + 1);
            }
        }
    }

    let mut max_set = HashSet::new();
    for i in 0..n {
        if !max_set.contains(&(x[i] - 1)) {
            max_set.insert(x[i] - 1);
            continue;
        }
        if !max_set.contains(&x[i]) {
            max_set.insert(x[i]);
            continue;
        }
        if !max_set.contains(&(x[i] + 1)) {
            max_set.insert(x[i] + 1);
            continue;
        }
    }

    writeln!(w, "{} {}", min_set.len(), max_set.len());
}

fn main() {

    let stdout = io::stdout();
    let mut writer = io::BufWriter::new(stdout.lock());
    let mut n: usize = 1;
    if MULTI {
        n = scan();
    }
    for _ in 0..n {
        solve(&mut writer);
    }
}

/*

 */

Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...$$$n$$$ friends live in a city which can be represented as a number line. The $$$i$$$-th friend lives in a house with an integer coordinate $$$x_i$$$. The $$$i$$$-th friend can come celebrate the New Year to the house with coordinate $$$x_i-1$$$, $$$x_i+1$$$ or stay at $$$x_i$$$. Each friend is allowed to move no more than once.For all friends $$$1 \le x_i \le n$$$ holds, however, they can come to houses with coordinates $$$0$$$ and $$$n+1$$$ (if their houses are at $$$1$$$ or $$$n$$$, respectively).For example, let the initial positions be $$$x = [1, 2, 4, 4]$$$. The final ones then can be $$$[1, 3, 3, 4]$$$, $$$[0, 2, 3, 3]$$$, $$$[2, 2, 5, 5]$$$, $$$[2, 1, 3, 5]$$$ and so on. The number of occupied houses is the number of distinct positions among the final ones.So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of friends.
The second line contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le n$$$) — the coordinates of the houses of the friends.

Print two integers — the minimum and the maximum possible number of occupied houses after all moves are performed.

struct Scanner<R> {
    reader: R,
    line: Vec<u8>,
    ptr: usize

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        return Self {reader, line: vec![], ptr: 0};
    }

    fn scan<T: std::str::FromStr>(&mut self) -> T {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                let start = self.ptr;
                while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {
                    self.ptr += 1;
                }
                return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().
                    expect("parse error");
            }
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
    }

}

fn solve_min(counts: &Vec<usize>) -> usize {
    let mut result = 0;
    let mut ptr = 0;
    while ptr < counts.len() {
        if counts[ptr] == 0 {
            ptr += 1;
            continue;
        }
        ptr += 3;
        result += 1;
    }
    return result;
}

fn solve_max(mut counts: Vec<usize>) -> usize {
    let mut result = 0;
    for i in 0..counts.len() {
        if let Some(v) = counts.get_mut(i.wrapping_sub(1)) {
            if *v != 0 {
                *v -= 1;
                result += 1;
                continue;
            }
        }
        if counts[i] != 0 {
            counts[i] -= 1;
            result += 1;
            continue;
        }
        if let Some(v) = counts.get_mut(i + 1) {
            if *v != 0 {
                *v -= 1;
                result += 1;
                continue;
            }
        }
    }
    return result;
}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let x: Vec<usize> = (0..n).map(|_| scanner.scan()).collect();
    let mut counts: Vec<usize> = vec![0; n + 2];
    for &x in &x {
        counts[x] += 1;
    }
    let min = solve_min(&counts);
    let max = solve_max(counts);
    writeln!(writer, "{} {}", min, max).unwrap();
}

fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut writer = std::io::BufWriter::new(stdout.lock());
    let mut scanner = Scanner::new(stdin.lock());
    let tests: usize = 1;
    for _ in 0..tests {
        solve(&mut scanner, &mut writer);
    }
}


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

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(|x| x.unwrap());
    let n: usize = lines.next().unwrap().parse().unwrap();

    let mut possible_moves: Vec<String> = Vec::new();
    for _ in 0..n {
        possible_moves.push(lines.next().unwrap());
    }

    let mut possible_positions: HashSet<(i32, i32)> = HashSet::new();
    possible_positions.insert((0, 0));

    for moves in possible_moves {
        let mut new_positions: HashSet<(i32, i32)> = HashSet::new();
        for position in possible_positions {
            let (x, y) = position;
            match moves.as_str() {
                "UL" => {
                    new_positions.insert((x - 1, y));
                    new_positions.insert((x, y + 1));
                }
                "UR" => {
                    new_positions.insert((x + 1, y));
                    new_positions.insert((x, y + 1));
                }
                "DL" => {
                    new_positions.insert((x - 1, y));
                    new_positions.insert((x, y - 1));
                }
                "DR" => {
                    new_positions.insert((x + 1, y));
                    new_positions.insert((x, y - 1));
                }
                "ULDR" => {
                    new_positions.insert((x - 1, y));
                    new_positions.insert((x + 1, y));
                    new_positions.insert((x, y + 1));
                    new_positions.insert((x, y - 1));
                }
                _ => panic!("Invalid movement string"),
            }
        }
        possible_positions = new_positions;
    }

    println!("{}", possible_positions.len());
}

Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x,y) to one of these four points: to point (x-1,y) which we will mark by letter "L", to point (x+1,y) — "R", to point (x,y-1) — "D", to point (x,y+1) — "U".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0,0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).

The first line contains a single integer n (1≤n≤2·10^5) — the number of the car's movements from the headquarters to the stall.
Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR".
All movements are given in chronological order.
Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.

Print a single integer — the number of different possible locations of the gang's headquarters.

The figure below shows the nine possible positions of the gang headquarters from the first sample:

For example, the following movements can get the car from point (1,0) to point (0,0):

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

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(|x| x.unwrap());

    let n: usize = lines.next().unwrap().parse().unwrap();

    let mut possible_movements: Vec<String> = Vec::new();
    for _ in 0..n {
        possible_movements.push(lines.next().unwrap());
    }

    let mut possible_points: HashSet<(i32, i32)> = HashSet::new();
    possible_points.insert((0, 0));

    for movement in possible_movements {
        let mut new_possible_points: HashSet<(i32, i32)> = HashSet::new();

        for &(x, y) in &possible_points {
            match &movement[..] {
                "UL" => {
                    new_possible_points.insert((x - 1, y));
                    new_possible_points.insert((x, y + 1));
                }
                "UR" => {
                    new_possible_points.insert((x + 1, y));
                    new_possible_points.insert((x, y + 1));
                }
                "DL" => {
                    new_possible_points.insert((x - 1, y));
                    new_possible_points.insert((x, y - 1));
                }
                "DR" => {
                    new_possible_points.insert((x + 1, y));
                    new_possible_points.insert((x, y - 1));
                }
                "ULDR" => {
                    new_possible_points.insert((x - 1, y));
                    new_possible_points.insert((x + 1, y));
                    new_possible_points.insert((x, y - 1));
                    new_possible_points.insert((x, y + 1));
                }
                _ => panic!("Invalid movement"),
            }
        }

        possible_points = new_possible_points;
    }

    println!("{}", possible_points.len());
}


macro_rules! stdin_to {
    ($name: ident: &str) => { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); s = remove_linebreak(&s).to_string(); let $name = s; };
    ($name: ident: $t: ty) => { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); s = remove_linebreak(&s).to_string(); let $name = s.parse::<$t>().unwrap(); };
}
macro_rules! stdin_to_vec {
    ($name: ident: &str, $spl: tt) => { stdin_to!(line: &str); let $name = line.split($spl).map(|s| s.to_string()).collect::<Vec<_>>(); };
    ($name: ident: $t: ty, $spl: tt) => { stdin_to!(line: &str); let $name = line.split($spl).map(|s| s.parse::<$t>().unwrap()).collect::<Vec<_>>(); };
}
fn remove_linebreak(s: &str) -> &str { s.strip_suffix("\r\n").or(s.strip_suffix("\n")).unwrap_or(s) }

fn main() {
    stdin_to!(n: usize);
}

One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i-j|=di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited.The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.

The first line contains positive integer n (1≤n≤100) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.

If the given state is reachable in the described game, output YES, otherwise NO.

//resubmission to find cause of Runtime Error when reading input

use std::collections::HashSet;

macro_rules! stdin_to {
    ($name: ident: &str) => { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); s = remove_linebreak(&s).to_string(); let $name = s; };
    ($name: ident: $t: ty) => { let mut s = String::new(); std::io::stdin().read_line(&mut s).unwrap(); s = remove_linebreak(&s).to_string(); let $name = s.parse::<$t>().unwrap(); };
}
macro_rules! stdin_to_vec {
    ($name: ident: &str, $spl: tt) => { stdin_to!(line: &str); let $name = line.split($spl).map(|s| s.to_string()).collect::<Vec<_>>(); };
    ($name: ident: $t: ty, $spl: tt) => { stdin_to!(line: &str); let $name = line.split($spl).map(|s| s.parse::<$t>().unwrap()).collect::<Vec<_>>(); };
}
fn remove_linebreak(s: &str) -> &str { s.strip_suffix("\r\n").or(s.strip_suffix("\n")).unwrap_or(s) }

fn main() {

    stdin_to!(n: usize);
    stdin_to_vec!(perm: i32, " ");
    stdin_to_vec!(favs: i32, " ");

    //let n = 7;
    //let perm = vec![4, 2, 5, 1, 3, 7, 6];
    //let favs = vec![4, 6, 6, 1, 6, 6, 1];

    let mut arr = (0..n).collect::<Vec<_>>();

    for i in 0..n {
        let val1 = i as i32 + 1;
        for j in i+1..n {
            let val2 = j as i32 + 1;
            let d = (val1-val2).abs();
            if d == favs[i] || d == favs[j] {
                //println!("join {i} {j}");
                join(i, j, &mut arr);
            }
        }
    }
    //println!("{arr:?}");

    if (0..n).all(|i| find(i, &mut arr) == find((perm[i] as i32-1) as usize, &mut arr)) {
        println!("YES");
    } else {
        println!("NO");
    }
}
fn join(a: usize, b: usize, arr: &mut Vec<usize>) {
    let a = find(a, arr);
    let b = find(b, arr);
    arr[a] = b;
}
fn find(mut x: usize, arr: &mut Vec<usize>) -> usize {
    while x != arr[x] { arr[x] = arr[arr[x]]; x = arr[x]; }
    x
}


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

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

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

//

use std::io::Write;

fn run() {
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    input! {
        n: usize,
        s: [chars; n],
    }
//    let mut p = 0;
    let mut map = std::collections::BTreeMap::new();
    for n in (1989i64..).take(100000) {
        let mut key = vec![];
        let mut d = 1;
        loop {
            key.insert(0, n / d % 10);
            d *= 10;
            let mut s = String::new();
            for k in key.iter() {
                s.push_str(&format!("{}", *k));
            }
            if map.contains_key(&s) {
                continue;
            }
            /*
            if n != s.parse::<i64>().unwrap() {
                if p == 0 {
                    p = n;
                }
            } else if p > 0 {
                println!("{} {}", p, n);
                p = 0;
            }
            */
            map.insert(s, n);
            break;
        }
    }
    let solve = |n: String| -> String {
        if let Some(v) = map.get(&n) {
            return format!("{}", v);
        }
        let v = n.parse::<i64>().unwrap();
        let q = v / 10000;
        let r = v % 10000;
        let mut cond = format!("{}", q).len() + 4 < n.len();
        cond |= format!("{}", q).chars().all(|c| c == '1') && r < 3099;
        if cond {
            let d = 10i64.pow(n.len() as u32);
            format!("{}", v + d)
        } else {
            n
        }
    };
    for s in s {
        let n = s[4..].iter().cloned().collect::<String>();
        let ans = solve(n);
        writeln!(out, "{}", ans).ok();
    }
}

fn main() {
    run();
}

International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.  Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

For each abbreviation given in the input, find the year of the corresponding Olympiad.

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

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

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

//

use std::io::Write;

fn run() {
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    input! {
        n: usize,
        s: [chars; n],
    }
    let mut p = 0;
    let mut map = std::collections::BTreeMap::new();
    for n in (1989i64..).take(100000) {
        let mut key = vec![];
        let mut d = 1;
        loop {
            key.insert(0, n / d % 10);
            d *= 10;
            let mut s = String::new();
            for k in key.iter() {
                s.push_str(&format!("{}", *k));
            }
            if map.contains_key(&s) {
                continue;
            }
            if n != s.parse::<i64>().unwrap() {
//                println!("{} : {}", n, s);
                if p == 0 {
                    p = n;
                }
            } else if p > 0 {
//                println!("{} {}", p, n);
                p = 0;
            }
            map.insert(s, n);
            break;
        }
    }
    let solve = |n: String| -> String {
        if let Some(v) = map.get(&n) {
            return format!("{}", v);
        }
        let v = n.parse::<i64>().unwrap();
        let q = v / 10000;
        let r = v % 10000;
        let mut cond = false;
        cond |= q < 10i64.pow((n.len() - 4) as u32) / 9;
        cond |= format!("{}", q).chars().all(|c| c == '1') && r < 3099;
        if cond {
            let d = 10i64.pow(n.len() as u32);
            format!("{}", v + d)
        } else {
            n
        }
    };
    for s in s {
        let n = s[4..].iter().cloned().collect::<String>();
        let ans = solve(n);
        writeln!(out, "{}", ans).ok();
    }
}

fn main() {
    run();
}


#![allow(unused_imports)]
#![allow(unused_macros)]
use std::cell::{RefCell, RefMut};
use std::cmp::{max, min};
use std::collections::*;
use std::io::{stdin, Read};

#[allow(unused_macros)]
macro_rules! parse {
    ($it: ident ) => {};
    ($it: ident, ) => {};
    ($it: ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = parse_val!($it, $t);
        parse!($it $($r)*);
    };
    ($it: ident, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = parse_val!($it, $t);
        parse!($it $($r)*);
    };
    ($it: ident, $var:ident $($r:tt)*) => {
        let $var = parse_val!($it, usize);
        parse!($it $($r)*);
    };
}

#[allow(unused_macros)]
macro_rules! parse_val {
    ($it: ident, [$t:tt; $len:expr]) => {
        (0..$len).map(|_| parse_val!($it, $t)).collect::<Vec<_>>();
    };
    ($it: ident, ($($t: tt),*)) => {
        ($(parse_val!($it, $t)),*)
    };
    ($it: ident, u1) => {
        $it.next().unwrap().parse::<usize>().unwrap() -1
    };
    ($it: ident, $t: ty) => {
        $it.next().unwrap().parse::<$t>().unwrap()
    };
}

#[cfg(debug_assertions)]
macro_rules! debug {
    ($( $args:expr ),*) => { eprintln!( $( $args ),* ); }
}

#[cfg(not(debug_assertions))]
macro_rules! debug {
    ($( $args:expr ),*) => {
        ()
    };
}

const S: usize = 26;
fn solve(s: &str) {
    let mut it = s.split_whitespace();
    let s: Vec<_> = it.next().unwrap().bytes().map(|x| x - b'A').collect();
    let t: Vec<_> = it.next().unwrap().bytes().map(|x| x - b'A').collect();
    let v: Vec<_> = it.next().unwrap().bytes().map(|x| x - b'A').collect();
    let mut next = vec![[0; S]; v.len()];
    for i in 0..v.len() {
        for j in 0u8..(S as u8) {
            let mut curs = v[..i].to_vec();
            curs.push(j);
            let mut curs: &[u8] = &curs;
            while curs != &v[..curs.len()] {
                curs = &curs[1..];
            }
            next[i][j as usize] = curs.len();
        }
    }
    let mut dp = vec![vec![vec![0; v.len()]; t.len() + 1]; s.len() + 1];
    for i in 0..s.len() {
        for j in 0..t.len() {
            for k in 0..v.len() {
                let _m = next[k][s[i] as usize];
                if s[i] == t[j] && _m != v.len() {
                    let m = _m;
                    dp[i + 1][j + 1][m] = max(dp[i + 1][j + 1][m], dp[i][j][k] + 1);
                    if i == 10 {}
                } else {
                    dp[i + 1][j + 1][k] = max(dp[i + 1][j + 1][k], dp[i][j][k])
                }
                dp[i + 1][j][k] = max(dp[i + 1][j][k], dp[i][j][k]);
                dp[i][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k]);
            }
        }
    }
    let mut ret = 0;
    for i in 0..=s.len() {
        for j in 0..=t.len() {
            ret = max(ret, *dp[i][j].iter().max().unwrap());
        }
    }
    println!("{}", ret);
}

fn main() {
    let mut s = String::new();
    stdin().read_to_string(&mut s).unwrap();
    solve(&s);
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_input() {
        let s = "
        ";
        solve(s);
    }
}

In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.

The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.

Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.  If there is no valid common subsequence, output 0.

#![allow(unused_imports)]
#![allow(unused_macros)]
use std::cell::{RefCell, RefMut};
use std::cmp::{max, min};
use std::collections::*;
use std::io::{stdin, Read};

#[allow(unused_macros)]
macro_rules! parse {
    ($it: ident ) => {};
    ($it: ident, ) => {};
    ($it: ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = parse_val!($it, $t);
        parse!($it $($r)*);
    };
    ($it: ident, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = parse_val!($it, $t);
        parse!($it $($r)*);
    };
    ($it: ident, $var:ident $($r:tt)*) => {
        let $var = parse_val!($it, usize);
        parse!($it $($r)*);
    };
}

#[allow(unused_macros)]
macro_rules! parse_val {
    ($it: ident, [$t:tt; $len:expr]) => {
        (0..$len).map(|_| parse_val!($it, $t)).collect::<Vec<_>>();
    };
    ($it: ident, ($($t: tt),*)) => {
        ($(parse_val!($it, $t)),*)
    };
    ($it: ident, u1) => {
        $it.next().unwrap().parse::<usize>().unwrap() -1
    };
    ($it: ident, $t: ty) => {
        $it.next().unwrap().parse::<$t>().unwrap()
    };
}

#[cfg(debug_assertions)]
macro_rules! debug {
    ($( $args:expr ),*) => { eprintln!( $( $args ),* ); }
}

#[cfg(not(debug_assertions))]
macro_rules! debug {
    ($( $args:expr ),*) => {
        ()
    };
}

fn chmax(s: &mut Vec<u8>, t: &[u8]) {
    if s.len() < t.len() {
        *s = t.to_vec();
    }
}

const S: usize = 26;
fn solve(s: &str) {
    let mut it = s.split_whitespace();
    let s: Vec<_> = it.next().unwrap().bytes().map(|x| x - b'A').collect();
    let t: Vec<_> = it.next().unwrap().bytes().map(|x| x - b'A').collect();
    let v: Vec<_> = it.next().unwrap().bytes().map(|x| x - b'A').collect();
    let mut next = vec![[0; S]; v.len()];
    for i in 0..v.len() {
        for j in 0u8..(S as u8) {
            let mut curs = v[..i].to_vec();
            curs.push(j);
            let mut curs: &[u8] = &curs;
            while curs != &v[..curs.len()] {
                curs = &curs[1..];
            }
            next[i][j as usize] = curs.len();
        }
    }
    let mut dp = vec![vec![vec![vec![]; v.len()]; t.len() + 1]; s.len() + 1];
    for i in 0..s.len() {
        for j in 0..t.len() {
            for k in 0..v.len() {
                let tmp = dp[i][j][k].clone();
                let _m = next[k][s[i] as usize];
                if s[i] == t[j] && _m != v.len() {
                    let m = _m;
                    let mut tmp = tmp.clone();
                    tmp.push(s[i]);
                    chmax(&mut dp[i + 1][j + 1][m], &tmp);
                } else {
                    chmax(&mut dp[i + 1][j + 1][k], &tmp);
                }
                chmax(&mut dp[i + 1][j][k], &tmp);
                chmax(&mut dp[i][j + 1][k], &tmp);
            }
        }
    }
    let mut ret = vec![];
    for i in 0..=s.len() {
        for j in 0..=t.len() {
            for k in 0..v.len() {
                chmax(&mut ret, &dp[i][j][k]);
            }
        }
    }
    let ret: String = ret.iter().map(|&b| (b + b'A') as char).collect();
    if ret.len() == 0 {
        println!("{}", 0);
    } else {
        println!("{}", ret);
    }
}

fn main() {
    let mut s = String::new();
    stdin().read_to_string(&mut s).unwrap();
    solve(&s);
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_input() {
        let s = "
        ";
        solve(s);
    }
}