use std::io;
fn all_same(s: &String) -> bool {
    if s.len() <= 1 {
        return true;
    }
    let fch: char = s.chars().next().unwrap();
    for ch in s.chars().skip(1) {
        if ch != fch {
            return false;
        }
    }
    true
}
fn all_diff(s: &String) -> bool {
    if s.len() <= 1 {
        return true;
    }
    let chars = s.chars().collect::<Vec<char>>();
    for i in 0..s.len() {
        for j in (i + 1)..s.len() {
            if chars[i] == chars[j] {
                return false;
            }
        }
    }
    true
}
fn main() {
    let mut line = String::new();
    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read line");

    let inputs: Vec<u32> = line
        .split_whitespace()
        .map(|x| x.parse().expect("Failed to read"))
        .collect();

    let n: usize = inputs[0] as usize;

    let mut matrix: Vec<String> = vec![];
    for _ in 0..n {
        let mut str: String = String::new();
        io::stdin()
            .read_line(&mut str)
            .expect("failed to read input.");
        matrix.push(str.trim().parse().expect("invalid input"));
    }
    let mut str: String = Default::default();
    for s in matrix.iter() {
        str.push(s.chars().next().unwrap());
    }
    if all_diff(&str) == true {
        for s in matrix.iter() {
            if all_same(s) == false {
                print!("NO");
                return;
            }
        }
        print!("YES");
    } else {
        print!("NO");
    }
}

According to a new ISO standard, a flag of every country should have a chequered field n×m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.

The first line of the input contains numbers n and m (1≤n,m≤100), n — the amount of rows, m — the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following n lines contain m characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.

Output YES, if the flag meets the new ISO standard, and NO otherwise.

use std::io;
fn all_same(s: &String) -> bool {
    if s.len() <= 1 {
        return true;
    }
    let fch: char = s.chars().next().unwrap();
    for ch in s.chars().skip(1) {
        if ch != fch {
            return false;
        }
    }
    true
}
fn all_diff(s: &String) -> bool {
    if s.len() <= 1 {
        return true;
    }
    let chars = s.chars().collect::<Vec<char>>();
    for i in 0..s.len() - 1 {
        if chars[i] == chars[i + 1] {
            return false;
        }
    }
    true
}
fn main() {
    let mut line = String::new();
    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read line");

    let inputs: Vec<u32> = line
        .split_whitespace()
        .map(|x| x.parse().expect("Failed to read"))
        .collect();

    let n: usize = inputs[0] as usize;

    let mut matrix: Vec<String> = vec![];
    for _ in 0..n {
        let mut str: String = String::new();
        io::stdin()
            .read_line(&mut str)
            .expect("failed to read input.");
        matrix.push(str.trim().parse().expect("invalid input"));
    }
    let mut str: String = Default::default();
    for s in matrix.iter() {
        str.push(s.chars().next().unwrap());
    }
    if all_diff(&str) == true {
        for s in matrix.iter() {
            if all_same(s) == false {
                print!("NO");
                return;
            }
        }
        print!("YES");
    } else {
        print!("NO");
    }
}


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 q: Vec<(usize, usize)> = (0..n).map(|id| (scanner.scan(), id)).collect();
    let m: usize = scanner.scan();
    let mut gr_inv = vec![Vec::new(); n];
    for _ in 0..m {
        let a = scanner.scan::<usize>() - 1;
        let b = scanner.scan::<usize>() - 1;
        let c: i64 = scanner.scan();
        gr_inv[b].push((c, a));
    }
    q.sort_unstable();
    for row in &mut gr_inv {
        row.sort_unstable();
    }
    let mut result = 0;
    let mut used = vec![false; n];
    used[q[0].1] = true;
    for i in 1..n {
        let mut ok = false;
        for &(val, id) in &gr_inv[q[i].1] {
            if used[id] {
                result += val;
                used[q[i].1] = true;
                ok = true;
                break;
            }
        }
        if !ok {
            result = -1;
            break;
        }
    }
    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);
    }
}

Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai>qbi. Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.

The first input line contains integer n (1≤n≤1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0≤qj≤10^6)— the employees' qualifications. The following line contains number m (0≤m≤10000) — amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai, bi and ci (1≤ai,bi≤n, 0≤ci≤10^6). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai>qbi.

Output the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.

In the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1.

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 q: Vec<(usize, usize)> = (0..n).map(|id| (scanner.scan(), id)).collect();
    let m: usize = scanner.scan();
    let mut gr_inv = vec![Vec::new(); n];
    for _ in 0..m {
        let a = scanner.scan::<usize>() - 1;
        let b = scanner.scan::<usize>() - 1;
        let c: i64 = scanner.scan();
        gr_inv[b].push((c, a));
    }
    q.sort_unstable();
    q.reverse();
    for row in &mut gr_inv {
        row.sort_unstable();
    }
    let mut result = 0;
    let mut used = vec![false; n];
    used[q[0].1] = true;
    for i in 1..n {
        let mut ok = false;
        for &(val, id) in &gr_inv[q[i].1] {
            if used[id] {
                result += val;
                used[q[i].1] = true;
                ok = true;
                break;
            }
        }
        if !ok {
            result = -1;
            break;
        }
    }
    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);
    }
}


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::<i32>().unwrap()).collect();
    let mut costs: Vec<_> = lines.next().unwrap().unwrap().split(" ").enumerate().map(|(index, s)| (s.parse::<i32>().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);
}

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


use std::cmp::min;

use Direction::*;

