Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.

The first line contains an integer n (1≤n≤100) — the number of leaves Alyona has found. The next n lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.

Output the single number — the number of Alyona's leaves.

5
birch yellow
maple red
birch yellow
maple yellow
maple green

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

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        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 line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let mut set = std::collections::BTreeSet::new();
    for _ in 0..n {
        let a: String = scanner.scan();
        let b: String = scanner.scan();
        set.insert(a + " " + &b);
    }
    writeln!(writer, "{}", set.len()).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);
    }
}

[{'input': ['5\r\nbirch yellow\r\nmaple red\r\nbirch yellow\r\nmaple yellow\r\nmaple green\r\n'], 'output': ['4\r\n']}, {'input': ['3\r\noak yellow\r\noak yellow\r\noak yellow\r\n'], 'output': ['1\r\n']}, {'input': ['5\r\nxbnbkzn hp\r\nkaqkl vrgzbvqstu\r\nj aqidx\r\nhos gyul\r\nwefxmh tygpluae\r\n'], 'output': ['5\r\n']}, {'input': ['1\r\nqvwli hz\r\n'], 'output': ['1\r\n']}, {'input': ['4\r\nsrhk x\r\nsrhk x\r\nqfoe vnrjuab\r\nqfoe vnrjuab\r\n'], 'output': ['2\r\n']}, {'input': ['4\r\nsddqllmmpk syded\r\nfprsq fnenjnaz\r\nn hdej\r\nsddqllmmpk syded\r\n'], 'output': ['3\r\n']}, {'input': ['17\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\njtbctslqq tosqzw\r\n'], 'output': ['1\r\n']}, {'input': ['18\r\nb d\r\nrfdb esp\r\nrfdb esp\r\nb d\r\nrfdb esp\r\nrfdb esp\r\nb d\r\nb d\r\nrfdb esp\r\nrfdb esp\r\nb d\r\nrfdb esp\r\nb d\r\nrfdb esp\r\nb d\r\nb d\r\nrfdb esp\r\nrfdb esp\r\n'], 'output': ['2\r\n']}, {'input': ['13\r\nsvpzwtwn rykzfdce\r\nqweiyeck jkreouy\r\nhk nnli\r\ntwxrnbbdt vtuv\r\nxokqjtylly sz\r\nesdt dbfidjslq\r\ng ybqgomvw\r\nxcpfjmf zcqvz\r\nifajadhj invzueip\r\nvdemdnxifb hckwebmi\r\nsdpnhipam wvowzavh\r\nuqdlfskhgo vunbpghae\r\ne dtigwnb\r\n'], 'output': ['13\r\n']}, {'input': ['20\r\nm vkfh\r\nvptikamead mvx\r\nitu mf\r\nklruxckw aqega\r\nekqkd enjllwol\r\ncc uybfdh\r\nimrfdngvo u\r\ne uh\r\ntwt jsslcfuogk\r\nbljwqsag tuqbdn\r\nqcv q\r\nasx gzhvwwmajj\r\nqcv q\r\nekqkd enjllwol\r\nasx gzhvwwmajj\r\nks vv\r\nkzyfi cn\r\ncc uybfdh\r\nitu mf\r\ncjbjhtbyvk vatwfmux\r\n'], 'output': ['15\r\n']}, {'input': ['2\r\nab ab\r\na bab\r\n'], 'output': ['2\r\n']}]


School holidays come in Berland. The holidays are going to continue for n days. The students of school №N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.

The first input line contains two numbers n and m (1≤n,m≤100) — the number of days in Berland holidays and the number of people in charge of the watering respectively. The next m lines contain the description of the duty schedule. Each line contains two integers ai and bi (1≤ai≤bi≤n), meaning that the i-th person in charge should water the flowers from the ai-th to the bi-th day inclusively, once a day. The duty shifts are described sequentially, i.e. bi≤ai+1 for all i from 1 to n-1 inclusively.

Print "OK" (without quotes), if the schedule does not contain mistakes. Otherwise you have to find the minimal number of a day when the flowers will not be watered or will be watered multiple times, and output two integers — the day number and the number of times the flowers will be watered that day.

Keep in mind that in the second sample the mistake occurs not only on the second day, but also on the sixth day, when nobody waters the flowers. However, you have to print the second day, i.e. the day with the minimal number.

fn main() {
    let (n,m): (usize,usize) = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };

    let mut ans=vec![0;n+1];

    for _ in 0..m{
        let (x,y): (usize,usize) = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        for j in x..y+1{
            ans[j]+=1;
        }
    }

    let mut flag=0;

    for i in 1..n+1{
        if ans[i]!=1{
            println!("{} {}",i,ans[i]);
            flag=1;
            break;
        }
    }

    if flag==0{
        println!("OK");
    }

}


A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n=5, then after the third throw the child number 2 has the ball again. Overall, n-1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2≤n≤100) which indicates the number of kids in the circle.

In the single line print n-1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

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

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        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 line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let mut ptr = 0;
    for i in 1..n {
        ptr = (ptr + i) % n;
        write!(writer, "{} ", ptr + 1).unwrap();
    }
    writeln!(writer).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);
    }
}


A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

The first line contains number n (1≤n≤10^5). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.

Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

use std::{collections::HashMap, io::BufRead};

