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

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

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

// ここまで

fn run() {
    input! {
        n: usize,
        a: [usize; n],
    }
    let m = 5000;
    let mut weight = vec![0; m + 1];
    for a in a {
        if a == 0 {
            weight[1] += 1;
        } else {
            weight[a] += 1;
        }
    }
    let mut factor: Vec<usize> = vec![m; m + 1];
    let mut prime = vec![];
    for i in 2..=m {
        if factor[i] == m {
            for j in 1..=(m / i) {
                factor[j * i] = prime.len();
            }
            prime.push(i);
        }
    }
    let mut cnt = vec![vec![0; prime.len()]; m + 1];
    for i in 2..=m {
        let mut c = cnt[i - 1].clone();
        let mut t = i;
        while t > 1 {
            let k = factor[t];
            let p = prime[k];
            while t % p == 0 {
                c[k] += 1;
                t /= p;
            }
        }
        cnt[i] = c;
    }
    let mut root_sum = 0u64;
    for i in 1..=m {
        root_sum += cnt[i].iter().fold(0, |s, a| s + *a) * weight[i];
    }
    let all = n as u64;
    let root_sum = root_sum;
    let mut dfs = vec![];
    for i in 0..prime.len() {
        let mut c = 0;
        let r = if i == prime.len() - 1 {m + 1} else {prime[i + 1]};
        for j in prime[i]..r {
            c += weight[j];
        }
        dfs.push((prime[i], r, i, 1, c, root_sum - c + all - c));
    }
    let mut ans = root_sum;
    while let Some((l, r, index, num, sum, w)) = dfs.pop() {
        ans = std::cmp::min(ans, w);
        if sum == 0 || l >= r || index >= prime.len() {
            continue;
        }
        if cnt[l][index] > num {
            dfs.push((l, r, index, num + 1, sum, w + all - 2 * sum));
        } else if cnt[l][index] == cnt[r - 1][index] {
            dfs.push((l, r, index - 1, 1, sum, w + all - 2 * sum));
        } else {
            let mut zero = 0;
            let mut k = l;
            while k < r && cnt[k][index] == cnt[l][index] {
                zero += weight[k];
                k += 1;
            }
            dfs.push((l, k, index - 1, 1, zero, w + all - 2 * zero));
            dfs.push((k, r, index, num + 1, sum - zero, w + all - 2 * (sum - zero)));
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}

Æsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($$$1, 2, 3, \ldots$$$). The node with a number $$$x$$$ ($$$x > 1$$$), is directly connected with a node with number $$$\frac{x}{f(x)}$$$, with $$$f(x)$$$ being the lowest prime divisor of $$$x$$$.Vanessa's mind is divided into $$$n$$$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $$$i$$$-th fragment is now located at the node with a number $$$k_i!$$$ (a factorial of $$$k_i$$$).To maximize the chance of successful awakening, Ivy decides to place the samples in a node $$$P$$$, so that the total length of paths from each fragment to $$$P$$$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $$$P$$$ needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $$$P$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — number of fragments of Vanessa's mind. The second line contains $$$n$$$ integers: $$$k_1, k_2, \ldots, k_n$$$ ($$$0 \le k_i \le 5000$$$), denoting the nodes where fragments of Vanessa's mind are located: the $$$i$$$-th fragment is at the node with a number $$$k_i!$$$.

Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $$$P$$$). As a reminder, if there are multiple fragments at the same node, the distance from that node to $$$P$$$ needs to be counted multiple times as well.

NoteConsidering the first $$$24$$$ nodes of the system, the node network will look as follows (the nodes $$$1!$$$, $$$2!$$$, $$$3!$$$, $$$4!$$$ are drawn bold):For the first example, Ivy will place the emotion samples at the node $$$1$$$. From here:  The distance from Vanessa's first fragment to the node $$$1$$$ is $$$1$$$.  The distance from Vanessa's second fragment to the node $$$1$$$ is $$$0$$$.  The distance from Vanessa's third fragment to the node $$$1$$$ is $$$4$$$. The total length is $$$5$$$.For the second example, the assembly node will be $$$6$$$. From here:  The distance from Vanessa's first fragment to the node $$$6$$$ is $$$0$$$.  The distance from Vanessa's second fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's third fragment to the node $$$6$$$ is $$$2$$$.  The distance from Vanessa's fourth fragment to the node $$$6$$$ is again $$$2$$$. The total path length is $$$6$$$.

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

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

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

// ここまで

fn run() {
    input! {
        n: usize,
        a: [usize; n],
    }
    let m = 5000;
    let mut weight = vec![0; m + 1];
    for a in a {
        if a == 0 {
            weight[1] += 1;
        } else {
            weight[a] += 1;
        }
    }
    let mut factor: Vec<usize> = vec![m; m + 1];
    let mut prime = vec![];
    for i in 2..=m {
        if factor[i] == m {
            for j in 1..=(m / i) {
                factor[j * i] = prime.len();
            }
            prime.push(i);
        }
    }
    let mut cnt = vec![vec![0; prime.len()]; m + 1];
    for i in 2..=m {
        let mut c = cnt[i - 1].clone();
        let mut t = i;
        while t > 1 {
            let k = factor[t];
            let p = prime[k];
            while t % p == 0 {
                c[k] += 1;
                t /= p;
            }
        }
        cnt[i] = c;
    }
    let cnt = cnt;
    let mut root_sum = 0u64;
    for i in 1..=m {
        root_sum += cnt[i].iter().fold(0, |s, a| s + *a) * weight[i];
    }
    let all = n as u64;
    let root_sum = root_sum;
    let mut dfs = vec![(2, m + 1, prime.len() - 1, 0, all - weight[1], root_sum)];
    let mut ans = root_sum;
    while let Some((l, r, index, num, sum, w)) = dfs.pop() {
        ans = std::cmp::min(ans, w);
        if 2 * sum <= all || l >= r || index >= prime.len() {
            continue;
        }
        assert!(num <= cnt[l][index]);
        if cnt[l][index] > num {
            dfs.push((l, r, index, num + 1, sum, w + all - 2 * sum));
        } else if cnt[l][index] == cnt[r - 1][index] {
            dfs.push((l, r, index - 1, 0, sum, w));
        } else {
            let mut zero = 0;
            let mut k = l;
            while k < r && cnt[k][index] == cnt[l][index] {
                zero += weight[k];
                k += 1;
            }
            dfs.push((l, k, index - 1, 0, zero, w));
            dfs.push((k, r, index, num, sum - zero, w));
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}


#![allow(non_snake_case)]
#[allow(dead_code)] fn read_line() -> String { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("failed to read line"); buffer }
#[allow(dead_code)] fn read<T : std::str::FromStr>() -> T where T::Err: std::fmt::Debug { read_line().trim().parse::<T>().expect("failed to read value") }
#[allow(dead_code)]fn read_vec<T : std::str::FromStr>() -> Vec<T> where T::Err: std::fmt::Debug { read_line().split_whitespace().map(|x| x.parse::<T>().expect("failed to read values")).collect() }
fn lock_stdout() -> std::io::BufWriter<std::io::StdoutLock<'static>> { let stdout = std::io::stdout().lock(); std::io::BufWriter::new(stdout) }
struct StdoutLogger {buf: std::io::BufWriter<std::io::StdoutLock<'static>>}impl StdoutLogger {fn log(&mut self, s: &str) {std::io::Write::write(&mut self.buf, s.as_bytes()).expect("error writing stdout");std::io::Write::write(&mut self.buf, "\n".as_bytes()).expect("error writing stdout");}}
macro_rules! init {($name: ident) => {let mut $name = StdoutLogger{buf:lock_stdout()};}}

use std::collections::VecDeque;

fn main() {
    init!(outp);

    let _n = read::<usize>();
    let inp = read_line();

    //let inp = "HTHTHTHHT";

    let cycle = inp.chars().collect::<VecDeque<_>>();

    let h_cnt = cycle.iter().filter(|&&ch| ch=='H').count();

    let mut t_cnt = i32::MAX;
    for i in 0..cycle.len() {
        let mut remain = h_cnt;
        let mut c = 0;
        for j in i..i+cycle.len() {
            if remain==0 {break}
            if cycle[j%cycle.len()]=='T' {c+=1};
            remain-=1;
        }
        if c<t_cnt {t_cnt=c}
    }

    outp.log(&format!("{t_cnt}"));

}

Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.

The first line contains number n (2≤n≤1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one.

Print the single number which is the minimal number of swaps that let the trainer to achieve his goal.

In the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7.

#![allow(non_snake_case)]
#[allow(dead_code)] fn read_line() -> String { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("failed to read line"); buffer.trim().to_string() }
#[allow(dead_code)] fn read<T : std::str::FromStr>() -> T where T::Err: std::fmt::Debug { read_line().trim().parse::<T>().expect("failed to read value") }
#[allow(dead_code)]fn read_vec<T : std::str::FromStr>() -> Vec<T> where T::Err: std::fmt::Debug { read_line().split_whitespace().map(|x| x.parse::<T>().expect("failed to read values")).collect() }
fn lock_stdout() -> std::io::BufWriter<std::io::StdoutLock<'static>> { let stdout = std::io::stdout().lock(); std::io::BufWriter::new(stdout) }
struct StdoutLogger {buf: std::io::BufWriter<std::io::StdoutLock<'static>>}impl StdoutLogger {fn log(&mut self, s: &str) {std::io::Write::write(&mut self.buf, s.as_bytes()).expect("error writing stdout");std::io::Write::write(&mut self.buf, "\n".as_bytes()).expect("error writing stdout");}}
macro_rules! init {($name: ident) => {let mut $name = StdoutLogger{buf:lock_stdout()};}}

use std::collections::VecDeque;

fn main() {
    init!(outp);

    let _n = read::<usize>();
    let inp = read_line();

    // let inp = "HTHTHTHHT";

    let cycle = inp.chars().collect::<VecDeque<_>>();

    let h_cnt = cycle.iter().filter(|&&ch| ch=='H').count();

    let mut t_cnt = i32::MAX;
    for i in 0..cycle.len() {
        let mut remain = h_cnt;
        let mut c = 0;
        for j in i..i+cycle.len() {
            if remain==0 {break}
            if cycle[j%cycle.len()]=='T' {c+=1};
            remain-=1;
        }
        if c<t_cnt {t_cnt=c}
    }

    outp.log(&format!("{t_cnt}"));

}

[{'input': ['3\r\nHTH\r\n'], 'output': ['0\r\n']}, {'input': ['9\r\nHTHTHTHHT\r\n'], 'output': ['2\r\n']}, {'input': ['2\r\nTH\r\n'], 'output': ['0\r\n']}, {'input': ['4\r\nHTTH\r\n'], 'output': ['0\r\n']}, {'input': ['4\r\nHTHT\r\n'], 'output': ['1\r\n']}, {'input': ['7\r\nTTTHTTT\r\n'], 'output': ['0\r\n']}, {'input': ['8\r\nHHTHHTHH\r\n'], 'output': ['1\r\n']}, {'input': ['13\r\nHTTTHHHTTTTHH\r\n'], 'output': ['3\r\n']}, {'input': ['20\r\nTTHTHTHHTHTTHHTTTHHH\r\n'], 'output': ['4\r\n']}, {'input': ['35\r\nTTTTTTHTTHTTTTTHTTTTTTTTTTTHTHTTTTT\r\n'], 'output': ['3\r\n']}, {'input': ['120\r\nTTTTTTTHTHTHTTTTTHTHTTTTHTTTTTTTTTTTTTTTTTTTTHTTHTTTTHTTHTTTTTTTTTTTTTTTHTTTTTTHTHTTHTTTTTTHTTTTTTTTTHTTHTTTTHTTTHTTTTTH\r\n'], 'output': ['14\r\n']}, {'input': ['19\r\nHHHHHHHHHHHHHTTTHHH\r\n'], 'output': ['0\r\n']}, {'input': ['87\r\nHTHHTTHHHHTHHHHHTTTHHTHHHHTTTTHHHTTHHTHTHTHHTTHTHHTHTHTTHHHTTTTTHTTHHHHHHTHHTHHTHTTHTHH\r\n'], 'output': ['17\r\n']}, {'input': ['178\r\nTHHHTHTTTHTTHTTHHHHHTTTHTTHHTHTTTHTHTTTTTHHHTHTHHHTHHHTTTTTTTTHHHHTTHHTHHHHTHTTTHHHHHHTHHTHTTHTHTTTTTTTTTHHTTHHTHTTHHTHHHHHTTHHTTHHTTHHHTTHHTTTTHTHHHTHTTHTHTTTHHHHTHHTHHHTHTTTTTT\r\n'], 'output': ['40\r\n']}]


fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let s: Vec<u32> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();

    let n = s[0];
    let m = s[1];

    let mut cols: Vec<u32> = [].to_vec();
    let mut rows: Vec<u32> = [].to_vec();
    let mut board: Vec<Vec<char>> = [].to_vec();

    for k in 0..n {
        let mut x = String::new();
        std::io::stdin().read_line(&mut x).unwrap();
        let x: Vec<char> = x.chars().collect::<Vec<char>>()[..m as usize].to_vec();
        board.push(x.clone());

        rows.push(0);

        for (i, &e) in x.iter().enumerate() {
            if e == '*' {
                rows[k as usize] += 1;
            }
            if k == 0 {
                cols.push(if e == '*' { 1 } else { 0 });
            }
            else {
                if e == '*' {
                    cols[i] += 1;
                }
            }
        }
    }

    let mut count = 0;

    for i in 0..n {
        for j in 0..m {
            if board[i as usize][j as usize] == '*' {
                count += (rows[i as usize] - 1) * (cols[j as usize] - 1);
            }
        }
    }

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

You are given a n×m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle).

The first line contains two positive integer numbers n and m (1≤n,m≤1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed.

Output a single number — total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

#[allow(dead_code)] fn read_line() -> String { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("failed to read line"); buffer.trim().to_string() }
#[allow(dead_code)] fn read<T : std::str::FromStr>() -> T where T::Err: std::fmt::Debug { read_line().trim().parse::<T>().expect("failed to read value") }
#[allow(dead_code)]fn read_vec<T : std::str::FromStr>() -> Vec<T> where T::Err: std::fmt::Debug { read_line().split_whitespace().map(|x| x.parse::<T>().expect("failed to read values")).collect() }
fn lock_stdout() -> std::io::BufWriter<std::io::StdoutLock<'static>> { let stdout = std::io::stdout().lock(); std::io::BufWriter::new(stdout) }
struct StdoutLogger {buf: std::io::BufWriter<std::io::StdoutLock<'static>>}impl StdoutLogger {fn log(&mut self, s: &str) {std::io::Write::write(&mut self.buf, s.as_bytes()).expect("error writing stdout");std::io::Write::write(&mut self.buf, "\n".as_bytes()).expect("error writing stdout");}}
macro_rules! init {($name: ident) => {let mut $name = StdoutLogger{buf:lock_stdout()};}}

fn main() {
    init!(outp);

    let line0 = read_vec::<usize>();
    let n = line0[0]; let m = line0[1];
    let mtx = (0..n).map(|_| read_line()).collect::<Vec<_>>();

    // let mtx = vec![
    //     "*..*",
    //     ".**.",
    //     "*.**",
    // ];

    // let mtx = vec![
    //     "..*..**..",
    //     "*.*...**.",
    //     ".*...*.*.",
    //     ".*****.*.",
    //     ".*.*.**.*",
    //     ".**.*....",
    //     "**.......",
    //     "**..*.*.*",
    //     "*.*.**.*.",
    //     "*.*.*.*.*",
    // ];

    let mtx = mtx.iter().map(|s| s.chars().collect::<Vec<_>>()).collect::<Vec<_>>();
    let row_c = mtx.len();
    let col_c = mtx[0].len();
    let mut rs = vec![0; row_c];
    let mut cs = vec![0; col_c];
    for r in 0..row_c {
        for c in 0..col_c {
            if mtx[r][c] == '*' {
                rs[r] += 1;
                cs[c] += 1;
            }
        }
    }
    let mut cnt: u128 = 0;
    for r in 0..row_c {
        for c in 0..col_c {
            if mtx[r][c] == '*' {
                cnt += (rs[r]-1)*(cs[c]-1);
            }
        }
    }

    println!("{cnt}");
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

// Mint (mod any) {{{
#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] struct Mint(i32,i32);
#[allow(dead_code)] impl Mint {
	fn new<T: Copy+Into<i64>>(a: T, m: T) -> Self { Self(Self::cv(a,m),m.into() as i32) }
	unsafe fn new_unchecked(a: i32, m: i32) -> Self { Self(a,m) }
	fn hi(mut a: i32, m: i32) -> i32 { if a >= m { a -= m; } a }
	fn lo(mut a: i32, m: i32) -> i32 { if a < 0 { a += m; } a }
	fn cv<T: Copy+Into<i64>>(a: T, m: T) -> i32 { Self::lo((a.into() % m.into()) as i32, m.into() as i32) }
	unsafe fn inv(self) -> Self { self.pow(self.1-2) } // ONLY FOR PRIMES!
	fn pow<T: Copy+Into<i64>>(self, b: T) -> Self {
		let b = b.into(); if b == 0 { Self(1,self.1) } else {
			let mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res
		}
	}
}
impl Add for Mint { type Output = Self; fn add(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::hi(self.0 + a.0, self.1), self.1) }}
impl Sub for Mint { type Output = Self; fn sub(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::lo(self.0 - a.0, self.1), self.1) }}
impl Mul for Mint { type Output = Self; fn mul(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::cv(self.0 as i64 * a.0 as i64, self.1 as i64), self.1) }}
impl Div for Mint { type Output = Self; fn div(self, a: Self) -> Self::Output { self * unsafe {a.inv()} }}
impl Neg for Mint { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0, self.1), self.1) }}
impl AddAssign for Mint { fn add_assign(&mut self, a: Self) { *self = *self + a; } }
impl SubAssign for Mint { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }
impl MulAssign for Mint { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }
impl DivAssign for Mint { fn div_assign(&mut self, a: Self) { *self = *self / a; } }
use std::fmt::{Display, Formatter, Result};
impl Display for Mint { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.0) } }
//}}}