#[derive(Debug, Eq, PartialEq)]
enum Direction { Direct, Reverse }

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

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

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

    let mut roads: Vec<Road> = Vec::with_capacity(cities_count);
    for _ in 0..cities_count {
        roads.push(Road {
            to: 0,
            direction: Direct,
            price: 0,
        })
    }

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

        if roads[from - 1].to == 0 {
            roads[from - 1] = Road { to, direction: Direct, price };
        } else {
            roads[to - 1] = Road { to: from, direction: Reverse, price };
        }
    }

    let direct_total_price: usize = roads
        .iter()
        .filter(|road| road.direction == Reverse)
        .map(|road| road.price)
        .sum();
    let reverse_total_price: usize = roads
        .iter()
        .filter(|road| road.direction == Direct)
        .map(|road| road.price)
        .sum();

    println!("{}", min(direct_total_price, reverse_total_price));
}

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


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 t = read::<usize>().unwrap();
    let v = read_vec::<i32>().unwrap();
    let mut ans = 1;

    for i in 0..t {
        let mut v_dif = Vec::new();

        for j in 0..t {
            if i == j {
                continue;
            }

            let dif = (v[i] - v[j]).abs();
            v_dif.push(dif);
        }

        let v_dif_dif = v_dif
            .windows(2)
            .map(|a| (a[0] - a[1]).abs())
            .collect::<Vec<i32>>();

        if v_dif_dif[0] % 2 == 0 && v_dif_dif.iter().min() == v_dif_dif.iter().max() {
            ans = i + 1;
            break;
        }
    }

    println!("{ans}");
}

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.

The first line contains integer n (3≤n≤100) — amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.

Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.

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 t = read::<usize>().unwrap();
    let v = read_vec::<i32>().unwrap();
    let mut ans = 1;

    for i in 0..t {
        let mut v_dif = Vec::new();

        for j in 0..t {
            if i == j {
                continue;
            }

            let dif = (v[i] - v[j]).abs();
            v_dif.push(dif);
        }

        dbg!(&v_dif);

        let v_dif_dif = v_dif
            .windows(2)
            .map(|a| (a[0] - a[1]).abs())
            .collect::<Vec<i32>>();

        let is_found = v_dif_dif.iter().all(|&x| x % 2 == 0);

        if is_found {
            ans = i + 1;
            break;
        }
    }

    println!("{ans}");
}


fn scan_str() -> String {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).unwrap();
    n
}
fn main() {
    let hours: usize = scan_str().trim().parse().unwrap();
    let array : Vec<usize> = scan_str().trim().split_whitespace().map(|x| x.parse().unwrap()).collect();
    let mut op = array[hours-1];

    loop {
        if !array.contains(&(op + 1)) {
            println!("{}",op +1);
            break;
        }
        else {
            op +=1;
        }
    }
}

«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.

The first line contains one integer n (1≤n≤3000) — the amount of previously added tests. The second line contains n distinct integers a1,a2,...,an (1≤ai≤3000) — indexes of these tests.

Output the required default value for the next test index.

use std::collections::HashSet;

#[allow(unused_macros)]
macro_rules! read {
    ($out:ident as $type:ty) => {
        let mut inner = String::new();
        std::io::stdin().read_line(&mut inner).expect("A string");
        let $out = inner.trim().parse::<$type>().expect("A parsable");
    };
}
#[allow(unused_macros)]
macro_rules! read_str {
    ($out:ident) => {
        let mut inner = String::new();
        std::io::stdin().read_line(&mut inner).expect("A string");
        let $out = inner.trim();
    };
}
#[allow(unused_macros)]
macro_rules! read_vec {
    ($out:ident as $type:ty) => {
        let mut inner = String::new();
        std::io::stdin().read_line(&mut inner).expect("A string");
        let $out = inner
            .trim()
            .split_whitespace()
            .map(|s| s.parse::<$type>().unwrap())
            .collect::<Vec<$type>>();
    };
}
fn solve() {
    let mut hs = (1..3001).collect::<HashSet<i32>>();
    read!(_n as i32);
    read_vec!(arr as i32);
    let ans = 3001;
    for c in arr {
        if hs.contains(&c) {
            hs.remove(&c);
        }
    }
    let mut hs = hs.drain().collect::<Vec<i32>>();
    hs.sort();
    match hs.iter().next() {
        Some(v) => println!("{}", v),
        None => println!("{}", ans),
    }
}
fn main() {
    let t = 1;
    //read!(t as i32);
    let mut t = t;
    while t > 0 {
        solve();
        t -= 1;
    }
}


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

fn main() {
    // Read input
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read input");

    let n: usize = input.trim().parse().expect("Invalid input");

    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read input");

    let lengths: Vec<u32> = input
        .split_whitespace()
        .map(|x| x.parse().expect("Invalid input"))
        .collect();

    // Create a HashMap to count the occurrences of each length
    let mut length_count = HashMap::new();

    for &length in &lengths {
        *length_count.entry(length).or_insert(0) += 1;
    }

    // Find the maximum count and the total number of distinct lengths
    let (max_count, distinct_lengths) = length_count
        .iter()
        .map(|(&length, &count)| (count, length))
        .max()
        .unwrap();

    println!("{} {}", max_count, distinct_lengths);
}

Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.

The first line contains an integer N (1≤N≤1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000.

In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars.

use std::io::{Stdout, stdout, Write, BufWriter};

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>
}

impl Scanner {
    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buffer.pop() {
                return token.parse().ok().expect("Failed parsing");
            }
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).expect("Failed reading");
            self.buffer = line.split_whitespace().rev().map(String::from).collect();
        }
    }

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