/**
 * C. Registration system
 * time limit per test: 5 seconds
 * memory limit per test: 64 megabytes
 * input: standard input
 * output: standard output
 *
 * A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to
 * launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of
 * site registration system. The system should work on the following principle.
 *
 * Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in
 * the system database, it is inserted into the database, and the user gets the response OK, confirming the successful
 * registration. If the name already exists in the system database, the system makes up a new user name, sends it to the
 * user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers,
 * starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so
 * that namei does not yet exist in the database.
 *
 * Input
 * The first line contains number n (1ââ¤ânââ¤â105). The following n lines contain the requests to the system. Each request is
 * a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.
 *
 * Output
 * Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new
 * name, if the requested name is already taken.
 *
 * Examples
 *   Input
 *   4
 *   abacaba
 *   acaba
 *   abacaba
 *   acab
 *
 *   Output
 *   OK
 *   OK
 *   abacaba1
 *   OK
 *
 *   Input
 *   6
 *   first
 *   first
 *   second
 *   second
 *   third
 *   third
 *
 *   Output
 *   OK
 *   first1
 *   OK
 *   second1
 *   OK
 *   third1
 */
fn main() {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();

    let mut names: HashMap<String, usize> = HashMap::new();
    let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for line in lines.take(n) {
        let line = line.unwrap();

        if let Some(id) = names.get_mut(&line) {
            println!("{line}{id}");
            *id += 1;
        } else {
            println!("OK");
            names.insert(line, 1);
        }
    }
}


There is a given sequence of integers a1,a2,...,an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.

The first line contains an integer n (1≤n≤10^6). The second line contains a sequence of integers a1,a2,...,an (1≤ai≤3).

Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal.

In the example all the numbers equal to 1 and 3 should be replaced by 2.

use std::collections::HashSet;

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

    let mut a = String::new();
    std::io::stdin().read_line(&mut a).unwrap();
    let a: Vec<u32> = a.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let s: HashSet<&u32> = HashSet::from_iter(a.iter().clone());

    let mut m: u64 = 0;

    for &e in s.iter() {
        m = [m, a.iter().filter(|&x| *x == *e).count() as u64]
            .iter()
            .max()
            .unwrap()
            .clone();
    }

    println!("{}", n - m);
}


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

welcome to the
Codeforces
Beta
Round 5

and
good luck

use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::str::FromStr;
use std::fmt::Debug;
use std::ops::Add;
use std::collections::HashMap;
use std::collections::HashSet;

fn rep(c: char, n: usize) -> String {
    vec![c; n].into_iter().collect()
}

fn main() {
    let buf = &mut io::BufReader::new(io::stdin());
    let mut lines = Vec::new();
    let mut max_len = 0;
    loop {
        let mut line = String::new();
        let read_result = buf.read_line(&mut line);
        match read_result {
            Ok(0) => break,
            _ => {}
        }
        let text = line.trim();
        max_len = max_len.max(text.len());
        lines.push(text.to_owned());
    }
    let mut left_align = true;
    println!("{}", rep('*', max_len + 2));
    for l in lines {
        let spaces = max_len - l.len();
        if spaces % 2 == 0 {
            println!("*{}{}{}*", rep(' ', spaces/2), l, rep(' ', spaces/2));
        } else {
            if left_align {
                println!("*{}{}{}*", rep(' ', spaces/2), l, rep(' ', spaces/2 + 1));
            } else {
                println!("*{}{}{}*", rep(' ', spaces/2 + 1), l, rep(' ', spaces/2));
            }
            left_align = !left_align;
        }
    }
    println!("{}", rep('*', max_len + 2));
}


A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.

The first line contains a positive integer n (1≤n≤100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body (-100≤xi,yi,zi≤100).

Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.

// mod scanner;
// use scanner::Scanner;
use std::io::{self, prelude::*};
use std::str;
pub struct Scanner<R> {
    reader: R,
    buffer: Vec<String>,
}

impl<R: io::BufRead> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            buffer: vec![],
        }
    }

    /// Use "turbofish" syntax token::<T>() to select data type of next token.
    ///
    /// # Panics
    ///
    /// Panics if there's an I/O error or if the token cannot be parsed as T.
    pub fn token<T: 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();
            self.reader.read_line(&mut input).expect("Failed read");
            self.buffer = input.split_whitespace().rev().map(String::from).collect();
        }
    }
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    let n: usize = scan.token();
    let mut partial_sum = vec![0, 0, 0];
    for _ in 0..n {
        let vector: Vec<isize> = (0..3).map(|_| scan.token()).collect();
        partial_sum[0] = partial_sum[0] + vector[0];
        partial_sum[1] = partial_sum[1] + vector[1];
        partial_sum[2] = partial_sum[2] + vector[2];
    }
    if partial_sum[0] != 0 || partial_sum[1] != 0 || partial_sum[2] != 0 {
        write!(out, "NO").ok();
    } else {
        write!(out, "YES").ok();
    }
}


Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?