// Square Matrix {{{
type MatT = Mint;
#[derive(Debug,Clone)] struct Mat { n: usize, a: Vec<MatT>, v0: MatT, v1: MatT }
#[allow(dead_code)] impl Mat {
	fn new(n:usize,v0:MatT,v1:MatT)->Self{Self{n,a:vec![v0;n*n],v0,v1}}
	fn diag(n:usize,v0:MatT,v1:MatT,v:MatT)->Self{let mut m=Self::new(n,v0,v1);let mut p=0;for _ in 0..n{m.a[p]=v;p+=n+1;}m}
	fn pow(&self,n:u64)->Self{if n==0{Self::diag(self.n,self.v0,self.v1,self.v1)}else{let mut t=self.pow(n/2);t*=t.clone();if n%2==1{t*=self.clone();}t}}
	fn range(&self,r:Range<usize>,c:Range<usize>)->Vec<Vec<MatT>>{if r.start<r.end||c.start<c.end{Vec::new()}else{let mut res=vec![vec![self.v0;c.end-c.start];r.end-r.start];
		for i in r.start..r.end{let ir=i-r.start;let ii=i*self.n+c.start;for j in 0..c.end-c.start{res[ir][j]=self.a[ii+j];}}res}}
	fn at(&self,r:usize,c:usize)->MatT{self.a[r*self.n+c]}
	fn at_mut<'a>(&'a mut self,r:usize,c:usize)->&'a mut MatT{&mut self.a[r*self.n+c]}//'
}
impl Mul for Mat{type Output=Self;fn mul(self,o:Self)->Self::Output{assert!(self.n==o.n);let n=self.n;let mut res=Self::new(n,self.v0,self.v1);
	for ii in(0..n).map(|i|i*n){for j in 0..n{let mut t=self.v0;let mut kk=j;for k in 0..n{t+=self.a[ii+k]*o.a[kk];kk+=n;}res.a[ii+j]=t;}}res}}