fn solution() {
    let mut input: Scanner = Scanner::default();
    let mut output: BufWriter<Stdout> = BufWriter::new(stdout());

    let bar_count: usize = input.next::<usize>();
    let mut bars: Vec<usize> = input.nexts::<usize>(bar_count);
    bars.sort();

    let mut height: usize = 1;
    let mut max_length: usize = 0;

    let mut i: usize = 0;
    while i < bar_count {
        let mut j = i + 1;
        while j < bar_count {
            if bars[i] != bars[j] {
                height += 1;
                break;
            }

            j += 1;
        }

        if max_length < j - i {
            max_length = j - i;
        }

        i = j;
    }

    writeln!(output, "{0} {1}", max_length, height).ok();
}

fn main() {
    solution();
}


use std::fmt::Write as OtherWrite;
use std::io::{self, Write};
use std::io::{stdin, stdout};
use std::string;

fn main() -> Result<(), io::Error> {
    let reader = stdin();
    let mut writer = stdout().lock();
    let mut lines = reader.lines();
    let s1 = lines.next().unwrap().unwrap();
    let s2 = lines.next().unwrap().unwrap();
    if let Some((index, repeat)) = solve(s1, s2) {
        writeln!(writer, "{repeat}")?;
        writeln!(
            writer,
            "{}",
            (index + 1..index + 1 + repeat)
                .map(|i| i.to_string())
                .collect::<Vec<_>>()
                .join(" ")
        )?;
    } else {
        writeln!(writer, "{}", 0)?;
    }
    Ok(())
}

fn solve(s1: String, s2: String) -> Option<(usize, usize)> {
    let mut iter2 = s2.chars().peekable();
    let mut result_index = None;
    for (i, c1) in s1.chars().enumerate() {
        if let Some(&c2) = iter2.peek() {
            if c1 != c2 {
                if result_index.is_some() {
                    return None;
                } else {
                    result_index = Some(i);
                }
            } else {
                iter2.next();
            }
        } else {
            if (s1.chars().skip(i + 1).next()) == None {
                return Some((i, 1));
            } else {
                return None;
            }
        }
    }
    let result_index = result_index?;
    let mut iter1 = s1.chars().skip(result_index);
    let c_result = iter1.next().unwrap();
    return Some((
        result_index,
        iter1.take_while(|&c| c_result == c).count() + 1,
    ));
}

Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?

The input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 10^6 symbols inclusive, the first string contains exactly 1 symbol more than the second one.

In the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0.

use std::io;

fn main(){

    let mut s1 = String::new();
    let mut s2 = String::new();

    io::stdin().read_line(&mut s1).expect("Failed to read line");
    io::stdin().read_line(&mut s2).expect("Failed to read line");

    s1 = s1.trim().to_owned();
    s2 = s2.trim().to_owned();

    let s1_len = s1.len();

    let prefix = prefix_length(&s1, &s2);
    let suffix = suffix_length(&s1, &s2);

    let mut total: i32 = (prefix as i32 + 1) - (s1_len as i32 - suffix as i32) + 1;

    if total < 0 {
        total = 0;
    }

    println!("{}",total);

    for i in 0..total{
        print!("{}",s1_len - suffix + i as usize + 1);
        if i < total-1{
            print!(" ");
        }else{
            println!();
        }
    }

}

fn prefix_length(s1: &String, s2: &String) -> usize {

    let s1_bytes = s1.as_bytes();
    let s2_bytes = s2.as_bytes();

    let s2_len = s2.len();

    let mut i: usize = 0;
    while i < s2_len && s1_bytes[i] == s2_bytes[i] {
        i+=1;
    }

    return i-1;
}

fn suffix_length(s1: &String, s2: &String) -> usize {

    let s1_bytes = s1.as_bytes();
    let s2_bytes = s2.as_bytes();

    let s1_len = s1.len();

    let mut i: usize = s1_len - 1;

    while i > 0 && s1_bytes[i] == s2_bytes[i-1] {
        i-=1;
    }

    return s1_len - i;
}

[{'input': ['abdrakadabra\r\nabrakadabra\r\n'], 'output': ['1\r\n3 ']}, {'input': ['aa\r\na\r\n'], 'output': ['2\r\n1 2 ']}, {'input': ['competition\r\ncodeforces\r\n'], 'output': ['0\r\n']}, {'input': ['ab\r\na\r\n'], 'output': ['1\r\n2 ']}, {'input': ['bb\r\nb\r\n'], 'output': ['2\r\n1 2 ']}, {'input': ['aab\r\nab\r\n'], 'output': ['2\r\n1 2 ']}, {'input': ['aabb\r\nabb\r\n'], 'output': ['2\r\n1 2 ']}, {'input': ['babaacaacaa\r\nbbaacaacaa\r\n'], 'output': ['1\r\n2 ']}, {'input': ['bccaabbcccc\r\nbccaabcccc\r\n'], 'output': ['2\r\n6 7 ']}, {'input': ['ababcaabaaa\r\nabacaabaaa\r\n'], 'output': ['1\r\n4 ']}, {'input': ['cccacaccacb\r\ncccacaccac\r\n'], 'output': ['1\r\n11 ']}, {'input': ['aaaaaaaaaaa\r\naaaaaaaaaa\r\n'], 'output': ['11\r\n1 2 3 4 5 6 7 8 9 10 11 ']}, {'input': ['lcaaxcbcjca\r\nccaaacccca\r\n'], 'output': ['0\r\n']}, {'input': ['babbbtaamba\r\nbabbbaabba\r\n'], 'output': ['0\r\n']}, {'input': ['xdfxmcnzpch\r\nazvotghvtk\r\n'], 'output': ['0\r\n']}, {'input': ['ki\r\nb\r\n'], 'output': ['0\r\n']}, {'input': ['vct\r\nie\r\n'], 'output': ['0\r\n']}, {'input': ['feee\r\nsnl\r\n'], 'output': ['0\r\n']}, {'input': ['cbxxxxzvks\r\ncbxxxzvks\r\n'], 'output': ['4\r\n3 4 5 6 ']}, {'input': ['qybldcgfhdhhhhhhhhhhopqkhuczzytzluiahwbqjltgafvvoecititchjwdoljiehubngmtjckqymldhoncgtqhxnqvoagnrmur\r\nqybldcgfhdhhhhhhhhhopqkhuczzytzluiahwbqjltgafvvoecititchjwdoljiehubngmtjckqymldhoncgtqhxnqvoagnrmur\r\n'], 'output': ['10\r\n11 12 13 14 15 16 17 18 19 20 ']}]


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

