There are $$$n$$$ chips arranged in a circle, numbered from $$$1$$$ to $$$n$$$. Initially each chip has black or white color. Then $$$k$$$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $$$i$$$, three chips are considered: chip $$$i$$$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $$$i$$$ becomes white. Otherwise, the chip $$$i$$$ becomes black. Note that for each $$$i$$$ from $$$2$$$ to $$$(n - 1)$$$ two neighbouring chips have numbers $$$(i - 1)$$$ and $$$(i + 1)$$$. The neighbours for the chip $$$i = 1$$$ are $$$n$$$ and $$$2$$$. The neighbours of $$$i = n$$$ are $$$(n - 1)$$$ and $$$1$$$.The following picture describes one iteration with $$$n = 6$$$. The chips $$$1$$$, $$$3$$$ and $$$4$$$ are initially black, and the chips $$$2$$$, $$$5$$$ and $$$6$$$ are white. After the iteration $$$2$$$, $$$3$$$ and $$$4$$$ become black, and $$$1$$$, $$$5$$$ and $$$6$$$ become white. Your task is to determine the color of each chip after $$$k$$$ iterations.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(3 \le n \le 200\,000, 1 \le k \le 10^{9})$$$ — the number of chips and the number of iterations, respectively.
The second line contains a string consisting of $$$n$$$ characters "W" and "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th chip is white initially. If the $$$i$$$-th character is "B", then the $$$i$$$-th chip is black initially.

Print a string consisting of $$$n$$$ characters "W" and "B". If after $$$k$$$ iterations the $$$i$$$-th chip is white, then the $$$i$$$-th character should be "W". Otherwise the $$$i$$$-th character should be "B".

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

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

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

        v
    }}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#[allow(dead_code)]
pub trait IteratorExt: Iterator + Sized {
    fn sorted(self) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        Self::Item: std::cmp::Ord,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort();
        v.into_iter()
    }
    fn sorted_by<F>(self, f: F) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        F: FnMut(&Self::Item, &Self::Item) -> std::cmp::Ordering,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort_by(f);
        v.into_iter()
    }
    fn sorted_by_key<F, K>(self, f: F) -> <std::vec::Vec<Self::Item> as IntoIterator>::IntoIter
    where
        F: FnMut(&Self::Item) -> K,
        K: std::cmp::Ord,
    {
        let mut v = self.collect::<Vec<_>>();
        v.sort_by_key(f);
        v.into_iter()
    }
    fn join(self, delim: &str) -> String
    where
        Self::Item: ToString,
    {
        self.enumerate().fold(String::new(), |s, (i, t)| {
            if i == 0 {
                s + &t.to_string()
            } else {
                s + delim + &t.to_string()
            }
        })
    }
}
impl<I> IteratorExt for I where I: Iterator {}

fn main() {
    let (n, k) = read_tuple!(usize, usize);
    let s = read_str();

    let t = (0..n)
        .map(|i| {
            let prev = s[(i + n - 1) % n];
            let current = s[i];
            let next = s[(i + 1) % n];

            if prev == current || current == next {
                Some(current)
            } else {
                None
            }
        })
        .collect::<Vec<_>>();

    let d0 = (0..2 * n)
        .scan(None, |p, i| {
            if let Some(c) = t[i % n] {
                *p = Some((i, c));
                Some(None)
            } else {
                if let Some((pp, c)) = *p {
                    Some(Some((i - pp, c)))
                } else {
                    Some(None)
                }
            }
        })
        .skip(n)
        .collect::<Vec<_>>();

    let d1 = (0..2 * n)
        .rev()
        .scan(None, |p, i| {
            if let Some(c) = t[i % n] {
                *p = Some((i, c));
                Some(None)
            } else {
                if let Some((pp, c)) = *p {
                    Some(Some((pp - i, c)))
                } else {
                    Some(None)
                }
            }
        })
        .skip(n)
        .collect::<Vec<_>>();

    let ans = t
        .citer()
        .zip(s.citer())
        .zip(d0.citer().zip(d1.citer().rev()))
        .map(|((tt, ss), (dd0, dd1))| {
            if let Some(c) = tt {
                c
            } else if let Some((x, c0)) = dd0 {
                let (y, c1) = dd1.unwrap();

                let d = min(x, y);

                if k < d {
                    if k % 2 == 0 {
                        ss
                    } else if ss == 'W' {
                        'B'
                    } else {
                        'W'
                    }
                } else if x < y {
                    c0
                } else {
                    c1
                }
            } else {
                if k % 2 == 0 {
                    ss
                } else if ss == 'W' {
                    'B'
                } else {
                    'W'
                }
            }
        })
        .collect::<Vec<_>>();
    println!("{}", ans.citer().join(""));
}