impl Add for Mat{type Output=Self;fn add(mut self,o:Self)->Self{self+=o;self}}
impl Sub for Mat{type Output=Self;fn sub(mut self,o:Self)->Self{self-=o;self}}
impl MulAssign for Mat{fn mul_assign(&mut self,a:Self){*self=self.clone()*a;}}
impl AddAssign for Mat{fn add_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x+=y;}} }
impl SubAssign for Mat{fn sub_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x-=y;}} }
impl PartialEq for Mat{fn eq(&self,o:&Self)->bool{self.n==o.n&&self.a==o.a}}impl Eq for Mat{}
// }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	l!(m,l,r,k = rin.l());
	let g = || -> i64 {
		for d in (1..(r-l)/(k-1)).rev() {
			if r / d - (l-1) / d >= k {
				return d;
			}
		}
		panic!("no")
	}();
	let f1 = Mint::new(1,m);
	let f0 = Mint::new(0,m);
	let mut mat = Mat::new(2,f0,f1);
	*mat.at_mut(0,0) = f0;
	*mat.at_mut(0,1) = f1;
	*mat.at_mut(1,0) = f1;
	*mat.at_mut(1,1) = f1;
	let sol = mat.pow(g as u64).at(0,1);
	writeln!(rout, "{}", sol).ok();
}

There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, l + 1, l + 2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1 = 1, F2 = 1, Fn = Fn - 1 + Fn - 2 for n ≥ 3.Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m.

The first line contains four space-separated integers m, l, r and k (1 ≤ m ≤ 109; 1 ≤ l < r ≤ 1012; 2 ≤ k ≤ r - l + 1). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the residue from dividing the sought greatest common divisor by m.

//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

// Mint (mod any) {{{
#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] struct Mint(i32,i32);
#[allow(dead_code)] impl Mint {
	fn new<T: Copy+Into<i64>>(a: T, m: T) -> Self { Self(Self::cv(a,m),m.into() as i32) }
	unsafe fn new_unchecked(a: i32, m: i32) -> Self { Self(a,m) }
	fn hi(mut a: i32, m: i32) -> i32 { if a >= m { a -= m; } a }
	fn lo(mut a: i32, m: i32) -> i32 { if a < 0 { a += m; } a }
	fn cv<T: Copy+Into<i64>>(a: T, m: T) -> i32 { Self::lo((a.into() % m.into()) as i32, m.into() as i32) }
	unsafe fn inv(self) -> Self { self.pow(self.1-2) } // ONLY FOR PRIMES!
	fn pow<T: Copy+Into<i64>>(self, b: T) -> Self {
		let b = b.into(); if b == 0 { Self(1,self.1) } else {
			let mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res
		}
	}
}
impl Add for Mint { type Output = Self; fn add(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::hi(self.0 + a.0, self.1), self.1) }}
impl Sub for Mint { type Output = Self; fn sub(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::lo(self.0 - a.0, self.1), self.1) }}
impl Mul for Mint { type Output = Self; fn mul(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::cv(self.0 as i64 * a.0 as i64, self.1 as i64), self.1) }}
impl Div for Mint { type Output = Self; fn div(self, a: Self) -> Self::Output { self * unsafe {a.inv()} }}
impl Neg for Mint { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0, self.1), self.1) }}
impl AddAssign for Mint { fn add_assign(&mut self, a: Self) { *self = *self + a; } }
impl SubAssign for Mint { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }
impl MulAssign for Mint { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }
impl DivAssign for Mint { fn div_assign(&mut self, a: Self) { *self = *self / a; } }
use std::fmt::{Display, Formatter, Result};
impl Display for Mint { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.0) } }
//}}}

// Square Matrix {{{
type MatT = Mint;
#[derive(Debug,Clone)] struct Mat { n: usize, a: Vec<MatT>, v0: MatT, v1: MatT }
#[allow(dead_code)] impl Mat {
	fn new(n:usize,v0:MatT,v1:MatT)->Self{Self{n,a:vec![v0;n*n],v0,v1}}
	fn diag(n:usize,v0:MatT,v1:MatT,v:MatT)->Self{let mut m=Self::new(n,v0,v1);let mut p=0;for _ in 0..n{m.a[p]=v;p+=n+1;}m}
	fn pow(&self,n:u64)->Self{if n==0{Self::diag(self.n,self.v0,self.v1,self.v1)}else{let mut t=self.pow(n/2);t*=t.clone();if n%2==1{t*=self.clone();}t}}
	fn range(&self,r:Range<usize>,c:Range<usize>)->Vec<Vec<MatT>>{if r.start<r.end||c.start<c.end{Vec::new()}else{let mut res=vec![vec![self.v0;c.end-c.start];r.end-r.start];
		for i in r.start..r.end{let ir=i-r.start;let ii=i*self.n+c.start;for j in 0..c.end-c.start{res[ir][j]=self.a[ii+j];}}res}}
	fn at(&self,r:usize,c:usize)->MatT{self.a[r*self.n+c]}
	fn at_mut<'a>(&'a mut self,r:usize,c:usize)->&'a mut MatT{&mut self.a[r*self.n+c]}//'
}
impl Mul for Mat{type Output=Self;fn mul(self,o:Self)->Self::Output{assert!(self.n==o.n);let n=self.n;let mut res=Self::new(n,self.v0,self.v1);
	for ii in(0..n).map(|i|i*n){for j in 0..n{let mut t=self.v0;let mut kk=j;for k in 0..n{t+=self.a[ii+k]*o.a[kk];kk+=n;}res.a[ii+j]=t;}}res}}
impl Add for Mat{type Output=Self;fn add(mut self,o:Self)->Self{self+=o;self}}
impl Sub for Mat{type Output=Self;fn sub(mut self,o:Self)->Self{self-=o;self}}
impl MulAssign for Mat{fn mul_assign(&mut self,a:Self){*self=self.clone()*a;}}
impl AddAssign for Mat{fn add_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x+=y;}} }
impl SubAssign for Mat{fn sub_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x-=y;}} }
impl PartialEq for Mat{fn eq(&self,o:&Self)->bool{self.n==o.n&&self.a==o.a}}impl Eq for Mat{}
// }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();

	l!(m,l,r,k = rin.l());
	if m == 1 {
		writeln!(rout, "0").ok();
		return;
	}
	let g = || -> i64 {
		let mut a = Vec::new();
		for d in 1.. {
			if d*d > r { break; }
			a.push(d);
			a.push(r/d);
			a.push(l/d);
		}
		a.sort();
		a.dedup();
		a.reverse();
		for d in a {
			if r / d - (l-1) / d >= k {
				return d;
			}
		}
		panic!("no")
	}();
	let f1 = Mint::new(1,m);
	let f0 = Mint::new(0,m);
	let mut mat = Mat::new(2,f0,f1);
	*mat.at_mut(0,0) = f0;
	*mat.at_mut(0,1) = f1;
	*mat.at_mut(1,0) = f1;
	*mat.at_mut(1,1) = f1;
	let sol = mat.pow(g as u64).at(0,1);
	writeln!(rout, "{}", sol).ok();
}