/* v1, faster but less about what we need to learn
struct TeamScore {
    name : String,
    score: usize
}

fn main() {
    let handle = io::stdin();
    let mut buf = String::new();
    handle.read_line(&mut buf).unwrap();

    let n : usize = buf.trim().parse().unwrap();

    buf.clear();
    handle.read_line(&mut buf).unwrap();
    let mut team1 = TeamScore{ name: buf.trim().to_string(), score: 1};
    buf.clear();
    let mut team2 = TeamScore{ name: String::new(), score: 0};
    for _ in 1..n {
        handle.read_line(&mut buf).unwrap();
        if buf.trim() == team1.name {
            team1.score += 1;
        } else {
            if team2.name.len() == 0 {
                team2.name = buf.trim().to_string();
            }
            team2.score += 1;
        }

        buf.clear();
    }

    if team1.score > team2.score {
        println!("{}", team1.name);
    } else {
        println!("{}", team2.name);
    }
}
*/

fn main() {
    let mut scores : HashMap<String, usize> = HashMap::new();
    let handle = io::stdin();
    let mut buf = String::new();
    handle.read_line(&mut buf).unwrap();

    let n : usize = buf.trim().parse().unwrap();

    for _ in 0..n {
        handle.read_line(&mut buf).unwrap();
        *scores.entry(buf.trim().to_string()).or_default() += 1;
        buf.clear();
    }

    let entry = scores.iter().max_by_key(|&(_k,v)| v).unwrap();
    println!("{}", entry.0);
}

One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.

