QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#853535#9731. Fuzzy Rankingucup-team296#TL 1413ms44248kbRust31.1kb2025-01-11 17:24:322025-01-11 17:24:34

Judging History

This is the latest submission verdict.

  • [2025-01-11 17:24:34]
  • Judged
  • Verdict: TL
  • Time: 1413ms
  • Memory: 44248kb
  • [2025-01-11 17:24:32]
  • Submitted

answer

// https://contest.ucup.ac/contest/1893/problem/9731
pub mod solution {
//{"name":"F. Fuzzy Ranking","group":"Universal Cup - The 3rd Universal Cup. Stage 25: Hangzhou","url":"https://contest.ucup.ac/contest/1893/problem/9731","interactive":false,"timeLimit":1000,"tests":[{"input":"2\n5 2 2\n1 2 3 4 5\n5 4 3 2 1\n1 0 2\n1 2 1\n5 3 3\n1 2 3 4 5\n1 3 2 4 5\n1 2 3 5 4\n0 0 2\n0 2 3\n1 0 3\n","output":"3\n10\n1\n1\n2\n"}],"testType":"single","input":{"type":"stdin","fileName":null,"pattern":null},"output":{"type":"stdout","fileName":null,"pattern":null},"languages":{"java":{"taskClass":"FFuzzyRanking"}}}

use std::collections::VecDeque;

use crate::algo_lib::collections::array_2d::Array2D;
#[allow(unused)]
use crate::dbg;
use crate::algo_lib::io::input::Input;
use crate::algo_lib::io::output::Output;
use crate::algo_lib::misc::binary_search::binary_search_first_true;
use crate::algo_lib::misc::rand::Random;
use crate::algo_lib::misc::vec_apply_delta::ApplyDelta;

#[derive(Clone, Copy, Debug)]
struct Segment {
    l: usize,
    r: usize,
}

impl Segment {
    fn new(l: usize, r: usize) -> Self {
        Self { l, r }
    }
}

struct Solver {
    segs: Vec<Vec<Segment>>,
    dp: Vec<Vec<i64>>,
}

impl Solver {
    fn new(perms: &[Vec<usize>]) -> Self {
        let k = perms.len();
        let n = perms[0].len();
        let mut g = vec![vec![]; n];
        for i in 0..k {
            for j in 0..n - 1 {
                g[perms[i][j + 1]].push(perms[i][j]);
            }
        }
        let mut segs: Vec<Vec<Segment>> = vec![vec![]; k];
        let mut dp = vec![vec![0i64; n + 1]; k];
        for i in 0..k {
            let mut seen = vec![false; n];
            let mut perm_inv = vec![0; n];
            for pos in 0..n {
                perm_inv[perms[i][pos]] = pos;
            }
            for pos in 0..n {
                let v = perms[i][pos];
                if seen[v] {
                    continue;
                }
                let mut max_pos = pos;
                let mut q = VecDeque::new();
                q.push_back(v);
                while let Some(v) = q.pop_front() {
                    seen[v] = true;
                    for &u in &g[v] {
                        if !seen[u] {
                            seen[u] = true;
                            q.push_back(u);
                            max_pos = max_pos.max(perm_inv[u]);
                        }
                    }
                }
                segs[i].push(Segment::new(pos, max_pos + 1));
            }
            {
                let mut sum_len = 0;
                for s in segs[i].iter() {
                    // dbg!(s);
                    sum_len += s.r - s.l;
                    for pos in s.l..s.r {
                        dp[i][pos + 1] = dp[i][pos];
                        dp[i][pos + 1] += (pos - s.l) as i64;
                    }
                }
                assert_eq!(sum_len, n);
            }
        }
        Self { segs, dp }
    }

    fn calc(&self, id: usize, mut l: usize, r: usize) -> i64 {
        let segs = &self.segs[id];
        let first_seg = binary_search_first_true(0..segs.len(), |i| segs[i].r > l);
        let mut v = 0;
        let first_seg_end = segs[first_seg].r.min(r);
        v += calc(l, first_seg_end);
        l = first_seg_end;
        if l != r {
            v += self.dp[id][r] - self.dp[id][l];
        }
        v
    }
}

fn solve(input: &mut Input, out: &mut Output, _test_case: usize) {
    let tc = input.usize();
    for _ in 0..tc {
        let n = input.usize();
        let k = input.usize();
        let q = input.usize();
        let mut perms = vec![];
        for _ in 0..k {
            let p = input.vec::<usize>(n).sub_from_all(1);
            perms.push(p);
        }
        let mut solver = Solver::new(&perms);

        let mut prev_v = 0;
        for _ in 0..q {
            let id = (input.i64() + prev_v) % k as i64;
            let l = (input.i64() + prev_v) % n as i64;
            let r = (input.i64() + prev_v) % n as i64;
            let id = id as usize;
            let mut l = l as usize;
            let r = r as usize + 1;
            assert!(l < r);
            let v = solver.calc(id, l, r);
            out.println(v);
            prev_v = v;
        }
    }
}

fn calc(l: usize, r: usize) -> i64 {
    let r = r - 1;
    assert!(l <= r);
    let n = (r - l) as i64;
    n * (n + 1) / 2
}

fn stress() {
    const MX: usize = 10;
    for it in 418.. {
        dbg!(it);

        let mut rnd = Random::new(it);
        let k = rnd.gen(1..MX);
        let n = rnd.gen(1..MX);
        let mut perms = vec![];
        let mut g = Array2D::new(false, n, n);
        for _ in 0..k {
            let p = rnd.gen_permutation(n);
            dbg!(p);
            perms.push(p);
        }
        for i in 0..k {
            for j in 0..n - 1 {
                g[perms[i][j]][perms[i][j + 1]] = true;
            }
        }
        for i in 0..n {
            for j in 0..n {
                for k in 0..n {
                    if g[j][i] && g[i][k] {
                        g[j][k] = true;
                    }
                }
            }
        }
        let solver = Solver::new(&perms);
        for _ in 0..100 {
            let id = rnd.gen(0..k);
            let l = rnd.gen(0..n);
            let r = rnd.gen(l + 1..n + 1);
            let mut real_ans = 0;
            for p1 in l..r {
                for p2 in p1 + 1..r {
                    if g[perms[id][p1]][perms[id][p2]] && g[perms[id][p2]][perms[id][p1]] {
                        real_ans += 1;
                    }
                }
            }
            let my_ans = solver.calc(id, l, r);
            dbg!(id, l, r);
            dbg!(real_ans, my_ans);
            assert_eq!(real_ans, my_ans);
        }
    }
}

pub(crate) fn run(mut input: Input, mut output: Output) -> bool {
    solve(&mut input, &mut output, 1);
    output.flush();
    true
}

}
pub mod algo_lib {
#![feature(test)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::type_complexity)]

pub mod collections {
pub mod array_2d {
use crate::algo_lib::io::output::Output;
use crate::algo_lib::io::output::Writable;
use crate::algo_lib::misc::num_traits::Number;
use std::io::Write;
use std::ops::Index;
use std::ops::IndexMut;
use std::ops::Mul;

// TODO: implement good Debug
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Array2D<T> {
    rows: usize,
    cols: usize,
    v: Vec<T>,
}

pub struct Iter<'a, T> {
    array: &'a Array2D<T>,
    row: usize,
    col: usize,
}

impl<T> Array2D<T>
where
    T: Clone,
{
    #[allow(unused)]
    pub fn new(empty: T, rows: usize, cols: usize) -> Self {
        Self {
            rows,
            cols,
            v: vec![empty; rows * cols],
        }
    }

    pub fn new_f(rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> T) -> Self {
        let mut v = Vec::with_capacity(rows * cols);
        for r in 0..rows {
            for c in 0..cols {
                v.push(f(r, c));
            }
        }
        Self { rows, cols, v }
    }

    pub fn rows(&self) -> usize {
        self.rows
    }

    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.rows()
    }