fn main() {
    let input = "3 50\n4 2 1\n";
    let mut lines = input.lines();
    let nk: Vec<i32> = lines
        .next()
        .unwrap()
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let n = nk[0];
    let k = nk[1];
    let a: Vec<i32> = lines
        .next()
        .unwrap()
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let mut min_energy = i32::MAX;
    for i in 0..n {
        min_energy = min_energy.min(a[i]);
    }
    let mut max_energy = i32::MIN;
    for i in 0..n {
        max_energy = max_energy.max(a[i]);
    }
    let mut low = min_energy as f64;
    let mut high = max_energy as f64;
    while high - low > 1e-6 {
        let mid = (low + high) / 2.0;
        let mut total_loss = 0.0;
        for i in 0..n {
            if a[i] > mid as i32 {
                total_loss += (a[i] - mid as i32) as f64 * (k as f64 / 100.0);
            }
            else {
                total_loss -= (mid as i32 - a[i]) as f64 * (k as f64 / 100.0);
            }
        }
        if total_loss > 0.0 {
            low = mid;
        }
        else {
            high = mid;
        }
    }
    println!("{:.9}", low);
}

It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by  units.Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.

First line of the input contains two integers n and k (1≤n≤10000,0≤k≤99) — number of accumulators and the percent of energy that is lost during transfers.
Next line contains n integers a1,a2,... ,an — amounts of energy in the first, second, .., n-th accumulator respectively (0≤ai≤1000,1≤i≤n).

Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy.
The absolute or relative error in the answer should not exceed 10^-6.

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

fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();

    let mut lines = input.lines();
    let params: Vec<usize> = lines.next().unwrap().split_whitespace().map(|x| x.parse().unwrap()).collect();
    let n = params[0];
    let k = params[1];

    let energy: Vec<f64> = lines.next().unwrap().split_whitespace().map(|x| x.parse().unwrap()).collect();

    let mut low = 0.0;
    let mut high = 1000.0;

    for _ in 0..100 {
        let mid = (low + high) / 2.0;
        let mut total_loss = 0.0;

        for i in 0..n {
            if energy[i] > mid {
                total_loss += (energy[i] - mid) * (1.0 - (k as f64) / 100.0);
            } else {
                total_loss -= (mid - energy[i]);
            }
        }

        if total_loss > 0.0 {
            low = mid;
        } else {
            high = mid;
        }
    }

    println!("{:.9}", low);
}


// ---------- begin SegmentTree Point update Range query ----------
mod segment_tree {
    pub struct PURQ<T: Clone, F: Fn(T, T) -> T> {
        n: usize,
        a: Vec<T>,
        id: T,
        op: F,
    }
    #[allow(dead_code)]
    impl<T: Clone, F: Fn(T, T) -> T> PURQ<T, F> {
        pub fn new(n: usize, id: T, op: F) -> PURQ<T, F> {
            let mut k = 1;
            while k < n {
                k *= 2;
            }
            PURQ {
                n: k,
                a: vec![id.clone(); 2 * k],
                id: id,
                op: op,
            }
        }
        pub fn update(&mut self, x: usize, v: T) {
            let mut k = self.n + x;
            let a = &mut self.a;
            a[k] = v;
            k >>= 1;
            while k > 0 {
                a[k] = (self.op)(a[2 * k].clone(), a[2 * k + 1].clone());
                k >>= 1;
            }
        }
        pub fn update_tmp(&mut self, x: usize, v: T) {
            self.a[x + self.n] = v;
        }
        pub fn update_all(&mut self) {
            for k in (1..(self.n)).rev() {
                self.a[k] = (self.op)(self.a[2 * k].clone(), self.a[2 * k + 1].clone());
            }
        }
        pub fn find(&self, mut l: usize, mut r: usize) -> T {
            let mut p = self.id.clone();
            let mut q = self.id.clone();
            l += self.n;
            r += self.n;
            while l < r {
                if (l & 1) == 1 {
                    p = (self.op)(p, self.a[l].clone());
                    l += 1;
                }
                if (r & 1) == 1 {
                    r -= 1;
                    q = (self.op)(self.a[r].clone(), q);
                }
                l >>= 1;
                r >>= 1;
            }
            (self.op)(p, q)
        }
    }
}
// ---------- end SegmentTree Point update Range query ----------

const MOD: u64 = (1u64 << 61) - 1;

#[derive(Clone, Copy, PartialEq, Eq)]
struct ModInt(u64);