The first line contains an integer n (1≤n≤100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.

Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.

#![allow(unused)]
use std::io::{stdin, stdout};

fn input() -> String {
    let mut buf: String = String::new();
    stdin().read_line(&mut buf);
    buf.trim().to_owned()
}

fn int_input() -> i32 {
    input().parse::<i32>().unwrap()
}

fn vec_input() -> Vec<String> {
    input().split_whitespace().map(|i| i.parse::<String>().unwrap()).collect::<Vec<String>>()
}

fn main() {
    let mut n = int_input();
    let mut arr = vec![];
    for _ in 0..n {
        arr.push(input());
    }
    arr.sort();
    println!("{}", arr[(n/2) as usize]);
}

[{'input': ['1\r\nABC\r\n'], 'output': ['ABC\r\n']}, {'input': ['5\r\nA\r\nABA\r\nABA\r\nA\r\nA\r\n'], 'output': ['A\r\n']}, {'input': ['2\r\nXTSJEP\r\nXTSJEP\r\n'], 'output': ['XTSJEP\r\n']}, {'input': ['3\r\nXZYDJAEDZ\r\nXZYDJAEDZ\r\nXZYDJAEDZ\r\n'], 'output': ['XZYDJAEDZ\r\n']}, {'input': ['3\r\nQCCYXL\r\nQCCYXL\r\nAXGLFQDD\r\n'], 'output': ['QCCYXL\r\n']}, {'input': ['3\r\nAZID\r\nEERWBC\r\nEERWBC\r\n'], 'output': ['EERWBC\r\n']}, {'input': ['3\r\nHNCGYL\r\nHNCGYL\r\nHNCGYL\r\n'], 'output': ['HNCGYL\r\n']}, {'input': ['4\r\nZZWZTG\r\nZZWZTG\r\nZZWZTG\r\nZZWZTG\r\n'], 'output': ['ZZWZTG\r\n']}, {'input': ['4\r\nA\r\nA\r\nKUDLJMXCSE\r\nA\r\n'], 'output': ['A\r\n']}, {'input': ['5\r\nPHBTW\r\nPHBTW\r\nPHBTW\r\nPHBTW\r\nPHBTW\r\n'], 'output': ['PHBTW\r\n']}, {'input': ['5\r\nPKUZYTFYWN\r\nPKUZYTFYWN\r\nSTC\r\nPKUZYTFYWN\r\nPKUZYTFYWN\r\n'], 'output': ['PKUZYTFYWN\r\n']}, {'input': ['5\r\nHH\r\nHH\r\nNTQWPA\r\nNTQWPA\r\nHH\r\n'], 'output': ['HH\r\n']}, {'input': ['10\r\nW\r\nW\r\nW\r\nW\r\nW\r\nD\r\nW\r\nD\r\nD\r\nW\r\n'], 'output': ['W\r\n']}, {'input': ['19\r\nXBCP\r\nTGACNIH\r\nXBCP\r\nXBCP\r\nXBCP\r\nXBCP\r\nXBCP\r\nTGACNIH\r\nXBCP\r\nXBCP\r\nXBCP\r\nXBCP\r\nXBCP\r\nTGACNIH\r\nXBCP\r\nXBCP\r\nTGACNIH\r\nTGACNIH\r\nXBCP\r\n'], 'output': ['XBCP\r\n']}, {'input': ['33\r\nOWQWCKLLF\r\nOWQWCKLLF\r\nOWQWCKLLF\r\nPYPAS\r\nPYPAS\r\nPYPAS\r\nOWQWCKLLF\r\nPYPAS\r\nOWQWCKLLF\r\nPYPAS\r\nPYPAS\r\nOWQWCKLLF\r\nOWQWCKLLF\r\nOWQWCKLLF\r\nPYPAS\r\nOWQWCKLLF\r\nPYPAS\r\nPYPAS\r\nPYPAS\r\nPYPAS\r\nOWQWCKLLF\r\nPYPAS\r\nPYPAS\r\nOWQWCKLLF\r\nOWQWCKLLF\r\nPYPAS\r\nOWQWCKLLF\r\nOWQWCKLLF\r\nPYPAS\r\nPYPAS\r\nOWQWCKLLF\r\nPYPAS\r\nPYPAS\r\n'], 'output': ['PYPAS\r\n']}, {'input': ['51\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\nNC\r\n'], 'output': ['NC\r\n']}, {'input': ['89\r\nH\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nH\r\nVOCI\r\nVOCI\r\nVOCI\r\nH\r\nH\r\nH\r\nVOCI\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nH\r\nH\r\nVOCI\r\nH\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nVOCI\r\nH\r\nH\r\nH\r\nH\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nH\r\nVOCI\r\nVOCI\r\n'], 'output': ['VOCI\r\n']}, {'input': ['100\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nM\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\nHA\r\n'], 'output': ['HA\r\n']}, {'input': ['100\r\nG\r\nG\r\nS\r\nS\r\nG\r\nG\r\nS\r\nS\r\nG\r\nS\r\nS\r\nS\r\nG\r\nS\r\nG\r\nG\r\nS\r\nG\r\nS\r\nS\r\nG\r\nS\r\nS\r\nS\r\nS\r\nS\r\nG\r\nS\r\nG\r\nS\r\nS\r\nG\r\nG\r\nG\r\nS\r\nS\r\nS\r\nS\r\nG\r\nS\r\nS\r\nG\r\nG\r\nG\r\nG\r\nG\r\nS\r\nG\r\nG\r\nS\r\nS\r\nS\r\nS\r\nS\r\nG\r\nG\r\nS\r\nG\r\nG\r\nG\r\nG\r\nG\r\nS\r\nS\r\nG\r\nS\r\nS\r\nS\r\nS\r\nG\r\nS\r\nS\r\nG\r\nS\r\nG\r\nG\r\nG\r\nG\r\nG\r\nG\r\nG\r\nG\r\nG\r\nG\r\nG\r\nS\r\nS\r\nG\r\nS\r\nS\r\nS\r\nS\r\nG\r\nG\r\nG\r\nS\r\nG\r\nG\r\nG\r\nS\r\n'], 'output': ['G\r\n']}, {'input': ['100\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nOBH\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\nWL\r\n'], 'output': ['WL\r\n']}]


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

fn main() {
    let mut name_count = HashMap::new();
    let mut names = Vec::new();

    let mut n = String::new();
    io::stdin().read_line(&mut n).unwrap();
    let n = n.trim().parse::<usize>().unwrap();

    for _ in 0..n {
        let mut name = String::new();
        io::stdin().read_line(&mut name).unwrap();
        let name = name.trim().to_owned();

        let count = name_count.entry(name.clone()).or_insert(0);
        *count += 1;

        let formatted_name = if *count > 1 {
            format!("{}({})", name, count)
        } else {
            name
        };

        names.push(formatted_name);
    }

    for name in names {
        println!("{}", name);
    }
}

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


use std::io;

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

  let n : usize = input.trim().parse().unwrap();

  let mut v : Vec<_> = vec![0;n];
  for i in 0..n {
    input.clear();
    io::stdin().read_line(&mut input).unwrap();
    v[i] = input.trim().parse::<usize>().unwrap();

  }
  let mut one = 0;
  let mut two = 0;
  let mut three = 0;
  for i in v {
    if i == 1 {
      one+=1;
    } else if i == 2 {
      two+=1;
    } else {
      three+=1;
    }
  }

  println!("{}",one+two+three - one.max(two).max(three));
  Ok(())

}

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


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];
    buf.clear();
    reader.read_line(&mut buf);
    let it = buf.trim().split(" ");
    let mut ct = 0;
    for sub in it{
        v[ct] = sub.trim().parse()
            .expect(" ");
        ct += 1;
    }
    buf.clear();
    reader.read_line(&mut buf);
    let wv = buf.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);
}

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


use std::io::stdin;

fn main() {
    let mut buffer = String::new();
    let mut sum: Vec<i32> = vec![0,0,0];

    stdin().read_line(&mut buffer);

    let count = buffer.trim()
                      .parse::<i32>()
                      .unwrap();

    for _x in 0..count {
        let mut x = 0;
        buffer.clear();
        stdin().read_line(&mut buffer);
               buffer.trim()
                     .split(" ")
                     .map(|x| x.parse::<i32>().unwrap())
                     .for_each(|y| { sum[x] += y; x += 1;})
    }

    if sum.iter().sum::<i32>() == 0 {
        print!("YES");
    } else {
        print!("NO");
    }
}

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


use std::io;