    pub fn cols(&self) -> usize {
        self.cols
    }

    pub fn swap(&mut self, row1: usize, row2: usize) {
        assert!(row1 < self.rows);
        assert!(row2 < self.rows);
        if row1 != row2 {
            for col in 0..self.cols {
                self.v.swap(row1 * self.cols + col, row2 * self.cols + col);
            }
        }
    }

    pub fn transpose(&self) -> Self {
        Self::new_f(self.cols, self.rows, |r, c| self[c][r].clone())
    }

    pub fn iter(&self) -> Iter<T> {
        Iter {
            array: self,
            row: 0,
            col: 0,
        }
    }

    pub fn pref_sum(&self) -> Self
    where
        T: Number,
    {
        let mut res = Self::new(T::ZERO, self.rows + 1, self.cols + 1);
        for i in 0..self.rows {
            for j in 0..self.cols {
                let value = self[i][j] + res[i][j + 1] + res[i + 1][j] - res[i][j];
                res[i + 1][j + 1] = value;
            }
        }
        res
    }
}

impl<T> Writable for Array2D<T>
where
    T: Writable,
{
    fn write(&self, output: &mut Output) {
        for r in 0..self.rows {
            self[r].write(output);
            output.write_all(&[b'\n']).unwrap();
        }
    }
}

impl<T> Index<usize> for Array2D<T> {
    type Output = [T];

    fn index(&self, index: usize) -> &Self::Output {
        &self.v[(index) * self.cols..(index + 1) * self.cols]
    }
}

impl<T> IndexMut<usize> for Array2D<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.v[(index) * self.cols..(index + 1) * self.cols]
    }
}

impl<T> Mul for &Array2D<T>
where
    T: Number,
{
    type Output = Array2D<T>;

    fn mul(self, rhs: Self) -> Self::Output {
        let n = self.rows;
        let m = self.cols;
        assert_eq!(m, rhs.rows);
        let k2 = rhs.cols;
        let mut res = Array2D::new(T::ZERO, n, k2);
        for i in 0..n {
            for j in 0..m {
                for k in 0..k2 {
                    res[i][k] += self[i][j] * rhs[j][k];
                }
            }
        }
        res
    }
}

impl<T> Array2D<T>
where
    T: Number,
{
    pub fn pown(&self, pw: usize) -> Self {
        assert_eq!(self.rows, self.cols);
        let n = self.rows;
        if pw == 0 {
            Self::new_f(n, n, |r, c| if r == c { T::ONE } else { T::ZERO })
        } else if pw == 1 {
            self.clone()
        } else {
            let half = self.pown(pw / 2);
            let half2 = &half * &half;
            if pw & 1 == 0 {
                half2
            } else {
                &half2 * self
            }
        }
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.col == self.array.cols {
            self.col = 0;
            self.row += 1;
        }
        if self.row >= self.array.rows {
            return None;
        }
        let elem = &self.array[self.row][self.col];
        self.col += 1;
        Some(elem)
    }
}
}
}
pub mod io {
pub mod input {
use std::fmt::Debug;
use std::io::Read;
use std::marker::PhantomData;
use std::path::Path;
use std::str::FromStr;

pub struct Input {
    input: Box<dyn Read>,
    buf: Vec<u8>,
    at: usize,
    buf_read: usize,
}

macro_rules! read_integer_fun {
    ($t:ident) => {
        #[allow(unused)]
        pub fn $t(&mut self) -> $t {
            self.read_integer()
        }
    };
}

impl Input {
    const DEFAULT_BUF_SIZE: usize = 4096;

    ///
    /// Using with stdin:
    /// ```no_run
    /// use algo_lib::io::input::Input;
    /// let stdin = std::io::stdin();
    /// let input = Input::new(Box::new(stdin));
    /// ```
    ///
    /// For read files use ``new_file`` instead.
    ///
    ///
    pub fn new(input: Box<dyn Read>) -> Self {
        Self {
            input,
            buf: vec![0; Self::DEFAULT_BUF_SIZE],
            at: 0,
            buf_read: 0,
        }
    }

    pub fn new_stdin() -> Self {
        let stdin = std::io::stdin();
        Self::new(Box::new(stdin))
    }