impl std::ops::Add for ModInt {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        assert!(self.0 < MOD && rhs.0 < MOD);
        let mut d = self.0 + rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::Sub for ModInt {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        assert!(self.0 < MOD && rhs.0 < MOD);
        let mut d = self.0 + MOD - rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::Mul for ModInt {
    type Output = Self;
    fn mul(self, rhs: Self) -> Self::Output {
        assert!(self.0 < MOD && rhs.0 < MOD);
        const MASK31: u64 = (1u64 << 31) - 1;
        const MASK30: u64 = (1u64 << 30) - 1;
        let au = self.0 >> 31;
        let ad = self.0 & MASK31;
        let bu = rhs.0 >> 31;
        let bd = rhs.0 & MASK31;
        let mid = ad * bu + au * bd;
        let midu = mid >> 30;
        let midd = mid & MASK30;
        let sum = au * bu * 2 + midu + (midd << 31) + ad * bd;
        let mut ans = (sum >> 61) + (sum & MOD);
        if ans >= MOD {
            ans -= MOD;
        }
        ModInt(ans)
    }
}

impl ModInt {
    fn new(v: u64) -> Self {
        ModInt(v % MOD)
    }
    fn zero() -> Self {
        ModInt(0)
    }
    fn pow(&self, n: u64) -> Self {
        let mut t = ModInt(1);
        let mut s = *self;
        let mut n = n;
        while n > 0 {
            if n & 1 == 1 {
                t = t * s;
            }
            s = s * s;
            n >>= 1;
        }
        t
    }
    fn inv(&self) -> Self {
        assert!(self.0 > 0);
        self.pow(MOD - 2)
    }
}

pub const BASE_NUM: usize = 2;

#[derive(Clone, PartialEq, Eq)]
pub struct ModVector {
    val: [ModInt; BASE_NUM],
}

impl ModVector {
    pub fn zero() -> Self {
        ModVector {
            val: [ModInt::zero(); BASE_NUM],
        }
    }
    pub fn new(v: &[u64]) -> Self {
        assert!(v.len() >= BASE_NUM);
        let mut ans = ModVector::zero();
        for (x, a) in ans.val.iter_mut().zip(v.iter()) {
            *x = ModInt::new(*a);
        }
        ans
    }
    pub fn one(v: u64) -> Self {
        ModVector::new(&[v; BASE_NUM])
    }
    pub fn add(&self, rhs: &Self) -> Self {
        let mut ans = ModVector::zero();
        for (c, (a, b)) in ans.val.iter_mut().zip(self.val.iter().zip(rhs.val.iter())) {
            *c = *a + *b;
        }
        ans
    }
    pub fn sub(&self, rhs: &Self) -> Self {
        let mut ans = ModVector::zero();
        for (c, (a, b)) in ans.val.iter_mut().zip(self.val.iter().zip(rhs.val.iter())) {
            *c = *a - *b;
        }
        ans
    }
    pub fn mul(&self, rhs: &Self) -> Self {
        let mut ans = ModVector::zero();
        for (c, (a, b)) in ans.val.iter_mut().zip(self.val.iter().zip(rhs.val.iter())) {
            *c = *a * *b;
        }
        ans
    }
    pub fn inv(&self) -> Self {
        let mut ans = ModVector::zero();
        for (x, a) in ans.val.iter_mut().zip(self.val.iter()) {
            *x = a.inv();
        }
        ans
    }
}

pub fn rand_time() -> u32 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap().subsec_nanos()
}

pub fn rand_memory() -> u32 {
    Box::into_raw(Box::new("I hope this is a random number")) as u32
}

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

fn run() {
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut it = s.trim().split_whitespace();
    let n: usize = it.next().unwrap().parse().unwrap();
    let t: Vec<u32> = it.next().unwrap().chars().map(|c| c.to_digit(10).unwrap()).collect();
    let rad = ModVector::new(&vec![rand_time() as u64, rand_memory() as u64]);
    let inv = rad.inv();
    let mut pow = vec![ModVector::new(&[1, 1])];
    for _ in 0..n {
        let v = pow.last().unwrap().mul(&rad);
        pow.push(v);
    }
    type T = (ModVector, usize, bool, bool);
    let fold = |a: T, b: T| -> T {
        if a.1 == 0 {
            return b;
        }
        if b.1 == 0 {
            return a;
        }
        if a.3 && b.2 {
            let mut val = a.0.sub(&ModVector::one(2).mul(&pow[a.1 - 1]));
            val = val.add(&pow[a.1 - 1].mul(&inv.mul(&b.0.sub(&ModVector::one(2)))));
            let len = a.1 + b.1 - 2;
            match (a.1 == 1, b.1 == 1) {
                (true, true) => (val, len, false, false),
                (true, false) => (val, len, a.2, false),
                (false, true) => (val, len, false, b.3),
                (false, false) => (val, len, a.2, b.3),
            }
        } else {
            let val = a.0.add(&b.0.mul(&pow[a.1]));
            let len = a.1 + b.1;
            (val, len, a.2, b.3)
        }
    };
    let mut seg = segment_tree::PURQ::new(n, (ModVector::zero(), 0, false, false), fold);
    for (i, &c) in t.iter().enumerate() {
        if c == 1 {
            seg.update_tmp(i, (ModVector::one(2), 1, true, true));
        } else {
            seg.update_tmp(i, (ModVector::one(1), 1, false, false));
        }
    }
    seg.update_all();
    let q: usize = it.next().unwrap().parse().unwrap();
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    for _ in 0..q {
        let a: usize = it.next().unwrap().parse().unwrap();
        let b: usize = it.next().unwrap().parse().unwrap();
        let len: usize = it.next().unwrap().parse().unwrap();
        let ans = if seg.find(a - 1, a - 1 + len) == seg.find(b - 1, b - 1 + len) {
            "Yes"
        } else {
            "No"
        };
        writeln!(out, "{}", ans).ok();
    }
}

fn main() {
    run();
}

In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $$$s$$$ starting from the $$$l$$$-th character and ending with the $$$r$$$-th character as $$$s[l \dots r]$$$. The characters of each string are numbered from $$$1$$$.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string $$$a$$$ is considered reachable from binary string $$$b$$$ if there exists a sequence $$$s_1$$$, $$$s_2$$$, ..., $$$s_k$$$ such that $$$s_1 = a$$$, $$$s_k = b$$$, and for every $$$i \in [1, k - 1]$$$, $$$s_i$$$ can be transformed into $$$s_{i + 1}$$$ using exactly one operation. Note that $$$k$$$ can be equal to $$$1$$$, i. e., every string is reachable from itself.You are given a string $$$t$$$ and $$$q$$$ queries to it. Each query consists of three integers $$$l_1$$$, $$$l_2$$$ and $$$len$$$. To answer each query, you have to determine whether $$$t[l_1 \dots l_1 + len - 1]$$$ is reachable from $$$t[l_2 \dots l_2 + len - 1]$$$.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of string $$$t$$$. The second line contains one string $$$t$$$ ($$$|t| = n$$$). Each character of $$$t$$$ is either 0 or 1. The third line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, each line represents a query. The $$$i$$$-th line contains three integers $$$l_1$$$, $$$l_2$$$ and $$$len$$$ ($$$1 \le l_1, l_2 \le |t|$$$, $$$1 \le len \le |t| - \max(l_1, l_2) + 1$$$) for the $$$i$$$-th query.

For each query, print either YES if $$$t[l_1 \dots l_1 + len - 1]$$$ is reachable from $$$t[l_2 \dots l_2 + len - 1]$$$, or NO otherwise. You may print each letter in any register.

// ---------- begin SegmentTree Point update Range query ----------
mod segment_tree {
    pub struct PURQ<T: Clone, F: Fn(T, T) -> T> {
        n: usize,
        a: Vec<T>,
        id: T,
        op: F,
    }
    #[allow(dead_code)]
    impl<T: Clone, F: Fn(T, T) -> T> PURQ<T, F> {
        pub fn new(n: usize, id: T, op: F) -> PURQ<T, F> {
            let mut k = 1;
            while k < n {
                k *= 2;
            }
            PURQ {
                n: k,
                a: vec![id.clone(); 2 * k],
                id: id,
                op: op,
            }
        }
        pub fn update(&mut self, x: usize, v: T) {
            let mut k = self.n + x;
            let a = &mut self.a;
            a[k] = v;
            k >>= 1;
            while k > 0 {
                a[k] = (self.op)(a[2 * k].clone(), a[2 * k + 1].clone());
                k >>= 1;
            }
        }
        pub fn update_tmp(&mut self, x: usize, v: T) {
            self.a[x + self.n] = v;
        }
        pub fn update_all(&mut self) {
            for k in (1..(self.n)).rev() {
                self.a[k] = (self.op)(self.a[2 * k].clone(), self.a[2 * k + 1].clone());
            }
        }
        pub fn find(&self, mut l: usize, mut r: usize) -> T {
            let mut p = self.id.clone();
            let mut q = self.id.clone();
            l += self.n;
            r += self.n;
            while l < r {
                if (l & 1) == 1 {
                    p = (self.op)(p, self.a[l].clone());
                    l += 1;
                }
                if (r & 1) == 1 {
                    r -= 1;
                    q = (self.op)(self.a[r].clone(), q);
                }
                l >>= 1;
                r >>= 1;
            }
            (self.op)(p, q)
        }
    }
}
// ---------- end SegmentTree Point update Range query ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

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

// ここまで

use std::io::Write;

fn mod_pow(r: u128, mut n: u128, p: u128) -> u128 {
    let mut t = 1;
    let mut s = r;
    while n > 0 {
        if n & 1 == 1 {
            t = t * s % p;
        }
        s = s * s % p;
        n >>= 1;
    }
    t
}

fn run() {
    input! {
        n: usize,
        s: chars,
        q: usize,
        ask: [(usize1, usize1, usize); q],
    }
    const MOD: u128 = 4611686018427194327;
    let rad = 3;
    let mut pow = vec![1; n + 1];
    for i in 1..=n {
        pow[i] = pow[i - 1] * rad % MOD;
    }
    let inv = mod_pow(rad, MOD - 2, MOD);
    type T = (u128, usize, bool, bool);// ハッシュ、長さ、先頭1, 最後1
    let fold = |a: T, b: T| -> T {
        if a.1 == 0 {
            return b;
        }
        if b.1 == 0 {
            return a;
        }
        if a.3 && b.2 {
            let mut val = a.0;
            val = (val + MOD - 2 * pow[a.1 - 1] % MOD) % MOD;
            val = (val + pow[a.1 - 1] * (b.0 + MOD - 2) % MOD * inv % MOD) % MOD;
            let len = a.1 + b.1 - 2;
            return match (a.1 == 1, b.1 == 1) {
                (true, true) => (0, 0, false, false),
                (true, false) => (val, len, false, b.3),
                (false, true) => (val, len, a.2, false),
                (false, false) => (val, len, a.2, b.3),
            };
        }
        let val = (a.0 + pow[a.1] * b.0 % MOD) % MOD;
        let len = a.1 + b.1;
        (val, len, a.2, b.3)
    };
    let mut seg = segment_tree::PURQ::new(n, (0, 0, false, false), fold);
    for i in 0..n {
        if s[i] == '1' {
            seg.update_tmp(i, (2, 1, true, true));
        } else {
            seg.update_tmp(i, (1, 1, false, false));
        }
    }
    seg.update_all();
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    for (x, y, len) in ask {
        let p = seg.find(x, x + len);
        let q = seg.find(y, y + len);
        if p.0 == q.0 && p.1 == q.1 {
            writeln!(out, "Yes").ok();
        } else {
            writeln!(out, "No").ok();
        }
    }

}

fn main() {
    run();
}


#![allow(non_snake_case)]
#[allow(dead_code)] fn read_line() -> String { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("failed to read line"); buffer.trim().to_string() }
#[allow(dead_code)] fn read<T : std::str::FromStr>() -> T where T::Err: std::fmt::Debug { read_line().trim().parse::<T>().expect("failed to read value") }
#[allow(dead_code)]fn read_vec<T : std::str::FromStr>() -> Vec<T> where T::Err: std::fmt::Debug { read_line().split_whitespace().map(|x| x.parse::<T>().expect("failed to read values")).collect() }
#[allow(dead_code)] fn lock_stdout() -> std::io::BufWriter<std::io::StdoutLock<'static>> { let stdout = std::io::stdout().lock(); std::io::BufWriter::new(stdout) }
#[allow(dead_code)] struct StdoutLogger {buf: std::io::BufWriter<std::io::StdoutLock<'static>>}impl StdoutLogger {fn log(&mut self, s: &str) {std::io::Write::write(&mut self.buf, s.as_bytes()).expect("error writing stdout");std::io::Write::write(&mut self.buf, "\n".as_bytes()).expect("error writing stdout");}}
#[allow(dead_code)] macro_rules! init {($name: ident) => {#[allow(unused_mut)]let mut $name = StdoutLogger{buf:lock_stdout()};}}

fn main() {
    init!(outp);

    let n = read::<usize>();
    let inp = read_line();

    // let n = 2;
    // let inp = "How are you?";

    // let n = 25;
    // let inp = "Hello! Do you like fish? Why?";

    let sntncs = inp.split(['.', '?', '!']);
    let mut cnt = 1;
    let mut sntnc_c = 0;
    let mut p = 0;
    for sntnc in sntncs {
        if sntnc.len()==0 {continue};
        // println!("sntnc:{sntnc} len:{}", sntnc.len());
        if p+sntnc.len()+1<=n {
            sntnc_c += 1;
            // println!("+{}", &inp[p..p+sntnc.len()+1]);
            p += sntnc.len()+1;
        } else {
            if sntnc_c==0 {
                println!("Impossible");
                return;
            }
            // println!("|{}", &inp[p..p+sntnc.len()+1]);
            p += sntnc.len()+1;
            cnt += 1;
        }
    }
    println!("{cnt}");

}

Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?

The first line contains an integer n, which is the size of one message (2≤n≤255). The second line contains the text. The length of the text does not exceed 10^4 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.

On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.

Let's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".

#![allow(non_snake_case)]
#[allow(dead_code)] fn read_line() -> String { let mut buffer = String::new(); std::io::stdin().read_line(&mut buffer).expect("failed to read line"); buffer.trim().to_string() }
#[allow(dead_code)] fn read<T : std::str::FromStr>() -> T where T::Err: std::fmt::Debug { read_line().trim().parse::<T>().expect("failed to read value") }
#[allow(dead_code)]fn read_vec<T : std::str::FromStr>() -> Vec<T> where T::Err: std::fmt::Debug { read_line().split_whitespace().map(|x| x.parse::<T>().expect("failed to read values")).collect() }
#[allow(dead_code)] fn lock_stdout() -> std::io::BufWriter<std::io::StdoutLock<'static>> { let stdout = std::io::stdout().lock(); std::io::BufWriter::new(stdout) }
#[allow(dead_code)] struct StdoutLogger {buf: std::io::BufWriter<std::io::StdoutLock<'static>>}impl StdoutLogger {fn log(&mut self, s: &str) {std::io::Write::write(&mut self.buf, s.as_bytes()).expect("error writing stdout");std::io::Write::write(&mut self.buf, "\n".as_bytes()).expect("error writing stdout");}}
#[allow(dead_code)] macro_rules! init {($name: ident) => {#[allow(unused_mut)]let mut $name = StdoutLogger{buf:lock_stdout()};}}

fn main() {
    init!(outp);

    let n = read::<usize>();
    let inp = read_line();

    // let n = 4;
    // let inp = "ab. b. de.";

    // let n = 146;
    // let inp = "iIQVkDsPqzAJyBrtHk EhBSN gzDoigItCMzETerb cIbXhTPbKYMdMoYqyFTEN. qcrrseVwmaZEiQUQoGT SUyErST lJDejKkjqTdoUrHR tsZYDyI? pmuNNHYqQUISxdZfWOB XdEECvNz hnNmVfODaIC qjhRIEPAlEsQBxo apZ! gCpqoiUFIwWLBOmYubywj qJojFVhLd dCpovICpXHfgihydEOoij?";

    // let n = 2;
    // let inp = "How are you?";

    // let n = 19;
    // let inp = "Hello! Do you like fish? Why?";

    let sntncs = inp.split(['.', '?', '!']);
    let mut cnt = 1;
    let mut sntnc_c = 0;
    let mut p = 0;
    let mut i = 0;
    for sntnc in sntncs {
        if sntnc.len()==0 {continue};
        let sntnc = sntnc.trim();

        let sntnc_len = sntnc.len()+1; //+1 for .,?,!
        let spaced_sntnc_len = sntnc_len + if i==0{0}else{1};
        if sntnc_len > n {
            println!("Impossible");
            return;
        }

        //println!("sntnc:{sntnc} len:{}", sntnc.len());
        if p+spaced_sntnc_len<=n {
            // println!("spaced_sntnc_len {}", spaced_sntnc_len);
            sntnc_c += 1;
            p += spaced_sntnc_len;
        } else {
            if sntnc_c==0 {
                println!("Impossible");
                return;
            }
            p = sntnc_len;
            cnt += 1;
        }

        i+=1;
    }
    println!("{cnt}");

}

[{'input': ['25\r\nHello. I am a little walrus.\r\n'], 'output': ['2\r\n']}, {'input': ['2\r\nHow are you?\r\n'], 'output': ['Impossible\r\n']}, {'input': ['19\r\nHello! Do you like fish? Why?\r\n'], 'output': ['3\r\n']}, {'input': ['4\r\na. A.\r\n'], 'output': ['2\r\n']}, {'input': ['191\r\nEvx vnxZtUSgtzH yDNXCsTaxCKQus gVZLHppOplkGGekIK xbme. krbusMqUs YEnBBTJpjNicZPlx TqEtBPcbejZMzvn fFTub CHYWLmiOFkDdzR! LoQmXPfHJ KVnfrbrFooVSkj xwAZwrRr DdILZ kpco cLoRmJbVKhnbOEhnHKpci. PgYhxFPXdlvlrp mDLZBnVRf AgRMUjxepFuLyKlIAhLS wtmEiLDNUAHpZEsKnkOu!\r\n'], 'output': ['2\r\n']}, {'input': ['146\r\niIQVkDsPqzAJyBrtHk EhBSN gzDoigItCMzETerb cIbXhTPbKYMdMoYqyFTEN. qcrrseVwmaZEiQUQoGT SUyErST lJDejKkjqTdoUrHR tsZYDyI? pmuNNHYqQUISxdZfWOB XdEECvNz hnNmVfODaIC qjhRIEPAlEsQBxo apZ! gCpqoiUFIwWLBOmYubywj qJojFVhLd dCpovICpXHfgihydEOoij?\r\n'], 'output': ['2\r\n']}, {'input': ['151\r\nayDIuxJXWNqu OImqJLodviANkQNxZ OpDpwyoPQdZyosXJpqRx! ZFQNQJPnoEVUEEbjqs iyfUYK HuGCOtlsEllsCiHIdEuW ZmlRSWVOmLAD MSYsC? CGKxobjmddejDDdF qbQsAWi qxViwV iLmPHfhLjP ZfNCItjZikwaQyhQGC? bvSaaZhwHdbNKSiiI bEJXRjANEasfrElNHPA UuQCajtuODHgxwgL qbssJss TqT.\r\n'], 'output': ['2\r\n']}, {'input': ['123\r\nOjg CVJm qfE RnHislFds nNKKt TCPLWukqNGAsVBplYbTfq? VeYKjfFGTzXWA ydpVZLIImNub yApKnAHv iXQmqv GjQvxrnAgtfTApiQyCKtg. GdmapGwvI udRqxTbnzgnOUNZx slAuEuLGCJycZJvtCczQ vommS xuuT eIK! DOJeFEaubbz HYLGlIIlNKfyaJQKVN eFNnUvKKCQLXvGhwX gjmRscMkedELUlHq? aTbyMGB EofzX wcAEjyRQpxghWvXhdJb cwIz FEUsEFicYZ.\r\n'], 'output': ['3\r\n']}, {'input': ['126\r\ntjQvloOnRednqfvIRudX wAPhGdwEZ BiuuuAW EfSzDuRTdC rptjpHnxyM? FkLaTBruN IwuIQMdpdUpn etTVVJUsKztaR YNY EAENiDgJwYXDDrayjyuKp! yKqRNHznLRpnTqjisR LuapWDnWmwYDE NcClOZBNzMYrpa? SEZdSZIgBekpCPvyEiO AMjztArkFRJuS ilycvolFExqxrXJK. sLvBUxjIOomxUqYd jZsOXWN iBtqSykbeUbAsQgRVs DinPLrpzt.\r\n'], 'output': ['3\r\n']}, {'input': ['118\r\ngweVo bjbEKaZQw PpSi AWOYt sQSvAHNRswh vUaGuLbtExNECz! USsQxMCjaGOmUESwHvyY SshkERibaWkmNLSZOtWZy FFTUWQgekPRjLRetAdSFt! sIhcimZTisFvndrYioLF HetLn wjoaDUKfbkagupl QdYb fFiV GNqBygStKQw. XLiYZEOGnTLSHmCwktEr pVBePMoRGopNt LdEujxuxzmlbycQdR?\r\n'], 'output': ['4\r\n']}, {'input': ['16\r\nAbacaba. Abacaba. abacaba. abacab.\r\n'], 'output': ['3\r\n']}, {'input': ['21\r\nHello. I am a little walrus.\r\n'], 'output': ['2\r\n']}, {'input': ['16\r\nAbacaba. Abacab. abacaba. abacaba.\r\n'], 'output': ['3\r\n']}, {'input': ['10\r\nhello! how are you?\r\n'], 'output': ['Impossible\r\n']}, {'input': ['5\r\nabc. abcd.\r\n'], 'output': ['2\r\n']}, {'input': ['16\r\nabacaba. abacab. Abacaba. Abacaba.\r\n'], 'output': ['3\r\n']}, {'input': ['5\r\na. b. c. d.\r\n'], 'output': ['2\r\n']}, {'input': ['8\r\nabc! ab.\r\n'], 'output': ['1\r\n']}, {'input': ['2\r\na. b.\r\n'], 'output': ['2\r\n']}]


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

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

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

fn run() {
    input! {
        m: u64,
        xaniar: (usize, usize, u64, u64),
        abol: (usize, usize, u64, u64),
    }
    let cond = |b: bool| {
        if !b {
            println!("-1");
            std::process::exit(0);
        }
    };
    let next = |h: usize| -> usize {
        let x = xaniar.2;
        let y = xaniar.3;
        ((h as u64 * x + y) % m) as usize
    };
    let mut time = vec![None; m as usize];
    let mut p = xaniar.0;
    time[p] = Some(0);
    let mut k = 1;
    p = next(p);
    while time[p].is_none() {
        time[p] = Some(k);
        k += 1;
        p = next(p);
    }
    let step = k - time[p].unwrap();
    let a = xaniar.1;
    cond(time[a].is_some());
    if time[a].unwrap() < time[p].unwrap() {
        let next = |h: usize| -> usize {
            let x = abol.2;
            let y = abol.3;
            ((h as u64 * x + y) % m) as usize
        };
        let t = time[a].unwrap();
        let mut p = abol.0;
        for _ in 0..t {
            p = next(p);
        }
        cond(p == abol.1);
        println!("{}", t);
        return;
    }
    let t = time[a].unwrap();
    let mut abol = abol;
    for _ in 0..t {
        abol.0 = {
            let x = abol.2;
            let y = abol.3;
            ((abol.0 as u64 * x + y) % m) as usize
        };
    }
    let mut mat = (1, 0);
    for _ in 0..step {
        mat = (mat.0 * abol.2 % m, (mat.1 * abol.2 + abol.3) % m);
    }
    abol.2 = mat.0;
    abol.3 = mat.1;
    let mut time = vec![None; m as usize];
    let next = |h: usize| -> usize {
        let x = abol.2;
        let y = abol.3;
        ((h as u64 * x + y) % m) as usize
    };
    let mut p = abol.0;
    time[abol.0] = Some(0);
    p = next(p);
    let mut k = 1;
    while time[p].is_some() {
        time[p] = Some(k);
        p = next(p);
        k += 1;
    }
    cond(time[abol.1].is_some());
    let ans = time[abol.1].unwrap() as u64 * step as u64 + t as u64;
    println!("{}", ans);
}

fn main() {
    run();
}

Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.  So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become  and height of Abol will become  where x1, y1, x2 and y2 are some integer numbers and  denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.

The first line of input contains integer m (2 ≤ m ≤ 106). The second line of input contains integers h1 and a1 (0 ≤ h1, a1 < m). The third line of input contains integers x1 and y1 (0 ≤ x1, y1 < m). The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 < m). The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 < m). It is guaranteed that h1 ≠ a1 and h2 ≠ a2.

Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.