fn main() {
    let times: Vec<usize> = io::stdin()
        .lines()
        .skip(1)
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|str| str.parse().unwrap())
        .collect();

    let mut lhs_position = 0;
    let mut lhs_time: usize = 0;
    let mut lhs_count: usize = 0;

    let mut rhs_position = times.len().checked_sub(1).unwrap();
    let mut rhs_time: usize = 0;
    let mut rhs_count: usize = 0;

    while lhs_position < rhs_position {
        if lhs_time <= rhs_time {
            lhs_time += times[lhs_position];
            lhs_count += 1;
            lhs_position += 1;
        } else {
            rhs_time += times[rhs_position];
            rhs_count += 1;
            rhs_position -= 1;
        }
    }

    println!("{lhs_count} {rhs_count}")
}

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


use std::io;

fn main() {
    let mut num_words = String::new();
    io::stdin().read_line(&mut num_words).expect("Failed");

    let n: u32 = num_words.trim().parse().expect("Failed");

    for _k in 0..n {
        let mut question_string: String = String::new();
        io::stdin().read_line(&mut question_string).expect("Failed");

        if question_string.len() > 10 {
            println!("{}{}{}", question_string.chars().nth(0).unwrap(), question_string.len() - 2, question_string.chars().last().unwrap());
        } else {
            println!("{}", question_string);
        }
    }
}

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


use std::io::stdin;

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

    stdin().read_line(&mut buffer).unwrap();

    let numbers: Vec<i32> = buffer
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap())
        .collect();

    let (n, k, t): (i32, i32, i32) = (numbers[0], numbers[1], numbers[2]);

    let count: i32 = ((t as f32) * (n as f32) * (k as f32) / 100f32).floor() as i32;

    let mut squares: Vec<String> = Vec::new();

    for i in 0..n {
        if i < count / n {
            squares.push(k.to_string());
        } else if i == count / k {
            squares.push((count % k).to_string());
        } else {
            squares.push("0".to_string());
        }
    }

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

A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1≤i≤n) is displayed, squares 1,2,... ,i-1 has the saturation k, squares i+1,i+2,... ,n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture. For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.

We are given 3 space-separated integers n, k, t (1≤n,k≤100, 0≤t≤100).

Print n numbers. The i-th of them should be equal to ai.

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

/*
 * [[[[[[[[[[[[[[[[hello]]]]]]]]]]]]]]]]
 * [[[[[[[[[[[[[[[[darkness]]]]]]]]]]]]]]]]
 * [[[[[[[[[[[[[[[[my]]]]]]]]]]]]]]]]
 * [[[[[[[[[[[[[[[[old]]]]]]]]]]]]]]]]
 * [[[[[[[[[[[[[[[[friend]]]]]]]]]]]]]]]]
 */

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

    let n = reader.next::<i32>();
    let k = reader.next::<i32>();
    let t = reader.next::<i32>();

    let total = n * k;
    let mut needed = (((t as f64) * (total as f64)) / 100.0) as i32;

    // writeln!(out, "{} {}", total, needed).ok();

    for _ in 0..n {
        if needed > 0 {
            write!(out, "{} ", min(needed, k)).ok();
        } else {
            write!(out, "0 ").ok();
        }
        needed -= k;
    }
    writeln!(out, "").ok();
}

#[derive(Default)]
struct Scanner {
    buffer: Vec<String>,
}

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


#![allow(dead_code)]
#![allow(unused)]
#![allow(unused_imports)]
use std::io::{self, prelude::*};
use std::str;
use std::cmp; // cmp::max
use std::collections::BTreeMap;
use std::f64; // f64::max
use std::collections::BTreeSet;

struct Scanner<R> {
    reader: R,
    buf_str: Vec<u8>,
    buf_iter: str::SplitWhitespace<'static>,
}

impl<R: BufRead> Scanner<R> {
    fn new(reader: R) -> Self {
        Self { reader, buf_str: vec![], buf_iter: "".split_whitespace() }
    }
    fn token<T: str::FromStr>(&mut self) -> T {
        loop {
            if let Some(token) = self.buf_iter.next() {
                return token.parse().ok().expect("Failed parse");
            }
            self.buf_str.clear();
            self.reader.read_until(b'\n', &mut self.buf_str).expect("Failed read");
            self.buf_iter = unsafe {
                let slice = str::from_utf8_unchecked(&self.buf_str);
                std::mem::transmute(slice.split_whitespace())
            }
        }
    }

    fn token0(&mut self) -> String {
        self.buf_str.clear();
        self.reader.read_until(b'\n', &mut self.buf_str).expect("Failed read");
        return String::from_utf8_lossy(&self.buf_str).trim().to_string();
    }

    fn i64(&mut self) -> i64 {
        self.token::<i64>()
    }

    fn string(&mut self) -> Vec<u8> {
        self.token::<String>().into_bytes()
    }

    fn usize(&mut self) -> usize {
        self.token::<usize>()
    }
}

#[derive(Debug, PartialOrd, Ord, PartialEq, Eq)]
struct Data {
    x: i64,
    y: i64,
} // .sort_by(|a, b| b.x.cmp(&a.x));

fn is_prime(s: i64) -> i64 {
    let mut lo = 0;
    for i in 1..=s {
        if s % i == 0 {
            lo += 1;
        }
    }
    if lo == 2 {
        1
    }  else {
        0
    }
}

fn solve<R: BufRead>(s: &mut Scanner<R>) {
    let x = s.i64();
    let y = s.i64();
    for i in x+1..y {
        if is_prime(i) == 1 {
            println!("NO");
        }
    }

    if is_prime(y) == 1 {
        println!("YES");
    } else {
        println!("NO");
    }
}

fn main() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut t = 1;
    // t = scan.i64();
    while t > 0 {
        t -= 1;
        solve(&mut scan);
    }
}

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