[{'input': ['6 1\r\nBWBBWW\r\n'], 'output': ['WBBBWW\r\n']}, {'input': ['7 3\r\nWBWBWBW\r\n'], 'output': ['WWWWWWW\r\n']}, {'input': ['6 4\r\nBWBWBW\r\n'], 'output': ['BWBWBW\r\n']}, {'input': ['4 5\r\nBWBB\r\n'], 'output': ['BBBB\r\n']}, {'input': ['16 7\r\nWBBWBWWBBWBWWBWW\r\n'], 'output': ['WBBBWWWBBBWWWWWW\r\n']}, {'input': ['16 19\r\nBWWWBBBWWBWBBBWB\r\n'], 'output': ['BWWWBBBWWWBBBBBB\r\n']}, {'input': ['10 1000000000\r\nBBWWBBWWBB\r\n'], 'output': ['BBWWBBWWBB\r\n']}, {'input': ['12 1000000000\r\nBBWWBBWWBBWW\r\n'], 'output': ['BBWWBBWWBBWW\r\n']}, {'input': ['3 1000000000\r\nWWB\r\n'], 'output': ['WWW\r\n']}, {'input': ['3 1\r\nBWB\r\n'], 'output': ['BBB\r\n']}, {'input': ['16 1000000000\r\nBWBWBWBWBWBWBWBW\r\n'], 'output': ['BWBWBWBWBWBWBWBW\r\n']}, {'input': ['3 2\r\nBWB\r\n'], 'output': ['BBB\r\n']}, {'input': ['3 3\r\nWBW\r\n'], 'output': ['WWW\r\n']}, {'input': ['3 3\r\nWWW\r\n'], 'output': ['WWW\r\n']}, {'input': ['3 1\r\nWWB\r\n'], 'output': ['WWW\r\n']}, {'input': ['3 1\r\nBWW\r\n'], 'output': ['WWW\r\n']}, {'input': ['3 1\r\nBBW\r\n'], 'output': ['BBB\r\n']}, {'input': ['3 1\r\nWBW\r\n'], 'output': ['WWW\r\n']}, {'input': ['16 20\r\nBWBWWBBBWWWWWBWB\r\n'], 'output': ['BBWWWBBBWWWWWWBB\r\n']}, {'input': ['16 11\r\nBWWBBWBBWBWWWWWB\r\n'], 'output': ['BWWBBBBBBWWWWWWB\r\n']}, {'input': ['16 5\r\nWBBBBWBBBBBBWBBW\r\n'], 'output': ['WBBBBBBBBBBBBBBW\r\n']}, {'input': ['16 3\r\nBWWWWWBBBBWWBBWB\r\n'], 'output': ['BWWWWWBBBBWWBBBB\r\n']}, {'input': ['16 17\r\nWBWBBWBWWBWWBWWW\r\n'], 'output': ['WWBBBBWWWWWWWWWW\r\n']}, {'input': ['16 19\r\nBWBWWBWWWWBWWWBB\r\n'], 'output': ['BBWWWWWWWWWWWWBB\r\n']}, {'input': ['16 19\r\nBWWBWBWWWWBBBBWB\r\n'], 'output': ['BWWWWWWWWWBBBBBB\r\n']}, {'input': ['16 5\r\nWBWBBBBBWBWBBWWW\r\n'], 'output': ['WWBBBBBBBBBBBWWW\r\n']}, {'input': ['20 1\r\nBWBWBWBBBWBWBWBWBWBB\r\n'], 'output': ['BBWBWBBBBBWBWBWBWBBB\r\n']}, {'input': ['31 2\r\nBWBWBWBWBWBWBWWWBWBWBWBBBWBWWWB\r\n'], 'output': ['BBBWBWBWBWBWWWWWWWBWBBBBBBWWWWB\r\n']}, {'input': ['50 4\r\nBWBWBWBWBWBWBWBWBWBWBBWWBWBWBWBWWWWWBWBWBWBWBBBWBW\r\n'], 'output': ['BWBWBWBWBWBWBWBWBBBBBBWWWWWWWWWWWWWWWWWWBBBBBBBBBB\r\n']}, {'input': ['101 2\r\nBWBWBWWWBWBWBWWWBWWWBWWWBWBBBBBWBWBBBWBWBWWBBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWWWBWBWBWB\r\n'], 'output': ['BBBWWWWWWWBWWWWWWWWWWWWWWBBBBBBBBBBBBBBWWWWBBBBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWBWWWWWWWBWBBB\r\n']}]


This is the harder version of the problem. In this version, $$$1 \le n \le 10^6$$$ and $$$0 ≤ a_i ≤ 10^6$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problemsChristmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $$$n$$$ boxes of chocolate, numbered from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th box contains $$$a_i$$$ chocolate pieces.Since Bob is a typical nice guy, he will not send Alice $$$n$$$ empty boxes. In other words, at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $$$k > 1$$$ such that the number of pieces in each box is divisible by $$$k$$$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $$$i$$$ and put it into either box $$$i-1$$$ or box $$$i+1$$$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of chocolate boxes.
The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the number of chocolate pieces in the $$$i$$$-th box.
It is guaranteed that at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive.

If there is no way for Charlie to make Alice happy, print $$$-1$$$.
Otherwise, print a single integer $$$x$$$ — the minimum number of seconds for Charlie to help Bob make Alice happy.

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

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

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

        v
    }}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

fn main() {
    let n: usize = read();
    let a = read_row::<usize>();

    let s = a.citer().sum::<usize>();

    if s == 1 {
        println!("-1");
        return;
    }

    let prime_factors = (2..)
        .scan(s, |m, i| {
            if i * i > *m {
                if *m == 1 {
                    None
                } else {
                    Some(Some(replace(m, 1)))
                }
            } else {
                let (d, mm) = successors(Some(*m), |mm| Some(mm / i))
                    .enumerate()
                    .skip_while(|&(_, mm)| mm % i == 0)
                    .next()
                    .unwrap();
                *m = mm;

                if d > 0 {
                    Some(Some(i))
                } else {
                    Some(None)
                }
            }
        })
        .flatten()
        .collect::<Vec<_>>();

    let ans = prime_factors
        .citer()
        .map(|k| {
            a.citer()
                .enumerate()
                .scan((0, 0, 0), |(num, sum_pos, mid), (i, aa)| {
                    assert!(*num < k);

                    if *num < (k + 1) / 2 {
                        if *num + aa < (k + 1) / 2 {
                            *num += aa;
                            *sum_pos += i * aa;
                            Some(0)
                        } else if *num + aa < k {
                            let m = i * *num - *sum_pos;
                            *num += aa;
                            *mid = i;
                            Some(m)
                        } else {
                            let r = *num + aa - k;
                            let m = i * *num - *sum_pos;
                            *num = r % k;
                            *sum_pos = (r % k) * i;
                            // *numã(k+1)/2è¶ãã¦ããã¨ãç¨
                            *mid = i;
                            Some(m)
                        }
                    } else {
                        if *num + aa < k {
                            let m = aa * (i - *mid);
                            *num += aa;
                            Some(m)
                        } else {
                            let r = *num + aa - k;
                            let m = (k - *num) * (i - *mid);
                            *num = r % k;
                            *sum_pos = (r % k) * i;
                            // *numã(k+1)/2è¶ãã¦ããã¨ãç¨
                            *mid = i;
                            Some(m)
                        }
                    }
                })
                .sum::<usize>()
        })
        .min()
        .unwrap();

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


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


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


The only difference between easy and hard versions is the number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. In one move you can choose any $$$a_i$$$ and divide it by $$$2$$$ rounding down (in other words, in one move you can set $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).You can perform such an operation any (possibly, zero) number of times with any $$$a_i$$$.Your task is to calculate the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.Don't forget that it is possible to have $$$a_i = 0$$$ after some operations, thus the answer always exists.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$) — the number of elements in the array and the number of equal numbers required. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible number of operations required to obtain at least $$$k$$$ equal numbers in the array.

use std::io;
use std::str::FromStr;
use std::num::ParseIntError;
use std::ops::Index;

struct RevBinary {
    data: Vec<bool>,
}

impl FromStr for RevBinary {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let i = s.parse::<u32>()?;

        Ok(RevBinary::new(i))
    }
}