    pub fn new_file<P: AsRef<Path>>(path: P) -> Self {
        let file = std::fs::File::open(&path)
            .unwrap_or_else(|_| panic!("Can't open file: {:?}", path.as_ref().as_os_str()));
        Self::new(Box::new(file))
    }

    pub fn new_with_size(input: Box<dyn Read>, buf_size: usize) -> Self {
        Self {
            input,
            buf: vec![0; buf_size],
            at: 0,
            buf_read: 0,
        }
    }

    pub fn new_file_with_size<P: AsRef<Path>>(path: P, buf_size: usize) -> Self {
        let file = std::fs::File::open(&path)
            .unwrap_or_else(|_| panic!("Can't open file: {:?}", path.as_ref().as_os_str()));
        Self::new_with_size(Box::new(file), buf_size)
    }

    pub fn get(&mut self) -> Option<u8> {
        if self.refill_buffer() {
            let res = self.buf[self.at];
            self.at += 1;
            Some(res)
        } else {
            None
        }
    }

    pub fn peek(&mut self) -> Option<u8> {
        if self.refill_buffer() {
            Some(self.buf[self.at])
        } else {
            None
        }
    }

    pub fn skip_whitespace(&mut self) {
        while let Some(b) = self.peek() {
            if !char::from(b).is_whitespace() {
                return;
            }
            self.get();
        }
    }

    pub fn next_token(&mut self) -> Option<Vec<u8>> {
        self.skip_whitespace();
        let mut res = Vec::new();
        while let Some(c) = self.get() {
            if char::from(c).is_whitespace() {
                break;
            }
            res.push(c);
        }
        if res.is_empty() {
            None
        } else {
            Some(res)
        }
    }

    //noinspection RsSelfConvention
    pub fn is_exhausted(&mut self) -> bool {
        self.peek().is_none()
    }

    pub fn has_more_elements(&mut self) -> bool {
        !self.is_exhausted()
    }

    pub fn read<T: Readable>(&mut self) -> T {
        T::read(self)
    }

    pub fn vec<T: Readable>(&mut self, size: usize) -> Vec<T> {
        let mut res = Vec::with_capacity(size);
        for _ in 0usize..size {
            res.push(self.read());
        }
        res
    }

    pub fn string_vec(&mut self, size: usize) -> Vec<Vec<u8>> {
        let mut res = Vec::with_capacity(size);
        for _ in 0usize..size {
            res.push(self.string());
        }
        res
    }

    pub fn read_line(&mut self) -> String {
        let mut res = String::new();
        while let Some(c) = self.get() {
            if c == b'\n' {
                break;
            }
            if c == b'\r' {
                if self.peek() == Some(b'\n') {
                    self.get();
                }
                break;
            }
            res.push(c.into());
        }
        res
    }

    #[allow(clippy::should_implement_trait)]
    pub fn into_iter<T: Readable>(self) -> InputIterator<T> {
        InputIterator {
            input: self,
            phantom: Default::default(),
        }
    }

    fn read_integer<T: FromStr + Debug>(&mut self) -> T
    where
        <T as FromStr>::Err: Debug,
    {
        let res = self.read_string();
        res.parse::<T>().unwrap()
    }

    fn read_string(&mut self) -> String {
        match self.next_token() {
            None => {
                panic!("Input exhausted");
            }
            Some(res) => unsafe { String::from_utf8_unchecked(res) },
        }
    }

    pub fn string_as_string(&mut self) -> String {
        self.read_string()
    }

    pub fn string(&mut self) -> Vec<u8> {
        self.read_string().into_bytes()
    }

    fn read_char(&mut self) -> char {
        self.skip_whitespace();
        self.get().unwrap().into()
    }

    fn read_float(&mut self) -> f64 {
        self.read_string().parse().unwrap()
    }

    pub fn f64(&mut self) -> f64 {
        self.read_float()
    }

    fn refill_buffer(&mut self) -> bool {
        if self.at == self.buf_read {
            self.at = 0;
            self.buf_read = self.input.read(&mut self.buf).unwrap();
            self.buf_read != 0
        } else {
            true
        }
    }

    read_integer_fun!(i32);
    read_integer_fun!(i64);
    read_integer_fun!(i128);
    read_integer_fun!(u32);
    read_integer_fun!(u64);
    read_integer_fun!(usize);
}

pub trait Readable {
    fn read(input: &mut Input) -> Self;
}

impl Readable for String {
    fn read(input: &mut Input) -> Self {
        input.read_string()
    }
}

impl Readable for char {
    fn read(input: &mut Input) -> Self {
        input.read_char()
    }
}

impl Readable for f64 {
    fn read(input: &mut Input) -> Self {
        input.read_string().parse().unwrap()
    }
}

impl Readable for f32 {
    fn read(input: &mut Input) -> Self {
        input.read_string().parse().unwrap()
    }
}

impl<T: Readable> Readable for Vec<T> {
    fn read(input: &mut Input) -> Self {
        let size = input.read();
        input.vec(size)
    }
}

pub struct InputIterator<T: Readable> {
    input: Input,
    phantom: PhantomData<T>,
}

impl<T: Readable> Iterator for InputIterator<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.input.skip_whitespace();
        self.input.peek().map(|_| self.input.read())
    }
}

macro_rules! read_integer {
    ($t:ident) => {
        impl Readable for $t {
            fn read(input: &mut Input) -> Self {
                input.read_integer()
            }
        }
    };
}

read_integer!(i8);
read_integer!(i16);
read_integer!(i32);
read_integer!(i64);
read_integer!(i128);
read_integer!(isize);
read_integer!(u8);
read_integer!(u16);
read_integer!(u32);
read_integer!(u64);
read_integer!(u128);
read_integer!(usize);
}
pub mod output {
use std::io::Write;

pub struct Output {
    output: Box<dyn Write>,
    buf: Vec<u8>,
    at: usize,
    auto_flush: bool,
}

impl Output {
    const DEFAULT_BUF_SIZE: usize = 4096;