NoteIn the first sample, heights sequences are following:Xaniar: Abol:

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

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

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

fn run() {
    input! {
        m: u64,
        xaniar: (usize, usize, u64, u64),
        abol: (usize, usize, u64, u64),
    }
    let cond = |b: bool| {
        if !b {
            println!("-1");
            std::process::exit(0);
        }
    };
    let next = |h: usize| -> usize {
        let x = xaniar.2;
        let y = xaniar.3;
        ((h as u64 * x + y) % m) as usize
    };
    let mut time = vec![None; m as usize];
    let mut p = xaniar.0;
    time[p] = Some(0);
    let mut k = 1;
    p = next(p);
    while time[p].is_none() {
        time[p] = Some(k);
        k += 1;
        p = next(p);
    }
    let step = k - time[p].unwrap();
    let a = xaniar.1;
    cond(time[a].is_some());
    if time[a].unwrap() < time[p].unwrap() {
        let next = |h: usize| -> usize {
            let x = abol.2;
            let y = abol.3;
            ((h as u64 * x + y) % m) as usize
        };
        let t = time[a].unwrap();
        let mut p = abol.0;
        for _ in 0..t {
            p = next(p);
        }
        cond(p == abol.1);
        println!("{}", t);
        return;
    }
    let t = time[a].unwrap();
    let mut abol = abol;
    for _ in 0..t {
        abol.0 = {
            let x = abol.2;
            let y = abol.3;
            ((abol.0 as u64 * x + y) % m) as usize
        };
    }
    let mut mat = (1, 0);
    for _ in 0..step {
        mat = (mat.0 * abol.2 % m, (mat.1 * abol.2 + abol.3) % m);
    }
    abol.2 = mat.0;
    abol.3 = mat.1;
    let mut time = vec![None; m as usize];
    let next = |h: usize| -> usize {
        let x = abol.2;
        let y = abol.3;
        ((h as u64 * x + y) % m) as usize
    };
    let mut p = abol.0;
    time[abol.0] = Some(0);
    p = next(p);
    let mut k = 1;
    while time[p].is_none() {
        time[p] = Some(k);
        p = next(p);
        k += 1;
    }
    cond(time[abol.1].is_some());
    let ans = time[abol.1].unwrap() as u64 * step as u64 + t as u64;
    println!("{}", ans);
}

