QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#273430 | #7881. Computational Complexity | ucup-team296# | TL | 246ms | 2652kb | Rust | 30.8kb | 2023-12-02 23:51:58 | 2023-12-02 23:51:58 |
Judging History
answer
pub mod solution {
//{"name":"h","group":"Manual","url":"","interactive":false,"timeLimit":2000,"tests":[{"input":"","output":""}],"testType":"single","input":{"type":"stdin","fileName":null,"pattern":null},"output":{"type":"stdout","fileName":null,"pattern":null},"languages":{"java":{"taskClass":"h"}}}
use std::collections::BTreeMap;
use std::collections::HashSet;
use crate::algo_lib::collections::array_2d::Array2D;
use crate::algo_lib::io::output::output;
use crate::algo_lib::io::task_io_settings::TaskIoType;
use crate::algo_lib::io::task_runner::run_task;
use crate::algo_lib::io::input::Input;
use crate::algo_lib::io::task_io_settings::TaskIoSettings;
use crate::algo_lib::misc::min_max::UpdateMinMax;
use crate::algo_lib::misc::rand::Random;
#[allow(unused)]
use crate::dbg;
use crate::out;
use crate::out_line;
fn go(x: u64, seen: &mut HashSet<u64>) {
if x < 20_000_000 {
return;
}
if seen.contains(&x) {
return;
}
seen.insert(x);
for div in [2, 3, 4, 5, 7] {
go(x / div, seen);
}
}
fn stress() {
let max_n = 1e15 as u64;
let mut rnd = Random::new(787788);
for it in 0..100_000 {
let mut hm = HashSet::new();
let n = rnd.gen_u64() % max_n;
go(n, &mut hm);
dbg!(n, it, hm.len());
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
struct Query {
x: u64,
id: usize,
}
fn solve(input: &mut Input, _test_case: usize) {
let f0 = input.u64();
let g0 = input.u64();
let tc = input.usize();
let modu = input.u64();
let mut queries = vec![];
for id in 0..tc {
let x = input.u64();
queries.push(Query { x, id });
}
queries.sort();
let f_div = [2, 3, 5, 7];
let g_div = [2, 3, 4, 5];
let mut prec = vec![[f0, g0]];
for i in 1..10 {
let mut now = [0, 0];
for &d in f_div.iter() {
now[0] += prec[i / d][1]
}
for &d in g_div.iter() {
now[1] += prec[i / d][0]
}
let nn = i as u64;
now[0].update_max(nn);
now[1].update_max(nn);
prec.push(now);
}
for entry in prec.iter_mut() {
for x in entry.iter_mut() {
*x %= modu;
}
}
for i in prec.len()..100 {
let mut now = [0, 0];
for &d in f_div.iter() {
now[0] += prec[i / d][1]
}
for &d in g_div.iter() {
now[1] += prec[i / d][0]
}
for x in now.iter_mut() {
*x %= modu;
}
prec.push(now);
}
// for i in 0..10 {
// dbg!(i, prec[i]);
// }
let mut set = BTreeMap::new();
let mut start = Array2D::new(0, 2, 2);
start[0][0] = 1;
start[1][1] = 1;
set.insert(1u64, start);
let mut res = vec![[0, 0]; tc];
for query in queries.iter() {
loop {
let (&x, matrix) = set.iter().next().unwrap();
if (query.x / x) as usize >= prec.len() {
let matrix = matrix.clone();
set.remove(&x);
for &d in f_div.iter() {
let d = d as u64;
for i in 0..2 {
let cur = matrix[0][i];
let entry = set.entry(x * d).or_insert_with(|| Array2D::new(0, 2, 2));
entry[1][i] += cur;
entry[1][i] %= modu;
}
}
for &d in g_div.iter() {
let d = d as u64;
for i in 0..2 {
let cur = matrix[1][i];
let entry = set.entry(x * d).or_insert_with(|| Array2D::new(0, 2, 2));
entry[0][i] += cur;
entry[0][i] %= modu;
}
}
} else {
break;
}
}
// dbg!(query, set);
let mut cur_res = [0, 0];
for (&d, matrix) in set.iter() {
for i in 0..2 {
for j in 0..2 {
cur_res[i] += ((prec[(query.x / d) as usize][j] as u128)
* (matrix[j][i] as u128)
% (modu as u128)) as u64;
}
}
}
for x in cur_res.iter_mut() {
*x %= modu;
}
res[query.id] = cur_res;
}
for &x in res.iter() {
out_line!(x[0], x[1]);
}
}
pub(crate) fn run(mut input: Input) -> bool {
solve(&mut input, 1);
output().flush();
true
}
#[allow(unused)]
pub fn submit() -> bool {
let io = TaskIoSettings {
is_interactive: false,
input: TaskIoType::Std,
output: TaskIoType::Std,
};
run_task(io, run)
}
}
pub mod algo_lib {
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)]
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 * ½
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_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>(&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_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 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 static mut OUTPUT: Option<Output> = None;
pub fn set_global_output_to_stdout() {
unsafe {
OUTPUT = Some(Output::new(Box::new(std::io::stdout())));
}
}
pub fn set_global_output_to_file(path: &str) {
unsafe {
let out_file =
std::fs::File::create(path).unwrap_or_else(|_| panic!("Can't create file {}", path));
OUTPUT = Some(Output::new(Box::new(out_file)));
}
}
pub fn set_global_output_to_none() {
unsafe {
match &mut OUTPUT {
None => {}
Some(output) => output.flush(),
}
OUTPUT = None;
}
}
pub fn output() -> &'static mut Output {
unsafe {
match &mut OUTPUT {
None => {
panic!("Global output wasn't initialized");
}
Some(output) => output,
}
}
}
#[macro_export]
macro_rules! out {
($first: expr $(,$args:expr )*) => {
output().print(&$first);
$(output().put(b' ');
output().print(&$args);
)*
output().maybe_flush();
}
}
#[macro_export]
macro_rules! out_line {
($first: expr $(, $args:expr )* ) => {
{
out!($first $(,$args)*);
output().put(b'\n');
output().maybe_flush();
}
};
() => {
{
output().put(b'\n');
output().maybe_flush();
}
};
}
}
pub mod task_io_settings {
pub enum TaskIoType {
Std,
File(String),
}
pub struct TaskIoSettings {
pub is_interactive: bool,
pub input: TaskIoType,
pub output: TaskIoType,
}
}
pub mod task_runner {
use std::io::Write;
use super::input::Input;
use super::output::Output;
use super::output::OUTPUT;
use super::task_io_settings::TaskIoSettings;
use super::task_io_settings::TaskIoType;
pub fn run_task<Res>(io: TaskIoSettings, run: impl FnOnce(Input) -> Res) -> Res {
let output: Box<dyn Write> = match io.output {
TaskIoType::Std => Box::new(std::io::stdout()),
TaskIoType::File(file) => {
let out_file = std::fs::File::create(file).unwrap();
Box::new(out_file)
}
};
unsafe {
OUTPUT = Some(Output::new(output));
}
let input = match io.input {
TaskIoType::Std => {
let sin = std::io::stdin();
Input::new(Box::new(sin))
}
TaskIoType::File(file) => Input::new_file(file),
};
run(input)
}
}
}
pub mod misc {
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 min_max {
pub trait UpdateMinMax: PartialOrd + Sized {
#[inline(always)]
fn update_min(&mut self, other: Self) -> bool {
if other < *self {
*self = other;
true
} else {
false
}
}
#[inline(always)]
fn update_max(&mut self, other: Self) -> bool {
if other > *self {
*self = other;
true
} else {
false
}
}
}
impl<T: PartialOrd + Sized> UpdateMinMax for T {}
pub trait FindMinMaxPos {
fn index_of_min(&self) -> usize;
fn index_of_max(&self) -> usize;
}
impl<T: PartialOrd> FindMinMaxPos for [T] {
fn index_of_min(&self) -> usize {
let mut pos_of_best = 0;
for (idx, val) in self.iter().enumerate().skip(1) {
if val < &self[pos_of_best] {
pos_of_best = idx;
}
}
pos_of_best
}
fn index_of_max(&self) -> usize {
let mut pos_of_best = 0;
for (idx, val) in self.iter().enumerate().skip(1) {
if val > &self[pos_of_best] {
pos_of_best = idx;
}
}
pos_of_best
}
}
pub fn index_of_min_by<T, F>(n: usize, f: F) -> usize
where
T: PartialOrd,
F: Fn(usize) -> T,
{
assert!(n > 0);
let mut best_idx = 0;
let mut best_val = f(0);
for idx in 1..n {
let cur_val = f(idx);
if cur_val < best_val {
best_val = cur_val;
best_idx = idx;
}
}
best_idx
}
pub fn index_of_max_by<T, F>(n: usize, f: F) -> usize
where
T: PartialOrd,
F: Fn(usize) -> T,
{
assert!(n > 0);
let mut best_idx = 0;
let mut best_val = f(0);
for idx in 1..n {
let cur_val = f(idx);
if cur_val > best_val {
best_val = cur_val;
best_idx = idx;
}
}
best_idx
}
}
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
}
}
}
}
}
fn main() {
crate::solution::submit();
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 1ms
memory: 2208kb
input:
1958 920 10 100000000000 0 1 2 3 10 100 200 1000 19580920 20232023
output:
1958 920 3680 7832 10592 9554 17504 11276 50294 64826 784112 893714 1894550 1905470 12057866 12979424 71481494756 48626708512 28127864908 7251681354
result:
ok 20 numbers
Test #2:
score: 0
Accepted
time: 0ms
memory: 2020kb
input:
0 0 10 100000000000 0 1 2 3 4 10 20 30 40 100
output:
0 0 1 1 2 2 3 3 4 4 11 12 25 26 41 41 55 58 162 172
result:
ok 20 numbers
Test #3:
score: 0
Accepted
time: 0ms
memory: 2076kb
input:
2023 2023 10 2023 0 1 2 3 4 5 6 7 8 9
output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
result:
ok 20 numbers
Test #4:
score: 0
Accepted
time: 82ms
memory: 2536kb
input:
36092 30559 2149 729566623185 909730017626 961811467628 978809456383 494310140318 760462959632 726343527430 220697276132 366336227300 456813204361 569783542145 13854148170 51526515764 564416233246 876430686824 862897449267 956440673661 512777546436 728860125927 799238602356 978766770799 47962348351 ...
output:
192287632545 510282654057 513694515018 658644741565 90751152870 6088748556 138070013247 301112114677 224113421002 105290451187 630454127249 196841848259 546918129568 526274849982 226761501362 157889210040 135623074930 620463814922 78467045157 602244472172 51639549042 411354142414 329188915935 306494...
result:
ok 4298 numbers
Test #5:
score: 0
Accepted
time: 246ms
memory: 2652kb
input:
46012 72474 6895 931299293479 635558333906 151352929427 186830308154 201652909474 130684521091 862625793178 335372663856 565394770762 609752364488 636658378167 568072145317 23602174799 74849827839 567735061723 964475612065 721588322843 526921882143 141483206690 794896616456 923141155683 443983986019...
output:
737640936783 269480550026 785950579990 586907405473 274405996613 356240054012 164145774405 803378519477 613956922400 426121843045 509646717167 788278629379 95131481441 672600899832 720839818877 52329269906 131977527669 257593035330 737640936783 269480550026 202443098753 171133839273 188615102144 605...
result:
ok 13790 numbers
Test #6:
score: -100
Time Limit Exceeded
input:
4625 65696 87448 104757899185 324541097749 340894391228 353710640194 913290645927 500906082550 994613091630 486893604015 755863379632 795242109754 670982629049 89739557323 995677833835 622128974870 291590021762 74643709454 491030939322 504220665415 590951839890 749414110824 908656060298 831415689095...