    pub fn new(output: Box<dyn Write>) -> Self {
        Self {
            output,
            buf: vec![0; Self::DEFAULT_BUF_SIZE],
            at: 0,
            auto_flush: false,
        }
    }

    pub fn new_stdout() -> Self {
        let stdout = std::io::stdout();
        Self::new(Box::new(stdout))
    }

    pub fn new_file(path: impl AsRef<std::path::Path>) -> Self {
        let file = std::fs::File::create(path).unwrap();
        Self::new(Box::new(file))
    }

    pub fn new_with_auto_flush(output: Box<dyn Write>) -> Self {
        Self {
            output,
            buf: vec![0; Self::DEFAULT_BUF_SIZE],
            at: 0,
            auto_flush: true,
        }
    }

    pub fn flush(&mut self) {
        if self.at != 0 {
            self.output.write_all(&self.buf[..self.at]).unwrap();
            self.at = 0;
            self.output.flush().expect("Couldn't flush output");
        }
    }

    pub fn print<T: Writable>(&mut self, s: T) {
        s.write(self);
    }

    pub fn println<T: Writable>(&mut self, s: T) {
        s.write(self);
        self.put(b'\n');
    }

    pub fn put(&mut self, b: u8) {
        self.buf[self.at] = b;
        self.at += 1;
        if self.at == self.buf.len() {
            self.flush();
        }
    }

    pub fn maybe_flush(&mut self) {
        if self.auto_flush {
            self.flush();
        }
    }

    pub fn print_per_line<T: Writable>(&mut self, arg: &[T]) {
        for i in arg {
            i.write(self);
            self.put(b'\n');
        }
    }

    pub fn print_iter<T: Writable, I: Iterator<Item = T>>(&mut self, iter: I) {
        let mut first = true;
        for e in iter {
            if first {
                first = false;
            } else {
                self.put(b' ');
            }
            e.write(self);
        }
    }

    pub fn print_iter_ref<'a, T: 'a + Writable, I: Iterator<Item = &'a T>>(&mut self, iter: I) {
        let mut first = true;
        for e in iter {
            if first {
                first = false;
            } else {
                self.put(b' ');
            }
            e.write(self);
        }
    }
}

impl Write for Output {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let mut start = 0usize;
        let mut rem = buf.len();
        while rem > 0 {
            let len = (self.buf.len() - self.at).min(rem);
            self.buf[self.at..self.at + len].copy_from_slice(&buf[start..start + len]);
            self.at += len;
            if self.at == self.buf.len() {
                self.flush();
            }
            start += len;
            rem -= len;
        }
        if self.auto_flush {
            self.flush();
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.flush();
        Ok(())
    }
}

pub trait Writable {
    fn write(&self, output: &mut Output);
}

impl Writable for &str {
    fn write(&self, output: &mut Output) {
        output.write_all(self.as_bytes()).unwrap();
    }
}

impl Writable for String {
    fn write(&self, output: &mut Output) {
        output.write_all(self.as_bytes()).unwrap();
    }
}

impl Writable for char {
    fn write(&self, output: &mut Output) {
        output.put(*self as u8);
    }
}

impl<T: Writable> Writable for [T] {
    fn write(&self, output: &mut Output) {
        output.print_iter_ref(self.iter());
    }
}

impl<T: Writable> Writable for Vec<T> {
    fn write(&self, output: &mut Output) {
        self[..].write(output);
    }
}

macro_rules! write_to_string {
    ($t:ident) => {
        impl Writable for $t {
            fn write(&self, output: &mut Output) {
                self.to_string().write(output);
            }
        }
    };
}

write_to_string!(u8);
write_to_string!(u16);
write_to_string!(u32);
write_to_string!(u64);
write_to_string!(u128);
write_to_string!(usize);
write_to_string!(i8);
write_to_string!(i16);
write_to_string!(i32);
write_to_string!(i64);
write_to_string!(i128);
write_to_string!(isize);
write_to_string!(f32);
write_to_string!(f64);

impl<T: Writable, U: Writable> Writable for (T, U) {
    fn write(&self, output: &mut Output) {
        self.0.write(output);
        output.put(b' ');
        self.1.write(output);
    }
}