fn main() {
    run();
}


fn main() {

    use std::io::{self, Read};
    use std::cmp::Ordering;
    use std::collections::{HashMap,HashSet};
    use std::mem;

    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    handle.read_to_string(&mut buffer).unwrap();

    let input_strs = buffer.split_whitespace().take(3).map( |x| x.parse::<i64>().unwrap() ).collect::< Vec<i64> >();

    let n = *input_strs.iter().nth(0).unwrap();

    let mut hs = HashSet::new();
    hs.insert(0);

    let mut dp_count = HashMap::new();

    //strategy: use dp and the number of additional unique values added per round tops off at some point for value denominations of 1, 5, 10, 50
    // so use that value for bigger number of rounds
    for i in 0..13 {
        let mut temp = HashSet::new();
        for j in hs.iter() {
            temp.insert( *j + 1 );
            temp.insert( *j + 5 );
            temp.insert( *j + 10 );
            temp.insert( *j + 50 );
        }
        mem::swap( & mut temp, & mut hs );
        let count = hs.len();
        dp_count.insert(i+1, count);
    }

    let ans = if n <= 12 {
        *dp_count.get(&n).expect("dp_count")
    } else {
        let increment = *dp_count.get(&12).unwrap() - *dp_count.get(&11).unwrap();
        *dp_count.get(&12).unwrap() + (n as usize - 12) * increment
    };
    println!( "{}", ans );
}

Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $$$1$$$, $$$5$$$, $$$10$$$ and $$$50$$$ respectively. The use of other roman digits is not allowed.Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it.For example, the number XXXV evaluates to $$$35$$$ and the number IXI — to $$$12$$$.Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $$$11$$$, not $$$9$$$.One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by exactly $$$n$$$ roman digits I, V, X, L.

The only line of the input file contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of roman digits to use.

Output a single integer — the number of distinct integers which can be represented using $$$n$$$ roman digits exactly.

NoteIn the first sample there are exactly $$$4$$$ integers which can be represented — I, V, X and L.In the second sample it is possible to represent integers $$$2$$$ (II), $$$6$$$ (VI), $$$10$$$ (VV), $$$11$$$ (XI), $$$15$$$ (XV), $$$20$$$ (XX), $$$51$$$ (IL), $$$55$$$ (VL), $$$60$$$ (XL) and $$$100$$$ (LL).

fn main() {

    use std::io::{self, Read};
    use std::cmp::Ordering;
    use std::collections::{HashMap,HashSet};
    use std::mem;

    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    handle.read_to_string(&mut buffer).unwrap();

    let input_strs = buffer.split_whitespace().take(3).map( |x| x.parse::<i64>().unwrap() ).collect::< Vec<i64> >();

    let n = *input_strs.iter().nth(0).unwrap();

    let mut hs = HashSet::new();
    hs.insert(0);

    let mut dp_count = HashMap::new();

    //dp_count.insert( &0, 1 );

    //strategy: use dp and the number of additional unique values added per round tops off at some point for value denominations of 1, 5, 10, 50
    // so use that value for bigger number of rounds
    for i in 0..13 {
        let mut temp = HashSet::new();
        for j in hs.iter() {
            temp.insert( *j + 1i64 );
            temp.insert( *j + 5i64 );
            temp.insert( *j + 10i64 );
            temp.insert( *j + 50i64 );
        }
        mem::swap( & mut temp, & mut hs );
        let count = hs.len();
        dp_count.insert(i+1, count);
    }

    let ans = if n <= 12 {
        *dp_count.get(&n).expect("dp_count") as i64
    } else {
        let increment = *dp_count.get(&12).unwrap() - *dp_count.get(&11).unwrap();
        *dp_count.get(&12).unwrap() as i64 + (n as i64 - 12i64) * increment as i64
    };
    println!( "{}", ans );
}


// ---------- begin ModInt ----------
const MOD: u32 = 1_000_000_007;

#[derive(Clone, Copy)]
struct ModInt(u32);