impl Index<usize> for RevBinary {
    type Output = bool;

    fn index(&self, i: usize) -> &Self::Output {
        &self.data[self.data.len() - i - 1]
    }
}

impl RevBinary {
    fn new(x : u32) -> RevBinary {
        let mut y = x;
        let mut bin : Vec<bool> = Vec::new();
        while y != 0 {
           bin.push(if y % 2 == 1 { true } else { false });
           y /= 2;
        }
        RevBinary {
            data: bin,
        }
    }

    fn size(&self) -> usize {
        self.data.len()
    }
}

fn process_node(all: &Vec<RevBinary>, ind: Vec<usize>, depth: usize, k: u32) -> u32 {
    let mut result : u32 = ind.iter().take(k as usize).map(|&x| all[x].size() - depth).sum::<usize>() as u32;

    if result == 0 {
        return 0;
    }

    let new_ind : (Vec<usize>, Vec<usize>) = ind.iter().filter(|&&x| all[x].size() > depth).partition(|&&x| all[x][depth]);
    if new_ind.0.len() >= k as usize {
        result = result.min(process_node(&all, new_ind.0, depth + 1, k));
    }
    if result != 0 && new_ind.1.len() >= k as usize {
        result = result.min(process_node(&all, new_ind.1, depth + 1, k));
    }
    result
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("failed to read input");
    let mut input_iter = input.split_whitespace();
    let n = input_iter.next().unwrap().parse::<usize>().unwrap();
    let k = input_iter.next().unwrap().parse::<u32>().unwrap();
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("failed to read input");
    let mut a = buffer.split_whitespace().map(|x| x.parse::<RevBinary>().unwrap()).collect::<Vec<RevBinary>>();
    a.sort_by(|a, b| a.size().cmp(&b.size()));

    println!("{}", process_node(&a, (0..n).collect::<Vec<usize>>(), 0, k));
}


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

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

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

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

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

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

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

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

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

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

    let mut answ = first.max(second);

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

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

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

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

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

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

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

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

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

        solve(&mut f, &mut buf);

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

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

        solve(&mut f, &mut buf);

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

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

        solve(&mut f, &mut buf);

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

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

        solve(&mut f, &mut buf);

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


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


You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors  and  is acute (i.e. strictly less than ). Otherwise, the point is called good.The angle between vectors  and  in 5-dimensional space is defined as , where  is the scalar product and  is length of .Given the list of points, print the indices of the good points in ascending order.

The first line of input contains a single integer n (1 ≤ n ≤ 103) — the number of points. The next n lines of input contain five integers ai, bi, ci, di, ei (|ai|, |bi|, |ci|, |di|, |ei| ≤ 103)  — the coordinates of the i-th point. All points are distinct.

First, print a single integer k — the number of good points. Then, print k integers, each on their own line — the indices of the good points in ascending order.

NoteIn the first sample, the first point forms exactly a  angle with all other pairs of points, so it is good.In the second sample, along the cd plane, we can see the points look as follows:We can see that all angles here are acute, so no points are good.

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

//

fn run() {
    input! {
        n: usize,
        p: [[i64; 5]; n],
    }
    if n > 100 {
        println!("0");
        return;
    }
    let mut ans = vec![];
    for i in 0..n {
        let mut q = p.clone();
        let p = q.remove(i);
        for q in q.iter_mut() {
            for (q, p) in q.iter_mut().zip(p.iter()) {
                *q -= *p;
            }
        }
        let mut ok = true;
        for (i, a) in q.iter().enumerate() {
            for b in q.iter().take(i) {
                let mut sum = 0;
                for (a, b) in a.iter().zip(b.iter()) {
                    sum += *a * *b;
                }
                if sum > 0 {
                    ok = false;
                }
            }
        }
        if ok {
            ans.push(i + 1);
        }
    }
    println!("{}", ans.len());
    for (i, a) in ans.iter().enumerate() {
        if i > 0 {
            print!(" ");
        }
        print!("{}", a);
    }
    println!();
}

fn main() {
    run();
}


It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 <; r ≤ 2k. Let's call that representation prairie partition of x.For example, the prairie partitions of 12, 17, 7 and 1 are:  12 = 1 + 2 + 4 + 5,17 = 1 + 2 + 4 + 8 + 2,7 = 1 + 2 + 4,1 = 1. Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of numbers given from Alice to Borys. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1012; a1 ≤ a2 ≤ ... ≤ an) — the numbers given from Alice to Borys.

Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input. If there are no such values of m, output a single integer -1.

NoteIn the first example, Alice could get the input sequence from [6, 20] as the original sequence.In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3].

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

//