The first line contains one integer n (1≤n≤10^5) — the amount of bars on the table. The second line contains a sequence t1,t2,...,tn (1≤ti≤1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.

use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::str::FromStr;
use std::fmt::Debug;
use std::ops::Add;
use std::collections::HashMap;
use std::collections::HashSet;

fn main() {
    let buf = &mut io::BufReader::new(io::stdin());
    let mut line = String::new();
    buf.read_line(&mut line).unwrap();
    let mut nm = line.trim().split(" ");
    let n = nm.next().unwrap().parse::<usize>().unwrap();
    line.clear();
    buf.read_line(&mut line).unwrap();
    let ts = line.trim().split(" ").map(|x| x.parse::<usize>().unwrap()).collect::<Vec<_>>();
    let mut i = 0;
    let mut j = n - 1;
    let mut ii = 0;
    let mut jj = 0;
    let mut ai = 0;
    let mut aj = 0;
    while i <= j {
        if ii <= jj {
            ii += ts[i];
            i += 1;
            ai += 1;
        } else {
            jj += ts[j];
            j -= 1;
            aj += 1;
        }
    }
    println!("{} {}", ai, aj);
}


Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.

The first line contains an integer n (1≤n≤100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.

Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.

4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis

use std::{io, str::FromStr};

fn input<T: FromStr>() -> Result<T, <T as std::str::FromStr>::Err> {
    let mut s: String = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().parse()
}
fn main() {
    let line_count: usize = input().unwrap();

    for _ in 0..line_count {
        let word: String = input().unwrap();
        if word.len() <= 10 {
            println!("{word}");
        } else {
            println!(
                "{}{}{}",
                word.chars().nth(0).unwrap(),
                word.len() - 2,
                word.chars().nth_back(0).unwrap()
            );
        }
    }
}


Fox Ciel saw a large field while she was on a bus. The field was a n×m rectangle divided into 1×1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:  Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i,j).  First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1,1)→...→(1,m)→(2,1)→...→(2,m)→...→(n,1)→...→(n,m). Waste cells will be ignored.  Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells.

In the first line there are four positive integers n,m,k,t (1≤n≤4·10^4,1≤m≤4·10^4,1≤k≤10^3,1≤t≤10^3), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell.
Following each k lines contains two integers a,b (1≤a≤n,1≤b≤m), which denotes a cell (a,b) is waste. It is guaranteed that the same cell will not appear twice in this section.
Following each t lines contains two integers i,j (1≤i≤n,1≤j≤m), which is a query that asks you the kind of crop plants of a cell (i,j).

For each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.

The sample corresponds to the figure in the statement.

Waste
Grapes
Carrots
Kiwis
Carrots
Carrots

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

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        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 line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let m: usize = scanner.scan();
    let k: usize = scanner.scan();
    let t: usize = scanner.scan();
    let mut sets = vec![Vec::new(); n];
    let mut counts = vec![m; n];
    for _ in 0..k {
        let a = scanner.scan::<usize>() - 1;
        let b = scanner.scan::<usize>() - 1;
        sets[a].push(b);
        counts[a] -= 1;
    }
    let mut ps = vec![0; n + 1];
    for i in 0..n {
        ps[i + 1] = ps[i] + counts[i];
        sets[i].sort_unstable();
    }
    let names = ["Carrots", "Kiwis", "Grapes"];
    for _ in 0..t {
        let i = scanner.scan::<usize>() - 1;
        let j = scanner.scan::<usize>() - 1;
        if let Err(ptr) = sets[i].binary_search(&j) {
            let id = ps[i] + j - ptr;
            writeln!(writer, "{}", names[id % 3]).unwrap();
        } else {
            writeln!(writer, "Waste").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);
    }
}


A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m>n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?

The first and only input line contains two positive integers — n and m (2≤n<m≤50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2≤n<m≤4.

Print YES, if m is the next prime number after n, or NO otherwise.

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

#[allow(dead_code)]
fn read_line() -> String {
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("failed to read line");

    buffer
}

#[allow(dead_code)]
fn read<T: FromStr>() -> Result<T, T::Err> {
    read_line().trim().parse::<T>()
}

#[allow(dead_code)]
fn read_vec<T: FromStr>() -> Result<Vec<T>, T::Err> {
    read_line()
        .split_whitespace()
        .map(|x| x.parse::<T>())
        .collect()
}

fn main() {
    let i = read_vec::<usize>().unwrap();
    let p = i[0];
    let n = i[1];

    let mut v = [0; 100];
    v[2] = 3;
    v[3] = 5;
    v[5] = 7;
    v[7] = 11;
    v[11] = 13;
    v[13] = 17;
    v[17] = 19;
    v[19] = 23;
    v[23] = 29;
    v[29] = 31;
    v[31] = 37;
    v[37] = 41;
    v[41] = 43;
    v[43] = 47;
    v[47] = 53;

    if v[p] == n {
        println!("YES");
    } else {
        println!("NO");
    }
}


Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.

The first line of the input data contains an integer n (1≤n≤10^5). The second line contains an array of original integers a1,a2,...,an (-10^9≤ai≤10^9).

Print on the single line the answer to the problem: the amount of subarrays, which are magical.
Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).

Notes to sample tests:
Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.
In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].
In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].

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

}

impl<R: std::io::BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        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 line(&mut self) -> Vec<u8> {
        if self.ptr == self.line.len() {
            self.line.clear();
            self.reader.read_until(b'\n', &mut self.line).expect("read error");
            self.ptr = 0;
        }
        let result = self.line[self.ptr..].to_vec();
        self.ptr = self.line.len();
        return result;
    }

    fn eof(&mut self) -> bool {
        loop {
            while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {
                self.ptr += 1;
            }
            if self.ptr != self.line.len() {
                return false;
            }
            self.line.clear();
            self.ptr = 0;
            if let Ok(0) = self.reader.read_until(b'\n', &mut self.line) {
                return true;
            }
        }
    }

}