impl std::ops::Add for ModInt {
    type Output = ModInt;
    fn add(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::AddAssign for ModInt {
    fn add_assign(&mut self, rhs: ModInt) {
        *self = *self + rhs;
    }
}

impl std::ops::Sub for ModInt {
    type Output = ModInt;
    fn sub(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + MOD - rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::SubAssign for ModInt {
    fn sub_assign(&mut self, rhs: ModInt) {
        *self = *self - rhs;
    }
}

impl std::ops::Mul for ModInt {
    type Output = ModInt;
    fn mul(self, rhs: ModInt) -> Self::Output {
        ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)
    }
}

impl std::ops::MulAssign for ModInt {
    fn mul_assign(&mut self, rhs: ModInt) {
        *self = *self * rhs;
    }
}

impl std::ops::Neg for ModInt {
    type Output = ModInt;
    fn neg(self) -> Self::Output {
        ModInt(if self.0 == 0 {0} else {MOD - self.0})
    }
}

impl std::fmt::Display for ModInt {
    fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for ModInt {
    type Err = std::num::ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let val = s.parse::<u32>()?;
        Ok(ModInt::new(val))
    }
}

impl From<usize> for ModInt {
    fn from(val: usize) -> Self {
        ModInt((val % MOD as usize) as u32)
    }
}

#[allow(dead_code)]
impl ModInt {
    pub fn new(n: u32) -> ModInt {
        ModInt(n % MOD)
    }
    pub fn zero() -> ModInt {
        ModInt(0)
    }
    pub fn one() -> ModInt {
        ModInt(1)
    }
    pub fn pow(self, mut n: u32) -> ModInt {
        let mut t = ModInt::one();
        let mut s = self;
        while n > 0 {
            if n & 1 == 1 {
                t *= s;
            }
            s *= s;
            n >>= 1;
        }
        t
    }
    pub fn inv(self) -> ModInt {
        assert!(self.0 > 0);
        self.pow(MOD - 2)
    }
}
// ---------- end ModInt ----------
// ---------- begin Precalc ----------
#[allow(dead_code)]
struct Precalc {
    inv: Vec<ModInt>,
    fact: Vec<ModInt>,
    ifact: Vec<ModInt>,
}

#[allow(dead_code)]
impl Precalc {
    pub fn new(n: usize) -> Precalc {
        let mut inv = vec![ModInt::one(); n + 1];
        let mut fact = vec![ModInt::one(); n + 1];
        let mut ifact = vec![ModInt::one(); n + 1];
        for i in 2..(n + 1) {
            inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);
            fact[i] = fact[i - 1] * ModInt(i as u32);
            ifact[i] = ifact[i - 1] * inv[i];
        }
        Precalc {
            inv: inv,
            fact: fact,
            ifact: ifact,
        }
    }
    pub fn inv(&self, n: usize) -> ModInt {
        self.inv[n]
    }
    pub fn fact(&self, n: usize) -> ModInt {
        self.fact[n]
    }
    pub fn ifact(&self, n: usize) -> ModInt {
        self.ifact[n]
    }
    pub fn comb(&self, n: usize, k: usize) -> ModInt {
        if k > n {
            return ModInt::zero();
        }
        self.fact[n] * self.ifact[k] * self.ifact[n - k]
    }
}
// ---------- end Precalc ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

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

//

fn run() {
    input! {
        n: usize,
        w: usize,
        a: [usize; n],
    }
    let mut a = a;
    a.sort();
    let mut dp = vec![vec![ModInt::zero(); w + 1]; 2];
    dp[0][0] = ModInt::one();
    dp[1][0] = ModInt::one();
    for d in a.windows(2) {
        let d = d[1] - d[0];
        let mut next = vec![vec![ModInt::zero(); w + 1]; dp.len() + 1];
        // 単体
        for (i, dp) in dp.iter().enumerate() {
            let next = &mut next[i];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += v;
                } else {
                    break;
                }
            }
        }
        // 閉じる
        for (i, dp) in dp.iter().enumerate().skip(1) {
            let next = &mut next[i - 1];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += v;
                } else {
                    break;
                }
            }
        }
        // 割り当て
        for (i, dp) in dp.iter().enumerate().skip(1) {
            let next = &mut next[i];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += ModInt::from(i) * v;
                } else {
                    break;
                }
            }
        }
        // 開く
        for (i, dp) in dp.iter().enumerate() {
            let next = &mut next[i + 1];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += v;
                } else {
                    break;
                }
            }
        }
        dp = next;
    }
    let mut ans = ModInt::zero();
    for a in dp[0].iter() {
        ans += *a;
    }
    println!("{}", ans);
}

fn main() {
    run();
}

There are n students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the i-th student ai minutes to finish his/her independent piece.If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum ai in the group minus the minimum ai in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most k?Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 200, 0 ≤ k ≤ 1000) — the number of students and the maximum total imbalance allowed, respectively. The second line contains n space-separated integers ai (1 ≤ ai ≤ 500) — the time it takes the i-th student to complete his/her independent piece of work.

Print a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 109 + 7.

NoteIn the first sample, we have three options:   The first and second students form a group, and the third student forms a group. Total imbalance is 2 + 0 = 2.  The first student forms a group, and the second and third students form a group. Total imbalance is 0 + 1 = 1.  All three students form their own groups. Total imbalance is 0. In the third sample, the total imbalance must be 0, so each student must work individually.

// ---------- begin ModInt ----------
const MOD: u32 = 1_000_000_007;

#[derive(Clone, Copy)]
struct ModInt(u32);

impl std::ops::Add for ModInt {
    type Output = ModInt;
    fn add(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::AddAssign for ModInt {
    fn add_assign(&mut self, rhs: ModInt) {
        *self = *self + rhs;
    }
}

impl std::ops::Sub for ModInt {
    type Output = ModInt;
    fn sub(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + MOD - rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::SubAssign for ModInt {
    fn sub_assign(&mut self, rhs: ModInt) {
        *self = *self - rhs;
    }
}

impl std::ops::Mul for ModInt {
    type Output = ModInt;
    fn mul(self, rhs: ModInt) -> Self::Output {
        ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)
    }
}

impl std::ops::MulAssign for ModInt {
    fn mul_assign(&mut self, rhs: ModInt) {
        *self = *self * rhs;
    }
}

impl std::ops::Neg for ModInt {
    type Output = ModInt;
    fn neg(self) -> Self::Output {
        ModInt(if self.0 == 0 {0} else {MOD - self.0})
    }
}

impl std::fmt::Display for ModInt {
    fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for ModInt {
    type Err = std::num::ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let val = s.parse::<u32>()?;
        Ok(ModInt::new(val))
    }
}

impl From<usize> for ModInt {
    fn from(val: usize) -> Self {
        ModInt((val % MOD as usize) as u32)
    }
}

#[allow(dead_code)]
impl ModInt {
    pub fn new(n: u32) -> ModInt {
        ModInt(n % MOD)
    }
    pub fn zero() -> ModInt {
        ModInt(0)
    }
    pub fn one() -> ModInt {
        ModInt(1)
    }
    pub fn pow(self, mut n: u32) -> ModInt {
        let mut t = ModInt::one();
        let mut s = self;
        while n > 0 {
            if n & 1 == 1 {
                t *= s;
            }
            s *= s;
            n >>= 1;
        }
        t
    }
    pub fn inv(self) -> ModInt {
        assert!(self.0 > 0);
        self.pow(MOD - 2)
    }
}
// ---------- end ModInt ----------
// ---------- begin Precalc ----------
#[allow(dead_code)]
struct Precalc {
    inv: Vec<ModInt>,
    fact: Vec<ModInt>,
    ifact: Vec<ModInt>,
}

#[allow(dead_code)]
impl Precalc {
    pub fn new(n: usize) -> Precalc {
        let mut inv = vec![ModInt::one(); n + 1];
        let mut fact = vec![ModInt::one(); n + 1];
        let mut ifact = vec![ModInt::one(); n + 1];
        for i in 2..(n + 1) {
            inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);
            fact[i] = fact[i - 1] * ModInt(i as u32);
            ifact[i] = ifact[i - 1] * inv[i];
        }
        Precalc {
            inv: inv,
            fact: fact,
            ifact: ifact,
        }
    }
    pub fn inv(&self, n: usize) -> ModInt {
        self.inv[n]
    }
    pub fn fact(&self, n: usize) -> ModInt {
        self.fact[n]
    }
    pub fn ifact(&self, n: usize) -> ModInt {
        self.ifact[n]
    }
    pub fn comb(&self, n: usize, k: usize) -> ModInt {
        if k > n {
            return ModInt::zero();
        }
        self.fact[n] * self.ifact[k] * self.ifact[n - k]
    }
}
// ---------- end Precalc ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

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

//

fn run() {
    input! {
        n: usize,
        w: usize,
        a: [usize; n],
    }
    let mut a = a;
    a.sort();
    let mut dp = vec![vec![ModInt::zero(); w + 1]; 2];
    dp[0][0] = ModInt::one();
    dp[1][0] = ModInt::one();
    for d in a.windows(2) {
        let d = d[1] - d[0];
        let mut next = vec![vec![ModInt::zero(); w + 1]; dp.len() + 1];
        // 単体
        for (i, dp) in dp.iter().enumerate() {
            let next = &mut next[i];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += v;
                } else {
                    break;
                }
            }
        }
        // 閉じる
        for (i, dp) in dp.iter().enumerate().skip(1) {
            let next = &mut next[i - 1];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += ModInt::from(i) * v;
                } else {
                    break;
                }
            }
        }
        // 割り当て
        for (i, dp) in dp.iter().enumerate().skip(1) {
            let next = &mut next[i];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += ModInt::from(i) * v;
                } else {
                    break;
                }
            }
        }
        // 開く
        for (i, dp) in dp.iter().enumerate() {
            let next = &mut next[i + 1];
            for (j, &v) in dp.iter().enumerate() {
                if let Some(p) = next.get_mut(j + i * d) {
                    *p += v;
                } else {
                    break;
                }
            }
        }
        dp = next;
    }
    let mut ans = ModInt::zero();
    for a in dp[0].iter() {
        ans += *a;
    }
    println!("{}", ans);
}

fn main() {
    run();
}