// 最大値は貪欲に割り当てれば良い？
// 2冪を均等に割り振る、割り振れなかったのは2冪でない列に突っ込む
// 2冪でない列を貪欲に割り当てる
// 小さい値を小さい値に割り振る感じ
// これでできないならNo
// できたら？
// 小さい列を解消して再割り当てができるかというのを順に続けるといいか
// 計算量？
// 全部1とかだと割り当ての回数がO(N)になる、辛い
// 割り当て可能かは単調なので二分探索

fn valid(beki: &[u64], b: &mut [u64]) -> bool {
    b.sort();
    let mut p = 0;
    for pow in beki.iter().rev() {
        if p < b.len() && *pow * 2 >= b[p] {
            p += 1;
        }
    }
    p == b.len()
}

fn run() {
    input! {
        n: usize,
        a: [u64; n],
    }
    let mut beki = vec![];
    let mut k = 0;
    while k < n && a[k] == 1 {
        beki.push(1);
        k += 1;
    }
    if k == 0 {
        println!("-1");
        return;
    }
    let mut pos = 0;
    let mut b = vec![];
    for a in a[k..].iter() {
        if *a == beki[pos] * 2 {
            beki[pos] *= 2;
            pos = (pos + 1) % beki.len();
        } else {
            pos = 0;
            if *a == beki[pos] * 2 {
                beki[pos] *= 2;
                pos = (pos + 1) % beki.len();
            } else {
                b.push(*a);
            }
        }
    }
    let (beki, b) = (beki, b);
    if !valid(&beki, &mut b.clone()) {
        println!("-1");
        return;
    }
    let mut ok = beki.len();
    let mut ng = 0;
    while ok - ng > 1 {
        let mid = (ok + ng) / 2;
        let mut b = b.clone();
        for p in beki[mid..].iter() {
            let mut k = 1;
            while k <= *p {
                b.push(k);
                k *= 2;
            }
        }
        if valid(&beki[..mid], &mut b) {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    let mut s = String::new();
    for k in ok..=beki.len() {
        s.push_str(&format!("{} ", k));
    }
    s.pop();
    println!("{}", s);
}

fn main() {
    run();
}


You are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 109 + 7.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of points. n lines follow. The (i + 1)-th of these lines contains two integers xi, yi ( - 109 ≤ xi, yi ≤ 109) — coordinates of the i-th point. It is guaranteed that all points are distinct.

Print the number of possible distinct pictures modulo 109 + 7.

NoteIn the first example there are two vertical and two horizontal lines passing through the points. You can get pictures with any subset of these lines. For example, you can get the picture containing all four lines in two ways (each segment represents a line containing it). The first way:      The second way:      In the second example you can work with two points independently. The number of pictures is 32 = 9.

//---------- begin union_find ----------
pub struct DSU {
    p: Vec<i32>,
}
impl DSU {
    pub fn new(n: usize) -> DSU {
        DSU { p: vec![-1; n] }
    }
    pub fn init(&mut self) {
        for p in self.p.iter_mut() {
            *p = -1;
        }
    }
    pub fn root(&self, mut x: usize) -> usize {
        assert!(x < self.p.len());
        while self.p[x] >= 0 {
            x = self.p[x] as usize;
        }
        x
    }
    pub fn same(&self, x: usize, y: usize) -> bool {
        assert!(x < self.p.len());
        assert!(y < self.p.len());
        self.root(x) == self.root(y)
    }
    pub fn unite(&mut self, x: usize, y: usize) -> Option<(usize, usize)> {
        assert!(x < self.p.len());
        assert!(y < self.p.len());
        let mut x = self.root(x);
        let mut y = self.root(y);
        if x == y {
            return None;
        }
        if self.p[x] > self.p[y] {
            std::mem::swap(&mut x, &mut y);
        }
        self.p[x] += self.p[y];
        self.p[y] = x as i32;
        Some((x, y))
    }
    pub fn parent(&self, x: usize) -> Option<usize> {
        assert!(x < self.p.len());
        let p = self.p[x];
        if p >= 0 {
            Some(p as usize)
        } else {
            None
        }
    }
    pub fn size(&self, x: usize) -> usize {
        assert!(x < self.p.len());
        let r = self.root(x);
        (-self.p[r]) as usize
    }
}
//---------- end union_find ----------
// ---------- begin ModInt ----------
mod modint {

    #[allow(dead_code)]
    pub struct Mod;
    impl ConstantModulo for Mod {
        const MOD: u32 = 1_000_000_007;
    }

    #[allow(dead_code)]
    pub struct StaticMod;
    static mut STATIC_MOD: u32 = 0;
    impl Modulo for StaticMod {
        fn modulo() -> u32 {
            unsafe { STATIC_MOD }
        }
    }

    #[allow(dead_code)]
    impl StaticMod {
        pub fn set_modulo(p: u32) {
            unsafe {
                STATIC_MOD = p;
            }
        }
    }

    use std::marker::*;
    use std::ops::*;

    pub trait Modulo {
        fn modulo() -> u32;
    }

    pub trait ConstantModulo {
        const MOD: u32;
    }

    impl<T> Modulo for T
    where
        T: ConstantModulo,
    {
        fn modulo() -> u32 {
            T::MOD
        }
    }

    pub struct ModInt<T>(pub u32, PhantomData<T>);

    impl<T> Clone for ModInt<T> {
        fn clone(&self) -> Self {
            ModInt::new_unchecked(self.0)
        }
    }

    impl<T> Copy for ModInt<T> {}

    impl<T: Modulo> Add for ModInt<T> {
        type Output = ModInt<T>;
        fn add(self, rhs: Self) -> Self::Output {
            let mut d = self.0 + rhs.0;
            if d >= T::modulo() {
                d -= T::modulo();
            }
            ModInt::new_unchecked(d)
        }
    }

    impl<T: Modulo> AddAssign for ModInt<T> {
        fn add_assign(&mut self, rhs: Self) {
            *self = *self + rhs;
        }
    }

    impl<T: Modulo> Sub for ModInt<T> {
        type Output = ModInt<T>;
        fn sub(self, rhs: Self) -> Self::Output {
            let mut d = T::modulo() + self.0 - rhs.0;
            if d >= T::modulo() {
                d -= T::modulo();
            }
            ModInt::new_unchecked(d)
        }
    }

    impl<T: Modulo> SubAssign for ModInt<T> {
        fn sub_assign(&mut self, rhs: Self) {
            *self = *self - rhs;
        }
    }

    impl<T: Modulo> Mul for ModInt<T> {
        type Output = ModInt<T>;
        fn mul(self, rhs: Self) -> Self::Output {
            let v = self.0 as u64 * rhs.0 as u64 % T::modulo() as u64;
            ModInt::new_unchecked(v as u32)
        }
    }

    impl<T: Modulo> MulAssign for ModInt<T> {
        fn mul_assign(&mut self, rhs: Self) {
            *self = *self * rhs;
        }
    }

    impl<T: Modulo> Neg for ModInt<T> {
        type Output = ModInt<T>;
        fn neg(self) -> Self::Output {
            if self.0 == 0 {
                Self::zero()
            } else {
                Self::new_unchecked(T::modulo() - self.0)
            }
        }
    }

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

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

    impl<T: Modulo> From<usize> for ModInt<T> {
        fn from(val: usize) -> ModInt<T> {
            ModInt::new_unchecked((val % T::modulo() as usize) as u32)
        }
    }

    impl<T: Modulo> From<u64> for ModInt<T> {
        fn from(val: u64) -> ModInt<T> {
            ModInt::new_unchecked((val % T::modulo() as u64) as u32)
        }
    }

    impl<T: Modulo> From<i64> for ModInt<T> {
        fn from(val: i64) -> ModInt<T> {
            let m = T::modulo() as i64;
            ModInt::new((val % m + m) as u32)
        }
    }

    #[allow(dead_code)]
    impl<T> ModInt<T> {
        pub fn new_unchecked(d: u32) -> Self {
            ModInt(d, PhantomData)
        }
        pub fn zero() -> Self {
            ModInt::new_unchecked(0)
        }
        pub fn one() -> Self {
            ModInt::new_unchecked(1)
        }
        pub fn is_zero(&self) -> bool {
            self.0 == 0
        }
    }

    #[allow(dead_code)]
    impl<T: Modulo> ModInt<T> {
        pub fn new(d: u32) -> Self {
            ModInt::new_unchecked(d % T::modulo())
        }
        pub fn pow(&self, mut n: u64) -> Self {
            let mut t = Self::one();
            let mut s = *self;
            while n > 0 {
                if n & 1 == 1 {
                    t *= s;
                }
                s *= s;
                n >>= 1;
            }
            t
        }
        pub fn inv(&self) -> Self {
            assert!(self.0 != 0);
            self.pow(T::modulo() as u64 - 2)
        }
    }

    #[allow(dead_code)]
    pub fn mod_pow(r: u64, mut n: u64, m: u64) -> u64 {
        let mut t = 1 % m;
        let mut s = r % m;
        while n > 0 {
            if n & 1 == 1 {
                t = t * s % m;
            }
            s = s * s % m;
            n >>= 1;
        }
        t
    }
}
// ---------- end ModInt ----------
// ---------- 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 ----------

use modint::*;
type M = ModInt<Mod>;

fn run() {
    input! {
        n: usize,
        p: [(i32, i32); n],
    }
    let mut x = vec![];
    let mut y = vec![];
    for p in p.iter() {
        x.push(p.0);
        y.push(p.1);
    }
    x.sort();
    x.dedup();
    y.sort();
    y.dedup();
    let len = x.len() + y.len();
    let mut dsu = DSU::new(len);
    let mut cnt = vec![0; len];
    for &(a, b) in p.iter() {
        let a = x.binary_search(&a).unwrap();
        let b = y.binary_search(&b).unwrap() + x.len();
        if let Some((a, b)) = dsu.unite(a, b) {
            cnt[a] += cnt[b];
        }
        cnt[dsu.root(a)] += 1;
    }
    let mut ans = M::one();
    for i in 0..len {
        if i == dsu.root(i) {
            let size = dsu.size(i);
            if cnt[i] >= size {
                ans *= M::new(2).pow(size as u64);
            } else {
                ans *= M::new(2).pow(size as u64) - M::one();
            }
        }
    }
    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();
}


Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.

The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.

Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.

NoteIn the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.In more detail, after choosing X = 42 the process of building a tower is:  Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.  The second added block has side 2, so the remaining volume is 15 - 8 = 7.  Finally, Limak adds 7 blocks with side 1, one by one. So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.

// ---------- begin kth root ----------
// floor(a ^ (1 / k))
fn kth_root(a: u64, k: u64) -> u64 {
    assert!(k > 0);
    if a == 0 {
        return 0;
    }
    if k >= 64 {
        return 1;
    }
    if k == 1 {
        return a;
    }
    let valid = |x: u64| -> bool {
        let mut t = x;
        for _ in 1..k {
            let (val, ok) = t.overflowing_mul(x);
            if !(!ok && val <= a) {
                return false;
            }
            t = val;
        }
        true
    };
    let mut ok = 1;
    let mut ng = 2;
    while valid(ng) {
        ok = ng;
        ng *= 2;
    }
    while ng - ok > 1 {
        let mid = ok + (ng - ok) / 2;
        if valid(mid) {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    ok
}
// ---------- end kth root ----------

use std::cmp::*;

type Map = std::collections::BTreeMap<u64, (u64, u64)>;

fn calc(n: u64, map: &mut Map) -> (u64, u64) {
    if n == 0 {
        return (0, 0);
    }
    if let Some(v) = map.get(&n) {
        return *v;
    }
    let p = kth_root(n, 3);
    let v = p.pow(3);
    let (a, b) = calc(v - 1, map);
    let (c, d) = calc(n - v, map);
    let (c, d) = (c + 1, d + v);
    let ans = max((a, b), (c, d));
    map.insert(n, ans);
    ans
}

fn run() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let m: u64 = s.trim().parse().unwrap();
    let mut memo = Map::new();
    let (cnt, x) = calc(m, &mut memo);
    println!("{} {}", cnt, x);
}

fn main() {
    run();
}


The only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes $$$n$$$ pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $$$i$$$-th picture has a non-negative weight $$$w_i$$$, and the probability of the $$$i$$$-th picture being displayed is $$$\frac{w_i}{\sum_{j=1}^nw_j}$$$. That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $$$1$$$ to its weight; otherwise, she would subtract $$$1$$$ from its weight.Nauuo will visit the website $$$m$$$ times. She wants to know the expected weight of each picture after all the $$$m$$$ visits modulo $$$998244353$$$. Can you help her?The expected weight of the $$$i$$$-th picture can be denoted by $$$\frac {q_i} {p_i}$$$ where $$$\gcd(p_i,q_i)=1$$$, you need to print an integer $$$r_i$$$ satisfying $$$0\le r_i<998244353$$$ and $$$r_i\cdot p_i\equiv q_i\pmod{998244353}$$$. It can be proved that such $$$r_i$$$ exists and is unique.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n\le 2\cdot 10^5$$$, $$$1\le m\le 3000$$$) — the number of pictures and the number of visits to the website. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$a_i$$$ is either $$$0$$$ or $$$1$$$) — if $$$a_i=0$$$ , Nauuo does not like the $$$i$$$-th picture; otherwise Nauuo likes the $$$i$$$-th picture. It is guaranteed that there is at least one picture which Nauuo likes. The third line contains $$$n$$$ positive integers $$$w_1,w_2,\ldots,w_n$$$ ($$$w_i \geq 1$$$) — the initial weights of the pictures. It is guaranteed that the sum of all the initial weights does not exceed $$$998244352-m$$$.

The output contains $$$n$$$ integers $$$r_1,r_2,\ldots,r_n$$$ — the expected weights modulo $$$998244353$$$.

NoteIn the first example, if the only visit shows the first picture with a probability of $$$\frac 2 3$$$, the final weights are $$$(1,1)$$$; if the only visit shows the second picture with a probability of $$$\frac1 3$$$, the final weights are $$$(2,2)$$$.So, both expected weights are $$$\frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3$$$ .Because $$$332748119\cdot 3\equiv 4\pmod{998244353}$$$, you need to print $$$332748119$$$ instead of $$$\frac4 3$$$ or $$$1.3333333333$$$.In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, $$$w_1$$$ will be increased by $$$1$$$.So, the expected weight is $$$1+2=3$$$.Nauuo is very naughty so she didn't give you any hint of the third example.

// https://codeforces.com/contest/1172/problem/C2
//
#![allow(unused_imports)]
use std::io::*;
use std::io::Write;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

#[allow(unused_macros)]
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)*}
    };
}