fn solve<R: std::io::BufRead, W: std::io::Write>(scanner: &mut Scanner<R>, writer: &mut W) {
    let n: usize = scanner.scan();
    let a: Vec<i32> = (0..n).map(|_| scanner.scan()).collect();
    let mut len = 1;
    let mut result = 1usize;
    for i in 1..n {
        if a[i] == a[i - 1] {
            len += 1;
        } else {
            len = 1;
        }
        result += len;
    }
    writeln!(writer, "{}", result).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);
    }
}


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.

The single line contains an integer n (1≤n≤10^6) — the sum of digits of the required lucky number.

Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.

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

struct LuckyNum{
    n4: usize,
    n7: usize,
}
impl LuckyNum{
    fn new(n4: usize, n7: usize) -> LuckyNum{
        LuckyNum { n4, n7 }
    }
    fn len(&self) -> usize{
        self.n4 + self.n7
    }
    fn digit_sum(&self) -> usize{
        self.n4 * 4 + self.n7 * 7
    }
    fn less_than(&self, other: &LuckyNum) -> bool{
        if self.len() < other.len(){
            true
        }
        else if self.len() > other.len(){
            false
        }
        else{
            self.n4 > other.n4
        }
    }
    fn to_string(&self) -> String{
        let mut res = "4".repeat(self.n4);
        res.push_str("7".repeat(self.n7).as_str());
        res
    }
}
fn main(){
    let n: usize = input();
    let mut ans = LuckyNum::new(n, n);
    for n4 in 0..=n/4{
        let n7 = (n - n4 * 4) / 7;
        let lucky_num = LuckyNum::new(n4, n7);
        if lucky_num.digit_sum() == n && lucky_num.less_than(&ans){
            ans = lucky_num;
        }
    }
    if ans.digit_sum() == n{
        println!("{}", ans.to_string());
    }
    else{
        println!("-1");
    }
}

fn input<T>() -> T
    where
        T: FromStr,
        <T as FromStr>::Err: std::fmt::Debug,
{
    let mut n = String::new();
    io::stdin()
        .read_line(&mut n)
        .expect("failed to read from stdin");
    n.trim().parse::<T>().expect("parsing error")
}

fn input_line<T>() -> Vec<T>
    where
        T: FromStr,
        <T as FromStr>::Err: std::fmt::Debug,
{
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Failed to read line");
    let mut inputs: Vec<T> = line.trim().split(" ")
        .map(|x| x.parse::<T>().expect("parsing error"))
        .collect();
    inputs
}
//      IIIIIIIII      OOOOO             A          NN        N    EEEEEEEEEE
//          I         O     O           A A         N N       N    E
//          I        O       O         A   A        N  N      N    E
//          I        O       O        A     A       N   N     N    E
//          I        O       O       AAAAAAAAA      N    N    N    EEEEEEEE
//          I        O       O      A         A     N     N   N    E
//          I        O       O     A           A    N      N  N    E
//          I         O     O     A             A   N       N N    E
//      IIIIIIIII      OOOOO     A               A  N        NN    EEEEEEEEEE ___ KAPANADZE


Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?

The first line contains integer n (3≤n≤100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1≤ai,bi≤n,ai≠bi,1≤ci≤100) — road is directed from city ai to city bi, redirecting the traffic costs ci.

Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.

#[derive(Debug)]
struct Edge {
    from: usize,
    to: usize,
    price: usize,
}

#[derive(Debug)]
struct City {
    id: usize,
    roads: Vec<Road>,
}

#[derive(Debug)]
struct Road {
    to: usize,
    out: bool,
    price: usize,
}

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

    let cities_count: usize = {
        let mut buf = String::new();
        stdin.read_line(&mut buf).unwrap();
        let mut iter = buf.trim_end().split_whitespace();
        iter.next().unwrap().parse().unwrap()
    };

    let edges: Vec<Edge> = {
        let mut edges = Vec::with_capacity(cities_count);
        for _ in 0..cities_count {
            let mut buf = String::new();
            stdin.read_line(&mut buf).unwrap();
            let mut iter = buf.trim_end().split_whitespace();
            let from:  usize = iter.next().unwrap().parse().unwrap();
            let to:    usize = iter.next().unwrap().parse().unwrap();
            let price: usize = iter.next().unwrap().parse().unwrap();
            edges.push(Edge { from, to, price });
        }
        edges
    };

    let total_price: usize = edges.iter().map(|edge| edge.price).sum();

    let cities: Vec<City> = {
        let mut cities = Vec::with_capacity(cities_count);
        for index in 1..=cities_count {
            cities.push(City { id: index, roads: Vec::with_capacity(2) });
        }
        for edge in edges {
            cities[edge.from - 1].roads.push(Road {
                to: edge.to,
                out: true,
                price: edge.price,
            });
            cities[edge.to - 1].roads.push(Road {
                to: edge.from,
                out: false,
                price: edge.price,
            });
        }
        cities
    };

    let price: usize = {
        let mut price = 0;

        let start_id = 1;
        let mut current_id = start_id;
        let mut next_id = cities[current_id - 1].roads[0].to;
        let dir = cities[current_id - 1].roads[0].out;

        loop {
            let current_road = cities[current_id - 1]
                .roads
                .iter()
                .filter(|road| road.to == next_id)
                .next()
                .unwrap();
            let next_road = cities[next_id - 1]
                .roads
                .iter()
                .filter(|road| road.to != current_id)
                .next()
                .unwrap();

            if current_road.out != dir {
                price += current_road.price;
            }

            current_id = current_road.to;
            next_id = next_road.to;
            if current_id == start_id { break }
        }

        price
    };

    println!("{}", std::cmp::min(price, total_price - price));
}