impl<T: Writable, U: Writable, V: Writable> Writable for (T, U, V) {
    fn write(&self, output: &mut Output) {
        self.0.write(output);
        output.put(b' ');
        self.1.write(output);
        output.put(b' ');
        self.2.write(output);
    }
}
}
}
pub mod misc {
pub mod binary_search {
use crate::algo_lib::misc::num_traits::Number;
use std::ops::Range;

pub fn binary_search_first_true<T>(range: Range<T>, mut f: impl FnMut(T) -> bool) -> T
where
    T: Number,
{
    // we can't store [range.start - 1] into [left], because it could overflow
    let mut left_plus_one = range.start;
    let mut right = range.end;
    while right > left_plus_one {
        let mid = left_plus_one + (right - left_plus_one) / T::TWO;
        if f(mid) {
            right = mid;
        } else {
            left_plus_one = mid + T::ONE;
        }
    }
    right
}

pub fn binary_search_last_true<T>(range: Range<T>, mut f: impl FnMut(T) -> bool) -> Option<T>
where
    T: Number,
{
    let first_false = binary_search_first_true(range.clone(), |x| !f(x));
    if first_false == range.start {
        None
    } else {
        Some(first_false - T::ONE)
    }
}

#[test]
fn simple_stress() {
    const N: usize = 50;
    for n in 1..N {
        for cnt_false in 0..=n {
            let mut a = vec![false; cnt_false];
            a.resize(n, true);
            let mut max_f_calls = ((n + 1) as f64).log2().ceil() as i32;
            let f_is_true = |id: usize| -> bool {
                max_f_calls -= 1;
                assert!(max_f_calls >= 0);
                a[id]
            };
            let result = binary_search_first_true(0..n, f_is_true);
            assert_eq!(result, cnt_false);
        }
    }
}
}
pub mod dbg_macro {
#[macro_export]
#[allow(unused_macros)]
macro_rules! dbg {
    ($first_val:expr, $($val:expr),+ $(,)?) => {
        eprint!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val);
        ($(eprint!(", {} = {:?}", stringify!($val), &$val)),+,);
        eprintln!();
    };
    ($first_val:expr) => {
        eprintln!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val)
    };
}
}
pub mod gen_vector {
pub fn gen_vec<T>(n: usize, f: impl FnMut(usize) -> T) -> Vec<T> {
    (0..n).map(f).collect()
}
}
pub mod num_traits {
use std::cmp::Ordering;
use std::fmt::Debug;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Div;
use std::ops::DivAssign;
use std::ops::Mul;
use std::ops::MulAssign;
use std::ops::Sub;
use std::ops::SubAssign;

pub trait HasConstants<T> {
    const MAX: T;
    const MIN: T;
    const ZERO: T;
    const ONE: T;
    const TWO: T;
}

pub trait ConvSimple<T> {
    fn from_i32(val: i32) -> T;
    fn to_i32(self) -> i32;
    fn to_f64(self) -> f64;
}

pub trait Signum {
    fn signum(&self) -> i32;
}

pub trait Number:
    Copy
    + Add<Output = Self>
    + AddAssign
    + Sub<Output = Self>
    + SubAssign
    + Mul<Output = Self>
    + MulAssign
    + Div<Output = Self>
    + DivAssign
    + PartialOrd
    + PartialEq
    + HasConstants<Self>
    + Default
    + Debug
    + Sized
    + ConvSimple<Self>
{
}

impl<
        T: Copy
            + Add<Output = Self>
            + AddAssign
            + Sub<Output = Self>
            + SubAssign
            + Mul<Output = Self>
            + MulAssign
            + Div<Output = Self>
            + DivAssign
            + PartialOrd
            + PartialEq
            + HasConstants<Self>
            + Default
            + Debug
            + Sized
            + ConvSimple<Self>,
    > Number for T
{
}

macro_rules! has_constants_impl {
    ($t: ident) => {
        impl HasConstants<$t> for $t {
            // TODO: remove `std` for new rust version..
            const MAX: $t = std::$t::MAX;
            const MIN: $t = std::$t::MIN;
            const ZERO: $t = 0;
            const ONE: $t = 1;
            const TWO: $t = 2;
        }

        impl ConvSimple<$t> for $t {
            fn from_i32(val: i32) -> $t {
                val as $t
            }

            fn to_i32(self) -> i32 {
                self as i32
            }

            fn to_f64(self) -> f64 {
                self as f64
            }
        }
    };
}

has_constants_impl!(i32);
has_constants_impl!(i64);
has_constants_impl!(i128);
has_constants_impl!(u32);
has_constants_impl!(u64);
has_constants_impl!(u128);
has_constants_impl!(usize);
has_constants_impl!(u8);

impl ConvSimple<Self> for f64 {
    fn from_i32(val: i32) -> Self {
        val as f64
    }

    fn to_i32(self) -> i32 {
        self as i32
    }

    fn to_f64(self) -> f64 {
        self
    }
}

impl HasConstants<Self> for f64 {
    const MAX: Self = Self::MAX;
    const MIN: Self = -Self::MAX;
    const ZERO: Self = 0.0;
    const ONE: Self = 1.0;
    const TWO: Self = 2.0;
}

impl<T: Number + Ord> Signum for T {
    fn signum(&self) -> i32 {
        match self.cmp(&T::ZERO) {
            Ordering::Greater => 1,
            Ordering::Less => -1,
            Ordering::Equal => 0,
        }
    }
}
}
pub mod rand {
use crate::algo_lib::misc::gen_vector::gen_vec;
use crate::algo_lib::misc::num_traits::Number;
use std::ops::Range;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

#[allow(dead_code)]
pub struct Random {
    state: u64,
}

impl Random {
    pub fn gen_u64(&mut self) -> u64 {
        let mut x = self.state;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.state = x;
        x
    }

    #[allow(dead_code)]
    pub fn next_in_range(&mut self, from: usize, to: usize) -> usize {
        assert!(from < to);
        (from as u64 + self.gen_u64() % ((to - from) as u64)) as usize
    }

    pub fn gen_index<T>(&mut self, a: &[T]) -> usize {
        self.gen(0..a.len())
    }

    #[allow(dead_code)]
    #[inline(always)]
    pub fn gen_double(&mut self) -> f64 {
        (self.gen_u64() as f64) / (std::usize::MAX as f64)
    }

    #[allow(dead_code)]
    pub fn new(seed: u64) -> Self {
        let state = if seed == 0 { 787788 } else { seed };
        Self { state }
    }

    pub fn new_time_seed() -> Self {
        let time = SystemTime::now();
        let seed = (time.duration_since(UNIX_EPOCH).unwrap().as_nanos() % 1_000_000_000) as u64;
        if seed == 0 {
            Self::new(787788)
        } else {
            Self::new(seed)
        }
    }

    #[allow(dead_code)]
    pub fn gen_permutation(&mut self, n: usize) -> Vec<usize> {
        let mut result: Vec<_> = (0..n).collect();
        for i in 0..n {
            let idx = self.next_in_range(0, i + 1);
            result.swap(i, idx);
        }
        result
    }

    pub fn shuffle<T>(&mut self, a: &mut [T]) {
        for i in 1..a.len() {
            a.swap(i, self.gen(0..i + 1));
        }
    }

    pub fn gen<T>(&mut self, range: Range<T>) -> T
    where
        T: Number,
    {
        let from = T::to_i32(range.start);
        let to = T::to_i32(range.end);
        assert!(from < to);
        let len = (to - from) as usize;
        T::from_i32(self.next_in_range(0, len) as i32 + from)
    }

    pub fn gen_vec<T>(&mut self, n: usize, range: Range<T>) -> Vec<T>
    where
        T: Number,
    {
        gen_vec(n, |_| self.gen(range.clone()))
    }

    pub fn gen_nonempty_range(&mut self, n: usize) -> Range<usize> {
        let x = self.gen(0..n);
        let y = self.gen(0..n);
        if x <= y {
            x..y + 1
        } else {
            y..x + 1
        }
    }