use std::io::BufRead;

/**
 * A. Train and Peter
 * time limit per test: 1 second
 * memory limit per test: 64 megabytes
 * input: standard input
 * output: standard output
 *
 * 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.
 *
 * Input
 * 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
 * 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.
 *
 * Examples
 *   Input
 *   atob
 *   a
 *   b
 *
 *   Output
 *   forward
 *
 *   Input
 *   aaacaaa
 *   aca
 *   aa
 *
 *   Output
 *   both
 *
 * Note
 * It 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
 */
fn main() {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();

    let path = lines.next().unwrap().unwrap();
    let a = lines.next().unwrap().unwrap();
    let b = lines.next().unwrap().unwrap();

    let a_indices: Vec<_> = path
        .as_bytes()
        .windows(a.len())
        .enumerate()
        .filter(|(_, slice)| slice == &a.as_bytes())
        .map(|(i, _)| i)
        .collect();
    let b_indices: Vec<_> = path
        .as_bytes()
        .windows(b.len())
        .enumerate()
        .filter(|(_, slice)| slice == &b.as_bytes())
        .map(|(i, _)| i)
        .collect();

    let (mut left, mut right) = (false, false);
    for &i in &a_indices {
        for &j in &b_indices {
            if i < j {
                let a_end = i + a.len();
                left |= a_end <= j;
            } else {
                let b_end = j + b.len();
                right |= b_end <= i;
            }
        }
    }

    match (left, right) {
        (true, true) => println!("both"),
        (true, _) => println!("forward"),
        (_, true) => println!("backward"),
        _ => println!("fantasy"),
    }
}

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 10^5, 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.

It 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;
use std::io::BufReader;
use std::io::BufRead;
use std::str::FromStr;
use std::fmt::Debug;
use std::ops::Add;
use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet};

fn main() {
    let buf = &mut io::BufReader::new(io::stdin());
    let mut ss = String::new();
    let mut ss1 = String::new();
    let mut ss2 = String::new();

    buf.read_line(&mut ss).unwrap();
    buf.read_line(&mut ss1).unwrap();
    buf.read_line(&mut ss2).unwrap();

    let s = ss.trim();
    let s1 = ss1.trim();
    let s2 = ss2.trim();

    let mut fwd = false;
    if let Some(idx) = s.find(&s1) {
        if let Some(_) = s[idx+s1.len()..].find(&s2) {
            fwd = true;
        }
    }
    let mut bck = false;
    if let Some(idx) = s.rfind(&s1.chars().rev().collect::<String>()) {
        if let Some(_) = s[..idx].rfind(&s2.chars().rev().collect::<String>()) {
            bck = true;
        }
    }
    let result = match (fwd, bck) {
        (true, false) => "forward",
        (false, true) => "backward",
        (true, true) => "both",
        (false, false) => "fantasy",
    };
    println!("{}", result);
}

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


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

struct Input {
    buffer: collections::VecDeque<String>,
}

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

    fn next<T: std::str::FromStr>(&mut self) -> T {
        while self.buffer.len() == 0 {
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).ok();
            for word in line.split_whitespace() {
                self.buffer.push_back(word.to_string())
            }
        }

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

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

    let n: usize = input.next();
    let l: usize = input.next();

    let mut a: Vec<usize> = Vec::with_capacity(n);
    for _ in 0..n {
        let mut value = input.next();
        if value >= l {
            a.push(value);
        }
    }

    let mut max_area = 0;

    for width in l..(l * 2) {
        let mut height = 0;
        let mut cuttings: Vec<usize> = Vec::new();
        for j in 0..a.len() {
            let mut remains = a[j];
            while remains == width || remains >= width + l {
                height += 1;
                remains -= width;
            }
            if remains > 0 {
                cuttings.push(remains);
            }
        }
        cuttings.sort();
        while cuttings.len() > 0 {
            let mut remains = cuttings.pop().unwrap();
            while cuttings.len() > 0 || remains < width {
                remains += cuttings.drain(0..1).next().unwrap();
            }
            if remains >= width {
                height += 1;
            }
        }
        let area = width * height;
        if area > max_area {
            max_area = area;
        }
    }
    println!("{}", max_area);
}

The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k × d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.

The first output line contains two space-separated integers n and l (1 ≤ n, l ≤ 100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1 ≤ ai ≤ 100).

Print the single number — the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.

NoteIn the first sample test the required window is 2 × 4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves.

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

struct Input {
    buffer: collections::VecDeque<String>,
}

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

    fn next<T: std::str::FromStr>(&mut self) -> T {
        while self.buffer.len() == 0 {
            let mut line = String::new();
            std::io::stdin().read_line(&mut line).ok();
            for word in line.split_whitespace() {
                self.buffer.push_back(word.to_string())
            }
        }

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

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

    let n: usize = input.next();
    let l: usize = input.next();

    let mut a: Vec<usize> = Vec::with_capacity(n);
    for _ in 0..n {
        let mut value = input.next();
        if value >= l {
            a.push(value);
        }
    }

    let mut max_area = 0;

    for width in l..(l * 2) {
        let mut height = 0;
        let mut cuttings: Vec<usize> = Vec::new();
        for j in 0..a.len() {
            let mut remains = a[j];
            while remains == width || remains >= width + l {
                height += 1;
                remains -= width;
            }
            if remains > 0 && (remains >= width || remains <= width - l) {
                cuttings.push(remains);
            }
        }
        cuttings.sort();
        while cuttings.len() > 0 {
            let mut remains = cuttings.pop().unwrap();
            while cuttings.len() > 0 && remains < width {
                remains += cuttings.drain(0..1).next().unwrap();
            }
            if remains >= width {
                height += 1;
            }
        }
        let area = width * height;
        if area > max_area {
            max_area = area;
        }
        //println!("{:?}", width * height);
    }
    println!("{}", max_area);
}