Рассмотрим следующий код сортировки слиянием на языке 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!();
}


Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — the number of digits in the decimal representation of $$$S$$$ and the maximum allowed number of changed digits. The second line contains the integer $$$S$$$. It's guaranteed that $$$S$$$ has exactly $$$n$$$ digits and doesn't contain any leading zeroes.

Output the minimal possible value of $$$S$$$ which Ania can end with. Note that the resulting integer should also have $$$n$$$ digits.

NoteA number has leading zeroes if it consists of at least two digits and its first digit is $$$0$$$. For example, numbers $$$00$$$, $$$00069$$$ and $$$0101$$$ have leading zeroes, while $$$0$$$, $$$3000$$$ and $$$1010$$$ don't have leading zeroes.

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

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

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let mut s = input.trim().bytes().map(|x| x - '0' as u8).collect::<Vec<u8>>();

    if k != 0 {
        let mut start = 0;
        if s.len() > 1 {
            start = 1;
            if s[0] != 1 {
                s[0] = 1;
                k -= 1;
            }
        }

        if k != 0 {
            for d in start..s.len() {
                if s[d] != 0 {
                    s[d] = 0;
                    k -= 1;
                    if k == 0 {
                        break;
                    }
                }
            }
        }
    }

    let out = std::io::stdout();
    let mut buf = std::io::BufWriter::new(out.lock());

    for d in s.iter() {
        write!(buf, "{}", d);
    }
    writeln!(buf, "");
}


Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:    ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:   to do sport on any two consecutive days,  to write the contest on any two consecutive days.

NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.

//spnauti-rust
use std::io::*;
use std::str::*;
use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::*;
#[allow(unused_imports)] use std::collections::*;

#[allow(unused_macros)]
macro_rules! a {
    ($c: tt, $x: expr, $y: expr) => {{
        let b = $y; let a = &mut $x;
        if b $c *a { *a = b; true } else { false }
    }};
}
struct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }
#[allow(dead_code)]
impl<'a> WordReader<'a> {
    fn new<T: Read>(b: &mut String, mut r: T) -> WordReader {
        b.clear();
        r.read_to_string(b).ok();
        WordReader { it: b.split_ascii_whitespace() }
    }
    fn from_stdin(b: &mut String) -> WordReader {
        WordReader::new(b, stdin())
    }
    fn sl(&mut self) ->  &str { self.it.next().unwrap() }
    fn bs(&mut self) -> &[u8] { self.sl().as_bytes()    }
    fn s(&mut self) -> String { String::from(self.sl()) }
    fn i(&mut self) ->    i32 { self.p()                }
    fn u(&mut self) ->  usize { self.p()                }
    fn vi(&mut self, n: usize) -> Vec<i32> {
        self.vp::<i32>(n)
    }
    fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
        self.sl().parse::<T>().unwrap()
    }
    fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
        (0..n).map(|_| self.p()).collect()
    }
}

#[allow(dead_code)]
fn build_counting_hashmap<K: Eq + std::hash::Hash, T>(i: T) -> HashMap<K,usize>
    where T: Iterator<Item = K> {
    let mut m = HashMap::new();
    for k in i {
        let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };
        m.insert(k, n);
    }
    m
}

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

    const INF: i32 = 1000000;
    let n = input.u();
    let (a,b,c) = input.vi(n).into_iter().fold((0,0,0), |(a,b,c),x| {
        let aa = a.min(b).min(c) + 1;
        let bb = if x % 2 == 0 { INF } else { a.min(c) };
        let cc = if x < 2 { INF } else { a.min(b) };
        (aa,bb,cc)
    });
    println!("{}", a.min(b).min(c));
}


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

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

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n = lines.next().unwrap().unwrap().parse::<usize>().unwrap();
    let winnings: Vec<_> = lines.next().unwrap().unwrap().split(" ").map(|s| s.parse::<u64>().unwrap()).collect();
    let mut costs: Vec<_> = lines.next().unwrap().unwrap().split(" ").enumerate().map(|(index, s)| (s.parse::<u64>().unwrap(), index)).collect();
    costs.sort_by(|a, b| b.0.cmp(&a.0));
    let mut current = 0;
    let mut solution = vec![0; 5];
    for amount in winnings.into_iter() {
        current += amount;
        for cost in costs.iter() {
            let how_many = current / cost.0;
            current %= cost.0;
            solution[cost.1] += how_many;
        }
    }
    for how_many in solution {
        print!("{} ", how_many);
    }
    println!("");
    println!("{}", current);
}


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


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']}]


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

use std::io;

fn main() {
    let mut buf = String::new();
    let mut n: usize = 0;
    let reader = io::stdin();
    reader.read_line(&mut buf);
    n = buf.trim().parse()
            .expect(" ");
    let mut v = vec![0;n-1];

    let mut buf2 = String::new();
    reader.read_line(&mut buf2);
    let it = buf2.trim().split(" ");
    let mut ct = 0;
    for sub in it{
        v[ct] = sub.trim().parse()
            .expect(" ");
        ct += 1;
    }

    let mut buf3 = String::new();
    reader.read_line(&mut buf3);
    let wv = buf3.trim().split(" ").collect::<Vec<&str>>();
    let a:i32 =  wv[0].parse().expect(" ");
    let b:i32 =  wv[1].parse().expect(" ");
    let mut ans: u32 = 0;
    for i in (a-1)..=(b-2){
        ans += v[i as usize];
    }
    println!("{}",ans);
}


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

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