#[allow(unused_macros)]
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)*}
    };

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

#[allow(unused_macros)]
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, [ next / $t:tt ]) => {
        {
            let len = read_value!($iter, usize);
            (0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
        }
    };

    ($iter:expr, switch) => {
        {
            let ty = read_value!($iter, i32);
            if ty == 1 {
                vec![ty, read_value!($iter, i32), read_value!($iter, i32)]
            } else if ty == 2 {
                vec![ty, read_value!($iter, i32)]
            } else {
                vec![ty, read_value!($iter, i32)]
            }
        }
    };

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

#[allow(unused_macros)]
macro_rules! dvec {
    ($t:expr ; $len:expr) => {
        vec![$t; $len]
    };

    ($t:expr ; $len:expr, $($rest:expr),*) => {
        vec![dvec!($t; $($rest),*); $len]
    };
}

#[allow(unused_macros)]
macro_rules! ifv {
    ($t:expr, $a:expr, $b: expr) => {
        if $t { $a } else { $b }
    }
}

#[allow(unused_macros)]
macro_rules! fill {
    ($t:expr, $v:expr) => {
        for i in 0..$t.len() {
            $t[i] = $v;
        }
    };
}

#[allow(unused_macros)]
macro_rules! join {
    ($t:expr, $glue:expr) => {
        $t.into_iter().map(|w| w.to_string()).collect::<Vec<_>>().join($glue)
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

const MOD: i64 = 998244353;

fn inv(a: i64) -> i64 {
    pow(a, MOD - 2)
}

fn pow(a: i64, p: i64) -> i64 {
    let mut p = p;
    let mut aa = a;
    let mut ret = 1;
    while p >= 1 {
        if p & 1 == 1 {
            ret *= aa;
            ret %= MOD;
        }
        p >>= 1;
        aa = aa * aa % MOD;
    }
    ret
}

fn main() {
    input! {
        n: usize, m: usize,
        mut a: [i64; n],
        w: [i64; n]
    };

    let mut like_weight = 0;
    let mut dislike_weight = 0;
    for i in 0..n {
        if a[i] == 1 {
            like_weight += w[i];
        } else {
            dislike_weight += w[i];
        }
    }

    let GETA = 3100;
    let mut denom_pm = vec![0; GETA*2];
    for i in 0..GETA*2 {
        let w = i as i64 + like_weight + dislike_weight;
        denom_pm[i] = ifv!(w >= GETA as i64, inv(w-GETA as i64), 0);
    }
    let mut quot = |l: usize, d: usize, num: i64| ifv!(num <= 0, 0, num * denom_pm[GETA+l-d] % MOD);

    let mut dp = dvec!(0; 2, m+1, m+1);
    for i in 0..m+1 {
        dp[0][i][m-i] = 1;
        dp[1][i][m-i] = 1;
    }
    for i in (0..m+1).rev() {
        for j in (0..m+1).rev() {
            if i+j >= m {
                continue;
            }
            let mut total0 = 0;
            let mut total1 = 0;

            if i+1 <= m {
                total0 += dp[0][i+1][j] * quot(i, j, like_weight+(i as i64)+1);
                total1 += dp[1][i+1][j] * quot(i, j, like_weight+(i as i64));
            }
            if j+1 <= m {
                total0 += dp[0][i][j+1] * quot(i, j, dislike_weight-(j as i64));
                total1 += dp[1][i][j+1] * quot(i, j, dislike_weight-(j as i64)-1);
            }
            dp[0][i][j] = total0 % MOD;
            dp[1][i][j] = total1 % MOD;
        }
    }

    let out = stdout();
    let mut out = BufWriter::new(out.lock());
    for i in 0..n {
        if a[i] == 1 {
            writeln!(out, "{}", dp[0][0][0] * w[i] % MOD);
        } else {
            writeln!(out, "{}", dp[1][0][0] * w[i] % MOD);
        }
    }
}


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


As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?

The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≤ ai ≤ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.

Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.

NoteThe first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.

macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

#[allow(unused_macros)]
macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

use std::io::Write;

fn solve(writer: &mut std::io::BufWriter<std::io::Stdout>) {
    let (n, m) = parse_line!(usize, usize);
    let mut a = Vec::new();
    let mut pro = vec![0; n];
    let mut con = vec![0; n];
    let mut cons = 0;
    for _ in 0..n {
        let x = parse_line!(i32);
        a.push(x);
        if x > 0 {
            pro[(x - 1) as usize] += 1;
        }else{
            con[(-x - 1) as usize] += 1;
            cons += 1;
        }
    }
    let mut candidates = vec![false; n];
    let mut single = false;
    let mut more = false;
    for i in 0..n {
        if pro[i] + cons - con[i] == m {
            more = single;
            single = true;
            candidates[i] = true;
        }
    }
    for x in a {
        if x > 0 {
            if candidates[(x - 1) as usize] {
                if single && !more {
                    writeln!(writer, "Truth").unwrap();
                }else{
                    writeln!(writer, "Not defined").unwrap();
                }
            }else{
                writeln!(writer, "Lie").unwrap();
            }
        }else{
            if !candidates[(-x - 1) as usize] {
                writeln!(writer, "Truth").unwrap();
            }else{
                if single && !more {
                    writeln!(writer, "Lie").unwrap();
                }else{
                    writeln!(writer, "Not defined").unwrap();
                }
            }
        }
    }
}

fn main() {
    let mut writer = std::io::BufWriter::new(std::io::stdout());
    let tests = 1; // parse_line!(usize);
    for _ in 0..tests {
        solve(&mut writer);
    }
}

[{'input': '1 1\r\n+1\r\n', 'output': ['Truth\r\n']}, {'input': '3 2\r\n-1\r\n-2\r\n-3\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '4 1\r\n+2\r\n-3\r\n+4\r\n-1\r\n', 'output': ['Lie\r\nNot defined\r\nLie\r\nNot defined\r\n']}, {'input': '1 0\r\n-1\r\n', 'output': ['Lie\r\n']}, {'input': '2 2\r\n+1\r\n+1\r\n', 'output': ['Truth\r\nTruth\r\n']}, {'input': '2 1\r\n+2\r\n+1\r\n', 'output': ['Not defined\r\nNot defined\r\n']}, {'input': '2 0\r\n-2\r\n-2\r\n', 'output': ['Lie\r\nLie\r\n']}, {'input': '3 1\r\n+2\r\n+3\r\n+3\r\n', 'output': ['Truth\r\nLie\r\nLie\r\n']}, {'input': '6 3\r\n+5\r\n+5\r\n+5\r\n+1\r\n+1\r\n+1\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '4 3\r\n-4\r\n-3\r\n-1\r\n-3\r\n', 'output': ['Not defined\r\nTruth\r\nNot defined\r\nTruth\r\n']}, {'input': '10 4\r\n-8\r\n+1\r\n-6\r\n-10\r\n+5\r\n-6\r\n-8\r\n-8\r\n-4\r\n-8\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 5\r\n-4\r\n+4\r\n+4\r\n-9\r\n-9\r\n-4\r\n-4\r\n+2\r\n-9\r\n-4\r\n', 'output': ['Lie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '7 2\r\n+5\r\n+5\r\n+5\r\n-2\r\n+1\r\n-5\r\n-6\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nNot defined\r\nLie\r\nTruth\r\nNot defined\r\n']}, {'input': '7 4\r\n+7\r\n-3\r\n-3\r\n-4\r\n+3\r\n+3\r\n+3\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '6 3\r\n-6\r\n-1\r\n+5\r\n+1\r\n+6\r\n+1\r\n', 'output': ['Truth\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\nNot defined\r\n']}, {'input': '5 3\r\n-2\r\n+2\r\n+2\r\n-3\r\n+5\r\n', 'output': ['Not defined\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\n']}, {'input': '3 0\r\n-2\r\n-2\r\n-2\r\n', 'output': ['Lie\r\nLie\r\nLie\r\n']}, {'input': '5 3\r\n-1\r\n-1\r\n-4\r\n+1\r\n-4\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\n']}, {'input': '9 6\r\n+2\r\n+7\r\n+7\r\n-1\r\n-4\r\n+7\r\n-7\r\n+7\r\n+5\r\n', 'output': ['Lie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '43 18\r\n-14\r\n-28\r\n+16\r\n+10\r\n+25\r\n-30\r\n+25\r\n+30\r\n+25\r\n+25\r\n+25\r\n+25\r\n-25\r\n+22\r\n+3\r\n-17\r\n+16\r\n-25\r\n+10\r\n+14\r\n+41\r\n+25\r\n-25\r\n+33\r\n+24\r\n-23\r\n-25\r\n+25\r\n-22\r\n+29\r\n+28\r\n-25\r\n-25\r\n-29\r\n+11\r\n+26\r\n-25\r\n+25\r\n+10\r\n+1\r\n-20\r\n-17\r\n+23\r\n', 'output': ['Truth\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nLie\r\nNot defined\r\nNot defined\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '28 12\r\n+10\r\n-7\r\n+17\r\n-20\r\n+7\r\n-7\r\n+13\r\n-21\r\n-7\r\n-7\r\n-18\r\n+7\r\n+7\r\n+3\r\n+6\r\n+14\r\n+7\r\n-24\r\n-21\r\n-7\r\n-7\r\n+4\r\n+7\r\n-7\r\n+21\r\n-7\r\n-26\r\n+7\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': '17 9\r\n-6\r\n+16\r\n+5\r\n+16\r\n-17\r\n+17\r\n-11\r\n+5\r\n+14\r\n+5\r\n-8\r\n-5\r\n+6\r\n-2\r\n-11\r\n+4\r\n+17\r\n', 'output': ['Truth\r\nNot defined\r\nNot defined\r\nNot defined\r\nTruth\r\nLie\r\nTruth\r\nNot defined\r\nLie\r\nNot defined\r\nTruth\r\nNot defined\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\n']}, {'input': '14 3\r\n+14\r\n+12\r\n-9\r\n+9\r\n-9\r\n-9\r\n+8\r\n+9\r\n+2\r\n+1\r\n-13\r\n-9\r\n+13\r\n+3\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\n']}, {'input': '10 4\r\n-9\r\n-8\r\n-5\r\n-9\r\n-7\r\n-9\r\n-9\r\n-9\r\n-4\r\n-9\r\n', 'output': ['Lie\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 5\r\n-10\r\n-10\r\n-10\r\n-5\r\n-1\r\n+10\r\n-3\r\n-10\r\n-9\r\n-10\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 4\r\n-3\r\n-3\r\n-3\r\n-3\r\n-3\r\n-2\r\n-2\r\n-6\r\n-7\r\n-3\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '10 6\r\n-9\r\n-7\r\n-5\r\n-5\r\n-4\r\n-2\r\n-8\r\n-5\r\n-5\r\n-9\r\n', 'output': ['Truth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 4\r\n-8\r\n-2\r\n-8\r\n+1\r\n-4\r\n-8\r\n-2\r\n-8\r\n-8\r\n-1\r\n', 'output': ['Lie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 2\r\n-8\r\n+10\r\n+1\r\n+8\r\n+4\r\n+8\r\n+6\r\n-8\r\n+10\r\n+1\r\n', 'output': ['Not defined\r\nLie\r\nLie\r\nNot defined\r\nLie\r\nNot defined\r\nLie\r\nNot defined\r\nLie\r\nLie\r\n']}, {'input': '10 3\r\n+9\r\n+3\r\n+8\r\n+3\r\n+6\r\n-3\r\n+6\r\n+8\r\n+3\r\n+7\r\n', 'output': ['Lie\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nNot defined\r\nLie\r\n']}, {'input': '10 8\r\n-2\r\n+9\r\n+9\r\n-4\r\n+9\r\n+9\r\n+4\r\n-9\r\n-3\r\n+9\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': '10 7\r\n-4\r\n+6\r\n+4\r\n+9\r\n+6\r\n+6\r\n+6\r\n+6\r\n+6\r\n+2\r\n', 'output': ['Truth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '10 4\r\n+3\r\n+5\r\n+6\r\n+10\r\n+5\r\n+5\r\n+6\r\n+8\r\n+5\r\n+6\r\n', 'output': ['Lie\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '10 7\r\n-6\r\n-10\r\n-3\r\n-1\r\n-3\r\n-7\r\n-2\r\n-7\r\n-7\r\n-3\r\n', 'output': ['Truth\r\nTruth\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nTruth\r\nNot defined\r\nNot defined\r\nNot defined\r\n']}, {'input': '10 5\r\n-4\r\n-4\r\n-1\r\n-5\r\n-7\r\n-4\r\n-4\r\n-4\r\n-1\r\n-7\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\n']}, {'input': '10 5\r\n-9\r\n-7\r\n-6\r\n-3\r\n-10\r\n-10\r\n-10\r\n-10\r\n-10\r\n-2\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 3\r\n-10\r\n-10\r\n-10\r\n-3\r\n-10\r\n-10\r\n-10\r\n-8\r\n-4\r\n-10\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nLie\r\n']}, {'input': '10 5\r\n-8\r\n-8\r\n-4\r\n-9\r\n-10\r\n-2\r\n-9\r\n-8\r\n-8\r\n-8\r\n', 'output': ['Lie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\n']}, {'input': '10 5\r\n+7\r\n+8\r\n+9\r\n+1\r\n+7\r\n+7\r\n+7\r\n+6\r\n+6\r\n+7\r\n', 'output': ['Truth\r\nLie\r\nLie\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 5\r\n+2\r\n+2\r\n+2\r\n+2\r\n+9\r\n+10\r\n+8\r\n+7\r\n+4\r\n+2\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nLie\r\nLie\r\nLie\r\nTruth\r\n']}, {'input': '10 9\r\n+7\r\n+7\r\n+7\r\n+7\r\n+7\r\n+7\r\n+5\r\n+7\r\n+7\r\n+7\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nTruth\r\nTruth\r\n']}, {'input': '10 3\r\n+10\r\n+2\r\n+10\r\n+9\r\n+1\r\n+9\r\n+4\r\n+9\r\n+3\r\n+2\r\n', 'output': ['Lie\r\nLie\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nTruth\r\nLie\r\nLie\r\n']}, {'input': '10 6\r\n+10\r\n+10\r\n+10\r\n+3\r\n+10\r\n+10\r\n+6\r\n+6\r\n+10\r\n+8\r\n', 'output': ['Truth\r\nTruth\r\nTruth\r\nLie\r\nTruth\r\nTruth\r\nLie\r\nLie\r\nTruth\r\nLie\r\n']}, {'input': '3 2\r\n-1\r\n+2\r\n+3\r\n', 'output': ['Truth\r\nNot defined\r\nNot defined\r\n']}]