    pub fn gen_bool(&mut self) -> bool {
        self.gen(0..2) == 0
    }
}
}
pub mod vec_apply_delta {
use crate::algo_lib::misc::num_traits::Number;

pub trait ApplyDelta<T> {
    fn add_to_all(self, delta: T) -> Self;
    fn sub_from_all(self, sub: T) -> Self;
}

impl<T> ApplyDelta<T> for Vec<T>
where
    T: Number,
{
    fn add_to_all(mut self, delta: T) -> Self {
        self.iter_mut().for_each(|val| *val += delta);
        self
    }

    fn sub_from_all(mut self, sub: T) -> Self {
        self.iter_mut().for_each(|val| *val -= sub);
        self
    }
}

impl<T> ApplyDelta<T> for Vec<(T, T)>
where
    T: Number,
{
    fn add_to_all(mut self, delta: T) -> Self {
        self.iter_mut().for_each(|(val1, val2)| {
            *val1 += delta;
            *val2 += delta
        });
        self
    }

    fn sub_from_all(mut self, sub: T) -> Self {
        self.iter_mut().for_each(|(val1, val2)| {
            *val1 -= sub;
            *val2 -= sub;
        });
        self
    }
}

pub trait ApplyDelta2<T> {
    fn add_to_all(&mut self, delta: T);
    fn sub_from_all(&mut self, sub: T);
}

impl<T> ApplyDelta2<T> for [T]
where
    T: Number,
    T: Sized,
{
    fn add_to_all(self: &mut [T], delta: T) {
        self.iter_mut().for_each(|x| *x += delta);
    }

    fn sub_from_all(&mut self, sub: T) {
        self.iter_mut().for_each(|x| *x -= sub);
    }
}
}
}
}
fn main() {
    let input = algo_lib::io::input::Input::new_stdin();
    let mut output = algo_lib::io::output::Output::new_stdout();
    crate::solution::run(input, output);
}

详细

Test #1:

score: 100
Accepted
time: 0ms
memory: 2060kb

input:

2
5 2 2
1 2 3 4 5
5 4 3 2 1
1 0 2
1 2 1
5 3 3
1 2 3 4 5
1 3 2 4 5
1 2 3 5 4
0 0 2
0 2 3
1 0 3

output:

3
10
1
1
2

result:

ok 5 lines

Test #2:

score: 0
Accepted
time: 18ms
memory: 2324kb

input:

2000
10 10 10
4 5 3 6 8 9 2 1 7 10
4 5 6 3 8 9 1 2 10 7
5 4 3 6 8 9 1 2 7 10
4 5 6 3 8 9 1 2 7 10
4 5 3 6 8 9 2 1 10 7
4 5 6 3 8 9 1 2 10 7
5 4 6 3 8 9 1 2 7 10
5 4 6 3 8 9 1 2 10 7
4 5 6 3 8 9 2 1 7 10
5 4 3 6 8 9 2 1 10 7
3 1 6
5 7 8
0 2 3
7 9 9
2 1 9
6 1 6
7 2 3
0 0 4
1 8 1
1 8 7
10 10 10
9 10 5 ...

output:

1
1
0
0
3
2
0
2
2
4
1
0
1
1
1
1
2
4
4
3
1
6
28
0
0
10
10
6
6
15
0
3
10
6
16
6
11
1
2
1
1
6
3
3
0
4
5
3
4
1
1
3
2
4
0
3
4
4
4
4
0
0
1
1
2
0
0
1
2
1
1
0
0
1
4
3
0
4
4
1
3
6
16
16
0
11
16
1
4
15
1
4
2
0
0
2
0
1
2
4
0
0
0
0
0
0
0
0
0
0
1
0
0
6
3
0
3
4
0
0
0
0
0
0
0
0
0
0
0
0
3
0
0
1
3
1
0
0
3
3
9
1
9
4
...

result:

ok 20000 lines

Test #3:

score: 0
Accepted
time: 27ms
memory: 2252kb

input:

8000
5 5 10
3 5 2 4 1
3 2 5 4 1
3 5 2 4 1
3 5 2 4 1
3 5 2 4 1
1 1 1
4 1 3
1 0 3
4 2 3
1 0 1
3 2 3
1 2 3
3 0 2
1 1 3
1 1 2
5 5 10
5 3 1 2 4
3 5 1 2 4
5 3 1 2 4
3 5 1 2 4
5 3 1 2 4
0 0 1
2 0 1
4 1 2
1 3 4
2 0 1
4 3 3
1 4 4
1 3 4
0 0 4
0 0 3
5 5 10
2 3 4 1 5
5 1 4 3 2
1 3 4 2 5
2 3 4 1 5
5 1 3 4 2
1 2 ...

output:

0
1
1
0
0
0
0
1
0
1
1
0
0
0
1
0
0
0
1
0
3
0
3
1
0
3
1
6
1
0
0
0
0
0
0
0
0
0
0
0
1
1
2
1
0
3
0
0
3
0
1
0
0
0
0
0
0
1
0
0
6
1
0
6
0
3
3
3
0
0
3
3
6
1
10
1
3
0
1
0
3
1
0
0
1
0
1
1
1
2
0
0
0
0
0
0
0
0
0
0
0
0
3
1
3
3
1
3
1
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
1
6
0
6
6
1
1
1
0
1
1
0
0
1
0
0
0
3
0
1
1
0
2
3
3...

result:

ok 80000 lines

Test #4:

score: 0
Accepted
time: 25ms
memory: 2180kb

input:

8000
5 5 5
1 3 5 2 4
5 3 2 1 4
5 2 1 3 4
3 1 2 5 4
1 3 2 5 4
1 1 2
1 4 0
1 4 1
2 2 2
4 1 3
5 5 5
2 3 4 1 5
2 3 4 1 5
2 3 4 5 1
2 3 4 1 5
2 3 4 5 1
2 0 4
0 0 0
4 1 3
3 0 1
4 4 4
5 5 5
2 5 4 1 3
2 5 4 1 3
2 5 4 1 3
2 5 4 1 3
2 5 4 1 3
3 1 3
2 0 4
0 1 3
4 0 2
3 4 4
5 5 5
1 2 4 5 3
1 2 4 5 3
1 2 4 5 3
1...