fn get_line() -> String {
	let mut input = String::new();

	io::stdin().read_line(&mut input)
		.expect("");

	String::from(input.trim())
}

fn main() {
    let mut sh = HashMap::new();
    let s = get_line();
    for c in s.chars() {
        if !c.is_whitespace() && !sh.contains_key(&c) {
            sh.insert(c, 1);
            continue;
        }

        if let Some(v) = sh.get_mut(&c) {
            *v += 1;
        }
    }

    let t = get_line();
    for d in t.chars() {
        if d.is_whitespace() {
            continue;
        }

        if let Some(v) = sh.get_mut(&d) {
            if *v == 0 {
                println!("NO");
                return;
            }

            *v -= 1;
        } else {
            println!("NO");
            return;
        }
    }

    println!("YES");
}

[{'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\r\nwhere is your dog\r\n', 'output': ['NO\r\n']}, {'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\r\nYour dog is upstears\r\n', 'output': ['YES\r\n']}, {'input': 'Instead of dogging your footsteps it disappears but you dont notice anything\r\nYour dog is upstears\r\n', 'output': ['NO\r\n']}, {'input': 'abcdefg hijk\r\nk j i h g f e d c b a\r\n', 'output': ['YES\r\n']}, {'input': 'HpOKgo\r\neAtAVB\r\n', 'output': ['NO\r\n']}, {'input': 'GRZGc\r\nLPzD\r\n', 'output': ['NO\r\n']}, {'input': 'GtPXu\r\nd\r\n', 'output': ['NO\r\n']}, {'input': 'FVF\r\nr \r\n', 'output': ['NO\r\n']}, {'input': 'HpOKgo\r\nogK\r\n', 'output': ['YES\r\n']}, {'input': 'GRZGc\r\nZG\r\n', 'output': ['YES\r\n']}, {'input': 'HpOKgoueAtAVBdGffvQheJDejNDHhhwyKJisugiRAH OseK yUwqPPNuThUxTfthqIUeb wS jChGOdFDarNrKRT  MlwKecxWNoKEeD BbiHAruE XMlvKYVsJGPP\r\nAHN  XvoaNwV  AVBKwKjr u      U K wKE D K   Jy KiHsR h d W  Js IHyMPK Br iSqe  E fDA   g H\r\n', 'output': ['YES\r\n']}, {'input': 'GRZGcsLPzDrCSXhhNTaibJqVphhjbcPoZhCDUlzAbDnRWjHvxLKtpGiFWiGbfeDxBwCrdJmJGCGv GebAOinUsFrlqKTILOmxrFjSpEoVGoTdSSstJWVgMLKMPettxHASaQZNdOIObcTxtF qTHWBdNIKwj\r\nWqrxze Ji x q aT GllLrRV jMpGiMDTwwS JDsPGpAZKACmsFCOS CD Sj  bCDgKF  jJxa RddtLFAi VGLHH SecObzG q  hPF \r\n', 'output': ['YES\r\n']}, {'input': 'GtPXuwdAxNhODQbjRslDDKciOALJrCifTjDQurQEBeFUUSZWwCZQPdYwZkYbrduMijFjgodAOrKIuUKwSXageZuOWMIhAMexyLRzFuzuXqBDTEaWMzVdbzhxDGSJC SsIYuYILwpiwwcObEHWpFvHeBkWYNitqYrxqgHReHcKnHbtjcWZuaxPBVPb\r\nTQIKyqFaewOkY lZUOOuxEw EwuKcArxRQGFYkvVWIAe SuanPeHuDjquurJu aSxwgOSw jYMwjxItNUUArQjO BIujAhSwttLWp\r\n', 'output': ['YES\r\n']}, {'input': 'FVFSr unvtXbpKWF vPaAgNaoTqklzVqiGYcUcBIcattzBrRuNSnKUtmdGKbjcE\r\nUzrU K  an GFGR        Wc zt iBa     P c    T K v p     V In   b           B   c\r\n', 'output': ['YES\r\n']}, {'input': 'lSwjnYLYtDNIZjxHiTawdh ntSzggZogcIZTuiTMWVgwyloMtEhqkrOxgIcFvwvsboXUPILPIymFAEXnhApewJXJNtFyZ\r\nAoxe  jWZ u  yImg  o AZ FNI w lpj  tNhT g y  ZYcb rc J    w Dlv\r\n', 'output': ['YES\r\n']}, {'input': 'kvlekcdJqODUKdsJlXkRaileTmdGwUHWWgvgUokQxRzzbpFnswvNKiDnjfOFGvFcnaaiRnBGQmqoPxDHepgYasLhzjDgmvaFfVNEcSPVQCJKAbSyTGpXsAjIHr\r\nGjzUllNaGGKXUdYmDFpqFAKIwvTpjmqnyswWRTnxlBnavAGvavxJemrjvRJc\r\n', 'output': ['YES\r\n']}, {'input': 'kWbvhgvvoYOhwXmgTwOSCDXrtFHhqwvMlCvsuuAUXMmWaYXiqHplFZZemhgkTuvsUtIaUxtyYauBIpjdbyYxjZ ZkaBPzwqPfqF kCqGRmXvWuabnQognnkvdNDtRUsSUvSzgBuxCMBWJifbxWegsknp\r\nBsH   bWHJD n Ca T xq  PRCv  tatn Wjy sm  I q s WCjFqdWe  t W XUs  Do  eb Pfh ii  hTbF  O Fll\r\n', 'output': ['YES\r\n']}, {'input': 'OTmLdkMhmDEOMQMiW ZpzEIjyElHFrNCfFQDp SZyoZaEIUIpyCHfwOUqiSkKtFHggrTBGkqfOxkChPztmPrsHoxVwAdrxbZLKxPXHlMnrkgMgiaHFopiFFiUEtKwCjpJtwdwkbJCgA bxeDIscFdmHQJLAMNhWlrZisQrHQpvbALWTwpf jnx\r\nDbZwrQbydCdkJMCrftiwtPFfpMiwwrfIrKidEChKECxQUBVUEfFirbGWiLkFQkdJiFtkrtkbIAEXCEDkwLpK\r\n', 'output': ['YES\r\n']}, {'input': 'NwcGaIeSkOva\r\naIa\r\n', 'output': ['YES\r\n']}, {'input': 'gSrAcVYgAdbdayzbKGhIzLDjyznLRIJH KyvilAaEddmgkBPCNzpmPNeGEbmmpAyHvUSoPvnaORrPUuafpReEGoDOQsAYnUHYfBqhdcopQfxJuGXgKnbdVMQNhJYkyjiJDKlShqBTtnnDQQzEijOMcYRGMgPGVhfIReYennKBLwDTVvcHMIHMgVpJkvzTrezxqS\r\nHJerIVvRyfrPgAQMTI AqGNO mQDfDwQHKgeeYmuRmozKHILvehMPOJNMRtPTAfvKvsoGKi xHEeKqDAYmQJPUXRJbIbHrgVOMGMTdvYiLui\r\n', 'output': ['YES\r\n']}, {'input': 'ReB hksbHqQXxUgpvoNK bFqmNVCEiOyKdKcAJQRkpeohpfuqZabvrLfmpZOMcfyFBJGZwVMxiUPP pbZZtJjxhEwvrAba\r\nJTCpQnIViIGIdQtLnmkVzmcbBZR CoxAdTtWSYpbOglDFifqIVQ vfGKGtLpxpJHiHSWCMeRcrVOXBGBhoEnVhNTPWGTOErNtSvokcGdgZXbgTEtISUyTwaXUEIlJMmutsdCbiyrPZPJyRdOjnSuAGttLy\r\n', 'output': ['NO\r\n']}, {'input': 'hrLzRegCuDGxTrhDgVvM KowwyYuXGzIpcXdSMgeQVfVOtJZdkhNYSegwFWWoPqcZoeapbQnyCtojgkcyezUNHGGIZrhzsKrvvcrtokIdcnqXXkCNKjrOjrnEAKBNxyDdiMVeyLvXxUYMZQRFdlcdlcxzKTeYzBlmpNiwWbNAAhWkMoGpRxkCuyqkzXdKWwGH\r\nJESKDOfnFdxPvUOCkrgSBEPQHJtJHzuNGstRbTCcchRWJvCcveSEAtwtOmZZiW\r\n', 'output': ['NO\r\n']}, {'input': 'yDBxCtUygQwWqONxQCcuAvVCkMGlqgC zvkfEkwqbhMCQxnkwQIUhucCbVUyOBUcXvTNEGriTBwMDMfdsPZgWRgIUDqM\r\neptVnORTTyixxmWIBpSTEwOXqGZllBgSxPenYCDlFwckJlWsoVwWLAIbPOmFqcKcTcoQqahetl KLfVSyaLVebzsGwPSVbtQAeUdZAaJtfxlCEvvaRhLlVvRJhKat IaB awdqcDlrrhTbRxjEbzGwcdmdavkhcjHjzmwbxAgw\r\n', 'output': ['NO\r\n']}, {'input': 'jlMwnnotSdlQMluKWkJwAeCetcqbIEnKeNyLWoKCGONDRBQOjbkGpUvDlmSFUJ bWhohqmmIUWTlDsvelUArAcZJBipMDwUvRfBsYzMdQnPDPAuBaeJmAxVKwUMJrwMDxNtlrtAowVWqWiwFGtmquZAcrpFsLHCrvMSMMlvQUqypAihQWrFMNoaqfs IBg\r\nNzeWQ bafrmDsYlpNHSGTBBgPl WIcuNhyNaNOEFvL\r\n', 'output': ['NO\r\n']}, {'input': 'zyWvXBcUZqGqjHwZHQryBtFliLYnweXAoMKNpLaunaOlzaauWmLtywsEvWPiwxJapocAFRMjrqWJXYqfKEbBKnzLO\r\npsbi bsXpSeJaCkIuPWfSRADXdIClxcDCowwJzGCDTyAl\r\n', 'output': ['NO\r\n']}, {'input': 'kKhuIwRPLCwPFfcnsyCfBdnsraGeOCcLTfXuGjqFSGPSAeDZJSS bXKFanNqWjpFnvRpWxHJspvisDlADJBioxXNbVoXeUedoPcNEpUyEeYxdJXhGzFAmpAiHotSVwbZQsuWjIVhVaEGgqbZHIoDpiEmjTtFylCwCkWWzUOoUfOHxEZvDwNpXhBWamHn\r\nK VpJjGhNbwCRhcfmNGVjewBFpEmPlIKeTuWiukDtEWpjgqciqglkyNfWrBLbGAKvlNWxaUelJmSlSoakSpRzePvJsshOsTYrMPXdxKpaShjyVIXGhRIAdtiGpNwtiRmGTBZhkJqIMdxMHX RMxCMYcWjcjhtCHyFnCvjjezGbkRDRiVxkbh\r\n', 'output': ['NO\r\n']}, {'input': 'AXssNpFKyQmJcBdBdfkhhMUzfqJVgcLBddkwtnFSzSRUCjiDcdtmkzIGkCKSxWUEGhmHmciktJyGMkgCductyHx\r\nI nYhmJfPnvoKUiXYUBIPIcxNYTtvwPUoXERZvY ahlDpQFNMmVZqEBiYqYlHNqcpSCmhFczBlOAhsYFeqMGfqL EJsDNOgwoJfBzqijKOFcYQ\r\n', 'output': ['NO\r\n']}, {'input': 'lkhrzDZmkdbjzYKPNMRkiwCFoZsMzBQMnxxdKKVJezSBjnLjPpUYtabcPTIaDJeDEobbWHdKOdVfMQwDXzDDcSrwVenDEYpMqfiOQ xSsqApWnAMoyhQXCKFzHvvzvUvkWwmwZrvZz\r\nsUzGspYpRFsHRbRgTQuCBgnFgPkisTUfFNwyEEWWRiweWWgjRkVQxgTwxOzdsOwfrGIH O gCXpzvHzfItuEHaihmugEyymSJIogYwX qAwcwIItidfnzZDhZgQHi eRjMAeVkJHceDZuJkmxGowOsmcGYYvk Ajtgi TxwihvjLViNZjvscTWvsaQUelTSivLShhEl\r\n', 'output': ['NO\r\n']}, {'input': 'BRsVjyNhrqRHVwrJzuzRigEhdpbDmaACSPfed\r\nlWqKTjlrqOCUbgBBZdZDGCeQJDXawPnnDkQdZDgwrEQk\r\n', 'output': ['NO\r\n']}, {'input': 'KRmINuyBYPwiTsdlyiNVuylToysJKmOpcLovAtwGPqrgFJQNAYvuAiyQRkeFMECVZvkDEmTauXlyjAaYRnTJXORMZRnTakBaUzSelMilejySDIZjQjzcOIrwXdvDvpeRIkoBgreyFXIyyIZutjiEBtwrmzQtPVUhvvdEtDMbXjBpoPVjGdM EXTAK JbCnw\r\nXZZqlJvzKKtvdNlzFPDTYxidqlsgufVzyEmO FZuLQ vVQsJESNviUCovCK NwwlbxsmPtOJNmAonCqrOZ bZ LVKAsQGmoLnYjeekvEIECFk\r\n', 'output': ['NO\r\n']}]


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']}]


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
}