use std::io::BufRead;

/**
 * B. Running Student
 * time limit per test: 1 second
 * memory limit per test: 64 megabytes
 * input: standard input
 * output: standard output
 *
 * And again a misfortune fell on Poor Student. He is being late for an exam.
 *
 * Having rushed to a bus stop that is in point (0,â0), he got on a minibus and they drove along a straight line, parallel
 * to axis OX, in the direction of increasing x.
 *
 * Poor Student knows the following:
 *   during one run the minibus makes n stops, the i-th stop is in point (xi,â0)
 *   coordinates of all the stops are different
 *   the minibus drives at a constant speed, equal to vb
 *   it can be assumed the passengers get on and off the minibus at a bus stop momentarily
 *   Student can get off the minibus only at a bus stop
 *   Student will have to get off the minibus at a terminal stop, if he does not get off earlier
 *   the University, where the exam will be held, is in point (xu,âyu)
 *   Student can run from a bus stop to the University at a constant speed vs as long as needed
 *   a distance between two points can be calculated according to the following formula:
 *     d = sqrt((x_2 - x_1) ^ 2 + (y_2 - y_1) ^ 2)
 *   Student is already on the minibus, so, he cannot get off at the first bus stop
 * Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get
 * off. If such bus stops are multiple, choose the bus stop closest to the University.
 *
 * Input
 * The first line contains three integer numbers: 2ââ¤ânââ¤â100, 1ââ¤âvb,âvsââ¤â1000. The second line contains n non-negative
 * integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and
 * xnââ¤â105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute
 * value.
 *
 * Output
 * In the only line output the answer to the problem â index of the optimum bus stop.
 *
 * Examples
 *   Input
 *   4 5 2
 *   0 2 4 6
 *   4 1
 *
 *   Output
 *   3
 *
 *   Input
 *   2 1 1
 *   0 100000
 *   100000 100000
 *
 *   Output
 *   2
 *
 *   Note
 *   As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be
 * surprised, if Student's speed is higher than the speed of the minibus.
 */
fn main() {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();

    let first_line = lines.next().unwrap().unwrap();
    let mut first_line = first_line
        .split_ascii_whitespace()
        .map(|v| v.parse().unwrap());

    let n: usize = first_line.next().unwrap();
    let vb = first_line.next().unwrap();
    let vs = first_line.next().unwrap();
    let (vb, vs) = (vb as f64, vs as f64);

    let bus_stops: Vec<usize> = lines
        .next()
        .unwrap()
        .unwrap()
        .split_ascii_whitespace()
        .take(n)
        .map(|v| v.parse().unwrap())
        .collect();

    let university_line = lines.next().unwrap().unwrap();
    let (ux, uy) = university_line.split_once(' ').unwrap();
    let (ux, uy): (isize, isize) = (ux.parse().unwrap(), uy.parse().unwrap());
    let (ux, uy) = (ux as f64, uy as f64);

    let mut time_to_stop = vec![0.; bus_stops.len()];
    for i in 1..time_to_stop.len() {
        let prev_stop = bus_stops[i - 1];
        let stop = bus_stops[i];
        time_to_stop[i] = time_to_stop[i - 1] + (stop - prev_stop) as f64 / vb;
    }

    let bus_stop = bus_stops
        .into_iter()
        .zip(time_to_stop)
        .map(|(x, bus_time)| {
            let (dx, dy) = (ux - x as f64, uy);
            let distance = (dx * dx + dy * dy).sqrt();
            let student_time = distance / vs;
            bus_time + student_time
        })
        .enumerate()
        .skip(1)
        .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
        .map(|(i, _)| i + 1)
        .unwrap();

    println!("{bus_stop}");
}

And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0,0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi,0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu,yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2≤n≤100, 1≤vb,vs≤1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn≤10^5. The third line contains the coordinates of the University, integers xu and yu, not exceeding 10^5 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

use std::io;
fn main(){
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Err");
    let mut speeds: Vec<u64> = vec![];

    for i in input.trim().to_string().split(" "){
        speeds.push(i.parse::<u64>().unwrap());
    }

    input = String::new();
    io::stdin().read_line(&mut input).expect("Err");
    let mut stops: Vec<u64> = vec![];
    for i in input.trim().to_string().split(" "){
        stops.push(i.parse::<u64>().unwrap());
    }

    input = String::new();
    io::stdin().read_line(&mut input).expect("Err");
    let mut pos: Vec<i64> = vec![];
    for i in input.trim().to_string().split(" "){
        pos.push(i.parse::<i64>().unwrap());
    }

    let mut best: [f64; 2] = [2147483647 as f64; 2];

    for i in 0..stops.len(){
        let j = stops[i];
        if j == 0{
            continue;
        }
        let bus_time: f64 = j as f64 / speeds[1] as f64;
        let sprint_time: f64 = hyp(j as i64, pos[0], 0, pos[1]) / speeds[2] as f64;
        if bus_time + sprint_time <= best[0]{
            best[0] = bus_time + sprint_time;
            best[1] = i as f64;
        }
    }

    println!("{}", best[1] as u64 + 1 as u64);
}

fn hyp(x1: i64, x2: i64, y1: i64, y2: i64) -> f64{
    ((((x2-x1) as i64).pow(2) + ((y2-y1) as i64).pow(2)) as f64).sqrt()
}