output:

1
1
3
0
3
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
3
0
1
0
0
0
1
0
0
1
1
1
1
3
0
3
0
0
0
0
0
10
3
1
3
1
2
1
1
1
0
3
3
1
0
1
6
3
6
6
1
0
0
0
0
0
0
2
1
2
0
3
1
1
1
3
1
3
1
3
3
6
3
6
0
1
1
0
6
0
3
1
1
1
1
0
0
0
0
0
0
6
0
0
10
1
0
0
0
1
2
1
1
0
0
0
1
1
1
0
0
1
0
1
1
0
1
3
0
0
0
3
1
0
10
0
4
0
0
2...

result:

ok 40000 lines

Test #5:

score: 0
Accepted
time: 53ms
memory: 2100kb

input:

2000
1 100 100
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
25 0 0
9 0 0
80 0 0
37 0 0
18 0 0
24 0 0
5 0 0
87 0 0
50 0 0
63 0 0
53 0 0
62 0 0
37 ...

output:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
...

result:

ok 200000 lines

Test #6:

score: 0
Accepted
time: 160ms
memory: 3236kb

input:

10
20 1000 2000
2 5 1 3 12 16 14 15 7 4 19 13 18 10 20 9 11 8 6 17
5 2 12 1 16 3 19 4 7 15 14 18 13 10 9 20 11 8 6 17
2 5 1 16 12 3 7 14 4 19 15 13 18 10 20 9 11 17 6 8
2 5 1 16 3 12 15 7 4 14 19 18 13 10 9 20 11 8 6 17
5 2 3 12 1 16 14 7 4 15 19 18 13 10 20 9 11 6 17 8
2 5 3 1 12 16 19 15 7 4 14 18...

output:

11
0
11
10
1
11
5
10
10
5
13
2
0
18
2
14
2
18
10
13
1
1
0
1
4
7
6
0
15
11
1
4
6
19
3
9
3
1
0
20
2
16
1
0
3
2
3
0
18
1
17
1
1
8
1
5
17
1
3
6
1
2
15
15
2
1
0
3
18
22
0
1
2
15
13
12
20
3
0
9
15
1
4
17
22
16
8
6
13
0
7
11
15
19
15
6
7
10
17
12
9
1
11
1
0
4
6
17
1
17
6
5
1
1
16
14
3
1
12
18
1
0
18
12
17
...

result:

ok 20000 lines

Test #7:

score: 0
Accepted
time: 219ms
memory: 2640kb

input:

33
3 2000 2000
1 2 3
2 1 3
2 1 3
2 1 3
1 2 3
2 1 3
2 1 3
1 2 3
2 1 3
1 2 3
2 1 3
2 1 3
2 1 3
1 2 3
2 1 3
2 1 3
2 1 3
1 2 3
2 1 3
2 1 3
1 2 3
1 2 3
2 1 3
1 2 3
2 1 3
1 2 3
2 1 3
1 2 3
2 1 3
2 1 3
1 2 3
2 1 3
2 1 3
2 1 3
1 2 3
2 1 3
1 2 3
1 2 3
2 1 3
1 2 3
1 2 3
1 2 3
1 2 3
2 1 3
2 1 3
1 2 3
2 1 3
2 1...

output:

1
1
0
1
0
0
1
0
0
0
0
0
0
1
1
0
0
0
1
1
0
0
0
0
1
0
1
0
0
0
0
1
0
0
1
0
1
0
0
0
1
0
1
0
0
0
0
1
0
0
1
1
0
1
0
0
1
0
1
1
0
0
0
1
1
0
1
1
0
1
0
1
0
0
0
1
0
0
0
1
1
1
1
0
0
0
1
0
1
0
0
0
0
1
1
0
0
1
1
1
0
1
1
0
0
1
0
0
0
0
1
0
0
0
0
0
0
0
1
1
1
0
0
0
0
1
0
1
0
1
0
0
0
1
1
1
0
0
0
0
0
0
0
0
0
0
1
1
0
0
...

result:

ok 66000 lines

Test #8:

score: 0
Accepted
time: 74ms
memory: 3068kb

input:

10
100 200 20000
33 77 70 12 88 3 29 59 63 41 75 18 42 83 96 44 67 73 79 48 92 54 78 93 21 14 24 72 91 25 71 97 2 89 76 20 37 95 68 87 39 31 5 100 9 23 74 80 7 27 50 69 52 82 81 85 56 84 34 32 17 36 11 16 8 57 49 30 60 86 62 99 13 19 98 43 6 4 46 58 64 45 51 53 10 28 90 26 40 94 35 22 61 15 47 1 55 ...

output:

1
4
2
3
2
4
0
2
1
1
1
0
0
4
0
4
3
2
2
1
4
0
4
0
2
2
4
2
2
0
2
2
1
0
0
1
3
2
2
0
0
0
3
2
0
1
4
1
2
2
3
1
3
0
2
1
1
4
2
1
0
0
3
0
0
2
0
2
4
3
0
4
0
0
3
0
2
2
0
4
3
4
2
3
2
0
2
0
1
1
2
1
2
1
4
0
1
0
1
2
0
2
4
1
0
2
4
2
3
1
4
2
0
2
0
2
0
2
2
0
1
2
1
2
0
3
2
1
2
1
1
4
1
1
1
2
1
2
2
1
0
2
0
1
0
1
1
1
0
2
...

result:

ok 200000 lines

Test #9:

score: 0
Accepted
time: 159ms
memory: 10416kb

input:

1
316 632 200000
36 93 100 184 246 134 89 157 219 9 18 29 8 109 159 3 255 66 257 27 290 286 283 132 216 175 167 208 238 31 220 296 271 113 269 127 156 300 121 267 99 122 90 288 64 210 28 144 262 60 53 6 96 268 276 279 13 174 287 78 295 72 143 155 146 197 107 35 24 88 187 110 163 204 2 25 226 119 164...