There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i.Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.

The first line contains three space-separated integers n, r1, r2 (2≤n≤5·10^4,1≤r1≠r2≤n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly.
The following line contains n-1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.

Output n-1 numbers — new representation of the road map in the same format.

use std::io;

fn read_line() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.strip_suffix("\r\n").or(s.strip_suffix('\n')).unwrap_or(s.as_str()).to_string()
}
fn read_line_split(spl: &str) -> Vec<String> {
    let s = read_line();
    if s.len() == 0 { return vec![] }
    s.split(spl).map(|s| s.to_string()).collect::<Vec<_>>()
}

fn main() {

    let line0 = read_line_split(" ");
    let n = line0[0].parse::<usize>().unwrap();
    let mut capit1 = line0[1].parse().unwrap();
    let mut capit2 = line0[2].parse().unwrap();

    let inp: Vec<usize> = read_line_split(" ").iter().map(|s| s.parse().unwrap()).collect::<Vec<_>>();

    //let n = 3;
    //let mut capit1 = 2;
    //let mut capit2 = 3;
    //let inp = vec![2,2];

    //let n = 6;
    //let mut capit1 = 2;
    //let mut capit2 = 4;
    //let inp = vec![6,1,2,4,2];

    capit1 -= 1;
    capit2 -= 1;
    let inp = inp.iter().map(|&vx| vx-1).collect::<Vec<_>>();

    let mut adj_li: Vec<Vec<i64>> = vec![];

    let mut vx_ = 0;
    for &vx in &inp {
        if vx_ == capit1 { vx_ += 1; }
        while vx_ >= adj_li.len() || vx >= adj_li.len() { adj_li.push(vec![]); }
        adj_li[vx].push(vx_ as i64);
        adj_li[vx_].push(vx as i64);

        //println!("{vx} {vx_}");

        vx_ += 1;
    }

    let mut map = vec![-1; inp.len()+1];
    create_map_dfs(&adj_li, &mut map, -1, capit2);
    //println!("{:?}", adj_li);

    let map = map.iter().filter(|&&vx| vx >= 0).collect::<Vec<_>>();
    let map = map.iter().map(|&&vx| (vx+1).to_string()).collect::<Vec<_>>();

    println!("{}", map.join(" "));
}

fn create_map_dfs(adj_li: &Vec<Vec<i64>>, map: &mut Vec<i64>, last_vx: i64, vx: i64) {
    for &vx_ in &adj_li[vx as usize] {
        if last_vx != vx_ {
            map[vx_ as usize] = vx;
            create_map_dfs(adj_li, map, vx, vx_);
        }
    }
}