output:

7
87
10
47
74
55
79
64
19
2
104
21
54
1
4
72
81
57
12
74
28
77
82
77
7
22
56
6
81
4
28
24
56
19
25
7
7
4
64
68
51
16
95
23
67
31
33
45
72
69
65
7
24
11
85
25
0
1
0
20
72
43
56
12
16
76
98
91
50
84
23
71
8
14
22
49
64
3
24
2
15
5
90
11
26
40
3
12
4
23
88
65
34
42
25
4
80
3
6
20
41
83
12
10
43
24
3
77...

result:

ok 200000 lines

Test #10:

score: 0
Accepted
time: 120ms
memory: 10492kb

input:

1
632 316 200000
625 142 323 331 85 521 376 51 411 31 418 11 16 66 112 611 459 622 148 247 122 587 249 141 20 88 439 334 233 474 305 381 203 559 228 595 326 535 128 449 138 28 86 56 109 102 428 194 612 256 466 598 189 539 237 59 225 528 200 330 490 560 133 57 590 632 422 213 340 310 49 195 41 217 19...

output:

60
34
45
304
31
71
52
36
123
38
76
28
200
223
55
58
11
275
202
76
285
30
154
113
40
48
355
332
358
33
240
46
29
91
147
75
318
62
162
200
171
124
228
31
285
59
16
206
114
44
163
87
53
65
221
298
23
172
123
91
298
14
57
6
8
71
1
84
3
2
58
20
6
111
244
220
25
137
86
269
134
254
68
64
129
14
65
108
43
3...

result:

ok 200000 lines

Test #11:

score: 0
Accepted
time: 125ms
memory: 7920kb

input:

1
447 447 200000
108 218 332 238 439 329 405 417 75 380 227 395 285 112 24 290 141 390 269 155 364 36 79 403 170 284 348 250 93 331 232 90 419 228 21 424 213 365 353 404 274 144 146 291 88 29 44 12 362 233 312 369 400 95 142 17 327 111 414 86 58 314 163 401 358 197 441 157 160 40 220 180 283 10 63 6...

output:

720
254
101
688
77
209
15
516
644
262
61
102
719
85
49
52
471
94
275
145
3
714
101
385
407
241
154
441
839
247
124
278
100
290
408
290
567
42
72
320
296
528
471
420
293
295
688
516
354
159
812
468
487
671
190
514
396
154
887
64
119
125
604
27
901
669
651
148
432
673
291
183
3
123
946
722
783
382
367...

result:

ok 200000 lines

Test #12:

score: 0
Accepted
time: 60ms
memory: 6716kb

input:

2
10000 10 100000
9169 6526 4977 9620 6327 8688 1778 4867 8252 2611 762 6164 1606 5796 6803 7006 5759 9972 8099 6268 5700 9868 896 2146 7128 1326 2696 2311 8764 6495 8013 6340 8057 6116 8447 5480 6736 9968 1048 1357 9013 8647 2334 8332 1514 6336 1486 5441 2963 2814 6910 4862 9616 1340 9839 3105 3703...

output:

43
225
406
1980
718
2299
362
985
1715
111
2449
1855
241
1928
461
1018
2304
1158
2562
446
176
1874
1743
8
165
1024
1025
2514
267
2165
1126
428
1804
14
969
590
765
1839
293
2166
1189
434
83
1862
916
48
2000
126
1170
101
2535
809
1422
589
123
44
1265
794
1025
1568
88
1483
498
2464
904
511
997
305
513
2...

result:

ok 200000 lines

Test #13:

score: 0
Accepted
time: 1413ms
memory: 6920kb

input:

2
10 10000 100000
6 7 9 4 3 8 10 5 2 1
6 7 9 5 10 4 8 3 2 1
6 7 9 4 10 8 3 5 1 2
6 7 9 5 10 8 3 4 1 2
6 7 9 8 10 3 4 5 1 2
6 7 9 5 3 8 4 10 1 2
6 7 9 5 10 8 4 3 1 2
6 7 9 3 4 5 10 8 1 2
6 7 9 4 8 10 5 3 1 2
6 7 9 8 3 4 5 10 1 2
6 7 9 4 3 8 10 5 1 2
6 7 9 8 5 4 3 10 1 2
6 7 9 8 4 3 5 10 1 2
6 7 9 3 4...

output:

6
0
1
10
4
10
1
1
0
1
3
0
1
0
3
3
6
1
0
0
11
0
3
4
1
10
1
1
0
3
3
7
6
10
11
4
1
11
0
1
0
1
10
6
6
6
0
10
6
0
2
10
10
0
3
1
3
0
0
0
0
6
0
1
6
10
1
6
2
6
2
0
4
1
1
3
10
11
0
6
1
6
0
6
1
11
3
10
11
0
10
10
11
3
1
6
10
0
6
0
11
6
11
3
0
1
0
10
6
0
0
10
0
0
1
11
3
0
11
10
1
0
3
3
6
3
0
1
3
1
6
11
10
10
3...

result:

ok 200000 lines

Test #14:

score: 0
Accepted
time: 79ms
memory: 44248kb

input:

1
1 200000 200000
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
...

output:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
...

result:

ok 200000 lines

Test #15:

score: -100
Time Limit Exceeded

input:

1
2 100000 200000
2 1
2 1
1 2
1 2
2 1
2 1
1 2
1 2
2 1
1 2
2 1
1 2
1 2
1 2
2 1
2 1
2 1
1 2
1 2
2 1
2 1
2 1
2 1
2 1
1 2
1 2
2 1
1 2
2 1
2 1
1 2
1 2
1 2
2 1
2 1
2 1
1 2
2 1
1 2
1 2
2 1
1 2
1 2
2 1
2 1
2 1
1 2
1 2
1 2
2 1
2 1
1 2
1 2
1 2
2 1
2 1
2 1
1 2
1 2
2 1
1 2
1 2
2 1
1 2
2 1
1 2
2 1
1 2
2 1
2 1
2 ...

output:


result: