{"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn combination(n: u64, k: u64, m: u64) -> u64 {\n if n == 0 {\n return 1;\n }\n if k == 0 || k == n {\n return 1;\n }\n let new_k = if n - k < k { n - k } else { k };\n let mut res = 1;\n for i in ((n - new_k) + 1)..=n {\n res *= i;\n res %= m;\n }\n let mut den = 1;\n for i in 1..=(new_k) {\n den *= i;\n den %= m;\n }\n let (_one, inverse, _c) = egcd(den as i64, m as i64);\n let inverse = if inverse < 0 {\n m as i64 + inverse\n } else {\n inverse\n } as u64;\n //println!(\"inv: {} {}\", den, inverse);\n res *= inverse;\n res %= m;\n res\n}\n\nuse std::collections::HashSet;\nuse std::iter::FromIterator;\n\nfn n_to_vec(n: u64, l: usize) -> Vec {\n let mut res = vec![0; l];\n let mut n = n;\n for i in (0..l).rev() {\n if n % 2 == 1 {\n res[i] = 1;\n }\n n /= 2;\n }\n res\n}\n\nfn vec_to_n(v: Vec) -> u64 {\n let mut res = 0;\n for i in 0..v.len() {\n res *= 2;\n if v[i] == 1 {\n res += 1;\n }\n }\n res\n}\n\nfn main() -> Result<(), Box> {\n let (mut x1, mut y1, mut x2, mut y2) = read_4::();\n let (x3, y3, x4, y4) = read_4::();\n let (x5, y5, x6, y6) = read_4::();\n\n // lower edge\n if x3 <= x1 && x2 <= x4 {\n if y3 <= y1 {\n y1 = max(y1, y4);\n }\n if y2 <= y4 {\n y2 = min(y2, y3);\n }\n }\n if x5 <= x1 && x2 <= x6 {\n if y5 <= y1 {\n y1 = max(y1, y6);\n }\n if y2 <= y6 {\n y2 = min(y2, y5);\n }\n }\n // left edge\n if y3 <= y1 && y2 <= y4 {\n if x3 <= x1 {\n x1 = max(x1, x4);\n }\n if x2 <= x4 {\n x2 = min(x2, x3);\n }\n }\n if y5 <= y1 && y2 <= y6 {\n if x5 <= x1 {\n x1 = max(x1, x6);\n }\n if x2 <= x6 {\n x2 = min(x2, x5);\n }\n }\n //println!(\"{} {} {} {} \", x1, x2, y1, y2);\n\n if x1 < x2 && y1 < y2 {\n println!(\"YES\")\n } else {\n println!(\"NO\")\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "6e7b51c342ed01dda2abcbdb3472dbfb", "src_uid": "05c90c1d75d76a522241af6bb6af7781", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Write;\nuse std::cmp::max;\nuse std::cmp::min;\n\npub struct Scanner {\n buffer: Vec\n}\n\nimpl Scanner {\n pub fn new() -> Scanner {\n Scanner { buffer: Vec::new() }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nstruct Square {\n x1: u32,\n y1: u32,\n x2: u32,\n y2: u32,\n}\n\nimpl Square {\n fn from(scan: &mut Scanner) -> Square {\n Square::new(scan.next(), scan.next(), scan.next(), scan.next())\n }\n\n fn new(x1: u32, y1: u32, x2: u32, y2: u32) -> Square {\n if x1 <= x2 && y1 <= y2 {\n Square { x1, y1, x2, y2 }\n } else {\n Square { x1: 0, y1: 0, x2: 0, y2: 0 }\n }\n }\n\n fn intersect(&self, other: &Square) -> Square {\n Square::new(max(self.x1, other.x1), max(self.y1, other.y1),\n min(self.x2, other.x2), min(self.y2, other.y2))\n }\n\n fn area(&self) -> u64 {\n ((self.x2 - self.x1) as u64) * ((self.y2 - self.y1) as u64)\n }\n}\n\nfn main() {\n let stdout = std::io::stdout();\n let mut out = std::io::BufWriter::new(stdout.lock());\n let mut scan = Scanner::new();\n\n let white = Square::from(&mut scan);\n let black1 = Square::from(&mut scan);\n let black2 = Square::from(&mut scan);\n let intersect1 = white.intersect(&black1);\n let intersect2 = white.intersect(&black2);\n let covered = intersect1.area() + intersect2.area()\n - intersect1.intersect(&intersect2).area();\n if white.area() > covered {\n writeln!(out, \"YES\").unwrap();\n } else {\n writeln!(out, \"NO\").unwrap();\n }\n}", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "b91f95fe4405e09a37b0320cdddf2b56", "src_uid": "05c90c1d75d76a522241af6bb6af7781", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::stdin;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nuse std::cmp::{ min, max };\n\ntype Point = (i128, i128);\n\nfn intersect(a: &Point, b: &Point, c: &Point, d: &Point) -> (Point, Point) {\n let l = max(min(a.0, b.0), min(c.0, d.0));\n let r = min(max(a.0, b.0), max(c.0, d.0));\n let u = min(max(a.1, b.1), max(c.1, d.1));\n let d = max(min(a.1, b.1), min(c.1, d.1));\n if l >= r || u <= d {\n ((0,0), (0,0))\n } else {\n ((l, d), (r, u))\n }\n}\n\nfn area(x: &Point, y: &Point) -> i128 {\n (x.0 - y.0).abs() * (x.1 - y.1).abs()\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let (p1, p2): (Point, Point) = ((scan.next::(), scan.next::()),(scan.next::(), scan.next::()));\n let (p3, p4): (Point, Point) = ((scan.next::(), scan.next::()),(scan.next::(), scan.next::()));\n let (p5, p6): (Point, Point) = ((scan.next::(), scan.next::()),(scan.next::(), scan.next::()));\n let wb1 = intersect(&p1, &p2, &p3, &p4);\n let wb2 = intersect(&p1, &p2, &p5, &p6);\n let sb1b2 = intersect(&wb1.0, &wb1.1, &wb2.0, &wb2.1);\n let a = area(&p1, &p2);\n let b = area(&wb1.0, &wb1.1);\n let c = area(&wb2.0, &wb2.1);\n let d = area(&sb1b2.0, &sb1b2.1);\n println!(\"{}\", if a > b + c -d { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "9bc1f4be7d77bf83c44e0b2de11266ab", "src_uid": "05c90c1d75d76a522241af6bb6af7781", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[macro_export]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\nuse std::io;\nuse std::io::BufRead;\nuse std::str;\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len, complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n if len == 0 {\n break;\n }\n (len, buf2[len - 1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n } else {\n self.update_buf();\n }\n }\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\nconst BIG_STACK_SIZE: bool = true;\n#[allow(dead_code)]\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\nfn solve() {\n input!{\n w0: (i64,i64,i64,i64),\n b0: (i64,i64,i64,i64),\n b1: (i64,i64,i64,i64),\n }\n\n let mut xs = vec![];\n xs.push(w0.0);\n xs.push(w0.2);\n xs.push(b0.0);\n xs.push(b0.2);\n xs.push(b1.0);\n xs.push(b1.2);\n xs.sort();\n let mut x_compress = HashMap::new();\n let mut x_decompress = HashMap::new();\n let mut cur_x=0;\n for x in xs {\n if !x_compress.contains_key(&x) {\n x_compress.entry(x).or_insert(cur_x);\n x_decompress.entry(cur_x).or_insert(x);\n cur_x+=1;\n }\n }\n\n let mut ys = vec![];\n ys.push(w0.1);\n ys.push(w0.3);\n ys.push(b0.1);\n ys.push(b0.3);\n ys.push(b1.1);\n ys.push(b1.3);\n ys.sort();\n let mut y_compress = HashMap::new();\n let mut y_decompress = HashMap::new();\n let mut cur_y=0;\n for y in ys {\n if !y_compress.contains_key(&y) {\n y_compress.entry(y).or_insert(cur_y);\n y_decompress.entry(cur_y).or_insert(y);\n cur_y+=1;\n }\n }\n\n let mut table = vec![vec![false; cur_y-1]; cur_x-1];\n let x_comp = |x: i64| {\n x_compress.get(&x).unwrap().clone() as usize\n };\n let y_comp = |y: i64| {\n y_compress.get(&y).unwrap().clone() as usize\n };\n for x in x_comp(b0.0)..x_comp(b0.2) {\n for y in y_comp(b0.1)..y_comp(b0.3) {\n table[x][y]=true;\n }\n }\n for x in x_comp(b1.0)..x_comp(b1.2) {\n for y in y_comp(b1.1)..y_comp(b1.3) {\n table[x][y]=true;\n }\n }\n let mut ok = false;\n for x in x_comp(w0.0)..x_comp(w0.2) {\n for y in y_comp(w0.1)..y_comp(w0.3) {\n if !table[x][y] {\n ok=true;\n break;\n }\n }\n }\n\n if ok {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "dd01228fe4fe72f70babfc3255f559b2", "src_uid": "05c90c1d75d76a522241af6bb6af7781", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n p: [(u32, u32, u32, u32); 3],\n }\n let mut z = vec![];\n for &(a, b, c, d) in &p {\n z.push(a);\n z.push(b);\n z.push(c);\n z.push(d);\n z.push(c - 1);\n z.push(d - 1);\n }\n z.sort();\n z.dedup();\n let n = z.len();\n let mut ok = vec![vec![true; n]; n];\n for &(a, b, c, d) in &p[1..] {\n let a = z.binary_search(&a).unwrap();\n let b = z.binary_search(&b).unwrap();\n let c = z.binary_search(&c).unwrap();\n let d = z.binary_search(&d).unwrap();\n for i in a..c {\n for j in b..d {\n ok[i][j] = false;\n }\n }\n }\n let (a, b, c, d) = p[0];\n let a = z.binary_search(&a).unwrap();\n let b = z.binary_search(&b).unwrap();\n let c = z.binary_search(&c).unwrap();\n let d = z.binary_search(&d).unwrap();\n for i in a..c {\n for j in b..d {\n if ok[i][j] {\n println!(\"YES\");\n return;\n }\n }\n }\n println!(\"NO\");\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "6b56cdaa71ea8660ffa430bca17f0425", "src_uid": "05c90c1d75d76a522241af6bb6af7781", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize, m: usize, a: usize, b: usize,\n g0: i64, x: i64, y: i64, z: i64,\n }\n let mut d = vec![vec![0; m]; n];\n let mut state = g0;\n for i in 0..n {\n for j in 0..m {\n d[i][j] = state;\n state = (x * state + y) % z;\n }\n }\n let mut slide = vec![vec![0; m]; n];\n for i in 0..n {\n let mut st = VecDeque::<(i64, usize)>::new();\n for j in 0..m {\n if j >= b {\n while let Some(x) = st.pop_front() {\n if x.1 > j - b {\n st.push_front(x);\n break;\n }\n }\n }\n while let Some(x) = st.pop_back() {\n if x.0 < d[i][j] {\n st.push_back(x);\n break;\n }\n }\n st.push_back((d[i][j], j));\n slide[i][j] = st.front().unwrap().0;\n }\n }\n let mut ans = vec![vec![0; m]; n];\n for j in b - 1..m {\n let mut st = VecDeque::<(i64, usize)>::new();\n for i in 0..n {\n if i >= a {\n while let Some(x) = st.pop_front() {\n if x.1 > i - a {\n st.push_front(x);\n break;\n }\n }\n }\n while let Some(x) = st.pop_back() {\n if x.0 < slide[i][j] {\n st.push_back(x);\n break;\n }\n }\n st.push_back((slide[i][j], i));\n ans[i][j] = st.front().unwrap().0;\n }\n }\n let mut tot: i64 = 0;\n for i in a - 1..n {\n for j in b - 1..m {\n tot += ans[i][j];\n }\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "5c2946ed98c33305dff47bbacd78fb65", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n#[allow(unused_imports)]\nuse std::io::{stdout, stdin, BufWriter, Write};\nuse std::collections::VecDeque;\n\nstruct SlidingWindowQ {\n q: VecDeque,\n window: usize,\n f: F\n}\n\nimpl SlidingWindowQ\nwhere\n F: Fn(usize,usize) -> bool\n{\n fn new(window: usize, f: F) -> Self\n {\n SlidingWindowQ {\n q: VecDeque::new(),\n window: window,\n f: f\n }\n }\n\n fn push(&mut self, i: usize) {\n while self.q.len() > 0 {\n let j = *self.q.back().unwrap();\n\n if (self.f)(i, j) {\n self.q.pop_back();\n } else {\n break;\n }\n }\n self.q.push_back(i);\n\n let j = *self.q.front().unwrap();\n if i >= self.window && j == i - self.window {\n self.q.pop_front();\n }\n }\n\n fn front(&self) -> usize {\n *self.q.front().unwrap()\n }\n}\n\n\nfn main() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (writeln!(out,$($format)*).unwrap());\n }\n\n input!{\n n: usize,\n m: usize,\n a: usize,\n b: usize,\n g0: u64,\n x: u64,\n y: u64,\n z: u64,\n }\n\n let mut hs = vec![0; n*m];\n let mut g = g0;\n for i in 0..n*m {\n hs[i] = g;\n g = (g * x + y) % z;\n }\n\n const INF: u64 = 1 << 50;\n let mut mins = vec![INF; n*m];\n\n // \u30b9\u30e9\u30a4\u30c9\u6700\u5c0f\u5024\n use std::collections::VecDeque;\n for i in 0..n {\n let f = |a, b| hs[i*m + a] <= hs[i*m + b];\n let mut q = SlidingWindowQ::new(b, f);\n for j in 0..m {\n q.push(j);\n if j >= b-1 {\n let min_j = q.front();\n mins[i*m + j] = hs[i*m + min_j];\n }\n }\n }\n\n let mut ans = 0;\n assert!(mins.len() == n*m);\n for j in b-1..m {\n let f = |a, b| mins[a*m + j] <= mins[b*m + j];\n let mut q = SlidingWindowQ::new(a, f);\n for i in 0..n {\n q.push(i);\n if i >= a-1 {\n let min_i = q.front();\n let v = mins[min_i * m + j];\n ans += v;\n }\n }\n }\n puts!(\"{}\", ans);\n}\n\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "4d293656665acdaab493af2e351ed2aa", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n#[allow(unused_imports)]\nuse std::io::{stdout, stdin, BufWriter, Write};\n\npub mod ds {\n use std::collections::VecDeque;\n pub struct SlidingWindowQ {\n q: VecDeque,\n window: usize,\n cur: usize,\n f: F,\n }\n impl SlidingWindowQ\n where\n F: Fn(usize, usize) -> bool,\n {\n pub fn new(window: usize, f: F) -> Self {\n SlidingWindowQ {\n q: VecDeque::new(),\n window: window,\n f: f,\n cur: 0,\n }\n }\n pub fn next(&mut self) -> usize {\n let i = self.cur;\n self.cur += 1;\n while self.q.len() > 0 {\n let j = *self.q.back().unwrap();\n if (self.f)(i, j) {\n self.q.pop_back();\n } else {\n break;\n }\n }\n self.q.push_back(i);\n let j = *self.q.front().unwrap();\n if i >= self.window && j == i - self.window {\n self.q.pop_front();\n }\n self.front()\n }\n pub fn front(&self) -> usize {\n *self.q.front().unwrap()\n }\n }\n}\n\n\nfn main() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (writeln!(out,$($format)*).unwrap());\n }\n\n input!{\n n: usize,\n m: usize,\n a: usize,\n b: usize,\n g0: u64,\n x: u64,\n y: u64,\n z: u64,\n }\n\n let mut hs = vec![0; n*m];\n let mut g = g0;\n for i in 0..n*m {\n hs[i] = g;\n g = (g * x + y) % z;\n }\n\n const INF: u64 = 1 << 50;\n let mut mins = vec![INF; n*m];\n\n use ds::SlidingWindowQ;\n\n // \u30b9\u30e9\u30a4\u30c9\u6700\u5c0f\u5024\n for i in 0..n {\n let f = |a, b| hs[i*m + a] <= hs[i*m + b];\n let mut q = SlidingWindowQ::new(b, f);\n for j in 0..m {\n let min_idx = q.next();\n if j >= b-1 {\n mins[i*m + j] = hs[i*m + min_idx];\n }\n }\n }\n\n let mut ans = 0;\n assert!(mins.len() == n*m);\n for j in b-1..m {\n let f = |a, b| mins[a*m + j] <= mins[b*m + j];\n let mut q = SlidingWindowQ::new(a, f);\n for i in 0..n {\n let min_idx = q.next();\n if i >= a-1 {\n let v = mins[min_idx * m + j];\n ans += v;\n }\n }\n }\n puts!(\"{}\", ans);\n}\n\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "5ddbd95f24479d2fbeea7169e4afa26d", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n#[allow(unused_imports)]\nuse std::io::{stdout, stdin, BufWriter, Write};\nuse std::collections::VecDeque;\n\nstruct SlidingWindowQ {\n q: VecDeque,\n window: usize,\n f: F\n}\n\nimpl SlidingWindowQ\nwhere\n F: Fn(usize,usize) -> bool\n{\n fn new(window: usize, f: F) -> Self\n {\n SlidingWindowQ {\n q: VecDeque::new(),\n window: window,\n f: f\n }\n }\n\n fn push(&mut self, i: usize) {\n while self.q.len() > 0 {\n let j = *self.q.back().unwrap();\n\n if (self.f)(i, j) {\n self.q.pop_back();\n } else {\n break;\n }\n }\n self.q.push_back(i);\n\n let j = *self.q.front().unwrap();\n if i >= self.window && j == i - self.window {\n self.q.pop_front();\n }\n }\n\n fn front(&self) -> usize {\n *self.q.front().unwrap()\n }\n}\n\n\nfn main() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (writeln!(out,$($format)*).unwrap());\n }\n\n input!{\n n: usize,\n m: usize,\n a: usize,\n b: usize,\n g0: u64,\n x: u64,\n y: u64,\n z: u64,\n }\n\n let mut hs = vec![0; n*m];\n let mut g = g0;\n for i in 0..n*m {\n hs[i] = g;\n g = (g * x + y) % z;\n }\n\n const INF: u64 = 1 << 50;\n let mut mins = vec![INF; n*(m-b+1)];\n\n // \u30b9\u30e9\u30a4\u30c9\u6700\u5c0f\u5024\n use std::collections::VecDeque;\n for i in 0..n {\n let f = |a, b| hs[i*m + a] <= hs[i*m + b];\n let mut q = SlidingWindowQ::new(b, f);\n for j in 0..m {\n q.push(j);\n if j >= b-1 {\n let min_j = q.front();\n let idx = i*(m-b+1) + j+1-b;\n mins[idx] = hs[i*m + min_j];\n }\n }\n }\n\n let mut ans = 0;\n let m = m-b+1;\n assert!(mins.len() == n*m);\n for j in 0..m {\n let f = |a, b| mins[a*m + j] <= mins[b*m + j];\n let mut q = SlidingWindowQ::new(a, f);\n for i in 0..n {\n q.push(i);\n if i >= a-1 {\n let min_i = q.front();\n let v = mins[min_i * m + j];\n ans += v;\n }\n }\n }\n puts!(\"{}\", ans);\n}\n\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "39e211735f5791c99fc5e014380a9e68", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin Foldable Deque ----------\nstruct FoldableDeque {\n front: Vec<(T, T)>,\n back: Vec<(T, T)>,\n op: F,\n}\n\n#[allow(dead_code)]\nimpl FoldableDeque\nwhere T: Clone,\n F: Fn(&T, &T) -> T,\n{\n fn new(op: F) -> Self {\n FoldableDeque {\n front: Vec::new(),\n back: Vec::new(),\n op: op,\n }\n }\n fn find(&self) -> Option {\n match (self.front.last(), self.back.last()) {\n (Some(a), Some(b)) => Some((self.op)(&a.1, &b.1)),\n (Some(a), None) => Some(a.1.clone()),\n (None, Some(b)) => Some(b.1.clone()),\n (None, None) => None,\n }\n }\n fn clear(&mut self) {\n self.front.clear();\n self.back.clear();\n }\n fn len(&self) -> usize {\n self.front.len() + self.back.len()\n }\n fn push_back(&mut self, val: T) {\n let sum = if let Some(p) = self.back.last() {\n (self.op)(&p.1, &val)\n } else {\n val.clone()\n };\n self.back.push((val, sum));\n }\n fn push_front(&mut self, val: T) {\n let sum = if let Some(p) = self.front.last() {\n (self.op)(&val, &p.1)\n } else {\n val.clone()\n };\n self.front.push((val, sum));\n }\n fn pop_front(&mut self) -> Option {\n if self.len() == 0 {\n return None;\n }\n if self.front.is_empty() {\n let a = self.back.clone();\n let m = (self.back.len() + 1) / 2;\n self.back.clear();\n let (f, b) = a.split_at(m);\n for v in f.iter().rev() {\n self.push_front(v.0.clone());\n }\n for v in b.iter() {\n self.push_back(v.0.clone());\n }\n }\n self.front.pop().map(|p| p.0)\n }\n fn pop_back(&mut self) -> Option {\n if self.len() == 0 {\n return None;\n }\n if self.back.is_empty() {\n let a = self.front.clone();\n let m = self.front.len() / 2;\n self.front.clear();\n let (f, b) = a.split_at(m);\n for v in f.iter().rev() {\n self.push_front(v.0.clone());\n }\n for v in b.iter() {\n self.push_back(v.0.clone());\n }\n }\n self.back.pop().map(|p| p.0)\n }\n}\n// ---------- end Foldable Deque ----------\n\nuse std::io::Read;\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let h: usize = it.next().unwrap().parse().unwrap();\n let w: usize = it.next().unwrap().parse().unwrap();\n let r: usize = it.next().unwrap().parse().unwrap();\n let c: usize = it.next().unwrap().parse().unwrap();\n let mut g: u64 = it.next().unwrap().parse().unwrap();\n let x: u64 = it.next().unwrap().parse().unwrap();\n let y: u64 = it.next().unwrap().parse().unwrap();\n let z: u64 = it.next().unwrap().parse().unwrap();\n let mut a = vec![0u32; h * w];\n for a in a.iter_mut() {\n *a = g as u32;\n g = (g * x + y) % z;\n }\n let mut b = vec![0u32; h * (w - c + 1)];\n let op = |a: &u32, b: &u32| std::cmp::min(*a, *b);\n let mut q = FoldableDeque::new(op);\n for (i, a) in a.chunks(w).enumerate() {\n q.clear();\n for a in a.iter().take(c - 1) {\n q.push_back(*a);\n }\n for (b, a) in b[i..].iter_mut().step_by(h).zip(a.iter().skip(c - 1)) {\n q.push_back(*a);\n *b = q.find().unwrap();\n q.pop_front();\n }\n }\n let mut ans = 0u64;\n for b in b.chunks(h) {\n q.clear();\n for b in b.iter().take(r - 1) {\n q.push_back(*b);\n }\n for b in b.iter().skip(r - 1) {\n q.push_back(*b);\n ans += q.find().unwrap() as u64;\n q.pop_front();\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "56e611a53e74d3d310c1e3263e45d1b9", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin Foldable Deque ----------\nstruct FoldableDeque {\n front: Vec<(T, T)>,\n back: Vec<(T, T)>,\n op: F,\n}\n\n#[allow(dead_code)]\nimpl FoldableDeque\nwhere T: Clone,\n F: Fn(&T, &T) -> T,\n{\n fn new(op: F) -> Self {\n FoldableDeque {\n front: Vec::new(),\n back: Vec::new(),\n op: op,\n }\n }\n fn find(&self) -> Option {\n match (self.front.last(), self.back.last()) {\n (Some(a), Some(b)) => Some((self.op)(&a.1, &b.1)),\n (Some(a), None) => Some(a.1.clone()),\n (None, Some(b)) => Some(b.1.clone()),\n (None, None) => None,\n }\n }\n fn clear(&mut self) {\n self.front.clear();\n self.back.clear();\n }\n fn len(&self) -> usize {\n self.front.len() + self.back.len()\n }\n fn push_back(&mut self, val: T) {\n let sum = if let Some(p) = self.back.last() {\n (self.op)(&p.1, &val)\n } else {\n val.clone()\n };\n self.back.push((val, sum));\n }\n fn push_front(&mut self, val: T) {\n let sum = if let Some(p) = self.front.last() {\n (self.op)(&val, &p.1)\n } else {\n val.clone()\n };\n self.front.push((val, sum));\n }\n fn pop_front(&mut self) -> Option {\n if self.len() == 0 {\n return None;\n }\n if self.front.is_empty() {\n let a = self.back.clone();\n let m = (self.back.len() + 1) / 2;\n self.back.clear();\n let (f, b) = a.split_at(m);\n for v in f.iter().rev() {\n self.push_front(v.0.clone());\n }\n for v in b.iter() {\n self.push_back(v.0.clone());\n }\n }\n self.front.pop().map(|p| p.0)\n }\n fn pop_back(&mut self) -> Option {\n if self.len() == 0 {\n return None;\n }\n if self.back.is_empty() {\n let a = self.front.clone();\n let m = self.front.len() / 2;\n self.front.clear();\n let (f, b) = a.split_at(m);\n for v in f.iter().rev() {\n self.push_front(v.0.clone());\n }\n for v in b.iter() {\n self.push_back(v.0.clone());\n }\n }\n self.back.pop().map(|p| p.0)\n }\n}\n// ---------- end Foldable Deque ----------\n\nuse std::io::Read;\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let h: usize = it.next().unwrap().parse().unwrap();\n let w: usize = it.next().unwrap().parse().unwrap();\n let r: usize = it.next().unwrap().parse().unwrap();\n let c: usize = it.next().unwrap().parse().unwrap();\n let mut g: u64 = it.next().unwrap().parse().unwrap();\n let x: u64 = it.next().unwrap().parse().unwrap();\n let y: u64 = it.next().unwrap().parse().unwrap();\n let z: u64 = it.next().unwrap().parse().unwrap();\n let mut a = vec![vec![0u32; w]; h];\n for a in a.iter_mut() {\n for a in a.iter_mut() {\n *a = g as u32;\n g = (g * x + y) % z;\n }\n }\n let op = |a: &u32, b: &u32| std::cmp::min(*a, *b);\n let mut q = FoldableDeque::new(op);\n for a in a.iter_mut() {\n q.clear();\n for a in a.iter().take(c - 1) {\n q.push_back(*a);\n }\n for j in (c - 1)..w {\n q.push_back(a[j]);\n a[j - c + 1] = q.find().unwrap();\n q.pop_front();\n }\n }\n let mut ans = 0u64;\n for j in 0..(w - c + 1) {\n q.clear();\n for i in 1..r {\n q.push_back(a[i - 1][j]);\n }\n for i in (r - 1)..h {\n q.push_back(a[i][j]);\n ans += q.find().unwrap() as u64;\n q.pop_front();\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "38591ea4e08179053bc00e19a00f66d4", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut guess = String::new();\n let mut i_2:i32 = 0;\n for i in 0_i32..5 {\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n \n for elem in guess.chars() {\n if elem == '1'{\n let aux_i = if (i_2 % 5) == 0 {i_2 + 1} else {i_2};\n let line = (aux_i as f32/5.0).ceil() as i32;\n let col = i_2%5;\n let mut mv = col-2;\n mv = mv.abs() + (line - 3).abs();\n print!(\"{}\",mv);\n std::process::exit(0);\n }\n else if elem == '0'{\n i_2 +=1;\n }\n }\n guess = String::new();\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "fde6e350f0f43fb7a9db728b0e6fedc1", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n#[derive(Debug)]\nstruct Matrix {\n origin: (usize, usize),\n target: (usize, usize),\n}\n\nimpl Matrix {\n fn new(row: usize, col: usize) -> Matrix {\n Matrix {\n origin: (row, col),\n target: (3, 3),\n }\n }\n\n fn compute(&mut self) -> i64 {\n let row_diff = self.origin.0 as i64 - self.target.0 as i64;\n let col_diff = self.origin.1 as i64 - self.target.1 as i64;\n row_diff.abs() + col_diff.abs()\n }\n}\n\nfn main() {\n let mut lines = vec![String::new(); 5];\n\n for i in 0..5 {\n let _ = io::stdin().read_line(&mut lines[i]);\n }\n\n let mut rows: Vec> = vec![vec![0; 5]; 5];\n for (index, line) in lines.iter().enumerate() {\n rows[index] = line\n .split_whitespace()\n .map(|item| item.parse().unwrap())\n .collect();\n }\n\n let mut m = Matrix::new(0, 0);\n for (idx_r, row) in rows.iter().enumerate() {\n for (idx_c, elem) in row.iter().enumerate() {\n if elem == &1 {\n m = Matrix::new(idx_r + 1, idx_c + 1);\n break;\n }\n }\n }\n\n println!(\"{}\", m.compute());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f2e868513afc2248eb32b753b8d38773", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n let mut x1 = -1;\n let mut y1 = -1;\n\n for y in 1..6 {\n for x in 1..6 {\n\t let n = scan.next::();\n if n == 1 {\n x1 = x;\n y1 = y;\n }\n }\n }\n\n writeln!(out, \"{}\", (x1-3i8).abs() + (y1-3i8).abs()).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "66f5cd734dadc89705e8cafcd642f97d", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut count: i64 = 1;\n // let mut column: i64 = 0;\n let mut position: i64 = 0;\nwhile count < 6 { \n let mut input = String::new();\n std::io::stdin()\n .read_line(&mut input)\n .expect(\"Value not found\");\n\n let input: Vec = input\n .split_whitespace()\n .map(|s| s.parse()\n .expect(\"Parse Error\"))\n .collect();\n // println!(\"{}\",input.len());\n // let mut j = 0;\n // column += 1;\n for i in 0..input.len() {\n if input[i] == 1 {\n let j = i as i64;\n let first: i64 = 3 - count;\n // println!(\"first = {}\", first);\n let f: i64 = first.abs();\n // println!(\"first.abs = {}\", f);\n let second: i64 = 3 - j - 1;\n // println!(\"second = {}\", second);\n let s: i64 = second.abs();\n // println!(\"second.abs = {}\", s);\n position = f + s; \n }\n }\n count += 1;\n }\n println!(\"{}\", position);\n }\n\n// fn abs(x: isize) -> isize {\n// if x < 0 { x = x * -1}\n// else {x}\n// x\n\n// }", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0a22ed95e0dbfd62eaf81a8d857acda9", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\npub fn main(){\n let input = input();\n let mut x = 0;\n let mut y = 0;\n for i in 0..5 {\n for j in 0..5 {\n if input[i][j] == 1 {\n x = i;\n y = j;\n }\n }\n }\n let mut dist = 0;\n dist += if x > 2 { x - 2 } else { 2 - x};\n dist += if y > 2 { y - 2 } else { 2 - y};\n println!(\"{}\", dist);\n}\n\nfn input() -> Vec> {\n let mut vec = Vec::new();\n for _ in 0..5 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input);\n vec.push(input.split_whitespace()\n .map(|s| s.parse::().unwrap())\n .collect());\n }\n vec\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4418cb920180cdec8f14b0ad693f1c70", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n\nfn main() {\n let stdin = std::io::stdin();\n\n let mut buf;\n let mut i = 0;\n let mut j = 0;\n\n\n for r in 0..5 {\n buf = String::new();\n stdin.read_line(&mut buf).ok().expect(\"Error!\");\n let sbuf = buf.trim();\n\n let mut iter = sbuf.split_whitespace();\n \n for col in 0..5 {\n match iter.next() {\n Some(v) => {\n if v == \"1\" {\n j = col;\n i = r;\n }\n ()\n }\n None => (),\n }\n }\n }\n\n let mut res;\n res = (2i32 - i).abs();\n res += (2i32 - j).abs();\n\n // println!(\"{} {}\\n\", i, j);\n\n println!(\"{}\", res);\n \n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4a30f88299bf8fce6f00b8b0bdcc5939", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n for i in 0..5 {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let arr = input.trim().split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect::>();\n for (j, &elem) in arr.iter().enumerate() {\n if elem == 1 {\n println!(\"{}\", i32::abs(i as i32 - 2) + i32::abs(j as i32 - 2));\n return;\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "50cd4150f8235713829044576a6be2b4", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n\n let mut one: (u8, u8) = (0, 0);\n for i in 0..5 {\n io::stdin().read_line(&mut input)?;\n let v = input\n .trim()\n .split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect::>();\n for (j, x) in v.iter().enumerate() {\n if *x == 1 {\n one = (i, j as u8);\n }\n }\n input.clear();\n }\n\n println!(\"{}\", ((one.0 - 2) as i8).abs() + ((one.1 - 2) as i8).abs());\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "27739bebf98c8883c41ad96534fb0857", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*, Write};\nuse std::str;\nuse std::string::String;\nuse std::vec::Vec;\n\n#[allow(unused_must_use)]\nfn run(mut reader: Scanner, mut writer: W) {\n let mut numbers: Vec = reader.next_line().split('+').map(|n| n.parse().unwrap()).collect();\n numbers.sort_unstable();\n\n for i in 0..numbers.len() {\n write!(writer, \"{}\", numbers[i]);\n if i + 1 != numbers.len() {\n write!(writer, \"+\");\n }\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n run(reader, writer);\n io::stdout().flush().unwrap();\n}\n\npub struct Scanner {\n reader: B,\n buffer_string: Vec,\n buffer_iterator: str::SplitWhitespace<'static>,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n return Self {\n reader,\n buffer_string: Vec::new(),\n buffer_iterator: \"\".split_whitespace()\n };\n }\n\n pub fn next(&mut self) -> T {\n loop {\n //if buffer already exists, just use existing buffer\n if let Some(token) = self.buffer_iterator.next() {\n return token.parse().ok().expect(\"Fail to parse token\");\n }\n\n //get new line\n self.buffer_string.clear();\n self.reader.read_until(b'\\n', &mut self.buffer_string).expect(\"Failed to read\");\n\n //split by white space\n self.buffer_iterator = unsafe {\n let slice = str::from_utf8_unchecked(&self.buffer_string);\n std::mem::transmute(slice.split_whitespace())\n };\n }\n }\n\n pub fn next_line(&mut self) -> String {\n //reset buffer\n self.buffer_iterator = \"\".split_whitespace();\n self.buffer_string.clear();\n\n let mut input: String = String::new();\n self.reader.read_line(&mut input).expect(\"Failed to read line\");\n return input.trim().to_string();\n }\n}", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "eca14338e514ece16c92d62d01412fbe", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spna-rust\n#[allow(unused_imports)]\nuse std::io::{self,Read};\n\n#[derive(Debug)]\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader : T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let mut a = input.ab()\n .into_iter().step_by(2)\n .collect::>();\n a.sort();\n a.into_iter().enumerate().for_each(|(i,b)| {\n if i > 0 { print!(\"+\"); }\n print!(\"{}\", b as char);\n });\n}\n\n", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "778cfcfd45635e2522839f6fa6f003e8", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn main() {\n let mut word = String::new();\n io::stdin().read_line(&mut word)\n .expect(\"Failed to read line\");\n \n\n let snums = word.trim().split(\"+\");\n // let nums: Vec = word.split(\"+\");\n // // .map(|s| s.parse::().unwrap())\n // // .collect();\n \n let mut nums = Vec::::new();\n for s in snums {\n let n = s.parse::().unwrap();\n nums.push(n);\n }\n\n nums.sort();\n \n match nums.pop() {\n Some(last) => {\n for n in nums {\n print!(\"{}+\", n);\n }\n println!(\"{}\", last);\n },\n None => println!(\"bad input\")\n }\n \n \n \n\n}", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "ed576706c02833a7ecfdadb357af1c1d", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\nuse std::io::Read;\n\nfn main() {\n let expr: String = next();\n let mut counts = [0u8, 0u8, 0u8];\n\n for ch in expr.chars() {\n if ch != '+' {\n let digit = ch.to_digit(10).unwrap() as u8;\n counts[digit as usize - 1] += 1;\n }\n }\n\n let mut expr = String::with_capacity(expr.len());\n for (k, v) in counts.iter().enumerate() {\n let mut v = *v;\n while v > 0 {\n if !expr.is_empty() {\n expr.push('+');\n }\n expr.push((k + 1).to_string().chars().nth(0).unwrap());\n v -= 1;\n }\n }\n\n println!(\"{}\", expr);\n}\n\nfn next() -> T {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::().unwrap_or_else(|_| panic!(\"failed to parse\"))\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "316f08a02051c6c180161275ec66d512", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s);\n let mut v :Vec= s.trim().split(\"+\").map( |s| s.parse::().unwrap()).collect();\n v.sort();\n let ret = v.iter().map( |i| i.to_string()).collect::>().join(\"+\");\n println!(\"{}\", ret);\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "a482965090a7c50654376b6fc401c91d", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"error\");\n\n let mut numbers: Vec = input\n .trim()\n .split(\"+\")\n .map(|s| s.parse::().unwrap())\n .collect();\n numbers.sort();\n\n println!(\n \"{}\",\n numbers\n .iter()\n .map(|a| a.to_string())\n .collect::>()\n .join(\"+\")\n );\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "b07587fd0747f00582bb10626883120d", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::{Read, Write};\n\nfn solve(input: &mut Read, output: &mut Write) {\n let mut sin = String::new();\n input.read_to_string(&mut sin).unwrap();\n let mut s = sin.lines()\n .next().unwrap().trim()\n .split('+').map(|x| x.parse::().unwrap())\n .collect::>();\n s.sort();\n let string: String = s.iter().map(|x| x.to_string() + \"+\").collect();\n let res = &string[..string.len()-1];\n\n output.write(res.to_string().trim().as_bytes()).unwrap();\n}\n\nfn main() {\n solve(&mut io::stdin(), &mut io::stdout());\n}\n\n#[cfg(test)]\nmod tests {\n use std::fs::File;\n use std::io::Read;\n use solve;\n\n #[test]\n fn test() {\n (1..3 + 1).map(|x| {\n println!(\"test #{}\", x);\n let mut fin = File::open(\"./src/in\".to_string() + &x.to_string() + \".txt\").unwrap();\n let mut buf: Vec = Vec::new();\n solve(&mut fin, &mut buf);\n let res = String::from_utf8(buf).unwrap();\n\n let mut fout = File::open(\"./src/out\".to_string() + &x.to_string() + \".txt\").unwrap();\n let mut sout = String::new();\n fout.read_to_string(&mut sout).unwrap();\n assert_eq!(res, sout.trim());\n\n }).count();\n\n }\n}", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "5aa99b615a063d05f1368d92d7cb6c17", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\npub fn main(){\n let mut inputs = input();\n inputs.sort_unstable();\n print!(\"{}\", inputs[0]);\n for i in 1..inputs.len() {\n print!(\"+{}\", inputs[i]);\n }\n println!(\"\");\n}\n\nfn input() -> Vec {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input);\n input.trim().split('+').map(|s| s.parse::().unwrap())\n .collect()\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "580720ac0aec68274f96156da75aa113", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\n\nfn read_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim().to_owned()\n}\n\nfn reads() -> Vec\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n read_line()\n .split_whitespace()\n .map(|w| w.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let n: usize = reads()[0];\n\n let mut aa: Vec = reads();\n\n while aa.len() > 0 {\n let mut maxi = 0;\n for i in 0..aa.len() {\n if aa[maxi] < aa[i] {\n maxi = i;\n }\n }\n\n if maxi > 0 && (aa[maxi - 1] - aa[maxi]).abs() >= 2 {\n println!(\"NO\");\n return;\n }\n\n if maxi + 1 < aa.len() && (aa[maxi + 1] - aa[maxi]).abs() >= 2 {\n println!(\"NO\");\n return;\n }\n\n aa.remove(maxi);\n }\n\n println!(\"YES\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5a92926c8da756502af33081e7325399", "src_uid": "704d0ae50bccaa8bc49319812ae0be45", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn input(read_file: bool) -> String {\n if read_file {\n let mut file = std::fs::File::open(\"sample.txt\").unwrap();\n let mut buf = String::new();\n file.read_to_string(&mut buf).unwrap();\n buf\n } else {\n let mut buf = String::new();\n std::io::stdin().read_to_string(&mut buf).unwrap();\n buf.trim_end().to_owned()\n }\n}\n\nfn solve(ws: &mut std::str::SplitWhitespace) {\n let r: f64 = ws.next().unwrap().parse().unwrap();\n let x: f64 = ws.next().unwrap().parse().unwrap();\n let y: f64 = ws.next().unwrap().parse().unwrap();\n let xd: f64 = ws.next().unwrap().parse().unwrap();\n let yd: f64 = ws.next().unwrap().parse().unwrap();\n\n let dist = ((xd - x).powi(2) + (yd - y).powi(2)).sqrt();\n let r2 = 2.0 * r;\n\n println!(\"{}\", (dist / r2).ceil() as i32);\n}\n\nfn main() {\n const READ_FROM_FILE: bool = false;\n\n let s = input(READ_FROM_FILE);\n let mut ws = s.split_whitespace();\n\n solve(&mut ws);\n}\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "a0e6e50dd1ec67dc8439575be277455f", "src_uid": "698da80c7d24252b57cca4e4f0ca7031", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let r: f64 = input.p();\n let x: f64 = input.p();\n let y: f64 = input.p();\n let xx: f64 = input.p();\n let yy: f64 = input.p();\n println!(\"{}\", (((x - xx).powi(2) + (y - yy).powi(2)).sqrt() / (2. * r)).ceil());\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "bc26071b79088e9e254f035436ebe6b2", "src_uid": "698da80c7d24252b57cca4e4f0ca7031", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let n: usize = {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.trim().parse().unwrap()\n };\n\n let a: Vec = {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.split_whitespace().map(|k| k.parse().unwrap()).collect()\n };\n\n let ans = n % 2 == 1 && a.first().unwrap() % 2 == 1 && a.last().unwrap() % 2 == 1;\n\n if ans {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "159aa74270406ae3886f8f7c56e41122", "src_uid": "2b8c2deb5d7e49e8e3ededabfd4427db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{self, BufRead};\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! scan_to_vec {\n ($count:expr, $t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n for _ in 0..$count {\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_to_vec: failed at `handle.read_line`.\");\n result.push(buffer.trim().parse::<$t>()\n .expect(\"scan_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line_to_vec {\n ($t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line_to_vec: failed at `handle.read_line`.\");\n \n for s in buffer.split_whitespace() {\n result.push(s.parse::<$t>()\n .expect(\"scan_line_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line {\n () => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n buffer\n });\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\ntrait Ext {\n fn is_odd(&self) -> bool;\n fn is_even(&self) -> bool;\n}\n\nimpl Ext for i32 {\n #[inline]\n fn is_odd(&self) -> bool {\n self % 2 != 0\n }\n\n #[inline]\n fn is_even(&self) -> bool {\n self % 2 == 0\n }\n}\n\nfn main() {\n let (n,) = scan_line!(usize);\n let array = scan_line_to_vec!(i32);\n\n let mut result = true;\n result &= array[0].is_odd();\n result &= array[n - 1].is_odd();\n result &= (array.len() as i32).is_odd();\n\n\n if result {\n println!(\"YES\")\n } else {\n println!(\"NO\")\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f87f23ef33548a84d2dc34436dd90b3b", "src_uid": "2b8c2deb5d7e49e8e3ededabfd4427db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut sc = new(std::io::stdin());\n let n: usize = sc.next();\n let mut res = 1_000_000_000;\n for h in 1..(n + 1) {\n let w = (n + h - 1) / h;\n\n if (h + w) * 2 < res {\n res = (h + w) * 2;\n }\n }\n println!(\"{}\", res);\n}\n\nuse std::io;\nuse std::io::BufRead;\n\npub struct Scanner {\n br: io::BufReader,\n // Read tokens are stored in reversed order per line.\n buf: Vec,\n}\n\npub fn new(r: R) -> Scanner {\n Scanner::new(r)\n}\n\nimpl Scanner {\n #[inline]\n fn new(r: R) -> Scanner {\n Scanner {\n br: io::BufReader::new(r),\n buf: vec![],\n }\n }\n #[inline]\n pub fn next(&mut self) -> T\n where T: std::str::FromStr,\n T::Err: std::fmt::Debug\n {\n self.next_string().map(|s| s.parse::().expect(\"Parse failed: \")).unwrap()\n }\n fn next_string(&mut self) -> Option {\n self.buf.pop().or_else(|| match self.update() {\n true => self.next_string(),\n false => None,\n })\n }\n #[inline]\n fn update(&mut self) -> bool {\n let mut s = String::new();\n let res = self.br.read_line(&mut s);\n match res.expect(\"I/O error.\") {\n 0 => false,\n _ => {\n self.buf = s.split_whitespace().map(|x| x.to_string()).rev().collect();\n true\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "640a780e5dda047369a51cc29a42da29", "src_uid": "414cc57550e31d98c1a6a56be6722a12", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{min, max};\nuse std::f64::consts::*;\nuse std::mem::swap;\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: i32 = 1000000007;\n\n#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone)]\nstruct Pair(A, B);\n\nstruct Input\n{\n\tbuffer: Buf\n}\n\nimpl Input\n{\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\t#[inline]\n\tfn read_int(&mut self) -> i32 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_long(&mut self) -> i64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_usize(&mut self) -> usize {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_double(&mut self) -> f64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n}\nmacro_rules! read {\n () => {};\n\t($inf:ident,$($t:ty),*) => ({($({$inf.read_word().parse::<$t>().expect(\"Parsing error\")}),*)});\n}\nfn gcd + Copy>(x: T, y: T) -> T {\n\tlet (mut a, mut b) = (x, y);\n\twhile b > T::from(0) {\n\t\ta %= b;\n\t\tswap(&mut a, &mut b);\n\t}\n\ta\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input {\n\t\t\t\tbuffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\"))\n\t\t\t};\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(stdin()) };\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output)\n{\n\tlet n = read!(inf,i32);\n\tlet mut s = (n as f64).sqrt() as i32;\n\tif s * s < n {\n\t\ts += 1;\n\t}\n\n\twriteln!(ouf, \"{}\", 2 * (s + ((n + s - 1) / s)));\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "822782e4606832102eac7667a6f8e41d", "src_uid": "414cc57550e31d98c1a6a56be6722a12", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\nuse std::str::FromStr;\nuse std::collections::HashSet;\n\nfn main() {\n let stdin = stdin();\n let mut sc = Scanner::new(stdin.lock());\n\n let x = sc.next::();\n let mut a = vec![0; x];\n for i in 0..x {\n a[i] = sc.next::();\n }\n let mut s = HashSet::new();\n let mut result = vec![];\n for v in a.iter().rev() {\n if s.contains(&v) {\n continue;\n }\n s.insert(v);\n result.push(v);\n }\n result.reverse();\n println!(\"{}\", result.len());\n for i in 0..result.len() {\n print!(\"{}\", result[i]);\n if i < result.len() - 1 {\n print!(\" \");\n }\n }\n println!(\"\");\n}\n\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "be50dd6b00ddfebe500d1ea5348ccf66", "src_uid": "1b9d3dfcc2353eac20b84c75c27fab5a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n if self.f[crt] { return; }\n self.c += 1;\n self.f[crt] = true;\n self.v.push(crt);\n self.vc[crt] = self.c;\n self.u[crt] = self.v.len()-1;\n for i in 0..self.e[crt].len() {\n self.dfs(self.e[crt][i]);\n }\n //debug!(crt, self.c, self.vc[crt]);\n self.vc[crt] = self.c - self.vc[crt];\n }\n}\n\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let mut a:Vec = (0..n).map(|_| read()).collect();\n a.reverse();\n let mut v = vec![];\n for i in 0..n {\n let mut f = false;\n for j in 0..v.len() {\n if a[i] == v[j] {\n f = true;\n }\n }\n if !f {\n v.push(a[i]);\n }\n }\n v.reverse();\n println!(\"{}\",v.len());\n for e in v {print!(\"{} \",e);} println!();\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "31eb1ba08fd6d0fde1fd64aa92f20d03", "src_uid": "1b9d3dfcc2353eac20b84c75c27fab5a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn vec_to_split_str(v: Vec) -> String {\n let mut s = String::with_capacity(2 * v.len());\n for elem in v {\n s.push_str(&format!(\"{} \", elem));\n }\n s.trim().to_string()\n}\n\nfn input_split() -> Vec {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn main() {\n {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n }\n\n let mut nums = input_split();\n nums.reverse();\n\n let mut filtered = Vec::with_capacity(nums.len());\n for num in nums {\n if !filtered.contains(&num) {\n filtered.push(num)\n }\n }\n\n filtered.reverse();\n println!(\"{}\", filtered.len());\n println!(\"{}\", vec_to_split_str(filtered));\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b21e17a127557608dd93e8bd9c79687b", "src_uid": "1b9d3dfcc2353eac20b84c75c27fab5a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub fn main() {\n let mut input = io::Input::new();\n\n let mut vis = vec![false; 1001];\n\n let n = input.next();\n\n let mut u = Vec::::new();\n let mut v = Vec::::new();\n\n for _i in 0..n {\n u.push(input.next());\n }\n u.reverse();\n\n for a in u {\n if ! vis[a as usize] {\n vis[a as usize] = true;\n v.push(a);\n }\n }\n\n v.reverse();\n\n println!(\"{}\", v.len());\n for u in v {\n print!(\"{} \", u);\n }\n println!();\n}\n\n#[allow(unused)]\npub mod io {\n\n const BUFFER_SIZE: usize = 8192;\n\n use std::collections::VecDeque;\n use std::str::FromStr;\n use std::io;\n use std::io::Read;\n\n type AsciiStr = Vec;\n\n pub struct Input {\n token_buffer: VecDeque,\n remaining: String,\n }\n\n impl Input {\n\n pub fn new() -> Input {\n Input {\n token_buffer: VecDeque::with_capacity(100),\n remaining: String::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where T::Err: ::std::fmt::Debug\n {\n self.fill_buffer();\n self.token_buffer.pop_front().unwrap().parse().unwrap()\n }\n\n pub fn next_ascii_string(&mut self) -> AsciiStr {\n self.fill_buffer();\n Vec::from(self.token_buffer.pop_front().unwrap().as_bytes())\n }\n\n fn fill_buffer(&mut self) {\n while self.token_buffer.is_empty() {\n let mut minibuffer = [0u8; BUFFER_SIZE];\n let size = io::stdin().read(&mut minibuffer[..]).unwrap();\n\n self.remaining += &String::from_utf8_lossy(&minibuffer[..size]);\n\n if self.remaining.trim().len() > 0 {\n for token in self.remaining.trim().split_whitespace() {\n self.token_buffer.push_back(String::from(token))\n }\n\n if size > 0 && ! self.remaining.ends_with(|c: char|char::is_ascii_whitespace(&c)) {\n self.remaining = self.token_buffer.pop_back().unwrap();\n } else {\n self.remaining.clear();\n }\n\n } else if size == 0 {\n panic!(\"EOF\");\n }\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "347a9db9ab70bb75f5bedfbbda398243", "src_uid": "1b9d3dfcc2353eac20b84c75c27fab5a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Read, Write, BufWriter};\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($format:expr) => (write!(out,$format).unwrap());\n ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())\n }\n let n = get();\n let a: Vec = (0..n).map(|_| get()).collect();\n let mut marked = vec![false; n];\n for i in 0 .. n {\n for j in i + 1 .. n {\n if a[i] == a[j] {\n marked[i] = true;\n }\n }\n }\n let mut left = Vec::new();\n for i in 0 .. n {\n if !marked[i] { left.push(a[i]); }\n }\n puts!(\"{}\\n\", left.len());\n for i in 0 .. left.len() {\n puts!(\"{}{}\", left[i], if i == left.len() - 1 { \"\\n\" } else { \" \" });\n }\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6fccfe24c1dc4d46ffd11af34da6e675", "src_uid": "1b9d3dfcc2353eac20b84c75c27fab5a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Basics\n\n#![allow(unused_imports)]\n#![allow(dead_code)]\n\n//extern crate rand;\n\nuse std::io::prelude::*;\nuse std::mem;\nuse std::io;\nuse std::io::BufRead;\nuse std::io::BufReader;\nuse std::string;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::vec::Vec;\nuse std::collections::LinkedList;\nuse std::num;\nuse std::ops;\nuse std::fmt::Debug;\nuse std::str::FromStr;\nuse std::ops::Shr;\n\nstruct Cin {\n data: LinkedList,\n}\n\nimpl Cin {\n fn new() -> Self {\n Cin { data: LinkedList::new() }\n }\n fn read_line(&self) -> String {\n let mut s: String = String::new();\n io::stdin().read_line(&mut s).expect(\"err\");\n s\n }\n fn read_str(&mut self) -> String {\n if self.data.len() == 0 {\n let s = self.read_line();\n// let split = s.split(\"\\\\s+\");\n let split = s.split_whitespace();\n for el in split {\n self.data.push_back(String::from(el));\n }\n }\n self.data.pop_front().expect(\"empty\")\n }\n fn read_int(&mut self) -> i64 {\n self.read_str().parse().expect(\"err parse\")\n }\n fn read_vec(&mut self, size: &i64) -> Vec {\n let mut v: Vec = Vec::new();\n for _i in 0..*size {\n v.push(self.read_int());\n }\n v\n }\n}\n\nfn main() {\n let mut cin = Cin::new();\n let n: i64 = cin.read_int();\n let vec = cin.read_vec(&n);\n let mut s: HashSet = HashSet::new();\n let mut res: LinkedList = LinkedList::new();\n for i in 0..vec.len() {\n let ref value = vec[vec.len() - 1 - i];\n let option = s.get(value).is_some();\n if !option {\n s.insert(value.clone());\n res.push_front(*value);\n }\n }\n println!(\"{}\", res.len());\n for r in res { print!(\"{} \", r); }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c3581cfd8785157288ef8f9906b28766", "src_uid": "1b9d3dfcc2353eac20b84c75c27fab5a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> String {\n let stdin = std::io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n String::from(line.trim())\n}\n\nmacro_rules! scanln {\n ($($ty: ty),*) => {{\n let line = readln();\n let mut iter = line.split_whitespace();\n ($(iter.next().unwrap().parse::<$ty>().unwrap()),*)\n }}\n}\n\nfn main() {\n let (m, n) = scanln!(i32, i32);\n let mut total = (m / 2) * (n / 2) * 2;\n if m % 2 == 1 {\n total += n / 2;\n }\n if n % 2 == 1 {\n total += m / 2;\n }\n println!(\"{}\", total);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "8bd73feb7edc74ec687463488f093ce5", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (m, n) = read_inp();\n let ans = (m * (n / 2)) + ((n % 2) * (m / 2));\n println!(\"{}\", ans);\n}\n\nfn read_inp() -> (i32, i32) {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"x\");\n let buffer: Vec = buffer.split_whitespace().map(|i| i.parse().unwrap()).collect();\n (buffer[0], buffer[1])\n}", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "2f9402f5df653cbaa7331da780edbaab", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let n: (i32,i32) = (scan.next::(),scan.next::());\n let mut result = 0i32;\n\n result = (n.0 * n.1) - (n.0 * n.1)%2;\n result /=2;\n\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "6b2162d8c79ef358259885dd79454f12", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)?;\n\n let numbers: Vec = input\n .trim()\n .split(\" \")\n .map(|x| x.parse::().unwrap())\n .take(2)\n .collect();\n \n let (m, n) = (numbers[0], numbers[1]);\n\n let result = m * n / 2;\n println!(\"{}\", result);\n\n return Ok(());\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "c69d613ed90f11dec476bf351cf33f2b", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let inputs: Vec = reads(sin);\n let m = inputs[0];\n let n = inputs[1];\n\n let case1 = (m / 2.).floor() as u64 * n as u64;\n let case2 = (n / 2.).floor() as u64 * m as u64;\n let mut remain = 0;\n let mut other = 0;\n\n let ans = if case1 < case2 {\n other = m as u64;\n case2\n } else {\n other = n as u64;\n case1\n };\n\n if m as u64 % 2 != 0 && n as u64 % 2 != 0 {\n remain = (other as f64 / 2.).floor() as u64;\n }\n\n println!(\"{}\", ans + remain);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "6473fb3445232d0c5468e597f4f8fa84", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/problemset/problem/50/A\n\nfn main() {\n use std::io;\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let mut ns = buf.split(\" \")\n .map(|str| str.trim().parse::().unwrap());\n let m = ns.next().unwrap();\n let n = ns.next().unwrap();\n\n println!(\"{}\", (m * n) / 2);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "f1c41e892ffbc911af6a7c8799e2b74b", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let a = input.split_whitespace()\n .map(|x| x.parse().unwrap())\n .fold(1, |a, x: u32| a * x);\n println!(\"{}\", a / 2);\n\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "8e515ac0708c9cc4103bda80b2aa37c6", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\n\nfn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn read_vec(split_char: char) -> Vec {\n read_str()\n .split(split_char)\n .map(|value| value.parse::().ok().expect(\"Error\"))\n .collect()\n}\n\nfn read_tuple() -> (T, T) {\n let buffer: Vec = read_vec(' ');\n (buffer[0], buffer[1])\n}\n\nfn main() {\n let (m, n): (u16, u16) = read_tuple();\n println!(\"{}\", (m * n) / 2);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "635e05e7129b7a65764ae6a907a1ff57", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (on, ) = R!(u64);\n let names = vec![\"Sheldon\".to_string(), \"Leonard\".to_string(), \"Penny\".to_string(), \"Rajesh\".to_string(), \"Howard\".to_string()];\n\n let mut n: u64 = on - 1;\n let mut seg: u64 = 1;\n while n >= seg * 5 {\n n -= seg * 5;\n seg *= 2;\n }\n println!(\"{}\", names[(n / seg) as usize]);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "23e04dec57a150d0b497a7f78c407620", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input() -> u32 {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n}\n\nfn main() {\n let mut n = input();\n let (mut repet, mut queue_len) = (1, 5);\n\n while n > queue_len {\n n -= queue_len;\n queue_len *= 2;\n repet *= 2;\n }\n\n let mut index = 0;\n while n > repet {\n n -= repet;\n index += 1;\n }\n\n let options = [\"Sheldon\", \"Leonard\", \"Penny\", \"Rajesh\", \"Howard\"];\n\n println!(\"{}\", options[index]);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "90992124797d30b79320579136491bb8", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut n: i32 = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n };\n let mut group = 1;\n while n > group * 5 {\n n -= group * 5;\n group *= 2;\n }\n let index = (n - 1) / group;\n let names = vec![\"Sheldon\", \"Leonard\", \"Penny\", \"Rajesh\", \"Howard\"];\n println!(\"{}\", names[index as usize]);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "8e1f9f2245ebb1eb4310b2361fcb77c9", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nconst NAMES : [&str; 6] = [\"\",\n \"Sheldon\",\n \"Leonard\",\n \"Penny\",\n \"Rajesh\",\n \"Howard\"]; \n\nfn next_width(w : u64) -> u64 {\n 2 * w\n}\n\nfn next_interval(h : u64, w : u64) -> (u64, u64) {\n (h + 1, h + w)\n}\n\nfn within_interval(l : u64, h : u64, n : u64) -> bool {\n (n >= l) && (n <= h)\n}\n\nfn drinks_nth(n : u64) -> String {\n let mut l = 1;\n let mut h = 5;\n let mut w = h - l + 1;\n loop {\n if within_interval(l, h, n) {\n break;\n } else {\n w = next_width(w);\n let (x, y) = next_interval(h, w); \n l = x;\n h = y;\n }\n }\n let b = w / 5;\n let i = ((n - l) / b) + 1;\n String::from(NAMES[i as usize])\n}\n\nfn main() {\n let stdin = io::stdin();\n let n = read_t(&stdin);\n println!(\"{}\", drinks_nth(n));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "da507237dd1713ee744448c773ac730f", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn get_cycle_rate(c: u32) -> u64 {\n (2 as u64).pow(c)\n}\n\nfn get_cycle_person_width(c: u32) -> u64 {\n 5 * get_cycle_rate(c)\n}\n\n/// return cycle number and cycle offset\nfn get_cycle(n: u64) -> Option<(u32, u64)> {\n let mut total = 0;\n\n for i in 0..100 {\n if n < (total + get_cycle_person_width(i)) {\n return Some((i, total));\n }\n\n total = total + get_cycle_person_width(i);\n }\n\n return None;\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let n: u64 = read(sin);\n\n let idx = n - 1;\n\n let queue = [\"Sheldon\", \"Leonard\", \"Penny\", \"Rajesh\", \"Howard\"];\n\n // 1.. 2.. 4.. 8..\n // Sheldon, Leonard, Penny, Rajesh, Howard\n // Sheldon, Sheldon, Leonard, Leonard, Penny, Penny, Rajesh, Rajesh, Howard, Howard\n // Sheldon, Sheldon, Sheldon, Sheldon, Leonard, Leonard, Leonard, Leonard, ...\n\n // elements\n // 5 + 10 + 20 + 40\n // 0 1 2 3\n\n // 5 * 2^i\n let (cycle, offset) = get_cycle(idx).unwrap();\n\n println!(\n \"{}\",\n queue[((idx - offset) / get_cycle_rate(cycle)) as usize]\n );\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e39e904846f0d15c182543bb911b94ea", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect()\n}\n\nconst NAMES: &'static [&'static str] = &[\"Sheldon\", \"Leonard\", \"Penny\", \"Rajesh\", \"Howard\"];\n\nfn main() {\n let input = readln();\n let mut n = input[0] - 1;\n\n let mut cnt = 1;\n let mut total_len = 0;\n while total_len + cnt * 5 <= n {\n total_len += cnt * 5;\n cnt *= 2;\n }\n\n n -= total_len;\n n /= cnt;\n\n println!(\"{}\", NAMES[n as usize]);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "4bc0bb6063f300b27052229a91739a8a", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let mut n = input.i() - 1;\n while n >= 5 {\n n = (n - 5) / 2;\n }\n let a = [\"Sheldon\", \"Leonard\", \"Penny\", \"Rajesh\", \"Howard\"];\n println!(\"{}\", a[n as usize]);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d20dfa7179b463f6fbaaa5b3ff56de17", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut n: u64 = scan.next();\n n -= 1;\n let mut current: u64 = 5;\n while current <= n {\n n -= current;\n current*=2;\n }\n let each = current / 5;\n let index = (n/each) as usize;\n let persons: [&str; 5] = [\"Sheldon\", \"Leonard\", \"Penny\", \"Rajesh\", \"Howard\"];\n println!(\"{}\", persons[index]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "fcbd7a940c360912b33e7f783828c72a", "src_uid": "023b169765e81d896cdc1184e5a82b22", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n // two input strings\n let mut s1 = String::new();\n let mut s2 = String::new();\n std::io::stdin().read_line(&mut s1).unwrap();\n std::io::stdin().read_line(&mut s2).unwrap();\n\n let lcs1: Vec = s1.trim().to_lowercase().chars().collect();\n let lcs2: Vec = s2.trim().to_lowercase().chars().collect();\n\n // Compare strings\n let mut r: i32 = 0;\n let mut i: usize = 0;\n let mut j: usize = 0;\n while i < lcs1.len() && j < lcs2.len() {\n if lcs1[i] == lcs2[j] {\n i += 1;\n j += 1;\n continue;\n }\n\n if lcs1[i] < lcs2[j] {\n r = -1;\n break;\n }\n\n r = 1;\n break;\n }\n\n // Display results\n println!(\"{}\", r);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d3c53c4fa90f7f9185cd26ab88053915", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::Ordering;\n\nfn main() -> io::Result<()> {\n let mut a = String::new();\n let mut b = String::new();\n\n io::stdin().read_line(&mut a)?;\n io::stdin().read_line(&mut b)?;\n\n match a.to_lowercase().cmp(&b.to_lowercase()) {\n Ordering::Greater => println!(\"1\"),\n Ordering::Equal => println!(\"0\"),\n Ordering::Less => println!(\"-1\")\n }\n\n return Ok(());\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "edb5480c3b193780562010fc854051da", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": " \nuse std::io::{self};\n\nfn main() {\n let mut buffer1 = String::new();\n let mut buffer2 = String::new();\n io::stdin().read_line(&mut buffer1).expect(\"???\");\n io::stdin().read_line(&mut buffer2).expect(\"???\");\n\n println!(\"{}\", {\n if &(buffer1.to_ascii_lowercase()) < &(buffer2.to_ascii_lowercase()) {\n -1\n } else if buffer1.eq_ignore_ascii_case(&buffer2) {\n 0\n } else {\n 1\n }\n });\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "2060b143405f2a7e19b2ee37413a544d", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin};\n\nfn main() {\n\tlet mut s1 = String::from(\"\");\n\tlet mut s2 = String::from(\"\");\n\n\tstdin().read_line(&mut s1).expect(\"\");\n\tstdin().read_line(&mut s2).expect(\"\");\n\n\ts1 = s1.to_lowercase().to_string();\n\ts2 = s2.to_lowercase().to_string();\n\n\tif s1 > s2 {\n\t\tprint!(\"{}\", 1);\n\t} else if s1 < s2 {\n\t\tprint!(\"{}\", -1);\n\t} else {\n\t\tprint!(\"{}\", 0);\n\t}\n\t\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "3067d101ee06e526a59bd4df106ea8f9", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*};\nuse std::str;\n\n#[allow(unused_must_use)]\nfn run(mut reader: Scanner, mut writer: W) {\n let s1: String = reader.next_line().to_lowercase();\n let s2: String = reader.next_line().to_lowercase();\n\n if s1 < s2 {\n writeln!(writer, \"-1\");\n } else if s1 == s2 {\n writeln!(writer, \"0\");\n } else {\n writeln!(writer, \"1\");\n }\n\n}\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n run(reader, writer);\n}\n\npub struct Scanner {\n reader: B,\n buffer_string: Vec,\n buffer_iterator: str::SplitWhitespace<'static>,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n return Self {\n reader,\n buffer_string: Vec::new(),\n buffer_iterator: \"\".split_whitespace()\n };\n }\n\n pub fn next(&mut self) -> T {\n loop {\n //if buffer already exists, just use existing buffer\n if let Some(token) = self.buffer_iterator.next() {\n return token.parse().ok().expect(\"Fail to parse token\");\n }\n\n //get new line\n self.buffer_string.clear();\n self.reader.read_until(b'\\n', &mut self.buffer_string).expect(\"Failed to read\");\n\n //split by white space\n self.buffer_iterator = unsafe {\n let slice = str::from_utf8_unchecked(&self.buffer_string);\n std::mem::transmute(slice.split_whitespace())\n };\n }\n }\n\n pub fn next_line(&mut self) -> String {\n //reset buffer\n self.buffer_iterator = \"\".split_whitespace();\n self.buffer_string.clear();\n\n let mut input: String = String::new();\n self.reader.read_line(&mut input).expect(\"Failed to read line\");\n return input.trim().to_string();\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "fb33a4d77e702c11533b77962a0cee10", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\nuse std::cmp::Ordering;\n\nfn main() {\n let stdin = io::stdin();\n let mut iterator = stdin.lock().lines();\n let line1 = iterator.next().unwrap().unwrap().to_ascii_lowercase();\n let line2 = iterator.next().unwrap().unwrap().to_ascii_lowercase();\n match line1.cmp(&line2) {\n Ordering::Less => println!(\"-1\"),\n Ordering::Greater => println!(\"1\"),\n Ordering::Equal => println!(\"0\"),\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "12d68efe8766a7e18ee5f4e348c99a48", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports, deprecated, dead_code)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{VecDeque,HashSet,HashMap,BinaryHeap};\n// Module for v1.15.1\nuse std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead\n\n// Functions\n\n// Main\nfn main() {\n\n input! {\n s1: String,\n s2: String\n }\n\n let s1 = s1.to_lowercase();\n let s2 = s2.to_lowercase();\n\n let mut ans = 0;\n if s1 < s2 {\n ans = -1;\n } else if s1 > s2 {\n ans = 1;\n }\n\n println!(\"{}\", ans);\n\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "90956a3a0508be9b4488a5eea614c557", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufReader, BufWriter, Read, Write, stdin, stdout};\n\npub struct Scanner {\n pub buffer: Vec,\n pub reader: U,\n}\nimpl Scanner {\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_to_string(&mut input).expect(\"Failed read\");\n self.buffer = input.lines().rev().map(String::from).collect();\n }\n }\n\n pub fn new(reader: U) -> Self {\n return Scanner {\n buffer: vec![],\n reader,\n };\n }\n}\npub fn solution_of_p112a(input: &mut Read, out: &mut Write) {\n let mut scanner = Scanner::new(input);\n let arr1: Vec = scanner\n .next::()\n .to_ascii_lowercase()\n .chars()\n .collect();\n let arr2: Vec = scanner\n .next::()\n .to_ascii_lowercase()\n .chars()\n .collect();\n\n let res = lexicographical_order(arr1, arr2);\n write!(out, \"{}\\n\", res).ok();\n}\n\npub fn lexicographical_order(arr1: Vec, arr2: Vec) -> i32 {\n let l = arr1.len(); // assume the 2 string has the same length\n for i in 0..l {\n let u1 = arr1[i] as u8;\n let u2 = arr2[i] as u8;\n if u1 < u2 {\n return -1;\n } else if u1 > u2 {\n return 1;\n }\n }\n return 0;\n}\n\nfn main() {\n solution_of_p112a(&mut stdin(), &mut stdout());\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "82e1772a73f0a6124bbb955b916887ee", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::collections::HashSet;\n\nfn read_line<'a>() -> Result> {\n let mut line = String::new();\n stdin().read_line(&mut line)?;\n\n Ok(line.trim().to_owned())\n}\n\nfn main() -> Result<(), Box> {\n let line = read_line()?;\n let mut nums = line\n .split(' ')\n .map(|s| s.parse::().unwrap());\n\n let _ = nums.next().unwrap();\n let mut b = nums.next().unwrap();\n\n let line = read_line()?;\n\n let nums = line\n .split(' ')\n .map(|s| s.parse::().unwrap())\n .collect::>();\n\n let evency = nums\n .iter()\n .map(|n| if n % 2 == 0 { 1 } else { -1 })\n .collect::>();\n\n let mut split_points = HashSet::new();\n let mut s = 0;\n\n for (i, e) in evency[..evency.len() - 1].iter().enumerate() {\n s += e;\n\n // println!(\"{}, {}, {}\", i, s, e);\n\n if s == 0 {\n split_points.insert(i);\n }\n }\n\n let mut diffs = nums\n .iter()\n .zip(&nums[1..])\n .map(|(&prev, &curr)| (curr - prev).abs())\n .enumerate()\n .collect::>();\n \n diffs.sort_unstable_by_key(|&(_, diff)| diff);\n\n // println!(\"diffs: {:?}\", diffs);\n // println!(\"split_points: {:?}\", split_points);\n\n let mut ans = 0;\n\n for (i, diff) in diffs {\n if split_points.contains(&i) && b >= diff {\n // println!(\"split at {}, price {}, current budget: {}\", i, diff, b);\n\n ans += 1;\n b -= diff;\n }\n }\n\n\n println!(\"{}\", ans);\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "dp", "greedy"], "code_uid": "33319a059c8f8f8db566cdd6a8e79f26", "src_uid": "b3f8e769ee7719ea5c9f458428b16a4e", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::cmp::Ordering;\n\nfn cut( accum: &Vec<(i64,i64)>, nums: &Vec, s: usize, e: usize ) -> (i64,i64) {\n //println!(\"cut range: {},{}\", s,e);\n for idx in s..e {\n let b = ( accum[e-1].0 - accum[idx].0, accum[e-1].1 - accum[idx].1 );\n let a = if s > 0 {\n ( accum[idx].0 - accum[s-1].0, accum[idx].1 - accum[s-1].1 )\n } else {\n ( accum[idx].0, accum[idx].1 )\n };\n //println!(\"idx:{}, a: {:?}, b: {:?}\", idx, a, b );\n if b.0 == b.1 && b.0 != 0 && a.0 == a.1 && a.0 != 0 {\n //make a cut between (idx, idx+1)\n //println!(\"make a cut between {}, {}\", idx, idx+1 );\n return (idx as i64,idx as i64 + 1) \n }\n }\n return (-1,-1)\n}\n\nfn main() {\n\n use std::collections::{HashMap,HashSet, BinaryHeap};\n \n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n handle.read_to_string(&mut buffer).unwrap();\n\n let input_strs = buffer.split_whitespace().map( |x| x.parse::().unwrap() ).collect::< Vec >();\n\n let n = *input_strs.iter().nth(0).unwrap();\n let b = *input_strs.iter().nth(1).unwrap();\n \n let nums = input_strs.iter().skip(2).cloned().collect::< Vec >();\n\n //println!( \"{:?}\", nums );\n\n\n let mut eo = nums.iter().map( |x| if *x % 2 == 0 { true } else { false } ).collect::>();\n\n let mut count_e = 0;\n let mut count_o = 0;\n let accum = eo.iter().enumerate().map(|(k,x)| {\n if *x == true { count_e += 1; } else { count_o += 1; }\n ( count_e, count_o )\n } ).collect::< Vec< (i64,i64) > >();\n \n //println!( \"{:?}\", accum );\n\n let mut cut_idxs = cut( &accum, &nums, 0, nums.len() );\n let mut accum_cost = 0;\n let mut num_cuts = 0;\n\n let mut possible_cuts = vec![];\n loop {\n if cut_idxs.0 == -1 || cut_idxs.1 == -1 {\n break;\n }\n let cost_cut = (nums[cut_idxs.0 as usize] - nums[cut_idxs.1 as usize]).abs();\n\n cut_idxs = cut( &accum, &nums, cut_idxs.1 as usize, nums.len() );\n possible_cuts.push( ( cost_cut, cut_idxs ) );\n }\n\n possible_cuts.sort();\n \n // println!( \"{:?}\", possible_cuts );\n\n for i in possible_cuts.iter() {\n if accum_cost + i.0 <= b {\n accum_cost += i.0;\n num_cuts += 1;\n } else {\n break;\n }\n }\n\n println!( \"{}\", num_cuts );\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "dp", "greedy"], "code_uid": "1a50be2ffa43c657b37d2e55b899e2b9", "src_uid": "b3f8e769ee7719ea5c9f458428b16a4e", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let n = get!(u64);\n let m9 = (0..)\n .take_while(|&x| (2 * n - 1) >= 10u64.pow(x as u32) - 1)\n .last()\n .unwrap();\n\n let mut ans = 0;\n for i in 0.. {\n let y = i as u64 * 10u64.pow(m9 as u32) + 10u64.pow(m9 as u32) - 1;\n if y > 2 * n - 1 {\n break;\n }\n if y <= 2 * n - 1 && y > 0 {\n if y > n {\n ans += (n - (y - n) - 1) / 2 + 1;\n } else {\n ans += (y - 1) / 2;\n }\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "2e285e02a77a2028ae0de14ea626cccb", "src_uid": "c20744c44269ae0779c5f549afd2e3f2", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::prelude::*;\n std::io::stdin().read_to_string(&mut input).unwrap();\n let mut it = input.split_whitespace();\n\n let n: u64 = it.next().unwrap().parse().unwrap();\n\n if 2 * n < 10 {\n let ans = n * (n - 1) / 2;\n println!(\"{}\", ans);\n return;\n }\n\n let mut max_nine_count = 0;\n let mut k = 2 * n;\n while k >= 10 {\n max_nine_count += 1;\n k /= 10;\n }\n\n let mut ans = 0;\n\n for mut i in 1..k + 1 {\n for _ in 0..max_nine_count {\n i *= 10;\n }\n let j = i / 2;\n let p = std::cmp::min(i - 2, n) - j + 1;\n ans += p;\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "6ebd8dd8fcdab17ad73e4a81a488665d", "src_uid": "c20744c44269ae0779c5f549afd2e3f2", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io;\n\nfn to_pairs(line: &str) -> Vec<(i32, i32)> {\n\tlet mut iter = line.trim().split_whitespace();\n\tlet mut ret = Vec::new();\n\twhile let Some(x) = iter.next() {\n\t\tret.push((x.parse().unwrap(),\n\t\t iter.next().unwrap().parse().unwrap()));\n\t}\n\tret.sort();\n\treturn ret\n}\n\nfn get_unique(s1: (i32, i32), s2: (i32, i32)) -> Option {\n\tlet mut v = Vec::new();\n\tv.push(s1.0);\n\tv.push(s1.1);\n\tv.push(s2.0);\n\tv.push(s2.1);\n\tv.sort();\n\tv.dedup();\n\tif v.len() != 3 { return None; }\n\tfor x in v {\n\t\tif (x == s1.0 || x == s1.1) && (x == s2.0 || x == s2.1) {\n\t\t\treturn Some(x);\n\t\t}\n\t}\n\treturn None;\n}\n\nfn get_only_bit(x: i32) -> Option {\n\tlet mut count = 0;\n\tlet mut last = 0;\n\tfor i in 1..10 {\n\t\tif (x >> i & 1) != 0 {\n\t\t\tcount += 1;\n\t\t\tlast = i;\n\t\t}\n\t}\n\tif count == 1 { return Some(last); }\n\treturn None;\n}\n\nfn solve(s1: Vec<(i32, i32)>, s2: Vec<(i32, i32)>) -> i32 {\n\tlet mut va: HashMap<(i32, i32), i32> = HashMap::new();\n\tlet mut vb: HashMap<(i32, i32), i32> = HashMap::new();\n\tlet mut vab = 0;\n\tfor a in s1.iter() {\n\t\tfor b in s2.iter() {\n\t\t\tif let Some(x) = get_unique(*a, *b) {\n\t\t\t\tva.entry(*a)\n\t\t\t\t\t.and_modify(|e| { *e |= 1 << x })\n\t\t\t\t\t.or_insert(1 << x);\n\t\t\t\tvb.entry(*b)\n\t\t\t\t\t.and_modify(|e| { *e |= 1 << x })\n\t\t\t\t\t.or_insert(1 << x);\n\t\t\t\tvab |= 1 << x;\n\t\t\t}\n\t\t}\n\t}\n\tif let Some(x) = get_only_bit(vab) { return x; }\n\tfor (_, v) in va.iter() {\n\t\tif let None = get_only_bit(*v) { return -1; }\n\t}\n\tfor (_, v) in vb.iter() {\n\t\tif let None = get_only_bit(*v) { return -1; }\n\t}\n\treturn 0;\n}\n\nfn main() -> io::Result<()> {\n\tlet f = io::stdin();\n\tlet mut line = String::new();\n\tf.read_line(&mut line)?;\n\tline.clear();\n\tf.read_line(&mut line)?;\n\tlet s1 = to_pairs(&line);\n\tline.clear();\n\tf.read_line(&mut line)?;\n\tlet s2 = to_pairs(&line);\n\tprintln!(\"{}\", solve(s1, s2));\n\n\tOk(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "bitmasks"], "code_uid": "08e2697961efe5ea11862d95f156b226", "src_uid": "cb4de190ae26127df6eeb7a1a1db8a6d", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\nuse std::collections::HashMap;\n\nfn get_num() -> i32 {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n i32::from_str(input.trim()).unwrap()\n}\n\nfn get_nums() -> Vec {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n input.trim()\n .split_whitespace()\n .map(|s| i32::from_str(s).unwrap())\n .collect::>()\n}\n\nfn main() {\n let n = get_num();\n let a = get_nums();\n \n let mut m = HashMap::new();\n let mut min_pos = -1;\n let mut max_pos = -1;\n for (idx, e) in a.iter().enumerate() {\n m.insert(*e, (idx + 1) as i32);\n \n if *e == n {\n max_pos = (idx + 1) as i32;\n }\n\n if *e == 1 {\n min_pos = (idx + 1) as i32;\n }\n }\n\n let mut d = (max_pos - min_pos).abs();\n for i in 1..=n {\n if i == *m.get(&1).unwrap() || i == *m.get(&n).unwrap() {\n continue;\n }\n\n d = std::cmp::max(d, (i - max_pos).abs());\n d = std::cmp::max(d, (i - min_pos).abs());\n }\n\n println!();\n println!(\"{}\", d);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "03443bb6d84d092e847671954837ab22", "src_uid": "1d2b81ce842f8c97656d96bddff4e8b4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n#![allow(unused_imports)]\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::str::FromStr;\nuse std::collections::{VecDeque, HashMap};\n\nfn main() {\n let stdin = io::stdin();\n let mut input = stdin.lock();\n let mut line = String::new();\n input.read_line(&mut line).unwrap();\n let n = get_numbers::(&line)[0];\n line.clear();\n input.read_line(&mut line).unwrap();\n let arr = get_numbers::(&line);\n\n let min_i = arr.iter().position(|&v| v == 1).unwrap();\n let max_i = arr.iter().position(|&v| v == n).unwrap();\n\n let d_min = f64::abs(min_i as f64 - ((n-1) as f64 / 2.0)); // distance to center\n let d_max = f64::abs(max_i as f64 - ((n-1) as f64 / 2.0));\n \n // pick closest to center to move\n let d = if d_min < d_max {\n if min_i < max_i { // move min to 0\n max_i\n } else {\n (n-1)-max_i // move min to end\n }\n } else {\n if max_i < min_i {\n min_i\n } else {\n (n-1)-min_i\n }\n };\n\n println!(\"{}\", d);\n}\n\n/*\n * Utility Functions\n */\n\n// get numbers from line seperated by spaces\nfn get_numbers(line: &str) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n line.split_whitespace()\n .map(|chunk| chunk.parse::().expect(\"failed to parse\"))\n .collect()\n}\n\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "8c2ee166c44f26b72688179475c5856f", "src_uid": "1d2b81ce842f8c97656d96bddff4e8b4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let a = input.vi(n);\n let i = a.iter().position(|&x| x == 1).unwrap();\n let j = a.iter().position(|&x| x == n as i32).unwrap();\n let sol = i.max(j).max(n - i - 1).max(n - j - 1);\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "38ecb799a6f54b7b63db333fc6c35ae4", "src_uid": "1d2b81ce842f8c97656d96bddff4e8b4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io;\n use std::io::prelude::*;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let n: usize = it.next().unwrap().parse().unwrap();\n let a: Vec = it.take(n).map(|x| x.parse().unwrap()).collect();\n\n let mut outmost = 101;\n\n for (i, a) in a.into_iter().enumerate() {\n if a == 1 || a == n {\n if i < outmost {\n outmost = i;\n }\n if n - 1 - i < outmost {\n outmost = n - 1 - i;\n }\n }\n }\n\n let ans = n - 1 - outmost;\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "378fe0b6b7098df66b5732af3be03078", "src_uid": "1d2b81ce842f8c97656d96bddff4e8b4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap, VecDeque, BTreeSet, BTreeMap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let s: Vec = util::line().chars().collect();\n\n let mut dp = vec![vec![0; 3]; s.len()];\n\n for (i, &c) in s.iter().enumerate() {\n match c {\n 'Q' => {\n for k in 0..i {\n dp[i][2] += dp[k][1];\n }\n dp[i][0] += 1;\n }\n 'A' => {\n for k in 0..i {\n dp[i][1] += dp[k][0];\n }\n }\n _ => (),\n }\n }\n\n println!(\"{}\", dp.iter().map(|v| v[2]).sum::());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "4c52fd0eb41daff3fa2cd5fe76be1a38", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main () {\n let mut s = String::new();\n io::stdin().read_line(&mut s);\n let chars : Vec = s.chars().collect();\n let mut cnt = 0;\n for i in 0..s.len () {\n for j in i+1..s.len () {\n for k in j+1..s.len () {\n if chars[i] == 'Q' && chars[j] == 'A' && chars[k] == 'Q' {\n cnt+=1;\n }}}}\n println!(\"{}\", cnt);\n}", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "3487cbca63a75f62571b48d3628bb5ac", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn _main() {\n let mut line = String::new();\n std::io::stdin()\n .read_line(&mut line)\n .expect(\"failed to read\");\n let line: Vec = line.chars().collect();\n let mut cnt = 0usize;\n for i in 0..line.len() {\n for j in i + 1..line.len() {\n for k in j + 1..line.len() {\n if line[i] == 'Q' && line[j] == 'A' && line[k] == 'Q' {\n cnt += 1;\n }\n }\n }\n }\n println!(\"{}\", cnt);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "5233a7b5bc05a02add4110f7943d466b", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n s: chars,\n }\n let mut ans = 0;\n for (i, a) in s.iter().enumerate() {\n for (j, b) in s[..i].iter().enumerate() {\n for c in s[..j].iter() {\n if *a == 'Q' && *b == 'A' && *c == 'Q' {\n ans += 1;\n }\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "24ea8482f42d8426cc3b07102213796e", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/// ========== \u5165\u529b\u7528\u30de\u30af\u30ed ====================================================\n/// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\n/// FromStr\u578b, Vec, Vec, \u306b\u5bfe\u5fdc;\n/// \n/// \u5165\u529b\u3068\u5e73\u884c\u3057\u3066\u51e6\u7406\u3057\u305f\u3044\u3068\u304d\u306b\u306f\u4f7f\u3048\u306a\u3044 -> \u5f8c\u8ff0\u306e read() \u3092\u4f7f\u7528\n#[macro_export]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n\n// ========== \u5e38\u7528\u95a2\u6570 =======================================================\npub use std::f64::consts::PI;\n\n// 10^9 + 7 \u3067\u5272\u3063\u305f\u3042\u307e\u308a\u3092\u51fa\u529b\u3057\u3066\u304f\u3060\u3055\u3044\npub const MOD: u64 = 1_000_000_007;\n\n// atcoder\u6587\u5b57\u5217, \u4f7f\u3046\u3068\u304d\u306f`main()`\u5185\u306b\u30b3\u30d4\u30da\n// let atcoder: Vec = vec!['a', 't', 'c', 'o', 'd', 'e', 'r'];\n\n/// \u6a19\u6e96\u5165\u529b\u304b\u3089\n/// \u7a7a\u767d\u6587\u5b57\u3067\u56f2\u307e\u308c\u305f1\u3064\u306e\u30c8\u30fc\u30af\u30f3\u3092\n/// \u6307\u5b9a\u306e\u578b\u306b\u5909\u63db\u3059\u308b\npub fn read() -> T {\n use std::io::Read;\n let stdin = std::io::stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\n/// \u6a19\u6e96\u5165\u529b\u304b\u30891\u884c\u8aad\u307f\u53d6\u308a\n/// \u7a7a\u767d\u6587\u5b57\u3067\u533a\u5207\u3063\u3066\n/// \u6307\u5b9a\u306e\u578b\u306e`Vec`\u306b\u683c\u7d0d\u3059\u308b\npub fn read_vec() -> Vec {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\n/// \u30e6\u30fc\u30af\u30ea\u30c3\u30c9\u306e\u4e92\u9664\u6cd5\u3088\u308a\n/// 2\u6570\u306e\u6700\u5927\u516c\u7d04\u6570\u3092\u6c42\u3081\u308b\npub fn gcd(arg1: usize, arg2: usize) -> usize {\n let mut u = if arg1 > arg2 { arg1 } else { arg2 };\n let mut v = if arg1 > arg2 { arg2 } else { arg1 };\n let mut r: usize;\n while v != 0 {\n r = u % v;\n u = v;\n v = r;\n }\n u\n}\n\n/// `Vec` \u306b\u5bfe\u3057\u3066\u9806\u306b `gcd()` \u3092\u9069\u7528\u3057\u3066\n/// \u914d\u5217\u5168\u4f53\u306e\u6700\u5927\u516c\u7d04\u6570\u3092\u6c42\u3081\u308b\npub fn gcd_vec(v: &[usize]) -> usize {\n let mut r = v[0];\n for i in &v[1..] {\n r = gcd(r, *i);\n }\n r\n}\n\n/// `gcd()` \u3092\u5229\u7528\u3057\u30662\u6570\u306e\u6700\u5c0f\u516c\u500d\u6570\u3092\u6c42\u3081\u308b\npub fn lcm(arg1: usize, arg2: usize) -> usize {\n arg1 * arg2 / gcd(arg1, arg2)\n}\n\n/// `Vec` \u306b\u5bfe\u3057\u3066\u9806\u306b`lcm()` \u3092\u9069\u7528\u3057\u3066\n/// \u914d\u5217\u5168\u4f53\u306e\u6700\u5c0f\u516c\u500d\u6570\u3092\u6c42\u3081\u308b\npub fn lcm_vec(v: &[usize]) -> usize {\n let mut r = v[0];\n for i in &v[1..] {\n r = lcm(r, *i);\n }\n r\n}\n\n/// \u4e0e\u3048\u3089\u308c\u305f `char` \u304c\u6bcd\u97f3\u3067\u3042\u308c\u3070 `true` \u3092\u8fd4\u3059\npub fn is_vowel(c: char) -> bool {\n match c {\n 'a' | 'i' | 'u' | 'e' | 'o' => true,\n _ => false,\n }\n}\n\n/// \u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u7d42\u4e86\npub fn exit() {\n std::process::exit(0)\n}\n\n// ========== main() ==========================================================\n\nfn main() {\n input! {\n s: chars\n }\n\n let mut a_whr = Vec::new();\n for i in 1..s.len()-1 {\n if s[i] == 'A' {\n a_whr.push(i);\n }\n }\n\n let mut ans = 0;\n for i in a_whr {\n ans += s[..i].iter().filter(|c| **c == 'Q').count() *\n s[i+1..].iter().filter(|c| **c == 'Q').count();\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "35075e79dc01c97490c61869d69515b5", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let input = input_vec_chars();\n let d: Vec = input\n .into_iter()\n .filter(|c| *c == 'Q' || *c == 'A').collect();\n\n let mut count = 0;\n\n for (i, elm) in d.iter().enumerate() {\n if *elm == 'Q' {\n for j in i+1..d.len() {\n if d[j] == 'A' {\n for k in j+1..d.len() {\n if d[k] == 'Q' {\n count += 1;\n }\n }\n }\n } \n }\n }\n println!(\"{:?}\", count);\n}\n\nfn input_str() -> String {\n let mut buff = String::new();\n std::io::stdin().read_line(&mut buff).expect(\"Err\");\n buff\n}\n\nfn input_u64() -> u64 {\n input_str().trim().parse().unwrap()\n}\n\nfn input_vec(sep: &str) -> Vec \nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().split(sep).map(|c| c.parse::().expect(\"Err pars\")).collect()\n}\n\nfn input_vec_chars() -> Vec {\n input_str().trim().chars().collect()\n}", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "e51baf3b09d0f27792c703d0b581963a", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::{max, min};\nuse std::io::{stdin, stdout, BufWriter, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut count = 0;\n\n let mut scanner = Scanner::default();\n let s = scanner.next::();\n\n let s_chars = s.chars().collect::>();\n\n let mut first_q = vec![0; s_chars.len()];\n let mut a = vec![];\n\n first_q[0] = if s_chars[0] == 'Q' { 1 } else { 0 };\n\n for i in 1..s_chars.len() {\n first_q[i] = first_q[i - 1];\n match s_chars[i] {\n 'Q' => {\n first_q[i] += 1;\n }\n 'A' => a.push(i),\n _ => (),\n }\n }\n\n for i in a {\n count += first_q[i] * (first_q.last().unwrap() - first_q[i]);\n }\n\n println!(\"{}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "1cd942d0267fa77f8367a1ec9c9df0a6", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::mem::size_of_val;\nuse std::cmp::{max, min};\nuse std::rc::Rc;\nuse std::collections::btree_map::BTreeMap;\nuse std::io::{Write, BufRead};\nuse std::collections::HashMap;\nuse std::ptr::write_volatile;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused)]\nfn read_strings() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n v\n}\n\n#[allow(unused)]\nfn read_array_i32() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.split_whitespace().map(|x| x.parse::().unwrap()).collect()\n}\n\n#[allow(unused)]\nfn read_array_usize() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.split_whitespace().map(|x| x.parse::().unwrap()).collect()\n}\n\n\n#[allow(unused_macros)]\nmacro_rules! read_array {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap())\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n// mod math;\n// mod binary_search;\n// mod graph;\n// mod structure;\n// mod fibonacci;\n// mod string;\n// mod permutations;\n\n// mod patterns;\n\n\n#[allow(dead_code)]\nfn memory_properties(value: &T)\n where\n T: std::fmt::Display + ?Sized,\n{\n println!(\n \"Variable address in memory = {:p}, Allocated bytes for type = {}\",\n value,\n size_of_val(value)\n );\n}\n\n#[allow(unused_macros)]\nmacro_rules! sum {\n ($($x:expr), *) => {\n {\n let mut res = 0;\n $(res += $x;)*\n res\n }\n };\n}\n\nstatic mut array: [[u8;101];101] = [[0u8; 101]; 101];\n\nfn main() {\n use std::io::Write;\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n\n let mut ans = 0;\n let s = gets();\n let bytes = s.as_bytes();\n\n for i in 0..bytes.len() {\n if bytes[i] == 'Q' as u8 {\n for j in i + 1..bytes.len() {\n if bytes[j] == 'A' as u8 {\n for k in j + 1..bytes.len() {\n if bytes[k] == 'Q' as u8 {\n ans += 1;\n }\n }\n }\n }\n }\n }\n writeln!(out, \"{}\", ans);\n // writeln!(out, \"{}\", \"Hello Rust\").unwrap();\n}", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "951e3f9e882876b84161fad6d83d339a", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let w = i32::from_str(buf.trim()).unwrap();\n println!(\n \"{}\",\n match (w - 2) > 0 && (w - 2) % 2 == 0 {\n true => \"YES\",\n false => \"NO\",\n }\n )\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "11811bc837636806656413b713cff7ea", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\n let mut weight = String::new();\n\n io::stdin().read_line(&mut weight).expect(\"Error\");\n\n let trimmed = weight.trim();\n match trimmed.parse::() {\n Ok(i) => if i == 2 {\n println!(\"NO\");\n } else if i%2 == 0 {\n println!(\"YES\")\n }\n else {\n println!(\"NO\")\n }\n Err(..) => println!(\"this was not an integer: {}\", trimmed),\n }\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "ec70880838fa518b23afab781f374cd8", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut n = String::new();\n io::stdin()\n .read_line(&mut n)\n .expect(\"\u041e\u0448\u0438\u0431\u043a\u0430 \u043f\u0440\u0438 \u0447\u0442\u0435\u043d\u0438\u0438 \u0441\u0442\u0440\u043e\u043a\u0438\");\n let n: u32 = match n.trim().parse() {\n Ok(num) => num,\n Err(_) => return\n };\n match n % 2 == 0 && (n / 2) * 2 == n && n != 2 {\n true => println!(\"YES\"),\n false => println!(\"NO\")\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "8ac9e5c6c154ecbc39d48e12a1ea5496", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\n\nfn main() {\n let n: i32 = std::io::stdin()\n .lock()\n .lines()\n .next()\n .expect(\"stdin should be available\")\n .expect(\"couldn't read from stdin\")\n .parse()\n .expect(\"input was not an integer\");\n println!(\"{}\", if n > 2 && n % 2 == 0 {\n \"YES\"\n } else {\n \"NO\"\n });\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "43da40d4901feae6d9772547ee0a1842", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).unwrap();\n let num: i8 = input.trim().parse().unwrap();\n watermelon(num);\n}\n\nfn watermelon(weight: i8) {\n if weight == 2 {\n println!(\"NO\");\n } else if weight % 2 == 0 {\n println!(\"YES\"); \n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "afb50fd387e6def44625bc053848615c", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! read {\n\t() => { read!(\"\") };\n\t($msg:expr) => {{\n\t\tuse std::io::Write;\n\t\tprint!(\"{}\", $msg);\n\t\tstd::io::stdout().flush().unwrap();\n\t\tstd::str::FromStr::from_str(&read_word()).unwrap()\n\t}};\n}\n\npub fn read_word() -> String {\n\tuse std::io::prelude::*;\n\tlet mut word: Vec = vec![];\n\n\tfor c in ::std::io::stdin().bytes() {\n\t\tlet c = c.unwrap();\n\t\tif (c as char).is_whitespace() {\n\t\t\tif !word.is_empty() {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tword.push(c);\n\t\t}\n\t}\n\t::std::str::from_utf8(&word).unwrap().to_string()\n}\n\nfn main() {\n\tlet w: i8 = read!();\n\tif w > 3 && w % 2 == 0 {\n\t\tprintln!(\"YES\");\n\t} else {\n\t\tprintln!(\"NO\");\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "3707ee49ce31c94722bf15ca01c99d35", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut number_line = String::new();\n std::io::stdin().read_line(&mut number_line).unwrap();\n let number: i32 = number_line.trim().parse().unwrap();\n let result = if number == 2 || number % 2 != 0 {\n \"NO\"\n } else {\n \"YES\"\n };\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "17bb6107b88174d20d7a46e595582129", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//use std::str::FromStr;\n\n\n#[cfg(test)]\nmod tests {\n use crate::quest;\n\n #[test]\n fn test1() {\n assert_eq!(quest(2,2,1,1),2)\n }\n #[test]\n fn test2() {\n assert_eq!(quest(4,4,2,1),3)\n }\n #[test]\n fn test3() {\n assert_eq!(quest(6,10,4,2),6)\n }\n\n}\n/*\n#[inline]\npub fn input_in_four_var() -> (T, T, T, T)\nwhere T: Copy,\n{\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let numbers: Vec = line.split_whitespace().filter_map(\n |s| s.parse().ok()\n )\n .collect();\n (*numbers.get(0).unwrap(),*numbers.get(1).unwrap(),*numbers.get(2).unwrap(),*numbers.get(3).unwrap() )\n\n}\n*/\n\n\n\n\nfn main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let v: i32 =match line.trim().parse() {\n Ok(t) => t,\n Err(_e) => panic!()\n };\n if v%2 ==0 && v !=2{\n return println!(\"YES\")\n }\n println!(\"NO\")\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "b0092e882799af41c759048025b71326", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn main() {\n readln!();\n let encoded = readln!();\n let encoded: Vec = encoded.chars().collect();\n\n let mut decoded = String::with_capacity(10);\n let mut index = 0;\n let mut decoded_index = 0;\n while index < encoded.len() {\n decoded.push(encoded[index]);\n decoded_index += 1;\n\n index += decoded_index;\n }\n\n println!(\"{}\", decoded);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1fa0bfa94469c9cb45405b5e0275791b", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let arr: Vec = scan.next::().chars().collect();\n let mut res: Vec = vec![];\n let mut i = 0usize;\n let mut cnt = 1usize;\n while i < n {\n res.push(arr[i]);\n i += cnt;\n cnt += 1;\n }\n let res: String = res.iter().collect();\n println!(\"{}\", res);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e0f6dec9a6961bb98dfbccaa7da2392d", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let s:Vec = read::().chars().collect();\n\n let mut k = 1;\n let mut i = 0;\n while i < n {\n print!(\"{}\", s[i]);\n i += k;\n k += 1;\n }\n println!();\n\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2d60dcbb63e54baf9609d45b565ec48d", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn raw_input() -> String {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n}\n\nfn decrypt(t: &str) -> String {\n let mut s = String::new();\n let mut step = 0;\n\n let mut iter = t.chars();\n while let Some(c) = iter.nth(step) {\n s.push(c);\n step += 1;\n }\n\n s\n}\n\nfn main() {\n {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n }\n\n let t = raw_input();\n print!(\"{}\", decrypt(&t));\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4684fd5555b23ef6d686d40729208ae8", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::prelude::*;\n\nfn main() -> io::Result<()> {\n let stdin = io::stdin();\n let mut line_it = stdin.lock().lines();\n let n: usize = line_it.next().unwrap().unwrap().parse::().unwrap();\n let s: Vec = line_it.next().unwrap().unwrap().chars().collect();\n let mut v: Vec = Vec::new();\n let mut i = 0;\n let mut c = 1;\n while i < s.len() {\n v.push(s[i]);\n c += 1;\n i += c;\n }\n println!(\"{}\", v.into_iter().collect::());\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "31c56251d02dbabe1ed381544a2f8a93", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let s = input.bs();\n let mut p = 0;\n for i in 1.. {\n print!(\"{}\", s[p] as char);\n p += i;\n if p >= n {\n break;\n }\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "61f5d92d69747f70cc08cc6a7f79bda8", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let stdin = io::stdin();\n\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n let _m: usize = line.trim().parse().unwrap();\n\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n let s: Vec = s.chars().collect();\n\n let mut res = String::new();\n let mut i: usize = 0;\n for delta in 1.. {\n if i >= s.len() {\n break;\n }\n res.push(s[i]);\n i += delta;\n }\n\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c0647a07f02e6e9a4e4df2e0329891f1", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n let amount = input.trim().parse::().expect(\"LENGTH::parse to i32 failed\");\n\n input.clear();\n\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n let vec = input.chars().collect::>();\n\n let mut index: usize = usize::default();\n let mut times: usize = usize::default();\n while index < amount {\n times += 1;\n print!(\"{}\", &vec[index]);\n index += times;\n }\n println!();\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "dd13689d60dd3754a013f96a1d2aabbc", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n// use proconio::input;\nuse std::cmp::{Ordering::*, Reverse};\nuse std::collections::{BTreeMap, BTreeSet};\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\nmacro_rules! answer {\n ($out:ident, $ans:expr) => {\n writeln!($out, \"{}\", $ans)\n };\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let s: String = scan.token();\n let mut s = s.chars();\n\n answer!(out, \"hello\".chars().all(|c| s.any(|x| c == x)).yes())\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Mostly copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse [Scanner]\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\n// aka #![feature(bool_to_option)]\ntrait BoolThen {\n fn then_(self, f: impl FnOnce() -> T) -> Option;\n}\n\nimpl BoolThen for bool {\n fn then_(self, f: impl FnOnce() -> T) -> Option {\n if self {\n Some(f())\n } else {\n None\n }\n }\n}\n\ntrait BoolToYes {\n fn yes(self) -> &'static str;\n}\n\nimpl BoolToYes for bool {\n fn yes(self) -> &'static str {\n match self {\n true => \"YES\",\n false => \"NO\",\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "b3d105cbe284324307ba5df51fed86af", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let list=input();\n let hello:Vec<&str>=vec![\"h\",\"e\",\"l\",\"l\",\"o\"];\n let mut i_hello=0;\n for i in &list{\n if i==hello[i_hello as usize]{\n i_hello+=1;\n if i_hello==5{\n break;\n }\n }\n }if i_hello==5{\n println!(\"YES\");\n }else{\n println!(\"NO\");\n }\n}\n\nfn read() -> String{\n let mut input=String::new();\n io::stdin().read_line(&mut input).expect(\"unable to read\");\n input.trim().to_string()\n}\n\nfn input() -> Vec{\n let inp:Vec=read()\n .chars().map(|x| x.to_string()).collect();\n inp\n}\n/* let n=read().parse::().expect(\"Failed to parse\");\n let inp=read();\n (n,inp.split_whitespace().map(|x| x.parse::().expect(\"Failed to parse\")).collect())\n let list: Vec<_>=inp.split_whitespace().collect();\n let qu: Vec<_>=read().chars().collect();\n (list[0].parse::().expect(\"Failed to parse\"),\n list[1].parse::().expect(\"Failed to parse\"),qu)\n*/\n\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "44648e1e0787b0bf2e10ad67fdfda6b7", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n\tlet s = scan.next::();\n\n let orig = \"hello\".as_bytes();\n let mut res = false;\n let mut i: usize = 0;\n\n for &c in s.as_bytes() {\n if c == orig[i] {\n i = i + 1;\n if i == orig.len() {\n res = true;\n break;\n }\n }\n }\n\n writeln!(out, \"{}\", if res { \"YES\" } else { \"NO\" }).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "451c4eb7605be57d8bf4df6a4a004d3c", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n let mut line=String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let control=['h','e','l','l','o'];\n let mut line:Vec=line\n .trim()\n .chars()\n .filter(|c|match c{\n 'h'=>true,\n 'e'=>true,\n 'l'=>true,\n 'o'=>true,\n _=>false,\n })\n .collect();\n line.push(' ');\n let len=line.len();\n let mut stop:usize=0;\n 'control:for c in 0..5{\n for l in stop..=len{\n if control[c]==line[l]{\n stop=l+1;\n continue'control\n }\n if c<5 && l==len-1{print!(\"NO\");return}\n }\n }\n print!(\"YES\")\n}", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "0f15971636817e368c6bf39d813ba993", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn substring(sentence: &str, word: &str) -> bool {\n\tif word.len() == 0 {\n\t\treturn true;\n\t}\n\telse if sentence.len() == 0 {\n\t\treturn false;\n\t}\n\tif sentence.chars().next() == word.chars().next() {\n\t\treturn substring(&sentence[1..], &word[1..]);\n\t}\n\telse {\n\t\treturn substring(&sentence[1..], &word[0..]);\n\t}\n}\n\nfn main() {\n\tlet mut sentence = String::new();\n\tmatch io::stdin().read_line(&mut sentence) {\n\t Ok(_) => (),\n\t Err(e) => println!(\"Error: {}\", e),\n\t}\n\tlet word = \"hello\";\n\tprintln!(\"{}\", if substring(&sentence, &word) {\"YES\"} else {\"NO\"});\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "a5604fccd4381b5a7dc7c235c4ef952e", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n let a = vec!('h','e','l','l','o');\n let mut z = 0;\n let mut val = String::new();\n std::io::stdin().read_line(&mut val).unwrap();\n let val = val.trim().parse::().unwrap();\n for j in val.chars(){\n if a[z] == j {\n z += 1;\n }\n if z == 5 {\n break;\n }\n }\n if z == 5{\n println!(\"YES\");\n }\n else{\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "c6c66ac26da260b5f2ef1ee61e045194", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut text = String::new();\n std::io::stdin().read_line(&mut text).expect(\"\");\n let mut hello = \"hello\".chars().peekable();\n for x in text.trim().chars() {\n if Some(&x) == hello.peek() {\n hello.next();\n }\n }\n println!(\"{}\", if hello.peek() == None { \"YES\" } else { \"NO\" } );\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "d4be4ba78fd1e83453ee66dd21127fa0", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let input: String = read(sin);\n let target = ['h', 'e', 'l', 'l', 'o'];\n let mut current_idx = 0;\n\n for c in input.as_str().chars() {\n if c == target[current_idx as usize] {\n current_idx += 1;\n if current_idx == 5 {\n println!(\"YES\");\n return;\n }\n }\n }\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "6aa7634ef3efe35c3a75f19c6ee3341f", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn gcd(a: usize, b: usize) -> usize {\n let mut x = a;\n let mut y = b;\n let mut tmp = 0usize;\n while x > 0 {\n tmp = x;\n x = y % x;\n y = tmp;\n }\n y\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: usize = scan.next();\n let b: usize = scan.next();\n let c: usize = scan.next();\n let d: usize = scan.next();\n let mut p = 0usize;\n let mut q = 0usize;\n if a * d >= c * b {\n p = c * b;\n q = a * d;\n } else {\n p = d * a;\n q = b * c;\n }\n p = q - p;\n let m = gcd(p, q);\n p = p / m;\n q = q / m;\n println!(\"{}/{}\", p, q);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "aef481e5567cf1246fba232f7fd7d248", "src_uid": "b0f435fc2f7334aee0d07524bc37cb1e", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn gcd(a: i64, b: i64) -> i64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn to_fraction(num: i64, denom: i64) -> (i64, i64) {\n let g = gcd(num, denom);\n (num / g, denom / g)\n}\n\nfn max_fraction(num1: i64, denom1: i64, num2: i64, denom2: i64) -> (i64, i64) {\n if num1 * denom2 < num2 * denom1 {\n to_fraction(num2, denom2)\n }\n else {\n to_fraction(num1, denom1)\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let a: i64 = scan.token();\n let b: i64 = scan.token();\n let c: i64 = scan.token();\n let d: i64 = scan.token();\n\n let num1 = a * d - b * c;\n let denom1 = a * d;\n let num2 = b * c - a * d;\n let denom2 = b * c;\n\n let ans = max_fraction(num1, denom1, num2, denom2);\n writeln!(out, \"{}/{}\", ans.0, ans.1).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "a8b6a3dd1d1b5df6ba49ea2f3842101c", "src_uid": "b0f435fc2f7334aee0d07524bc37cb1e", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io::{self, prelude::*, StdinLock, StdoutLock};\r\nuse std::str;\r\n\r\nconst MOD: u64 = 1e9 as u64 + 7;\r\n\r\nfn solve(scan: &mut Scanner, out: &mut io::BufWriter) {\r\n let n: u64 = scan.token();\r\n let k: u16 = scan.token();\r\n\r\n let mut ans = 1u64;\r\n for _ in 0..k {\r\n ans = (ans * n) % MOD;\r\n }\r\n writeln!(out, \"{}\", ans).ok();\r\n}\r\n\r\nstruct Scanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitWhitespace<'static>,\r\n}\r\n\r\nimpl Scanner {\r\n fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: vec![],\r\n buf_iter: \"\".split_whitespace(),\r\n }\r\n }\r\n fn token(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_whitespace())\r\n }\r\n }\r\n }\r\n}\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let mut scan = Scanner::new(stdin.lock());\r\n let mut out = io::BufWriter::new(stdout.lock());\r\n\r\n let t = scan.token::();\r\n for _ in 0..t {\r\n solve(&mut scan, &mut out);\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "f80524ffa0249af20be313367b9a69ab", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin scannner ----------\r\n#[allow(dead_code)]\r\nmod scanner {\r\n\tuse std::str::FromStr;\r\n\tpub struct Scanner<'a> {\r\n\t\tit: std::str::SplitWhitespace<'a>,\r\n\t}\r\n\timpl<'a> Scanner<'a> {\r\n\t\tpub fn new(s: &'a String) -> Scanner<'a> {\r\n\t\t\tScanner {\r\n\t\t\t\tit: s.split_whitespace(),\r\n\t\t\t}\r\n\t\t}\r\n\t\tpub fn next(&mut self) -> T {\r\n\t\t\tself.it.next().unwrap().parse::().ok().unwrap()\r\n\t\t}\r\n\t\tpub fn next_bytes(&mut self) -> Vec {\r\n\t\t\tself.it.next().unwrap().bytes().collect()\r\n\t\t}\r\n\t\tpub fn next_chars(&mut self) -> Vec {\r\n\t\t\tself.it.next().unwrap().chars().collect()\r\n\t\t}\r\n\t\tpub fn next_vec(&mut self, len: usize) -> Vec {\r\n\t\t\t(0..len).map(|_| self.next()).collect()\r\n\t\t}\r\n\t}\r\n}\r\n// ---------- end scannner ----------\r\nuse std::io::Write;\r\nfn main() {\r\n\tuse std::io::Read;\r\n\tlet mut s = String::new();\r\n\tstd::io::stdin().read_to_string(&mut s).unwrap();\r\n\tlet mut sc = scanner::Scanner::new(&s);\r\n\tlet out = std::io::stdout();\r\n\tlet mut out = std::io::BufWriter::new(out.lock());\r\n\tlet t: usize = sc.next();\r\n\tfor _ in 0..t {\r\n\t\tsolve(&mut sc, &mut out);\r\n\t}\r\n}\r\nfn binary_exponentiation(a: i64, b: u64, mod_: i64) -> i64 {\r\n\tlet mut ans: i64 = 1;\r\n\tlet mut a = a % mod_;\r\n\tlet mut b = b;\r\n\twhile b != 0 {\r\n\t\tif (b & 1) == 1 {\r\n\t\t\tans = ans * a % mod_;\r\n\t\t}\r\n\t\ta = a * a % mod_;\r\n\t\tb >>= 1;\r\n\t}\r\n\treturn ans;\r\n}\r\nfn solve(sc: &mut scanner::Scanner, out: &mut std::io::BufWriter) {\r\n\tlet (n, k): (i64, u64) = (sc.next(), sc.next());\r\n\tlet ans = binary_exponentiation(n, k, 1e9 as i64 + 7);\r\n\twriteln!(out, \"{}\", ans).ok();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "a2586ec1bb5745dcde0d2f391c12c368", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::Ordering;\r\nuse std::cmp;\r\nuse std::cmp::min;\r\nuse std::collections::BTreeMap;\r\nuse std::process;\r\nuse std::cmp::Ord;\r\nuse std::collections::HashMap;\r\nuse std::collections::HashSet;\r\nuse std::collections::VecDeque;\r\nuse std::collections::BTreeSet;\r\nuse std::mem;\r\nuse std::collections::BinaryHeap;\r\nuse std::hash::{Hash, Hasher};\r\n\r\npub struct Scanner {\r\n stdin: R,\r\n}\r\n \r\nimpl Scanner {\r\n pub fn read(&mut self) -> T {\r\n use std::io::Read;\r\n let buf = self\r\n .stdin\r\n .by_ref()\r\n .bytes()\r\n .map(|b| b.unwrap())\r\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r')\r\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r')\r\n .collect::>();\r\n std::str::from_utf8(&buf).unwrap()\r\n .parse()\r\n .ok()\r\n .expect(\"Parse error.\")\r\n }\r\n pub fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.read()).collect()\r\n }\r\n pub fn chars(&mut self) -> Vec {\r\n self.read::().chars().collect()\r\n }\r\n}\r\n\r\n\r\npub trait BinarySearch {\r\n fn lower_bound(&self, x:&T) -> usize;\r\n fn upper_bound(&self, x:&T) -> usize;\r\n}\r\n\r\nimpl BinarySearch for VecDeque{\r\n fn lower_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less => {\r\n low = mid + 1;\r\n }\r\n Ordering::Equal | Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n\r\n fn upper_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less | Ordering::Equal => {\r\n low = mid + 1;\r\n }\r\n Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n}\r\nimpl BinarySearch for [T]{\r\n fn lower_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less => {\r\n low = mid + 1;\r\n }\r\n Ordering::Equal | Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n\r\n fn upper_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less | Ordering::Equal => {\r\n low = mid + 1;\r\n }\r\n Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n}\r\n\r\n//10\u9032\u6570\u3067\u8868\u3059\u3068n\u3092x\u9032\u6570\u3067\u8868\u3059\r\nfn base_number(x:usize, n:usize)->Vec{\r\n let mut x = x;\r\n let mut n = n;\r\n let mut r = 1;\r\n let mut q = x;\r\n let mut res = vec![];\r\n while(q>=n){\r\n r = q%n;\r\n res.push(r);\r\n q = q/n;\r\n }\r\n r = q%n;\r\n res.push(r);\r\n res.reverse();\r\n return res\r\n}\r\n\r\n//\u6700\u5927\u516c\u7d04\u6570\r\nfn gcd(a:usize, b:usize)->usize{\r\n if b==0{return a;}\r\n return gcd(b, a%b);\r\n}\r\n//\u62e1\u5f35GCD\r\n//ax+by=1\u3068\u306a\u308b\u6574\u6570x,y\u3092\u6c42\u3081\u308b\r\nfn extgcd(a:i64, b:i64, x:&mut i64, y:&mut i64) -> i64{\r\n let mut d = a;\r\n if b != 0{\r\n d = extgcd(b, a%b, y, x);\r\n *y -= (a/b)*(*x);\r\n }\r\n else{\r\n *x = 1;\r\n *y = 0;\r\n }\r\n return d;\r\n}\r\n//\u6700\u5c0f\u516c\u500d\u6570\r\nfn lcm(a:usize, b:usize)->usize{\r\n return (b/gcd(a, b))*a;\r\n}\r\n//\u9006\u5143\r\nfn modinv(a:usize, M:usize)->usize{\r\n let mut b = M as i64;\r\n let mut u = 1 as i64;\r\n let mut v = 0 as i64;\r\n let mut a = a as i64;\r\n let mut m = M as i64;\r\n while(b>0){\r\n let mut t = a/b;\r\n a -= t*b;\r\n mem::swap(&mut a, &mut b);\r\n u-=t*v;\r\n mem::swap(&mut u, &mut v);\r\n }\r\n u%=m;\r\n if u<0{u+=m;}\r\n return u as usize;\r\n\r\n}\r\n//\u9023\u7acb\u5408\u540c\u65b9\u7a0b\u5f0f\r\n//A * X = B (MOD M) ->(b, m) x=b(mod m)\r\n\r\n\r\n//\u5ea7\u6a19\u5727\u7e2e\uff12\u6b21\u5143 [1, W]\r\nfn linear_congruence(A:&Vec, B:&Vec, M:&Vec) -> (i64, i64){\r\n let mut x = 0;\r\n let mut m = 1;\r\n for i in 0..A.len(){\r\n let mut a = A[i]*m;\r\n let mut b = B[i]-A[i]*x;\r\n let mut d = gcd(M[i] as usize, a as usize) as i64;\r\n if (b%d != 0){ \r\n return (0, -1);\r\n }\r\n let mut t= b/d*(modinv( (a/d) as usize, (M[i]/d) as usize) as i64)%(M[i]/d);\r\n x = x+m*t;\r\n m*=M[i]/d;\r\n }\r\n return (x%m, m);\r\n\r\n}\r\n\r\n\r\n//\u5ea7\u6a19\u5727\u7e2e\uff12\u6b21\u5143 [1, W]\r\nfn compress_2d(x1:&mut Vec, x2:&mut Vec, w:i64) -> Vec{\r\n let mut xs = vec![];\r\n for i in 0..x1.len(){\r\n for d in -1..2{\r\n let mut tx1 = x1[i]+d;\r\n let mut tx2 = x2[i]+d;\r\n if (1<=tx1 && tx1 <= w){\r\n xs.push(tx1);\r\n }\r\n if (1<=tx2 && tx2 <= w){\r\n xs.push(tx2);\r\n }\r\n }\r\n }\r\n let mut h = HashSet::new();\r\n for i in 0..xs.len(){\r\n h.insert(xs[i]);\r\n }\r\n let mut xs:Vec = h.into_iter().collect();\r\n xs.sort();\r\n return xs;\r\n}\r\n\r\n\r\n//\u30bb\u30b0\u30e1\u30f3\u30c8\u6728\r\nstruct segment_tree{\r\n n: usize,\r\n dat: Vec,\r\n op:Op,\r\n e:I,\r\n}\r\nimpl segment_tree\r\n \r\n \r\n where Op: Fn(I, I) -> I, I:Copy{\r\n \r\n pub fn new(n_:usize, op: Op, e:I)->Self{\r\n let mut n = 1;\r\n while(n0){\r\n k = (k-1)/2;\r\n self.dat[k] = (self.op)(self.dat[k*2 + 1], self.dat[k*2+2]);\r\n }\r\n }\r\n\r\n pub fn query_sub(&self, a:usize, b:usize, k:usize, l:usize, r:usize) -> I{\r\n if r<=a || b<=l{return self.e;}\r\n if a<=l && r<=b{return self.dat[k];}\r\n else{\r\n let mut vl = self.query_sub(a, b, k*2+1, l, (l+r)/2);\r\n let mut vr = self.query_sub(a, b, k*2+2, (l+r)/2, r);\r\n return (self.op)(vl, vr);\r\n }\r\n }\r\n pub fn query(&self, a:usize, b:usize)->I{\r\n return self.query_sub(a, b, 0, 0, self.n);\r\n }\r\n }\r\n\r\n\r\n\r\n//\u9045\u5ef6\u8a55\u4fa1\u30bb\u30b0\u30e1\u30f3\u30c8\u6728\r\n// composition(a, b) -> b(a(x))\r\nstruct lazy_segment_tree{\r\n n: usize,\r\n op:op,\r\n mapping:mapping,\r\n composition:composition,\r\n s:S,\r\n f:F,\r\n dat: Vec,\r\n lazy:Vec,\r\n \r\n}\r\nimpl lazy_segment_tree\r\n \r\n \r\n where op:Fn(S, S)->S, mapping:Fn(F, S)->S, composition:Fn(F, F)->F, S:Copy, F:Copy, S:PartialEq, F:PartialEq{\r\n \r\n pub fn new(n_:usize, s:S, f:F, op:op, mapping:mapping, composition:composition)->Self{\r\n let mut n = 1;\r\n while(n){\r\n for i in 0..self.n*2-1{\r\n self.dat.push(self.s.clone());\r\n self.lazy.push(self.f.clone());\r\n }\r\n for i in 0..initial.len(){\r\n self.dat[i+self.n-1] = initial[i];\r\n }\r\n for i in (0..self.n-1).rev(){\r\n self.dat[i] = (self.op)(self.dat[i*2+1], self.dat[i*2+2]);\r\n }\r\n }\r\n pub fn eval(&mut self, k:usize){\r\n if self.lazy[k] == self.f{\r\n return;\r\n }\r\n if k*2+1 < self.n*2-1{\r\n self.lazy[k*2+1] = (self.composition)(self.lazy[k*2+1], self.lazy[k]);\r\n self.lazy[k*2+2] = (self.composition)(self.lazy[k*2+2], self.lazy[k]);\r\n }\r\n self.dat[k] = (self.mapping)(self.lazy[k], self.dat[k]);\r\n self.lazy[k] = self.f;\r\n }\r\n pub fn update_sub(&mut self, a:usize, b:usize, x:F, k:usize, l:usize, r:usize)->S{\r\n self.eval(k);\r\n if r<=a || b<=l{\r\n return self.dat[k];\r\n }\r\n if a<=l && r<= b{\r\n self.lazy[k] = (self.composition)(self.lazy[k], x);\r\n return (self.mapping)(self.lazy[k], self.dat[k]);\r\n }\r\n let mut vr = self.update_sub(a, b, x, k*2+1, l, (l+r)/2);\r\n let mut vl = self.update_sub(a, b, x, k*2+2, (l+r)/2, r);\r\n self.dat[k] = (self.op)(vr, vl);\r\n return self.dat[k];\r\n }\r\n pub fn update(&mut self, a:usize, b:usize, x:F){\r\n self.update_sub(a, b, x, 0, 0, self.n);\r\n }\r\n pub fn query_sub(&mut self, a:usize, b:usize, k:usize, l:usize, r:usize)->S{\r\n self.eval(k);\r\n if r<= a || b <= l{\r\n return self.s;\r\n }\r\n else if a<= l && r<= b{\r\n return self.dat[k];\r\n }\r\n else{\r\n let mut vl = self.query_sub(a, b, k*2+1, l, (l+r)/2);\r\n let mut vr = self.query_sub(a, b, k*2+2, (l+r)/2, r);\r\n return (self.op)(vl, vr);\r\n }\r\n }\r\n pub fn query(&mut self, a:usize, b:usize)->S{\r\n return self.query_sub(a, b, 0, 0, self.n);\r\n }\r\n\r\n }\r\n\r\n//\u30c0\u30a4\u30af\u30b9\u30c8\u30e9\u6cd5\r\nfn dijkstra(s:usize, g:&Vec>)->Vec{\r\n let mut dist = vec![INF;g.len()];\r\n dist[s] = 0;\r\n let mut h = BinaryHeap::new();\r\n h.push((0, s));\r\n while(h.len() != 0){\r\n let mut t = h.pop().unwrap();\r\n let mut d = t.0 * -1;\r\n let mut v = t.1;\r\n if dist[v]d+dd{\r\n dist[n] = d+dd;\r\n h.push((dist[n]*-1, n));\r\n }\r\n }\r\n }\r\n return dist;\r\n}\r\nfn dijkstra2(s:usize, g:&Vec>)->Vec{\r\n let mut dist = vec![INF;g.len()];\r\n dist[s] = 0;\r\n let mut h = BinaryHeap::new();\r\n h.push((0, s));\r\n while(h.len() != 0){\r\n let mut t = h.pop().unwrap();\r\n let mut d = t.0 * -1;\r\n let mut v = t.1;\r\n if dist[v]d+dd{\r\n dist[n] = d+dd;\r\n h.push((dist[n]*-1, n));\r\n }\r\n }\r\n }\r\n return dist;\r\n}\r\nfn dijkstra3(st:(usize, usize), go:(usize, usize), h:usize, w:usize, map:&Vec>)->Vec>{ \r\n let mut d = vec![vec![INF;w];h];\r\n d[st.0][st.1] = 0;\r\n let mut hh = BinaryHeap::new();\r\n hh.push((0, st));\r\n let mut dx = vec![0, 0, 1, -1];\r\n let mut dy = vec![1, -1, 0, 0];\r\n \r\n while(hh.len() != 0){\r\n let mut tt = hh.pop().unwrap();\r\n let mut dist = tt.0 as i64 * -1;\r\n let mut x = (tt.1).0;\r\n let mut y = (tt.1).1;\r\n if d[x][y]dist+1{\r\n d[nx][ny]=dist+1;\r\n hh.push((-1*(dist+1),(nx, ny)));\r\n }\r\n\r\n }\r\n }\r\n }\r\n return d;\r\n}\r\n//\uff12\u6b21\u5143\u548c [ (x, y), (x, y) )\r\n//sum[i+1][j+1] = ((sum[i+1][j]+sum[i][j+1]+MODu-sum[i][j])%MODu+dp[i+1][j+1])%MODu;\r\n/*for (int i = 0; i < H; i++) {\r\n \r\n for (int j = 0; j < W; j++) {\r\n imos[i][j + 1] += imos[i][j];\r\n }\r\n }\r\n \r\n for (int j = 0; j < W; j++) {\r\n for (int i = 0; i < H; i++) {\r\n imos[i + 1][j] += imos[i][j];\r\n }\r\n }\r\n \r\n sums[yy1][xx1]+=1;\r\n sums[yy2][xx2]+=1;\r\n sums[yy1][xx2]-=1;\r\n sums[yy2][xx1]-=1;\r\n }\r\n for i in 0..ys.len() {\r\n for j in 0..xs.len(){\r\n sums[i][j + 1] += sums[i][j];\r\n }\r\n }\r\n \r\n for j in 0..xs.len(){\r\n for i in 0..ys.len(){\r\n sums[i + 1][j] += sums[i][j];\r\n }\r\n }\r\n*/\r\n//3\u6b21\u5143\u548c [ (x, y, z), (x, y, z) )\r\n/*\r\n//let mut v = vec![X1, Y1, Z1, X2, Y2, Z2];\r\n let mut si = vec![1i64, -1i64];\r\n for i in 0..2{\r\n for j in 0..2{\r\n for k in 0..2{\r\n let mut X = v[0+i*3];\r\n let mut Y = v[1+j*3];\r\n let mut Z = v[2+k*3];\r\n sum[X][Y][Z]+=si[i]*si[j]*si[k];\r\n }\r\n }\r\n }\r\n }\r\n for i in 0..xs.len()-1{\r\n for j in 0..ys.len(){\r\n for k in 0..zs.len(){\r\n sum[i+1][j][k] += sum[i][j][k];\r\n }\r\n }\r\n }\r\n \r\n for i in 0..xs.len(){\r\n for j in 0..ys.len()-1{\r\n for k in 0..zs.len(){\r\n sum[i][j+1][k] += sum[i][j][k];\r\n }\r\n }\r\n }\r\n \r\n for i in 0..xs.len(){\r\n for j in 0..ys.len(){\r\n for k in 0..zs.len()-1{\r\n sum[i][j][k+1] += sum[i][j][k];\r\n }\r\n }\r\n }\r\n*/\r\n\r\n//\u968e\u4e57\r\nfn invs(max:usize)->(Vec, Vec){\r\n let mut fac = vec![0;max+1];\r\n let mut ifac = vec![0;max+1];\r\n fac[0] = 1;\r\n ifac[0] = 1;\r\n for i in 0..max{\r\n \r\n fac[i+1] = fac[i] * (i+1)%MODu;\r\n ifac[i+1] = ifac[i] * modpow(i+1, MODu - 2)%MODu;\r\n }\r\n (fac, ifac)\r\n}\r\n//\u30b3\u30f3\u30d3\u30cd\u30fc\u30b7\u30e7\u30f3\r\nfn comb(a:usize, b:usize, fac:&Vec, ifac:&Vec)->usize{\r\n let mut a = a;\r\n let mut b = b;\r\n if a == 0 && b == 0{return 1;}\r\n if a, ifac:&Vec)->usize{\r\n return comb(n+r-1, r, fac, ifac);\r\n}\r\n//\r\nfn modpow(x:usize, n:usize) -> usize{\r\n let mut ans = 1;\r\n let mut n = n as usize;\r\n let mut x = x;\r\n while(n != 0){\r\n if (n&1 == 1){ans = ans*x%MODu;}\r\n x = x*x%MODu;\r\n n = n>>1;\r\n }\r\n ans\r\n}\r\nfn modpow2(x:i64, n:i64, m:i32) -> i64{\r\n let mut ans = 1;\r\n let mut n = n as i64;\r\n let mut x = x;\r\n while(n != 0){\r\n if (n&1 == 1){ans = ans*x%m as i64;}\r\n x = x*x%m as i64;\r\n n = n>>1;\r\n }\r\n ans\r\n}\r\n\r\n\r\n\r\n//\u30e6\u30cb\u30aa\u30f3\u30d5\u30a1\u30a4\u30f3\u30c9\u6728\r\nstruct union_find{\r\n par:Vec,\r\n rank:Vec,\r\n size:Vec,\r\n size_edge:Vec,\r\n}\r\nimpl union_find{\r\n fn new(n:usize) -> union_find{\r\n let mut par = vec![0;n];\r\n for i in 0..n{\r\n par[i] = i;\r\n }\r\n union_find{\r\n par:par,\r\n rank:vec![0;n],\r\n size:vec![1;n],\r\n size_edge:vec![0;n],\r\n }\r\n }\r\n fn find(&mut self, x:usize) ->usize{\r\n if(self.par[x] == x){\r\n x\r\n }\r\n else{\r\n let p = self.par[x];\r\n let res = self.find(p);\r\n self.par[x] = res;\r\n res\r\n }\r\n }\r\n fn same(&mut self, a:usize, b:usize)->bool{\r\n self.find(a) == self.find(b)\r\n }\r\n fn unite(&mut self, a:usize, b:usize){\r\n let x = self.find(a);\r\n let y = self.find(b);\r\n if x != y{\r\n if (self.rank[x] < self.rank[y]){\r\n self.par[x] = y;\r\n self.size[y] += self.size[x];\r\n self.size_edge[y] += self.size_edge[x];\r\n self.size_edge[y] += 1;\r\n }\r\n else{\r\n self.par[y] = x;\r\n self.size[x] += self.size[y];\r\n self.size_edge[x] += self.size_edge[y];\r\n self.size_edge[x] += 1;\r\n if(self.rank[x] == self.rank[y]){ self.rank[x]+=1;}\r\n }\r\n\r\n }\r\n else{\r\n self.size_edge[x] += 1;\r\n }\r\n }\r\n fn check_size(&mut self, a:usize) -> usize{\r\n let x = self.find(a);\r\n let s = self.size[x];\r\n s\r\n }\r\n}\r\n//\u504f\u89d2\u30bd\u30fc\u30c8 \u53cd\u6642\u8a08\u5468\u308a\r\nfn norm(x:f64, y:f64)->f64{\r\n (x*x + y*y).sqrt()\r\n}\r\nfn rad(x:f64, y:f64)->f64{\r\n if y>=0.0{\r\n (x /norm(x, y)).acos()\r\n }\r\n else{\r\n 2.0*PI - (x/norm(x,y)).acos()\r\n }\r\n}\r\nfn acos(v1:Vec, v2:Vec)->f64{\r\n ((v1[0]*v2[0] + v1[1]*v2[1])/(norm(v1[0], v1[1])*norm(v2[0], v2[1]))).acos()\r\n}\r\n\r\nfn argument_sort(xy:&mut Vec>){\r\n xy.sort_by(|a, b| rad(a[0], a[1]).partial_cmp(&(rad(b[0], b[1]))).unwrap());\r\n}\r\nfn argument_sort2(xy:&mut Vec<(f64, f64, usize)>){\r\n xy.sort_by(|a, b| rad(a.0, a.1).partial_cmp(&(rad(b.0, b.1))).unwrap());\r\n}\r\n\r\n//\u884c\u5217\u306e\u639b\u3051\u7b97 A*B\r\n//\r\nfn matmul(A:&Vec>, B:&Vec>) -> Vec>{\r\n let mut C = vec![vec![0;B[0].len()];A.len()];\r\n for i in 0..A.len(){\r\n for k in 0..B.len(){\r\n for j in 0..B[0].len(){\r\n C[i][j] += A[i][k]*B[k][j];\r\n C[i][j] %= MOD;\r\n }\r\n }\r\n }\r\n return C;\r\n}\r\nfn divisor(n:usize) -> Vec{\r\n let mut res:Vec = Vec::new();\r\n for i in 1..n+1{\r\n if i*i>n{break;}\r\n if n%i == 0{\r\n res.push(i);\r\n if i != n/i{\r\n res.push(n/i);\r\n }\r\n }\r\n }\r\n res\r\n}\r\n\r\n\r\n//x\u306b10\u306epow\u4e57\u3092\u639b\u3051\u3066\u5c0f\u6570\u90e8\u5206\u3092\u6d88\u3059\r\nfn f64_trans(x:Vec, pow:usize)->i64{\r\n let mut w = x.len();\r\n let mut a = vec![];\r\n let mut b = vec![];\r\n let mut f = false;\r\n let mut ism = false;\r\n if x[0] == '-'{\r\n ism = true;\r\n }\r\n for i in 0..x.len(){\r\n if x[i] == '-'{\r\n continue;\r\n }\r\n if x[i] == '.'{\r\n w = i;\r\n f = true;\r\n }\r\n else if f{\r\n b.push(x[i]);\r\n }\r\n else{\r\n a.push(x[i]);\r\n }\r\n }\r\n for i in 0..b.len(){\r\n a.push(b[i]);\r\n }\r\n for j in 0..pow-b.len(){\r\n a.push('0');\r\n }\r\n let mut now = 1;\r\n let mut res = 0;\r\n for i in (0..a.len()).rev(){\r\n res += now*(a[i] as i64 - '0' as i64);\r\n now*=10;\r\n }\r\n if ism{\r\n res*=-1;\r\n }\r\n return res;\r\n}\r\n\r\n\r\n\r\n\r\n//\u30ed\u30fc\u30ea\u30f3\u30b0\u30cf\u30c3\u30b7\u30e5\r\nstruct rolling_hash{\r\n base1:usize,\r\n base2:usize,\r\n mod1:usize,\r\n mod2:usize,\r\n hash1:Vec,\r\n hash2:Vec,\r\n power1:Vec,\r\n power2:Vec\r\n}\r\nimpl rolling_hash{\r\n fn new(S:&Vec)->rolling_hash{\r\n let mut n = S.len();\r\n let mut base1 = 1007;\r\n let mut base2 = 2009;\r\n let mut mod1 = 1000000007;\r\n let mut mod2 = 1000000009;\r\n let mut hash1 = vec![0;n+1];\r\n let mut hash2 = vec![0;n+1];\r\n let mut power1 = vec![1;n+1];\r\n let mut power2 = vec![1;n+1];\r\n\r\n for i in 0..n{\r\n hash1[i+1] = (hash1[i] * base1 + S[i])%mod1;\r\n hash2[i+1] = (hash2[i] * base2 + S[i])%mod2;\r\n power1[i+1] = (power1[i] * base1)%mod1;\r\n power2[i+1] = (power2[i] * base2)%mod2;\r\n }\r\n\r\n return rolling_hash{\r\n hash1:hash1,\r\n hash2:hash2,\r\n power1:power1,\r\n power2:power2,\r\n base1:base1,\r\n base2:base2,\r\n mod1:mod1,\r\n mod2:mod2\r\n }\r\n }\r\n // [l, r) \r\n fn get(&self, l:usize, r:usize)->(usize, usize){\r\n let mut res1 = self.hash1[r] as i64 - self.hash1[l] as i64 * self.power1[r-l] as i64%self.mod1 as i64;\r\n if (res1<0) {res1+= self.mod1 as i64;}\r\n let mut res2 = self.hash2[r] as i64 - self.hash2[l] as i64 * self.power2[r-l] as i64%self.mod2 as i64;\r\n if (res2<0) {res2+= self.mod2 as i64;}\r\n return (res1 as usize, res2 as usize);\r\n }\r\n}\r\n\r\n/*\r\n#[macro_use]\r\nextern crate lazy_static;\r\nlazy_static!{\r\n static ref all:Vec={\r\n let n_ = 200001;\r\n let mut a = vec![0;n_+1];\r\n for i in 1..n_+1{\r\n a[i] = (a[i-1]*10%MODu+1)%MODu;\r\n }\r\n a\r\n };\r\n}\r\n*/\r\n//\u4e2d\u56fd\u5270\u4f59\u5b9a\u7406\r\nfn safe_mod(x:i64, m:i64)->i64{\r\n let mut x = x;\r\n let mut m = m;\r\n x%=m;\r\n if x<0{\r\n x+=m;\r\n }\r\n return x;\r\n}\r\nfn inv_gcd(a:i64, b:i64)->(i64, i64){\r\n let mut a = a;\r\n let mut b = b;\r\n a = safe_mod(a, b);\r\n if (a == 0){\r\n return (b, 0);\r\n }\r\n\r\n let mut s = b;\r\n let mut t = a;\r\n let mut m0 = 0;\r\n let mut m1 = 1;\r\n\r\n while (t != 0) {\r\n let mut u = s / t;\r\n s -= t * u;\r\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\r\n\r\n // [3]:\r\n // (s - t * u) * |m1| + t * |m0 - m1 * u|\r\n // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)\r\n // = s * |m1| + t * |m0| <= b\r\n\r\n let mut tmp = s;\r\n s = t;\r\n t = tmp;\r\n tmp = m0;\r\n m0 = m1;\r\n m1 = tmp;\r\n }\r\n // by [3]: |m0| <= b/g\r\n // by g != b: |m0| < b/g\r\n if (m0 < 0){\r\n m0 += b / s;\r\n }\r\n return (s, m0);\r\n}\r\nfn floor_sum(n: i64, m: i64, mut a: i64, mut b: i64) -> i64 {\r\n let mut ans = 0;\r\n if a >= m {\r\n ans += (n - 1) * n * (a / m) / 2;\r\n a %= m;\r\n }\r\n if b >= m {\r\n ans += n * (b / m);\r\n b %= m;\r\n }\r\n\r\n let y_max = (a * n + b) / m;\r\n let x_max = y_max * m - b;\r\n if y_max == 0 {\r\n return ans;\r\n }\r\n ans += (n - (x_max + a - 1) / a) * y_max;\r\n ans += floor_sum(y_max, a, m, (a - x_max % a) % a);\r\n ans\r\n}\r\nfn crt(r: &Vec, m: &Vec) -> (i64, i64) {\r\n assert_eq!(r.len(), m.len());\r\n let (mut r0, mut m0) = (0, 1);\r\n for (&(mut ri), &(mut mi)) in r.iter().zip(m.iter()) {\r\n assert!(1 <= mi);\r\n ri = safe_mod(ri, mi);\r\n if m0 < mi {\r\n mem::swap(&mut r0, &mut ri);\r\n mem::swap(&mut m0, &mut mi);\r\n }\r\n if m0 % mi == 0 {\r\n if r0 % mi != ri {\r\n return (0, 0);\r\n }\r\n continue;\r\n }\r\n \r\n let (g, im) = inv_gcd(m0, mi);\r\n let u1 = mi / g;\r\n if (ri - r0) % g != 0 {\r\n return (0, 0);\r\n }\r\n let x = (ri - r0) / g % u1 * im % u1;\r\n \r\n r0 += x * m0;\r\n m0 *= u1; // -> lcm(m0, mi)\r\n if r0 < 0 {\r\n r0 += m0\r\n };\r\n }\r\n \r\n (r0, m0)\r\n}\r\n//\u7573\u307f\u8fbc\u307f\u8a08\u7b97\r\n\r\n\r\nfn mul_mod(a: u32, b: u32, m: u32, im: u64) -> u32 {\r\n let mut z = a as u64;\r\n z *= b as u64;\r\n let x = (((z as u128) * (im as u128)) >> 64) as u64;\r\n let mut v = z.wrapping_sub(x.wrapping_mul(m as u64)) as u32;\r\n if m <= v {\r\n v = v.wrapping_add(m);\r\n }\r\n v\r\n}\r\n\r\n\r\nfn inv_gcd2(a: i64, b: i64) -> (i64, i64) {\r\n let a = safe_mod(a, b);\r\n if a == 0 {\r\n return (b, 0);\r\n }\r\n\r\n let mut s = b;\r\n let mut t = a;\r\n let mut m0 = 0;\r\n let mut m1 = 1;\r\n\r\n while t != 0 {\r\n let u = s / t;\r\n s -= t * u;\r\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\r\n\r\n\r\n mem::swap(&mut s, &mut t);\r\n mem::swap(&mut m0, &mut m1);\r\n }\r\n if m0 < 0 {\r\n m0 += b / s;\r\n }\r\n (s, m0)\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nuse std::{\r\n cell::RefCell,\r\n convert::{Infallible, TryInto as _},\r\n fmt,\r\n iter::{Product, Sum},\r\n marker::PhantomData,\r\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\r\n str::FromStr,\r\n sync::atomic::{self, AtomicU32, AtomicU64},\r\n thread::LocalKey,\r\n};\r\n\r\npub type ModInt1000000007 = StaticModInt;\r\npub type ModInt998244353 = StaticModInt;\r\n\r\n#[derive(Copy, Clone, Eq, PartialEq)]\r\n#[repr(transparent)]\r\npub struct StaticModInt {\r\n val: u32,\r\n phantom: PhantomData M>,\r\n}\r\n\r\nimpl StaticModInt {\r\n #[inline(always)]\r\n pub fn modulus() -> u32 {\r\n M::VALUE\r\n }\r\n\r\n #[inline]\r\n pub fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(M::VALUE))\r\n }\r\n\r\n #[inline]\r\n pub fn raw(val: u32) -> Self {\r\n Self {\r\n val,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n #[inline]\r\n pub fn val(self) -> u32 {\r\n self.val\r\n }\r\n\r\n #[inline]\r\n pub fn pow(self, n: u64) -> Self {\r\n ::pow(self, n)\r\n }\r\n\r\n #[inline]\r\n pub fn inv(self) -> Self {\r\n if M::HINT_VALUE_IS_PRIME {\r\n if self.val() == 0 {\r\n panic!(\"attempt to divide by zero\");\r\n }\r\n self.pow((M::VALUE - 2).into())\r\n } else {\r\n Self::inv_for_non_prime_modulus(self)\r\n }\r\n }\r\n}\r\n\r\nimpl ModIntBase for StaticModInt {\r\n #[inline(always)]\r\n fn modulus() -> u32 {\r\n Self::modulus()\r\n }\r\n\r\n #[inline]\r\n fn raw(val: u32) -> Self {\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn val(self) -> u32 {\r\n self.val()\r\n }\r\n\r\n #[inline]\r\n fn inv(self) -> Self {\r\n self.inv()\r\n }\r\n}\r\n\r\npub trait Modulus: 'static + Copy + Eq {\r\n const VALUE: u32;\r\n const HINT_VALUE_IS_PRIME: bool;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>>;\r\n}\r\n\r\n#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\npub enum Mod1000000007 {}\r\n\r\nimpl Modulus for Mod1000000007 {\r\n const VALUE: u32 = 1_000_000_007;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n}\r\n\r\n#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\npub enum Mod998244353 {}\r\n\r\nimpl Modulus for Mod998244353 {\r\n const VALUE: u32 = 998_244_353;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n}\r\n\r\npub struct ButterflyCache {\r\n pub(crate) sum_e: Vec>,\r\n pub(crate) sum_ie: Vec>,\r\n}\r\n\r\n\r\n\r\n\r\npub trait ModIntBase:\r\n Default\r\n + FromStr\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + Copy\r\n + Eq\r\n + Hash\r\n + fmt::Display\r\n + fmt::Debug\r\n + Neg\r\n + Add\r\n + Sub\r\n + Mul\r\n + Div\r\n + AddAssign\r\n + SubAssign\r\n + MulAssign\r\n + DivAssign\r\n{\r\n fn modulus() -> u32;\r\n\r\n fn raw(val: u32) -> Self;\r\n\r\n fn val(self) -> u32;\r\n\r\n fn inv(self) -> Self;\r\n\r\n #[inline]\r\n fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(Self::modulus()))\r\n }\r\n\r\n #[inline]\r\n fn pow(self, mut n: u64) -> Self {\r\n let mut x = self;\r\n let mut r = Self::raw(1);\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n r *= x;\r\n }\r\n x *= x;\r\n n >>= 1;\r\n }\r\n r\r\n }\r\n}\r\n\r\npub trait RemEuclidU32 {\r\n /// Calculates `self` _mod_ `modulus` losslessly.\r\n fn rem_euclid_u32(self, modulus: u32) -> u32;\r\n}\r\n\r\nmacro_rules! impl_rem_euclid_u32_for_small_signed {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self as i64).rem_euclid(i64::from(modulus)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\nimpl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\r\n\r\nimpl RemEuclidU32 for i128 {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self.rem_euclid(i128::from(modulus)) as _\r\n }\r\n}\r\n\r\nmacro_rules! impl_rem_euclid_u32_for_small_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self as u32 % modulus\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\nmacro_rules! impl_rem_euclid_u32_for_large_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self % (modulus as $ty)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\nimpl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\r\nimpl_rem_euclid_u32_for_large_unsigned!(u64, u128);\r\n\r\n#[cfg(target_pointer_width = \"32\")]\r\nimpl_rem_euclid_u32_for_small_unsigned!(usize);\r\n\r\n#[cfg(target_pointer_width = \"64\")]\r\nimpl_rem_euclid_u32_for_large_unsigned!(usize);\r\n\r\ntrait InternalImplementations: ModIntBase {\r\n #[inline]\r\n fn inv_for_non_prime_modulus(this: Self) -> Self {\r\n let (gcd, x) = inv_gcd2(this.val().into(), Self::modulus().into());\r\n if gcd != 1 {\r\n panic!(\"the multiplicative inverse does not exist\");\r\n }\r\n Self::new(x)\r\n }\r\n\r\n #[inline]\r\n fn default_impl() -> Self {\r\n Self::raw(0)\r\n }\r\n\r\n #[inline]\r\n fn from_str_impl(s: &str) -> Result {\r\n Ok(s.parse::()\r\n .map(Self::new)\r\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\r\n }\r\n\r\n #[inline]\r\n fn hash_impl(this: &Self, state: &mut impl Hasher) {\r\n this.val().hash(state)\r\n }\r\n\r\n #[inline]\r\n fn display_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Display::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn debug_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Debug::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn neg_impl(this: Self) -> Self {\r\n Self::sub_impl(Self::raw(0), this)\r\n }\r\n\r\n #[inline]\r\n fn add_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val() + rhs.val();\r\n if val >= modulus {\r\n val -= modulus;\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn sub_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val().wrapping_sub(rhs.val());\r\n if val >= modulus {\r\n val = val.wrapping_add(modulus)\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self;\r\n\r\n #[inline]\r\n fn div_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::mul_impl(lhs, rhs.inv())\r\n }\r\n}\r\n\r\nimpl InternalImplementations for StaticModInt {\r\n #[inline]\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::raw((u64::from(lhs.val()) * u64::from(rhs.val()) % u64::from(M::VALUE)) as u32)\r\n }\r\n}\r\n\r\n\r\nmacro_rules! impl_basic_traits {\r\n () => {};\r\n (impl <$generic_param:ident : $generic_param_bound:tt> _ for $self:ty; $($rest:tt)*) => {\r\n impl <$generic_param: $generic_param_bound> Default for $self {\r\n #[inline]\r\n fn default() -> Self {\r\n Self::default_impl()\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> FromStr for $self {\r\n type Err = Infallible;\r\n\r\n #[inline]\r\n fn from_str(s: &str) -> Result {\r\n Self::from_str_impl(s)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound, V: RemEuclidU32> From for $self {\r\n #[inline]\r\n fn from(from: V) -> Self {\r\n Self::new(from)\r\n }\r\n }\r\n\r\n #[allow(clippy::derive_hash_xor_eq)]\r\n impl<$generic_param: $generic_param_bound> Hash for $self {\r\n #[inline]\r\n fn hash(&self, state: &mut H) {\r\n Self::hash_impl(self, state)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Display for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::display_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Debug for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::debug_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n Self::neg_impl(self)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for &'_ $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n <$self>::neg_impl(*self)\r\n }\r\n }\r\n\r\n impl_basic_traits!($($rest)*);\r\n };\r\n}\r\n\r\nimpl_basic_traits! {\r\n impl _ for StaticModInt ;\r\n}\r\n\r\nmacro_rules! impl_bin_ops {\r\n () => {};\r\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~ <$rhs_ty:ty> -> $output:ty { { $lhs_body:expr } ~ { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$($generic_param: $generic_param_bound),*> Add<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn add(self, rhs: $rhs_ty) -> $output {\r\n <$output>::add_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Sub<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn sub(self, rhs: $rhs_ty) -> $output {\r\n <$output>::sub_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Mul<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn mul(self, rhs: $rhs_ty) -> $output {\r\n <$output>::mul_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Div<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn div(self, rhs: $rhs_ty) -> $output {\r\n <$output>::div_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl_bin_ops!($($rest)*);\r\n };\r\n}\r\n\r\nmacro_rules! impl_assign_ops {\r\n () => {};\r\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~= <$rhs_ty:ty> { _ ~= { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$($generic_param: $generic_param_bound),*> AddAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn add_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self + apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> SubAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn sub_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self - apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> MulAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn mul_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self * apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> DivAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn div_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self / apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl_assign_ops!($($rest)*);\r\n };\r\n}\r\n\r\n#[inline]\r\nfn apply O, X, O>(f: F, x: X) -> O {\r\n f(x)\r\n}\r\n\r\nimpl_bin_ops! {\r\n for > ~ > -> StaticModInt { { |x| x } ~ { |x| x } }\r\n for > ~ <&'_ StaticModInt > -> StaticModInt { { |x| x } ~ { |&x| x } }\r\n for <&'_ StaticModInt > ~ > -> StaticModInt { { |&x| x } ~ { |x| x } }\r\n for <&'_ StaticModInt > ~ <&'_ StaticModInt > -> StaticModInt { { |&x| x } ~ { |&x| x } }\r\n\r\n for > ~ -> StaticModInt { { |x| x } ~ { StaticModInt::::new } }\r\n}\r\n\r\nimpl_assign_ops! {\r\n for > ~= > { _ ~= { |x| x } }\r\n for > ~= <&'_ StaticModInt > { _ ~= { |&x| x } }\r\n\r\n for > ~= { _ ~= { StaticModInt::::new } }\r\n}\r\n\r\nmacro_rules! impl_folding {\r\n () => {};\r\n (impl<$generic_param:ident : $generic_param_bound:tt> $trait:ident<_> for $self:ty { fn $method:ident(_) -> _ { _($unit:expr, $op:expr) } } $($rest:tt)*) => {\r\n impl<$generic_param: $generic_param_bound> $trait for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl<'a, $generic_param: $generic_param_bound> $trait<&'a Self> for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl_folding!($($rest)*);\r\n };\r\n}\r\n\r\nimpl_folding! {\r\n impl Sum<_> for StaticModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\r\n impl Product<_> for StaticModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\r\n}\r\n\r\n\r\n\r\n\r\n//convolution.ts\r\n//\r\n\r\n\r\nfn primitive_root(m: i32) -> i32 {\r\n match m {\r\n 2 => return 1,\r\n 167_772_161 => return 3,\r\n 469_762_049 => return 3,\r\n 754_974_721 => return 11,\r\n 998_244_353 => return 3,\r\n _ => {}\r\n }\r\n\r\n let mut divs = [0; 20];\r\n divs[0] = 2;\r\n let mut cnt = 1;\r\n let mut x = (m - 1) / 2;\r\n while x % 2 == 0 {\r\n x /= 2;\r\n }\r\n for i in (3..std::i32::MAX).step_by(2) {\r\n if i as i64 * i as i64 > x as i64 {\r\n break;\r\n }\r\n if x % i == 0 {\r\n divs[cnt] = i;\r\n cnt += 1;\r\n while x % i == 0 {\r\n x /= i;\r\n }\r\n }\r\n }\r\n if x > 1 {\r\n divs[cnt] = x;\r\n cnt += 1;\r\n }\r\n let mut g = 2;\r\n loop {\r\n if (0..cnt).all(|i| modpow2(g, ((m - 1) / divs[i]) as i64, m) != 1) {\r\n break g as i32;\r\n }\r\n g += 1;\r\n }\r\n}\r\n\r\n\r\n\r\nfn ceil_pow2(n: u32) -> u32 {\r\n 32 - n.saturating_sub(1).leading_zeros()\r\n}\r\n\r\n\r\nmacro_rules! modulus {\r\n ($($name:ident),*) => {\r\n $(\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n enum $name {}\r\n\r\n impl Modulus for $name {\r\n const VALUE: u32 = $name as _;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static ::std::thread::LocalKey<::std::cell::RefCell<::std::option::Option>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: ::std::cell::RefCell<::std::option::Option>> = ::std::default::Default::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n }\r\n )*\r\n };\r\n}\r\n\r\n#[allow(clippy::many_single_char_names)]\r\npub fn convolution(a: &[StaticModInt], b: &[StaticModInt]) -> Vec>\r\nwhere\r\n M: Modulus,\r\n{\r\n if a.is_empty() || b.is_empty() {\r\n return vec![];\r\n }\r\n let (n, m) = (a.len(), b.len());\r\n\r\n if cmp::min(n, m) <= 60 {\r\n let (n, m, a, b) = if n < m { (m, n, b, a) } else { (n, m, a, b) };\r\n let mut ans = vec![StaticModInt::new(0); n + m - 1];\r\n for i in 0..n {\r\n for j in 0..m {\r\n ans[i + j] += a[i] * b[j];\r\n }\r\n }\r\n return ans;\r\n }\r\n\r\n let (mut a, mut b) = (a.to_owned(), b.to_owned());\r\n let z = 1 << ceil_pow2((n + m - 1) as _);\r\n a.resize(z, StaticModInt::raw(0));\r\n butterfly(&mut a);\r\n b.resize(z, StaticModInt::raw(0));\r\n butterfly(&mut b);\r\n for (a, b) in a.iter_mut().zip(&b) {\r\n *a *= b;\r\n }\r\n butterfly_inv(&mut a);\r\n a.resize(n + m - 1, StaticModInt::raw(0));\r\n let iz = StaticModInt::new(z).inv();\r\n for a in &mut a {\r\n *a *= iz;\r\n }\r\n a\r\n}\r\n\r\npub fn convolution_raw(a: &[T], b: &[T]) -> Vec\r\nwhere\r\n T: RemEuclidU32 + TryFrom + Clone,\r\n T::Error: fmt::Debug,\r\n M: Modulus,\r\n{\r\n let a = a.iter().cloned().map(Into::into).collect::>();\r\n let b = b.iter().cloned().map(Into::into).collect::>();\r\n convolution::(&a, &b)\r\n .into_iter()\r\n .map(|z| {\r\n z.val()\r\n .try_into()\r\n .expect(\"the numeric type is smaller than the modulus\")\r\n })\r\n .collect()\r\n}\r\n\r\n\r\n#[allow(clippy::many_single_char_names)]\r\nfn butterfly(a: &mut [StaticModInt]) {\r\n let n = a.len();\r\n let h = ceil_pow2(n as u32);\r\n\r\n M::butterfly_cache().with(|cache| {\r\n let mut cache = cache.borrow_mut();\r\n let ButterflyCache { sum_e, .. } = cache.get_or_insert_with(prepare);\r\n for ph in 1..=h {\r\n let w = 1 << (ph - 1);\r\n let p = 1 << (h - ph);\r\n let mut now = StaticModInt::::new(1);\r\n for s in 0..w {\r\n let offset = s << (h - ph + 1);\r\n for i in 0..p {\r\n let l = a[i + offset];\r\n let r = a[i + offset + p] * now;\r\n a[i + offset] = l + r;\r\n a[i + offset + p] = l - r;\r\n }\r\n now *= sum_e[(!s).trailing_zeros() as usize];\r\n }\r\n }\r\n });\r\n}\r\n\r\n#[allow(clippy::many_single_char_names)]\r\nfn butterfly_inv(a: &mut [StaticModInt]) {\r\n let n = a.len();\r\n let h = ceil_pow2(n as u32);\r\n\r\n M::butterfly_cache().with(|cache| {\r\n let mut cache = cache.borrow_mut();\r\n let ButterflyCache { sum_ie, .. } = cache.get_or_insert_with(prepare);\r\n for ph in (1..=h).rev() {\r\n let w = 1 << (ph - 1);\r\n let p = 1 << (h - ph);\r\n let mut inow = StaticModInt::::new(1);\r\n for s in 0..w {\r\n let offset = s << (h - ph + 1);\r\n for i in 0..p {\r\n let l = a[i + offset];\r\n let r = a[i + offset + p];\r\n a[i + offset] = l + r;\r\n a[i + offset + p] = StaticModInt::new(M::VALUE + l.val() - r.val()) * inow;\r\n }\r\n inow *= sum_ie[(!s).trailing_zeros() as usize];\r\n }\r\n }\r\n });\r\n}\r\n\r\nfn prepare() -> ButterflyCache {\r\n let g = StaticModInt::::raw(primitive_root(M::VALUE as i32) as u32);\r\n let mut es = [StaticModInt::::raw(0); 30]; // es[i]^(2^(2+i)) == 1\r\n let mut ies = [StaticModInt::::raw(0); 30];\r\n let cnt2 = (M::VALUE - 1).trailing_zeros() as usize;\r\n let mut e = g.pow(((M::VALUE - 1) >> cnt2).into());\r\n let mut ie = e.inv();\r\n for i in (2..=cnt2).rev() {\r\n es[i - 2] = e;\r\n ies[i - 2] = ie;\r\n e *= e;\r\n ie *= ie;\r\n }\r\n let sum_e = es\r\n .iter()\r\n .scan(StaticModInt::new(1), |acc, e| {\r\n *acc *= e;\r\n Some(*acc)\r\n })\r\n .collect();\r\n let sum_ie = ies\r\n .iter()\r\n .scan(StaticModInt::new(1), |acc, ie| {\r\n *acc *= ie;\r\n Some(*acc)\r\n })\r\n .collect();\r\n ButterflyCache { sum_e, sum_ie }\r\n}\r\n\r\n\r\n\r\n\r\nuse std::{\r\n convert::{TryFrom, TryInto as _},\r\n};\r\n\r\n\r\n\r\n#[allow(clippy::many_single_char_names)]\r\npub fn convolution_i64(a: &[i64], b: &[i64]) -> Vec {\r\n const M1: u64 = 754_974_721; // 2^24\r\n const M2: u64 = 167_772_161; // 2^25\r\n const M3: u64 = 469_762_049; // 2^26\r\n const M2M3: u64 = M2 * M3;\r\n const M1M3: u64 = M1 * M3;\r\n const M1M2: u64 = M1 * M2;\r\n const M1M2M3: u64 = M1M2.wrapping_mul(M3);\r\n\r\n modulus!(M1, M2, M3);\r\n\r\n if a.is_empty() || b.is_empty() {\r\n return vec![];\r\n }\r\n\r\n let (_, i1) = inv_gcd(M2M3 as _, M1 as _);\r\n let (_, i2) = inv_gcd(M1M3 as _, M2 as _);\r\n let (_, i3) = inv_gcd(M1M2 as _, M3 as _);\r\n\r\n let c1 = convolution_raw::(a, b);\r\n let c2 = convolution_raw::(a, b);\r\n let c3 = convolution_raw::(a, b);\r\n\r\n c1.into_iter()\r\n .zip(c2)\r\n .zip(c3)\r\n .map(|((c1, c2), c3)| {\r\n const OFFSET: &[u64] = &[0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3];\r\n\r\n let mut x = [(c1, i1, M1, M2M3), (c2, i2, M2, M1M3), (c3, i3, M3, M1M2)]\r\n .iter()\r\n .map(|&(c, i, m1, m2)| c.wrapping_mul(i).rem_euclid(m1 as _).wrapping_mul(m2 as _))\r\n .fold(0, i64::wrapping_add);\r\n\r\n let mut diff = c1 - safe_mod(x, M1 as _);\r\n if diff < 0 {\r\n diff += M1 as i64;\r\n }\r\n x = x.wrapping_sub(OFFSET[diff.rem_euclid(5) as usize] as _);\r\n x\r\n })\r\n .collect()\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n//suffix array\r\nstruct suffix_array{\r\n n:usize,\r\n S:Vec,\r\n k:usize,\r\n sa:Vec,\r\n rank:Vec,\r\n tmp:Vec,\r\n lcp:Vec,\r\n}\r\n\r\n\r\nimpl suffix_array{\r\n fn compare_sa(&mut self, i:&i64, j:&i64)-> std::cmp::Ordering{\r\n match self.rank[*i as usize].cmp(&(self.rank[*j as usize])){\r\n std::cmp::Ordering::Less => std::cmp::Ordering::Less,\r\n std::cmp::Ordering::Greater => std::cmp::Ordering::Greater,\r\n std::cmp::Ordering::Equal => {\r\n let mut ri = {if (*i as usize+self.k)<=self.n{self.rank[*i as usize+self.k]}else{-1}};\r\n let mut rj = {if (*j as usize+self.k)<=self.n{self.rank[*j as usize+self.k]}else{-1}};\r\n match ri.cmp(&rj){\r\n std::cmp::Ordering::Less => std::cmp::Ordering::Less,\r\n std::cmp::Ordering::Greater => std::cmp::Ordering::Greater,\r\n std::cmp::Ordering::Equal => std::cmp::Ordering::Greater,\r\n }\r\n \r\n }\r\n }\r\n }\r\n\r\n\r\n fn new(S:&Vec)->suffix_array{\r\n let mut n = S.len();\r\n let mut s = vec![];\r\n for i in 0..n{\r\n s.push(S[i] as i64);\r\n }\r\n let mut sa = vec![];\r\n let mut rank = vec![0;n+1];\r\n let mut tmp = vec![0;n+1];\r\n let mut lcp = vec![];\r\n return suffix_array{lcp:lcp, n:n, S:s, sa:sa, rank:rank, tmp:tmp, k:0};\r\n }\r\n fn build(&mut self){\r\n let mut sa = vec![0;self.n+1];\r\n for i in 0..self.n+1{\r\n sa[i] = i as i64;\r\n self.rank[i] = {if iself.n{\r\n break;\r\n }\r\n sa.sort_by(|a, b| self.compare_sa(a, b));\r\n self.tmp[sa[0] as usize] = 0;\r\n for i in 1..self.n+1{\r\n let res = self.compare_sa(&(sa[i-1]), &(sa[i]));\r\n let mut zo = 0;\r\n if res == Ordering::Greater{\r\n zo = 0;\r\n }\r\n else{\r\n zo = 1;\r\n }\r\n self.tmp[sa[i] as usize] = self.tmp[sa[i-1] as usize] + zo;\r\n }\r\n mem::swap(&mut self.rank, &mut self.tmp);\r\n self.k*=2;\r\n }\r\n self.sa = sa;\r\n }\r\n fn contain(&self, T:&Vec)->bool{\r\n let mut a = 0;\r\n let mut b = self.S.len();\r\n let mut t = T.as_slice();\r\n while(b-a>1){\r\n let mut c= (a+b)/2;\r\n if &(self.S[ (self.sa[c] as usize)..(self.sa[c] as usize + T.len()) ]) < t{\r\n a = c;\r\n }\r\n else{\r\n b = c;\r\n }\r\n }\r\n return &(self.S[self.sa[b] as usize ..self.sa[b] as usize+T.len()]) == T.as_slice();\r\n }\r\n\r\n\r\n fn construct_lcp(&mut self){\r\n let mut n = self.S.len();\r\n for i in 0..n+1{\r\n self.rank[self.sa[i] as usize] = i as i64;\r\n }\r\n let mut h = 0;\r\n self.lcp = vec![0;n+1];\r\n self.lcp[0] = 0;\r\n for i in 0..n{\r\n let mut j = self.sa[self.rank[i] as usize -1];\r\n if h>0{\r\n h-=1;\r\n }\r\n while(true){\r\n if( (j as i64+h as i64) , size:usize)->i64{\r\n for i in 0..size{\r\n let a = pat[i];\r\n if x+i>=self.S.len(){\r\n return -1;\r\n }\r\n let b = self.S[x+i];\r\n if ab{\r\n return 1;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n fn search_pattern_sub(&self, pat:&Vec, pat_size:usize)->i64{\r\n let mut low= 0;\r\n let mut high = self.S.len()-1;\r\n while low<=high{\r\n let mut mid =(low+high)/2;\r\n let mut r = self.compare_pat(self.sa[mid] as usize, pat, pat_size);\r\n if r==0{\r\n return mid as i64;\r\n }\r\n else if r>0{\r\n low = mid+1;\r\n }\r\n else{\r\n high = mid-1;\r\n }\r\n }\r\n return -1;\r\n }\r\n fn search_pat(&self, pat:&Vec)->i64{\r\n let mut pat_size = pat.len();\r\n let mut x = self.search_pattern_sub(pat, pat_size);\r\n if x >= 0{\r\n return self.sa[x as usize];\r\n }\r\n return -1;\r\n }\r\n fn search_pattern_all(&self, pat:&Vec)->Vec{\r\n let mut pat_size = pat.len();\r\n let mut x = self.search_pattern_sub(pat, pat_size);\r\n if x<0{\r\n return vec![];\r\n }\r\n let mut s = x-1;\r\n while s>=0 && self.compare_pat(self.sa[s as usize] as usize, pat, pat_size) == 0 {\r\n s -=1;\r\n }\r\n let mut e = x+1;\r\n while (e as usize) < self.S.len() && self.compare_pat(self.sa[e as usize] as usize, pat, pat_size) ==0{\r\n e+=1;\r\n }\r\n return self.sa[s as usize+1..e as usize].to_vec();\r\n }\r\n\r\n\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n//\u7d20\u56e0\u6570\u5206\u89e3\r\nfn prime_factor(n:usize)->HashMap{\r\n let mut res = HashMap::new();\r\n let mut n = n;\r\n for i in 2..n{\r\n if i*i>n{break;}\r\n while(n%i==0){\r\n *res.entry(i).or_insert(0)+=1;\r\n n/=i;\r\n }\r\n }\r\n if n != 1{\r\n res.insert(n, 1);\r\n }\r\n res\r\n}\r\n\r\n//\u7d20\u56e0\u6570\u5206\u89e3\u3000\u30af\u30a8\u30ea\r\n//let mut spf = smallest_prime_factor(10000);\r\n//let mut f = factorization(x, &sfp);\r\nfn smallest_prime_factor(n:usize)->Vec{\r\n let mut spf = vec![0;n+1];\r\n for i in 0..n+1{\r\n spf[i] = i;\r\n }\r\n for i in 2..INFu{\r\n if i*i>n{\r\n break;\r\n }\r\n if spf[i] == i{\r\n let mut j = i*i;\r\n while(j<=n){\r\n if spf[j] == j{\r\n spf[j] = i;\r\n }\r\n j+=i;\r\n }\r\n }\r\n }\r\n\r\n return spf;\r\n}\r\nfn factorization(x:usize, spf:&Vec)->Vec{\r\n let mut res = vec![];\r\n let mut x = x;\r\n while(x != 1){\r\n res.push(spf[x]);\r\n x/=spf[x];\r\n }\r\n res.sort();\r\n return res;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nfn usize_multiply_is_overflow(a:usize, b:usize)->bool{\r\n if a (Vec, Vec){\r\n let mut p:usize = 0;\r\n let mut is_prime = vec![false; n+1];\r\n let mut prime = Vec::new();\r\n for i in 0..n+1{\r\n is_prime[i] = true;\r\n }\r\n is_prime[0] = false;\r\n is_prime[1] = false;\r\n for i in 2..n+1{\r\n if is_prime[i]{\r\n prime.push(i as usize);\r\n let mut j = 2*i;\r\n while(j<=n){\r\n is_prime[j] = false;\r\n j+=i;\r\n }\r\n }\r\n }\r\n (is_prime, prime)\r\n \r\n}\r\n\r\n\r\n\r\n\r\nfn transpose(v: Vec>) -> Vec>\r\nwhere\r\n T: Clone,\r\n{\r\n assert!(!v.is_empty());\r\n (0..v[0].len())\r\n .map(|i| v.iter().map(|inner| inner[i].clone()).collect::>())\r\n .collect()\r\n}\r\nuse std::ops::Bound::Included;\r\nuse std::iter::{once, repeat};\r\n\r\n\r\nfn solve(){\r\n let sssss = std::io::stdin();\r\n let mut sc = Scanner { stdin: sssss.lock() };\r\n let mut test:usize = sc.read();\r\n for _ in 0..test{\r\n let mut n:i64 = sc.read();\r\n let mut k:i64 = sc.read();\r\n let mut res = 1;\r\n for i in 0..k{\r\n res*=n;\r\n res%=MOD;\r\n }\r\n println!(\"{}\", res);\r\n\r\n\r\n }\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n \r\nfn main(){\r\n solve();\r\n}\r\n\r\n\r\nconst PI:f64 = std::f64::consts::PI;\r\npub static MOD:i64 = 1000000007;\r\npub static MODu:usize = 1000000007;\r\npub static MODi32:i32 = 998244353;\r\npub static eps:f64 = 1e-6;\r\nconst INF: i64 = 1 << 60;\r\nconst INFu:usize = 1<<30;\r\n\r\n\r\n\r\n\r\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "53dbc8e17c496ba2c662708476d0eb67", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\r\n#![allow(unused_imports)]\r\n#![allow(non_upper_case_globals)]\r\n#![allow(non_snake_case)]\r\n#![allow(unused_mut)]\r\n#![allow(unused_variables)]\r\n#![allow(dead_code)]\r\n\r\ntype Vec2 = Vec>;\r\ntype Vec3 = Vec>>;\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! invec {\r\n ( $ t : ty ) => {{\r\n let mut s = String::new();\r\n match std::io::stdin().read_line(&mut s) {\r\n Ok(0) => Vec::<$t>::new(),\r\n Ok(n) => s\r\n .trim()\r\n .split_whitespace()\r\n .map(|s| s.parse::<$t>().unwrap())\r\n .collect::>(),\r\n Err(_) => Vec::<$t>::new(),\r\n }\r\n }};\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! get {\r\n ($t:ty) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.trim().parse::<$t>().unwrap()\r\n }\r\n };\r\n ($($t:ty),*) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n let mut iter = line.split_whitespace();\r\n (\r\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\r\n )\r\n }\r\n };\r\n ($t:ty; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($t)\r\n ).collect::>()\r\n };\r\n ($($t:ty),*; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($($t),*)\r\n ).collect::>()\r\n };\r\n ($t:ty ;;) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.split_whitespace()\r\n .map(|t| t.parse::<$t>().unwrap())\r\n .collect::>()\r\n }\r\n };\r\n ($t:ty ;; $n:expr) => {\r\n (0..$n).map(|_| get!($t ;;)).collect::>()\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let mut s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\r\n let mut $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n\r\n ($next:expr, [$t:tt]) => {\r\n {\r\n let len = read_value!($next, usize);\r\n (0..len).map(|_| read_value!($next, $t)).collect::>()\r\n }\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\n#[cfg(debug_assertions)]\r\nmacro_rules! mydbg {\r\n //($arg:expr) => (dbg!($arg))\r\n //($arg:expr) => (println!(\"{:?}\",$arg));\r\n ($($a:expr),*) => {\r\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\r\n }\r\n}\r\n#[cfg(not(debug_assertions))]\r\nmacro_rules! mydbg {\r\n ($($arg:expr),*) => {};\r\n}\r\n\r\nmacro_rules! echo {\r\n ($($a:expr),*) => {\r\n $(println!(\"{}\",$a))*\r\n }\r\n}\r\n\r\nuse std::cmp::*;\r\nuse std::collections::*;\r\nuse std::ops::{Add, Div, Mul, Rem, Sub};\r\n\r\ntrait SafeRangeContain {\r\n fn safe_contains(&self, x: i64) -> bool;\r\n}\r\n\r\nimpl SafeRangeContain for std::ops::Range {\r\n fn safe_contains(&self, x: i64) -> bool {\r\n if x < 0 {\r\n return false;\r\n }\r\n return self.contains(&(x as usize));\r\n }\r\n}\r\n\r\n#[allow(dead_code)]\r\nstatic INF_I64: i64 = i64::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_I32: i32 = i32::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_USIZE: usize = usize::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic M_O_D: usize = 1000000007;\r\n#[allow(dead_code)]\r\nstatic PAI: f64 = 3.1415926535897932;\r\n\r\ntrait IteratorExt: Iterator {\r\n fn toVec(self) -> Vec;\r\n}\r\n\r\nimpl IteratorExt for T {\r\n fn toVec(self) -> Vec {\r\n self.collect()\r\n }\r\n}\r\n\r\ntrait CharExt {\r\n fn toNum(&self) -> usize;\r\n fn toAlphabetIndex(&self) -> usize;\r\n fn toNumIndex(&self) -> usize;\r\n}\r\nimpl CharExt for char {\r\n fn toNum(&self) -> usize {\r\n return *self as usize;\r\n }\r\n fn toAlphabetIndex(&self) -> usize {\r\n return self.toNum() - 'a' as usize;\r\n }\r\n fn toNumIndex(&self) -> usize {\r\n return self.toNum() - '0' as usize;\r\n }\r\n}\r\n\r\ntrait VectorExt {\r\n fn joinToString(&self, s: &str) -> String;\r\n}\r\nimpl VectorExt for Vec {\r\n fn joinToString(&self, s: &str) -> String {\r\n return self\r\n .iter()\r\n .map(|x| x.to_string())\r\n .collect::>()\r\n .join(s);\r\n }\r\n}\r\n\r\ntrait StringExt {\r\n fn get_reverse(&self) -> String;\r\n}\r\nimpl StringExt for String {\r\n fn get_reverse(&self) -> String {\r\n self.chars().rev().collect::()\r\n }\r\n}\r\n\r\ntrait UsizeExt {\r\n fn pow(&self, n: usize) -> usize;\r\n}\r\nimpl UsizeExt for usize {\r\n fn pow(&self, n: usize) -> usize {\r\n return ((*self as u64).pow(n as u32)) as usize;\r\n }\r\n}\r\n\r\n//https://github.com/rust-lang-ja/ac-library-rs\r\n\r\npub mod internal_math {\r\n // remove this after dependencies has been added\r\n #![allow(dead_code)]\r\n use std::mem::swap;\r\n\r\n /// # Arguments\r\n /// * `m` `1 <= m`\r\n ///\r\n /// # Returns\r\n /// x mod m\r\n /* const */\r\n pub(crate) fn safe_mod(mut x: i64, m: i64) -> i64 {\r\n x %= m;\r\n if x < 0 {\r\n x += m;\r\n }\r\n x\r\n }\r\n\r\n /// Fast modular by barrett reduction\r\n /// Reference: https://en.wikipedia.org/wiki/Barrett_reduction\r\n /// NOTE: reconsider after Ice Lake\r\n pub(crate) struct Barrett {\r\n pub(crate) _m: u32,\r\n pub(crate) im: u64,\r\n }\r\n\r\n impl Barrett {\r\n /// # Arguments\r\n /// * `m` `1 <= m`\r\n /// (Note: `m <= 2^31` should also hold, which is undocumented in the original library.\r\n /// See the [pull reqeust commment](https://github.com/rust-lang-ja/ac-library-rs/pull/3#discussion_r484661007)\r\n /// for more details.)\r\n pub(crate) fn new(m: u32) -> Barrett {\r\n Barrett {\r\n _m: m,\r\n im: (-1i64 as u64 / m as u64).wrapping_add(1),\r\n }\r\n }\r\n\r\n /// # Returns\r\n /// `m`\r\n pub(crate) fn umod(&self) -> u32 {\r\n self._m\r\n }\r\n\r\n /// # Parameters\r\n /// * `a` `0 <= a < m`\r\n /// * `b` `0 <= b < m`\r\n ///\r\n /// # Returns\r\n /// a * b % m\r\n #[allow(clippy::many_single_char_names)]\r\n pub(crate) fn mul(&self, a: u32, b: u32) -> u32 {\r\n // [1] m = 1\r\n // a = b = im = 0, so okay\r\n\r\n // [2] m >= 2\r\n // im = ceil(2^64 / m)\r\n // -> im * m = 2^64 + r (0 <= r < m)\r\n // let z = a*b = c*m + d (0 <= c, d < m)\r\n // a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im\r\n // c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2\r\n // ((ab * im) >> 64) == c or c + 1\r\n let mut z = a as u64;\r\n z *= b as u64;\r\n let x = (((z as u128) * (self.im as u128)) >> 64) as u64;\r\n let mut v = z.wrapping_sub(x.wrapping_mul(self._m as u64)) as u32;\r\n if self._m <= v {\r\n v = v.wrapping_add(self._m);\r\n }\r\n v\r\n }\r\n }\r\n\r\n /// # Parameters\r\n /// * `n` `0 <= n`\r\n /// * `m` `1 <= m`\r\n ///\r\n /// # Returns\r\n /// `(x ** n) % m`\r\n /* const */\r\n #[allow(clippy::many_single_char_names)]\r\n pub(crate) fn pow_mod(x: i64, mut n: i64, m: i32) -> i64 {\r\n if m == 1 {\r\n return 0;\r\n }\r\n let _m = m as u32;\r\n let mut r: u64 = 1;\r\n let mut y: u64 = safe_mod(x, m as i64) as u64;\r\n while n != 0 {\r\n if (n & 1) > 0 {\r\n r = (r * y) % (_m as u64);\r\n }\r\n y = (y * y) % (_m as u64);\r\n n >>= 1;\r\n }\r\n r as i64\r\n }\r\n\r\n /// Reference:\r\n /// M. Forisek and J. Jancina,\r\n /// Fast Primality Testing for Integers That Fit into a Machine Word\r\n ///\r\n /// # Parameters\r\n /// * `n` `0 <= n`\r\n /* const */\r\n pub(crate) fn is_prime(n: i32) -> bool {\r\n let n = n as i64;\r\n match n {\r\n _ if n <= 1 => return false,\r\n 2 | 7 | 61 => return true,\r\n _ if n % 2 == 0 => return false,\r\n _ => {}\r\n }\r\n let mut d = n - 1;\r\n while d % 2 == 0 {\r\n d /= 2;\r\n }\r\n for &a in &[2, 7, 61] {\r\n let mut t = d;\r\n let mut y = pow_mod(a, t, n as i32);\r\n while t != n - 1 && y != 1 && y != n - 1 {\r\n y = y * y % n;\r\n t <<= 1;\r\n }\r\n if y != n - 1 && t % 2 == 0 {\r\n return false;\r\n }\r\n }\r\n true\r\n }\r\n\r\n // omitted\r\n // template constexpr bool is_prime = is_prime_constexpr(n);\r\n\r\n /// # Parameters\r\n /// * `b` `1 <= b`\r\n ///\r\n /// # Returns\r\n /// (g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\r\n /* const */\r\n #[allow(clippy::many_single_char_names)]\r\n pub(crate) fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\r\n let a = safe_mod(a, b);\r\n if a == 0 {\r\n return (b, 0);\r\n }\r\n\r\n // Contracts:\r\n // [1] s - m0 * a = 0 (mod b)\r\n // [2] t - m1 * a = 0 (mod b)\r\n // [3] s * |m1| + t * |m0| <= b\r\n let mut s = b;\r\n let mut t = a;\r\n let mut m0 = 0;\r\n let mut m1 = 1;\r\n\r\n while t != 0 {\r\n let u = s / t;\r\n s -= t * u;\r\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\r\n\r\n // [3]:\r\n // (s - t * u) * |m1| + t * |m0 - m1 * u|\r\n // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)\r\n // = s * |m1| + t * |m0| <= b\r\n\r\n swap(&mut s, &mut t);\r\n swap(&mut m0, &mut m1);\r\n }\r\n // by [3]: |m0| <= b/g\r\n // by g != b: |m0| < b/g\r\n if m0 < 0 {\r\n m0 += b / s;\r\n }\r\n (s, m0)\r\n }\r\n\r\n /// Compile time (currently not) primitive root\r\n /// @param m must be prime\r\n /// @return primitive root (and minimum in now)\r\n /* const */\r\n pub(crate) fn primitive_root(m: i32) -> i32 {\r\n match m {\r\n 2 => return 1,\r\n 167_772_161 => return 3,\r\n 469_762_049 => return 3,\r\n 754_974_721 => return 11,\r\n 998_244_353 => return 3,\r\n _ => {}\r\n }\r\n\r\n let mut divs = [0; 20];\r\n divs[0] = 2;\r\n let mut cnt = 1;\r\n let mut x = (m - 1) / 2;\r\n while x % 2 == 0 {\r\n x /= 2;\r\n }\r\n for i in (3..std::i32::MAX).step_by(2) {\r\n if i as i64 * i as i64 > x as i64 {\r\n break;\r\n }\r\n if x % i == 0 {\r\n divs[cnt] = i;\r\n cnt += 1;\r\n while x % i == 0 {\r\n x /= i;\r\n }\r\n }\r\n }\r\n if x > 1 {\r\n divs[cnt] = x;\r\n cnt += 1;\r\n }\r\n let mut g = 2;\r\n loop {\r\n if (0..cnt).all(|i| pow_mod(g, ((m - 1) / divs[i]) as i64, m) != 1) {\r\n break g as i32;\r\n }\r\n g += 1;\r\n }\r\n }\r\n // omitted\r\n // template constexpr int primitive_root = primitive_root_constexpr(m);\r\n\r\n #[cfg(test)]\r\n mod tests {\r\n #![allow(clippy::unreadable_literal)]\r\n #![allow(clippy::cognitive_complexity)]\r\n use crate::internal_math::{inv_gcd, is_prime, pow_mod, primitive_root, safe_mod, Barrett};\r\n use std::collections::HashSet;\r\n\r\n #[test]\r\n fn test_safe_mod() {\r\n assert_eq!(safe_mod(0, 3), 0);\r\n assert_eq!(safe_mod(1, 3), 1);\r\n assert_eq!(safe_mod(2, 3), 2);\r\n assert_eq!(safe_mod(3, 3), 0);\r\n assert_eq!(safe_mod(4, 3), 1);\r\n assert_eq!(safe_mod(5, 3), 2);\r\n assert_eq!(safe_mod(73, 11), 7);\r\n assert_eq!(safe_mod(2306249155046129918, 6620319213327), 1374210749525);\r\n\r\n assert_eq!(safe_mod(-1, 3), 2);\r\n assert_eq!(safe_mod(-2, 3), 1);\r\n assert_eq!(safe_mod(-3, 3), 0);\r\n assert_eq!(safe_mod(-4, 3), 2);\r\n assert_eq!(safe_mod(-5, 3), 1);\r\n assert_eq!(safe_mod(-7170500492396019511, 777567337), 333221848);\r\n }\r\n\r\n #[test]\r\n fn test_barrett() {\r\n let b = Barrett::new(7);\r\n assert_eq!(b.umod(), 7);\r\n assert_eq!(b.mul(2, 3), 6);\r\n assert_eq!(b.mul(4, 6), 3);\r\n assert_eq!(b.mul(5, 0), 0);\r\n\r\n let b = Barrett::new(998244353);\r\n assert_eq!(b.umod(), 998244353);\r\n assert_eq!(b.mul(2, 3), 6);\r\n assert_eq!(b.mul(3141592, 653589), 919583920);\r\n assert_eq!(b.mul(323846264, 338327950), 568012980);\r\n\r\n // make `z - x * self._m as u64` overflow.\r\n // Thanks @koba-e964 (at https://github.com/rust-lang-ja/ac-library-rs/pull/3#discussion_r484932161)\r\n let b = Barrett::new(2147483647);\r\n assert_eq!(b.umod(), 2147483647);\r\n assert_eq!(b.mul(1073741824, 2147483645), 2147483646);\r\n }\r\n\r\n #[test]\r\n fn test_pow_mod() {\r\n assert_eq!(pow_mod(0, 0, 1), 0);\r\n assert_eq!(pow_mod(0, 0, 3), 1);\r\n assert_eq!(pow_mod(0, 0, 723), 1);\r\n assert_eq!(pow_mod(0, 0, 998244353), 1);\r\n assert_eq!(pow_mod(0, 0, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(0, 1, 1), 0);\r\n assert_eq!(pow_mod(0, 1, 3), 0);\r\n assert_eq!(pow_mod(0, 1, 723), 0);\r\n assert_eq!(pow_mod(0, 1, 998244353), 0);\r\n assert_eq!(pow_mod(0, 1, i32::max_value()), 0);\r\n\r\n assert_eq!(pow_mod(0, i64::max_value(), 1), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), 3), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), 723), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), 998244353), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), i32::max_value()), 0);\r\n\r\n assert_eq!(pow_mod(1, 0, 1), 0);\r\n assert_eq!(pow_mod(1, 0, 3), 1);\r\n assert_eq!(pow_mod(1, 0, 723), 1);\r\n assert_eq!(pow_mod(1, 0, 998244353), 1);\r\n assert_eq!(pow_mod(1, 0, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(1, 1, 1), 0);\r\n assert_eq!(pow_mod(1, 1, 3), 1);\r\n assert_eq!(pow_mod(1, 1, 723), 1);\r\n assert_eq!(pow_mod(1, 1, 998244353), 1);\r\n assert_eq!(pow_mod(1, 1, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(1, i64::max_value(), 1), 0);\r\n assert_eq!(pow_mod(1, i64::max_value(), 3), 1);\r\n assert_eq!(pow_mod(1, i64::max_value(), 723), 1);\r\n assert_eq!(pow_mod(1, i64::max_value(), 998244353), 1);\r\n assert_eq!(pow_mod(1, i64::max_value(), i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(i64::max_value(), 0, 1), 0);\r\n assert_eq!(pow_mod(i64::max_value(), 0, 3), 1);\r\n assert_eq!(pow_mod(i64::max_value(), 0, 723), 1);\r\n assert_eq!(pow_mod(i64::max_value(), 0, 998244353), 1);\r\n assert_eq!(pow_mod(i64::max_value(), 0, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 1), 0);\r\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 3), 1);\r\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 723), 640);\r\n assert_eq!(\r\n pow_mod(i64::max_value(), i64::max_value(), 998244353),\r\n 683296792\r\n );\r\n assert_eq!(\r\n pow_mod(i64::max_value(), i64::max_value(), i32::max_value()),\r\n 1\r\n );\r\n\r\n assert_eq!(pow_mod(2, 3, 1_000_000_007), 8);\r\n assert_eq!(pow_mod(5, 7, 1_000_000_007), 78125);\r\n assert_eq!(pow_mod(123, 456, 1_000_000_007), 565291922);\r\n }\r\n\r\n #[test]\r\n fn test_is_prime() {\r\n assert!(!is_prime(0));\r\n assert!(!is_prime(1));\r\n assert!(is_prime(2));\r\n assert!(is_prime(3));\r\n assert!(!is_prime(4));\r\n assert!(is_prime(5));\r\n assert!(!is_prime(6));\r\n assert!(is_prime(7));\r\n assert!(!is_prime(8));\r\n assert!(!is_prime(9));\r\n\r\n // assert!(is_prime(57));\r\n assert!(!is_prime(57));\r\n assert!(!is_prime(58));\r\n assert!(is_prime(59));\r\n assert!(!is_prime(60));\r\n assert!(is_prime(61));\r\n assert!(!is_prime(62));\r\n\r\n assert!(!is_prime(701928443));\r\n assert!(is_prime(998244353));\r\n assert!(!is_prime(1_000_000_000));\r\n assert!(is_prime(1_000_000_007));\r\n\r\n assert!(is_prime(i32::max_value()));\r\n }\r\n\r\n #[test]\r\n fn test_is_prime_sieve() {\r\n let n = 1_000_000;\r\n let mut prime = vec![true; n];\r\n prime[0] = false;\r\n prime[1] = false;\r\n for i in 0..n {\r\n assert_eq!(prime[i], is_prime(i as i32));\r\n if prime[i] {\r\n for j in (2 * i..n).step_by(i) {\r\n prime[j] = false;\r\n }\r\n }\r\n }\r\n }\r\n\r\n #[test]\r\n fn test_inv_gcd() {\r\n for &(a, b, g) in &[\r\n (0, 1, 1),\r\n (0, 4, 4),\r\n (0, 7, 7),\r\n (2, 3, 1),\r\n (-2, 3, 1),\r\n (4, 6, 2),\r\n (-4, 6, 2),\r\n (13, 23, 1),\r\n (57, 81, 3),\r\n (12345, 67890, 15),\r\n (-3141592 * 6535, 3141592 * 8979, 3141592),\r\n (i64::max_value(), i64::max_value(), i64::max_value()),\r\n (i64::min_value(), i64::max_value(), 1),\r\n ] {\r\n let (g_, x) = inv_gcd(a, b);\r\n assert_eq!(g, g_);\r\n let b_ = b as i128;\r\n assert_eq!(((x as i128 * a as i128) % b_ + b_) % b_, g as i128 % b_);\r\n }\r\n }\r\n\r\n #[test]\r\n fn test_primitive_root() {\r\n for &p in &[\r\n 2,\r\n 3,\r\n 5,\r\n 7,\r\n 233,\r\n 200003,\r\n 998244353,\r\n 1_000_000_007,\r\n i32::max_value(),\r\n ] {\r\n assert!(is_prime(p));\r\n let g = primitive_root(p);\r\n if p != 2 {\r\n assert_ne!(g, 1);\r\n }\r\n\r\n let q = p - 1;\r\n for i in (2..i32::max_value()).take_while(|i| i * i <= q) {\r\n if q % i != 0 {\r\n break;\r\n }\r\n for &r in &[i, q / i] {\r\n assert_ne!(pow_mod(g as i64, r as i64, p), 1);\r\n }\r\n }\r\n assert_eq!(pow_mod(g as i64, q as i64, p), 1);\r\n\r\n if p < 1_000_000 {\r\n assert_eq!(\r\n (0..p - 1)\r\n .scan(1, |i, _| {\r\n *i = *i * g % p;\r\n Some(*i)\r\n })\r\n .collect::>()\r\n .len() as i32,\r\n p - 1\r\n );\r\n }\r\n }\r\n }\r\n }\r\n}\r\npub mod modint {\r\n //! Structs that treat the modular arithmetic.\r\n //!\r\n //! # Major changes from the original ACL\r\n //!\r\n //! - Converted the struct names to PascalCase.\r\n //! - Renamed `mod` -> `modulus`.\r\n //! - Moduli are `u32`, not `i32`.\r\n //! - `Id`s are `usize`, not `i32`.\r\n //! - The default `Id` is `0`, not `-1`.\r\n //! - The type of the argument of `pow` is `u64`, not `i64`.\r\n //! - Modints implement `FromStr` and `Display`. Modints in the original ACL don't have `operator<<` or `operator>>`.\r\n\r\n use crate::internal_math;\r\n use std::{\r\n cell::RefCell,\r\n convert::{Infallible, TryInto as _},\r\n fmt,\r\n hash::{Hash, Hasher},\r\n iter::{Product, Sum},\r\n marker::PhantomData,\r\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\r\n str::FromStr,\r\n thread::LocalKey,\r\n };\r\n\r\n pub type ModInt1000000007 = StaticModInt;\r\n pub type ModInt998244353 = StaticModInt;\r\n pub type ModInt = DynamicModInt;\r\n\r\n /// Corresponds to `atcoder::static_modint` in the original ACL.\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n #[repr(transparent)]\r\n pub struct StaticModInt {\r\n val: u32,\r\n phantom: PhantomData M>,\r\n }\r\n\r\n impl StaticModInt {\r\n /// Corresponds to `atcoder::static_modint::mod` in the original ACL.\r\n #[inline(always)]\r\n pub fn modulus() -> u32 {\r\n M::VALUE\r\n }\r\n\r\n /// Creates a new `StaticModInt`.\r\n #[inline]\r\n pub fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(M::VALUE))\r\n }\r\n\r\n /// Corresponds to `atcoder::static_modint::raw` in the original ACL.\r\n #[inline]\r\n pub fn raw(val: u32) -> Self {\r\n Self {\r\n val,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n /// Corresponds to `atcoder::static_modint::val` in the original ACL.\r\n #[inline]\r\n pub fn val(self) -> u32 {\r\n self.val\r\n }\r\n\r\n /// Corresponds to `atcoder::static_modint::pow` in the original ACL.\r\n #[inline]\r\n pub fn pow(self, n: u64) -> Self {\r\n ::pow(self, n)\r\n }\r\n\r\n /// Corresponds to `atcoder::static_modint::inv` in the original ACL.\r\n ///\r\n /// # Panics\r\n ///\r\n /// Panics if the multiplicative inverse does not exist.\r\n #[inline]\r\n pub fn inv(self) -> Self {\r\n if M::HINT_VALUE_IS_PRIME {\r\n if self.val() == 0 {\r\n panic!(\"attempt to divide by zero\");\r\n }\r\n debug_assert!(\r\n internal_math::is_prime(M::VALUE.try_into().unwrap()),\r\n \"{} is not a prime number\",\r\n M::VALUE,\r\n );\r\n self.pow((M::VALUE - 2).into())\r\n } else {\r\n Self::inv_for_non_prime_modulus(self)\r\n }\r\n }\r\n }\r\n\r\n impl ModIntBase for StaticModInt {\r\n #[inline(always)]\r\n fn modulus() -> u32 {\r\n Self::modulus()\r\n }\r\n\r\n #[inline]\r\n fn raw(val: u32) -> Self {\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn val(self) -> u32 {\r\n self.val()\r\n }\r\n\r\n #[inline]\r\n fn inv(self) -> Self {\r\n self.inv()\r\n }\r\n }\r\n\r\n pub trait Modulus: 'static + Copy + Eq {\r\n const VALUE: u32;\r\n const HINT_VALUE_IS_PRIME: bool;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>>;\r\n }\r\n\r\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\n pub enum Mod1000000007 {}\r\n\r\n impl Modulus for Mod1000000007 {\r\n const VALUE: u32 = 1_000_000_007;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n }\r\n\r\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\n pub enum Mod998244353 {}\r\n\r\n impl Modulus for Mod998244353 {\r\n const VALUE: u32 = 998_244_353;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n }\r\n\r\n pub struct ButterflyCache {\r\n pub(crate) sum_e: Vec>,\r\n pub(crate) sum_ie: Vec>,\r\n }\r\n\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n #[repr(transparent)]\r\n pub struct DynamicModInt {\r\n val: u32,\r\n phantom: PhantomData I>,\r\n }\r\n\r\n impl DynamicModInt {\r\n #[inline]\r\n pub fn modulus() -> u32 {\r\n I::companion_barrett().with(|bt| bt.borrow().umod())\r\n }\r\n\r\n #[inline]\r\n pub fn set_modulus(modulus: u32) {\r\n if modulus == 0 {\r\n panic!(\"the modulus must not be 0\");\r\n }\r\n I::companion_barrett().with(|bt| *bt.borrow_mut() = Barrett::new(modulus))\r\n }\r\n\r\n #[inline]\r\n pub fn new(val: T) -> Self {\r\n ::new(val)\r\n }\r\n\r\n #[inline]\r\n pub fn raw(val: u32) -> Self {\r\n Self {\r\n val,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n #[inline]\r\n pub fn val(self) -> u32 {\r\n self.val\r\n }\r\n\r\n #[inline]\r\n pub fn pow(self, n: u64) -> Self {\r\n ::pow(self, n)\r\n }\r\n\r\n #[inline]\r\n pub fn inv(self) -> Self {\r\n Self::inv_for_non_prime_modulus(self)\r\n }\r\n }\r\n\r\n impl ModIntBase for DynamicModInt {\r\n #[inline]\r\n fn modulus() -> u32 {\r\n Self::modulus()\r\n }\r\n\r\n #[inline]\r\n fn raw(val: u32) -> Self {\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn val(self) -> u32 {\r\n self.val()\r\n }\r\n\r\n #[inline]\r\n fn inv(self) -> Self {\r\n self.inv()\r\n }\r\n }\r\n\r\n pub trait Id: 'static + Copy + Eq {\r\n // TODO: Make `internal_math::Barret` `Copy`.\r\n fn companion_barrett() -> &'static LocalKey>;\r\n }\r\n\r\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\n pub enum DefaultId {}\r\n\r\n impl Id for DefaultId {\r\n fn companion_barrett() -> &'static LocalKey> {\r\n thread_local! {\r\n static BARRETT: RefCell = RefCell::default();\r\n }\r\n &BARRETT\r\n }\r\n }\r\n\r\n pub struct Barrett(internal_math::Barrett);\r\n\r\n impl Barrett {\r\n #[inline]\r\n pub fn new(m: u32) -> Self {\r\n Self(internal_math::Barrett::new(m))\r\n }\r\n\r\n #[inline]\r\n fn umod(&self) -> u32 {\r\n self.0.umod()\r\n }\r\n\r\n #[inline]\r\n fn mul(&self, a: u32, b: u32) -> u32 {\r\n self.0.mul(a, b)\r\n }\r\n }\r\n\r\n impl Default for Barrett {\r\n #[inline]\r\n fn default() -> Self {\r\n Self(internal_math::Barrett::new(998_244_353))\r\n }\r\n }\r\n\r\n pub trait ModIntBase:\r\n Default\r\n + FromStr\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + Copy\r\n + Eq\r\n + Hash\r\n + fmt::Display\r\n + fmt::Debug\r\n + Neg\r\n + Add\r\n + Sub\r\n + Mul\r\n + Div\r\n + AddAssign\r\n + SubAssign\r\n + MulAssign\r\n + DivAssign\r\n {\r\n fn modulus() -> u32;\r\n fn raw(val: u32) -> Self;\r\n fn val(self) -> u32;\r\n fn inv(self) -> Self;\r\n\r\n #[inline]\r\n fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(Self::modulus()))\r\n }\r\n\r\n #[inline]\r\n fn pow(self, mut n: u64) -> Self {\r\n let mut x = self;\r\n let mut r = Self::raw(1);\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n r *= x;\r\n }\r\n x *= x;\r\n n >>= 1;\r\n }\r\n r\r\n }\r\n }\r\n\r\n pub trait RemEuclidU32 {\r\n fn rem_euclid_u32(self, modulus: u32) -> u32;\r\n }\r\n\r\n macro_rules! impl_rem_euclid_u32_for_small_signed {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self as i64).rem_euclid(i64::from(modulus)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\r\n\r\n impl RemEuclidU32 for i128 {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self.rem_euclid(i128::from(modulus)) as _\r\n }\r\n }\r\n\r\n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self as u32 % modulus\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self % (modulus as $ty)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\r\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\r\n\r\n #[cfg(target_pointer_width = \"32\")]\r\n impl_rem_euclid_u32_for_small_unsigned!(usize);\r\n\r\n #[cfg(target_pointer_width = \"64\")]\r\n impl_rem_euclid_u32_for_large_unsigned!(usize);\r\n\r\n trait InternalImplementations: ModIntBase {\r\n #[inline]\r\n fn inv_for_non_prime_modulus(this: Self) -> Self {\r\n let (gcd, x) = internal_math::inv_gcd(this.val().into(), Self::modulus().into());\r\n if gcd != 1 {\r\n panic!(\"the multiplicative inverse does not exist\");\r\n }\r\n Self::new(x)\r\n }\r\n\r\n #[inline]\r\n fn default_impl() -> Self {\r\n Self::raw(0)\r\n }\r\n\r\n #[inline]\r\n fn from_str_impl(s: &str) -> Result {\r\n Ok(s.parse::()\r\n .map(Self::new)\r\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\r\n }\r\n\r\n #[inline]\r\n fn hash_impl(this: &Self, state: &mut impl Hasher) {\r\n this.val().hash(state)\r\n }\r\n\r\n #[inline]\r\n fn display_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Display::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn debug_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Debug::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn neg_impl(this: Self) -> Self {\r\n Self::sub_impl(Self::raw(0), this)\r\n }\r\n\r\n #[inline]\r\n fn add_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val() + rhs.val();\r\n if val >= modulus {\r\n val -= modulus;\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn sub_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val().wrapping_sub(rhs.val());\r\n if val >= modulus {\r\n val = val.wrapping_add(modulus)\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self;\r\n\r\n #[inline]\r\n fn div_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::mul_impl(lhs, rhs.inv())\r\n }\r\n }\r\n\r\n impl InternalImplementations for StaticModInt {\r\n #[inline]\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::raw((u64::from(lhs.val()) * u64::from(rhs.val()) % u64::from(M::VALUE)) as u32)\r\n }\r\n }\r\n\r\n impl InternalImplementations for DynamicModInt {\r\n #[inline]\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\r\n I::companion_barrett().with(|bt| Self::raw(bt.borrow().mul(lhs.val, rhs.val)))\r\n }\r\n }\r\n\r\n macro_rules! impl_basic_traits {\r\n () => {};\r\n (impl <$generic_param:ident : $generic_param_bound:tt> _ for $self:ty; $($rest:tt)*) => {\r\n impl <$generic_param: $generic_param_bound> Default for $self {\r\n #[inline]\r\n fn default() -> Self {\r\n Self::default_impl()\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> FromStr for $self {\r\n type Err = Infallible;\r\n\r\n #[inline]\r\n fn from_str(s: &str) -> Result {\r\n Self::from_str_impl(s)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound, V: RemEuclidU32> From for $self {\r\n #[inline]\r\n fn from(from: V) -> Self {\r\n Self::new(from)\r\n }\r\n }\r\n\r\n #[allow(clippy::derive_hash_xor_eq)]\r\n impl<$generic_param: $generic_param_bound> Hash for $self {\r\n #[inline]\r\n fn hash(&self, state: &mut H) {\r\n Self::hash_impl(self, state)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Display for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::display_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Debug for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::debug_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n Self::neg_impl(self)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for &'_ $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n <$self>::neg_impl(*self)\r\n }\r\n }\r\n\r\n impl_basic_traits!($($rest)*);\r\n };\r\n}\r\n\r\n impl_basic_traits! {\r\n impl _ for StaticModInt ;\r\n impl _ for DynamicModInt;\r\n }\r\n\r\n macro_rules! impl_bin_ops {\r\n () => {};\r\n (for<$generic_param:ident : $generic_param_bound:tt> <$lhs_ty:ty> ~ <$rhs_ty:ty> -> $output:ty { { $lhs_body:expr } ~ { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$generic_param: $generic_param_bound> Add<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn add(self, rhs: $rhs_ty) -> $output {\r\n <$output>::add_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> Sub<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn sub(self, rhs: $rhs_ty) -> $output {\r\n <$output>::sub_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> Mul<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn mul(self, rhs: $rhs_ty) -> $output {\r\n <$output>::mul_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> Div<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn div(self, rhs: $rhs_ty) -> $output {\r\n <$output>::div_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl_bin_ops!($($rest)*);\r\n };\r\n}\r\n\r\n macro_rules! impl_assign_ops {\r\n () => {};\r\n (for<$generic_param:ident : $generic_param_bound:tt> <$lhs_ty:ty> ~= <$rhs_ty:ty> { _ ~= { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$generic_param: $generic_param_bound> AddAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn add_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self + apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> SubAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn sub_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self - apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> MulAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn mul_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self * apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> DivAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn div_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self / apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl_assign_ops!($($rest)*);\r\n };\r\n}\r\n\r\n #[inline]\r\n fn apply O, X, O>(f: F, x: X) -> O {\r\n f(x)\r\n }\r\n\r\n impl_bin_ops! {\r\n for > ~ > -> StaticModInt { { |x| x } ~ { |x| x } }\r\n for > ~ <&'_ StaticModInt > -> StaticModInt { { |x| x } ~ { |&x| x } }\r\n for <&'_ StaticModInt > ~ > -> StaticModInt { { |&x| x } ~ { |x| x } }\r\n for <&'_ StaticModInt > ~ <&'_ StaticModInt > -> StaticModInt { { |&x| x } ~ { |&x| x } }\r\n for > ~ > -> DynamicModInt { { |x| x } ~ { |x| x } }\r\n for > ~ <&'_ DynamicModInt> -> DynamicModInt { { |x| x } ~ { |&x| x } }\r\n for <&'_ DynamicModInt> ~ > -> DynamicModInt { { |&x| x } ~ { |x| x } }\r\n for <&'_ DynamicModInt> ~ <&'_ DynamicModInt> -> DynamicModInt { { |&x| x } ~ { |&x| x } }\r\n }\r\n\r\n impl_assign_ops! {\r\n for > ~= > { _ ~= { |x| x } }\r\n for > ~= <&'_ StaticModInt > { _ ~= { |&x| x } }\r\n for > ~= > { _ ~= { |x| x } }\r\n for > ~= <&'_ DynamicModInt> { _ ~= { |&x| x } }\r\n }\r\n\r\n macro_rules! impl_folding {\r\n () => {};\r\n (impl<$generic_param:ident : $generic_param_bound:tt> $trait:ident<_> for $self:ty { fn $method:ident(_) -> _ { _($unit:expr, $op:expr) } } $($rest:tt)*) => {\r\n impl<$generic_param: $generic_param_bound> $trait for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl<'a, $generic_param: $generic_param_bound> $trait<&'a Self> for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl_folding!($($rest)*);\r\n };\r\n}\r\n\r\n impl_folding! {\r\n impl Sum<_> for StaticModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\r\n impl Product<_> for StaticModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\r\n impl Sum<_> for DynamicModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\r\n impl Product<_> for DynamicModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\r\n }\r\n\r\n #[cfg(test)]\r\n mod tests {\r\n use crate::modint::ModInt1000000007;\r\n\r\n #[test]\r\n fn static_modint_new() {\r\n assert_eq!(0, ModInt1000000007::new(0u32).val);\r\n assert_eq!(1, ModInt1000000007::new(1u32).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008u32).val);\r\n\r\n assert_eq!(0, ModInt1000000007::new(0u64).val);\r\n assert_eq!(1, ModInt1000000007::new(1u64).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008u64).val);\r\n\r\n assert_eq!(0, ModInt1000000007::new(0usize).val);\r\n assert_eq!(1, ModInt1000000007::new(1usize).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008usize).val);\r\n\r\n assert_eq!(0, ModInt1000000007::new(0i64).val);\r\n assert_eq!(1, ModInt1000000007::new(1i64).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008i64).val);\r\n assert_eq!(1_000_000_006, ModInt1000000007::new(-1i64).val);\r\n }\r\n\r\n #[test]\r\n fn static_modint_add() {\r\n fn add(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) + ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(2, add(1, 1));\r\n assert_eq!(1, add(1_000_000_006, 2));\r\n }\r\n\r\n #[test]\r\n fn static_modint_sub() {\r\n fn sub(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) - ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(1, sub(2, 1));\r\n assert_eq!(1_000_000_006, sub(0, 1));\r\n }\r\n\r\n #[test]\r\n fn static_modint_mul() {\r\n fn mul(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) * ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(1, mul(1, 1));\r\n assert_eq!(4, mul(2, 2));\r\n assert_eq!(999_999_937, mul(100_000, 100_000));\r\n }\r\n\r\n #[test]\r\n fn static_modint_prime_div() {\r\n fn div(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) / ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(0, div(0, 1));\r\n assert_eq!(1, div(1, 1));\r\n assert_eq!(1, div(2, 2));\r\n assert_eq!(23_809_524, div(1, 42));\r\n }\r\n\r\n #[test]\r\n fn static_modint_sum() {\r\n fn sum(values: &[i64]) -> ModInt1000000007 {\r\n values.iter().copied().map(ModInt1000000007::new).sum()\r\n }\r\n\r\n assert_eq!(ModInt1000000007::new(-3), sum(&[-1, 2, -3, 4, -5]));\r\n }\r\n\r\n #[test]\r\n fn static_modint_product() {\r\n fn product(values: &[i64]) -> ModInt1000000007 {\r\n values.iter().copied().map(ModInt1000000007::new).product()\r\n }\r\n\r\n assert_eq!(ModInt1000000007::new(-120), product(&[-1, 2, -3, 4, -5]));\r\n }\r\n }\r\n}\r\nuse modint::*;\r\n\r\nuse ModInt1000000007 as mint;\r\nfn main() {\r\n let T = get!(usize);\r\n for testcase in 0..T {\r\n mydbg!(testcase);\r\n\r\n let (N, K) = get!(usize, usize);\r\n let mut ans = mint::new(N);\r\n ans = ans.pow(K as u64);\r\n echo!(ans);\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "dc6c13842b0706de7c2408845fa00c74", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// codesnip-guard: main\nfn main() {\n #![allow(unused_imports, unused_macros)]\n prepare_io!(_in_buf, scanner, _out);\n macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n scan!(scanner, t);\n for _ in 0..t {\n scan!(scanner, n, k);\n println!(\"{}\", M::from(n).pow(k));\n }\n}\npub type M = mint_basic::MInt1000000007;\n#[macro_export]\nmacro_rules! prepare_io {\n ($ in_buf : ident , $ scanner : ident , $ out : ident) => {\n use std::io::{stdout, BufWriter, Write as _};\n let $in_buf = read_stdin_all_unchecked();\n let mut $scanner = Scanner::new(&$in_buf);\n let $out = stdout();\n let mut $out = BufWriter::new($out.lock());\n };\n}\n// codesnip-guard: _echo\npub fn echo(\n mut writer: impl std::io::Write,\n iter: impl IntoIterator,\n sep: impl std::fmt::Display,\n) -> std::io::Result<()> {\n let mut iter = iter.into_iter();\n if let Some(item) = iter.next() {\n write!(writer, \"{}\", item)?;\n }\n for item in iter {\n write!(writer, \"{}{}\", sep, item)?;\n }\n writeln!(writer)\n}\n// codesnip-guard: scanner\npub fn read_stdin_all_unchecked() -> String {\n use std::io::Read as _;\n let mut buf = Vec::new();\n std::io::stdin().read_to_end(&mut buf).expect(\"io error\");\n unsafe { String::from_utf8_unchecked(buf) }\n}\npub fn read_stdin_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).expect(\"io error\");\n s\n}\npub trait IterScan: Sized {\n type Output;\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option;\n}\npub trait MarkedIterScan: Sized {\n type Output;\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option;\n}\n#[derive(Clone, Debug)]\npub struct Scanner<'a> {\n iter: std::str::SplitAsciiWhitespace<'a>,\n}\nmod scanner_impls {\n use super::*;\n impl<'a> Scanner<'a> {\n #[inline]\n pub fn new(s: &'a str) -> Self {\n let iter = s.split_ascii_whitespace();\n Self { iter }\n }\n #[inline]\n pub fn scan(&mut self) -> ::Output {\n ::scan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn mscan(&mut self, marker: T) -> ::Output {\n marker.mscan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn scan_vec(&mut self, size: usize) -> Vec<::Output> {\n (0..size)\n .map(|_| ::scan(&mut self.iter).expect(\"scan error\"))\n .collect()\n }\n #[inline]\n pub fn iter<'b, T: IterScan>(&'b mut self) -> ScannerIter<'a, 'b, T> {\n ScannerIter {\n inner: self,\n _marker: std::marker::PhantomData,\n }\n }\n }\n macro_rules ! iter_scan_impls { ($ ($ t : ty) *) => { $ (impl IterScan for $ t { type Output = Self ; # [inline] fn scan <'a , I : Iterator < Item = &'a str >> (iter : & mut I) -> Option < Self > { iter . next () ?. parse ::<$ t > () . ok () } }) * } ; }\n iter_scan_impls ! (char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);\n macro_rules ! iter_scan_tuple_impl { ($ ($ T : ident) *) => { impl <$ ($ T : IterScan) ,*> IterScan for ($ ($ T ,) *) { type Output = ($ (<$ T as IterScan >:: Output ,) *) ; # [inline] fn scan <'a , It : Iterator < Item = &'a str >> (_iter : & mut It) -> Option < Self :: Output > { Some (($ (<$ T as IterScan >:: scan (_iter) ?,) *)) } } } ; }\n iter_scan_tuple_impl!();\n iter_scan_tuple_impl!(A);\n iter_scan_tuple_impl ! (A B);\n iter_scan_tuple_impl ! (A B C);\n iter_scan_tuple_impl ! (A B C D);\n iter_scan_tuple_impl ! (A B C D E);\n iter_scan_tuple_impl ! (A B C D E F);\n iter_scan_tuple_impl ! (A B C D E F G);\n iter_scan_tuple_impl ! (A B C D E F G H);\n iter_scan_tuple_impl ! (A B C D E F G H I);\n iter_scan_tuple_impl ! (A B C D E F G H I J);\n iter_scan_tuple_impl ! (A B C D E F G H I J K);\n pub struct ScannerIter<'a, 'b, T> {\n inner: &'b mut Scanner<'a>,\n _marker: std::marker::PhantomData T>,\n }\n impl<'a, 'b, T: IterScan> Iterator for ScannerIter<'a, 'b, T> {\n type Item = ::Output;\n #[inline]\n fn next(&mut self) -> Option {\n ::scan(&mut self.inner.iter)\n }\n }\n}\n#[derive(Debug, Copy, Clone)]\npub struct Usize1;\n#[derive(Debug, Copy, Clone)]\npub struct CharWithBase(pub char);\n#[derive(Debug, Copy, Clone)]\npub struct Chars;\n#[derive(Debug, Copy, Clone)]\npub struct CharsWithBase(pub char);\n#[derive(Debug, Copy, Clone)]\npub struct Collect::Output>> {\n size: usize,\n _marker: std::marker::PhantomData (T, B)>,\n}\nmod marker_impls {\n use super::*;\n use std::{iter::FromIterator, marker::PhantomData};\n impl IterScan for Usize1 {\n type Output = usize;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n ::scan(iter)?.checked_sub(1)\n }\n }\n impl MarkedIterScan for CharWithBase {\n type Output = usize;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some((::scan(iter)? as u8 - self.0 as u8) as usize)\n }\n }\n impl IterScan for Chars {\n type Output = Vec;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(iter.next()?.chars().collect())\n }\n }\n impl MarkedIterScan for CharsWithBase {\n type Output = Vec;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n iter.next()?\n .chars()\n .map(|c| (c as u8 - self.0 as u8) as usize)\n .collect(),\n )\n }\n }\n impl::Output>> Collect {\n pub fn new(size: usize) -> Self {\n Self {\n size,\n _marker: PhantomData,\n }\n }\n }\n impl::Output>> MarkedIterScan for Collect {\n type Output = B;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n (0..self.size)\n .map(|_| ::scan(iter).expect(\"scan error\"))\n .collect::(),\n )\n }\n }\n}\n#[macro_export]\nmacro_rules ! scan_value { ($ scanner : expr , ($ ($ t : tt) ,*)) => { ($ ($ crate :: scan_value ! ($ scanner , $ t)) ,*) } ; ($ scanner : expr , [$ t : tt ; $ len : expr]) => { (0 ..$ len) . map (| _ | $ crate :: scan_value ! ($ scanner , $ t)) . collect ::< Vec < _ >> () } ; ($ scanner : expr , [$ t : ty ; $ len : expr]) => { $ scanner . scan_vec ::<$ t > ($ len) } ; ($ scanner : expr , [$ t : ty]) => { $ scanner . iter ::<$ t > () } ; ($ scanner : expr , { $ e : expr }) => { $ scanner . mscan ($ e) } ; ($ scanner : expr , $ t : ty) => { $ scanner . scan ::<$ t > () } ; }\n#[macro_export]\nmacro_rules ! scan { ($ scanner : expr) => { } ; ($ scanner : expr ,) => { } ; ($ scanner : expr , mut $ var : tt : $ t : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , $ var : tt : $ t : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , mut $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , mut $ var : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , $ var : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , mut $ var : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; }\n// codesnip-guard: MInt\npub mod mint_basic {\n use super::*;\n #[macro_export]\n macro_rules ! define_basic_mintbase { ($ name : ident , $ m : expr , $ basety : ty , $ signedty : ty , $ upperty : ty , [$ ($ unsigned : ty) ,*] , [$ ($ signed : ty) ,*]) => { pub struct $ name ; impl MIntBase for $ name { type Inner = $ basety ; # [inline] fn get_mod () -> Self :: Inner { $ m } # [inline] fn mod_zero () -> Self :: Inner { 0 } # [inline] fn mod_one () -> Self :: Inner { 1 } # [inline] fn mod_add (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { let z = x + y ; let m = Self :: get_mod () ; if z >= m { z - m } else { z } } # [inline] fn mod_sub (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { if x < y { x + Self :: get_mod () - y } else { x - y } } # [inline] fn mod_mul (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { (x as $ upperty * y as $ upperty % Self :: get_mod () as $ upperty) as $ basety } # [inline] fn mod_div (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { Self :: mod_mul (x , Self :: mod_inv (y)) } # [inline] fn mod_neg (x : Self :: Inner) -> Self :: Inner { if x == 0 { 0 } else { Self :: get_mod () - x } } fn mod_inv (x : Self :: Inner) -> Self :: Inner { let p = Self :: get_mod () as $ signedty ; let (mut a , mut b) = (x as $ signedty , p) ; let (mut u , mut x) = (1 , 0) ; while a != 0 { let k = b / a ; x -= k * u ; b -= k * a ; std :: mem :: swap (& mut x , & mut u) ; std :: mem :: swap (& mut b , & mut a) ; } (if x < 0 { x + p } else { x }) as _ } } $ (impl MIntConvert <$ unsigned > for $ name { # [inline] fn from (x : $ unsigned) -> Self :: Inner { (x % < Self as MIntBase >:: get_mod () as $ unsigned) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ unsigned { x as $ unsigned } # [inline] fn mod_into () -> $ unsigned { < Self as MIntBase >:: get_mod () as $ unsigned } }) * $ (impl MIntConvert <$ signed > for $ name { # [inline] fn from (x : $ signed) -> Self :: Inner { let x = x % < Self as MIntBase >:: get_mod () as $ signed ; if x < 0 { (x + < Self as MIntBase >:: get_mod () as $ signed) as $ basety } else { x as $ basety } } # [inline] fn into (x : Self :: Inner) -> $ signed { x as $ signed } # [inline] fn mod_into () -> $ signed { < Self as MIntBase >:: get_mod () as $ signed } }) * } ; }\n #[macro_export]\n macro_rules ! define_basic_mint32 { ($ ([$ name : ident , $ m : expr , $ mint_name : ident]) ,*) => { $ (crate :: define_basic_mintbase ! ($ name , $ m , u32 , i32 , u64 , [u32 , u64 , u128 , usize] , [i32 , i64 , i128 , isize]) ; pub type $ mint_name = MInt <$ name >;) * } ; }\n define_basic_mint32!(\n [Modulo998244353, 998_244_353, MInt998244353],\n [Modulo1000000007, 1_000_000_007, MInt1000000007],\n [Modulo1000000009, 1_000_000_009, MInt1000000009],\n [\n DynModuloU32,\n DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() }),\n DynMIntU32\n ]\n );\n thread_local ! (static DYN_MODULUS_U32 : std :: cell :: UnsafeCell < u32 > = std :: cell :: UnsafeCell :: new (1_000_000_007));\n impl DynModuloU32 {\n pub fn set_mod(m: u32) {\n DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() = m })\n }\n }\n thread_local ! (static DYN_MODULUS_U64 : std :: cell :: UnsafeCell < u64 > = std :: cell :: UnsafeCell :: new (1_000_000_007));\n define_basic_mintbase!(\n DynModuloU64,\n DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() }),\n u64,\n i64,\n u128,\n [u64, u128, usize],\n [i64, i128, isize]\n );\n impl DynModuloU64 {\n pub fn set_mod(m: u64) {\n DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() = m })\n }\n }\n pub type DynMIntU64 = MInt;\n pub struct Modulo2;\n impl MIntBase for Modulo2 {\n type Inner = u32;\n #[inline]\n fn get_mod() -> Self::Inner {\n 2\n }\n #[inline]\n fn mod_zero() -> Self::Inner {\n 0\n }\n #[inline]\n fn mod_one() -> Self::Inner {\n 1\n }\n #[inline]\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x | y\n }\n #[inline]\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n assert_ne!(y, 0);\n x\n }\n #[inline]\n fn mod_neg(x: Self::Inner) -> Self::Inner {\n x\n }\n #[inline]\n fn mod_inv(x: Self::Inner) -> Self::Inner {\n assert_ne!(x, 0);\n x\n }\n #[inline]\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n if y == 0 {\n 1\n } else {\n x\n }\n }\n }\n macro_rules ! impl_to_mint_base_for_modulo2 { ($ name : ident , $ basety : ty , [$ ($ t : ty) ,*]) => { $ (impl MIntConvert <$ t > for $ name { # [inline] fn from (x : $ t) -> Self :: Inner { (x & 1) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ t { x as $ t } # [inline] fn mod_into () -> $ t { 1 } }) * } ; }\n impl_to_mint_base_for_modulo2!(\n Modulo2,\n u32,\n [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]\n );\n pub type MInt2 = MInt;\n}\n// codesnip-guard: MIntBase\n#[repr(transparent)]\npub struct MInt\nwhere\n M: MIntBase,\n{\n x: M::Inner,\n _marker: std::marker::PhantomData M>,\n}\npub trait MIntBase {\n type Inner: Sized + Copy + Eq + std::fmt::Debug + std::hash::Hash;\n fn get_mod() -> Self::Inner;\n fn mod_zero() -> Self::Inner;\n fn mod_one() -> Self::Inner;\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_neg(x: Self::Inner) -> Self::Inner;\n fn mod_inv(x: Self::Inner) -> Self::Inner;\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n let (mut x, mut y, mut z) = (x, y, Self::mod_one());\n while y > 0 {\n if y & 1 == 1 {\n z = Self::mod_mul(z, x);\n }\n x = Self::mod_mul(x, x);\n y >>= 1;\n }\n z\n }\n}\npub trait MIntConvert::Inner>: MIntBase {\n fn from(x: T) -> ::Inner;\n fn into(x: ::Inner) -> T;\n fn mod_into() -> T;\n}\nmod mint_base {\n use super::*;\n use std::{\n fmt::{self, Debug, Display},\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n };\n impl MInt\n where\n M: MIntConvert,\n {\n #[inline]\n pub fn new(x: M::Inner) -> Self {\n Self::new_unchecked(>::from(x))\n }\n #[inline]\n pub fn inner(self) -> M::Inner {\n >::into(self.x)\n }\n }\n impl MInt\n where\n M: MIntBase,\n {\n #[inline]\n pub fn new_unchecked(x: M::Inner) -> Self {\n Self {\n x,\n _marker: PhantomData,\n }\n }\n #[inline]\n pub fn get_mod() -> M::Inner {\n M::get_mod()\n }\n #[inline]\n pub fn pow(self, y: usize) -> Self {\n Self::new_unchecked(M::mod_pow(self.x, y))\n }\n #[inline]\n pub fn inv(self) -> Self {\n Self::new_unchecked(M::mod_inv(self.x))\n }\n }\n impl Clone for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn clone(&self) -> Self {\n Self {\n x: Clone::clone(&self.x),\n _marker: PhantomData,\n }\n }\n }\n impl Copy for MInt where M: MIntBase {}\n impl Debug for MInt\n where\n M: MIntBase,\n {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Debug::fmt(&self.x, f)\n }\n }\n impl Default for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn default() -> Self {\n ::zero()\n }\n }\n impl PartialEq for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n PartialEq::eq(&self.x, &other.x)\n }\n }\n impl Eq for MInt where M: MIntBase {}\n impl Hash for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn hash(&self, state: &mut H) {\n Hash::hash(&self.x, state)\n }\n }\n macro_rules ! impl_mint_from { ($ ($ t : ty) ,*) => { $ (impl < M > From <$ t > for MInt < M > where M : MIntConvert <$ t >, { # [inline] fn from (x : $ t) -> Self { Self :: new_unchecked (< M as MIntConvert <$ t >>:: from (x)) } } impl < M > From < MInt < M >> for $ t where M : MIntConvert <$ t >, { # [inline] fn from (x : MInt < M >) -> $ t { < M as MIntConvert <$ t >>:: into (x . x) } }) * } ; }\n impl_mint_from!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n impl Zero for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn zero() -> Self {\n Self::new_unchecked(M::mod_zero())\n }\n }\n impl One for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn one() -> Self {\n Self::new_unchecked(M::mod_one())\n }\n }\n impl Add for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_add(self.x, rhs.x))\n }\n }\n impl Sub for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_sub(self.x, rhs.x))\n }\n }\n impl Mul for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_mul(self.x, rhs.x))\n }\n }\n impl Div for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_div(self.x, rhs.x))\n }\n }\n impl Neg for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn neg(self) -> Self::Output {\n Self::new_unchecked(M::mod_neg(self.x))\n }\n }\n impl Sum for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl Product for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl<'a, M: 'a> Sum<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl<'a, M: 'a> Product<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl Display for MInt\n where\n M: MIntConvert,\n M::Inner: Display,\n {\n fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {\n write!(f, \"{}\", self.inner())\n }\n }\n impl FromStr for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Err = ::Err;\n #[inline]\n fn from_str(s: &str) -> Result {\n s.parse::().map(Self::new)\n }\n }\n impl IterScan for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Output = Self;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n iter.next()?.parse::>().ok()\n }\n }\n macro_rules! impl_mint_ref_binop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp<$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: $t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, other)\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(self, *other)\n }\n }\n impl $imp<&$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, *other)\n }\n }\n };\n }\n impl_mint_ref_binop!(Add, add, MInt);\n impl_mint_ref_binop!(Sub, sub, MInt);\n impl_mint_ref_binop!(Mul, mul, MInt);\n impl_mint_ref_binop!(Div, div, MInt);\n macro_rules! impl_mint_ref_unop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp>::Output;\n #[inline]\n fn $method(self) -> <$t as $imp>::Output {\n $imp::$method(*self)\n }\n }\n };\n }\n impl_mint_ref_unop!(Neg, neg, MInt);\n macro_rules! impl_mint_ref_op_assign {\n ($ imp : ident , $ method : ident , $ t : ty , $ fromimp : ident , $ frommethod : ident) => {\n impl $imp<$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, rhs: $t) {\n *self = $fromimp::$frommethod(*self, rhs);\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, other: &$t) {\n $imp::$method(self, *other);\n }\n }\n };\n }\n impl_mint_ref_op_assign!(AddAssign, add_assign, MInt, Add, add);\n impl_mint_ref_op_assign!(SubAssign, sub_assign, MInt, Sub, sub);\n impl_mint_ref_op_assign!(MulAssign, mul_assign, MInt, Mul, mul);\n impl_mint_ref_op_assign!(DivAssign, div_assign, MInt, Div, div);\n}\n// codesnip-guard: zero_one\npub trait Zero: Sized {\n fn zero() -> Self;\n #[inline]\n fn is_zero(&self) -> bool\n where\n Self: PartialEq,\n {\n self == &Self::zero()\n }\n #[inline]\n fn set_zero(&mut self) {\n *self = Self::zero();\n }\n}\npub trait One: Sized {\n fn one() -> Self;\n #[inline]\n fn is_one(&self) -> bool\n where\n Self: PartialEq,\n {\n self == &Self::one()\n }\n #[inline]\n fn set_one(&mut self) {\n *self = Self::one();\n }\n}\nmacro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { fn $ method () -> Self { $ e } }) *) * } ; }\nzero_one_impls ! ({ Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 0 } { Zero zero f32 f64 , 0. } { One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 1 } { One one f32 f64 , 1. });\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "1166873cb3dc9645561908da5da36be8", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\n\nconst MOD: i64 = 1e9 as i64 + 7;\n\nfn pow(mut a: i64, mut b: i64) -> i64 {\n let mut ans: i64 = 1;\n while b > 0 {\n if b & 1 == 1 {\n ans = (ans as i64 * a as i64) % MOD;\n }\n a = (a * a) % MOD;\n b >>= 1;\n }\n ans\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut sc = cf_scanner::Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n for _ in 0..sc.next() {\n writeln!(out, \"{}\", pow(sc.next(), sc.next())).unwrap();\n }\n}\n\n#[allow(dead_code)]\nmod cf_scanner {\n use std::io;\n use std::str::{FromStr, SplitAsciiWhitespace};\n\n pub struct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n }\n\n impl Scanner {\n pub fn new(reader: R) -> Scanner {\n Scanner {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "4ca3e5bf3803c69ac7b604edc53f1afe", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(dead_code)]\r\nfn solve(read: &mut snio::Reader>) {\r\n let n = read.usize();\r\n let k = read.i64();\r\n //let mut ans = Vec::new();\r\n //xans.push(base);\r\n set_mod_int(1e9 as i64 + 7);\r\n let mut ans = mod_int::ModInt::new(n as i64);\r\n if n == 0 {\r\n println!(\"1\");\r\n }else{\r\n ans = ans.pow(k);\r\n println!(\"{}\",ans.value());\r\n }\r\n}\r\n\r\n//use proconio::input;\r\nfn main() {\r\n let t = std::io::stdin();\r\n let mut read = snio::Reader::new(t.lock());\r\n let n = read.i64();\r\n for _ in 0..n {\r\n solve(&mut read);\r\n }\r\n // let mut rec = Vec::new();\r\n}\r\n\r\n#[allow(dead_code)]\r\npub mod snio {\r\n pub struct Reader {\r\n reader: R,\r\n buf: std::collections::VecDeque,\r\n }\r\n\r\n impl Reader {\r\n pub fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf: std::collections::VecDeque::new(),\r\n }\r\n }\r\n fn load(&mut self) {\r\n while self.buf.is_empty() {\r\n let mut s = String::new();\r\n let length = self.reader.read_line(&mut s).unwrap();\r\n if length == 0 {\r\n break;\r\n }\r\n self.buf.extend(s.split_whitespace().map(|s| s.to_owned()));\r\n }\r\n }\r\n pub fn string(&mut self) -> String {\r\n self.load();\r\n self.buf.pop_front().unwrap_or_else(|| panic!(\"input ended\"))\r\n }\r\n pub fn char(&mut self) -> char {\r\n let string = self.string();\r\n let mut chars = string.chars();\r\n let res = chars.next().unwrap();\r\n assert!(chars.next().is_none(), \"invalid input!\");\r\n res\r\n }\r\n pub fn chars(&mut self) -> Vec {\r\n self.read::().chars().collect()\r\n }\r\n pub fn read(&mut self) -> T\r\n where\r\n ::Err: ::std::fmt::Debug,\r\n {\r\n self.string().parse::().expect(\"Failed to parse the input.\")\r\n }\r\n }\r\n macro_rules! definition_of_reader_of_numbers {\r\n ($($ty:tt,)*) => {\r\n impl Reader {\r\n $(\r\n #[inline]\r\n pub fn $ty (&mut self) -> $ty {\r\n self.read::<$ty>()\r\n }\r\n )*\r\n }\r\n }\r\n }\r\n definition_of_reader_of_numbers! {\r\n u8,u16,u32,u64,usize,\r\n i8,i16,i32,i64,isize,\r\n }\r\n}\r\n\r\n\r\nuse crate::mod_int::{set_mod_int,ModInt};\r\n//from https://github.com/kenkoooo/competitive-programming-rs/blob/master/src/math/mod_int.rs\r\npub mod mod_int {\r\n use std::cell::RefCell;\r\n use std::ops::{Add,AddAssign,Div,DivAssign,Mul,MulAssign,Sub,SubAssign};\r\n\r\n type InternalNum = i64;\r\n thread_local!(\r\n static MOD: RefCell = RefCell::new(0);//0\u3068\u3044\u3046\u5024\u3067RefCell\u3092\u751f\u6210\r\n );\r\n\r\n pub fn set_mod_int(v:T)\r\n where\r\n InternalNum: From,\r\n {\r\n MOD.with(|x| x.replace(InternalNum::from(v)));\r\n }\r\n\r\n fn modulo() -> InternalNum {\r\n MOD.with(|x| *x.borrow())\r\n }\r\n\r\n pub struct ModInt(InternalNum);//tuple\u69cb\u9020\u4f53\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n Self(self.0)\r\n }\r\n }\r\n impl Copy for ModInt {}\r\n\r\n impl ModInt {\r\n pub fn new(v:T) -> Self\r\n where\r\n InternalNum: From,\r\n {\r\n let mut v = InternalNum::from(v);\r\n let m = modulo();\r\n if v >= m {\r\n v %= m;\r\n }\r\n Self(v)\r\n }\r\n\r\n pub fn internal_pow(&self, mut e: InternalNum) -> Self {\r\n let mut result = 1;\r\n let mut cur = self.0;\r\n let modulo = modulo();\r\n while e > 0 {\r\n if e & 1 == 1 {\r\n result *= cur;\r\n result %= modulo;\r\n }\r\n e >>= 1;\r\n cur = (cur * cur) % modulo;\r\n }\r\n Self(result)\r\n }\r\n\r\n pub fn pow(&self , e:T) -> Self\r\n where\r\n InternalNum: From,\r\n {\r\n self.internal_pow(InternalNum::from(e))\r\n }\r\n\r\n pub fn value(&self) -> InternalNum {\r\n self.0\r\n }\r\n }\r\n\r\n impl From for InternalNum {\r\n fn from(m:ModInt) -> Self {\r\n m.value()\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n fn add_assign(&mut self,rhs:T) {\r\n let mut rhs = InternalNum::from(rhs);\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n\r\n self.0 += rhs;\r\n if self.0 >= m {\r\n self.0 -= m;\r\n }\r\n }\r\n }\r\n\r\n impl Add for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n type Output = ModInt;\r\n fn add(self, rhs: T) -> Self::Output {\r\n let mut res = self;\r\n res += rhs;\r\n res\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n fn sub_assign(&mut self, rhs: T) {\r\n let mut rhs = InternalNum::from(rhs);\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n if rhs > 0 {\r\n self.0 += m - rhs;\r\n }\r\n if self.0 >= m {\r\n self.0 -= m;\r\n }\r\n }\r\n }\r\n\r\n impl Sub for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n type Output = Self;\r\n fn sub(self,rhs:T) -> Self::Output {\r\n let mut res = self;\r\n res -= rhs;\r\n res\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n fn mul_assign(&mut self, rhs: T) {\r\n let mut rhs = InternalNum::from(rhs);\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n self.0 *= rhs;\r\n self.0 %= m;\r\n }\r\n }\r\n\r\n impl Mul for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n type Output = Self;\r\n fn mul(self, rhs:T) -> Self::Output {\r\n let mut res = self;\r\n res *= rhs;\r\n res\r\n }\r\n }\r\n\r\n impl DivAssign for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n fn div_assign(&mut self, rhs:T){\r\n let mut rhs = InternalNum::from(rhs);\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n let inv = Self(rhs).internal_pow(m - 2);\r\n self.0 *= inv.value();\r\n self.0 %= m;\r\n }\r\n }\r\n\r\n impl Div for ModInt\r\n where\r\n InternalNum: From,\r\n {\r\n type Output = Self;\r\n fn div(self, rhs: T) -> Self::Output {\r\n let mut res = self;\r\n res /= rhs;\r\n res\r\n }\r\n }\r\n}\r\n\r\npub mod binomial_coefficient {\r\n use crate::mod_int::{set_mod_int,ModInt};\r\n pub struct BinomialCoefficient {\r\n fact:Vec,\r\n inversion:Vec\r\n }\r\n impl BinomialCoefficient {\r\n pub fn new(n:usize,_mod:i64) -> Self {\r\n set_mod_int(_mod);\r\n let a = ModInt::new(1);\r\n let mut _fact:Vec = vec![a;n + 1];\r\n let mut _inversion:Vec = vec![a;n + 1];\r\n for i in 1..=n{\r\n _fact[i] = _fact[i - 1] * i as i64;\r\n }\r\n _inversion[n] = _fact[n].internal_pow(_mod - 2);\r\n for i in (1..=n).rev(){\r\n _inversion[i - 1] = _inversion[i] * i as i64;\r\n }\r\n BinomialCoefficient {\r\n fact:_fact,\r\n inversion:_inversion\r\n }\r\n }\r\n pub fn combination(&mut self,n:i64,k:i64) -> ModInt{\r\n if k < 0 || k > n {\r\n return ModInt::new(0)\r\n }\r\n self.fact[n as usize] * self.inversion[k as usize] * self.inversion[n as usize - k as usize]\r\n\r\n }\r\n\r\n pub fn permutation(&mut self,n:i64,k:i64) -> ModInt{\r\n if k < 0 || k > n{\r\n return ModInt::new(0)\r\n }\r\n self.combination(n,k) * self.fact[k as usize]\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "69e6d6d1c239902eee88fa0c59c733fa", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{\r\n fmt::Write,\r\n io::{prelude::*, stdin},\r\n iter::{self, Peekable},\r\n};\r\n\r\nfn main() {\r\n let mut input = String::new();\r\n stdin().read_to_string(&mut input).unwrap();\r\n\r\n let mut it = input\r\n .split_whitespace()\r\n .map(|s| s.parse::().unwrap());\r\n\r\n let t = it.next().unwrap();\r\n\r\n let mut output = String::new();\r\n\r\n let p = 1_000_000_007;\r\n\r\n for _ in 0..t {\r\n let mut n = it.next().unwrap();\r\n let mut k = it.next().unwrap();\r\n\r\n let mut ans = 1;\r\n \r\n for _ in 0..k {\r\n ans = (ans * n) % p;\r\n }\r\n\r\n writeln!(&mut output, \"{}\", ans).unwrap();\r\n }\r\n\r\n print!(\"{}\", output);\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "bitmasks"], "code_uid": "c9419011e2c301dc6ca1a27f95523a90", "src_uid": "2e7a9f3a97938e4a7e036520d812b97a", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n\tlet a = scan.next::();\n let lower = a.chars().filter(|c| c.is_lowercase()).count();\n let upper = a.chars().filter(|c| c.is_uppercase()).count();\n\n writeln!(out, \"{}\", if upper > lower { a.to_uppercase() } else { a.to_lowercase() }).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "9290e735dc49e82a4fd4d40a7c6c7a5c", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut word = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n };\n\n let half = word.len() / 2;\n if word.chars().filter(|c| c.is_uppercase()).count() > half {\n word = word.to_uppercase();\n } else {\n word = word.to_lowercase();\n }\n\n println!(\"{}\", word);\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "87bbedd1c467b301c039b5fc5f6baadb", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer\n}\n\nfn main() -> io::Result<()> {\n let mut input = get_input().trim().to_string();\n\n let mut count = 0;\n for c in input.chars() {\n if c.is_ascii_uppercase() {\n count += 1;\n }\n }\n\n if count > input.len() / 2 {\n println!(\"{}\", input.to_uppercase());\n } else {\n println!(\"{}\", input.to_lowercase());\n }\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "feaa61ad10f7ca8eff19dd2b71c50fdc", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let s = gets();\n let lower = s.chars().filter(|c| c.is_lowercase()).count();\n let upper = s.chars().filter(|c| c.is_uppercase()).count();\n if lower >= upper {\n println!(\"{}\", s.to_lowercase());\n } else {\n println!(\"{}\", s.to_uppercase());\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "760fdd0078557118f49860b20ed9553a", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let (simple,word)=input();\n let mut upper=0;\n let mut lower=0;\n for i in word{\n if i.is_uppercase(){\n upper+=1;\n continue;\n }\n lower+=1;\n }\n if upper>lower{\n println!(\"{}\",simple.to_uppercase());\n }else{\n println!(\"{}\",simple.to_lowercase());\n } \n}\nfn read() -> String{\n let mut input=String::new();\n io::stdin().read_line(&mut input).expect(\"unable to read\");\n input.trim().to_string()\n}\n\nfn input() -> (String,Vec){\n let inp=read();\n let l:Vec=inp.chars().collect();\n (inp,l)\n}\n/* let n=read().parse::().expect(\"Failed to parse\");\n let inp=read();\n (n,inp.split_whitespace().map(|x| x.parse::().expect(\"Failed to parse\")).collect())\n let list: Vec<_>=inp.split_whitespace().collect();\n let qu: Vec<_>=read().chars().collect();\n (list[0].parse::().expect(\"Failed to parse\"),\n list[1].parse::().expect(\"Failed to parse\"),qu)\n*/\n\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "85b9d1f4681c7de58e16014ed3eeebe3", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/59/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let str = buf.trim();\n let mut count = 0i32;\n for c in str.chars() {\n if c.is_uppercase() {\n count += 1;\n } else if c.is_lowercase() {\n count -= 1;\n }\n }\n println!(\"{}\",\n if count > 0 {\n str.to_uppercase()\n } else {\n str.to_lowercase()\n }\n );\n}\n\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "ae158791ce8d3185d2c36e77bee14b59", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::prelude::*;\n\nfn main() {\n let stdin = io::stdin();\n let mut s=\"\".to_string();\n let mut iter = stdin.lock().lines();\n s=iter.next().unwrap().unwrap();\n \n let mut up=0;\n let mut down=0;\n for i in s.chars() {\n \tif i.is_uppercase() {\n \t\tup+=1;\n \t}\n \telse{\n \t\tdown+=1;\n \t}\n }\n if down>=up {\n \tprintln!(\"{}\",s.to_lowercase());\n }\n else{\n \tprintln!(\"{}\",s.to_uppercase());\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "cb196fd3a83e904a1d65fb679a81cbb2", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut buf = String::new();\n let _ = stdin().read_line(&mut buf);\n let (mut l, mut h) = (0, 0);\n for i in buf.trim_end().as_bytes() {\n if *i >= 65 && *i <= 91 {\n h += 1;\n } else {\n l += 1;\n }\n }\n if l < h {\n println!(\"{}\", buf.to_uppercase());\n } else {\n println!(\"{}\", buf.to_lowercase());\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "07fd9626f7d3c25110204c96fdefe46d", "src_uid": "b432dfa66bae2b542342f0b42c0a2598", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ($out:ident as $type:ty) => {\n let mut inner = String::new();\n io::stdin().read_line(&mut inner).expect(\"A String\");\n let $out = inner.trim().parse::<$type>().expect(\"Parseble\");\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_str {\n ($out:ident) => {\n let mut inner = String::new();\n io::stdin().read_line(&mut inner).expect(\"A String\");\n let $out = inner.trim();\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_vec {\n ($out:ident as $type:ty) => {\n let mut inner = String::new();\n io::stdin().read_line(&mut inner).unwrap();\n let $out = inner\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$type>().unwrap())\n .collect::>();\n };\n}\n\nfn main(){\n read_vec!(inp as i32);\n let mut vector = vec![inp[0], inp[1], inp[2]];\n let mut ans: i32 = 0;\n let d = inp[3];\n vector.sort();\n\n let a = vector[0];\n let b = vector[1];\n let c = vector[2];\n\n ans += if b-a >= d { 0 } else { d-(b-a) };\n ans += if c-b >= d { 0 } else { d-(c-b) };\n\n println!(\"{}\",ans);\n\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "42e4b9e2a9f1994420667a6488a8ff22", "src_uid": "47c07e46517dbc937e2e779ec0d74eb3", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{BufReader, BufWriter, stdin, stdout, Write};\nuse std::cmp::{min, max};\nuse std::collections::{VecDeque, HashMap, BTreeMap, HashSet, BTreeSet, BinaryHeap};\n\nfn main() {\n\tlet mut inp = my_input::default();\n\tlet out = &mut BufWriter::new(stdout());\n\tlet A:i64 = inp.scan::();\n\tlet B:i64 = inp.scan::();\n\tlet C:i64 = inp.scan::();\n\tlet D:i64 = inp.scan::();\n\tlet mut v = vec![A, B, C];\n\tv.sort();\n\twriteln!(out, \"{}\", max(0, D - (v[1] - v[0])) + max(0, D - (v[2] - v[1])));\n}\n\n#[derive(Default)]\nstruct my_input {\n\tbuffer: Vec\n}\n\nimpl my_input {\n\tfn scan(&mut self) -> T {\n\t\tloop {\n\t\t\tif let Some(token) = self.buffer.pop() {\n\t\t\t\treturn token.parse().ok().expect(\"Parsing Error\");\n\t\t\t}\n\t\t\tlet mut s = String::new();\n\t\t\tstdin().read_line(&mut s).expect(\"Reading Error\");\n\t\t\tself.buffer = s.split_whitespace().rev().map(String::from).collect();\n\t\t}\n\t}\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "454aba8b951a9fbff43d67e62463e9b1", "src_uid": "47c07e46517dbc937e2e779ec0d74eb3", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::{min, max};\nuse std::io::{self, Write};\nuse std::str;\n\nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: Vec::new(), buf_iter: \"\".split_ascii_whitespace() }\n }\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n fn next_line(&mut self) -> String {\n let mut line = String::new();\n self.reader.read_line(&mut line).expect(\"Failed to read line\");\n line\n }\n\n fn next_vec(&mut self) -> Vec {\n let mut res: Vec = Vec::new();\n loop {\n loop {\n match self.buf_iter.next() {\n Some(token) => res.push(token.parse().ok().expect(\"Failed parse\")),\n None => break,\n }\n }\n if res.len() > 0 {\n return res;\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut cin = Scanner::new(stdin.lock());\n let mut cout = io::BufWriter::new(stdout.lock());\n\n let mut u = vec![cin.next::(), cin.next::(), cin.next::()];\n let d = cin.next::();\n\n u.sort();\n\n writeln!(cout, \"{}\", max(0, d + (u[0] - u[1])) + max(0, d + (u[1] - u[2]))).ok();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "923b629b3e757c20e8ebc6eba7fc6f49", "src_uid": "47c07e46517dbc937e2e779ec0d74eb3", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(dead_code)]\n\nuse std::thread;\nuse std::io::{ self, Read };\nuse std::fmt;\nuse std::iter::Iterator;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::str::*;\nuse std::mem::*;\nuse std::cell::*;\n\nstruct Input {\n stdin: io::Stdin,\n buf: VecDeque\n}\n\nimpl Input {\n fn new() -> Input {\n Input { \n stdin: io::stdin(),\n buf: VecDeque::new()\n }\n }\n\n fn read(&mut self) -> T \n where ::Err: fmt::Debug {\n self.next().unwrap().parse::().unwrap()\n }\n\n fn read_2(&mut self) -> (T, U)\n where ::Err: fmt::Debug,\n ::Err: fmt::Debug {\n (self.read(), self.read())\n }\n\n fn read_3(&mut self) -> (T, U, V)\n where ::Err: fmt::Debug,\n ::Err: fmt::Debug,\n ::Err: fmt::Debug {\n (self.read(), self.read(), self.read())\n }\n\n fn read_bytes(&mut self) -> Vec {\n self.next().unwrap().into_bytes()\n }\n\n fn read_n(&mut self, n: usize) -> Vec\n where ::Err: fmt::Debug {\n let mut v = Vec::new();\n for _ in 0..n { v.push(self.read::()); }\n v\n }\n}\n\nimpl Iterator for Input {\n type Item = String;\n fn next(&mut self) -> Option {\n while self.buf.is_empty() {\n let mut s = String::new();\n let _res = self.stdin.read_line(&mut s);\n self.buf.extend(s.split_whitespace().map(|s| s.to_owned()));\n }\n self.buf.pop_front()\n }\n}\n\nfn run() {\n let mut ip = Input::new();\n let mut a: Vec = ip.read_n(3);\n let d: i64 = ip.read();\n a.sort();\n println!(\"{}\", max(0, d - (a[2] - a[1])) + max(0, d - (a[1] - a[0])));\n}\n\nfn main() {\n let _ = thread::Builder::new()\n .stack_size(50 * 1024 * 1024)\n .spawn(run).unwrap()\n .join();\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "eafa0b9ad31019a723b8a81837956bf3", "src_uid": "47c07e46517dbc937e2e779ec0d74eb3", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn count(n: u32) -> u32 {\n if n == 1 {\n return 1;\n }\n\n if n % 2 == 1 {\n 1 + count(n / 2)\n } else {\n count(n / 2)\n }\n}\n\nfn main() {\n let n = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n };\n\n println!(\"{}\", count(n));\n}", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "97dc1eb0ba05bb02f751d26a07a38f33", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> (i32) {\n let mut input = String::new();\n \n io::stdin().read_line(&mut input).unwrap();\n \n let n: i32 = input.trim().parse().unwrap();\n\n n\n}\n\nfn main(){\n \n let mut n = read_line();\n let mut bacterias = 0;\n\n while n > 0 {\n bacterias += n % 2;\n n = n /2;\n }\n\n println!(\"{}\", bacterias);\n}\n", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "d3b11983a0fb71a6ba66d0b9b3d6d35e", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn solve(x:i32) -> i32 {\n if x==0 {\n return 0;\n } else if (x%2) == 0 {\n return solve(x/2);\n } else if (x%2) == 1 {\n return 1+solve(x/2);\n }\n return -1;\n}\n\nfn main() {\n let n = readln!(i32);\n println!(\"{}\",solve(n));\n}\n", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "f4b8dc535cbf0e64cee963dbb26b772a", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (x, ) = R!(usize);\n let mut ans = 0;\n for i in 0.. {\n if (x >> i) == 0 {\n break;\n }\n ans += (x >> i) % 2;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "afb428a837084ade8767fef8eb91e2c9", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let mut n = input.i();\n let mut sol = 0;\n while n > 0 {\n sol += 1;\n n -= n & -n;\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "782d8dc7c01fcba91ac5e90cb1948580", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut s:String=String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut a:i64=s.trim().parse::().unwrap();\n let mut sum:i64=0;\n while a!=0{\n sum+=a%2;\n a/=2;\n }\n println!(\"{}\",sum);\n}", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "dd3d736e165d307037bb1b4168c87a8c", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut n: usize = scan.next();\n let mut x: usize = 0;\n while n>0 {\n if n&1 == 1 {\n x += 1;\n }\n n >>= 1;\n }\n println!(\"{}\", x);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "8aa347b74e58d0bd11c40f105cad4f7b", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/579/A\nuse std::io;\n\nfn main() {\n let mut n = String::new();\n\n io::stdin()\n .read_line(&mut n)\n .unwrap();\n\n let n: i64 = n.trim().parse().unwrap();\n\n let mut ans = 0;\n\n for bit in 0..64 {\n if (n & (1< 0 {\n ans += 1;\n }\n }\n\n println!(\"{}\", ans);\n}\n\n", "lang_cluster": "Rust", "tags": ["bitmasks"], "code_uid": "dc667a94a4de835a66d0a0cec0deec05", "src_uid": "03e4482d53a059134676f431be4c16d2", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn main() {\n let (result, divider) = readln!(i32, i32);\n\n let mut min = std::i32::MAX;\n for right in 1..divider {\n if result % right == 0 {\n let x = right + divider * result / right;\n if x < min {\n min = x;\n }\n }\n }\n\n println!(\"{}\", min);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "c16af15f3bd8cc5334dcae231b72e2a5", "src_uid": "ed0ebc1e484fcaea875355b5b7944c57", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let mut buffer_iter = buffer.split_whitespace().map(|n| n.parse::().unwrap());\n let n = buffer_iter.next().unwrap();\n let k = buffer_iter.next().unwrap();\n\n let md = (1..k).rev().find(|x| n % x == 0).unwrap();\n println!(\"{}\", (n / md) * k + md);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "682b9fa393fab9d8b344973ba73422ca", "src_uid": "ed0ebc1e484fcaea875355b5b7944c57", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n a: chars,\n b: chars,\n }\n let pc = |a: &[char]| {\n 10 * (a[0] as u8 as i32) + a[1] as u8 as i32 - 48 * 11\n };\n let p = |a: Vec| {\n 60 * pc(&a[0..2]) + pc(&a[3..5])\n };\n let mid = (p(a) + p(b)) / 2;\n puts!(\"{:02}:{:02}\\n\", mid / 60, mid % 60);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ba6fc26b2d613fa448c703ff47ac7132", "src_uid": "f7a32a8325ce97c4c50ce3a5c282ec50", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn parse(s: &str) -> u32 {\n s.parse().unwrap()\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n let start_raw = lines.next().unwrap().unwrap();\n let end_raw = lines.next().unwrap().unwrap();\n let start: Vec<_> = start_raw.split(':').map(parse).collect();\n let end: Vec<_> = end_raw.split(':').map(parse).collect();\n\n let mut duration = 0;\n duration = duration + end[1] - start[1];\n duration += 60 * (end[0] - start[0]);\n\n let half = duration / 2;\n let mut half_min = start[1] + half;\n let half_hour = start[0] + (half_min / 60);\n half_min %= 60;\n\n println!(\"{:02}:{:02}\", half_hour, half_min);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e647a4e74c96154a11b0a73d34aefc34", "src_uid": "f7a32a8325ce97c4c50ce3a5c282ec50", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::prelude::BufRead;\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufReader, BufWriter, Write};\n#[allow(unused_imports)]\nuse std::mem::swap;\n#[allow(unused_imports)]\nuse std::str::FromStr;\n\nfn main() {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n let start;\n let end;\n {\n let line = buf.trim().split(\":\").collect::>();\n start = line[0].parse::().unwrap() * 60 + line[1].parse::().unwrap();\n }\n buf.clear();\n stdin().read_line(&mut buf).unwrap();\n {\n let line = buf.trim().split(\":\").collect::>();\n end = line[0].parse::().unwrap() * 60 + line[1].parse::().unwrap(); \n }\n let mid = (start + end) / 2;\n let (h, m) = (mid / 60, mid % 60);\n if h < 10 {\n print!(\"0{}:\", h);\n } else {\n print!(\"{}:\", h);\n }\n if m < 10 {\n println!(\"0{}\", m);\n } else {\n println!(\"{}\", m);\n }\n}\n\n#[allow(dead_code)]\nfn read() -> T\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n return buf.trim().parse().unwrap();\n}\n\n#[allow(dead_code)]\nfn read_vector() -> Vec\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n let mut buf = String::with_capacity(100);\n stdin().read_line(&mut buf).unwrap();\n return buf.split_whitespace().map(|s| s.parse().unwrap()).collect();\n}\n\n#[allow(dead_code)]\nfn read_matrix() -> Vec>\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n use std::io::prelude::*;\n let stdin = stdin();\n let mut reader = BufReader::with_capacity(100 * 1024, stdin);\n let mut line = String::with_capacity(100);\n let mut matrix: Vec> = Vec::new();\n\n while reader.read_line(&mut line).unwrap() > 0 {\n matrix.push(\n line.trim()\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect(),\n );\n line.clear();\n }\n\n return matrix;\n}\n\n#[allow(dead_code)]\nfn read_chars() -> Vec {\n let stdin = stdin();\n let mut buf = String::new();\n let _bytes = stdin.read_line(&mut buf).unwrap();\n return buf.trim().chars().collect();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5142e1721f0942e545ee58c993895e54", "src_uid": "f7a32a8325ce97c4c50ce3a5c282ec50", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n\n#[allow(unused_imports)]\nuse input::*;\n\nfn main() {\n let start_time_str = input_line_str();\n let end_time_str = input_line_str();\n let start_time = start_time_str\n .split(':')\n .map(|a| a.parse::().unwrap())\n .collect::>();\n let end_time = end_time_str\n .split(':')\n .map(|a| a.parse::().unwrap())\n .collect::>();\n let ans = (end_time[0] * 60 + end_time[1] + start_time[0] * 60 + start_time[1]) >> 1;\n dbg!(start_time, end_time, ans);\n println!(\"{:02}:{:02}\", ans / 60, ans % 60);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d9733b51aedca8a4b349e4fc4c83456a", "src_uid": "f7a32a8325ce97c4c50ce3a5c282ec50", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, BufRead, Stdin, StdinLock};\n\nfn get_average_time(time1: (usize, usize), time2: (usize, usize)) -> (usize, usize) {\n let time1_minutes: usize = time1.0 * 60 + time1.1;\n let time2_minutes: usize = time2.0 * 60 + time2.1;\n\n let time3_minutes = (time1_minutes + time2_minutes) / 2;\n\n return ((time3_minutes / 60), (time3_minutes % 60));\n}\n\n#[cfg(test)]\nmod test {\n use super::get_average_time;\n\n #[test]\n fn test1() {\n let time1: (usize, usize) = (10, 0);\n let time2: (usize, usize) = (11, 0);\n let time_result: (usize, usize) = get_average_time(time1, time2);\n\n assert_eq!(time_result, (10, 30));\n }\n #[test]\n fn test2() {\n let time1: (usize, usize) = (11, 10);\n let time2: (usize, usize) = (11, 12);\n let time_result: (usize, usize) = get_average_time(time1, time2);\n\n assert_eq!(time_result, (11, 11));\n }\n #[test]\n fn test3() {\n let time1: (usize, usize) = (1, 2);\n let time2: (usize, usize) = (3, 2);\n let time_result: (usize, usize) = get_average_time(time1, time2);\n\n assert_eq!(time_result, (2, 2));\n }\n}\n\nfn read_data() -> ((usize, usize), (usize, usize)) {\n let stdin_stream: Stdin = stdin();\n let mut stdin_handle: StdinLock = stdin_stream.lock();\n\n let mut str1: String = String::new();\n stdin_handle.read_line(&mut str1).unwrap();\n let str1_tokens: Vec = str1\n .trim()\n .split(\":\")\n .map(|s| s.parse::().unwrap())\n .collect();\n\n let mut str2: String = String::new();\n stdin_handle.read_line(&mut str2).unwrap();\n let str2_tokens: Vec = str2\n .trim()\n .split(\":\")\n .map(|s| s.parse::().unwrap())\n .collect();\n\n return (\n (str1_tokens[0], str1_tokens[1]),\n (str2_tokens[0], str2_tokens[1]),\n );\n}\n\nfn main() {\n let (time1, time2): ((usize, usize), (usize, usize)) = read_data();\n\n let time_result: (usize, usize) = get_average_time(time1, time2);\n\n println!(\"{:02}:{:02}\", time_result.0, time_result.1);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d5c014da7990e9901c9981799c3af20e", "src_uid": "f7a32a8325ce97c4c50ce3a5c282ec50", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut string = String::new();\n io::stdin().read_line(&mut string)\n .expect(\"Read error!\");\n\n let int_vec: Vec<_> = string.trim().split(' ')\n .map(|x| x.parse::().expect(\"Not an integer!\"))\n .collect();\n\n if int_vec.len() != 3 {\n panic!(\"Bad input\");\n }\n\n println!(\"{}\", ((int_vec[0] as f64) / (int_vec[2] as f64)).ceil() *\n ((int_vec[1] as f64) / (int_vec[2] as f64)).ceil() );\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "5d90d19484a6294ad9d359f71f873c82", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n let mut v: Vec = Vec::with_capacity(3);\n for i in input.split_whitespace() {\n v.push(i.trim().parse().unwrap());\n }\n let (mut k,mut l) = (v[0]/v[2] , v[1]/v[2] );\n if v[0]%v[2] != 0 { k+=1}\n if v[1]%v[2] != 0 { l+=1}\n println!(\"{}\",k*l);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "6a08aed366cf8d11ffed2482aca6f661", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\n//[TIME TO INIT: 10:38]\n\nfn main() {\n\n let mut contents = String::new();\n let mut vec = vec![];\n\n stdin().read_line(&mut contents).unwrap();\n\n vec = contents\n .split(\" \")\n .map(|x| x.trim().parse::().unwrap())\n .collect();\n\n let mut width = vec[0] / vec[2];\n let mut height = vec[1] / vec[2];\n\n if vec[0] % vec[2] != 0 {\n width += 1;\n }\n if vec[1] % vec[2] != 0 {\n height += 1;\n }\n println!(\"{}\", width * height);\n\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "06cf2265c6bc676ce3a77d5f9408f39e", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n // The input n, m, a\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n\n // Caculate the results\n let v: Vec = s.trim().split_whitespace().map(|s| s.parse().unwrap()).collect();\n let r = ((v[0] / v[2]).ceil() * (v[1] / v[2]).ceil()).floor();\n\n // Display the results\n println!(\"{}\", r);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "a043f0b747fdaf4ab12356a7706f266e", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut s:String=String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut a:Vec=Vec::new();\n let mut c:usize=0;\n let mut n:usize=0;\n while c<=s.len()-1{\n n=c;\n if s.chars().nth(c).unwrap()!=' '{\n while s.chars().nth(n).unwrap()!=' ' && n0{a[0]/a[2]+1}else{a[0]/a[2]};\n let n:i64=if a[1]%a[2]>0{a[1]/a[2]+1}else{a[1]/a[2]};\n println!(\"{}\",m*n);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "e5155355d109f9c921ff8f09a7f081eb", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ($out:ident as $type:ty) => {\n let mut inner = String::new();\n io::stdin().read_line(&mut inner).expect(\"A String\");\n let $out = inner.trim().parse::<$type>().expect(\"Parseble\");\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_str {\n ($out:ident) => {\n let mut inner = String::new();\n io::stdin().read_line(&mut inner).expect(\"A String\");\n let $out = inner.trim();\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_vec {\n ($out:ident as $type:ty) => {\n let mut inner = String::new();\n io::stdin().read_line(&mut inner).unwrap();\n let $out = inner\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$type>().unwrap())\n .collect::>();\n };\n}\n\nfn main() {\n read_vec!(inp as u64);\n let a = (inp[0] as f64 / inp[2] as f64).ceil() as u64;\n let b = (inp[1] as f64 / inp[2] as f64).ceil() as u64;\n\n println!(\"{}\", a * b);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "41046889f6c9aea6356b36aac8b63cee", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> String {\n let stdin = std::io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n String::from(line.trim())\n}\n\nmacro_rules! scanln {\n ($($ty: ty),*) => {{\n let line = readln();\n let mut iter = line.split_whitespace();\n ($(iter.next().unwrap().parse::<$ty>().unwrap()),*)\n }}\n}\n\nfn ceil(a: i32, b: i32) -> u64 {\n (a as u64 - 1) / b as u64 + 1\n}\n\nfn main() {\n let (n, m, a) = scanln!(i32, i32, i32);\n println!(\"{}\", ceil(n, a) * ceil(m, a));\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "4c0d3ef6a64f4c2814dea822d5a5929c", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n let vec = a_str.split_whitespace()\n .map(|x| x.parse::().expect(\"parse error\"))\n .collect::>();\n\n let m = vec[0];\n let n = vec[1];\n let a = vec[2];\n\n let x: u64;\n if m % a != 0 {\n x = (m / a) + 1;\n } else {\n x = m / a;\n }\n\n let y: u64;\n if n % a != 0 {\n y = (n / a) + 1;\n } else {\n y = n / a;\n }\n\n println!(\"{}\", x*y);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "c32e3c380f81ea7f37ad9058d89b80fe", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut sc = new(std::io::stdin());\n let k = sc.next();\n let mut rm = 0;\n for _ in 0..k {\n let r = sc.next();\n if r > rm {\n rm = r;\n }\n }\n let mut res = rm - 25;\n if res < 0 {\n res = 0;\n }\n println!(\"{}\", res);\n}\n\nuse std::io;\nuse std::io::BufRead;\n\npub struct Scanner {\n br: io::BufReader,\n // Read tokens are stored in reversed order per line.\n buf: Vec,\n}\n\npub fn new(r: R) -> Scanner {\n Scanner::new(r)\n}\n\nimpl Scanner {\n #[inline]\n fn new(r: R) -> Scanner {\n Scanner {\n br: io::BufReader::new(r),\n buf: vec![],\n }\n }\n #[inline]\n pub fn next(&mut self) -> T\n where T: std::str::FromStr,\n T::Err: std::fmt::Debug\n {\n self.next_string().map(|s| s.parse::().expect(\"Parse failed: \")).unwrap()\n }\n fn next_string(&mut self) -> Option {\n self.buf.pop().or_else(|| match self.update() {\n true => self.next_string(),\n false => None,\n })\n }\n #[inline]\n fn update(&mut self) -> bool {\n let mut s = String::new();\n let res = self.br.read_line(&mut s);\n match res.expect(\"I/O error.\") {\n 0 => false,\n _ => {\n self.buf = s.split_whitespace().map(|x| x.to_string()).rev().collect();\n true\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "bdda947f6b445a73279a84034c04dbcd", "src_uid": "ef657588b4f2fe8b2ff5f8edc0ab8afd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{min, max};\nuse std::f64::consts::*;\nuse std::mem::swap;\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: i32 = 1000000007;\n\n#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone)]\nstruct Pair(A, B);\n\nstruct Input\n{\n\tbuffer: Buf\n}\n\nimpl Input\n{\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\t#[inline]\n\tfn read_int(&mut self) -> i32 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_long(&mut self) -> i64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_usize(&mut self) -> usize {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_double(&mut self) -> f64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n}\nmacro_rules! read {\n () => {};\n\t($inf:ident,$($t:ty),*) => ({($({$inf.read_word().parse::<$t>().expect(\"Parsing error\")}),*)});\n}\nfn gcd + Copy>(x: T, y: T) -> T {\n\tlet (mut a, mut b) = (x, y);\n\twhile b > T::from(0) {\n\t\ta %= b;\n\t\tswap(&mut a, &mut b);\n\t}\n\ta\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input {\n\t\t\t\tbuffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\"))\n\t\t\t};\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(stdin()) };\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output)\n{\n\tlet k = read!(inf,usize);\n\tlet mut v = vec![0; k];\n\tfor i in 0..k {\n\t\tv[i] = read!(inf,i32);\n\t}\n\tv.sort();\n\twriteln!(ouf, \"{}\", max(v[k - 1] - 25, 0));\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "8644f3de7f517d2540662120e943b909", "src_uid": "ef657588b4f2fe8b2ff5f8edc0ab8afd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\nuse std::io::{StdinLock, stdin, BufRead};\nuse std::collections::*;\nuse std::cmp::*;\n\nfn scan_helper(lock : &mut StdinLock) -> String {\n let mut buffer = String::new();\n lock.read_line(&mut buffer).ok();\n buffer\n}\n\nmacro_rules! scan {\n ($lock:ident, $t:ty) => ({\n scan_helper(&mut $lock).split_whitespace()\n .next().unwrap()\n .parse::<$t>().unwrap()\n });\n ($lock:ident, $($t:ty),+) => ({\n let buffer = scan_helper(&mut $lock);\n let mut iter = buffer.split_whitespace();\n ($(\n {\n iter.next().unwrap()\n .parse::<$t>().unwrap()\n },\n )+)\n })\n}\n\nmacro_rules! scan_iter {\n ($lock:ident, $t:ty) => ({\n scan_helper(&mut $lock).split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect()\n })\n}\n\ntrait Ext {\n fn idx(&self) -> usize;\n fn num(&self) -> i64;\n}\n\nmacro_rules! ext {\n ($t:ty) => (\n impl Ext for $t {\n #[inline]\n fn idx(&self) -> usize {\n *self as usize\n }\n\n #[inline]\n fn num(&self) -> i64 {\n *self as i64\n }\n }\n )\n}\next!(i64);\next!(usize);\n\nmacro_rules! derive_regular {\n ($t:ty) => (\n impl Ord for $t {\n fn cmp(&self, other : &$t) -> Ordering {\n self.partial_cmp(other).unwrap()\n }\n }\n impl PartialEq for $t {\n fn eq(&self, other : &$t) -> bool {\n self.cmp(other) == Ordering::Equal\n }\n }\n impl Eq for $t {}\n )\n}\n\nfn main() {\n let stdin = stdin();\n let mut s = stdin.lock();\n let n = scan!(s, usize);\n let data : Vec = scan_iter!(s, i64);\n let m = data.iter().max().unwrap();\n println!(\"{}\", max(0, m - 25));\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "4e0b592cbc911f6646862aeecc8ad262", "src_uid": "ef657588b4f2fe8b2ff5f8edc0ab8afd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn main() {\n read_str();\n let mut remove: u8 = 0;\n let stones: String = read_str();\n let mut current: char = stones.chars().nth(0).expect(\"Error\");\n\n for stone in stones[1..].chars() {\n if current == stone { remove += 1; }\n current = stone;\n }\n println!(\"{}\", remove)\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "94eddb5a95f42cc6ac55221283e4f4c8", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\npub fn main(){\n let chars: Vec = input().chars().collect();\n let mut color = chars[0];\n let mut extras = -1;\n for c in chars {\n if c == color {\n extras += 1;\n } else {\n color = c;\n }\n }\n println!(\"{}\", extras);\n}\n\nfn input() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input);\n input = String::new();\n std::io::stdin().read_line(&mut input);\n input\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0358a7885a34959d5614901144ef0ca0", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn read() -> String{\n let mut input=String::new();\n io::stdin().read_line(&mut input).expect(\"unable to read\");\n input.trim().to_string()\n}\nfn main() {\n let mut sum=0;\n let _=read().parse::().unwrap();\n let list: Vec<_>=read().chars().collect();\n let mut first=\".\".to_string();\n for i in &list{\n if i.to_string()==first{\n sum+=1;\n }first=i.to_string();\n }println!(\"{}\",sum)\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9c3af5abb04ff06c217fb7f2c92c608d", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read() -> String {\n let mut res = String::new();\n std::io::stdin().read_line(&mut res).expect(\"???\");\n res\n}\n\nfn parse_int(s: &str) -> usize {\n s.trim().parse().expect(\"???\")\n}\n\nfn parse_ints(s: &str) -> Vec {\n s.split_whitespace().map(parse_int).collect()\n}\n\nfn main() {\n let n = parse_int(&read());\n let s = read().into_bytes();\n let mut curr = b' ';\n let mut res = 0;\n for c in s.into_iter() {\n if curr == c {\n res += 1;\n }\n curr = c;\n }\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "35325df585230bd4923eb875fbd8234d", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut string = String::new();\n io::stdin().read_line(&mut string)\n .expect(\"Read error!\");\n\n let count = string.trim().parse::().expect(\"Not an integer!\");\n\n string.clear();\n io::stdin().read_line(&mut string)\n .expect(\"Read error!\");\n\n\n let bytes = string.trim().as_bytes();\n let mut cnt = 0;\n\n for i in 1..count {\n if bytes[i - 1] == bytes[i] {\n cnt += 1;\n }\n }\n\n println!(\"{}\", cnt);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d88fbedb72ad588eb861e08e8c012b3d", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::{Read, Write};\n\nfn solve(input: &mut Read, output: &mut Write) {\n let mut sin = String::new();\n input.read_to_string(&mut sin).unwrap();\n let mut chars = sin.lines().skip(1).next().unwrap().trim().chars();\n let mut last = chars.next().unwrap();\n let res = chars.fold(0, |acc, x| {\n if x == last {\n acc + 1\n } else {\n last = x;\n acc\n }\n });\n\n output.write(res.to_string().trim().as_bytes()).unwrap();\n}\n\nfn main() {\n solve(&mut io::stdin(), &mut io::stdout());\n}\n\n#[cfg(test)]\nmod tests {\n use std::fs::File;\n use std::io::Read;\n use solve;\n\n #[test]\n fn test() {\n (1..3 + 1).map(|x| {\n println!(\"test #{}\", x);\n let mut fin = File::open(\"./src/in\".to_string() + &x.to_string() + \".txt\").unwrap();\n let mut buf: Vec = Vec::new();\n solve(&mut fin, &mut buf);\n let res = String::from_utf8(buf).unwrap();\n\n let mut fout = File::open(\"./src/out\".to_string() + &x.to_string() + \".txt\").unwrap();\n let mut sout = String::new();\n fout.read_to_string(&mut sout).unwrap();\n assert_eq!(res, sout.trim());\n\n }).count();\n\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ece95ac5db6ff66bb75a91cf2002ac2e", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\n\nmacro_rules! read_line(\n () => {{\n let stdin = std::io::stdin();\n let stdin = stdin.lock();\n let mut lines = stdin.lines();\n lines.next().unwrap()\n }}\n);\n\nfn main() -> Result<(), Box> {\n let amount: usize = read_line!()?.parse()?;\n let colors: String = read_line!()?.parse()?;\n let chars: Vec<_> = colors.chars().collect();\n let result = chars.windows(2).fold(0, |acc, pair| if pair[0] == pair[1] { acc + 1} else { acc });\n println!(\"{}\", result);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "77304eeafd2ca633046709860d2e45e0", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut n = String::new();\n\tio::stdin().read_line(&mut n).unwrap();\n\tlet mut stones = String::new();\n\tio::stdin().read_line(&mut stones).unwrap();\n\n\tlet mut ans: i32 = 0;\n\tlet mut prev_stone = '0';\n\tfor stone in stones.trim().chars() {\n\t\tif stone == prev_stone {\n\t\t\tans += 1;\n\t\t} else {\n\t\t\tprev_stone = stone;\n\t\t}\n\t}\n\tprintln!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ccc685e308f9e37e2ea4d739404298b5", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin, stdin};\nuse std::str::FromStr;\nuse std::error::Error;\n\nfn main() -> Result<(), Box> {\n let stdin = stdin();\n\n let cases = {\n let l = line(&stdin)?;\n let mut ite = l.trim().split(' ');\n usize::from_str(ite.next().unwrap())?\n };\n\n for _ in 0..cases {\n let it = {\n let l = line(&stdin)?;\n let mut ite = l.trim().split(' ');\n u32::from_str(ite.next().unwrap())?\n };\n\n let mut best: u32 = 1;\n for d in 2..=f64::sqrt(it as f64) as u32 {\n if it % d == 0 {\n let nd = it / d;\n if nd > best {\n best = nd;\n }\n }\n }\n println!(\"{} {}\", best, it - best);\n }\n\n Ok(())\n}\n\nfn line(s: &Stdin) -> io::Result {\n let mut i = String::new();\n s.read_line(&mut i)?;\n Ok(i)\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "9a3671d254fad81b31e7c88be3eb1ee8", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io;\nuse std::ops;\nuse std::str::FromStr;\n\n#[derive(Clone, Debug, Default)]\nstruct ProblemState {\n}\n\nfn gcd(a: u128, b: u128) -> u128 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nimpl Problem {\n fn solve(&mut self) {\n let n: u64 = self.scan();\n\n let mut x = 2;\n let mut k = 1;\n\n while x * x <= n {\n if n % x == 0 {\n k = n / x;\n break;\n }\n\n x += 1;\n }\n\n println!(\"{} {}\", k, n - k);\n }\n}\n\nfn main() {\n Problem::new().solve_cases();\n}\n\nstruct Problem {\n input_state: InputState,\n problem_state: ProblemState,\n}\n\nstruct InputState {\n stdin: io::Stdin,\n buffer: String,\n tokens: VecDeque,\n}\n\nimpl Problem {\n fn new() -> Self {\n Self {\n input_state: InputState {\n stdin: io::stdin(),\n buffer: String::new(),\n tokens: VecDeque::new(),\n },\n problem_state: Default::default(),\n }\n }\n\n fn solve_cases(&mut self) {\n for _ in 0usize..self.scan() {\n self.solve()\n }\n }\n\n fn scan(&mut self) -> T {\n while self.input_state.tokens.is_empty() {\n self.input_state.stdin.read_line(&mut self.input_state.buffer).unwrap();\n\n for token in self.input_state.buffer.split_ascii_whitespace() {\n self.input_state.tokens.push_back(token.to_string());\n }\n\n self.input_state.buffer.clear();\n }\n\n self.input_state.tokens.pop_front().unwrap().parse().ok().unwrap()\n }\n\n fn scan_vec(&mut self, n: usize) -> Vec {\n (0..n).into_iter().map(|_| self.scan()).collect()\n }\n\n fn scan_line(&mut self) -> String {\n let mut line = String::new();\n self.input_state.stdin.read_line(&mut line).unwrap();\n while line.ends_with('\\n') || line.ends_with('\\r') { line.pop(); }\n line\n }\n\n fn scan_line_vec(&mut self, n: usize) -> Vec {\n (0..n).into_iter().map(|_| self.scan_line()).collect()\n }\n}\n\nimpl ops::Deref for Problem {\n type Target = ProblemState;\n\n fn deref(&self) -> &ProblemState {\n &self.problem_state\n }\n}\n\nimpl ops::DerefMut for Problem {\n fn deref_mut(&mut self) -> &mut ProblemState {\n &mut self.problem_state\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "a29fee3c89d54d8a71ff5896c7324495", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n date : 2020 / 5 / 5\n author : quickn (quickn.ga)\n email : quickwshell@gmail.com\n*/\n\nuse std::io::{self, BufWriter, Write};\n\nmod scanner {\n use std::{io, str};\n /* https://github.com/EbTech/rust-algorithms */\n\n /// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n /// **REQUIRES** Rust 1.34 or higher\n pub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n }\n\n impl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n }\n}\n\nuse std::cmp::{max, min};\nuse std::mem::swap;\n\nfn gcd(a: usize, b: usize) -> usize {\n let (mut a_t, mut b_t) = (max(a, b), min(a, b));\n while b_t != 0 {\n a_t %= b_t;\n swap(&mut a_t, &mut b_t);\n }\n a_t\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let (mut scan, mut sout) = (\n scanner::UnsafeScanner::new(stdin.lock()),\n BufWriter::new(stdout.lock()),\n );\n let t: usize = scan.token();\n for i in 0..t {\n let n: usize = scan.token();\n let mut func = n;\n let mut a_t = n;\n for a in 1..=((n as f64).sqrt() as usize) {\n if n % a == 0 {\n if (n/a)*(a-1) < func && a != 1 {\n a_t = n / a;\n func = (n/a)*(a-1);\n }\n if a*((n / a)-1) < func && (n / a) != 1 {\n a_t = a;\n func = a*((n / a)-1);\n }\n }\n }\n writeln!(sout, \"{} {}\", a_t, n-a_t).ok();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "76ea14e0bea85cd2c664ad03f6bc54cd", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(dead_code)]\n \nuse std::io::Read;\n \n\nstruct State {\n n: usize,\n}\n\nfn solve(st: &mut State) {\n let n = st.n;\n let mut i = 2;\n while i * i <= n {\n if n % i == 0 {\n print!(\"{} {}\\n\", n/i, n/i * (i-1));\n return;\n }\n i += 1;\n }\n print!(\"{} {}\\n\", 1, n-1);\n}\nfn main() {\n let mut buffer = String::new();\n std::io::stdin().read_to_string(&mut buffer).unwrap();\n let mut input = buffer.split_whitespace();\n \n let t: usize = input.next().unwrap().parse().unwrap();\n for _ in 0..t {\n let n: usize = input.next().unwrap().parse().unwrap();\n //let a: Vec = (0..n).map(|_| input.next().unwrap().parse().unwrap()).collect();\n solve(&mut State{n: n});\n }\n \n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "6e697134dc85021cefc4a0ce27cf136c", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros)]\n\nuse kyoproio::*;\nuse std::{\n collections::*,\n io::{self, prelude::*},\n iter,\n mem::{replace, swap},\n};\n\nfn main() -> io::Result<()> {\n std::thread::Builder::new()\n .stack_size(64 * 1024 * 1024)\n .spawn(|| {\n let stdin = io::stdin();\n let stdout = io::stdout();\n run(KInput::new(stdin.lock()), io::BufWriter::new(stdout.lock()))\n })?\n .join()\n .unwrap();\n Ok(())\n}\n\nfn run(mut kin: I, mut out: O) {\n macro_rules! output { ($($args:expr),+) => { write!(&mut out, $($args),+).unwrap(); }; }\n macro_rules! outputln {\n ($($args:expr),+) => { output!($($args),+); outputln!(); };\n () => { output!(\"\\n\"); if cfg!(debug_assertions) { out.flush().unwrap(); } }\n }\n\n let t: usize = kin.input();\n let ps = primes(100000);\n 'test: for _ in 0..t {\n let n: usize = kin.input();\n for &p in &ps {\n if n % p == 0 {\n let x = n / p;\n outputln!(\"{} {}\", x, x * (p - 1));\n continue 'test;\n }\n }\n outputln!(\"{} {}\", 1, n - 1);\n }\n}\n\npub fn primes(n: usize) -> Vec {\n // 1, 7, 11, 13, 17, 19, 23, 29\n const SKIP: [u8; 8] = [6, 4, 2, 4, 2, 4, 6, 2];\n const XTOI: [u8; 15] = [\n 0, 0, 0, 1, 0, 2, 3, 0, 4, 5, 0, 6, 0, 0, 7,\n ];\n let mut sieve = vec![0u8; n / 30 + 1];\n let mut ps = vec![2, 3, 5];\n if n <= 4 {\n ps.truncate([0, 0, 1, 2, 2][n]);\n return ps;\n }\n let mut x = 7;\n let mut i = 1;\n while x <= n {\n if sieve[i / 8] & 1 << i % 8 == 0 {\n ps.push(x);\n let mut j = i;\n let mut y = x * x;\n while y <= n {\n sieve[y / 30] |= 1 << XTOI[y / 2 % 15];\n y += x * SKIP[j % 8] as usize;\n j += 1;\n }\n }\n x += SKIP[i % 8] as usize;\n i += 1;\n }\n ps\n}\n\n\n\n// -----------------------------------------------------------------------------\npub mod kyoproio {\n use std::io::prelude::*;\n pub trait Input {\n fn str(&mut self) -> &str;\n fn input(&mut self) -> T {\n T::input(self)\n }\n fn iter(&mut self) -> Iter {\n Iter(self, std::marker::PhantomData)\n }\n fn seq>(&mut self, n: usize) -> B {\n self.iter().take(n).collect()\n }\n }\n pub struct KInput {\n src: R,\n buf: String,\n pos: usize,\n }\n impl KInput {\n pub fn new(src: R) -> Self {\n Self {\n src,\n buf: String::with_capacity(1024),\n pos: 0,\n }\n }\n }\n impl Input for KInput {\n fn str(&mut self) -> &str {\n loop {\n if self.pos >= self.buf.len() {\n self.pos = 0;\n self.buf.clear();\n if self.src.read_line(&mut self.buf).expect(\"io error\") == 0 {\n return &self.buf;\n }\n }\n let range = self.pos\n ..self.buf[self.pos..]\n .find(|c: char| c.is_ascii_whitespace())\n .map(|i| i + self.pos)\n .unwrap_or_else(|| self.buf.len());\n self.pos = range.end + 1;\n if range.end > range.start {\n return &self.buf[range];\n }\n }\n }\n }\n pub struct Iter<'a, T, I: ?Sized>(&'a mut I, std::marker::PhantomData<*const T>);\n impl<'a, T: InputParse, I: Input + ?Sized> Iterator for Iter<'a, T, I> {\n type Item = T;\n fn next(&mut self) -> Option {\n Some(self.0.input())\n }\n }\n pub trait InputParse: Sized {\n fn input(src: &mut I) -> Self;\n }\n impl InputParse for Vec {\n fn input(src: &mut I) -> Self {\n src.str().as_bytes().to_owned()\n }\n }\n macro_rules! from_str_impl {\n { $($T:ty)* } => {\n $(impl InputParse for $T {\n fn input(src: &mut I) -> Self {\n src.str().parse::<$T>().expect(\"parse error\")\n }\n })*\n }\n }\n from_str_impl! {\n String char bool f32 f64 isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128\n }\n macro_rules! tuple_impl {\n ($H:ident $($T:ident)*) => {\n impl<$H: InputParse, $($T: InputParse),*> InputParse for ($H, $($T),*) {\n fn input(src: &mut I) -> Self {\n ($H::input(src), $($T::input(src)),*)\n }\n }\n tuple_impl!($($T)*);\n };\n () => {}\n }\n tuple_impl!(A B C D E F G);\n #[macro_export]\n macro_rules! kdbg {\n ($($v:expr),*) => {\n if cfg!(debug_assertions) { dbg!($($v),*) } else { ($($v),*) }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "11879344663a9f328a71d1cdde6007e2", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::fmt::Debug;\nuse std::str::FromStr;\n\npub struct TokenReader {\n reader: std::io::Stdin,\n tokens: Vec,\n index: usize,\n}\n\nimpl TokenReader {\n pub fn new() -> Self {\n Self {\n reader: std::io::stdin(),\n tokens: Vec::new(),\n index: 0,\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index += 1;\n self.tokens[self.index - 1].parse().unwrap()\n }\n\n pub fn vector(&mut self) -> Vec\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index = self.tokens.len();\n self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()\n }\n\n pub fn load_next_line(&mut self) {\n let mut line = String::new();\n self.reader.read_line(&mut line).unwrap();\n\n self.tokens = line\n .split_whitespace()\n .map(String::from)\n .collect();\n self.index = 0;\n }\n}\n\nfn gcd(mut a: i64, mut b: i64) -> i64 {\n while b != 0 {\n let r = a % b;\n a = b;\n b = r;\n }\n a\n}\n\nfn lcm(a: i64, b: i64) -> i64 {\n ((a as i64 * b as i64) / (gcd(a, b) as i64)) as i64\n}\n\nfn solve(n: i64) -> (i64, i64) {\n let mut res = (n / 2, n - n / 2);\n let mut res_lcm = lcm(res.0, res.1);\n\n let mut i = 1i64;\n while i * i <= n as i64 {\n if n % i as i64 != 0 {\n i += 1;\n continue;\n }\n\n let a = i as i64;\n let b = n - a;\n let curr_lcm = lcm(a, b);\n\n if curr_lcm < res_lcm && a > 0 && b > 0 {\n res_lcm = curr_lcm;\n res = (a, b);\n }\n\n let a = n / i as i64;\n let b = n - a;\n let curr_lcm = lcm(a, b);\n\n if curr_lcm < res_lcm && a > 0 && b > 0 {\n res_lcm = curr_lcm;\n res = (a, b);\n }\n i += 1;\n }\n res\n}\n\nfn main() {\n let mut reader = TokenReader::new();\n let tests = reader.next();\n\n for _ in 0..tests {\n let n = reader.next();\n let (a, b) = solve(n);\n println!(\"{} {}\", a, b);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "2e162c9af8634d258832870a9994a96d", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let n = parse_line!(u32);\n for i in 2..n {\n if i * i > n {\n break;\n }\n if n % i == 0 {\n let a = n / i;\n let b = n - a;\n writeln!(writer, \"{} {}\", a, b).unwrap();\n return;\n }\n }\n writeln!(writer, \"1 {}\", n - 1).unwrap();\n}\n\nfn main() {\n let tests = parse_line!(usize);\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "d3832481aa8d68ae529f21327b7d1151", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(a: u64, b: u64) -> u64 {\n let mut a = a;\n let mut b = b;\n while a != b {\n if a > b {\n a = a - b\n } else {\n b = b - a\n }\n }\n a\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nuse std::cmp::{max, min};\nuse std::collections::VecDeque;\n\nfn first_factor(n: u32) -> u32 {\n if n % 2 == 0 {\n return 2;\n }\n if n % 3 == 0 {\n return 3;\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n if n % (f - 1) == 0 {\n return f - 1;\n }\n if n % (f + 1) == 0 {\n return f + 1;\n }\n f += 6;\n }\n return n;\n}\n\nfn main() -> Result<(), Box> {\n for _ in 0..read_usize() {\n let n = read::();\n let f = first_factor(n);\n let a = n / f;\n println!(\"{} {}\", a, n - a);\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "4c2cdf3d6b816cf39e195cbfc9372be2", "src_uid": "3fd60db24b1873e906d6dee9c2508ac5", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/// https://github.com/akiradeveloper/rust-comp-snippets\n\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n\n#[macro_export]\nmacro_rules! chmax {\n ($x:expr, $($v:expr),+) => {\n $(\n $x = std::cmp::max($x,$v);\n )+\n };\n}\n\n#[macro_export]\nmacro_rules! chmin {\n ($x:expr, $($v:expr),+) => {\n $(\n $x = std::cmp::min($x,$v);\n )+\n };\n}\n\n#[macro_export]\nmacro_rules! max {\n ($x:expr) => ( $x );\n ($x:expr, $($xs:expr),+) => {\n std::cmp::max($x, max!( $($xs),+ ))\n };\n}\n\n#[macro_export]\nmacro_rules! min {\n ($x:expr) => ( $x );\n ($x:expr, $($xs:expr),+) => {\n std::cmp::min($x, min!( $($xs),+ ))\n };\n}\n\n#[macro_export]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n \n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[macro_export]\nmacro_rules! cfor {\n // for (; ...; ...) { ... }\n (; $($rest: tt)*) => {\n cfor!((); $($rest)*)\n };\n // for ($init; ; ...) { ... }\n ($($init: stmt),+; ; $($rest: tt)*) => {\n // avoid the `while true` lint\n cfor!($($init),+; !false; $($rest)*)\n };\n\n // for ($init; $cond; ) { ... }\n ($($init: stmt),+; $cond: expr; ; $body: block) => {\n cfor!{$($init),+; $cond; (); $body}\n };\n\n // for ($init; $cond; $step) { $body }\n ($($init: stmt),+; $cond: expr; $($step: expr),+; $body: block) => {\n {\n $($init;)+\n while $cond {\n let mut _first = true;\n let mut _continue = false;\n // this loop runs once, allowing us to use `break` and\n // `continue` as `goto` to skip forward to the\n // condition.\n //\n // the booleans above are very transparent to the\n // optimiser, since they are modified exactly once,\n // with nice control flow, and this this optimises to\n // be similar to C for loop.\n loop {\n // if we *don't* hit this, there was a `break` in\n // the body (otherwise the loop fell-through or\n // was `continue`d.)\n if !_first { _continue = true; break }\n _first = false;\n\n $body\n }\n if !_continue {\n // the `if` wasn't hit, so we should propagate the\n // `break`.\n break\n }\n\n $($step;)+\n }\n }\n };\n}\n\n/// main\n\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\n\n// ref: tanakh \n// diff: using Parser\n#[macro_export]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut parser = Parser::from_str($s);\n input_inner!{parser, $($r)*}\n };\n (parser = $parser:ident, $($r:tt)*) => {\n input_inner!{$parser, $($r)*}\n };\n (new_stdin_parser = $parser:ident, $($r:tt)*) => {\n let stdin = std::io::stdin();\n let reader = std::io::BufReader::new(stdin.lock());\n let mut $parser = Parser::new(reader);\n input_inner!{$parser, $($r)*}\n };\n ($($r:tt)*) => {\n input!{new_stdin_parser = parser, $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! input_inner {\n ($parser:ident) => {};\n ($parser:ident, ) => {};\n ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($parser, $t);\n input_inner!{$parser $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($parser:ident, ( $($t:tt),* )) => {\n ( $(read_value!($parser, $t)),* )\n };\n ($parser:ident, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($parser, $t)).collect::>()\n };\n ($parser:ident, chars) => {\n read_value!($parser, String).chars().collect::>()\n };\n ($parser:ident, usize1) => {\n read_value!($parser, usize) - 1\n };\n ($parser:ident, $t:ty) => {\n $parser.next::<$t>().expect(\"Parse error\")\n };\n}\n\nuse std::io::BufRead;\nuse std::io;\nuse std::str;\n\n// ref: tatsuya6502 \n// ref: wariuni \n// diff: using std::io::BufRead::fill_buf()\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\n\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\n\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len,complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n // diff: care when there is no empty space or line at the end\n if len == 0 {\n break;\n }\n (len, buf2[len-1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n }\n else {\n self.update_buf();\n }\n }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\nconst BIG_STACK_SIZE: bool = true;\n#[allow(dead_code)]\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\n\nfn solve() {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n input!{\n n:i64,m:i64,\n }\n let mi = max(0, n-2*m);\n let fullconn = n*(n-1)/2;\n let ma = if m==0 {\n n\n } else {\n let mut i=1;\n loop {\n if i*(i-1)/2 >= m {\n break;\n }\n i += 1;\n }\n n-i\n };\n writeln!(out,\"{} {}\", mi,ma);\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "ffd3ac5b3fb7e210521fb027bdeca99b", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::max;\nuse std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: i64 = scan.token();\n let m: i64 = scan.token();\n if m == 0 {\n writeln!(out, \"{} {}\", n, n).ok();\n return;\n }\n let min_ans = max(n - 2 * m, 0);\n let k = ((1.0 + ((1 + 8 * m) as f64).sqrt()) / 2.0).ceil() as i64;\n let max_ans = n - k;\n writeln!(out, \"{} {}\", min_ans, max_ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "f82de57da53288027d196e466a24ed70", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n let mut s=String::new();\n let input=std::io::stdin().read_line(&mut s)\n .expect(\"\");\n let mut iter=s.split_whitespace();\n let n : i64 =match iter.next(){\n Some(x) => x.trim().parse().expect(\"\"),\n None => return ,\n };\n let m : i64 =match iter.next(){\n Some(x) => x.trim().parse().expect(\"\"),\n None => return ,\n };\n\n let ans_min = if n-2*m>=0 {n-2*m} else {0};\n let mut ans_max = 0;\n\n for i in 0..n {\n if(i*(i-1)/2 >= m){\n ans_max=n-i;\n break;\n }\n }\n\n println!(\"{} {}\",ans_min,ans_max);\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "bbc4f284f0d793f6750ae29fddeb9012", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\n#[derive(Clone)]\nstruct Graph {\n nodes: usize,\n edges: Vec>,\n}\n\nimpl Graph {\n fn new(n: usize) -> Self {\n Self {\n nodes: n,\n edges: vec![Vec::new(); n + 1],\n }\n }\n\n fn add_edge(&mut self, x: usize, y: usize, cost: u64) {\n self.edges[x].push((y, cost));\n self.edges[y].push((x, cost));\n }\n\n fn dijkstra(&mut self, start: usize, end: usize) -> u64 {\n let mut dist = vec![None; self.nodes + 1];\n let mut prev = vec![None; self.nodes + 1];\n dist[start] = Some(0);\n let mut queue = (1..=self.nodes).collect::>();\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n while let Some(next_node) = queue.pop() {\n if next_node == end {\n return dist[next_node].unwrap();\n }\n for (neighbour, cost) in self.edges[next_node].iter() {\n let alt = dist[next_node].unwrap() + cost;\n if dist[*neighbour].is_none() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n } else {\n if alt < dist[*neighbour].unwrap() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n }\n }\n }\n //println!(\"{:?} {:?}\", dist, prev);\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n }\n 0\n }\n\n fn set_cost(&mut self, x: usize, y: usize, cost: u64) {\n for i in 0..self.edges[x].len() {\n if self.edges[x][i].0 == y {\n self.edges[x][i].1 = cost\n }\n }\n for i in 0..self.edges[y].len() {\n if self.edges[y][i].0 == x {\n self.edges[y][i].1 = cost\n }\n }\n }\n}\n\nconst MODULO: u64 = 1_000_000_007;\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\nstruct BigPrimeRing {\n inner: u64,\n}\n\nimpl From for BigPrimeRing\nwhere\n T: Into,\n{\n fn from(n: T) -> Self {\n Self {\n inner: n.into() % MODULO,\n }\n }\n}\n\nimpl std::ops::Add for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn add(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::AddAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn add_assign(&mut self, rhs: T) {\n self.inner += rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Sub for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn sub(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + MODULO - rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::SubAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn sub_assign(&mut self, rhs: T) {\n self.inner += MODULO;\n self.inner -= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Mul for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn mul(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner * rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::MulAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn mul_assign(&mut self, rhs: T) {\n self.inner *= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl BigPrimeRing {\n fn inverse(self) -> Self {\n if self.inner == 0 {\n return self;\n }\n let (_g, mut x, _y) = egcd(self.inner as i64, MODULO as i64);\n if x < 0 {\n x += MODULO as i64;\n }\n Self { inner: x as u64 }\n }\n}\n\nfn main() -> Result<(), Box> {\n let (n, mut m) = read_2::();\n let min_isolate = if m == 0 {\n n\n } else if m * 2 > n {\n 0\n } else {\n n - m * 2\n };\n let mut max_isolate = n;\n for i in 1..=n {\n if m > 0 {\n m -= min(i - 1, m);\n max_isolate -= 1;\n } else {\n break;\n }\n }\n println!(\"{} {}\", min_isolate, max_isolate);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "44ddbe2a30962afa0a5834d82531c885", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n let m = get!();\n \n if m == 0 {\n println!(\"{} {}\", n, n);\n return;\n }\n \n let min = if m >= (n + 1) / 2 { 0 } else { n - m * 2 };\n let mut max = 0;\n for i in 1..n+1 {\n let v = i * (i - 1) / 2;\n if v >= m {\n max = n - i;\n break;\n }\n }\n \n println!(\"{} {}\", min, max);\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "1390a087d3f41e2645760f312dc53abe", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nuse std::io::*;\nuse std::str::FromStr;\nuse std::char::*;\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:i64 = 1000000009;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n flag: bool,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n flag: true,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n self.f[crt] = true;\n self.c = self.e[crt].len() as i64;\n if self.c != 2 {\n self.flag = false;\n }\n\n for i in 0..self.e[crt].len() {\n let v = self.e[crt][i];\n if self.f[v] { continue; }\n self.dfs(v);\n }\n }\n}\n\nfn binary_search(d:i64) -> f64 {\n let mut left = 0.0;\n let mut right = d as f64;\n\n while (right-left).abs() > 1e-12 {\n let a = (right+left)/2.0;\n let b = d as f64 - a;\n //debug!(left,mid,right,s[mid]);\n if a*b >= d as f64 { left = a; }\n else { right = a; }\n }\n left\n}\n\nfn neighbors(tree: &BTreeSet, val: usize) -> (Option<&usize>, Option<&usize>) {\n use std::ops::Bound::*;\n\n let mut before = tree.range((Unbounded, Excluded(val)));\n let mut after = tree.range((Excluded(val), Unbounded));\n\n (before.next_back(), after.next())\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n\nconst MAX_A:i64 = 1e16 as i64;\n\nfn gcd(a:i64, b:i64) -> i64 {\n if b==0 {return a;}\n gcd(b, a%b)\n}\n\nstruct BIT {\n n: usize,\n bit: Vec,\n}\n\nimpl BIT {\n fn new(n:usize) -> BIT {\n BIT {\n n,\n bit: vec![0;n+1],\n }\n }\n\n fn add(&mut self, a:usize, w:i64) {\n let mut x = a;\n while x <= self.n {\n self.bit[x] += w;\n x += (x as i64 & -(x as i64)) as usize;\n }\n }\n\n fn sum(&self, a:usize) -> i64 {\n let mut ret = 0;\n let mut x = a as i64;\n while x > 0 {\n ret += self.bit[x as usize];\n x -= x & -x;\n }\n ret\n }\n}\n\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n\n input! {\n n: i64,\n m: i64\n }\n\n let mn = max(0,n-2*m);\n let mut c = 0;\n for v in 1..n+1 {\n let u = v*(v-1)/2;\n //debug!(m,u);\n if m > u {\n c = v+1;\n }\n }\n //debug!(c);\n let mx = max(0, n-c);\n puts!(\"{} {}\\n\", mn, mx);\n\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "bc1fa70f4cef61479bcace90c458beb4", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($format:expr) => (write!(out,$format).unwrap());\n ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())\n }\n input!{\n n: i64,\n m: i64,\n }\n let mut p = 0;\n for i in 0 .. n + 1 {\n if m <= i * (i - 1) / 2 {\n p = i;\n break;\n }\n }\n puts!(\"{} {}\\n\", max(0, n - 2 * m), n - p);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "123f24122ba5cc78c4654d6e791309ce", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io;\r\n\r\nfn read_ints() -> Vec {\r\n let stdin = io::stdin();\r\n let mut buff = String::new();\r\n stdin.read_line(&mut buff);\r\n buff.split_whitespace().map(|s| s.parse::().unwrap()).collect()\r\n}\r\n\r\nfn main() {\r\n let n = read_ints()[0];\r\n for _ in 0..n {\r\n let mut r1 = read_ints();\r\n let mut r2 = read_ints();\r\n r1.append(&mut r2);\r\n println!(\"{}\", match r1.iter().sum() {\r\n 0 => 0,\r\n 4 => 2,\r\n _ => 1,\r\n });\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "76b1bd78d97efedbd1598d84b6e5aef1", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code)]\r\n#![allow(unused)]\r\n#![allow(unused_imports)]\r\n\r\nuse std::cmp::{max, min, Reverse};\r\nuse std::collections::{HashMap, HashSet};\r\nuse std::io::{self, prelude::*};\r\nuse std::{str, vec};\r\n\r\nfn solve(scan: &mut Scanner, w: &mut W) {\r\n let a = (0..4)\r\n .map(|_| scan.next())\r\n .filter(|x: &i32| *x == 1)\r\n .count();\r\n\r\n writeln!(\r\n w,\r\n \"{}\",\r\n match a {\r\n 0 => 0,\r\n 1..=3 => 1,\r\n _ => 2,\r\n }\r\n );\r\n}\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let mut scan = Scanner::new(stdin.lock());\r\n let mut out = io::BufWriter::new(stdout.lock());\r\n\r\n let t = scan.next();\r\n for i in 0..t {\r\n solve(&mut scan, &mut out);\r\n }\r\n}\r\n\r\npub struct Scanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitAsciiWhitespace<'static>,\r\n}\r\n\r\nimpl Scanner {\r\n pub fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: vec![],\r\n buf_iter: \"\".split_ascii_whitespace(),\r\n }\r\n }\r\n\r\n pub fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_ascii_whitespace())\r\n }\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d2323abe84c3d3170ded66cccc8566ba", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io::{self, prelude::*};\r\nuse std::str;\r\n\r\n// IO\r\n\r\nstruct CPReader {\r\n read: R,\r\n buf: Vec,\r\n iter: str::SplitAsciiWhitespace<'static>,\r\n}\r\n\r\nimpl CPReader {\r\n fn new(read: R) -> Self {\r\n Self { read, buf: vec![], iter: \"\".split_ascii_whitespace() }\r\n }\r\n fn update(&mut self) {\r\n self.buf.clear();\r\n self.read.read_until(b'\\n', &mut self.buf).unwrap();\r\n self.iter = unsafe {\r\n let slice = str::from_utf8_unchecked(& self.buf);\r\n std::mem::transmute(slice.split_ascii_whitespace())\r\n }\r\n }\r\n fn getstr(&mut self) -> & str {\r\n loop {\r\n if let Some(ret) = self.iter.next() {\r\n break ret;\r\n }\r\n self.update();\r\n }\r\n }\r\n fn get(&mut self) -> T {\r\n return self.getstr().parse().ok().unwrap();\r\n }\r\n}\r\n\r\n// Main\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let mut input = CPReader::new(stdin.lock());\r\n let mut output = io::BufWriter::new(stdout.lock());\r\n\r\n let t:usize = input.get();\r\n for _ in 0..t {\r\n //let n:usize = input.get();\r\n let mut ans:i64 = 0;\r\n for _ in 0..4 {\r\n ans += input.get::();\r\n }\r\n writeln!(output, \"{}\", if ans == 4 { 2 } else { if ans != 0 {1} else {0}}).unwrap();\r\n }\r\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e39ddf46deed4de842d36871bfc81281", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io;\r\n\r\nfn read_ints() -> Vec {\r\n let stdin = io::stdin();\r\n let mut buff = String::new();\r\n stdin.read_line(&mut buff);\r\n buff.split_whitespace().map(|s| s.parse::().unwrap()).collect()\r\n}\r\n\r\nfn main() {\r\n let n = read_ints()[0];\r\n for _ in 0..n {\r\n let mut r1 = read_ints();\r\n let mut r2 = read_ints();\r\n r1.append(&mut r2);\r\n println!(\"{}\", match r1.iter().sum() {\r\n 0 => 0,\r\n 4 => 2,\r\n _ => 1,\r\n });\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "edf89551cf00a5e3c3c9666eb0c2ad52", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code)]\n\nuse std::io::{Write};\n\n//region I/O\nmod io {\n use std::io::{BufWriter, stdin, Stdout, StdoutLock};\n use std::str::{FromStr, SplitWhitespace};\n pub type Output<'a> = BufWriter>;\n\n pub fn read_from_stdin() -> String {\n use std::io::Read;\n let mut input = String::new();\n\n stdin()\n .read_to_string(&mut input)\n .expect(\"Error reading from stdin\");\n input\n .trim()\n .to_string()\n }\n\n pub fn output(stdout: &Stdout) -> Output {\n BufWriter::new(stdout.lock())\n }\n\n pub struct Input<'a> {\n values: SplitWhitespace<'a>\n }\n\n impl <'a> Input<'a> {\n pub fn from(input: &'a str) -> Self {\n Self { values: input.split_whitespace() }\n }\n\n pub fn next(&mut self) -> T where T: FromStr {\n self\n .values\n .next()\n .unwrap()\n .parse::()\n .ok()\n .unwrap()\n }\n\n pub fn vec(&mut self, n: usize) -> Vec where T: FromStr {\n (0..n)\n .map(|_| self.next())\n .collect()\n }\n }\n}\n//endregion\n\nfn main() {\n let stdin = io::read_from_stdin();\n let stdout = std::io::stdout();\n let mut input = io::Input::from(&stdin);\n let mut output = io::output(&stdout);\n let k: usize = input.next();\n\n for _ in 0..k {\n solve(&mut input, &mut output)\n }\n}\n\nfn solve(input: &mut io::Input, output: &mut io::Output) {\n let a11: i32 = input.next();\n let a12: i32 = input.next();\n let a21: i32 = input.next();\n let a22: i32 = input.next();\n let ans = match (a11, a12, a21, a22) {\n (1, 1, 1, 1) => 2,\n (0, 0, 0, 0) => 0,\n _ => 1\n };\n\n writeln!(output, \"{ans}\").unwrap()\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "62d5a57549e0f291617c974e02e244f7", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::fmt::Debug;\nuse std::io::stdin;\nuse std::ops::{Deref, Rem};\nuse std::str::FromStr;\n\nfn solve() {\n let ones = gets()\n .split_whitespace()\n .map(|s| s.to_i() > 0)\n .chain(gets().split_whitespace().map(|s| s.to_i() > 0))\n .filter(|&x| x)\n .count();\n\n println!(\n \"{}\",\n match ones {\n 0 => 0,\n 1..=3 => 1,\n 4 => 2,\n _ => panic!(),\n }\n );\n}\n\nfn main() {\n let t = gets().to_i();\n for _ in 0..t {\n solve();\n }\n}\n\n// ------- \u2702 -------\n\nfn gets() -> String {\n let mut line = String::new();\n stdin().read_line(&mut line).expect(\"Failed to read line\");\n line.chomp()\n}\n\ntrait StringExt {\n fn chomp(self) -> String;\n}\n\nimpl StringExt for String {\n fn chomp(mut self) -> String {\n loop {\n match self.chars().last() {\n Some(c) if c.is_whitespace() => drop(self.pop()),\n _ => break,\n }\n }\n self\n }\n}\n\ntrait StrExt {\n fn to_i(&self) -> i32;\n fn to_i64(&self) -> i64;\n fn to_f64(&self) -> f64;\n fn to_usize(&self) -> usize;\n\n fn parse_2(&self) -> (F, F)\n where\n F: FromStr,\n ::Err: Debug;\n}\n\nimpl StrExt for T\nwhere\n T: Deref,\n{\n fn to_i(&self) -> i32 {\n self.parse().unwrap()\n }\n fn to_i64(&self) -> i64 {\n self.parse().unwrap()\n }\n fn to_f64(&self) -> f64 {\n self.parse().unwrap()\n }\n fn to_usize(&self) -> usize {\n self.parse().unwrap()\n }\n\n fn parse_2(&self) -> (F, F)\n where\n F: FromStr,\n ::Err: Debug,\n {\n let mut it = self.split_whitespace();\n let fst: F = it.next().unwrap().parse().unwrap();\n let snd: F = it.next().unwrap().parse().unwrap();\n (fst, snd)\n }\n}\n\ntrait IsOdd {\n fn is_odd(&self) -> bool;\n\n fn is_even(&self) -> bool {\n !self.is_odd()\n }\n}\n\nimpl IsOdd for T\nwhere\n T: Copy + PartialEq + From + Rem,\n{\n fn is_odd(&self) -> bool {\n *self % T::from(2) == T::from(1)\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "73cbd858c64b19a34e2fdd5d69b7b8c2", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_variables)]\n#![allow(unused_must_use)]\nuse collections::*;\nuse std::io::Write;\nuse std::*;\n\nfn test_case(sc: &mut input::In, out: &mut std::io::BufWriter) {\n let (a,b,c,d):(usize, usize, usize, usize) = (sc.read(), sc.read(), sc.read(), sc.read());\n let e = a+b+c+d;\n if e==0{\n writeln!(out, \"0\");\n }else if e==4 {\n writeln!(out, \"2\");\n }else{\n writeln!(out, \"1\");\n }\n}\n\nfn main() {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut sc = input::In::new(&s);\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n let t = 1;\n let t: usize = sc.read();\n for _ in 0..t {\n test_case(&mut sc, &mut out);\n }\n}\n\nmod input {\n use std::str::FromStr;\n use std::str::SplitWhitespace;\n pub struct In<'a> {\n iter: SplitWhitespace<'a>,\n }\n impl<'a> In<'a> {\n pub fn new(s: &'a String) -> Self {\n Self {\n iter: s.split_whitespace(),\n }\n }\n pub fn read(&mut self) -> T {\n self.iter.next().unwrap().parse::().ok().unwrap()\n }\n\n pub fn read_bytes(&mut self) -> Vec {\n self.iter.next().unwrap().bytes().collect()\n }\n pub fn read_chars(&mut self) -> Vec {\n self.iter.next().unwrap().chars().collect()\n }\n pub fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "97574891fb8cacb77f5ac9eda19151ad", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::fmt::{Display};\nuse std::io::{stdout, stdin, Write, BufReader, BufWriter, BufRead, Stdin, Stdout};\n\nfn main() -> () {\n let io = &mut IO::new();\n\n for _ in 0..io.read_i32() {\n let first_sum = io.read_array_i32(\" \").iter().sum::();\n let second_sum = io.read_array_i32(\" \").iter().sum::();\n\n io.write(match first_sum + second_sum {\n 0 => 0,\n 1..=3 => 1,\n _ => 2\n }, \"\\n\");\n }\n\n}\n\n\nstruct IO {\n reader: BufReader,\n writer: BufWriter,\n}\n\nimpl Drop for IO {\n fn drop(&mut self) {\n self.flush();\n }\n}\n\nimpl IO {\n pub fn new() -> IO {\n IO {\n reader: BufReader::new(stdin()),\n writer: BufWriter::new(stdout()),\n }\n }\n\n pub fn read_i32(&mut self) -> i32 {\n let mut res = String::new();\n self.reader.read_line(&mut res).expect(\"error read\");\n return res.trim().parse().unwrap();\n }\n\n pub fn read_array_i32(&mut self, split: &str) -> Vec {\n let mut res = String::new();\n self.reader.read_line(&mut res).expect(\"error read\");\n return res.trim().split(split).map(|x| x.parse().expect(\"not is i32\")).collect::>();\n }\n\n pub fn read_array_i64(&mut self, split: &str) -> Vec {\n let mut res = String::new();\n self.reader.read_line(&mut res).expect(\"error read\");\n return res.trim().split(split).map(|x| x.parse().expect(\"not is i64\")).collect::>();\n }\n\n pub fn read_str(&mut self) -> String {\n let mut res = String::new();\n self.reader.read_line(&mut res).expect(\"error read\");\n res\n }\n\n pub fn write(&mut self, value: T, end: &str) {\n self.writer.write(value.to_string().as_bytes()).expect(\"error write\");\n self.writer.write(end.as_bytes()).expect(\"error write\");\n }\n\n pub fn flush(&mut self) {\n self.writer.flush().expect(\"error flush\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6ed359715f6bdbf4672ecdeddabaf27c", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer)\n .expect(\"Failed to read line\");\n\n let num_letters = buffer.trim().parse::().expect(\"parse error\");\n if num_letters == 0 {\n println!(\"0\");\n return;\n }\n\n buffer.clear();\n io::stdin().read_line(&mut buffer)\n .expect(\"Failed to read line\");\n let mut splitted: Vec<&str> = buffer.trim().split('W').collect();\n splitted.retain(|&i|i != \"\");\n println!(\"{}\", splitted.len());\n\n for sub in &splitted {\n print!(\"{} \", sub.len());\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0ed7e4122e9f23e354b844c31522c805", "src_uid": "e4b3a2707ba080b93a152f4e6e983973", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input: String = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n let amount = input.trim().parse::().unwrap();\n\n input.clear();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n let vec:Vec = input.trim().chars().collect::>();\n let mut crossword: Vec = vec![];\n let mut max_len = i32::default();\n\n for _item in &vec {\n match _item {\n 'B' => max_len += 1,\n 'W' => {\n if max_len > 0 {\n crossword.push(max_len);\n max_len = 0;\n }\n },\n _ => println!(\"ERROR::letter not exist\")\n }\n\n }\n\n if max_len > 0 {\n crossword.push(max_len);\n max_len = 0;\n }\n\n match crossword.len() {\n 0 => println!(\"0\"),\n _ => {\n println!(\"{}\", crossword.len());\n for _item in &crossword {\n print!(\"{} \", _item);\n }\n }\n }\n\n\n\n //println!(\"{:?}\", vec);\n //println!(\"{:?}\", crossword);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "fc88605967b81a0b9b8be3990ee29de7", "src_uid": "e4b3a2707ba080b93a152f4e6e983973", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n readln!();\n let s = readln!();\n let mut res : Vec = Vec::new();\n let mut i = 0;\n let n = s.len();\n let z = s.into_bytes();\n while i < n {\n if z[i] == 'W' as u8 {\n i+=1;\n } else {\n let st = i;\n while i < n && z[i] == 'B' as u8 {\n i+=1;\n }\n res.push((i-st) as i32);\n }\n }\n println!(\"{}\",res.len());\n println!(\"{}\",res.iter().map(|x|x.to_string()).collect::>().join(\" \"));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "74b8fd40f15617740d373f9163d7aabd", "src_uid": "e4b3a2707ba080b93a152f4e6e983973", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n input.i();\n let a = input.sl().split(|a| a == 'W').map(|a| a.len()).filter(|&a| a > 0).collect::>();\n println!(\"{}\", a.len());\n for x in a {\n print!(\"{} \", x);\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9502b62ac1cc7472ab78ca2846cc8833", "src_uid": "e4b3a2707ba080b93a152f4e6e983973", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! debug(\n ($($arg:tt)*) => { {\n let r = writeln!(&mut ::std::io::stderr(), $($arg)*);\n r.expect(\"failed printing to stderr\");\n } }\n);\n\nstruct Scanner {\n buffer : std::collections::VecDeque\n}\n\nimpl Scanner {\n\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn process(&mut self) -> String {\n if self.buffer.len() == 0 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n for word in input.split_whitespace() {\n self.buffer.push_back(word.to_string())\n }\n }\n\n self.buffer.pop_front().unwrap()\n }\n\n fn next(&mut self) -> T {\n self.process().parse::().ok().unwrap()\n }\n\n fn next_char(&mut self) -> char {\n self.process().into_bytes()[0] as char\n }\n}\n\nfn main() {\n let mut sin = Scanner::new();\n let n : usize = sin.next();\n let x : String = sin.next();\n\n let mut count = 0;\n let mut counts : Vec = Vec::new();\n\n for i in x.chars()\n {\n if i == 'B' {\n count += 1;\n } else if i == 'W' && count != 0 {\n counts.push(count);\n count = 0;\n }\n }\n\n if count != 0 {\n counts.push(count);\n }\n\n println!(\"{}\", counts.len());\n if counts.len() > 0 {\n print!(\"{}\", counts[0]);\n for i in 1..counts.len() {\n print!(\" {}\", counts[i]);\n }\n println!(\"\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e9586b62a684f6712ca61e54eb3dc61e", "src_uid": "e4b3a2707ba080b93a152f4e6e983973", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let _n: usize = scan.next();\n let input: Vec = scan.next::().chars().take(_n).collect();\n let mut results: Vec = vec![];\n let mut count: usize = 0;\n for &item in input.iter() {\n if item == 'B' {\n count += 1;\n }\n if item == 'W' {\n if count != 0 {\n results.push(count);\n }\n count = 0;\n }\n }\n if count != 0 {\n results.push(count);\n }\n println!(\"{}\", results.len());\n for &item in results.iter() {\n print!(\"{} \", item);\n }\n println!();\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "96a2ef434fbeacbbd811080a8ca9479c", "src_uid": "e4b3a2707ba080b93a152f4e6e983973", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::collections::{HashSet, HashMap};\nuse std::cmp::{min,max};\nuse std::io;\nuse std::str;\n \nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: vec![], buf_iter: \"\".split_whitespace() }\n }\n fn token(&mut self) -> T {\n loop {\n // If we have another token in this line\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\"); // calls parse::() on the current token and returns it.\n }\n\n // If we do not have another token in the line then\n // we should go to the next line.\n self.buf_str.clear(); // empty out the buffer that holds the current line\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\"); // read a new line into the buffer\n\n // create an iterator over the white space delimited strings of the current line\n self.buf_iter = unsafe { \n let slice = str::from_utf8_unchecked(&self.buf_str); // makes a string from utf8 characters in the current line\n std::mem::transmute(slice.split_whitespace()) // transmutes the memory in place \n }\n }\n }\n}\n \nfn solve(scan: &mut Scanner, out: &mut W) {\n let n = scan.token::();\n let mut s = vec![];\n for _ in 0..n {\n s.push(scan.token::());\n }\n let mut max: u8 = 0;\n\n for i in 0..n {\n for j in i..n {\n let mut curr = 0;\n for k in 0..n {\n curr += {\n if k < i {s[k]}\n else if k >= i && k <= j {1 - s[k]}\n else {s[k]}\n }\n }\n max = u8::max(curr, max);\n }\n }\n writeln!(out, \"{}\", max);\n}\n \nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "f640ea7ef10c8bc2c59c69e319cc9b56", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::max;\nuse std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn max_ones(xs : &Vec) -> i8 {\n let s = xs.iter().sum::();\n let mut ys = vec![];\n let one = 1;\n let minus_one = -1;\n for &x in xs.iter() {\n if x == 0 {\n ys.push(one);\n } else {\n ys.push(minus_one);\n }\n }\n let mut max_upto_i = ys[0];\n let mut max_ending_at_i = ys[0];\n for i in 1 .. ys.len() {\n let y = ys[i];\n max_ending_at_i = max(y, max_ending_at_i + y);\n max_upto_i = max(max_ending_at_i, max_upto_i);\n }\n s + max_upto_i\n}\n\nfn main() {\n let stdin = io::stdin();\n let _ : usize = read_t(&stdin);\n let mut xs = vec![]; \n read_ts(&stdin, &mut xs);\n let result = max_ones(&xs);\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "89512e8f0a4ff05c17b2fd8f30bd9f68", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use rand::Rng;\n\nuse std::collections::*;\nuse std::io;\n\nfn trim_newline(s: &mut String) {\n if s.ends_with('\\n') {\n s.pop();\n if s.ends_with('\\r') {\n s.pop();\n }\n }\n}\nmacro_rules! parse_input {\n ($t:ident) => {{\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n trim_newline(&mut input_line);\n input_line.parse::<$t>().unwrap()\n }};\n}\n\nmacro_rules! split_input {\n ($t:ident) => {{\n parse_input!(String)\n .split(\" \")\n .map(|z| z.parse::<$t>().unwrap())\n .collect::>()\n }};\n}\n\nfn main() {\n let a = parse_input!(u64);\n let b = split_input!(u64);\n let mut best = 0;\n let mut cur = 0;\n let mut ones: u64 = b.iter().sum();\n if ones as usize == b.len() {\n ones -= 1;\n }\n for p in b.iter() {\n if *p == 0 {\n cur += 1;\n best = std::cmp::max(best, cur);\n } else if cur > 0 {\n cur -= 1;\n }\n }\n\n println!(\"{}\", ones + best);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "c09efcc0d5b5ffada74fad55a2bbc55e", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::max;\nuse std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn max_ones(ys : &Vec) -> i8 {\n let one = 1;\n let minus_one = -1;\n let mut s = ys[0];\n let y_0 = if ys[0] == 0 { one } else { minus_one };\n let mut max_upto_i = y_0;\n let mut max_ending_at_i = y_0;\n for i in 1 .. ys.len() {\n let ys_i = ys[i];\n s = s + ys_i;\n let y = if ys_i == 0 { one } else { minus_one };\n max_ending_at_i = max(y, max_ending_at_i + y);\n max_upto_i = max(max_ending_at_i, max_upto_i);\n }\n s + max_upto_i\n}\n\nfn main() {\n let stdin = io::stdin();\n let _ : usize = read_t(&stdin);\n let mut xs = vec![]; \n read_ts(&stdin, &mut xs);\n let result = max_ones(&xs);\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "18a27e72b42ab64cd66eef24c2922221", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn solve() {\n let n: usize = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim_end().parse().unwrap()\n };\n\n let a: Vec = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.split_whitespace().map(|s| s.parse().unwrap()).collect()\n };\n\n let mut ans = 0;\n for i in 0..n {\n for j in i..n {\n let mut tmp = a.clone();\n for k in i..j + 1 {\n tmp[k] = 1 - tmp[k];\n }\n ans = ans.max(tmp.iter().sum());\n }\n }\n\n println!(\"{}\", ans);\n}\n\nfn main() {\n solve();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "6763ba8d9752c6a598986c34d1d70610", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n inputv! {\n n:usize,\n }\n let a = input_vector::();\n let mut ans = 0;\n let one_count = a.iter().filter(|&&q| q == 1).count();\n for i in 0..n {\n for j in i + 1..=n {\n let zero = a[i..j].iter().filter(|&&q| q == 0).count();\n let one = j - i - zero;\n ans = std::cmp::max(ans, one_count + zero - one);\n }\n }\n println!(\"{}\", ans);\n}\n\n//https://github.com/manta1130/competitive-template-rs\n\nuse input::*;\n\npub mod input {\n use std::cell::RefCell;\n use std::io;\n pub const SPLIT_DELIMITER: char = ' ';\n pub use std::io::prelude::*;\n\n #[macro_export]\n thread_local! {\n pub static INPUT_BUFFER:RefCell>=RefCell::new(std::collections::VecDeque::new());\n }\n\n #[macro_export]\n macro_rules! input_internal {\n ($x:ident : $t:ty) => {\n INPUT_BUFFER.with(|p| {\n if p.borrow().len() == 0 {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str\n .split(SPLIT_DELIMITER)\n .map(|q| q.to_string())\n .collect::>();\n p.borrow_mut().append(&mut split_result_iter)\n }\n });\n let mut buf_split_result = String::new();\n INPUT_BUFFER.with(|p| buf_split_result = p.borrow_mut().pop_front().unwrap());\n let $x: $t = buf_split_result.parse().unwrap();\n };\n (mut $x:ident : $t:ty) => {\n INPUT_BUFFER.with(|p| {\n if p.borrow().len() == 0 {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str\n .split(SPLIT_DELIMITER)\n .map(|q| q.to_string())\n .collect::>();\n p.borrow_mut().append(&mut split_result_iter)\n }\n });\n let mut buf_split_result = String::new();\n INPUT_BUFFER.with(|p| buf_split_result = p.borrow_mut().pop_front().unwrap());\n let mut $x: $t = buf_split_result.parse().unwrap();\n };\n }\n\n #[macro_export]\n macro_rules! inputv {\n ($i:ident : $t:ty) => {\n input_internal!{$i : $t}\n };\n (mut $i:ident : $t:ty) => {\n input_internal!{mut $i : $t}\n };\n ($i:ident : $t:ty $(,)*) => {\n input_internal!{$i : $t}\n };\n (mut $i:ident : $t:ty $(,)*) => {\n input_internal!{mut $i : $t}\n };\n (mut $i:ident : $t:ty,$($q:tt)*) => {\n input_internal!{mut $i : $t}\n inputv!{$($q)*}\n };\n ($i:ident : $t:ty,$($q:tt)*) => {\n input_internal!{$i : $t}\n inputv!{$($q)*}\n };\n}\n\n pub fn input_all() {\n INPUT_BUFFER.with(|p| {\n if p.borrow().len() == 0 {\n let mut temp_str = String::new();\n std::io::stdin().read_to_string(&mut temp_str).unwrap();\n let mut split_result_iter = temp_str\n .split_whitespace()\n .map(|q| q.to_string())\n .collect::>();\n p.borrow_mut().append(&mut split_result_iter)\n }\n });\n }\n\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "8d991fd2fa15ac4e4b63d7f168d8b23d", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let arr: Vec = scan.next_n(n);\n let allones: usize = arr.iter().filter(|&&x| x==1).count();\n let total: isize = arr.iter().sum();\n // convert to an array in which Kadane can be used\n let arr2: Vec = arr.into_iter().map(|x| if x==1 { -1 } else { 1 }).collect();\n let mut cnt: isize = 0;\n let mut maxcnt: isize = 0;\n if allones == n {\n println!(\"{}\", total-1);\n return;\n }\n for i in 0..n {\n cnt += arr2[i];\n if cnt < 0 { cnt = 0; }\n maxcnt = maxcnt.max(cnt);\n }\n println!(\"{}\", total + maxcnt);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "993b5ae535037441b66f53951ac9cd71", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn num_of_1_before(i: &Vec, idx: usize) -> u32 {\n i.iter().take(idx).sum()\n}\n\nfn num_of_1_after(i: &Vec, idx: usize) -> u32 {\n i.iter().skip(idx + 1).sum()\n}\n\nfn max_num_of_1_flipped_after(i: &Vec, idx: usize) -> u32 {\n if 1 == *i.iter().nth(idx).unwrap() {\n return 0;\n }\n let targets = i.iter().skip(idx);\n let mut current_score = 0;\n let mut scores = Vec::new();\n for (local_index, value) in targets.enumerate() {\n if *value == 0 {\n current_score = current_score + 1;\n }\n scores.push(current_score + num_of_1_after(i, idx + local_index));\n }\n scores.into_iter().max().unwrap_or(0)\n}\n\nfn max_score(i: &Vec, idx: usize) -> u32 {\n num_of_1_before(i, idx) + max_num_of_1_flipped_after(i, idx)\n}\n\nfn main() {\n input! {\n n: usize,\n a: [u32; n],\n }\n\n let v = Vec::from(a);\n\n println!(\n \"{}\",\n (0..n).map(|idx| max_score(&v, idx)).max().unwrap_or(0)\n );\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "implementation"], "code_uid": "d0ece4e8e5a7e206d04e0c58f498784c", "src_uid": "9b543e07e805fe1dd8fa869d5d7c8b99", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\nfn mod_factorials(maxn: usize) -> Vec {\n let mut res = vec![ModInt::default(); maxn+1];\n res[0] = 1.into();\n for i in 1..=maxn {\n res[i] = res[i-1] * i\n }\n return res;\n}\n\nstruct ModCombinatorics {\n factorials: Vec,\n inv_factorials: Vec\n}\n#[allow(non_snake_case)]\nimpl ModCombinatorics {\n fn new(maxn: usize) -> Self {\n let factorials = mod_factorials(maxn);\n let mut inv = vec![ModInt::default(); maxn+1];\n inv[maxn] = factorials[maxn].inv();\n for i in (1..=maxn).rev() {\n inv[i-1] = inv[i] * i;\n }\n Self { factorials, inv_factorials: inv }\n }\n #[inline]\n fn factorial(&self, n: usize) -> ModInt { self.factorials[n] }\n #[inline]\n fn inv_factorial(&self, n: usize) -> ModInt { self.inv_factorials[n] }\n fn P(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(n-k) }\n }\n fn C(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(k) * self.inv_factorial(n-k) }\n }\n\n // multi-choose, be sure to adjust maxn accordingly\n fn M(&self, n: usize, k: usize) -> ModInt {\n if k == 0 { 1.into() } else { self.C(n + k - 1, k) }\n }\n}\n\npub struct ModFft {\n n_inv: ModInt,\n w: Vec\n}\nimpl ModFft {\n pub fn primitive_root() -> ModInt { ModInt::raw(3) /* for 998244353 */}\n pub fn good_len(deg: usize) -> usize { (deg + 1).next_power_of_two() }\n pub fn prepare(arr: &[ModInt], deg: usize) -> Vec { \n let n = Self::good_len(deg);\n let mut res = Vec::with_capacity(n);\n res.extend_from_slice(arr);\n res.resize(n, ModInt::raw(0));\n res\n }\n\n pub fn new(max_deg: usize) -> Self {\n let n = Self::good_len(max_deg);\n Self {\n n_inv: ModInt::new(n).inv(),\n w: ModInt::pow_vec(Self::primitive_root().pow((ModInt::modulus() - 1) as u64 / n as u64), n-1)\n }\n }\n\n pub fn transform(&self, a: &mut [ModInt]) { self.transform_impl(a, false) }\n pub fn transform_inv(&self, a: &mut [ModInt]) { self.transform_impl(a, true) }\n\n pub fn fft(&self, a: &[ModInt]) -> Vec { self.fft_deg(a, a.len() - 1) }\n pub fn fft_deg(&self, a: &[ModInt], deg: usize) -> Vec { \n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n a\n }\n pub fn fft_inv(&self, a: &[ModInt]) -> Vec { \n let mut a = Self::prepare(a, a.len() - 1);\n self.transform_inv(&mut a);\n a\n }\n\n pub fn max_deg(&self) -> usize { self.w.len() - 1 }\n\n #[inline] fn transform_impl(&self, a: &mut [ModInt], invert: bool) {\n let sz = a.len();\n if sz <= 1 { return }\n let n = self.w.len();\n debug_assert!(sz <= n && sz.is_power_of_two(), \"Array size {} must be <= {} and a power of 2\", sz, n);\n let sh = sz.leading_zeros() + 1;\n\n for i in 0..sz {\n let j = i.reverse_bits() >> sh;\n if i < j { a.swap(i, j) }\n }\n\n let mut len = 2usize;\n let mut ang = (n >> 1) as isize;\n if invert { ang = -ang; }\n while len <= sz {\n let h = len >> 1;\n for i in (0..sz).step_by(len) {\n let mut k = 0usize;\n for j in i..i+h {\n let u = a[j];\n let v = a[j+h] * self.w[k];\n a[j] = u + v;\n a[j+h] = u - v;\n k = k.wrapping_add(ang as usize) & (n-1);\n }\n }\n len <<= 1;\n ang >>= 1;\n }\n\n if invert {\n let sz_inv = self.n_inv * (n / sz);\n for i in 0..sz { a[i] *= sz_inv; }\n }\n }\n\n pub fn mul(&self, a: &[ModInt], b: &[ModInt]) -> Vec {\n if a.is_empty() || b.is_empty() { return vec![]; }\n let deg = a.len() + b.len() - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n let mut b = Self::prepare(b, deg);\n self.transform(&mut a);\n self.transform(&mut b);\n for i in 0..a.len() { a[i] *= b[i]; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn sq(&self, a: &[ModInt]) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = a.len() * 2 - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { let ai = a[i]; a[i] = ai * ai; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn pow(&self, a: &[ModInt], exp: usize) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = (a.len() - 1) * exp;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { a[i] = a[i].pow(exp as u64) }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn product(&self, mut polys: VecDeque>) -> Vec {\n while let Some(p) = polys.pop_front() {\n if let Some(q) = polys.pop_front() {\n polys.push_back(self.mul(&p, &q));\n } else { return p; }\n }\n\n vec![ModInt::new(1)]\n }\n}\n\nstruct FactorMap {\n map: Vec\n}\nimpl FactorMap {\n pub fn new(limit: usize) -> FactorMap {\n let limit = limit + 1;\n let mut map = vec![0; limit >> 1];\n for p in (3..limit).step_by(2) {\n if map[p >> 1] != 0 { continue; }\n let sq = p * p;\n if sq >= limit { break; }\n for i in (sq..limit).step_by(p*2) {\n if map[i >> 1] == 0 { map[i >> 1] = p as u32; }\n }\n }\n\n FactorMap { map }\n }\n\n pub fn least_prime_factor(&self, n: usize) -> usize {\n if n & 1 == 0 { return 2; }\n let p = self.map[n >> 1] as usize;\n if p == 0 { n } else { p }\n }\n\n pub fn factorize(&self, n: usize) -> FactorIterator {\n FactorIterator { fm: self, n }\n }\n\n pub fn is_prime(&self, n: usize) -> bool { n > 1 && self.least_prime_factor(n) == n }\n\n /// lists divisors, unsorted\n pub fn divisors(&self, mut n: usize) -> Vec {\n let mut res = vec![1];\n\n while n > 1 {\n let p = self.least_prime_factor(n);\n let mut x = 0;\n loop {\n n /= p;\n x += 1;\n if p != self.least_prime_factor(n) { break; }\n }\n for i in 0..res.len() {\n let mut a = res[i];\n for _ in 0..x {\n a *= p;\n res.push(a);\n }\n }\n }\n\n res\n }\n\n pub fn new_with_mobius(limit: usize) -> (FactorMap, Vec) {\n let fm = Self::new(limit);\n let mut mu = vec![1i8; limit + 1];\n mu[0] = 0;\n\n for i in 2..=limit {\n let p = fm.least_prime_factor(i);\n mu[i] = if p == fm.least_prime_factor(i/p) { 0 } else { -mu[i/p] };\n }\n\n (fm, mu)\n }\n}\nstruct FactorIterator<'a> {\n fm: &'a FactorMap,\n n: usize\n}\nimpl Iterator for FactorIterator<'_> {\n type Item = usize;\n\n fn next(&mut self) -> Option {\n if self.n <= 1 { return None; }\n let p = self.fm.least_prime_factor(self.n);\n self.n /= p;\n Some(p)\n }\n\n fn size_hint(&self) -> (usize, Option) { (0, Some(32)) }\n}\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let k = read!(usize);\n\n let mc = ModCombinatorics::new(n);\n let ff = ModFft::new(min(n, k) * 2);\n let mu = FactorMap::new_with_mobius(n).1;\n\n let mut m = 0usize;\n let mut A = mi(0);\n\n let mut ans = mi(0);\n if n == 1 || k == 1 { ans = mi(1); }\n else {\n for i in 1..=n {\n if mu[i] == 0 { continue; }\n let mn = n.div_ceil(i);\n if m != mn {\n m = mn;\n let l = min(m, k);\n\n let P = veci!(l+1, j: if j & 1 == 1 { -mc.inv_factorial(j) } else { mc.inv_factorial(j) });\n let Q = veci!(l+1, j: mi(j).pow(m as _) * mc.inv_factorial(j));\n let R = ff.mul(&P, &Q);\n A = R[2..=l].iter().sum();\n }\n if mu[i] == 1 { ans += A; } else { ans -= A; }\n }\n }\n\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "number theory", "combinatorics", "fft"], "code_uid": "e5bafe478f21f09bf8bdca7ddc4d9df2", "src_uid": "eb9d24070cc5b347d020189d803628ae", "difficulty": 2900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\nfn mod_factorials(maxn: usize) -> Vec {\n let mut res = vec![ModInt::default(); maxn+1];\n res[0] = 1.into();\n for i in 1..=maxn {\n res[i] = res[i-1] * i\n }\n return res;\n}\n\nstruct ModCombinatorics {\n factorials: Vec,\n inv_factorials: Vec\n}\n#[allow(non_snake_case)]\nimpl ModCombinatorics {\n fn new(maxn: usize) -> Self {\n let factorials = mod_factorials(maxn);\n let mut inv = vec![ModInt::default(); maxn+1];\n inv[maxn] = factorials[maxn].inv();\n for i in (1..=maxn).rev() {\n inv[i-1] = inv[i] * i;\n }\n Self { factorials, inv_factorials: inv }\n }\n #[inline]\n fn factorial(&self, n: usize) -> ModInt { self.factorials[n] }\n #[inline]\n fn inv_factorial(&self, n: usize) -> ModInt { self.inv_factorials[n] }\n fn P(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(n-k) }\n }\n fn C(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(k) * self.inv_factorial(n-k) }\n }\n\n // multi-choose, be sure to adjust maxn accordingly\n fn M(&self, n: usize, k: usize) -> ModInt {\n if k == 0 { 1.into() } else { self.C(n + k - 1, k) }\n }\n}\n\npub struct ModFft {\n n_inv: ModInt,\n w: Vec\n}\nimpl ModFft {\n pub fn primitive_root() -> ModInt { ModInt::raw(3) /* for 998244353 */}\n pub fn good_len(deg: usize) -> usize { (deg + 1).next_power_of_two() }\n pub fn prepare(arr: &[ModInt], deg: usize) -> Vec { \n let n = Self::good_len(deg);\n let mut res = Vec::with_capacity(n);\n res.extend_from_slice(arr);\n res.resize(n, ModInt::raw(0));\n res\n }\n\n pub fn new(max_deg: usize) -> Self {\n let n = Self::good_len(max_deg);\n Self {\n n_inv: ModInt::new(n).inv(),\n w: ModInt::pow_vec(Self::primitive_root().pow((ModInt::modulus() - 1) as u64 / n as u64), n-1)\n }\n }\n\n pub fn transform(&self, a: &mut [ModInt]) { self.transform_impl(a, false) }\n pub fn transform_inv(&self, a: &mut [ModInt]) { self.transform_impl(a, true) }\n\n pub fn fft(&self, a: &[ModInt]) -> Vec { self.fft_deg(a, a.len() - 1) }\n pub fn fft_deg(&self, a: &[ModInt], deg: usize) -> Vec { \n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n a\n }\n pub fn fft_inv(&self, a: &[ModInt]) -> Vec { \n let mut a = Self::prepare(a, a.len() - 1);\n self.transform_inv(&mut a);\n a\n }\n\n pub fn max_deg(&self) -> usize { self.w.len() - 1 }\n\n #[inline] fn transform_impl(&self, a: &mut [ModInt], invert: bool) {\n let sz = a.len();\n if sz <= 1 { return }\n let n = self.w.len();\n debug_assert!(sz <= n && sz.is_power_of_two(), \"Array size {} must be <= {} and a power of 2\", sz, n);\n let sh = sz.leading_zeros() + 1;\n\n for i in 0..sz {\n let j = i.reverse_bits() >> sh;\n if i < j { a.swap(i, j) }\n }\n\n let mut len = 2usize;\n let mut ang = (n >> 1) as isize;\n if invert { ang = -ang; }\n while len <= sz {\n let h = len >> 1;\n for i in (0..sz).step_by(len) {\n let mut k = 0usize;\n for j in i..i+h {\n let u = a[j];\n let v = a[j+h] * self.w[k];\n a[j] = u + v;\n a[j+h] = u - v;\n k = k.wrapping_add(ang as usize) & (n-1);\n }\n }\n len <<= 1;\n ang >>= 1;\n }\n\n if invert {\n let sz_inv = self.n_inv * (n / sz);\n for i in 0..sz { a[i] *= sz_inv; }\n }\n }\n\n pub fn mul(&self, a: &[ModInt], b: &[ModInt]) -> Vec {\n if a.is_empty() || b.is_empty() { return vec![]; }\n let deg = a.len() + b.len() - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n let mut b = Self::prepare(b, deg);\n self.transform(&mut a);\n self.transform(&mut b);\n for i in 0..a.len() { a[i] *= b[i]; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn sq(&self, a: &[ModInt]) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = a.len() * 2 - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { let ai = a[i]; a[i] = ai * ai; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn pow(&self, a: &[ModInt], exp: usize) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = (a.len() - 1) * exp;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { a[i] = a[i].pow(exp as u64) }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn product(&self, mut polys: VecDeque>) -> Vec {\n while let Some(p) = polys.pop_front() {\n if let Some(q) = polys.pop_front() {\n polys.push_back(self.mul(&p, &q));\n } else { return p; }\n }\n\n vec![ModInt::new(1)]\n }\n}\n\nstruct FactorMap {\n map: Vec\n}\nimpl FactorMap {\n pub fn new(limit: usize) -> FactorMap {\n let limit = limit + 1;\n let mut map = vec![0; limit >> 1];\n for p in (3..limit).step_by(2) {\n if map[p >> 1] != 0 { continue; }\n let sq = p * p;\n if sq >= limit { break; }\n for i in (sq..limit).step_by(p*2) {\n if map[i >> 1] == 0 { map[i >> 1] = p as u32; }\n }\n }\n\n FactorMap { map }\n }\n\n pub fn least_prime_factor(&self, n: usize) -> usize {\n if n & 1 == 0 { return 2; }\n let p = self.map[n >> 1] as usize;\n if p == 0 { n } else { p }\n }\n\n pub fn factorize(&self, n: usize) -> FactorIterator {\n FactorIterator { fm: self, n }\n }\n\n pub fn is_prime(&self, n: usize) -> bool { n > 1 && self.least_prime_factor(n) == n }\n\n /// lists divisors, unsorted\n pub fn divisors(&self, mut n: usize) -> Vec {\n let mut res = vec![1];\n\n while n > 1 {\n let p = self.least_prime_factor(n);\n let mut x = 0;\n loop {\n n /= p;\n x += 1;\n if p != self.least_prime_factor(n) { break; }\n }\n for i in 0..res.len() {\n let mut a = res[i];\n for _ in 0..x {\n a *= p;\n res.push(a);\n }\n }\n }\n\n res\n }\n\n pub fn new_with_mobius(limit: usize) -> (FactorMap, Vec) {\n let fm = Self::new(limit);\n let mut mu = vec![1i8; limit + 1];\n mu[0] = 0;\n\n for i in 2..=limit {\n let p = fm.least_prime_factor(i);\n mu[i] = if p == fm.least_prime_factor(i/p) { 0 } else { -mu[i/p] };\n }\n\n (fm, mu)\n }\n}\nstruct FactorIterator<'a> {\n fm: &'a FactorMap,\n n: usize\n}\nimpl Iterator for FactorIterator<'_> {\n type Item = usize;\n\n fn next(&mut self) -> Option {\n if self.n <= 1 { return None; }\n let p = self.fm.least_prime_factor(self.n);\n self.n /= p;\n Some(p)\n }\n\n fn size_hint(&self) -> (usize, Option) { (0, Some(32)) }\n}\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let k = read!(usize);\n\n let mut ans = mi(0);\n if min(n, k) == 1 { ans = mi(1); }\n else {\n let mc = ModCombinatorics::new(n);\n let ff = ModFft::new(min(n, k) * 2);\n let mu = FactorMap::new_with_mobius(n).1;\n\n let mut m = 0usize;\n let mut A = mi(0);\n\n for i in 1..=n {\n if mu[i] == 0 { continue; }\n let mn = n.div_ceil(i);\n if m != mn {\n m = mn;\n let l = min(m, k);\n\n let P = veci!(l+1, j: if j & 1 == 1 { -mc.inv_factorial(j) } else { mc.inv_factorial(j) });\n let Q = veci!(l+1, j: mi(j).pow(m as _) * mc.inv_factorial(j));\n let R = ff.mul(&P, &Q);\n A = R[2..=l].iter().sum();\n }\n if mu[i] == 1 { ans += A; } else { ans -= A; }\n }\n }\n\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "number theory", "combinatorics", "fft"], "code_uid": "bab334aff3b7a5e71636be64602b1a54", "src_uid": "eb9d24070cc5b347d020189d803628ae", "difficulty": 2900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\nfn mod_factorials(maxn: usize) -> Vec {\n let mut res = vec![ModInt::default(); maxn+1];\n res[0] = 1.into();\n for i in 1..=maxn {\n res[i] = res[i-1] * i\n }\n return res;\n}\n\nstruct ModCombinatorics {\n factorials: Vec,\n inv_factorials: Vec\n}\n#[allow(non_snake_case)]\nimpl ModCombinatorics {\n fn new(maxn: usize) -> Self {\n let factorials = mod_factorials(maxn);\n let mut inv = vec![ModInt::default(); maxn+1];\n inv[maxn] = factorials[maxn].inv();\n for i in (1..=maxn).rev() {\n inv[i-1] = inv[i] * i;\n }\n Self { factorials, inv_factorials: inv }\n }\n #[inline]\n fn factorial(&self, n: usize) -> ModInt { self.factorials[n] }\n #[inline]\n fn inv_factorial(&self, n: usize) -> ModInt { self.inv_factorials[n] }\n fn P(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(n-k) }\n }\n fn C(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(k) * self.inv_factorial(n-k) }\n }\n\n // multi-choose, be sure to adjust maxn accordingly\n fn M(&self, n: usize, k: usize) -> ModInt {\n if k == 0 { 1.into() } else { self.C(n + k - 1, k) }\n }\n}\n\npub struct ModFft {\n n_inv: ModInt,\n w: Vec\n}\nimpl ModFft {\n pub fn primitive_root() -> ModInt { ModInt::raw(3) /* for 998244353 */}\n pub fn good_len(deg: usize) -> usize { (deg + 1).next_power_of_two() }\n pub fn prepare(arr: &[ModInt], deg: usize) -> Vec { \n let n = Self::good_len(deg);\n let mut res = Vec::with_capacity(n);\n res.extend_from_slice(arr);\n res.resize(n, ModInt::raw(0));\n res\n }\n\n pub fn new(max_deg: usize) -> Self {\n let n = Self::good_len(max_deg);\n Self {\n n_inv: ModInt::new(n).inv(),\n w: ModInt::pow_vec(Self::primitive_root().pow((ModInt::modulus() - 1) as u64 / n as u64), n-1)\n }\n }\n\n pub fn transform(&self, a: &mut [ModInt]) { self.transform_impl(a, false) }\n pub fn transform_inv(&self, a: &mut [ModInt]) { self.transform_impl(a, true) }\n\n pub fn fft(&self, a: &[ModInt]) -> Vec { self.fft_deg(a, a.len() - 1) }\n pub fn fft_deg(&self, a: &[ModInt], deg: usize) -> Vec { \n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n a\n }\n pub fn fft_inv(&self, a: &[ModInt]) -> Vec { \n let mut a = Self::prepare(a, a.len() - 1);\n self.transform_inv(&mut a);\n a\n }\n\n pub fn max_deg(&self) -> usize { self.w.len() - 1 }\n\n #[inline] fn transform_impl(&self, a: &mut [ModInt], invert: bool) {\n let sz = a.len();\n if sz <= 1 { return }\n let n = self.w.len();\n debug_assert!(sz <= n && sz.is_power_of_two(), \"Array size {} must be <= {} and a power of 2\", sz, n);\n let sh = sz.leading_zeros() + 1;\n\n for i in 0..sz {\n let j = i.reverse_bits() >> sh;\n if i < j { a.swap(i, j) }\n }\n\n let mut len = 2usize;\n let mut ang = (n >> 1) as isize;\n if invert { ang = -ang; }\n while len <= sz {\n let h = len >> 1;\n for i in (0..sz).step_by(len) {\n let mut k = 0usize;\n for j in i..i+h {\n let u = a[j];\n let v = a[j+h] * self.w[k];\n a[j] = u + v;\n a[j+h] = u - v;\n k = k.wrapping_add(ang as usize) & (n-1);\n }\n }\n len <<= 1;\n ang >>= 1;\n }\n\n if invert {\n let sz_inv = self.n_inv * (n / sz);\n for i in 0..sz { a[i] *= sz_inv; }\n }\n }\n\n pub fn mul(&self, a: &[ModInt], b: &[ModInt]) -> Vec {\n if a.is_empty() || b.is_empty() { return vec![]; }\n let deg = a.len() + b.len() - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n let mut b = Self::prepare(b, deg);\n self.transform(&mut a);\n self.transform(&mut b);\n for i in 0..a.len() { a[i] *= b[i]; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn sq(&self, a: &[ModInt]) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = a.len() * 2 - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { let ai = a[i]; a[i] = ai * ai; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn pow(&self, a: &[ModInt], exp: usize) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = (a.len() - 1) * exp;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { a[i] = a[i].pow(exp as u64) }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn product(&self, mut polys: VecDeque>) -> Vec {\n while let Some(p) = polys.pop_front() {\n if let Some(q) = polys.pop_front() {\n polys.push_back(self.mul(&p, &q));\n } else { return p; }\n }\n\n vec![ModInt::new(1)]\n }\n}\n\nstruct FactorMap {\n map: Vec\n}\nimpl FactorMap {\n pub fn new(limit: usize) -> FactorMap {\n let limit = limit + 1;\n let mut map = vec![0; limit >> 1];\n for p in (3..limit).step_by(2) {\n if map[p >> 1] != 0 { continue; }\n let sq = p * p;\n if sq >= limit { break; }\n for i in (sq..limit).step_by(p*2) {\n if map[i >> 1] == 0 { map[i >> 1] = p as u32; }\n }\n }\n\n FactorMap { map }\n }\n\n pub fn least_prime_factor(&self, n: usize) -> usize {\n if n & 1 == 0 { return 2; }\n let p = self.map[n >> 1] as usize;\n if p == 0 { n } else { p }\n }\n\n pub fn factorize(&self, n: usize) -> FactorIterator {\n FactorIterator { fm: self, n }\n }\n\n pub fn is_prime(&self, n: usize) -> bool { n > 1 && self.least_prime_factor(n) == n }\n\n /// lists divisors, unsorted\n pub fn divisors(&self, mut n: usize) -> Vec {\n let mut res = vec![1];\n\n while n > 1 {\n let p = self.least_prime_factor(n);\n let mut x = 0;\n loop {\n n /= p;\n x += 1;\n if p != self.least_prime_factor(n) { break; }\n }\n for i in 0..res.len() {\n let mut a = res[i];\n for _ in 0..x {\n a *= p;\n res.push(a);\n }\n }\n }\n\n res\n }\n\n pub fn new_with_mobius(limit: usize) -> (FactorMap, Vec) {\n let fm = Self::new(limit);\n let mut mu = vec![1i8; limit + 1];\n mu[0] = 0;\n\n for i in 2..=limit {\n let p = fm.least_prime_factor(i);\n mu[i] = if p == fm.least_prime_factor(i/p) { 0 } else { -mu[i/p] };\n }\n\n (fm, mu)\n }\n}\nstruct FactorIterator<'a> {\n fm: &'a FactorMap,\n n: usize\n}\nimpl Iterator for FactorIterator<'_> {\n type Item = usize;\n\n fn next(&mut self) -> Option {\n if self.n <= 1 { return None; }\n let p = self.fm.least_prime_factor(self.n);\n self.n /= p;\n Some(p)\n }\n\n fn size_hint(&self) -> (usize, Option) { (0, Some(32)) }\n}\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let k = read!(usize);\n\n let mut ans = mi(0);\n if min(n, k) == 1 { ans = mi(1); }\n else {\n let mc = ModCombinatorics::new(min(n, k));\n let ff = ModFft::new(min(n, k) * 2);\n let mu = FactorMap::new_with_mobius(n).1;\n\n let mut m = 0usize;\n let mut A = mi(0);\n let P = veci!(min(n, k)+1, j: if j & 1 == 1 { -mc.inv_factorial(j) } else { mc.inv_factorial(j) });\n\n for i in 1..=n {\n if mu[i] == 0 { continue; }\n let mn = n.div_ceil(i);\n if m != mn {\n m = mn;\n let l = min(m, k);\n let Q = veci!(l+1, j: mi(j).pow(m as _) * mc.inv_factorial(j));\n let R = ff.mul(&P[..=l], &Q);\n A = R[2..=l].iter().sum();\n }\n if mu[i] == 1 { ans += A; } else { ans -= A; }\n }\n }\n\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "number theory", "combinatorics", "fft"], "code_uid": "528f5a28b338ed5d69e294bd8a961219", "src_uid": "eb9d24070cc5b347d020189d803628ae", "difficulty": 2900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin enumerate prime ----------\r\nfn enumerate_prime(n: usize, mut f: F)\r\nwhere\r\n F: FnMut(usize),\r\n{\r\n assert!(1 <= n && n <= 5 * 10usize.pow(8));\r\n let batch = (n as f64).sqrt().ceil() as usize;\r\n let mut is_prime = vec![true; batch + 1];\r\n for i in (2..).take_while(|p| p * p <= batch) {\r\n if is_prime[i] {\r\n let mut j = i * i;\r\n while let Some(p) = is_prime.get_mut(j) {\r\n *p = false;\r\n j += i;\r\n }\r\n }\r\n }\r\n let mut prime = vec![];\r\n for (i, p) in is_prime.iter().enumerate().skip(2) {\r\n if *p && i <= n {\r\n f(i);\r\n prime.push(i);\r\n }\r\n }\r\n let mut l = batch + 1;\r\n while l <= n {\r\n let r = std::cmp::min(l + batch, n + 1);\r\n is_prime.clear();\r\n is_prime.resize(r - l, true);\r\n for &p in prime.iter() {\r\n let mut j = (l + p - 1) / p * p - l;\r\n while let Some(is_prime) = is_prime.get_mut(j) {\r\n *is_prime = false;\r\n j += p;\r\n }\r\n }\r\n for (i, _) in is_prime.iter().enumerate().filter(|p| *p.1) {\r\n f(i + l);\r\n }\r\n l += batch;\r\n }\r\n}\r\n// ---------- end enumerate prime ----------\r\n// ---------- begin ModInt ----------\r\n// \u30e2\u30f3\u30b4\u30e1\u30ea\u4e57\u7b97\u3092\u7528\u3044\u308b\r\n// \u307b\u307cCodeforces\u7528\r\n// \u6ce8\u610f\r\n// new_unchecked \u306f\u5024x\u304c 0 <= x < modulo \u3067\u3042\u308b\u3053\u3068\u3092\u4eee\u5b9a\r\n// ModInt \u306e\u4e2d\u8eab\u306f\u6b63\u898f\u5316\u3055\u308c\u305f\u5024\u3067\u6301\u3063\u3066\u308b\u306e\u3067\u76f4\u63a5\u8aad\u3093\u3060\u308a\u66f8\u3044\u305f\u308a\u3059\u308b\u3068\u3076\u3063\u58ca\u308c\u308b\r\n// \u5947\u7d20\u6570\u306e\u307f\r\nmod modint {\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n fn rem() -> u32;\r\n fn ini() -> u64;\r\n fn reduce(x: u64) -> u32 {\r\n debug_assert!(x < (Self::modulo() as u64) << 32);\r\n let b = (x as u32 * Self::rem()) as u64;\r\n let t = x + b * Self::modulo() as u64;\r\n let mut c = (t >> 32) as u32;\r\n if c >= Self::modulo() {\r\n c -= Self::modulo();\r\n }\r\n c as u32\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod1_000_000_007 {}\r\n\r\n impl Modulo for Mod1_000_000_007 {\r\n fn modulo() -> u32 {\r\n 1_000_000_007\r\n }\r\n fn rem() -> u32 {\r\n 2226617417\r\n }\r\n fn ini() -> u64 {\r\n 582344008\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod998_244_353 {}\r\n\r\n impl Modulo for Mod998_244_353 {\r\n fn modulo() -> u32 {\r\n 998_244_353\r\n }\r\n fn rem() -> u32 {\r\n 998244351\r\n }\r\n fn ini() -> u64 {\r\n 932051910\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub fn generate_umekomi_modulo(p: u32) {\r\n assert!(\r\n p < (1 << 31)\r\n && p > 2\r\n && p & 1 == 1\r\n && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0)\r\n );\r\n let mut t = 1u32;\r\n let mut s = !p + 1;\r\n let mut n = !0u32 >> 2;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n let mut ini = (1u64 << 32) % p as u64;\r\n ini = (ini << 32) % p as u64;\r\n assert!(t * p == !0);\r\n println!(\"pub enum Mod{} {{}}\", p);\r\n println!(\"impl Modulo for Mod{} {{\", p);\r\n println!(\" fn modulo() -> u32 {{\");\r\n println!(\" {}\", p);\r\n println!(\" }}\");\r\n println!(\" fn rem() -> u32 {{\");\r\n println!(\" {}\", t);\r\n println!(\" }}\");\r\n println!(\" fn ini() -> u64 {{\");\r\n println!(\" {}\", ini);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n let mut f = vec![];\r\n let mut n = p - 1;\r\n for i in 2.. {\r\n if i * i > n {\r\n break;\r\n }\r\n if n % i == 0 {\r\n f.push(i);\r\n while n % i == 0 {\r\n n /= i;\r\n }\r\n }\r\n }\r\n if n > 1 {\r\n f.push(n);\r\n }\r\n let mut order = 1;\r\n let mut n = p - 1;\r\n while n % 2 == 0 {\r\n n /= 2;\r\n order <<= 1;\r\n }\r\n let z = (2u64..)\r\n .find(|z| {\r\n f.iter()\r\n .all(|f| mod_pow(*z, ((p - 1) / *f) as u64, p as u64) != 1)\r\n })\r\n .unwrap();\r\n let zeta = mod_pow(z, ((p - 1) / order) as u64, p as u64);\r\n println!(\"impl transform::NTTFriendly for Mod{} {{\", p);\r\n println!(\" fn order() -> usize {{\");\r\n println!(\" {}\", order);\r\n println!(\" }}\");\r\n println!(\" fn zeta() -> u32 {{\");\r\n println!(\" {}\", zeta);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n }\r\n\r\n pub struct ModInt(u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::build(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 - rhs.0;\r\n if self.0 < rhs.0 {\r\n d += T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::build(T::reduce(self.0 as u64 * rhs.0 as u64))\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::build(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n fn build(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n Self::build(0)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n Self::build(T::reduce(d as u64 * T::ini()))\r\n }\r\n pub fn new(d: u32) -> Self {\r\n Self::new_unchecked(d % T::modulo())\r\n }\r\n pub fn one() -> Self {\r\n Self::new_unchecked(1)\r\n }\r\n pub fn get(&self) -> u32 {\r\n T::reduce(self.0 as u64)\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n pub fn inv(&self) -> Self {\r\n assert!(!self.is_zero());\r\n self.pow((T::modulo() - 2) as u64)\r\n }\r\n }\r\n\r\n pub fn mod_pow(mut r: u64, mut n: u64, m: u64) -> u64 {\r\n let mut t = 1 % m;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t = t * r % m;\r\n }\r\n r = r * r % m;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n// ---------- begin Precalc ----------\r\nmod precalc {\r\n use super::modint::*;\r\n #[allow(dead_code)]\r\n pub struct Precalc {\r\n inv: Vec>,\r\n fact: Vec>,\r\n ifact: Vec>,\r\n }\r\n #[allow(dead_code)]\r\n impl Precalc {\r\n pub fn new(n: usize) -> Precalc {\r\n let mut inv = vec![ModInt::one(); n + 1];\r\n let mut fact = vec![ModInt::one(); n + 1];\r\n let mut ifact = vec![ModInt::one(); n + 1];\r\n for i in 2..(n + 1) {\r\n fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);\r\n }\r\n ifact[n] = fact[n].inv();\r\n if n > 0 {\r\n inv[n] = ifact[n] * fact[n - 1];\r\n }\r\n for i in (1..n).rev() {\r\n ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);\r\n inv[i] = ifact[i] * fact[i - 1];\r\n }\r\n Precalc {\r\n inv: inv,\r\n fact: fact,\r\n ifact: ifact,\r\n }\r\n }\r\n pub fn inv(&self, n: usize) -> ModInt {\r\n assert!(n > 0);\r\n self.inv[n]\r\n }\r\n pub fn fact(&self, n: usize) -> ModInt {\r\n self.fact[n]\r\n }\r\n pub fn ifact(&self, n: usize) -> ModInt {\r\n self.ifact[n]\r\n }\r\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[n - k]\r\n }\r\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\r\n }\r\n }\r\n}\r\n// ---------- end Precalc ----------\r\n\r\nuse modint::*;\r\n\r\npub trait NTTFriendly: modint::Modulo {\r\n fn order() -> usize;\r\n fn zeta() -> u32;\r\n}\r\n\r\ntype M = ModInt;\r\n\r\nimpl NTTFriendly for Mod998_244_353 {\r\n fn order() -> usize {\r\n 8388608\r\n }\r\n fn zeta() -> u32 {\r\n 15311432\r\n }\r\n}\r\n\r\n// \u5217\u306b\u5bfe\u3059\u308b\u547d\u4ee4\u3092\u30c6\u30ad\u30c8\u30fc\u306b\u8a70\u3081\u3042\u308f\u305b\r\n// modint, primitive type \u306e\uff12\u3064\u3042\u305f\u308a\u3067\u4f7f\u3046\u3053\u3068\u3092\u60f3\u5b9a\r\n// +, -, *\r\n// zero \u3092\u8981\u6c42\u3057\u3066\u306a\u3044\u306e\u306b\u4eee\u5b9a\u3057\u3066\u308b\u5834\u6240\u304c\u3042\u308b\r\n//\r\n// \u4f55\u3082\u8003\u3048\u305a\u306b\u66f8\u304d\u59cb\u3081\u305f\u3089\u3044\u308d\u3044\u308d\u3088\u304f\u308f\u304b\u3089\u306a\u3044\u3053\u3068\u306b\u306a\u3063\u305f\r\n// \u6574\u7406\r\n// \u9577\u3055\u304c\u7b49\u3057\u3044\u3068\u304d\u306e\u52a0\u7b97\u3001\u6e1b\u7b97\u3001dot\u7a4d\u306fok\r\n// \u9577\u3055\u304c\u7570\u306a\u308b\u3068\u304d\u306f\u3069\u3046\u3059\u308b\uff1f\r\n// 0\u57cb\u3081\u3055\u308c\u3066\u308b\u3068\u3044\u3046\u30a4\u30e1\u30fc\u30b8\u306a\u306e\u3067\r\n// \u52a0\u7b97\u3001\u6e1b\u7b97\u306f\u7d20\u76f4\u3060\u304cdot\u7a4d\u306f\u30a4\u30de\u30a4\u30c1\r\n// dot\u7a4d\u3060\u3051\u9577\u3055\u304c\u7b49\u3057\u3044\u3068\u3057\u3066\u304a\u304f?\r\n// \u3042\u308b\u3044\u306f0\u57cb\u3081\u306e\u30a4\u30e1\u30fc\u30b8\u3092\u6d88\u3059\u304b\r\n\r\nuse std::ops::*;\r\n\r\npub trait Zero: Sized + Add {\r\n fn zero() -> Self;\r\n}\r\n\r\npub fn zero() -> T {\r\n T::zero()\r\n}\r\n\r\nimpl Zero for ModInt {\r\n fn zero() -> Self {\r\n Self::zero()\r\n }\r\n}\r\n\r\nimpl Zero for usize {\r\n fn zero() -> Self {\r\n 0\r\n }\r\n}\r\n\r\npub trait ArrayAdd {\r\n type Item;\r\n fn add(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayAdd for [T]\r\nwhere\r\n T: Zero + Copy,\r\n{\r\n type Item = T;\r\n fn add(&self, rhs: &[Self::Item]) -> Vec {\r\n let mut c = vec![T::zero(); self.len().max(rhs.len())];\r\n c[..self.len()].copy_from_slice(self);\r\n c.add_assign(rhs);\r\n c\r\n }\r\n}\r\n\r\npub trait ArrayAddAssign {\r\n type Item;\r\n fn add_assign(&mut self, rhs: &[Self::Item]);\r\n}\r\n\r\nimpl ArrayAddAssign for [T]\r\nwhere\r\n T: Add + Copy,\r\n{\r\n type Item = T;\r\n fn add_assign(&mut self, rhs: &[Self::Item]) {\r\n assert!(self.len() >= rhs.len());\r\n self.iter_mut().zip(rhs).for_each(|(x, a)| *x = *x + *a);\r\n }\r\n}\r\n\r\nimpl ArrayAddAssign for Vec\r\nwhere\r\n T: Zero + Add + Copy,\r\n{\r\n type Item = T;\r\n fn add_assign(&mut self, rhs: &[Self::Item]) {\r\n if self.len() < rhs.len() {\r\n self.resize(rhs.len(), T::zero());\r\n }\r\n self.as_mut_slice().add_assign(rhs);\r\n }\r\n}\r\n\r\npub trait ArraySub {\r\n type Item;\r\n fn sub(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArraySub for [T]\r\nwhere\r\n T: Zero + Sub + Copy,\r\n{\r\n type Item = T;\r\n fn sub(&self, rhs: &[Self::Item]) -> Vec {\r\n let mut c = vec![T::zero(); self.len().max(rhs.len())];\r\n c[..self.len()].copy_from_slice(self);\r\n c.sub_assign(rhs);\r\n c\r\n }\r\n}\r\n\r\npub trait ArraySubAssign {\r\n type Item;\r\n fn sub_assign(&mut self, rhs: &[Self::Item]);\r\n}\r\n\r\nimpl ArraySubAssign for [T]\r\nwhere\r\n T: Sub + Copy,\r\n{\r\n type Item = T;\r\n fn sub_assign(&mut self, rhs: &[Self::Item]) {\r\n assert!(self.len() >= rhs.len());\r\n self.iter_mut().zip(rhs).for_each(|(x, a)| *x = *x - *a);\r\n }\r\n}\r\n\r\nimpl ArraySubAssign for Vec\r\nwhere\r\n T: Zero + Sub + Copy,\r\n{\r\n type Item = T;\r\n fn sub_assign(&mut self, rhs: &[Self::Item]) {\r\n if self.len() < rhs.len() {\r\n self.resize(rhs.len(), T::zero());\r\n }\r\n self.as_mut_slice().sub_assign(rhs);\r\n }\r\n}\r\n\r\npub trait ArrayDot {\r\n type Item;\r\n fn dot(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayDot for [T]\r\nwhere\r\n T: Mul + Copy,\r\n{\r\n type Item = T;\r\n fn dot(&self, rhs: &[Self::Item]) -> Vec {\r\n assert!(self.len() == rhs.len());\r\n self.iter().zip(rhs).map(|p| *p.0 * *p.1).collect()\r\n }\r\n}\r\n\r\npub trait ArrayDotAssign {\r\n type Item;\r\n fn dot_assign(&mut self, rhs: &[Self::Item]);\r\n}\r\n\r\nimpl ArrayDotAssign for [T]\r\nwhere\r\n T: MulAssign + Copy,\r\n{\r\n type Item = T;\r\n fn dot_assign(&mut self, rhs: &[Self::Item]) {\r\n assert!(self.len() == rhs.len());\r\n self.iter_mut().zip(rhs).for_each(|(x, a)| *x *= *a);\r\n }\r\n}\r\n\r\npub trait ArrayMul {\r\n type Item;\r\n fn mul(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayMul for [T]\r\nwhere\r\n T: Zero + Mul + Copy,\r\n{\r\n type Item = T;\r\n fn mul(&self, rhs: &[Self::Item]) -> Vec {\r\n if self.is_empty() || rhs.is_empty() {\r\n return vec![];\r\n }\r\n let mut res = vec![zero(); self.len() + rhs.len() - 1];\r\n for (i, a) in self.iter().enumerate() {\r\n for (c, b) in res[i..].iter_mut().zip(rhs) {\r\n *c = *c + *a * *b;\r\n }\r\n }\r\n res\r\n }\r\n}\r\n\r\npub trait ArrayNTT {\r\n type Item;\r\n fn ntt(&mut self);\r\n fn intt(&mut self);\r\n fn multiply(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayNTT for [ModInt]\r\nwhere\r\n T: NTTFriendly,\r\n{\r\n type Item = ModInt;\r\n fn ntt(&mut self) {\r\n let f = self;\r\n let n = f.len();\r\n assert!(n.count_ones() == 1);\r\n assert!(n <= T::order());\r\n let len = n.trailing_zeros() as usize;\r\n let mut es = [ModInt::zero(); 30];\r\n let mut ies = [ModInt::zero(); 30];\r\n let mut sum_e = [ModInt::zero(); 30];\r\n let cnt2 = T::order().trailing_zeros() as usize;\r\n let mut e = ModInt::new_unchecked(T::zeta());\r\n let mut ie = e.inv();\r\n for i in (2..=cnt2).rev() {\r\n es[i - 2] = e;\r\n ies[i - 2] = ie;\r\n e = e * e;\r\n ie = ie * ie;\r\n }\r\n let mut now = ModInt::one();\r\n for i in 0..(cnt2 - 1) {\r\n sum_e[i] = es[i] * now;\r\n now *= ies[i];\r\n }\r\n for ph in 1..=len {\r\n let p = 1 << (len - ph);\r\n let mut now = ModInt::one();\r\n for (i, f) in f.chunks_exact_mut(2 * p).enumerate() {\r\n let (x, y) = f.split_at_mut(p);\r\n for (x, y) in x.iter_mut().zip(y.iter_mut()) {\r\n let l = *x;\r\n let r = *y * now;\r\n *x = l + r;\r\n *y = l - r;\r\n }\r\n now *= sum_e[(!i).trailing_zeros() as usize];\r\n }\r\n }\r\n }\r\n fn intt(&mut self) {\r\n let f = self;\r\n let n = f.len();\r\n assert!(n.count_ones() == 1);\r\n assert!(n <= T::order());\r\n let len = n.trailing_zeros() as usize;\r\n let mut es = [ModInt::zero(); 30];\r\n let mut ies = [ModInt::zero(); 30];\r\n let mut sum_ie = [ModInt::zero(); 30];\r\n let cnt2 = T::order().trailing_zeros() as usize;\r\n let mut e = ModInt::new_unchecked(T::zeta());\r\n let mut ie = e.inv();\r\n for i in (2..=cnt2).rev() {\r\n es[i - 2] = e;\r\n ies[i - 2] = ie;\r\n e = e * e;\r\n ie = ie * ie;\r\n }\r\n let mut now = ModInt::one();\r\n for i in 0..(cnt2 - 1) {\r\n sum_ie[i] = ies[i] * now;\r\n now *= es[i];\r\n }\r\n for ph in (1..=len).rev() {\r\n let p = 1 << (len - ph);\r\n let mut inow = ModInt::one();\r\n for (i, f) in f.chunks_exact_mut(2 * p).enumerate() {\r\n let (x, y) = f.split_at_mut(p);\r\n for (x, y) in x.iter_mut().zip(y.iter_mut()) {\r\n let l = *x;\r\n let r = *y;\r\n *x = l + r;\r\n *y = (l - r) * inow;\r\n }\r\n inow *= sum_ie[(!i).trailing_zeros() as usize];\r\n }\r\n }\r\n let ik = ModInt::new_unchecked((T::modulo() + 1) >> 1).pow(len as u64);\r\n for f in f.iter_mut() {\r\n *f *= ik;\r\n }\r\n }\r\n fn multiply(&self, rhs: &[Self::Item]) -> Vec {\r\n if self.len().min(rhs.len()) <= 32 {\r\n return self.mul(rhs);\r\n }\r\n let size = (self.len() + rhs.len() - 1).next_power_of_two();\r\n let mut f = vec![ModInt::zero(); size];\r\n let mut g = vec![ModInt::zero(); size];\r\n f[..self.len()].copy_from_slice(self);\r\n g[..rhs.len()].copy_from_slice(rhs);\r\n f.ntt();\r\n g.ntt();\r\n f.dot_assign(&g);\r\n f.intt();\r\n f.truncate(self.len() + rhs.len() - 1);\r\n f\r\n }\r\n}\r\n\r\npub trait PolynomialOperation {\r\n type Item;\r\n fn eval(&self, x: Self::Item) -> Self::Item;\r\n fn derivative(&self) -> Vec;\r\n fn integral(&self) -> Vec;\r\n}\r\n\r\nimpl PolynomialOperation for [ModInt] {\r\n type Item = ModInt;\r\n fn eval(&self, x: Self::Item) -> Self::Item {\r\n self.iter().rev().fold(ModInt::zero(), |s, a| s * x + *a)\r\n }\r\n fn derivative(&self) -> Vec {\r\n if self.len() <= 1 {\r\n return vec![];\r\n }\r\n self[1..]\r\n .iter()\r\n .enumerate()\r\n .map(|(k, a)| ModInt::new_unchecked(k as u32 + 1) * *a)\r\n .collect()\r\n }\r\n fn integral(&self) -> Vec {\r\n if self.is_empty() {\r\n return vec![];\r\n }\r\n let mut inv = vec![ModInt::one(); self.len() + 1];\r\n let mut mul = ModInt::zero();\r\n for i in 1..=self.len() {\r\n mul += ModInt::one();\r\n inv[i] = inv[i - 1] * mul;\r\n }\r\n let mut prod = inv[self.len()].inv();\r\n for i in (1..=self.len()).rev() {\r\n inv[i] = self[i - 1] * inv[i - 1] * prod;\r\n prod *= mul;\r\n mul -= ModInt::one();\r\n }\r\n inv[0] = ModInt::zero();\r\n inv\r\n }\r\n}\r\n\r\npub trait FPSOperation {\r\n type Item;\r\n fn inverse(&self, n: usize) -> Vec;\r\n fn log(&self, n: usize) -> Vec;\r\n fn exp(&self, n: usize) -> Vec;\r\n}\r\n\r\nimpl FPSOperation for [ModInt] {\r\n type Item = ModInt;\r\n fn inverse(&self, n: usize) -> Vec {\r\n assert!(self.len() > 0 && !self[0].is_zero());\r\n let len = n.next_power_of_two();\r\n assert!(2 * len <= T::order());\r\n let mut b = vec![ModInt::zero(); n];\r\n b[0] = self[0].inv();\r\n let mut f = Vec::with_capacity(2 * len);\r\n let mut g = Vec::with_capacity(2 * len);\r\n let mut size = 1;\r\n while size < n {\r\n g.clear();\r\n g.extend(b.iter().take(size));\r\n g.resize(2 * size, ModInt::zero());\r\n f.clear();\r\n f.extend(self.iter().take(2 * size));\r\n f.resize(2 * size, ModInt::zero());\r\n f.ntt();\r\n g.ntt();\r\n f.dot_assign(&g);\r\n f.intt();\r\n f[..size].iter_mut().for_each(|f| *f = ModInt::zero());\r\n f.ntt();\r\n f.dot_assign(&g);\r\n f.intt();\r\n for (b, g) in b[size..].iter_mut().zip(&f[size..]) {\r\n *b = *b - *g;\r\n }\r\n size *= 2;\r\n }\r\n b\r\n }\r\n fn log(&self, n: usize) -> Vec {\r\n assert!(self.get(0).map_or(false, |p| p.get() == 1));\r\n let mut b = self.derivative().multiply(&self.inverse(n));\r\n b.truncate(n - 1);\r\n let mut b = b.integral();\r\n b.resize(n, ModInt::zero());\r\n b\r\n }\r\n fn exp(&self, n: usize) -> Vec {\r\n assert!(self.get(0).map_or(true, |a| a.is_zero()));\r\n assert!(n <= T::order());\r\n let mut b = vec![ModInt::one()];\r\n let mut size = 1;\r\n while size < n {\r\n size <<= 1;\r\n let f = b.log(size);\r\n let g = self[..self.len().min(size)].sub(&f);\r\n b = b.multiply(&g).add(&b);\r\n b.truncate(size);\r\n }\r\n b.truncate(n);\r\n b.resize(n, ModInt::zero());\r\n b\r\n }\r\n}\r\n\r\n// test\r\n// yuki907: https://yukicoder.me/submissions/712523\r\n// hhkb2020: https://atcoder.jp/contests/hhkb2020/submissions/26997806\r\n//\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nuse std::collections::*;\r\nuse std::io::Write;\r\n\r\ntype Map = BTreeMap;\r\ntype Set = BTreeSet;\r\ntype Deque = VecDeque;\r\n\r\n// F(a, k): a \u306e\u8981\u7d20\u306e\u500b\u6570\u3092k\u500d\u306b\u3057\u3066\u524d|a|\u500b\u3060\u3051\u53d6\u308a\u51fa\u3057\u305f\u6570\u5217\r\n// G(a, x, y): a\u4e2d\u306e\u5024x, y\u3092\u5165\u308c\u66ff\u3048\u305f\u3082\u306e\r\n// \u5217a\u304c\u5217b\u306e\u89aa\u3067\u3042\u308b\u3068\u3044\u3046\u306e\u306f\r\n// F(a, k) = b or G(a, x, y) = b\r\n// \u306a\u308bk \u307e\u305f\u306fx, y \u304c\u5b58\u5728\u3059\u308b\u6642\r\n// a\u304cb\u306e\u7956\u5148\u3067\u3042\u308b\u3068\u3044\u3046\u306e\u306fa\u306b\u635c\u67fb\u3057\u7d9a\u3051\u3066b\u306b\u3067\u304d\u308b\u6642\r\n//\r\n// n, k \u304c\u4e0e\u3048\u3089\u308c\u308b\r\n// \u9577\u3055n\u306e\u5217\u3067\u5024\u304c1..=k \u306e\u5168\u3066\u306e\u5217\u3092\u751f\u6210\u3067\u304d\u308b\u3088\u3046\u306a\u5143\u306e\u6700\u5c0f\u5024\u3092mod9982244353\u3067\u6c42\u3081\u3066\r\n//\r\n// G \u306f\u53ef\u9006\u306a\u64cd\u4f5c\r\n//\r\n// F \u306f\uff1f\r\n//\r\n\r\nfn run() {\r\n input!(n: usize, k: usize);\r\n if k == 1 || n == 1 {\r\n println!(\"1\");\r\n return;\r\n }\r\n let pc = precalc::Precalc::new(n + k);\r\n let mut memo = vec![M::zero(); n + 1];\r\n for i in 1..=n {\r\n// let len = n / i;\r\n let len = (n + i - 1) / i;\r\n let mut a = vec![M::zero(); len + 1];\r\n let mut b = vec![M::zero(); len + 1];\r\n for i in 0..=len {\r\n a[i] = M::from(i).pow(len as u64) * pc.ifact(i);\r\n b[i] = M::from(-1i64).pow(i as u64) * pc.ifact(i);\r\n }\r\n let mut c = a.multiply(&b);\r\n c.truncate((len + 1).min(k + 1));\r\n memo[i] = c.iter().fold(M::zero(), |s, a| s + *a) - M::one();\r\n }\r\n enumerate_prime(n, |p| {\r\n for i in 1..=(n / p) {\r\n memo[i] = memo[i] - memo[i * p];\r\n }\r\n });\r\n println!(\"{}\", memo[1]);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "number theory", "combinatorics", "fft"], "code_uid": "a68e3fe5ec72ad43d97b2acccfceb518", "src_uid": "eb9d24070cc5b347d020189d803628ae", "difficulty": 2900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\nfn mod_factorials(maxn: usize) -> Vec {\n let mut res = vec![ModInt::default(); maxn+1];\n res[0] = 1.into();\n for i in 1..=maxn {\n res[i] = res[i-1] * i\n }\n return res;\n}\n\nstruct ModCombinatorics {\n factorials: Vec,\n inv_factorials: Vec\n}\n#[allow(non_snake_case)]\nimpl ModCombinatorics {\n fn new(maxn: usize) -> Self {\n let factorials = mod_factorials(maxn);\n let mut inv = vec![ModInt::default(); maxn+1];\n inv[maxn] = factorials[maxn].inv();\n for i in (1..=maxn).rev() {\n inv[i-1] = inv[i] * i;\n }\n Self { factorials, inv_factorials: inv }\n }\n #[inline]\n fn factorial(&self, n: usize) -> ModInt { self.factorials[n] }\n #[inline]\n fn inv_factorial(&self, n: usize) -> ModInt { self.inv_factorials[n] }\n fn P(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(n-k) }\n }\n fn C(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(k) * self.inv_factorial(n-k) }\n }\n\n // multi-choose, be sure to adjust maxn accordingly\n fn M(&self, n: usize, k: usize) -> ModInt {\n if k == 0 { 1.into() } else { self.C(n + k - 1, k) }\n }\n}\n\npub struct ModFft {\n n_inv: ModInt,\n w: Vec\n}\nimpl ModFft {\n pub fn primitive_root() -> ModInt { ModInt::raw(3) /* for 998244353 */}\n pub fn good_len(deg: usize) -> usize { (deg + 1).next_power_of_two() }\n pub fn prepare(arr: &[ModInt], deg: usize) -> Vec { \n let n = Self::good_len(deg);\n let mut res = Vec::with_capacity(n);\n res.extend_from_slice(arr);\n res.resize(n, ModInt::raw(0));\n res\n }\n\n pub fn new(max_deg: usize) -> Self {\n let n = Self::good_len(max_deg);\n Self {\n n_inv: ModInt::new(n).inv(),\n w: ModInt::pow_vec(Self::primitive_root().pow((ModInt::modulus() - 1) as u64 / n as u64), n-1)\n }\n }\n\n pub fn transform(&self, a: &mut [ModInt]) { self.transform_impl(a, false) }\n pub fn transform_inv(&self, a: &mut [ModInt]) { self.transform_impl(a, true) }\n\n pub fn fft(&self, a: &[ModInt]) -> Vec { self.fft_deg(a, a.len() - 1) }\n pub fn fft_deg(&self, a: &[ModInt], deg: usize) -> Vec { \n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n a\n }\n pub fn fft_inv(&self, a: &[ModInt]) -> Vec { \n let mut a = Self::prepare(a, a.len() - 1);\n self.transform_inv(&mut a);\n a\n }\n\n pub fn max_deg(&self) -> usize { self.w.len() - 1 }\n\n #[inline] fn transform_impl(&self, a: &mut [ModInt], invert: bool) {\n let sz = a.len();\n if sz <= 1 { return }\n let n = self.w.len();\n debug_assert!(sz <= n && sz.is_power_of_two(), \"Array size {} must be <= {} and a power of 2\", sz, n);\n let sh = sz.leading_zeros() + 1;\n\n for i in 0..sz {\n let j = i.reverse_bits() >> sh;\n if i < j { a.swap(i, j) }\n }\n\n let mut len = 2usize;\n let mut ang = (n >> 1) as isize;\n if invert { ang = -ang; }\n while len <= sz {\n let h = len >> 1;\n for i in (0..sz).step_by(len) {\n let mut k = 0usize;\n for j in i..i+h {\n let u = a[j];\n let v = a[j+h] * self.w[k];\n a[j] = u + v;\n a[j+h] = u - v;\n k = k.wrapping_add(ang as usize) & (n-1);\n }\n }\n len <<= 1;\n ang >>= 1;\n }\n\n if invert {\n let sz_inv = self.n_inv * (n / sz);\n for i in 0..sz { a[i] *= sz_inv; }\n }\n }\n\n pub fn mul(&self, a: &[ModInt], b: &[ModInt]) -> Vec {\n if a.is_empty() || b.is_empty() { return vec![]; }\n let deg = a.len() + b.len() - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n let mut b = Self::prepare(b, deg);\n self.transform(&mut a);\n self.transform(&mut b);\n for i in 0..a.len() { a[i] *= b[i]; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn sq(&self, a: &[ModInt]) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = a.len() * 2 - 2;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { let ai = a[i]; a[i] = ai * ai; }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn pow(&self, a: &[ModInt], exp: usize) -> Vec {\n if a.is_empty() { return vec![]; }\n let deg = (a.len() - 1) * exp;\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\n let mut a = Self::prepare(a, deg);\n self.transform(&mut a);\n for i in 0..a.len() { a[i] = a[i].pow(exp as u64) }\n self.transform_inv(&mut a);\n a.truncate(deg + 1);\n a\n }\n\n pub fn product(&self, mut polys: VecDeque>) -> Vec {\n while let Some(p) = polys.pop_front() {\n if let Some(q) = polys.pop_front() {\n polys.push_back(self.mul(&p, &q));\n } else { return p; }\n }\n\n vec![ModInt::new(1)]\n }\n}\n\nstruct FactorMap {\n map: Vec\n}\nimpl FactorMap {\n pub fn new(limit: usize) -> FactorMap {\n let limit = limit + 1;\n let mut map = vec![0; limit >> 1];\n for p in (3..limit).step_by(2) {\n if map[p >> 1] != 0 { continue; }\n let sq = p * p;\n if sq >= limit { break; }\n for i in (sq..limit).step_by(p*2) {\n if map[i >> 1] == 0 { map[i >> 1] = p as u32; }\n }\n }\n\n FactorMap { map }\n }\n\n pub fn least_prime_factor(&self, n: usize) -> usize {\n if n & 1 == 0 { return 2; }\n let p = self.map[n >> 1] as usize;\n if p == 0 { n } else { p }\n }\n\n pub fn factorize(&self, n: usize) -> FactorIterator {\n FactorIterator { fm: self, n }\n }\n\n pub fn is_prime(&self, n: usize) -> bool { n > 1 && self.least_prime_factor(n) == n }\n\n /// lists divisors, unsorted\n pub fn divisors(&self, mut n: usize) -> Vec {\n let mut res = vec![1];\n\n while n > 1 {\n let p = self.least_prime_factor(n);\n let mut x = 0;\n loop {\n n /= p;\n x += 1;\n if p != self.least_prime_factor(n) { break; }\n }\n for i in 0..res.len() {\n let mut a = res[i];\n for _ in 0..x {\n a *= p;\n res.push(a);\n }\n }\n }\n\n res\n }\n\n pub fn new_with_mobius(limit: usize) -> (FactorMap, Vec) {\n let fm = Self::new(limit);\n let mut mu = vec![1i8; limit + 1];\n mu[0] = 0;\n\n for i in 2..=limit {\n let p = fm.least_prime_factor(i);\n mu[i] = if p == fm.least_prime_factor(i/p) { 0 } else { -mu[i/p] };\n }\n\n (fm, mu)\n }\n}\nstruct FactorIterator<'a> {\n fm: &'a FactorMap,\n n: usize\n}\nimpl Iterator for FactorIterator<'_> {\n type Item = usize;\n\n fn next(&mut self) -> Option {\n if self.n <= 1 { return None; }\n let p = self.fm.least_prime_factor(self.n);\n self.n /= p;\n Some(p)\n }\n\n fn size_hint(&self) -> (usize, Option) { (0, Some(32)) }\n}\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let k = read!(usize);\n\n let mut ans = mi(0);\n if min(n, k) == 1 { ans = mi(1); }\n else {\n let mc = ModCombinatorics::new(min(n, k));\n let ff = ModFft::new(min(n, k) * 2);\n let mu = FactorMap::new_with_mobius(n).1;\n\n let mut m = 0usize;\n let mut A = mi(0);\n\n for i in 1..=n {\n if mu[i] == 0 { continue; }\n let mn = n.div_ceil(i);\n if m != mn {\n m = mn;\n let l = min(m, k);\n\n let P = veci!(l+1, j: if j & 1 == 1 { -mc.inv_factorial(j) } else { mc.inv_factorial(j) });\n let Q = veci!(l+1, j: mi(j).pow(m as _) * mc.inv_factorial(j));\n let R = ff.mul(&P, &Q);\n A = R[2..=l].iter().sum();\n }\n if mu[i] == 1 { ans += A; } else { ans -= A; }\n }\n }\n\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "number theory", "combinatorics", "fft"], "code_uid": "42e7a20e0190d73e8993c32a27f5bbda", "src_uid": "eb9d24070cc5b347d020189d803628ae", "difficulty": 2900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\tconst INF: i32 = 1000000000;\n\n\tl!(n,m = rin.u());\n\tl!(s,t = rin.vb());\n\tassert!(s.len() == n);\n\tif t[0] == t[1] {\n\t\tlet c = s.into_iter().filter(|&x| x == t[0]).count();\n\t\tlet x = n.min(c + m);\n\t\tlet sol = if x <= 1 {0} else {x * (x-1) / 2};\n\t\twriteln!(rout, \"{}\", sol).ok();\n\t\treturn;\n\t}\n\tlet mut dp = v!([n+1][n+1][m+2] = -INF);\n\tdp[0][0][0] = 0;\n\tfor i in 0..n {\n\t\tfor j in 0..=i {\n\t\t\tfor k in 0..=m.min(i) {\n\t\t\t\tlet v = dp[i][j][k];\n\t\t\t\tif v < 0 {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif s[i] == t[0] {\n\t\t\t\t\tmax!(dp[i+1][j+1][k], v);\n\t\t\t\t} else {\n\t\t\t\t\tmax!(dp[i+1][j+1][k+1], v);\n\t\t\t\t}\n\t\t\t\tif s[i] == t[1] {\n\t\t\t\t\tmax!(dp[i+1][j][k], v + j as i32);\n\t\t\t\t} else {\n\t\t\t\t\tmax!(dp[i+1][j][k+1], v + j as i32);\n\t\t\t\t}\n\t\t\t\tmax!(dp[i+1][j][k], v);\n\t\t\t}\n\t\t}\n\t}\n\tlet mut sol = 0;\n\tfor j in 0..=n {\n\t\tfor k in 0..=m {\n\t\t\tmax!(sol, dp[n][j][k]);\n\t\t}\n\t}\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "c003588a7fa727e800bc267acddb91a1", "src_uid": "9c700390ac13942cbde7c3428965b18a", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead}; // (a)\nuse std::cmp::{max, min};\n\nmacro_rules! numsin {\n () => (\n io::stdin().lock() // (0)\n .lines().next().unwrap().unwrap() // (1)\n .split(' ').map(|s| s.trim()) // (2)\n .filter(|s| !s.is_empty()) // (3)\n .map(|s| s.parse().unwrap()) // (4)\n .collect()\n )\n}\n\nfn main() {\n let nk: Vec = numsin!();\n let mut s = String::new();\n let mut t = String::new();\n io::stdin().read_line(&mut s).expect(\"\");\n io::stdin().read_line(&mut t).expect(\"\");\n let s = s.as_bytes();\n let t = t.as_bytes();\n if t[0] == t[1] {\n let mut tc: i32 = 0;\n for i in 0..nk[0] {\n if s[i] == t[0] {\n tc += 1;\n }\n }\n if (tc as usize) + nk[1] >= nk[0] {\n tc = nk[0] as i32;\n }\n else {\n tc += nk[1] as i32;\n }\n println!(\"{}\", tc * (tc - 1) / 2);\n return;\n }\n let mut dp = vec![vec![vec![-200000i32;nk[0]+1];nk[1]+2];nk[0]+1];\n dp[0][0][0] = 0;\n for i in 0..nk[0] {\n for j in 0..nk[1]+1 {\n for k in 0..nk[0] {\n if s[i] == t[1] {\n dp[i+1][j][k] = max(dp[i+1][j][k], dp[i][j][k] + (k as i32));\n dp[i+1][j+1][k+1] = max(dp[i+1][j+1][k+1], dp[i][j][k]);\n }\n else if s[i] == t[0] {\n dp[i+1][j][k+1] = max(dp[i+1][j][k+1], dp[i][j][k]);\n dp[i+1][j+1][k] = max(dp[i+1][j+1][k], dp[i][j][k] + (k as i32));\n }\n else {\n dp[i+1][j][k] = max(dp[i+1][j][k], dp[i][j][k]);\n dp[i+1][j+1][k+1] = max(dp[i+1][j+1][k+1], dp[i][j][k]);\n dp[i+1][j+1][k] = max(dp[i+1][j+1][k], dp[i][j][k] + (k as i32));\n }\n }\n }\n }\n let mut ans: i32 = -1;\n for j in 0..nk[1]+1 {\n for k in 0..nk[0]+1 {\n ans = max(dp[nk[0]][j][k], ans);\n }\n }\n // println!(\"{:?}\", dp);\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "071a815ebc522584c377a637e3ed63a1", "src_uid": "9c700390ac13942cbde7c3428965b18a", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules !input {(source =$s :expr ,$($r :tt ) *) =>{let mut iter =$s .split_whitespace () ;let mut next =||{iter .next () .unwrap () } ;input_inner !{next ,$($r ) *} } ;($($r :tt ) *) =>{let stdin =std ::io ::stdin () ;let mut bytes =std ::io ::Read ::bytes (std ::io ::BufReader ::new (stdin .lock () ) ) ;let mut next =move ||->String {bytes .by_ref () .map (|r |r .unwrap () as char ) .skip_while (|c |c .is_whitespace () ) .take_while (|c |!c .is_whitespace () ) .collect () } ;input_inner !{next ,$($r ) *} } ;}\nmacro_rules !input_inner {($next :expr ) =>{} ;($next :expr ,) =>{} ;($next :expr ,$var :ident :$t :tt $($r :tt ) *) =>{let $var =read_value !($next ,$t ) ;input_inner !{$next $($r ) *} } ;}\nmacro_rules !read_value {($next :expr ,($($t :tt ) ,*) ) =>{($(read_value !($next ,$t ) ) ,*) } ;($next :expr ,[$t :tt ;$len :expr ] ) =>{(0 ..$len ) .map (|_ |read_value !($next ,$t ) ) .collect ::>() } ;($next :expr ,chars ) =>{read_value !($next ,String ) .chars () .collect ::>() } ;($next :expr ,usize1 ) =>{read_value !($next ,usize ) -1 } ;($next :expr ,$t :ty ) =>{$next () .parse ::<$t >() .expect (\"Parse error\" ) } ;}\ntrait Monoid {\n fn id() -> Self;\n fn f(a: Self, b: Self) -> Self;\n}\n#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]\nenum MaxInt {\n Minimal,\n Val(i64),\n}\nimpl std::ops::Mul for MaxInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self {\n if self > other {\n self\n } else {\n other\n }\n }\n}\nimpl MaxInt {\n fn unwrap(self) -> i64 {\n if let Self::Val(x) = self {\n x\n } else {\n panic!();\n }\n }\n fn map(self, f: F) -> Self\n where\n F: Fn(i64) -> i64,\n {\n if let Self::Val(x) = self {\n Self::Val(f(x))\n } else {\n Self::Minimal\n }\n }\n}\nimpl Monoid for MaxInt {\n fn id() -> Self {\n MaxInt::Minimal\n }\n fn f(a: Self, b: Self) -> Self {\n a * b\n }\n}\nuse MaxInt::*;\n\nfn main() {\n input! {\n n: usize,\n k: usize,\n s: String,\n t: String,\n }\n let s = s.chars().map(|c| c as u8).collect::>();\n let t = t.chars().map(|c| c as u8).collect::>();\n if t[0] == t[1] {\n let mut ans = 0;\n let mut c = 0;\n let mut k = k;\n for i in 0..n {\n if k != 0 && s[i] != t[0] {\n ans += c;\n c += 1;\n k -= 1;\n }\n if s[i] == t[0] {\n ans += c;\n c += 1;\n }\n }\n println!(\"{}\", ans);\n return;\n }\n if k == 0 {\n let mut ans = 0;\n let mut c = 0;\n for i in 0..n {\n if s[i] == t[0] {\n c += 1;\n }\n if s[i] == t[1] {\n ans += c;\n }\n }\n println!(\"{}\", ans);\n return;\n }\n\n let mut dp = vec![vec![vec![Minimal; n + 1]; k + 2]; n + 1];\n dp[0][0][0] = Val(0);\n for i in 0..n {\n for k in 0..=k {\n for c in 0..=i {\n if s[i] == t[0] {\n dp[i + 1][k][c + 1] = dp[i + 1][k][c + 1] * dp[i][k][c];\n } else {\n dp[i + 1][k + 1][c + 1] = dp[i + 1][k + 1][c + 1] * dp[i][k][c];\n }\n if s[i] == t[1] {\n dp[i + 1][k][c] = dp[i + 1][k][c] * dp[i][k][c].map(|v| v + c as i64);\n } else {\n dp[i + 1][k + 1][c] = dp[i + 1][k + 1][c] * dp[i][k][c].map(|v| v + c as i64);\n }\n if s[i] != t[0] && s[i] != t[1] {\n dp[i + 1][k][c] = dp[i + 1][k][c] * dp[i][k][c];\n }\n }\n }\n }\n let mut ans = Minimal;\n for k in 0..=k {\n for c in 0..=n {\n ans = ans * dp[n][k][c];\n }\n }\n println!(\"{}\", ans.unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "72a7a397992c4174048013da34f62d1e", "src_uid": "9c700390ac13942cbde7c3428965b18a", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::*;\nuse std::str::*;\n\n// scanner from https://codeforces.com/contest/1396/submission/91365784\nstruct Scanner {\n stdin: Stdin,\n buffer: VecDeque,\n}\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Self {\n Scanner {\n stdin: stdin(),\n buffer: VecDeque::new(),\n }\n }\n fn cin(&mut self) -> T {\n while self.buffer.is_empty() {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n self.buffer.pop_front().unwrap().parse::().ok().unwrap()\n }\n fn chars(&mut self) -> Vec {\n self.cin::().chars().collect()\n }\n fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.cin()).collect()\n }\n}\n\n\n// chmax https://qiita.com/maguro_tuna/items/fab200fdc1efde1612e7\nmacro_rules! max {\n ($a:expr $(,)*) => {{\n $a\n }};\n ($a:expr, $b:expr $(,)*) => {{\n std::cmp::max($a, $b)\n }};\n ($a:expr, $($rest:expr),+ $(,)*) => {{\n std::cmp::max($a, max!($($rest),+))\n }};\n}\n\nmacro_rules! chmax {\n ($base:expr, $($cmps:expr),+ $(,)*) => {{\n let cmp_max = max!($($cmps),+);\n if $base < cmp_max {\n $base = cmp_max;\n true\n } else {\n false\n }\n }};\n}\n\n// Editorial\u3092\u898b\u3066\u4f5c\u6210\nfn main() {\n let mut scan = Scanner::new();\n let out = &mut BufWriter::new(stdout());\n let n: usize = scan.cin();\n let max_k: usize = scan.cin();\n let s = scan.chars();\n let t = scan.chars();\n\n let v: Vec = s\n .iter()\n .map(|&c| {\n if c == t[0] {\n 0\n } else if c == t[1] {\n 1\n } else {\n 2\n }\n })\n .collect();\n\n if t[0] == t[1] {\n let ct = v.iter().filter(|&x| *x == 0).count();\n let x = min(ct + max_k, n);\n writeln!(out, \"{}\", x * (x - 1) / 2).ok();\n return;\n }\n // dp[i][k][ct] : [0,i) \u306e\u7bc4\u56f2\u3067\u3001k\u56de\u64cd\u4f5c\u3057\u3066\u3001t[0]\u306e\u6587\u5b57\u304cct\u500b\u3042\u308b\u5834\u5408\u3001\u3053\u306e\u7bc4\u56f2\u306bsubsequence\u3092\u4f55\u901a\u308a\u4f5c\u308c\u308b\u304b\n let mut dp = vec![vec![vec![-1000000i32; n + 2]; n + 2]; n + 2];\n dp[0][0][0] = 0;\n\n for i in 0..n {\n for k in 0..=max_k {\n for ct in 0..=i {\n let c = ct as i32;\n if v[i] == 0 {\n // op ->0 ->1\n chmax!(dp[i + 1][k + 0][ct + 1], dp[i][k][ct] + 0); // 0->0\n chmax!(dp[i + 1][k + 1][ct + 0], dp[i][k][ct] + c); // 0->1\n } else if v[i] == 1 {\n chmax!(dp[i + 1][k + 1][ct + 1], dp[i][k][ct] + 0); // 1->0\n chmax!(dp[i + 1][k + 0][ct + 0], dp[i][k][ct] + c); // 1->1\n } else if v[i] == 2 {\n chmax!(dp[i + 1][k + 1][ct + 1], dp[i][k][ct] + 0); // 2->0\n chmax!(dp[i + 1][k + 1][ct + 0], dp[i][k][ct] + c); // 2->1\n chmax!(dp[i + 1][k + 0][ct + 0], dp[i][k][ct] + 0); // 2->2\n }\n }\n }\n }\n\n let mut ans = 0;\n for k in 0..=max_k {\n //print!(\" k={} : \", k);\n for ct in 0..=n {\n //print!(\"{} \", dp[i][k][ct]);\n chmax!(ans, dp[n][k][ct]);\n }\n //println!(\" \");\n }\n\n writeln!(out, \"{} \", ans).ok();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "c53614dc4b80df2379d2a18501a8d5c7", "src_uid": "9c700390ac13942cbde7c3428965b18a", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (n, k): (usize, usize) = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let mut iter = buf.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n };\n let s: Vec = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim_end().chars().collect()\n };\n let t: Vec = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim_end().chars().collect()\n };\n\n let mut old = vec![vec![std::i32::MIN; n + 1]; k + 1];\n old[0][0] = 0;\n for x in 0..n {\n let mut new = vec![vec![std::i32::MIN; n + 1]; k + 1];\n let trans = |dst: &mut i32, src: i32| {\n *dst = std::cmp::max(*dst, src);\n };\n for i in 0..=k {\n for j in 0..=x {\n if t[0] == t[1] {\n if s[x] == t[0] {\n trans(&mut new[i][j + 1], old[i][j] + j as i32);\n } else {\n trans(&mut new[i][j], old[i][j]);\n if i == k { continue; }\n trans(&mut new[i + 1][j + 1], old[i][j] + j as i32);\n }\n } else {\n if s[x] == t[0] {\n trans(&mut new[i][j + 1], old[i][j]);\n if i == k { continue; }\n trans(&mut new[i + 1][j], old[i][j] + j as i32);\n } else if s[x] == t[1] {\n trans(&mut new[i][j], old[i][j] + j as i32);\n if i == k { continue; }\n trans(&mut new[i + 1][j + 1], old[i][j]);\n } else {\n trans(&mut new[i][j], old[i][j]);\n if i == k { continue; }\n trans(&mut new[i + 1][j + 1], old[i][j]);\n trans(&mut new[i + 1][j], old[i][j] + j as i32);\n } \n }\n }\n }\n old = new;\n }\n let ans = old.iter().map(|v| v.iter().max().unwrap()).max().unwrap();\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "2c42c65b58d285c54351114950d75284", "src_uid": "9c700390ac13942cbde7c3428965b18a", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(non_snake_case)]\r\nuse std::io::{BufWriter, stdin, stdout, Write};\r\n\r\nfn main() {\r\n let mut scan = Scanner::default();\r\n let out = &mut BufWriter::new(stdout());\r\n let t: usize = scan.next();\r\n for _ in 0..t {\r\n let x: usize = scan.next();\r\n let a: Vec = scan.vec(3);\r\n let mut doors = vec![false; 4];\r\n let mut key = x;\r\n while !doors[key] {\r\n doors[key] = true;\r\n if key == 0 { break; }\r\n key = a[key - 1];\r\n }\r\n if (1..=3).fold(true, |flag, i| doors[i] & flag) {\r\n writeln!(out, \"YES\").unwrap();\r\n } else {\r\n writeln!(out, \"NO\").unwrap();\r\n }\r\n }\r\n}\r\n\r\n#[derive(Default)]\r\npub struct Scanner {\r\n buffer: Vec\r\n}\r\nimpl Scanner {\r\n fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n let mut input = String::new();\r\n stdin().read_line(&mut input).expect(\"Failed read\");\r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n }\r\n }\r\n\r\n pub fn vec(&mut self, n:usize) -> Vec {\r\n (0..n).map(|_| self.next::()).collect()\r\n }\r\n}", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "6895019fd375ee272452ed9a3515e360", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\r\n#![allow(unused_must_use)]\r\n#![allow(non_snake_case)]\r\n#![allow(clippy::too_many_arguments)]\r\n#![allow(clippy::many_single_char_names)]\r\n\r\nuse std::cmp::{max, min, Reverse};\r\nuse std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};\r\nuse std::io::{self, prelude::*};\r\nuse std::str;\r\n\r\nfn solve(sc: &mut Scanner, wr: &mut W) {\r\n for _ in 0..sc.tok() {\r\n let mut x: usize = sc.tok();\r\n let v: Vec = (0..3).map(|_| sc.tok()).collect();\r\n let mut good = true;\r\n for _ in 0..2 {\r\n if v[x-1] == 0 {\r\n good = false;\r\n break;\r\n }\r\n x = v[x-1];\r\n }\r\n if good {\r\n writeln!(wr, \"YES\");\r\n } else {\r\n writeln!(wr, \"NO\");\r\n }\r\n }\r\n}\r\n\r\nuse std::marker::PhantomData;\r\nmacro_rules! recursive_function {\r\n ($name: ident, $trait: ident, ($($type: ident $arg: ident,)*)) => {\r\n pub trait $trait<$($type, )*Output> {\r\n fn call(&mut self, $($arg: $type,)*) -> Output;\r\n }\r\n\r\n pub struct $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n f: F,\r\n $($arg: PhantomData<$type>,\r\n )*\r\n phantom_output: PhantomData,\r\n }\r\n\r\n impl $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n pub fn new(f: F) -> Self {\r\n Self {\r\n f,\r\n $($arg: Default::default(),\r\n )*\r\n phantom_output: Default::default(),\r\n }\r\n }\r\n }\r\n\r\n impl $trait<$($type, )*Output> for $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n fn call(&mut self, $($arg: $type,)*) -> Output {\r\n let const_ptr = &self.f as *const F;\r\n let mut_ptr = const_ptr as *mut F;\r\n unsafe { (&mut *mut_ptr)(self, $($arg, )*) }\r\n }\r\n }\r\n }\r\n}\r\n\r\nrecursive_function!(RecursiveFunction0, Callable0, ());\r\nrecursive_function!(RecursiveFunction, Callable, (Arg arg,));\r\nrecursive_function!(RecursiveFunction2, Callable2, (Arg1 arg1, Arg2 arg2,));\r\nrecursive_function!(RecursiveFunction3, Callable3, (Arg1 arg1, Arg2 arg2, Arg3 arg3,));\r\nrecursive_function!(RecursiveFunction4, Callable4, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4,));\r\nrecursive_function!(RecursiveFunction5, Callable5, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5,));\r\nrecursive_function!(RecursiveFunction6, Callable6, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6,));\r\nrecursive_function!(RecursiveFunction7, Callable7, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7,));\r\nrecursive_function!(RecursiveFunction8, Callable8, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8,));\r\nrecursive_function!(RecursiveFunction9, Callable9, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9,));\r\n\r\nstruct Scanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitWhitespace<'static>,\r\n}\r\nimpl Scanner {\r\n fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: vec![],\r\n buf_iter: \"\".split_whitespace(),\r\n }\r\n }\r\n fn tok(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_whitespace())\r\n }\r\n }\r\n }\r\n}\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let mut scan = Scanner::new(stdin.lock());\r\n let mut out = io::BufWriter::new(stdout.lock());\r\n solve(&mut scan, &mut out);\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "ee44034080571e06e5ada899635909af", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "pub mod solution {\n\nuse crate::io::input::Input;\nuse crate::io::output::output;\nuse crate::numbers::num_traits::bit_ops::BitOps;\nuse crate::out_line;\n\nfn solve(input: &mut Input, _test_case: usize) {\n let mut x = input.read_usize();\n let behind = input.read_usize_vec(3);\n\n let mut has = 0;\n while x != 0 {\n has.set_bit(x - 1);\n x = behind[x - 1];\n }\n out_line!(has == 7);\n}\n\npub(crate) fn run(mut input: Input) -> bool {\n #[allow(dead_code)]\n enum TestType {\n Single,\n MultiNumber,\n MultiEof,\n }\n let test_type = TestType::MultiNumber;\n match test_type {\n TestType::Single => solve(&mut input, 1),\n TestType::MultiNumber => {\n let t = input.read();\n for i in 0usize..t {\n solve(&mut input, i + 1);\n }\n }\n TestType::MultiEof => {\n let mut i = 1usize;\n while input.peek().is_some() {\n solve(&mut input, i);\n i += 1;\n }\n }\n }\n output().flush();\n input.skip_whitespace();\n !input.peek().is_some()\n}\n\n}\npub mod io {\npub mod input {\nuse crate::numbers::num_traits::add_sub::AddSub;\nuse crate::numbers::num_traits::from_u8::FromU8;\nuse crate::numbers::num_traits::mul_div_rem::Multable;\nuse crate::numbers::num_traits::sign::IsSigned;\nuse crate::numbers::num_traits::zero_one::ZeroOne;\nuse std::fmt::Display;\nuse std::io::Read;\nuse std::marker::PhantomData;\n\nmacro_rules! read_impl {\n ($t: ty, $read_name: ident, $read_vec_name: ident) => {\n pub fn $read_name(&mut self) -> $t {\n self.read()\n }\n\n pub fn $read_vec_name(&mut self, len: usize) -> Vec<$t> {\n self.read_vec(len)\n }\n };\n\n ($t: ty, $read_name: ident, $read_vec_name: ident, $read_pair_vec_name: ident) => {\n read_impl!($t, $read_name, $read_vec_name);\n\n pub fn $read_pair_vec_name(&mut self, len: usize) -> Vec<($t, $t)> {\n self.read_vec(len)\n }\n };\n}\n\npub struct Input<'s> {\n input: &'s mut dyn Read,\n buf: Vec,\n at: usize,\n buf_read: usize,\n}\n\nimpl<'s> Input<'s> {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(input: &'s mut dyn Read) -> Self {\n Self {\n input,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn new_with_size(input: &'s mut dyn Read, buf_size: usize) -> Self {\n Self {\n input,\n buf: vec![0; buf_size],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn get(&mut self) -> Option {\n if self.refill_buffer() {\n let res = self.buf[self.at];\n self.at += 1;\n Some(res)\n } else {\n None\n }\n }\n\n pub fn peek(&mut self) -> Option {\n if self.refill_buffer() {\n Some(self.buf[self.at])\n } else {\n None\n }\n }\n\n pub fn skip_whitespace(&mut self) {\n while let Some(b) = self.peek() {\n if !char::from(b).is_whitespace() {\n return;\n }\n self.get();\n }\n }\n\n pub fn next_token(&mut self) -> Option> {\n self.skip_whitespace();\n let mut res = Vec::new();\n while let Some(c) = self.get() {\n if char::from(c).is_whitespace() {\n break;\n }\n res.push(c);\n }\n if res.is_empty() {\n None\n } else {\n Some(res)\n }\n }\n\n //noinspection RsSelfConvention\n pub fn is_exhausted(&mut self) -> bool {\n self.peek().is_none()\n }\n\n pub fn read(&mut self) -> T {\n T::read(self)\n }\n\n pub fn read_vec(&mut self, size: usize) -> Vec {\n let mut res = Vec::with_capacity(size);\n for _ in 0usize..size {\n res.push(self.read());\n }\n res\n }\n\n pub fn read_line(&mut self) -> String {\n let mut res = String::new();\n while let Some(c) = self.get() {\n if c == b'\\n' {\n break;\n }\n if c == b'\\r' {\n if self.peek() == Some(b'\\n') {\n self.get();\n }\n break;\n }\n res.push(c.into());\n }\n res\n }\n\n pub fn iter<'t, T: Readable + 't + 's>(&'t mut self) -> InputIterator<'t, 's, T>\n where\n 's: 't,\n {\n InputIterator {\n input: self,\n phantom: Default::default(),\n }\n }\n\n fn read_integer(&mut self) -> T {\n self.skip_whitespace();\n let mut c = self.get().unwrap();\n let sgn = if c == b'-' {\n if !T::SIGNED {\n panic!(\"negative integer\")\n }\n c = self.get().unwrap();\n true\n } else if c == b'+' {\n c = self.get().unwrap();\n false\n } else {\n false\n };\n let mut res = T::zero();\n loop {\n if !c.is_ascii_digit() {\n panic!(\n \"expected integer, found {}{}{}\",\n if sgn { \"-\" } else { \"\" },\n res,\n c as char\n );\n }\n res *= T::from_u8(10);\n res += T::from_u8(c - b'0');\n match self.get() {\n None => {\n break;\n }\n Some(ch) => {\n if char::from(ch).is_whitespace() {\n break;\n } else {\n c = ch;\n }\n }\n }\n }\n if sgn {\n debug_assert!(T::SIGNED);\n res = T::zero() - res\n }\n res\n }\n\n pub fn read_string(&mut self) -> String {\n match self.next_token() {\n None => {\n panic!(\"Input exhausted\");\n }\n Some(res) => unsafe { String::from_utf8_unchecked(res) },\n }\n }\n\n pub fn read_char(&mut self) -> char {\n self.skip_whitespace();\n self.get().unwrap().into()\n }\n\n read_impl!(u8, read_u8, read_u8_vec);\n read_impl!(u16, read_u16, read_u16_vec);\n read_impl!(u32, read_unsigned, read_unsigned_vec);\n read_impl!(u64, read_u64, read_u64_vec);\n read_impl!(u128, read_u128, read_u128_vec);\n read_impl!(usize, read_usize, read_usize_vec, read_usize_pair_vec);\n read_impl!(i8, read_i8, read_i8_vec);\n read_impl!(i16, read_i16, read_i16_vec);\n read_impl!(i32, read_int, read_int_vec, read_int_pair_vec);\n read_impl!(i64, read_long, read_long_vec, read_long_pair_vec);\n read_impl!(i128, read_i128, read_i128_vec);\n read_impl!(isize, read_isize, read_isize_vec);\n read_impl!(f64, read_float, read_float_vec);\n\n fn read_float_impl(&mut self) -> f64 {\n self.read::().parse().unwrap()\n }\n\n fn refill_buffer(&mut self) -> bool {\n if self.at == self.buf_read {\n self.at = 0;\n self.buf_read = self.input.read(&mut self.buf).unwrap();\n self.buf_read != 0\n } else {\n true\n }\n }\n}\n\npub struct InputIterator<'t, 's: 't, T: Readable + 't + 's> {\n input: &'t mut Input<'s>,\n phantom: PhantomData,\n}\n\nimpl<'t, 's: 't, T: Readable + 't + 's> Iterator for InputIterator<'t, 's, T> {\n type Item = T;\n\n fn next(&mut self) -> Option {\n self.input.skip_whitespace();\n self.input.peek().map(|_| self.input.read())\n }\n}\n\npub trait Readable {\n fn read(input: &mut Input) -> Self;\n}\n\nimpl Readable for String {\n fn read(input: &mut Input) -> Self {\n input.read_string()\n }\n}\n\nimpl Readable for char {\n fn read(input: &mut Input) -> Self {\n input.read_char()\n }\n}\n\nimpl Readable for f64 {\n fn read(input: &mut Input) -> Self {\n input.read_float_impl()\n }\n}\n\nimpl Readable for Vec {\n fn read(input: &mut Input) -> Self {\n let size = input.read();\n input.read_vec(size)\n }\n}\n\nmacro_rules! read_integer {\n ($($t:ident)+) => {$(\n impl Readable for $t {\n fn read(input: &mut Input) -> Self {\n input.read_integer()\n }\n }\n )+};\n}\n\nread_integer!(i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize);\n\nmacro_rules! tuple_readable {\n ($($name:ident)+) => {\n impl<$($name: Readable), +> Readable for ($($name,)+) {\n fn read(input: &mut Input) -> Self {\n ($($name::read(input),)+)\n }\n }\n }\n}\n\ntuple_readable! {T}\ntuple_readable! {T U}\ntuple_readable! {T U V}\ntuple_readable! {T U V X}\ntuple_readable! {T U V X Y}\ntuple_readable! {T U V X Y Z}\ntuple_readable! {T U V X Y Z A}\ntuple_readable! {T U V X Y Z A B}\ntuple_readable! {T U V X Y Z A B C}\ntuple_readable! {T U V X Y Z A B C D}\ntuple_readable! {T U V X Y Z A B C D E}\ntuple_readable! {T U V X Y Z A B C D E F}\n}\npub mod output {\nuse std::io::Write;\n\n#[derive(Copy, Clone)]\npub enum BoolOutput {\n YesNo,\n YesNoCaps,\n PossibleImpossible,\n Custom(&'static str, &'static str),\n}\n\nimpl BoolOutput {\n pub fn output(&self, output: &mut Output, val: bool) {\n (if val { self.yes() } else { self.no() }).write(output);\n }\n\n fn yes(&self) -> &str {\n match self {\n BoolOutput::YesNo => \"Yes\",\n BoolOutput::YesNoCaps => \"YES\",\n BoolOutput::PossibleImpossible => \"Possible\",\n BoolOutput::Custom(yes, _) => yes,\n }\n }\n\n fn no(&self) -> &str {\n match self {\n BoolOutput::YesNo => \"No\",\n BoolOutput::YesNoCaps => \"NO\",\n BoolOutput::PossibleImpossible => \"Impossible\",\n BoolOutput::Custom(_, no) => no,\n }\n }\n}\n\npub struct Output {\n output: Box,\n buf: Vec,\n at: usize,\n auto_flush: bool,\n pub bool_output: BoolOutput,\n}\n\nimpl Output {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: false,\n bool_output: BoolOutput::YesNoCaps,\n }\n }\n\n pub fn new_with_auto_flush(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: true,\n bool_output: BoolOutput::YesNoCaps,\n }\n }\n\n pub fn flush(&mut self) {\n if self.at != 0 {\n self.output.write_all(&self.buf[..self.at]).unwrap();\n self.output.flush().unwrap();\n self.at = 0;\n }\n }\n\n pub fn print(&mut self, s: &T) {\n s.write(self);\n }\n\n pub fn put(&mut self, b: u8) {\n self.buf[self.at] = b;\n self.at += 1;\n if self.at == self.buf.len() {\n self.flush();\n }\n }\n\n pub fn maybe_flush(&mut self) {\n if self.auto_flush {\n self.flush();\n }\n }\n\n pub fn print_per_line(&mut self, arg: &[T]) {\n for i in arg {\n i.write(self);\n self.put(b'\\n');\n }\n }\n\n pub fn print_iter>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n\n pub fn print_iter_ref<'a, T: 'a + Writable, I: Iterator>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n}\n\nimpl Write for Output {\n fn write(&mut self, buf: &[u8]) -> std::io::Result {\n let mut start = 0usize;\n let mut rem = buf.len();\n while rem > 0 {\n let len = (self.buf.len() - self.at).min(rem);\n self.buf[self.at..self.at + len].copy_from_slice(&buf[start..start + len]);\n self.at += len;\n if self.at == self.buf.len() {\n self.flush();\n }\n start += len;\n rem -= len;\n }\n if self.auto_flush {\n self.flush();\n }\n Ok(buf.len())\n }\n\n fn flush(&mut self) -> std::io::Result<()> {\n self.flush();\n Ok(())\n }\n}\n\npub trait Writable {\n fn write(&self, output: &mut Output);\n}\n\nimpl Writable for &str {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for String {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for char {\n fn write(&self, output: &mut Output) {\n output.put(*self as u8);\n }\n}\n\nimpl Writable for &[T] {\n fn write(&self, output: &mut Output) {\n output.print_iter_ref(self.iter());\n }\n}\n\nimpl Writable for &T {\n fn write(&self, output: &mut Output) {\n T::write(self, output)\n }\n}\n\nimpl Writable for Vec {\n fn write(&self, output: &mut Output) {\n (&self[..]).write(output);\n }\n}\n\nmacro_rules! write_to_string {\n ($($t:ident)+) => {$(\n impl Writable for $t {\n fn write(&self, output: &mut Output) {\n self.to_string().write(output);\n }\n }\n )+};\n}\n\nwrite_to_string!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize f32 f64);\n\nimpl Writable for (T, U) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n }\n}\n\nimpl Writable for (T, U, V) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n output.put(b' ');\n self.2.write(output);\n }\n}\n\nimpl Writable for (T, U, V, W) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n output.put(b' ');\n self.2.write(output);\n output.put(b' ');\n self.3.write(output);\n }\n}\n\nimpl Writable for (T, U, V, W, X) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n output.put(b' ');\n self.2.write(output);\n output.put(b' ');\n self.3.write(output);\n output.put(b' ');\n self.4.write(output);\n }\n}\n\nimpl Writable for Option {\n fn write(&self, output: &mut Output) {\n match self {\n None => (-1).write(output),\n Some(t) => t.write(output),\n }\n }\n}\n\nimpl Writable for bool {\n fn write(&self, output: &mut Output) {\n let bool_output = output.bool_output;\n bool_output.output(output, *self)\n }\n}\n\npub static mut OUTPUT: Option = None;\n\npub fn output() -> &'static mut Output {\n unsafe {\n match &mut OUTPUT {\n None => {\n panic!(\"Panic\");\n }\n Some(output) => output,\n }\n }\n}\n\n#[macro_export]\nmacro_rules! out {\n ($first: expr $(,$args:expr )*) => {\n $crate::io::output::output().print(&$first);\n $($crate::io::output::output().put(b' ');\n $crate::io::output::output().print(&$args);\n )*\n $crate::io::output::output().maybe_flush();\n }\n}\n\n#[macro_export]\nmacro_rules! out_line {\n ($first: expr $(, $args:expr )* ) => {\n $crate::out!($first $(,$args)*);\n $crate::io::output::output().put(b'\\n');\n $crate::io::output::output().maybe_flush();\n };\n () => {\n output().put(b'\\n');\n output().maybe_flush();\n };\n}\n}\n}\npub mod numbers {\npub mod num_traits {\npub mod add_sub {\nuse std::ops::{Add, AddAssign, Sub, SubAssign};\n\npub trait Addable: Add + AddAssign + Copy {}\nimpl + AddAssign + Copy> Addable for T {}\n\npub trait AddSub: Addable + Sub + SubAssign {}\nimpl + SubAssign> AddSub for T {}\n}\npub mod bit_ops {\nuse crate::numbers::num_traits::zero_one::ZeroOne;\nuse std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Shl};\nuse std::ops::{ShlAssign, Shr, ShrAssign};\n\npub trait BitOps:\n Copy\n + BitAnd\n + BitAndAssign\n + BitOr\n + BitOrAssign\n + BitXor\n + BitXorAssign\n + Not\n + Shl\n + ShlAssign\n + Shr\n + ShrAssign\n + ZeroOne\n + PartialEq\n{\n fn bit(at: usize) -> Self {\n Self::one() << at\n }\n\n fn is_set(&self, at: usize) -> bool {\n (*self >> at & Self::one()) == Self::one()\n }\n\n fn set_bit(&mut self, at: usize) {\n *self |= Self::bit(at)\n }\n\n fn unset_bit(&mut self, at: usize) {\n *self &= !Self::bit(at)\n }\n\n #[must_use]\n fn with_bit(mut self, at: usize) -> Self {\n self.set_bit(at);\n self\n }\n\n #[must_use]\n fn without_bit(mut self, at: usize) -> Self {\n self.unset_bit(at);\n self\n }\n\n fn flip_bit(&mut self, at: usize) {\n *self ^= Self::bit(at)\n }\n\n fn all_bits(n: usize) -> Self {\n let mut res = Self::zero();\n for i in 0..n {\n res.set_bit(i);\n }\n res\n }\n}\n\nimpl<\n T: Copy\n + BitAnd\n + BitAndAssign\n + BitOr\n + BitOrAssign\n + BitXor\n + BitXorAssign\n + Not\n + Shl\n + ShlAssign\n + Shr\n + ShrAssign\n + ZeroOne\n + PartialEq,\n > BitOps for T\n{\n}\n\npub trait Bits: BitOps {\n fn bits() -> u32;\n}\n\nmacro_rules! bits_integer_impl {\n ($($t: ident $bits: expr),+) => {$(\n impl Bits for $t {\n fn bits() -> u32 {\n $bits\n }\n }\n )+};\n}\n\nbits_integer_impl!(i128 128, i64 64, i32 32, i16 16, i8 8, isize 64, u128 128, u64 64, u32 32, u16 16, u8 8, usize 64);\n}\npub mod from_u8 {\npub trait FromU8 {\n fn from_u8(val: u8) -> Self;\n}\n\nmacro_rules! from_u8_impl {\n ($($t: ident)+) => {$(\n impl FromU8 for $t {\n fn from_u8(val: u8) -> Self {\n val as $t\n }\n }\n )+};\n}\n\nfrom_u8_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize f32 f64);\n}\npub mod mul_div_rem {\nuse std::ops::{Div, DivAssign, Mul, MulAssign, Rem, RemAssign};\n\npub trait Multable: Mul + MulAssign + Copy {}\nimpl + MulAssign + Copy> Multable for T {}\n\npub trait MulDiv: Multable + Div + DivAssign {}\nimpl + DivAssign> MulDiv for T {}\n\npub trait MulDivRem: MulDiv + Rem + RemAssign {}\nimpl + RemAssign> MulDivRem for T {}\n}\npub mod sign {\npub trait IsSigned {\n const SIGNED: bool;\n}\n\npub trait Signed: IsSigned {}\n\npub trait Unsigned: IsSigned {}\n\nmacro_rules! unsigned_impl {\n ($($t: ident)+) => {$(\n impl Unsigned for $t {}\n\n impl IsSigned for $t {\n const SIGNED: bool = false;\n }\n )+};\n}\n\nunsigned_impl!(u128 u64 u32 u16 u8 usize);\n\nmacro_rules! signed_impl {\n ($($t: ident)+) => {$(\n impl Signed for $t {}\n\n impl IsSigned for $t {\n const SIGNED: bool = true;\n }\n )+};\n}\n\nsigned_impl!(i128 i64 i32 i16 i8 isize f64 f32);\n}\npub mod zero_one {\npub trait ZeroOne {\n fn zero() -> Self;\n fn one() -> Self;\n}\n\nmacro_rules! zero_one_integer_impl {\n ($($t: ident)+) => {$(\n impl ZeroOne for $t {\n fn zero() -> Self {\n 0\n }\n\n fn one() -> Self {\n 1\n }\n }\n )+};\n}\n\nzero_one_integer_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize);\n\nmacro_rules! zero_one_float_impl {\n ($($t: ident)+) => {$(\n impl ZeroOne for $t {\n fn zero() -> Self {\n 0.\n }\n\n fn one() -> Self {\n 1.\n }\n }\n )+};\n}\n\nzero_one_float_impl!(f32 f64);\n}\n}\n}\nfn main() {\n let mut sin = std::io::stdin();\n let input = crate::io::input::Input::new(&mut sin);\n unsafe {\n crate::io::output::OUTPUT = Some(crate::io::output::Output::new(Box::new(std::io::stdout())));\n }\n crate::solution::run(input);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "7aaa97f44362b324ca940546e1b74b70", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn main() {\n let (r, w) = (std::io::stdin(), std::io::stdout());\n let mut sc = IO::new(r.lock(), w.lock());\n\n let t: usize = sc.read();\n for _ in 0..t {\n let x = sc.usize0();\n let t: Vec = sc.vec(3);\n\n let mut cur = x;\n let key = t[cur];\n if key == 0 {\n println!(\"NO\");\n continue;\n }\n cur = key - 1;\n let key = t[cur];\n if key == 0 {\n println!(\"NO\");\n continue;\n }\n println!(\"YES\");\n }\n}\n\npub struct IO(R, std::io::BufWriter);\n\nimpl IO {\n pub fn new(r: R, w: W) -> Self {\n Self(r, std::io::BufWriter::new(w))\n }\n pub fn write(&mut self, s: S) {\n use std::io::Write;\n self.1.write_all(s.to_string().as_bytes()).unwrap();\n }\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let buf = self\n .0\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn usize0(&mut self) -> usize {\n self.read::() - 1\n }\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "47acdeedc1299b01a05bfe513b93ae00", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::BTreeSet;\nuse std::io::{self, prelude::*};\nuse std::iter;\n\nfn solve(scan: &mut input::Scanner, out: &mut W) {\n let mut keys: BTreeSet = iter::once(scan.token()).collect();\n let doors: Vec<_> = (1..=3).map(|_| scan.token::()).collect();\n loop {\n let prev = keys.clone();\n for key in &prev {\n if doors[key - 1] != 0 {\n keys.insert(doors[key - 1]);\n }\n }\n if prev.len() == keys.len() {\n break;\n }\n }\n let answer = if keys.len() == 3 { \"YES\" } else { \"NO\" };\n writeln!(out, \"{answer}\").unwrap();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = input::Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n let t: i32 = scan.token();\n for _ in 1..=t {\n solve(&mut scan, &mut out);\n }\n}\n\nmod input {\n use std::io::prelude::*;\n use std::mem;\n use std::str;\n\n pub struct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitWhitespace<'static>,\n }\n impl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_whitespace(),\n }\n }\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n mem::transmute(slice.split_whitespace())\n }\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "19e74354120e9ed62230cd3241c87917", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "/* This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. */\n\nuse std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Read, Stdin, Stdout, Write};\n\nstruct Io\nwhere\n Input: Read,\n Output: Write,\n{\n input: BufReader,\n output: BufWriter,\n buffer: Vec,\n}\n\n#[allow(dead_code)]\nimpl Io\nwhere\n Input: Read,\n Output: Write,\n{\n fn new(input: Input, output: Output) -> Self {\n Self {\n input: BufReader::new(input),\n output: BufWriter::new(output),\n buffer: vec![],\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.input.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n fn print(&mut self, value: impl std::fmt::Display) {\n writeln!(self, \"{}\", value).ok();\n }\n\n fn prints(&mut self, items: &[impl std::fmt::Display], sep: &str) {\n writeln!(\n self,\n \"{}\",\n items\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(sep)\n )\n .ok();\n }\n}\n\nimpl Write for Io\nwhere\n Input: Read,\n Output: Write,\n{\n fn write(&mut self, buf: &[u8]) -> std::io::Result {\n self.output.write(buf)\n }\n\n fn flush(&mut self) -> std::io::Result<()> {\n self.output.flush()\n }\n}\n\nimpl Default for Io {\n fn default() -> Self {\n Self::new(stdin(), stdout())\n }\n}\n\nfn main() {\n let mut io = Io::default();\n for _ in 0..io.next() {\n let x: usize = io.next();\n let a: &[usize] = &[io.next(), io.next(), io.next()];\n if a[x - 1] == 0 {\n io.print(\"NO\");\n } else if a[a[x - 1] - 1] == 0 {\n io.print(\"NO\");\n } else {\n io.print(\"YES\");\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "29e96beb04a701d418d71a3b9f52fd00", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::{io::{BufRead, BufWriter, Write}, hash::Hash};\r\n#[allow(unused)]\r\nuse std::{{collections::*, mem::swap},cmp::Reverse};\r\n\r\nfn main() {\r\n let sin = std::io::stdin();\r\n let scan = &mut Scanner::new(sin.lock());\r\n let sout = std::io::stdout();\r\n let out = &mut BufWriter::new(sout.lock());\r\n solve_wrapper(scan, out, solve);\r\n}\r\n\r\n#[allow(unused)]\r\n#[macro_export]\r\nmacro_rules! logln {\r\n ($($arg:tt)*) => ({\r\n #[cfg(debug_assertions)]\r\n println!($($arg)*);\r\n })\r\n}\r\n\r\ntrait MapX {\r\n fn update_with V>(&mut self, key:K, get_new_value:F);\r\n}\r\nmacro_rules! update_with { () => {\r\n fn update_with V>(&mut self, key:K, get_new_value:F) {\r\n let v = self.entry(key).or_default();\r\n let nv = get_new_value(v);\r\n *v = nv;\r\n }\r\n} }\r\nimpl MapX for BTreeMap {\r\n update_with!();\r\n}\r\nimpl MapX for HashMap {\r\n update_with!();\r\n}\r\n\r\ntrait UsizeX {\r\n fn i64(self) -> i64;\r\n}\r\nimpl UsizeX for usize {\r\n fn i64(self) -> i64 {\r\n self as i64\r\n }\r\n}\r\n\r\npub struct Scanner {\r\n reader: R,\r\n buffer: Vec,\r\n}\r\nimpl Scanner {\r\n pub fn new(reader: R) -> Self {\r\n Self { reader, buffer: vec![] }\r\n }\r\n pub fn token(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n let mut input = String::new();\r\n self.reader.read_line(&mut input).expect(\"Failed read\");\r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n }\r\n }\r\n pub fn line(&mut self) -> Vec {\r\n if !self.buffer.is_empty() {\r\n panic!(\"Consume token buffer before read a line.\");\r\n }\r\n let mut input = String::new();\r\n self.reader.read_line(&mut input).expect(\"Failed read\");\r\n input.split_whitespace().map(|v| v.parse().ok().expect(\"Failed parse\")).collect()\r\n }\r\n pub fn line_withT>(&mut self, f: F) -> Vec {\r\n return self.line().iter().map(f).collect::>();\r\n }\r\n}\r\n\r\n#[cfg(test)]\r\nmod abc999x {\r\n use super::*;\r\n\r\n macro_rules! test_macro {\r\n ($name:ident, | $input:expr,) => {\r\n #[test]\r\n fn $name() {\r\n let vi = $input.split(\"\\n\").collect::>();\r\n let vi = &vi[..vi.len()-1];\r\n let mut inp = String::new();\r\n let mut cnt=0;\r\n for &line in vi {\r\n if line.starts_with(\"output\") { break; }\r\n cnt+=1;\r\n if line.starts_with(\"input\") || line.starts_with(\"Copy\") { continue; }\r\n inp+=line; inp+=\"\\n\";\r\n }\r\n let mut exp = String::new();\r\n for &line in &vi[cnt..] {\r\n if line.starts_with(\"output\") || line.starts_with(\"Copy\") { continue; }\r\n exp+=line; exp+=\"\\n\";\r\n }\r\n let output = &mut Vec::new();\r\n let scan = &mut Scanner::new(inp.as_bytes());\r\n solve_wrapper(scan, output, solve);\r\n assert_eq!(exp, std::str::from_utf8(output).unwrap());\r\n }\r\n };\r\n ($name:ident, $($n:ident),*, | $input:expr, $($i:expr),*,) => {\r\n test_macro!($name, | $input,);\r\n test_macro!($($n),*, | $($i),*,);\r\n };\r\n }\r\n\r\n test_macro!(\r\nest0,\r\ntest1,\r\ntest2,\r\ntest3,\r\n|\r\n// Example 0\r\n\"\\\r\ninputCopy\r\n\",\r\n// Example 1\r\n\"\\\r\ninputCopy\r\n4\r\n3\r\n0 1 2\r\n1\r\n0 3 2\r\n2\r\n3 1 0\r\n2\r\n1 3 0\r\noutputCopy\r\nYES\r\nNO\r\nYES\r\nNO\r\n\",\r\n// Example 2\r\n\"\\\r\ninput\r\n\",\r\n// Example 3\r\n\"\\\r\ninput\r\n\",\r\n);\r\n\r\n}\r\n\r\nfn solve_wrapper(scan: &mut Scanner, out: &mut W, mut solve: F)\r\n where B: BufRead, W: Write, F:FnMut(&mut Scanner, &mut W)\r\n {\r\n //let t = 1;\r\n let t = scan.token::();\r\n for _ in 0..t {\r\n solve(scan,out);\r\n }\r\n}\r\n\r\nfn solve(scan: &mut Scanner, out: &mut impl Write) {\r\n let mut x = scan.token::();\r\n let va = scan.line::();\r\n let mut vf = vec![false;3];\r\n loop {\r\n vf[x-1] = true;\r\n x = va[x-1];\r\n if x == 0 {\r\n break;\r\n }\r\n }\r\n let ok = vf.iter().all(|&v| v);\r\n\r\n if ok {\r\n writeln!(out, \"YES\" ).ok();\r\n } else {\r\n writeln!(out, \"NO\" ).ok();\r\n }\r\n\r\n}\r\n\r\n\r\n\r\n\r\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "f264e2c01cecd2c403a661938da1c4d0", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn solve() {\r\n input! {\r\n mut x: usize1,\r\n d: [usize; 3],\r\n }\r\n for _ in 0..2 {\r\n if d[x] == 0 {\r\n println!(\"NO\");\r\n return;\r\n }\r\n x = d[x] - 1;\r\n }\r\n println!(\"YES\");\r\n}\r\n\r\nfn main() {\r\n input! {\r\n t: usize,\r\n }\r\n for _ in 0..t {\r\n solve();\r\n }\r\n}\r\n\r\nmod io {\r\n use std::cell::RefCell;\r\n use std::io::*;\r\n\r\n std::thread_local! {\r\n pub static STDIN: RefCell = RefCell::new(stdin());\r\n pub static STDOUT: RefCell> = RefCell::new(BufWriter::new(stdout()));\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! input {\r\n () => {};\r\n (mut $var:ident: $t:tt, $($rest:tt)*) => {\r\n let mut $var = __input_inner!($t);\r\n input!($($rest)*)\r\n };\r\n ($var:ident: $t:tt, $($rest:tt)*) => {\r\n let $var = __input_inner!($t);\r\n input!($($rest)*)\r\n };\r\n (mut $var:ident: $t:tt) => {\r\n let mut $var = __input_inner!($t);\r\n };\r\n ($var:ident: $t:tt) => {\r\n let $var = __input_inner!($t);\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! __input_inner {\r\n (($($t:tt),*)) => {\r\n ($(__input_inner!($t)),*)\r\n };\r\n ([$t:tt; $n:expr]) => {\r\n (0..$n).map(|_| __input_inner!($t)).collect::>()\r\n };\r\n ([$t:tt]) => {{\r\n let n = __input_inner!(usize);\r\n (0..n).map(|_| __input_inner!($t)).collect::>()\r\n }};\r\n (chars) => {\r\n __input_inner!(String).chars().collect::>()\r\n };\r\n (bytes) => {\r\n __input_inner!(String).into_bytes()\r\n };\r\n (usize1) => {\r\n __input_inner!(usize) - 1\r\n };\r\n ($t:ty) => {\r\n $crate::io::STDIN.with(|r| {\r\n use std::io::BufRead;\r\n let r = r.borrow_mut();\r\n let mut r = r.lock();\r\n let mut s = vec![];\r\n loop {\r\n let buf = r.fill_buf().unwrap();\r\n if buf.is_empty() {\r\n break;\r\n }\r\n if let Some(i) = buf.iter().position(u8::is_ascii_whitespace) {\r\n s.extend_from_slice(&buf[..i]);\r\n r.consume(i + 1);\r\n if !s.is_empty() {\r\n break;\r\n }\r\n } else {\r\n s.extend_from_slice(buf);\r\n let n = buf.len();\r\n r.consume(n);\r\n }\r\n }\r\n std::str::from_utf8(&s).unwrap().parse::<$t>().unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! println {\r\n () => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::writeln!(w.borrow_mut()).unwrap()\r\n })\r\n };\r\n ($($arg:tt)*) => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::writeln!(w.borrow_mut(), $($arg)*).unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! print {\r\n ($($arg:tt)*) => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::write!(w.borrow_mut(), $($arg)*).unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! flush {\r\n () => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n w.borrow_mut().flush().unwrap()\r\n })\r\n };\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "7ae81b4d0b53e694d039f90fc63a6030", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io;\nuse std::ops;\nuse std::str::FromStr;\n\n#[derive(Clone, Debug, Default)]\nstruct ProblemState {\n}\n\nimpl Problem {\n fn solve(&mut self) {\n let n: u64 = self.scan();\n\n let mut ans1 = 1u64;\n let mut ans2 = 1u64;\n\n const MOD: u64 = 1_000_000_007;\n\n for i in 2..n + 1 {\n ans1 *= i;\n ans1 %= MOD;\n ans2 *= 2;\n ans2 %= MOD;\n }\n\n println!(\"{}\", (ans1 - ans2 + MOD) % MOD);\n }\n}\n\nfn main() {\n Problem::new().solve();\n}\n\nstruct Problem {\n input_state: InputState,\n problem_state: ProblemState,\n}\n\nstruct InputState {\n stdin: io::Stdin,\n buffer: String,\n tokens: VecDeque,\n}\n\nimpl Problem {\n fn new() -> Self {\n Self {\n input_state: InputState {\n stdin: io::stdin(),\n buffer: String::new(),\n tokens: VecDeque::new(),\n },\n problem_state: Default::default(),\n }\n }\n\n fn solve_cases(&mut self) {\n for _ in 0usize..self.scan() {\n self.solve()\n }\n }\n\n fn scan(&mut self) -> T {\n while self.input_state.tokens.is_empty() {\n self.input_state.stdin.read_line(&mut self.input_state.buffer).unwrap();\n\n for token in self.input_state.buffer.split_ascii_whitespace() {\n self.input_state.tokens.push_back(token.to_string());\n }\n\n self.input_state.buffer.clear();\n }\n\n self.input_state.tokens.pop_front().unwrap().parse().ok().unwrap()\n }\n\n fn scan_vec(&mut self, n: usize) -> Vec {\n (0..n).into_iter().map(|_| self.scan()).collect()\n }\n\n fn scan_line(&mut self) -> String {\n let mut line = String::new();\n self.input_state.stdin.read_line(&mut line).unwrap();\n while line.ends_with('\\n') || line.ends_with('\\r') { line.pop(); }\n line\n }\n\n fn scan_line_vec(&mut self, n: usize) -> Vec {\n (0..n).into_iter().map(|_| self.scan_line()).collect()\n }\n}\n\nimpl ops::Deref for Problem {\n type Target = ProblemState;\n\n fn deref(&self) -> &ProblemState {\n &self.problem_state\n }\n}\n\nimpl ops::DerefMut for Problem {\n fn deref_mut(&mut self) -> &mut ProblemState {\n &mut self.problem_state\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "f89a0505f8bc882e6a51fa4e668a394a", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\n#[derive(Debug, Copy, Clone)]\npub struct ModInt {\n x: i64,\n global_mod: i64,\n}\nimpl ModInt {\n pub fn new(p: i64) -> Self {\n let gm = 1000000007;\n let a = (p % gm + gm) % gm;\n return ModInt {\n x: a,\n global_mod: gm,\n };\n }\n pub fn inv(self) -> Self {\n return self.pow(self.global_mod - 2);\n }\n pub fn pow(self, t: i64) -> Self {\n if (t == 0) {\n return ModInt::new(1);\n };\n let mut a = self.pow(t >> 1);\n a = a * a;\n if (t & 1 != 0) {\n a = a * self\n };\n return a;\n }\n}\nimpl Add for ModInt {\n type Output = ModInt;\n fn add(self, other: ModInt) -> ModInt {\n let ret = self.x + other.x;\n return ModInt::new(ret);\n }\n}\nimpl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, other: ModInt) -> ModInt {\n let ret = self.x - other.x;\n return ModInt::new(ret);\n }\n}\nimpl Mul for ModInt {\n type Output = ModInt;\n fn mul(self, other: ModInt) -> ModInt {\n let ret = self.x * other.x;\n return ModInt::new(ret);\n }\n}\nimpl Div for ModInt {\n type Output = ModInt;\n fn div(self, other: ModInt) -> ModInt {\n let ret = self.x * other.inv().x;\n return ModInt::new(ret);\n }\n}\nimpl std::string::ToString for ModInt {\n fn to_string(&self) -> String {\n return self.x.to_string();\n }\n}\npub struct Combination {\n fact: Vec,\n ifact: Vec,\n}\nimpl Combination {\n pub fn new(n: i32) -> Self {\n if n > 3000000 {\n panic!(\"error\");\n }\n let mut fact = vec![ModInt::new(0); (n + 1) as usize];\n let mut ifact = vec![ModInt::new(0); (n + 1) as usize];\n fact[0] = ModInt::new(1);\n for i in 1..n + 1 {\n fact[i as usize] = fact[(i - 1) as usize] * ModInt::new(i as i64)\n }\n ifact[n as usize] = fact[n as usize].inv();\n for i in (1..n + 1).rev() {\n ifact[(i - 1) as usize] = ifact[i as usize] * ModInt::new(i as i64)\n }\n let a = Combination {\n fact: fact,\n ifact: ifact,\n };\n return a;\n }\n #[macro_use]\n pub fn gen(&mut self, n: i32, k: i32) -> ModInt {\n if (k < 0 || k > n) {\n return ModInt::new(0 as i64);\n };\n return self.fact[n as usize] * self.ifact[k as usize] * self.ifact[(n - k) as usize];\n }\n pub fn P(&mut self, n: i32, k: i32) -> ModInt {\n self.fact[n as usize] * self.ifact[(n - k) as usize]\n }\n}\n\nfn main() {\n let N = get!(usize);\n let mut ans = ModInt::new(0);\n let mut cmb = Combination::new(1000006);\n for m in 0..N {\n ans = ans + cmb.gen((N - 1) as i32, m as i32);\n }\n let mut a = cmb.P(N as i32, N as i32);\n ans = a - ans;\n\n echo!(ans.to_string());\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "d95ec97726aad6fe947f6a2c947c66ff", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Read, Write};\n\nfn main() {\n let mut stdin = io::stdin();\n // From https://keens.github.io/blog/2017/10/05/rustdekousokunahyoujunshutsuryoku/\n let stdout = io::stdout();\n let mut output = BufWriter::new(stdout.lock());\n let mut input_str = String::new();\n let _ = stdin.read_to_string(&mut input_str);\n let mut input_iter = input_str.split_ascii_whitespace();\n // From https://github.com/rust-lang-ja/atcoder-rust-resources/wiki/2020-Update#proconio\n sub_main(&mut input_iter, &mut output);\n}\n\nfn sub_main(input_iter: &mut dyn Iterator, output: &mut dyn Write) {\n macro_rules! read(() => (input_iter.next().unwrap().parse().unwrap()));\n macro_rules! print(( $( $x:expr ),*) => (write!(output, $($x,)*).unwrap()));\n macro_rules! println(( $( $x:expr ),*) => (writeln!(output, $($x,)*).unwrap()));\n // Deal with each case\n let n: usize = read!();\n let non_cyclic = ModP(2).pow(n - 1);\n let mut total_num = ModP(1);\n for i in 1..=n {\n total_num = total_num * ModP(i as u64);\n }\n let ans = total_num - non_cyclic;\n println!(\"{}\", ans.0);\n}\n\nuse std::ops::{Add, Div, Mul, Sub};\n\nconst MODULUS: u64 = 1000000007;\n\n#[derive(Clone, Copy, PartialEq, Debug)]\nstruct ModP(u64);\n\nimpl Add for ModP {\n type Output = Self;\n fn add(self, rhs: Self) -> Self {\n return ModP((self.0 + rhs.0) % MODULUS);\n }\n}\nimpl Sub for ModP {\n type Output = Self;\n fn sub(self, rhs: Self) -> Self {\n return ModP((self.0 + MODULUS - rhs.0) % MODULUS);\n }\n}\nimpl Mul for ModP {\n type Output = Self;\n fn mul(self, rhs: Self) -> Self {\n return ModP((self.0 * rhs.0) % MODULUS);\n }\n}\nimpl Div for ModP {\n type Output = Self;\n fn div(self, rhs: Self) -> Self {\n if rhs.0 == 0 {\n panic!(\"Tried to divide by ModP(0)!\");\n }\n let rhs_inv = rhs.pow((MODULUS - 2) as usize);\n return self * rhs_inv;\n }\n}\n\nimpl ModP {\n fn pow(&self, n: usize) -> Self {\n if n == 0 {\n return ModP(1);\n } else if n == 1 {\n return *self;\n } else {\n let half = self.pow(n / 2);\n if n % 2 == 0 {\n return half * half;\n } else {\n return half * half * (*self);\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "df6baa22596c4e86ef84b343b821b03c", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let n: u32 = input.trim().parse().unwrap();\n let mut pow = 1u32;\n let p = 1000000007u32;\n for _i in 0..(n-1) {\n pow = (pow as u64 * 2u64 % p as u64) as u32;\n }\n// println!(\"{}\", pow);\n let mut fact = 1u32;\n for i in 2..(n+1) {\n fact = (fact as u64 * i as u64 % p as u64) as u32;\n }\n// println!(\"{}\", fact);\n let ans;\n if fact < pow {\n ans = fact + p - pow;\n } else {\n ans = fact - pow;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "ed65958d493e759d62b7b6e9368ae3ac", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nconst MOD: i64 = 1_000_000_007;\n\nfn f(n: i64) -> i64 {\n let mut prod_n = 1;\n let mut prod_2 = 1;\n for i in 1..=n {\n prod_n = (prod_n * i) % MOD;\n }\n for i in 1..n {\n prod_2 = (prod_2 * 2) % MOD;\n }\n (prod_n - prod_2).rem_euclid(MOD)\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: i64 = scan.token();\n let ans = f(n);\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "35d16500de96100c308b6618b5e9e1d3", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nmod modint {\n\n #[allow(dead_code)]\n pub struct Mod;\n impl ConstantModulo for Mod {\n const MOD: u32 = 1_000_000_007;\n }\n\n #[allow(dead_code)]\n pub struct StaticMod;\n static mut STATIC_MOD: u32 = 0;\n impl Modulo for StaticMod {\n fn modulo() -> u32 {\n unsafe { STATIC_MOD }\n }\n }\n\n #[allow(dead_code)]\n impl StaticMod {\n pub fn set_modulo(p: u32) {\n unsafe {\n STATIC_MOD = p;\n }\n }\n }\n\n use std::marker::*;\n use std::ops::*;\n\n pub trait Modulo {\n fn modulo() -> u32;\n }\n\n pub trait ConstantModulo {\n const MOD: u32;\n }\n\n impl Modulo for T\n where\n T: ConstantModulo,\n {\n fn modulo() -> u32 {\n T::MOD\n }\n }\n\n pub struct ModInt(pub u32, PhantomData);\n\n impl Clone for ModInt {\n fn clone(&self) -> Self {\n ModInt::new_unchecked(self.0)\n }\n }\n\n impl Copy for ModInt {}\n\n impl Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: Self) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n ModInt::new_unchecked(d)\n }\n }\n\n impl AddAssign for ModInt {\n fn add_assign(&mut self, rhs: Self) {\n *self = *self + rhs;\n }\n }\n\n impl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: Self) -> Self::Output {\n let mut d = T::modulo() + self.0 - rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n ModInt::new_unchecked(d)\n }\n }\n\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: Self) {\n *self = *self - rhs;\n }\n }\n\n impl Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: Self) -> Self::Output {\n let v = self.0 as u64 * rhs.0 as u64 % T::modulo() as u64;\n ModInt::new_unchecked(v as u32)\n }\n }\n\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: Self) {\n *self = *self * rhs;\n }\n }\n\n impl Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n if self.0 == 0 {\n Self::zero()\n } else {\n Self::new_unchecked(T::modulo() - self.0)\n }\n }\n }\n\n impl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n\n impl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n }\n\n impl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: u64) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: i64) -> ModInt {\n let m = T::modulo() as i64;\n ModInt::new((val % m + m) as u32)\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n pub fn new_unchecked(d: u32) -> Self {\n ModInt(d, PhantomData)\n }\n pub fn zero() -> Self {\n ModInt::new_unchecked(0)\n }\n pub fn one() -> Self {\n ModInt::new_unchecked(1)\n }\n pub fn is_zero(&self) -> bool {\n self.0 == 0\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n pub fn new(d: u32) -> Self {\n ModInt::new_unchecked(d % T::modulo())\n }\n pub fn pow(&self, mut n: u64) -> Self {\n let mut t = Self::one();\n let mut s = *self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(&self) -> Self {\n assert!(self.0 != 0);\n self.pow(T::modulo() as u64 - 2)\n }\n }\n\n #[allow(dead_code)]\n pub fn mod_pow(r: u64, mut n: u64, m: u64) -> u64 {\n let mut t = 1 % m;\n let mut s = r % m;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s % m;\n }\n s = s * s % m;\n n >>= 1;\n }\n t\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\nmod precalc {\n use super::modint::*;\n #[allow(dead_code)]\n pub struct Precalc {\n inv: Vec>,\n fact: Vec>,\n ifact: Vec>,\n }\n #[allow(dead_code)]\n impl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);\n }\n ifact[n] = fact[n].inv();\n if n > 0 {\n inv[n] = ifact[n] * fact[n - 1];\n }\n for i in (1..n).rev() {\n ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);\n inv[i] = ifact[i] * fact[i - 1];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n assert!(n > 0);\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[n - k]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n }\n}\n// ---------- end Precalc ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nuse std::io::Write;\n\nuse modint::*;\nuse precalc::*;\n\ntype M = ModInt;\n\nfn run() {\n input! {\n n: usize,\n }\n let pc = Precalc::new(n);\n let ans: M = pc.fact(n) - ModInt::new(2).pow((n - 1) as u64);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "40827ff65ee77e1f880f13a0a28ed6df", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::*;\n\n// scanner from https://codeforces.com/contest/1396/submission/91365784\nstruct Scanner {\n stdin: Stdin,\n buffer: VecDeque,\n}\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Self {\n Scanner {\n stdin: stdin(),\n buffer: VecDeque::new(),\n }\n }\n fn cin(&mut self) -> T {\n while self.buffer.is_empty() {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n self.buffer.pop_front().unwrap().parse::().ok().unwrap()\n }\n fn chars(&mut self) -> Vec {\n self.cin::().chars().collect()\n }\n fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.cin()).collect()\n }\n fn u(&mut self) -> usize {\n self.cin()\n }\n fn vecu(&mut self, n: usize) -> Vec {\n self.vec(n)\n }\n}\n\n//\n// ModInt\n//\n\nconst M: i64 = 1000_000_007;\n#[derive(Debug, PartialEq, Eq, Clone, Copy)]\nstruct ModInt {\n val: i64,\n}\n#[allow(dead_code)]\nconst M0: ModInt = ModInt { val: 0 };\nconst M1: ModInt = ModInt { val: 1 };\n//const M_ERROR: ModInt = ModInt { val: -1 };\n\nimpl ModInt {\n fn new(v: i64) -> ModInt {\n ModInt {\n val: ModInt::val_from_i64(v),\n }\n }\n #[allow(dead_code)]\n fn new_raw(v: i64) -> ModInt {\n ModInt { val: v }\n }\n fn val_from_i64(v: i64) -> i64 {\n let t = v % M;\n if t < 0 {\n t + M\n } else {\n t\n }\n }\n fn val_from_addval(t: i64) -> i64 {\n if t >= M {\n t - M\n } else {\n t\n }\n }\n\n fn pow(self, exp: i64) -> ModInt {\n if exp == 0 {\n M1\n } else {\n let x = self.pow(exp / 2);\n if exp % 2 == 0 {\n x * x\n } else {\n self * x * x\n }\n }\n }\n\n fn inv(self) -> ModInt {\n self.pow(M - 2)\n }\n}\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> ModInt {\n ModInt {\n val: ModInt::val_from_addval(self.val + rhs.val),\n }\n }\n}\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: i64) -> ModInt {\n ModInt {\n val: ModInt::val_from_i64(self.val + rhs),\n }\n }\n}\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, other: ModInt) {\n self.val = ModInt::val_from_addval(self.val + other.val);\n }\n}\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, other: i64) {\n self.val = ModInt::val_from_i64(self.val + other);\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> ModInt {\n ModInt {\n val: ModInt::val_from_addval(self.val - rhs.val + M),\n }\n }\n}\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: i64) -> ModInt {\n self - ModInt::new(rhs)\n }\n}\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, other: ModInt) {\n self.val = ModInt::val_from_addval(self.val - other.val + M);\n }\n}\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, other: i64) {\n self.val = ModInt::val_from_i64(self.val - other);\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> ModInt {\n ModInt {\n val: if self.val == 0 { 0 } else { M - self.val },\n }\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> ModInt {\n ModInt {\n val: self.val * rhs.val % M,\n }\n }\n}\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: i64) -> ModInt {\n self * ModInt::new(rhs)\n }\n}\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, other: ModInt) {\n self.val = self.val * other.val % M;\n }\n}\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, other: i64) {\n self.mul_assign(ModInt::new(other));\n }\n}\n\nimpl std::ops::Div for ModInt {\n type Output = ModInt;\n fn div(self, rhs: ModInt) -> ModInt {\n self * rhs.inv()\n }\n}\nimpl std::ops::Div for ModInt {\n type Output = ModInt;\n fn div(self, rhs: i64) -> ModInt {\n self / ModInt::new(rhs)\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n // '\n write!(f, \"{}\", self.val)\n }\n}\n\n//\n// nCr\n//\n#[derive(Debug, Clone)]\nstruct Comb {\n fac: Vec,\n finv: Vec,\n inv: Vec,\n}\n\nimpl Comb {\n fn new(size: usize) -> Comb {\n let mut fac = vec![M1; size];\n let mut finv = vec![M1; size];\n let mut inv = vec![M1; size];\n\n for i in 2..size {\n fac[i] = fac[i - 1] * (i as i64);\n inv[i] = -inv[M as usize % i] * (M / (i as i64));\n finv[i] = finv[i - 1] * inv[i];\n }\n\n return Comb {\n fac: fac,\n finv: finv,\n inv: inv,\n };\n }\n}\ntrait CombC {\n fn c(&self, n: T, k: T) -> ModInt;\n fn p(&self, n: T, k: T) -> ModInt;\n}\n\nimpl CombC for Comb {\n fn c(&self, n: usize, k: usize) -> ModInt {\n if n < k {\n M0\n } else {\n self.fac[n] * self.finv[k] * self.finv[n - k]\n }\n }\n fn p(&self, n: usize, k: usize) -> ModInt {\n if n < k {\n M0\n } else {\n self.fac[n] * self.finv[n - k]\n }\n }\n}\n\nimpl CombC for Comb {\n fn c(&self, n: i64, k: i64) -> ModInt {\n if n < 0 || k < 0 || n < k {\n M0\n } else {\n self.c(n as usize, k as usize)\n }\n }\n fn p(&self, n: i64, k: i64) -> ModInt {\n if n < 0 || k < 0 || n < k {\n M0\n } else {\n self.p(n as usize, k as usize)\n }\n }\n}\n\n#[derive(Clone, Debug, Default)]\nstruct Solver {}\n\nimpl Solver {\n fn solve(&mut self, scan: &mut Scanner, out: &mut BufWriter) {\n // 1391c\n let n = scan.u();\n\n /*\n cyclic\u3067\u306a\u3044 == p\u306b\u8c37\u304c\u7121\u3044\u3001\u3064\u307e\u308a p[j]==n\u306a\u3089p[0..=j]\u306f\u5897\u52a0\u3001p[j..n]\u306f\u6e1b\u5c11\n */\n let comb = Comb::new(n + 1);\n let mut ans = M0;\n for j in 0..n {\n ans += comb.c(n - 1, j);\n }\n\n writeln!(out, \"{}\", comb.p(n, n) - ans).ok();\n }\n}\n\nfn solve() {\n let mut scan = Scanner::new();\n let out = &mut BufWriter::new(stdout());\n\n let testcase = 1;\n //let testcase: usize = scan.cin();\n for _ in 0..testcase {\n let mut s: Solver = Default::default();\n s.solve(&mut scan, out);\n }\n}\n\nfn main() {\n let th = std::thread::Builder::new().stack_size(64 * 1024 * 1024);\n th.spawn(|| solve()).unwrap().join().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "d7735e313c8d823d048bf46769f1312b", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn mpow(mut base: u32, mut ex: u32, p: u32) -> u32 {\n let mut ans = 1u32;\n while ex != 0 {\n if ex & 1u32 != 0 {\n ans = (ans as u64 * base as u64 % p as u64) as u32;\n }\n base = (base as u64 * base as u64 % p as u64) as u32;\n ex >>= 1;\n }\n return ans;\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let n: u32 = input.trim().parse().unwrap();\n let p = 1000000007u32;\n let pow = mpow(2u32, n - 1, p);\n// println!(\"{}\", pow);\n let mut fact = 1u32;\n for i in 2..(n+1) {\n fact = (fact as u64 * i as u64 % p as u64) as u32;\n }\n// println!(\"{}\", fact);\n let ans;\n if fact < pow {\n ans = fact + p - pow;\n } else {\n ans = fact - pow;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "10c980ee5f3eb922a3904a6fc1e38891", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let keyb = \"qwertyuiopasdfghjkl;zxcvbnm,./\";\n let mut r = String::new();\n let mut inp = String::new();\n std::io::stdin()\n .read_line(&mut r)\n .expect(\"failed reading from stdin\");\n std::io::stdin()\n .read_line(&mut inp)\n .expect(\"failed reading from stdin\");\n let keys = inp.trim().chars();\n for i in keys {\n if r.trim() == \"R\" {\n let idx = keyb.find(i).unwrap() - 1;\n print!(\"{}\", keyb.chars().nth(idx).unwrap())\n } else {\n let idx = keyb.find(i).unwrap() + 1;\n print!(\"{}\", keyb.chars().nth(idx).unwrap())\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4e7f926212dd09eeaec7ea3a18b20e35", "src_uid": "df49c0c257903516767fdb8ac9c2bfd6", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let a = [\n \"qwertyuiop\",\n \"asdfghjkl;\",\n \"zxcvbnm,./\",\n ];\n let b = readln!();\n let c = readln!();\n let d :i32= if b == \"R\" { -1 } else { 1 };\n let mut res = String::new();\n for x in c.chars() {\n for s in &a {\n if let Some(i) = s.find(x) {\n res.push(s.as_bytes()[(i as i32+d) as usize] as char);\n } else {\n continue;\n }\n }\n }\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2f7289115131b4741c180361cd7475c4", "src_uid": "df49c0c257903516767fdb8ac9c2bfd6", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, std::io::stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut buffer = String::new();\n let mut input = WordReader::from_stdin(&mut buffer);\n\n use std::collections::HashMap;\n const K: &[u8] = b\"qwertyuiopasdfghjkl;zxcvbnm,./\";\n let ml = K.iter().zip(K.iter().skip(1)).collect::>();\n let mr = K.iter().skip(1).zip(K.iter()).collect::>();\n let c = input.bs()[0];\n let s = input.bs();\n let m = if c == b'L' { ml } else { mr };\n for x in s {\n print!(\"{}\", *(m[x]) as char);\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "12ba1288f7714ff07659dc8a87e1cb99", "src_uid": "df49c0c257903516767fdb8ac9c2bfd6", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Keyboard = [[char; 10]; 3];\n\nfn raw_input() -> String {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n}\n\nfn find(row: &[char; 10], letter: char) -> Result {\n for i in 0..row.len() {\n if row[i] == letter {\n return Ok(i);\n }\n }\n Err(())\n}\n\nfn shift_message(message: &String, kb: &Keyboard, dir: isize) -> String {\n let mut new_message = String::with_capacity(message.len());\n for letter in message.chars() {\n for row in kb.iter() {\n if let Ok(index) = find(row, letter) {\n new_message.push(row[(index as isize + dir) as usize]);\n break;\n }\n }\n }\n new_message\n}\n\nfn main() {\n let dir = raw_input();\n let mut message = raw_input();\n let keyboard = [\n ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],\n ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';'],\n ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/'],\n ];\n\n match &dir[..] {\n \"L\" => message = shift_message(&message, &keyboard, 1),\n \"R\" => message = shift_message(&message, &keyboard, -1),\n _ => unreachable!(),\n }\n\n println!(\"{}\", message);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "246c7221e1535222bc44eafaa6f860fb", "src_uid": "df49c0c257903516767fdb8ac9c2bfd6", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let s = \"qwertyuiopasdfghjkl;zxcvbnm,./\";\n let sft = if R!(String).0 == \"R\" { -1i32 } else { 1i32 };\n let ans: String = R!(String).0.chars().map(|c| (s.find(c).unwrap() as i32 + sft) as usize).map(|i| s.get(i..i+1).unwrap()).collect();\n W!(ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c74fce917f9f00f1e763ebb97d93f980", "src_uid": "df49c0c257903516767fdb8ac9c2bfd6", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let keyboard: Vec = \"qwertyuiopasdfghjkl;zxcvbnm,./\".chars()\n .collect();\n let dir: char = scan.next();\n let input: String = scan.next::();\n let offset: isize = if dir == 'R' { -1 } else { 1 };\n for c in input.chars() {\n let mut index = keyboard.iter().position(|&x| x==c).unwrap();\n print!(\"{}\", keyboard[(index as isize + offset) as usize]);\n }\n\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1f9e572a6293985ad43fe1ff9b97aa2a", "src_uid": "df49c0c257903516767fdb8ac9c2bfd6", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\n#[derive(Clone)]\nstruct Graph {\n nodes: usize,\n edges: Vec>,\n}\n\nimpl Graph {\n fn new(n: usize) -> Self {\n Self {\n nodes: n,\n edges: vec![Vec::new(); n + 1],\n }\n }\n\n fn add_edge(&mut self, x: usize, y: usize, cost: u64) {\n self.edges[x].push((y, cost));\n self.edges[y].push((x, cost));\n }\n\n fn dijkstra(&mut self, start: usize, end: usize) -> u64 {\n let mut dist = vec![None; self.nodes + 1];\n let mut prev = vec![None; self.nodes + 1];\n dist[start] = Some(0);\n let mut queue = (1..=self.nodes).collect::>();\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n while let Some(next_node) = queue.pop() {\n if next_node == end {\n return dist[next_node].unwrap();\n }\n for (neighbour, cost) in self.edges[next_node].iter() {\n let alt = dist[next_node].unwrap() + cost;\n if dist[*neighbour].is_none() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n } else {\n if alt < dist[*neighbour].unwrap() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n }\n }\n }\n //println!(\"{:?} {:?}\", dist, prev);\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n }\n 0\n }\n\n fn set_cost(&mut self, x: usize, y: usize, cost: u64) {\n for i in 0..self.edges[x].len() {\n if self.edges[x][i].0 == y {\n self.edges[x][i].1 = cost\n }\n }\n for i in 0..self.edges[y].len() {\n if self.edges[y][i].0 == x {\n self.edges[y][i].1 = cost\n }\n }\n }\n}\n\nconst MODULO: u64 = 1_000_000_007;\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\nstruct BigPrimeRing {\n inner: u64,\n}\n\nimpl From for BigPrimeRing\nwhere\n T: Into,\n{\n fn from(n: T) -> Self {\n Self {\n inner: n.into() % MODULO,\n }\n }\n}\n\nimpl std::ops::Add for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn add(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::AddAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn add_assign(&mut self, rhs: T) {\n self.inner += rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Sub for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn sub(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + MODULO - rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::SubAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn sub_assign(&mut self, rhs: T) {\n self.inner += MODULO;\n self.inner -= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Mul for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn mul(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner * rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::MulAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn mul_assign(&mut self, rhs: T) {\n self.inner *= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl BigPrimeRing {\n fn inverse(self) -> Self {\n if self.inner == 0 {\n return self;\n }\n let (_g, mut x, _y) = egcd(self.inner as i64, MODULO as i64);\n if x < 0 {\n x += MODULO as i64;\n }\n Self { inner: x as u64 }\n }\n}\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn main() -> Result<(), Box> {\n let n = read::();\n let sum = n * (n + 1) / 2;\n println!(\"{}\", sum % 2);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "3244a4fa750b096f94103aa3c600c47c", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nfn divisor(n:i64) -> Vec {\n let mut res = Vec::new();\n let mut i = 1;\n while i*i <= n {\n if n%i == 0 {\n res.push(i);\n if i != n/i { res.push(n/i); }\n }\n i += 1;\n }\n res.sort();\n res\n}\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:i64 = read();\n let sum = n*(n+1)/2;\n println!(\"{}\", sum%2);\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "f6d23b63a5a9015e53cc7fbab281e456", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let n: u64 = {\n let mut read_buf = String::new();\n io::stdin().read_line(&mut read_buf).unwrap();\n read_buf.trim().parse().unwrap()\n };\n if n % 4 == 0 {\n println!(\"0\");\n } else if n % 4 == 1 {\n println!(\"1\");\n } else if n % 4 == 2 {\n println!(\"1\");\n } else if n % 4 == 3 {\n println!(\"0\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "f98b15f64a05d1c5b7cc7f4baca8b24e", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = IO::new();\n let n: u32 = input.read();\n let ans = match n % 4 {\n 1 | 2 => 1,\n _ => 0,\n };\n println!(\"{}\", ans);\n}\n\nstruct IO {\n tokens: Vec,\n}\n\nimpl IO {\n fn new() -> IO {\n IO { tokens: Vec::new() }\n }\n\n fn read(&mut self) -> T {\n self.read_token().parse::().ok().unwrap()\n }\n\n fn read_token(&mut self) -> String {\n if self.tokens.is_empty() {\n self.tokens = self\n .read_line()\n .split_whitespace()\n .map(|x| x.to_string())\n .collect();\n self.tokens.reverse();\n }\n self.tokens.pop().unwrap()\n }\n\n fn read_line(&mut self) -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).expect(\"die\");\n s.trim_right().to_string()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "a12c38f26852d9ab4edabc6317cddf24", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n: i64 = input.p();\n let x = n * (n + 1) / 2;\n println!(\"{}\", x % 2);\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "35856c39a2103de79cd3fe0223bcf3ec", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input() -> u64 {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n}\n\nfn main() {\n print!(\"{}\", 1 - ((input() - 1) / 2) % 2);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "bfae2c80dbf7b4d2673bf3660dfafb77", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn gcd(u: u32, v: u32) -> u32 {\n if u == 0 {\n return u;\n }\n if v == 0 {\n return v;\n }\n let mut shift = 0;\n let mut aux : [u32; 2] = [(u | v), 1];\n while aux[0] & aux[1] == 0 {\n shift += 1;\n aux[1] <<= 1;\n }\n let mut u = u >> shift;\n let mut v = v >> shift;\n\n while u & 1 == 0 {\n u >>= 1;\n }\n\n loop {\n while v & 1 == 0 {\n v >>= 1;\n }\n \n if u > v {\n aux[0] = v;\n v = u;\n u = aux[0];\n }\n v = v - u;\n\n if v == 0 {\n break;\n }\n }\n u << shift\n}\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let n: u32 = buffer.trim().parse().expect(\"invalid input\");\n\n let mut i = n / 2 + 1;\n while gcd(i, n - i) != 1 {\n i += 1;\n }\n println!(\"{} {}\", n - i, i);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms"], "code_uid": "037033d4586d80cbc5fd0c8a3b3d3c63", "src_uid": "0af3515ed98d9d01ce00546333e98e77", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn gcd(mut a: u32, mut b: u32) -> u32 {\n while a != 0 {\n b %= a;\n let t = a;\n a = b;\n b = t;\n }\n return b;\n}\n\nfn main() {\n let mut line: String = String::new();\n io::stdin().read_line(&mut line).unwrap();\n let n: u32 = line.trim().parse().unwrap();\n // let a = n / 2;\n for i in 0 .. n / 2 {\n let a: u32 = n / 2 - i;\n if gcd(a, n - a) == 1 {\n println!(\"{} {}\", a, n - a);\n break;\n }\n }\n // println!(\"{} {}\", a - (1 - n % 2), a + 1);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms"], "code_uid": "3fdcea6715236a28fb7d48794937b3c7", "src_uid": "0af3515ed98d9d01ce00546333e98e77", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{ self, BufRead };\nuse std::collections::*;\n\nmacro_rules! scan_line {\n () => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n buffer\n });\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\nfn main() {\n let (mut n, ) = scan_line!(i64);\n\n n -= 3;\n let mut numerator = 1;\n let mut denominator = 2;\n\n while n >= 1 {\n if numerator + 1 < denominator {\n numerator += 1;\n } else {\n denominator += 1;\n }\n n -= 1;\n }\n\n let primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101];\n\n loop {\n if numerator == 1 { break; }\n let mut good = true;\n for p in primes.iter() {\n if denominator % *p == 0 && numerator % *p == 0 {\n denominator += 1;\n numerator -= 1;\n good = false;\n break;\n }\n }\n if good { break; }\n }\n\n println!(\"{} {}\", numerator, denominator);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms"], "code_uid": "91a586da0a3ffb338a884a16b608f235", "src_uid": "0af3515ed98d9d01ce00546333e98e77", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec(s: String) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n s.split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn gcd(a: u32, b: u32) -> u32 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn main() {\n let n: u32 = get_line().trim().parse().unwrap();\n\n let (a, b) = if n % 2 == 0 {\n let p = n / 2;\n let i = (1..1000).find(|&k| gcd(p + k, p - k) == 1).unwrap();\n (p - i, p + i)\n } else {\n (n / 2, n / 2 + 1)\n };\n\n println!(\"{} {}\", a, b);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms"], "code_uid": "18197650737c7498d91f969f963fc3d7", "src_uid": "0af3515ed98d9d01ce00546333e98e77", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn board(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn framed_board(&mut self, r: usize, c: usize, f: u8) -> Vec> {\n\t\tlet mut res = v!([r+2]);\n\t\tres.push( v!([c+2] = f) );\n\t\trep!{[r]\n\t\t\tlet mut t = self.vb();\n\t\t\tassert!(t.len() == c);\n\t\t\tt.reserve(2);\n\t\t\tt.insert(0,f);\n\t\t\tt.push(f);\n\t\t\tres.push(t);\n\t\t}\n\t\tres.push( v!([c+2] = f) );\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n\tfn graph(&mut self, n: usize, m: usize) -> Vec> {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e\n\t}\n\tfn graph_w(&mut self, n: usize, m: usize) -> Vec> where T::Err: Debug {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet s = rin.vb();\n\tlet n = s.len();\n\tlet mut sol = 1000;\n\tfor (y,x) in vec![(b'2',b'5'), (b'5',b'0'), (b'7',b'5'), (b'0',b'0')] {\n\t\tl!(mut px,py = n);\n\t\tfor i in (0..n).rev() {\n\t\t\tif px == n && s[i] == x {\n\t\t\t\tpx = i;\n\t\t\t} else if py == n && s[i] == y {\n\t\t\t\tpy = i;\n\t\t\t}\n\t\t}\n\t\tif px < n && py < n {\n\t\t\tlet mut res = 2*n - 3 - px - py;\n\t\t\tif px < py {\n\t\t\t\tres += 1;\n\t\t\t}\n\t\t\tlet mut add = 0;\n\t\t\tlet mut done = false;\n\t\t\tfor i in 0..n {\n\t\t\t\tif i == px || i == py {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif s[i] != b'0' {\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tadd += 1;\n\t\t\t}\n\t\t\tres += add;\n\t\t\tmin!(sol, res);\n\t\t}\n\t}\n\tif sol < 1000 {\n\t\twriteln!(rout, \"{}\", sol).ok();\n\t} else {\n\t\twriteln!(rout, \"-1\").ok();\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "5bab665ea0c2a4335946487327f2f64b", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve_zeroes(s: &Vec, count: &Vec) -> usize {\n if count[0] < 2 {\n return std::usize::MAX;\n }\n let mut first = true;\n let mut result = 0;\n for i in 0..s.len() {\n if s[i] != 0 {\n continue;\n }\n if first {\n first = false;\n result += i;\n }else if !first {\n result += i - 1;\n break;\n }\n }\n return result;\n}\n\nfn solve_half(s: &Vec, count: &Vec) -> usize {\n if count[5] == 0 || count[0] == 0 {\n return std::usize::MAX;\n }\n if s[0] == 0 && s[1] == 5 {\n return 0;\n }\n if s[0] == 5 && s[1] == 0 {\n return 1;\n }\n if count[5] == 1 && count[0] + 1 == s.len() {\n return std::usize::MAX;\n }\n let mut result = 0;\n let mut first = [std::usize::MAX, std::usize::MAX];\n let mut other = std::usize::MAX;\n for i in 0..s.len() {\n if s[i] != 0 && s[i] != 5 || s[i] == 5 && first[1] != std::usize::MAX {\n other = i;\n }\n if first[0] == std::usize::MAX && s[i] == 0 {\n result += i;\n first[0] = i;\n }\n if first[1] == std::usize::MAX && s[i] == 5 {\n result += i - 1;\n first[1] = i;\n }\n }\n if first[0] > first[1] {\n result += 1;\n }\n if first[1] + 1 == s.len() {\n if s[s.len() - 2] == 0 || first[0] + 2 == s.len() && s[s.len() - 3] == 0 {\n result += s.len() - other - 2;\n if first[0] > other {\n result -= 1;\n }\n }\n }\n return result;\n}\n\nfn solve_one(s: &Vec, count: &Vec, b: usize, a: usize) -> usize {\n if count[a] == 0 || count[b] == 0 {\n return std::usize::MAX;\n }\n if s[0] == a as u8 && s[1] == b as u8 {\n return 0;\n }\n if s[0] == b as u8 && s[1] == a as u8 {\n return 1;\n }\n if count[a] == 1 && count[b] == 1 && count[0] + 2 == s.len() {\n return std::usize::MAX;\n }\n let mut result = 0;\n let mut first = [std::usize::MAX, std::usize::MAX];\n let mut other = std::usize::MAX;\n for i in 0..s.len() {\n if s[i] != 0 && s[i] != a as u8 && s[i] != b as u8 ||\n s[i] == a as u8 && first[0] != std::usize::MAX ||\n s[i] == b as u8 && first[1] != std::usize::MAX {\n other = i;\n }\n if first[0] == std::usize::MAX && s[i] == a as u8 {\n result += i;\n first[0] = i;\n }\n if first[1] == std::usize::MAX && s[i] == b as u8 {\n result += i - 1;\n first[1] = i;\n }\n }\n if first[0] > first[1] {\n result += 1;\n }\n if first[1] + 1 == s.len() {\n if s[s.len() - 2] == 0 || first[0] + 2 == s.len() && s[s.len() - 3] == 0 {\n result += s.len() - other - 2;\n if first[0] > other {\n result -= 1;\n }\n }\n }else if first[0] + 1 == s.len() {\n if s[s.len() - 2] == 0 || first[1] + 2 == s.len() && s[s.len() - 3] == 0 {\n result += s.len() - other - 2;\n if first[1] > other {\n result -= 1;\n }\n }\n }\n return result;\n}\n\nfn solve() {\n let mut s: Vec<_> = parse_line!(String).bytes().map(|x| x - b'0').collect();\n if s.len() == 1 {\n return println!(\"-1\");\n }\n s.reverse();\n let mut counts = vec![0; 10];\n for &c in s.iter() {\n counts[c as usize] += 1;\n }\n let result = std::cmp::min(solve_zeroes(&s, &counts), std::cmp::min(\n solve_one(&s, &counts, 2, 5), std::cmp::min(solve_one(&s, &counts, 7, 5),\n solve_half(&s, &counts))));\n if result == std::usize::MAX {\n println!(\"-1\");\n }else{\n println!(\"{}\", result);\n }\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "6c0f8c81304b8dcf266bc6ebf42c100d", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nconst INF: i32 = 1 << 29;\n\nfn calc(n: &[char], pat: &[char]) -> i32 {\n let len = n.len();\n let mut mi = INF;\n if len == 2 {\n for j in 0 .. len {\n if pat[0] != n[j] { continue; }\n for k in 0 .. len {\n if j == k || pat[1] != n[k] { continue; }\n let mut cost = 0;\n let mut x = j as i32;\n let mut y = k as i32;\n cost += (y - len as i32 + 1).abs();\n if x > y { x -= 1; }\n cost += (x - len as i32 + 2).abs();\n eprintln!(\"{:?} ==> {}\", (j, k), cost);\n mi = min(mi, cost);\n }\n }\n return mi;\n }\n for i in 0 .. len {\n if n[i] == '0' { continue; }\n for j in 0 .. len {\n if i == j || pat[0] != n[j] { continue; }\n for k in 0 .. len {\n if i == k || j == k || pat[1] != n[k] { continue; }\n let mut cost = 0;\n cost += i as i32;\n let mut x = if i < j { j } else { j + 1 } as i32;\n let mut y = if i < k { k } else { k + 1 } as i32;\n cost += (y - len as i32 + 1).abs();\n if x > y { x -= 1; }\n cost += (x - len as i32 + 2).abs();\n eprintln!(\"{:?} ==> {}\", (i, j, k), cost);\n mi = min(mi, cost);\n }\n }\n }\n return mi;\n}\n\n\nfn solve() {\n let n: Vec = get_word().chars().collect();\n let mut mi = INF;\n for pat in [['0', '0'], ['2', '5'], ['5', '0'], ['7', '5']].iter() {\n mi = min(mi, calc(&n, pat));\n }\n println!(\"{}\", if mi == INF { -1 } else { mi }); \n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "0585d1d34e23c2b09d85d7a0d802bcdc", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn digit_indices(ds : &Vec, di : &mut Vec>) {\n di.clear();\n for _ in 0 .. 10 {\n let ev = vec![];\n di.push(ev);\n }\n for i in 0 .. ds.len() {\n di[ds[i] as usize].push(i);\n }\n}\n\nfn digits(n : u64, ds : &mut Vec) {\n ds.clear();\n if n == 0 {\n ds.push(0);\n } else {\n let mut x = n;\n loop {\n if x == 0 {\n break;\n } else {\n let x_mod_10 = x % 10;\n let x_div_10 = x / 10;\n ds.push(x_mod_10);\n x = x_div_10;\n }\n }\n }\n}\n\nfn move_digits(from : usize, to : usize, dgts : &mut Vec) -> u64 {\n let mut num_swaps = 0;\n let dgt_from = dgts[from];\n let mut idx = from - 1;\n loop {\n if idx == to {\n dgts[idx + 1] = dgts[idx];\n dgts[idx] = dgt_from;\n num_swaps = num_swaps + 1;\n break;\n } else {\n dgts[idx + 1] = dgts[idx];\n idx = idx - 1;\n num_swaps = num_swaps + 1;\n }\n }\n num_swaps\n}\n\nfn swap_zero_out(from : usize, to : usize, dgts : &mut Vec) -> Option {\n if from < 2 {\n None\n } else {\n let mut found = false;\n let mut idx = from - 2;\n if idx < to {\n None\n } else {\n loop {\n if idx == to {\n if dgts[idx] == 0 {\n // Do nothing ...\n } else {\n found = true;\n }\n break;\n } else {\n if dgts[idx] == 0 {\n idx = idx - 1;\n } else {\n found = true;\n break;\n }\n }\n }\n if found {\n let num_swaps = move_digits(from - 1, idx, dgts);\n Some(num_swaps)\n } else {\n None\n }\n }\n }\n}\n\nfn swap_to_index(from : usize, to : usize, dgts : &mut Vec) -> Option {\n if from < to {\n panic!(\"Check failed: from({}) >= to({}).\", from, to);\n } else if from == to {\n Some(0)\n } else {\n let num_dgts = dgts.len();\n if from == (num_dgts - 1) {\n // From is the highest digit, we have to check whether\n // the digit immediately to the right of it is a zero.\n if dgts[from - 1] == 0 {\n // We have to swap zero out of its location.\n match swap_zero_out(from, to, dgts) {\n None => None,\n Some(x) => { \n let y = move_digits(from, to, dgts);\n let num_swaps = x + y;\n Some(num_swaps)\n },\n }\n } else {\n // We don't have to worry about swapping a zero into\n // the highest digit.\n let num_swaps = move_digits(from, to, dgts);\n Some(num_swaps)\n }\n } else {\n // From is not the highest digit, so we need not\n // worry about swapping a zero into its place.\n let num_swaps = move_digits(from, to, dgts);\n Some(num_swaps)\n }\n }\n}\n\nfn num_swaps_for_digits(n : u64,\n d_1 : usize,\n m_1 : usize,\n d_2 : usize,\n m_2 : usize) -> Option {\n let mut dgts = vec![];\n digits(n, &mut dgts);\n let mut dgt_indxs = vec![];\n digit_indices(&dgts, &mut dgt_indxs);\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[d_1][m_1], 0, &mut dgts) {\n None => {\n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[d_2][m_2], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n Some(num_swaps)\n } else {\n None\n }\n } else {\n None\n }\n}\n\nfn num_swaps_to_divisible_by_25(n : u64) -> Option {\n let mut dgts = vec![];\n digits(n, &mut dgts);\n let mut dgt_indxs = vec![];\n digit_indices(&dgts, &mut dgt_indxs);\n let num_digits = dgts.len();\n // Check for at least two digits.\n if num_digits < 2 {\n None\n } else {\n let mut min_num_swaps = u64::max_value();\n // Check for two zeros.\n if dgt_indxs[0].len() >= 2 {\n // We have to swap the digits into place...\n match num_swaps_for_digits(n, 0, 0, 0, 1) {\n None => (),\n Some(x) => {\n if x < min_num_swaps {\n min_num_swaps = x;\n }\n }\n }\n } \n digits(n, &mut dgts);\n digit_indices(&dgts, &mut dgt_indxs);\n if (dgt_indxs[0].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[0][0], 0, &mut dgts) {\n None => { \n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[5][0], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n if num_swaps < min_num_swaps {\n min_num_swaps = num_swaps;\n }\n }\n }\n } \n digits(n, &mut dgts);\n digit_indices(&dgts, &mut dgt_indxs);\n if (dgt_indxs[2].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[5][0], 0, &mut dgts) {\n None => {\n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[2][0], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n if num_swaps < min_num_swaps {\n min_num_swaps = num_swaps;\n }\n }\n }\n } \n digits(n, &mut dgts);\n digit_indices(&dgts, &mut dgt_indxs);\n if (dgt_indxs[7].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[5][0], 0, &mut dgts) {\n None => {\n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[7][0], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n if num_swaps < min_num_swaps {\n min_num_swaps = num_swaps;\n }\n }\n }\n } \n if min_num_swaps < u64::max_value() {\n Some(min_num_swaps)\n } else {\n None\n }\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let n = read_t(&stdin);\n match num_swaps_to_divisible_by_25(n) {\n None => println!(\"-1\"),\n Some(s) => println!(\"{}\", s),\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "2e548fa315fcf86285d8f50add01f050", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn digit_indices(ds : &Vec, di : &mut Vec>) {\n di.clear();\n for _ in 0 .. 10 {\n let ev = vec![];\n di.push(ev);\n }\n for i in 0 .. ds.len() {\n di[ds[i] as usize].push(i);\n }\n}\n\nfn digits(n : u64, ds : &mut Vec) {\n ds.clear();\n if n == 0 {\n ds.push(0);\n } else {\n let mut x = n;\n loop {\n if x == 0 {\n break;\n } else {\n let x_mod_10 = x % 10;\n let x_div_10 = x / 10;\n ds.push(x_mod_10);\n x = x_div_10;\n }\n }\n }\n}\n\nfn move_digits(from : usize, to : usize, dgts : &mut Vec) -> u64 {\n let mut num_swaps = 0;\n let dgt_from = dgts[from];\n let mut idx = from - 1;\n loop {\n if idx == to {\n dgts[idx + 1] = dgts[idx];\n dgts[idx] = dgt_from;\n num_swaps = num_swaps + 1;\n break;\n } else {\n dgts[idx + 1] = dgts[idx];\n idx = idx - 1;\n num_swaps = num_swaps + 1;\n }\n }\n num_swaps\n}\n\nfn swap_zero_out(from : usize, to : usize, dgts : &mut Vec) -> Option {\n if from < 2 {\n None\n } else {\n let mut found = false;\n let mut idx = from - 2;\n if idx < to {\n None\n } else {\n loop {\n if idx == to {\n if dgts[idx] == 0 {\n // Do nothing ...\n } else {\n found = true;\n }\n break;\n } else {\n if dgts[idx] == 0 {\n idx = idx - 1;\n } else {\n found = true;\n break;\n }\n }\n }\n if found {\n let num_swaps = move_digits(from - 1, idx, dgts);\n Some(num_swaps)\n } else {\n None\n }\n }\n }\n}\n\nfn swap_to_index(from : usize, to : usize, dgts : &mut Vec) -> Option {\n if from < to {\n panic!(\"Check failed: from({}) >= to({}).\", from, to);\n } else if from == to {\n Some(0)\n } else {\n let num_dgts = dgts.len();\n if from == (num_dgts - 1) {\n // From is the highest digit, we have to check whether\n // the digit immediately to the right of it is a zero.\n if dgts[from - 1] == 0 {\n // We have to swap zero out of its location.\n match swap_zero_out(from, to, dgts) {\n None => None,\n Some(x) => { \n let y = move_digits(from, to, dgts);\n let num_swaps = x + y;\n Some(num_swaps)\n },\n }\n } else {\n // We don't have to worry about swapping a zero into\n // the highest digit.\n let num_swaps = move_digits(from, to, dgts);\n Some(num_swaps)\n }\n } else {\n // From is not the highest digit, so we need not\n // worry about swapping a zero into its place.\n let num_swaps = move_digits(from, to, dgts);\n Some(num_swaps)\n }\n }\n}\n\nfn num_swaps_to_divisible_by_25(n : u64) -> Option {\n let mut dgts = vec![];\n digits(n, &mut dgts);\n let mut dgt_indxs = vec![];\n digit_indices(&dgts, &mut dgt_indxs);\n let num_digits = dgts.len();\n // Check for at least two digits.\n if num_digits < 2 {\n None\n } else {\n let mut min_num_swaps = u64::max_value();\n // Check for two zeros.\n if dgt_indxs[0].len() >= 2 {\n // We have to swap the digits into place...\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[0][0], 0, &mut dgts) {\n None => {\n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[0][1], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n if num_swaps < min_num_swaps {\n min_num_swaps = num_swaps;\n }\n }\n }\n } \n digits(n, &mut dgts);\n digit_indices(&dgts, &mut dgt_indxs);\n if (dgt_indxs[0].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[0][0], 0, &mut dgts) {\n None => { \n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[5][0], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n if num_swaps < min_num_swaps {\n min_num_swaps = num_swaps;\n }\n }\n }\n } \n digits(n, &mut dgts);\n digit_indices(&dgts, &mut dgt_indxs);\n if (dgt_indxs[2].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[5][0], 0, &mut dgts) {\n None => {\n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[2][0], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n if num_swaps < min_num_swaps {\n min_num_swaps = num_swaps;\n }\n }\n }\n } \n digits(n, &mut dgts);\n digit_indices(&dgts, &mut dgt_indxs);\n if (dgt_indxs[7].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n let mut could_swap = true;\n let mut num_swaps = u64::max_value();\n match swap_to_index(dgt_indxs[5][0], 0, &mut dgts) {\n None => {\n could_swap = false;\n },\n Some(x) => {\n num_swaps = x;\n },\n };\n if could_swap {\n let mut could_swap_2 = true;\n digit_indices(&dgts, &mut dgt_indxs);\n match swap_to_index(dgt_indxs[7][0], 1, &mut dgts) {\n None => {\n could_swap_2 = false;\n },\n Some(x) => {\n num_swaps = num_swaps + x;\n },\n };\n if could_swap_2 {\n if num_swaps < min_num_swaps {\n min_num_swaps = num_swaps;\n }\n }\n }\n } \n if min_num_swaps < u64::max_value() {\n Some(min_num_swaps)\n } else {\n None\n }\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let n = read_t(&stdin);\n match num_swaps_to_divisible_by_25(n) {\n None => println!(\"-1\"),\n Some(s) => println!(\"{}\", s),\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "d484cba99e4de0bc2368eb75ca461656", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub fn main() {\n let mut input = io::Input::new();\n\n let num: String = input.next();\n\n if num.len() == 1 {\n println!(\"-1\");\n return;\n }\n\n let p = vec![\n try(&num, '5', '2'),\n try(&num, '5', '7'),\n try(&num, '0', '0'),\n try(&num, '0', '5'),\n ];\n\n println!(\"{}\", match p.iter().min() {\n Some(&::std::usize::MAX) => -1,\n Some(&result) => result as i32,\n _ => unreachable!(),\n });\n}\n\nfn try(num: &String, s0: char, s1: char) -> usize {\n\n let mut num = num.clone();\n let mut swaps = 0usize;\n\n // find first\n\n let pos = num.rfind(s0);\n if let Some(pos) = pos {\n\n swaps += num.len() - pos - 1;\n\n num.remove(pos);\n\n // find second\n\n let pos = num.rfind(s1);\n\n if let Some(pos) = pos {\n\n swaps += num.len() - pos - 1;\n\n num.remove(pos);\n num.push(s1);\n num.push(s0);\n\n // correct leading zeroes, if necessary and possible\n\n if num.starts_with('0') {\n let pos = num.find(|c| c != '0');\n if let Some(pos) = pos {\n if pos < num.len() - 2 {\n swaps += pos;\n return swaps;\n }\n }\n } else {\n return swaps;\n }\n }\n }\n\n ::std::usize::MAX\n}\n\n#[allow(unused)]\npub mod io {\n\n const BUFFER_SIZE: usize = 8192;\n\n use std::collections::VecDeque;\n use std::str::FromStr;\n use std::io;\n use std::io::Read;\n\n type AsciiStr = Vec;\n\n pub struct Input {\n token_buffer: VecDeque,\n remaining: String,\n }\n\n impl Input {\n\n pub fn new() -> Input {\n Input {\n token_buffer: VecDeque::with_capacity(100),\n remaining: String::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where T::Err: ::std::fmt::Debug\n {\n self.fill_buffer();\n self.token_buffer.pop_front().unwrap().parse().unwrap()\n }\n\n pub fn next_ascii_string(&mut self) -> AsciiStr {\n self.fill_buffer();\n Vec::from(self.token_buffer.pop_front().unwrap().as_bytes())\n }\n\n fn fill_buffer(&mut self) {\n while self.token_buffer.is_empty() {\n let mut minibuffer = [0u8; BUFFER_SIZE];\n let size = io::stdin().read(&mut minibuffer[..]).unwrap();\n\n self.remaining += &String::from_utf8_lossy(&minibuffer[..size]);\n\n if self.remaining.trim().len() > 0 {\n for token in self.remaining.trim().split_whitespace() {\n self.token_buffer.push_back(String::from(token))\n }\n\n if size > 0 && ! self.remaining.ends_with(|c: char|char::is_ascii_whitespace(&c)) {\n self.remaining = self.token_buffer.pop_back().unwrap();\n } else {\n self.remaining.clear();\n }\n\n } else if size == 0 {\n panic!(\"EOF\");\n }\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "2d421e93f23b7f62742efde2314ee0e8", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let debug = false;\n let stdin: io::Stdin = io::stdin();\n let mut s: String = String::new();\n\n stdin.read_line(&mut s).unwrap();\n\n s = s.trim().to_string();\n\n let ends = [\n ('0', '0'),\n ('2', '5'),\n ('5', '0'),\n ('7', '5'),\n ];\n\n let mut mc = 100;\n\n for (l, r) in ends.iter() {\n if debug { println!(\"--------------\") }\n if debug { println!(\"({}{})\", l, r) }\n let mut l_pos = 100;\n let mut r_pos = 100;\n for (i, c) in s.chars().rev().enumerate() {\n if l_pos == 100 && c == *l {\n l_pos = i;\n if *l == *r && r_pos == 100 { l_pos = 100 }\n }\n if r_pos == 100 && c == *r {\n r_pos = i;\n }\n }\n\n if debug { println!(\"lpos {} rpos {}\", l_pos, r_pos) }\n if l_pos == 100 || r_pos == 100 {\n continue;\n }\n\n let mut cc = l_pos + r_pos - if l_pos > r_pos { 1 } else { 0 };\n\n if s.len() > 2 && (l_pos == s.len() - 1 || r_pos == s.len() - 1) {\n let mut m_pos = 100;\n for (i, c) in s.chars().enumerate() {\n if i == s.len() - 1 - l_pos { continue }\n if i == s.len() - 1 - r_pos { continue }\n if c != '0' {\n m_pos = i;\n break;\n }\n }\n\n if debug { println!(\"mpos {}\", m_pos) }\n if m_pos == 100 {\n cc = 101\n } else {\n cc += m_pos;\n if s.len() - 1 - l_pos < m_pos {\n cc -= 1;\n }\n if s.len() - 1 - r_pos < m_pos {\n cc -= 1;\n }\n }\n }\n if debug { println!(\"cc {}\", cc) }\n\n if cc < mc {\n mc = cc;\n }\n }\n\n if mc == 100 {\n println!(\"-1\");\n } else {\n println!(\"{}\", mc);\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "71585c633bdfd89f7e43dd9bf13ae595", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n\n let emploees: i32 = input.trim().parse().unwrap();\n let mut counter = 0;\n\n for leaders in 1..emploees {\n if (emploees - leaders) % leaders == 0 {\n counter = counter + 1;\n }\n }\n\n println!(\"{}\", counter);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "a24793d25b683fd8df81c4faa49a5f24", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let mut result = 0usize;\n for i in 1..=(n / 2) {\n if (n - i) % i == 0 {\n result += 1;\n }\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "0ff5f519d04e781d97d493784f56c884", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn get_line() -> io::Result {\n\tlet mut buffer = String::new();\n\tio::stdin().read_line(&mut buffer)?;\n\tOk(buffer)\n}\n\nfn main() {\n\tlet employees;\n\t{\n\t\tlet input = get_line().unwrap();\n\t\temployees = input.trim().parse::().unwrap();\n\t}\n\n\tlet mut ways = 0;\n\tfor i in 1..employees {\n\t\tif (employees - i) % i == 0 {\n\t\t\tways += 1;\n\t\t}\n\t}\n\tprint!(\"{}\", ways);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "66bc765697cb3b50e86f29775f91914e", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n let mut sol = 0;\n for i in 1.. {\n if i * i > n { break; }\n if i * i == n { sol += 1; }\n else if n % i == 0 { sol += 2; }\n }\n println!(\"{}\", sol - 1);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "6f94cd948b87eee04bbe1249fade9c85", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut no = String::new();\n std::io::stdin().read_line(&mut no)\n .expect(\"Error input\");\n let no_employees: usize = no.trim().parse().unwrap();\n print!(\"{}\", (1..no_employees).map(|i| no_employees % i).filter(|e| *e == 0).count());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "bf3a82bd23533d0bbbe5094f80d34a74", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)?;\n\n let n = input.trim().parse::().unwrap();\n\n let mut l = 0;\n for i in 1..n {\n if i > (n - i) {\n break;\n }\n if (n - i) % i == 0 {\n l += 1;\n }\n }\n\n println!(\"{}\", l);\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "e5d0abddc7850cde115189edf2ac55ea", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main() {\n\tlet mut inp_str = String::new();\n\tio::stdin().read_line(&mut inp_str).expect(\"Failed to read line\");\n\tlet emp_num: u128 = inp_str.trim().parse().expect(\"Failed to parse\");\n\tlet mut way: u128 = 0;\n\tfor i in (1..emp_num).rev() {\n\t\tif (emp_num - i) % i == 0 {\n\t\t\tway+=1;\n\t\t}\n\t}\n\tprintln!(\"{}\", way);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "ab691afdb513afb794253818e849039b", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufReader, BufRead};\n\nfn main() -> Result<(), Box> {\n let n = BufReader::new(std::io::stdin())\n .lines()\n .next()\n .unwrap()?\n .parse::()?;\n\n let sqrt = (n as f32).sqrt().floor() as usize;\n let perfect = n == sqrt * sqrt;\n let mut divisors = 0;\n\n for divisor in 1..=sqrt {\n if n % divisor == 0 {\n divisors += if perfect && divisor == sqrt { 1 } else { 2 };;\n }\n }\n\n println!(\"{}\", divisors - 1);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "3a6760f0cae4349ca7f1508d24cf67e6", "src_uid": "89f6c1659e5addbf909eddedb785d894", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec(s: String) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n s.split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let (l, r, x, y, k) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let l2 = k * x;\n let r2 = k * y;\n\n let l = max(l, l2);\n let r = min(r, r2);\n\n let q = l / k;\n \n let ans = r < l || (k * q < l && r < k * (q + 1));\n let ans = !ans;\n\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "brute force"], "code_uid": "f3fd5ad1fd56f778878a2a378336791c", "src_uid": "1110d3671e9f77fd8d66dca6e74d2048", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{ self, Write };\nuse std::str::FromStr;\nuse std::cmp::{ min, max };\nuse std::collections::{ BinaryHeap, VecDeque };\n\n#[allow(unused_macros)]\nmacro_rules! trace {\n ($var:expr) => {\n let _ = writeln!(&mut std::io::stderr(), \">>> {} = {:?}\", stringify!($var), $var);\n };\n ($($args:expr),*) => {\n let _ = writeln!(&mut std::io::stderr(), \">>> {} = {:?}\", stringify!($($args),*), ($($args),*));\n };\n}\n\nconst M: usize = 1_000_000_007;\n\nfn main() {\n let mut sc = Scanner::new();\n let l: u64 = sc.cin();\n let r: u64 = sc.cin();\n let x: u64 = sc.cin();\n let y: u64 = sc.cin();\n let k: u64 = sc.cin();\n\n for b in x..(y + 1) {\n let a = k * b;\n if l <= a && a <= r {\n println!(\"YES\");\n return;\n }\n }\n println!(\"NO\");\n}\n\n#[allow(dead_code)]\nstruct Scanner { stdin: io::Stdin, buffer: VecDeque, }\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }\n fn reserve(&mut self) {\n while self.buffer.len() == 0 {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n }\n fn cin(&mut self) -> T {\n self.reserve();\n match self.buffer.pop_front().unwrap().parse::() {\n Ok(a) => a,\n Err(_) => panic!(\"parse err\")\n }\n }\n fn get_char(&mut self) -> char {\n self.reserve();\n let head = self.buffer[0].chars().nth(0).unwrap();\n let tail = String::from( &self.buffer[0][1..] );\n if tail.len()>0 { self.buffer[0]=tail } else { self.buffer.pop_front(); }\n head\n }\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "brute force"], "code_uid": "4ebeb5cd96c600345ef34c2c13bc0fe1", "src_uid": "1110d3671e9f77fd8d66dca6e74d2048", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nuse std::io::Write;\n\nfn run() {\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n input! {\n n: usize,\n x: [u32; n],\n }\n for x in x {\n let mut ans = \"NO\";\n for a in 0..=100 {\n for b in 0..=100 {\n if 3 * a + 7 * b == x {\n ans = \"YES\";\n }\n }\n }\n writeln!(out, \"{}\", ans).ok();\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "1240e23688e2ccb00e01d20dfcbb27f9", "src_uid": "cfd1182be98fb5f0c426f8b68e48d452", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut d = [false; 100];\n\n for i in (0..).take_while(|&i| 7 * i <= 100) {\n for j in (0..).take_while(|&j| 7 * i + 3 * j <= 100) {\n if i != 0 || j != 0 {\n d[7 * i + 3 * j - 1] = true;\n }\n }\n }\n\n let mut input = String::new();\n use std::io::prelude::*;\n std::io::stdin().read_to_string(&mut input).unwrap();\n let mut it = input.split_whitespace().map(|x| x.parse::().unwrap());\n\n let n = it.next().unwrap();\n\n let mut ans_str = String::with_capacity(100 * 5);\n\n for _ in 0..n {\n let x = it.next().unwrap();\n\n if d[x as usize - 1] {\n ans_str.push_str(\"YES\\n\");\n } else {\n ans_str.push_str(\"NO\\n\");\n }\n }\n\n write!(std::io::stdout(), \"{}\", ans_str).unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "7378442c677996f01c608aa2aa193ad6", "src_uid": "cfd1182be98fb5f0c426f8b68e48d452", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut s:String=String::new();\n io::stdin().read_line(&mut s).unwrap();\n let n:i64=s.trim().parse::().unwrap();\n let mut b:i64=0;\n let mut p:i64=0;\n let mut m:i64=0;\n for c in 0..n{\n s.clear();\n io::stdin().read_line(&mut s).unwrap();\n b=s.trim().parse::().unwrap();\n if b%7==0 || b%3==0{println!(\"YES\")}\n else{\n p=b/7;\n m=p*7;\n while p!=0 && m!=b{\n m+=3;\n if m>b{p-=1;m=p*7}\n }\n if p==0{println!(\"NO\")}\n else{println!(\"YES\")}\n }\n } \n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "e30fe9f0ff4b5131e090f3bb487ae721", "src_uid": "cfd1182be98fb5f0c426f8b68e48d452", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let n = buffer.trim().parse::().unwrap();\n for _ in 0..n {\n buffer.clear();\n io::stdin().read_line(&mut buffer).unwrap();\n let x = buffer.trim().parse::().unwrap();\n let mut ok = false;\n for a in 0..34 {\n for b in 0..15 {\n ok |= (a * 3 + b * 7) == x;\n }\n }\n if ok {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "8919ab5c11f7c9b55e2c16a28cc00e04", "src_uid": "cfd1182be98fb5f0c426f8b68e48d452", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\nuse std::fs::File;\nuse std::io::Read;\n\n// fn pow_speedt_with_mod(mut p: i64, mut q: i64, m: i64) -> i64 {\n// p %= m;\n// let mut r = p;\n// let mut ret: i64 = 1;\n// while q > 0 {\n// ret *= if q % 2 == 1 {r} else {1};\n// r *= r;\n// r %= m;\n// q /= 2;\n// ret %= m;\n// }\n// return ret;\n// }\n\nfn main() {\n let inputstatus = 1;\n\n let mut buf = String::new();\n let filename = \"inputrust.txt\";\n\n if inputstatus == 0 {\n let mut f = File::open(filename).expect(\"file not found\");\n f.read_to_string(&mut buf)\n .expect(\"something went wrong reading the file\");\n } else {\n std::io::stdin().read_to_string(&mut buf).unwrap();\n }\n\n let mut iter = buf.split_whitespace();\n let a: i32 = iter.next().unwrap().parse().unwrap();\n let b: i32 = iter.next().unwrap().parse().unwrap();\n let c: i32 = iter.next().unwrap().parse().unwrap();\n\n let v: [i32; 3] = [a / 3, b / 2, c / 2];\n let week: i32 = *v.iter().min().unwrap() as i32;\n\n let fish: i32 = a - 3 * week;\n let rabbit: i32 = b - 2 * week;\n let chicken: i32 = c - 2 * week;\n let mut ans = 0;\n let menu: [usize; 7] = [0, 1, 2, 0, 2, 1, 0];\n\n for df in 0..7 {\n let mut rest: [i32; 3] = [fish, rabbit, chicken];\n for di in 0..7 {\n let d = menu[(df + di) % 7];\n rest[d] -= 1;\n if rest[d] < 0 {\n ans = cmp::max(ans, di as i32);\n break;\n }\n }\n }\n\n println!(\"{}\", ans + week * 7);\n\n // println!(\"{}\", n);\n\n // if p + 1 >= m\n\n // println!(\"{}\", n);\n // println!(\"{}\", k);\n // println!(\"{:?}\", num);\n // println!(\"{:?}\", cum_num);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "901acc9fa2788fb6105abee4bf2fd835", "src_uid": "e17df52cc0615585e4f8f2d31d2daafb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn combination(n: u64, k: u64, m: u64) -> u64 {\n if n == 0 {\n return 1;\n }\n if k == 0 || k == n {\n return 1;\n }\n let new_k = if n - k < k { n - k } else { k };\n let mut res = 1;\n for i in ((n - new_k) + 1)..=n {\n res *= i;\n res %= m;\n }\n let mut den = 1;\n for i in 1..=(new_k) {\n den *= i;\n den %= m;\n }\n let (_one, inverse, _c) = egcd(den as i64, m as i64);\n let inverse = if inverse < 0 {\n m as i64 + inverse\n } else {\n inverse\n } as u64;\n //println!(\"inv: {} {}\", den, inverse);\n res *= inverse;\n res %= m;\n res\n}\n\nuse std::collections::HashSet;\nuse std::iter::FromIterator;\n\nfn n_to_vec(n: u64, l: usize) -> Vec {\n let mut res = vec![0; l];\n let mut n = n;\n for i in (0..l).rev() {\n if n % 2 == 1 {\n res[i] = 1;\n }\n n /= 2;\n }\n res\n}\n\nfn vec_to_n(v: Vec) -> u64 {\n let mut res = 0;\n for i in 0..v.len() {\n res *= 2;\n if v[i] == 1 {\n res += 1;\n }\n }\n res\n}\n\nfn main() -> Result<(), Box> {\n let (a, b, c) = read_3::();\n let weeks = min(a / 3, min(b / 2, c / 2));\n let a = a - weeks * 3;\n let b = b - weeks * 2;\n let c = c - weeks * 2;\n let schedule = [1, 2, 3, 1, 3, 2, 1, 1, 2, 3, 1, 3, 2, 1];\n let mut max_additional = 0;\n for start in 0..7 {\n let mut p = start;\n let mut a_cop = a;\n let mut b_cop = b;\n let mut c_cop = c;\n let mut additional = 0;\n let mut flag = false;\n while !flag {\n if schedule[p] == 1 {\n if a_cop > 0 {\n a_cop -= 1;\n additional += 1;\n } else {\n flag = true;\n }\n } else if schedule[p] == 2 {\n if b_cop > 0 {\n b_cop -= 1;\n additional += 1;\n } else {\n flag = true;\n }\n } else {\n if c_cop > 0 {\n c_cop -= 1;\n additional += 1;\n } else {\n flag = true;\n }\n }\n p += 1;\n }\n max_additional = max(max_additional, additional);\n }\n println!(\"{}\", weeks * 7 + max_additional);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "7b873def7681dc5205e79363b49f9f1b", "src_uid": "e17df52cc0615585e4f8f2d31d2daafb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::{max, min};\nuse std::io::stdin;\n\nfn read_ints() -> Vec {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n return line.trim().split(\" \").map(|x| x.parse().unwrap()).collect();\n}\n\nfn main() {\n let mut rations = read_ints();\n let full_weeks = min(rations[0] / 3, min(rations[1] / 2, rations[2] / 2));\n rations[0] -= 3 * full_weeks;\n rations[1] -= 2 * full_weeks;\n rations[2] -= 2 * full_weeks;\n\n let mut max_more_days = 0;\n for start in 0..7 {\n let mut remain = rations.to_vec();\n for day in 0..7 {\n let idx = match (start + day) % 7 {\n 0 | 3 | 6 => 0,\n 1 | 5 => 1,\n _ => 2,\n };\n if remain[idx] == 0 {\n max_more_days = max(max_more_days, day);\n break;\n }\n remain[idx] -= 1;\n }\n }\n\n println!(\"{}\", full_weeks * 7 + max_more_days);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "2368e26d59c279c26853cf177a0890cd", "src_uid": "e17df52cc0615585e4f8f2d31d2daafb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::prelude::BufRead;\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufReader, BufWriter, Write};\n#[allow(unused_imports)]\nuse std::mem::swap;\n#[allow(unused_imports)]\nuse std::str::FromStr;\n\nfn main() {\n\tlet line = read_vector::();\n\tlet (a, b, c) = (line[0], line[1], line[2]);\n\tlet mut ans = 0;\n\tlet arr = vec!['a', 'a', 'b', 'c', 'a', 'c', 'b'];\n\tfor i in 0..7 {\n\t\tlet (mut a, mut b, mut c) = (a, b, c);\n\t\tlet week = min(a / 3, min(b / 2, c / 2));\n\t\tlet mut day = week * 7;\n\t\ta -= week * 3;\n\t\tb -= week * 2;\n\t\tc -= week * 2;\n\t\tloop {\n\t\t\tif arr[(i + day as usize) % 7] == 'a' {\n\t\t\t\tif a == 0 {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ta -= 1;\n\t\t\t} else if arr[(i + day as usize) % 7] == 'b' {\n\t\t\t\tif b == 0 {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tb -= 1;\n\t\t\t} else {\n\t\t\t\tif c == 0 {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tc -= 1;\n\t\t\t}\n\t\t\tday += 1;\n\t\t}\n\t\tans = max(day, ans);\n\t}\n\tprintln!(\"{}\", ans);\n}\n\n#[allow(dead_code)]\nfn read() -> T\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n return buf.trim().parse().unwrap();\n}\n\n#[allow(dead_code)]\nfn read_vector() -> Vec\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n let mut buf = String::with_capacity(100);\n stdin().read_line(&mut buf).unwrap();\n return buf.split_whitespace().map(|s| s.parse().unwrap()).collect();\n}\n\n#[allow(dead_code)]\nfn read_matrix() -> Vec>\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n use std::io::prelude::*;\n let stdin = stdin();\n let mut reader = BufReader::with_capacity(100 * 1024, stdin);\n let mut line = String::with_capacity(100);\n let mut matrix: Vec> = Vec::new();\n\n while reader.read_line(&mut line).unwrap() > 0 {\n matrix.push(\n line.trim()\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect(),\n );\n line.clear();\n }\n\n return matrix;\n}\n\n#[allow(dead_code)]\nfn read_chars() -> Vec {\n let stdin = stdin();\n let mut buf = String::new();\n let _bytes = stdin.read_line(&mut buf).unwrap();\n return buf.trim().chars().collect();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a365c7302d729ba39f57bc8d4a7e8e00", "src_uid": "e17df52cc0615585e4f8f2d31d2daafb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(clippy::many_single_char_names, dead_code, unused_imports, unused_macros, unused_variables)]\n#![recursion_limit = \"1000\"]\nuse std::{cmp::Reverse, collections::*, fmt::Binary, hash::Hash, io::{stdin, stdout, BufWriter, Read, StdinLock, StdoutLock, Write}, iter::FromIterator, mem::swap, ops::Rem};\n\nmacro_rules! parse {\n (check $n: expr, $t: ty) => { std::str::from_utf8_unchecked($n).parse::<$t>().unwrap() };\n ($n: expr, $t: ty) => {\n if cfg!(debug_assertions) {\n parse!(check $n, $t)\n } else {\n #[allow(unused_comparisons)] {\n if <$t>::default()-1 > 0 {\n parse!(unsigned $n, $t)\n } else {\n parse!(signed $n, $t)\n }\n }\n }\n };\n (unsigned $n: expr, $t: ty) => {{\n let mut num = 0;\n\n for d in $n {\n num = num*10 + (*d - b'0') as $t;\n }\n num\n }};\n (signed $n: expr, $t: ty) => {{\n if $n.get_unchecked(0) == &b'-' {\n let mut num = 0;\n\n for d in &$n[1..] {\n num = num*10 - (*d - b'0') as $t;\n }\n num\n } else {\n parse!(unsigned $n, $t)\n }\n }};\n}\n\nmacro_rules! read {\n ($r: expr) => { $r.read() };\n ($r: expr, str) => { String::from_utf8_unchecked($r.read().into()) };\n ($r: expr, f32) => { read!(check $r, f32) };\n ($r: expr, f64) => { read!(check $r, f64) };\n (check $r: expr, $t: ty) => {{\n let n = $r.read();\n parse!(check n, $t)\n }};\n ($r: expr, $t: ty) => {{\n let n = $r.read();\n parse!(n, $t)\n }}\n}\n\nmacro_rules! fill {\n (declare mut $r: expr, $t: ty, $($x: ident),+) => {\n $(\n let mut $x = read!($r, $t);\n )+\n };\n (declare $r: expr, $t: ty, $($x: ident),+) => {\n $(\n let $x = read!($r, $t);\n )+\n };\n ($r: expr, $t: ty, $($x: ident),+) => {\n $(\n $x = read!($r, $t);\n )+\n }\n}\n\nmacro_rules! read_vec {\n (const $r: expr, $t: ty, $n: expr) => {{\n let mut v = [0; $n];\n for x in &mut v {\n *x = read!($r, $t);\n }\n v\n }};\n (fill $r: expr, $t: ty, $v: expr, $n: expr) => {\n for x in &mut $v[..$n] {\n *x = read!($r, $t);\n }\n };\n ($r: expr, str, $n: expr) => {{\n let mut v = Vec::with_capacity($n);\n for _ in 0..$n {\n v.push(read!($r, str));\n // v.push(String::from_utf8_unchecked(read!($r).into()));\n }\n v\n }};\n ($r: expr, $t: ty, $n: expr) => {{\n let mut v = Vec::with_capacity($n);\n for _ in 0..$n {\n v.push(read!($r, $t));\n }\n v\n }};\n ($r: expr, str) => {{\n let mut v = Vec::with_capacity(10_000);\n loop {\n let (tmp, b) = $r.read_with_lf_check();\n v.push(String::from_utf8_unchecked(tmp.into()));\n if b {\n break v;\n }\n }\n }};\n ($r: expr, $t: ty) => {{\n let mut v = Vec::with_capacity(10_000);\n loop {\n let (tmp, b) = $r.read_with_lf_check();\n v.push(read!($r, $t));\n if b {\n break v;\n }\n }\n }};\n ($r: expr) => { read_vec!($r, str) };\n ($r: expr, $n: expr) => { read_vec!($r, str, $n) };\n}\n\nmacro_rules! w {\n ($w: expr $(, $args: expr)*) => {\n write!($w $(, $args)*).unwrap();\n };\n}\n\nmacro_rules! wl {\n ($w: expr $(, $args: expr)*) => {\n writeln!($w $(, $args)*).unwrap();\n };\n}\n\n\nmacro_rules! void {\n ($r: expr) => { void!($r, 2); };\n ($r: expr, 1) => {\n $r.cursor += 1;\n loop {\n if $r.buf.get_unchecked($r.cursor) <= &b' ' {\n if $r.cursor >= $r.buf_len {\n $r.buf_len = $r.stdin.read(&mut $r.buf).unwrap();\n $r.cursor = 0;\n } else {\n $r.cursor += 1;\n $r.reset();\n break;\n }\n } else {\n $r.cursor += 1;\n }\n }\n };\n ($r: expr, $n: expr) => {\n let mut acc = 0;\n $r.cursor += 1;\n loop {\n if $r.buf.get_unchecked($r.cursor) <= &b' ' {\n if $r.cursor >= $r.buf_len {\n $r.buf_len = $r.stdin.read(&mut $r.buf).unwrap();\n $r.cursor = 0;\n } else {\n acc += 1;\n $r.cursor += 1;\n $r.reset();\n if acc == $n {\n break;\n }\n }\n } else {\n $r.cursor += 1;\n }\n }\n };\n}\n\nstruct Reader<'a>/*'*/ {\n stdin: StdinLock<'a>/*'*/,\n cursor: usize,\n buf_len: usize,\n buf: [u8; BUF_LEN],\n temp_end: usize,\n temp: [u8; 10_000],\n}\n\nimpl Reader<'_>/*'*/ {\n #[inline]\n unsafe fn read(&mut self) -> &[u8] {\n let init = self.cursor;\n loop {\n if self.buf.get_unchecked(self.cursor) <= &b' ' {\n if self.cursor >= self.buf_len {\n let s = self.buf_len.saturating_sub(init);\n\n let src = self.buf.as_ptr().add(init);\n let dest = self.temp.as_mut_ptr().add(self.temp_end);\n std::ptr::copy_nonoverlapping(src, dest, s);\n\n self.buf_len = self.stdin.read(&mut self.buf).unwrap();\n self.temp_end += s;\n\n if self.buf_len == 0 {\n *self.temp.get_unchecked_mut(self.temp_end) = b'\\n';\n return &self.temp[..self.temp_end];\n }\n\n self.cursor = 0;\n\n if s == 0 { self.reset(); }\n return self.read();\n }\n\n if self.temp_end != 0 {\n let s = self.cursor - init;\n let n = self.temp_end + s;\n\n let src = self.buf.as_ptr().add(init);\n let dest = self.temp.as_mut_ptr().add(self.temp_end);\n std::ptr::copy_nonoverlapping(src, dest, s);\n *dest.add(s) = b'\\n';\n\n self.cursor += 1;\n self.reset();\n self.temp_end = 0;\n\n return &self.temp[..n];\n }\n\n let t = self.cursor;\n self.cursor += 1;\n self.reset();\n return &self.buf[init..t];\n }\n self.cursor += 1;\n }\n }\n #[inline(always)]\n unsafe fn reset(&mut self) {\n while self.buf.get_unchecked(self.cursor) <= &b' ' {\n self.cursor += 1;\n }\n }\n #[inline(always)]\n unsafe fn read_with_lf_check(&mut self) -> (&[u8], bool) {\n let t = self.read();\n (t, *t.as_ptr().add(t.len()) < b' ')\n }\n}\n\n// const BUF_LEN: usize = 1_000_000;\nconst BUF_LEN: usize = 100_000;\nfn main() {\n let stdin = stdin();\n let stdin = stdin.lock();\n let stdout = stdout();\n let stdout = stdout.lock();\n\n unsafe {\n solve(\n &mut Reader {\n stdin,\n cursor: 0,\n buf_len: 0,\n buf: [0; BUF_LEN],\n temp_end: 0,\n temp: [0; 10_000]\n },\n &mut BufWriter::with_capacity(100_000, stdout),\n );\n }\n}\n\nconst M: usize = std::usize::MAX;\nconst REM: usize = 1_000_000_007;\n\nfn bin_pow_rem(mut a: u128, mut b: u128, rem: u128) -> u128 {\n a %= rem;\n let mut res = 1;\n\n while b != 0 {\n if b&1 == 1 {\n res = res*a%rem;\n }\n a = a*a%rem;\n b >>= 1;\n }\n res\n}\n\n#[inline]\nunsafe fn solve(r: &mut Reader, w: &mut BufWriter) {\n let n = read!(r, u128);\n wl!(w, \"{}\", bin_pow_rem(4, (1 << n) -2, REM as u128)*6 % REM as u128);\n}", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "04408ea7d40f6af9060f256712d82d15", "src_uid": "5144b9b281ea4087d8334d91c3c8bda4", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(clippy::many_single_char_names, dead_code, unused_imports, unused_macros, unused_variables)]\n#![recursion_limit = \"1000\"]\nuse std::{cmp::Reverse, collections::*, fmt::Binary, hash::Hash, io::{stdin, stdout, BufWriter, Read, StdinLock, StdoutLock, Write}, iter::FromIterator, mem::swap, ops::Rem};\n\nmacro_rules! parse {\n (check $n: expr, $t: ty) => { std::str::from_utf8_unchecked($n).parse::<$t>().unwrap() };\n ($n: expr, $t: ty) => {\n if cfg!(debug_assertions) {\n parse!(check $n, $t)\n } else {\n #[allow(unused_comparisons)] {\n if <$t>::default()-1 > 0 {\n parse!(unsigned $n, $t)\n } else {\n parse!(signed $n, $t)\n }\n }\n }\n };\n (unsigned $n: expr, $t: ty) => {{\n let mut num = 0;\n\n for d in $n {\n num = num*10 + (*d - b'0') as $t;\n }\n num\n }};\n (signed $n: expr, $t: ty) => {{\n if $n.get_unchecked(0) == &b'-' {\n let mut num = 0;\n\n for d in &$n[1..] {\n num = num*10 - (*d - b'0') as $t;\n }\n num\n } else {\n parse!(unsigned $n, $t)\n }\n }};\n}\n\nmacro_rules! read {\n ($r: expr) => { $r.read() };\n ($r: expr, str) => { String::from_utf8_unchecked($r.read().into()) };\n ($r: expr, f32) => { read!(check $r, f32) };\n ($r: expr, f64) => { read!(check $r, f64) };\n (check $r: expr, $t: ty) => {{\n let n = $r.read();\n parse!(check n, $t)\n }};\n ($r: expr, $t: ty) => {{\n let n = $r.read();\n parse!(n, $t)\n }}\n}\n\nmacro_rules! fill {\n (declare mut $r: expr, $t: ty, $($x: ident),+) => {\n $(\n let mut $x = read!($r, $t);\n )+\n };\n (declare $r: expr, $t: ty, $($x: ident),+) => {\n $(\n let $x = read!($r, $t);\n )+\n };\n ($r: expr, $t: ty, $($x: ident),+) => {\n $(\n $x = read!($r, $t);\n )+\n }\n}\n\nmacro_rules! read_vec {\n (const $r: expr, $t: ty, $n: expr) => {{\n let mut v = [0; $n];\n for x in &mut v {\n *x = read!($r, $t);\n }\n v\n }};\n (fill $r: expr, $t: ty, $v: expr, $n: expr) => {\n for x in &mut $v[..$n] {\n *x = read!($r, $t);\n }\n };\n ($r: expr, str, $n: expr) => {{\n let mut v = Vec::with_capacity($n);\n for _ in 0..$n {\n v.push(read!($r, str));\n // v.push(String::from_utf8_unchecked(read!($r).into()));\n }\n v\n }};\n ($r: expr, $t: ty, $n: expr) => {{\n let mut v = Vec::with_capacity($n);\n for _ in 0..$n {\n v.push(read!($r, $t));\n }\n v\n }};\n ($r: expr, str) => {{\n let mut v = Vec::with_capacity(10_000);\n loop {\n let (tmp, b) = $r.read_with_lf_check();\n v.push(String::from_utf8_unchecked(tmp.into()));\n if b {\n break v;\n }\n }\n }};\n ($r: expr, $t: ty) => {{\n let mut v = Vec::with_capacity(10_000);\n loop {\n let (tmp, b) = $r.read_with_lf_check();\n v.push(read!($r, $t));\n if b {\n break v;\n }\n }\n }};\n ($r: expr) => { read_vec!($r, str) };\n ($r: expr, $n: expr) => { read_vec!($r, str, $n) };\n}\n\nmacro_rules! w {\n ($w: expr $(, $args: expr)*) => {\n write!($w $(, $args)*).unwrap();\n };\n}\n\nmacro_rules! wl {\n ($w: expr $(, $args: expr)*) => {\n writeln!($w $(, $args)*).unwrap();\n };\n}\n\n\nmacro_rules! void {\n ($r: expr) => { void!($r, 2); };\n ($r: expr, 1) => {\n $r.cursor += 1;\n loop {\n if $r.buf.get_unchecked($r.cursor) <= &b' ' {\n if $r.cursor >= $r.buf_len {\n $r.buf_len = $r.stdin.read(&mut $r.buf).unwrap();\n $r.cursor = 0;\n } else {\n $r.cursor += 1;\n $r.reset();\n break;\n }\n } else {\n $r.cursor += 1;\n }\n }\n };\n ($r: expr, $n: expr) => {\n let mut acc = 0;\n $r.cursor += 1;\n loop {\n if $r.buf.get_unchecked($r.cursor) <= &b' ' {\n if $r.cursor >= $r.buf_len {\n $r.buf_len = $r.stdin.read(&mut $r.buf).unwrap();\n $r.cursor = 0;\n } else {\n acc += 1;\n $r.cursor += 1;\n $r.reset();\n if acc == $n {\n break;\n }\n }\n } else {\n $r.cursor += 1;\n }\n }\n };\n}\n\nstruct Reader<'a>/*'*/ {\n stdin: StdinLock<'a>/*'*/,\n cursor: usize,\n buf_len: usize,\n buf: [u8; BUF_LEN],\n temp_end: usize,\n temp: [u8; 10_000],\n}\n\nimpl Reader<'_>/*'*/ {\n #[inline]\n unsafe fn read(&mut self) -> &[u8] {\n let init = self.cursor;\n loop {\n if self.buf.get_unchecked(self.cursor) <= &b' ' {\n if self.cursor >= self.buf_len {\n let s = self.buf_len.saturating_sub(init);\n\n let src = self.buf.as_ptr().add(init);\n let dest = self.temp.as_mut_ptr().add(self.temp_end);\n std::ptr::copy_nonoverlapping(src, dest, s);\n\n self.buf_len = self.stdin.read(&mut self.buf).unwrap();\n self.temp_end += s;\n\n if self.buf_len == 0 {\n *self.temp.get_unchecked_mut(self.temp_end) = b'\\n';\n return &self.temp[..self.temp_end];\n }\n\n self.cursor = 0;\n\n if s == 0 { self.reset(); }\n return self.read();\n }\n\n if self.temp_end != 0 {\n let s = self.cursor - init;\n let n = self.temp_end + s;\n\n let src = self.buf.as_ptr().add(init);\n let dest = self.temp.as_mut_ptr().add(self.temp_end);\n std::ptr::copy_nonoverlapping(src, dest, s);\n *dest.add(s) = b'\\n';\n\n self.cursor += 1;\n self.reset();\n self.temp_end = 0;\n\n return &self.temp[..n];\n }\n\n let t = self.cursor;\n self.cursor += 1;\n self.reset();\n return &self.buf[init..t];\n }\n self.cursor += 1;\n }\n }\n #[inline(always)]\n unsafe fn reset(&mut self) {\n while self.buf.get_unchecked(self.cursor) <= &b' ' {\n self.cursor += 1;\n }\n }\n #[inline(always)]\n unsafe fn read_with_lf_check(&mut self) -> (&[u8], bool) {\n let t = self.read();\n (t, *t.as_ptr().add(t.len()) < b' ')\n }\n}\n\nconst BUF_LEN: usize = 1_000_000;\nfn main() {\n let stdin = stdin();\n let stdin = stdin.lock();\n let stdout = stdout();\n let stdout = stdout.lock();\n\n unsafe {\n solve(\n &mut Reader {\n stdin,\n cursor: 0,\n buf_len: 0,\n buf: [0; BUF_LEN],\n temp_end: 0,\n temp: [0; 10_000]\n },\n &mut BufWriter::with_capacity(100_000, stdout),\n );\n }\n}\n\nconst M: usize = std::usize::MAX;\nconst REM: usize = 1_000_000_007;\n\nfn bin_pow_rem(mut a: u64, mut b: u64, rem: u64) -> u64 {\n a %= rem;\n let mut res = 1;\n\n while b != 0 {\n if b&1 == 1 {\n res = res*a%rem;\n }\n a = a*a%rem;\n b >>= 1;\n }\n res\n}\n\n#[inline]\nunsafe fn solve(r: &mut Reader, w: &mut BufWriter) {\n let n = read!(r, u64);\n wl!(w, \"{}\", bin_pow_rem(4, (1 << n) -2, REM as u64)*6 % REM as u64);\n}", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "d1950c105361978990c4ee0c7253685e", "src_uid": "5144b9b281ea4087d8334d91c3c8bda4", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn log2(mut input: u128) -> i32 {\n let mut count = -1;\n while input != 0 {\n input = input >> 1;\n count += 1;\n }\n return count\n}\nfn main() {\n let stdin = stdin();\n let mut string = String::new();\n\n stdin.read_line(&mut string).unwrap();\n\n let n = string.trim().parse::().unwrap();\n\n let mut nodes = 2u128.pow(n as u32) - 2;\n let mut re = 1;\n loop {\n let mut inner_re = 4;\n if nodes == 0 {\n break;\n }\n\n let times = log2(nodes) as u32;\n for _ in 0..times {\n inner_re = inner_re * inner_re;\n if inner_re > (1e9 as u128 + 7) {\n inner_re = inner_re % (1e9 as u128 + 7)\n }\n }\n\n re = re * inner_re % (1e9 as u128 + 7);\n nodes = nodes - 2u128.pow(times);\n }\n println!(\"{}\", re * 6 % (1e9 as u128 + 7))\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "dca03712172294158121bafd70c0bcab", "src_uid": "5144b9b281ea4087d8334d91c3c8bda4", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read(); };\n ($t: ty) => { read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n); };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }); };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }); }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }); }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE.rotate_right(1) >> self.leading_zeros() } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn set_max(&mut self, v: T) -> bool;\n fn set_min(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for T {\n fn set_max(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn set_min(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { r.wrapping_add(m) }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\n// type ModInt = ModInt998_244_353;\ntype ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n \n for _case_num in 1..=num_cases {\n let k = read!(u32);\n\n let n = (1u64 << k) - 1;\n let ans = mi(4).pow(n-1) * 6;\n println!(ans);\n }\n \n out_flush();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "e58525df6bf67aa0b9e58313dc4a7cf9", "src_uid": "5144b9b281ea4087d8334d91c3c8bda4", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::Ordering;\r\nuse std::cmp;\r\nuse std::cmp::min;\r\nuse std::collections::BTreeMap;\r\nuse std::process;\r\nuse std::cmp::Ord;\r\nuse std::collections::HashMap;\r\nuse std::collections::HashSet;\r\nuse std::collections::VecDeque;\r\nuse std::collections::BTreeSet;\r\nuse std::mem;\r\nuse std::collections::BinaryHeap;\r\nuse std::hash::{Hash, Hasher};\r\n\r\npub struct Scanner {\r\n stdin: R,\r\n}\r\n \r\nimpl Scanner {\r\n pub fn read(&mut self) -> T {\r\n use std::io::Read;\r\n let buf = self\r\n .stdin\r\n .by_ref()\r\n .bytes()\r\n .map(|b| b.unwrap())\r\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r')\r\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r')\r\n .collect::>();\r\n std::str::from_utf8(&buf).unwrap()\r\n .parse()\r\n .ok()\r\n .expect(\"Parse error.\")\r\n }\r\n pub fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.read()).collect()\r\n }\r\n pub fn chars(&mut self) -> Vec {\r\n self.read::().chars().collect()\r\n }\r\n}\r\n\r\n\r\npub trait BinarySearch {\r\n fn lower_bound(&self, x:&T) -> usize;\r\n fn upper_bound(&self, x:&T) -> usize;\r\n}\r\n\r\nimpl BinarySearch for VecDeque{\r\n fn lower_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less => {\r\n low = mid + 1;\r\n }\r\n Ordering::Equal | Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n\r\n fn upper_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less | Ordering::Equal => {\r\n low = mid + 1;\r\n }\r\n Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n}\r\nimpl BinarySearch for [T]{\r\n fn lower_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less => {\r\n low = mid + 1;\r\n }\r\n Ordering::Equal | Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n\r\n fn upper_bound(&self, x: &T) -> usize {\r\n let mut low = 0;\r\n let mut high = self.len();\r\n\r\n while low != high {\r\n let mid = (low + high) / 2;\r\n match self[mid].cmp(x) {\r\n Ordering::Less | Ordering::Equal => {\r\n low = mid + 1;\r\n }\r\n Ordering::Greater => {\r\n high = mid;\r\n }\r\n }\r\n }\r\n low\r\n }\r\n}\r\n\r\n//10\u9032\u6570\u3067\u8868\u3059\u3068n\u3092x\u9032\u6570\u3067\u8868\u3059\r\nfn base_number(x:usize, n:usize)->Vec{\r\n let mut x = x;\r\n let mut n = n;\r\n let mut r = 1;\r\n let mut q = x;\r\n let mut res = vec![];\r\n while(q>=n){\r\n r = q%n;\r\n res.push(r);\r\n q = q/n;\r\n }\r\n r = q%n;\r\n res.push(r);\r\n res.reverse();\r\n return res\r\n}\r\n\r\n//\u6700\u5927\u516c\u7d04\u6570\r\nfn gcd(a:usize, b:usize)->usize{\r\n if b==0{return a;}\r\n return gcd(b, a%b);\r\n}\r\n//\u62e1\u5f35GCD\r\n//ax+by=1\u3068\u306a\u308b\u6574\u6570x,y\u3092\u6c42\u3081\u308b\r\nfn extgcd(a:i64, b:i64, x:&mut i64, y:&mut i64) -> i64{\r\n let mut d = a;\r\n if b != 0{\r\n d = extgcd(b, a%b, y, x);\r\n *y -= (a/b)*(*x);\r\n }\r\n else{\r\n *x = 1;\r\n *y = 0;\r\n }\r\n return d;\r\n}\r\n//\u6700\u5c0f\u516c\u500d\u6570\r\nfn lcm(a:usize, b:usize)->usize{\r\n return (b/gcd(a, b))*a;\r\n}\r\n//\u9006\u5143\r\nfn modinv(a:usize, M:usize)->usize{\r\n let mut b = M as i64;\r\n let mut u = 1 as i64;\r\n let mut v = 0 as i64;\r\n let mut a = a as i64;\r\n let mut m = M as i64;\r\n while(b>0){\r\n let mut t = a/b;\r\n a -= t*b;\r\n mem::swap(&mut a, &mut b);\r\n u-=t*v;\r\n mem::swap(&mut u, &mut v);\r\n }\r\n u%=m;\r\n if u<0{u+=m;}\r\n return u as usize;\r\n\r\n}\r\n//\u9023\u7acb\u5408\u540c\u65b9\u7a0b\u5f0f\r\n//A * X = B (MOD M) ->(b, m) x=b(mod m)\r\n\r\n\r\n//\u5ea7\u6a19\u5727\u7e2e\uff12\u6b21\u5143 [1, W]\r\nfn linear_congruence(A:&Vec, B:&Vec, M:&Vec) -> (i64, i64){\r\n let mut x = 0;\r\n let mut m = 1;\r\n for i in 0..A.len(){\r\n let mut a = A[i]*m;\r\n let mut b = B[i]-A[i]*x;\r\n let mut d = gcd(M[i] as usize, a as usize) as i64;\r\n if (b%d != 0){ \r\n return (0, -1);\r\n }\r\n let mut t= b/d*(modinv( (a/d) as usize, (M[i]/d) as usize) as i64)%(M[i]/d);\r\n x = x+m*t;\r\n m*=M[i]/d;\r\n }\r\n return (x%m, m);\r\n\r\n}\r\n\r\n\r\n//\u5ea7\u6a19\u5727\u7e2e\uff12\u6b21\u5143 [1, W]\r\nfn compress_2d(x1:&mut Vec, x2:&mut Vec, w:i64) -> Vec{\r\n let mut xs = vec![];\r\n for i in 0..x1.len(){\r\n for d in -1..2{\r\n let mut tx1 = x1[i]+d;\r\n let mut tx2 = x2[i]+d;\r\n if (1<=tx1 && tx1 <= w){\r\n xs.push(tx1);\r\n }\r\n if (1<=tx2 && tx2 <= w){\r\n xs.push(tx2);\r\n }\r\n }\r\n }\r\n let mut h = HashSet::new();\r\n for i in 0..xs.len(){\r\n h.insert(xs[i]);\r\n }\r\n let mut xs:Vec = h.into_iter().collect();\r\n xs.sort();\r\n return xs;\r\n}\r\n\r\n\r\n//\u30bb\u30b0\u30e1\u30f3\u30c8\u6728\r\nstruct segment_tree{\r\n n: usize,\r\n dat: Vec,\r\n op:Op,\r\n e:I,\r\n}\r\nimpl segment_tree\r\n \r\n \r\n where Op: Fn(I, I) -> I, I:Copy{\r\n \r\n pub fn new(n_:usize, op: Op, e:I)->Self{\r\n let mut n = 1;\r\n while(n0){\r\n k = (k-1)/2;\r\n self.dat[k] = (self.op)(self.dat[k*2 + 1], self.dat[k*2+2]);\r\n }\r\n }\r\n\r\n pub fn query_sub(&self, a:usize, b:usize, k:usize, l:usize, r:usize) -> I{\r\n if r<=a || b<=l{return self.e;}\r\n if a<=l && r<=b{return self.dat[k];}\r\n else{\r\n let mut vl = self.query_sub(a, b, k*2+1, l, (l+r)/2);\r\n let mut vr = self.query_sub(a, b, k*2+2, (l+r)/2, r);\r\n return (self.op)(vl, vr);\r\n }\r\n }\r\n pub fn query(&self, a:usize, b:usize)->I{\r\n return self.query_sub(a, b, 0, 0, self.n);\r\n }\r\n }\r\n\r\n\r\n\r\n//\u9045\u5ef6\u8a55\u4fa1\u30bb\u30b0\u30e1\u30f3\u30c8\u6728\r\n// composition(a, b) -> b(a(x))\r\nstruct lazy_segment_tree{\r\n n: usize,\r\n op:op,\r\n mapping:mapping,\r\n composition:composition,\r\n s:S,\r\n f:F,\r\n dat: Vec,\r\n lazy:Vec,\r\n \r\n}\r\nimpl lazy_segment_tree\r\n \r\n \r\n where op:Fn(S, S)->S, mapping:Fn(F, S)->S, composition:Fn(F, F)->F, S:Copy, F:Copy, S:PartialEq, F:PartialEq{\r\n \r\n pub fn new(n_:usize, s:S, f:F, op:op, mapping:mapping, composition:composition)->Self{\r\n let mut n = 1;\r\n while(n){\r\n for i in 0..self.n*2-1{\r\n self.dat.push(self.s.clone());\r\n self.lazy.push(self.f.clone());\r\n }\r\n for i in 0..initial.len(){\r\n self.dat[i+self.n-1] = initial[i];\r\n }\r\n for i in (0..self.n-1).rev(){\r\n self.dat[i] = (self.op)(self.dat[i*2+1], self.dat[i*2+2]);\r\n }\r\n }\r\n pub fn eval(&mut self, k:usize){\r\n if self.lazy[k] == self.f{\r\n return;\r\n }\r\n if k*2+1 < self.n*2-1{\r\n self.lazy[k*2+1] = (self.composition)(self.lazy[k*2+1], self.lazy[k]);\r\n self.lazy[k*2+2] = (self.composition)(self.lazy[k*2+2], self.lazy[k]);\r\n }\r\n self.dat[k] = (self.mapping)(self.lazy[k], self.dat[k]);\r\n self.lazy[k] = self.f;\r\n }\r\n pub fn update_sub(&mut self, a:usize, b:usize, x:F, k:usize, l:usize, r:usize)->S{\r\n self.eval(k);\r\n if r<=a || b<=l{\r\n return self.dat[k];\r\n }\r\n if a<=l && r<= b{\r\n self.lazy[k] = (self.composition)(self.lazy[k], x);\r\n return (self.mapping)(self.lazy[k], self.dat[k]);\r\n }\r\n let mut vr = self.update_sub(a, b, x, k*2+1, l, (l+r)/2);\r\n let mut vl = self.update_sub(a, b, x, k*2+2, (l+r)/2, r);\r\n self.dat[k] = (self.op)(vr, vl);\r\n return self.dat[k];\r\n }\r\n pub fn update(&mut self, a:usize, b:usize, x:F){\r\n self.update_sub(a, b, x, 0, 0, self.n);\r\n }\r\n pub fn query_sub(&mut self, a:usize, b:usize, k:usize, l:usize, r:usize)->S{\r\n self.eval(k);\r\n if r<= a || b <= l{\r\n return self.s;\r\n }\r\n else if a<= l && r<= b{\r\n return self.dat[k];\r\n }\r\n else{\r\n let mut vl = self.query_sub(a, b, k*2+1, l, (l+r)/2);\r\n let mut vr = self.query_sub(a, b, k*2+2, (l+r)/2, r);\r\n return (self.op)(vl, vr);\r\n }\r\n }\r\n pub fn query(&mut self, a:usize, b:usize)->S{\r\n return self.query_sub(a, b, 0, 0, self.n);\r\n }\r\n\r\n }\r\n\r\n//\u30c0\u30a4\u30af\u30b9\u30c8\u30e9\u6cd5\r\nfn dijkstra(s:usize, g:&Vec>)->Vec{\r\n let mut dist = vec![INF;g.len()];\r\n dist[s] = 0;\r\n let mut h = BinaryHeap::new();\r\n h.push((0, s));\r\n while(h.len() != 0){\r\n let mut t = h.pop().unwrap();\r\n let mut d = t.0 * -1;\r\n let mut v = t.1;\r\n if dist[v]d+dd{\r\n dist[n] = d+dd;\r\n h.push((dist[n]*-1, n));\r\n }\r\n }\r\n }\r\n return dist;\r\n}\r\nfn dijkstra2(s:usize, g:&Vec>)->Vec{\r\n let mut dist = vec![INF;g.len()];\r\n dist[s] = 0;\r\n let mut h = BinaryHeap::new();\r\n h.push((0, s));\r\n while(h.len() != 0){\r\n let mut t = h.pop().unwrap();\r\n let mut d = t.0 * -1;\r\n let mut v = t.1;\r\n if dist[v]d+dd{\r\n dist[n] = d+dd;\r\n h.push((dist[n]*-1, n));\r\n }\r\n }\r\n }\r\n return dist;\r\n}\r\nfn dijkstra3(st:(usize, usize), go:(usize, usize), h:usize, w:usize, map:&Vec>)->Vec>{ \r\n let mut d = vec![vec![INF;w];h];\r\n d[st.0][st.1] = 0;\r\n let mut hh = BinaryHeap::new();\r\n hh.push((0, st));\r\n let mut dx = vec![0, 0, 1, -1];\r\n let mut dy = vec![1, -1, 0, 0];\r\n \r\n while(hh.len() != 0){\r\n let mut tt = hh.pop().unwrap();\r\n let mut dist = tt.0 as i64 * -1;\r\n let mut x = (tt.1).0;\r\n let mut y = (tt.1).1;\r\n if d[x][y]dist+1{\r\n d[nx][ny]=dist+1;\r\n hh.push((-1*(dist+1),(nx, ny)));\r\n }\r\n\r\n }\r\n }\r\n }\r\n return d;\r\n}\r\n//\uff12\u6b21\u5143\u548c [ (x, y), (x, y) )\r\n//sum[i+1][j+1] = ((sum[i+1][j]+sum[i][j+1]+MODu-sum[i][j])%MODu+dp[i+1][j+1])%MODu;\r\n/*for (int i = 0; i < H; i++) {\r\n \r\n for (int j = 0; j < W; j++) {\r\n imos[i][j + 1] += imos[i][j];\r\n }\r\n }\r\n \r\n for (int j = 0; j < W; j++) {\r\n for (int i = 0; i < H; i++) {\r\n imos[i + 1][j] += imos[i][j];\r\n }\r\n }\r\n \r\n sums[yy1][xx1]+=1;\r\n sums[yy2][xx2]+=1;\r\n sums[yy1][xx2]-=1;\r\n sums[yy2][xx1]-=1;\r\n }\r\n for i in 0..ys.len() {\r\n for j in 0..xs.len(){\r\n sums[i][j + 1] += sums[i][j];\r\n }\r\n }\r\n \r\n for j in 0..xs.len(){\r\n for i in 0..ys.len(){\r\n sums[i + 1][j] += sums[i][j];\r\n }\r\n }\r\n*/\r\n//3\u6b21\u5143\u548c [ (x, y, z), (x, y, z) )\r\n/*\r\n//let mut v = vec![X1, Y1, Z1, X2, Y2, Z2];\r\n let mut si = vec![1i64, -1i64];\r\n for i in 0..2{\r\n for j in 0..2{\r\n for k in 0..2{\r\n let mut X = v[0+i*3];\r\n let mut Y = v[1+j*3];\r\n let mut Z = v[2+k*3];\r\n sum[X][Y][Z]+=si[i]*si[j]*si[k];\r\n }\r\n }\r\n }\r\n }\r\n for i in 0..xs.len()-1{\r\n for j in 0..ys.len(){\r\n for k in 0..zs.len(){\r\n sum[i+1][j][k] += sum[i][j][k];\r\n }\r\n }\r\n }\r\n \r\n for i in 0..xs.len(){\r\n for j in 0..ys.len()-1{\r\n for k in 0..zs.len(){\r\n sum[i][j+1][k] += sum[i][j][k];\r\n }\r\n }\r\n }\r\n \r\n for i in 0..xs.len(){\r\n for j in 0..ys.len(){\r\n for k in 0..zs.len()-1{\r\n sum[i][j][k+1] += sum[i][j][k];\r\n }\r\n }\r\n }\r\n*/\r\n\r\n//\u968e\u4e57\r\nfn invs(max:usize)->(Vec, Vec){\r\n let mut fac = vec![0;max+1];\r\n let mut ifac = vec![0;max+1];\r\n fac[0] = 1;\r\n ifac[0] = 1;\r\n for i in 0..max{\r\n \r\n fac[i+1] = fac[i] * (i+1)%MODu;\r\n ifac[i+1] = ifac[i] * modpow(i+1, MODu - 2)%MODu;\r\n }\r\n (fac, ifac)\r\n}\r\n//\u30b3\u30f3\u30d3\u30cd\u30fc\u30b7\u30e7\u30f3\r\nfn comb(a:usize, b:usize, fac:&Vec, ifac:&Vec)->usize{\r\n let mut a = a;\r\n let mut b = b;\r\n if a == 0 && b == 0{return 1;}\r\n if a, ifac:&Vec)->usize{\r\n return comb(n+r-1, r, fac, ifac);\r\n}\r\n//\r\nfn modpow(x:usize, n:usize) -> usize{\r\n let mut ans = 1;\r\n let mut n = n as usize;\r\n let mut x = x;\r\n while(n != 0){\r\n if (n&1 == 1){ans = ans*x%MODu;}\r\n x = x*x%MODu;\r\n n = n>>1;\r\n }\r\n ans\r\n}\r\nfn modpow2(x:i64, n:i64, m:i32) -> i64{\r\n let mut ans = 1;\r\n let mut n = n as i64;\r\n let mut x = x;\r\n while(n != 0){\r\n if (n&1 == 1){ans = ans*x%m as i64;}\r\n x = x*x%m as i64;\r\n n = n>>1;\r\n }\r\n ans\r\n}\r\n\r\n\r\n\r\n//\u30e6\u30cb\u30aa\u30f3\u30d5\u30a1\u30a4\u30f3\u30c9\u6728\r\nstruct union_find{\r\n par:Vec,\r\n rank:Vec,\r\n size:Vec,\r\n size_edge:Vec,\r\n}\r\nimpl union_find{\r\n fn new(n:usize) -> union_find{\r\n let mut par = vec![0;n];\r\n for i in 0..n{\r\n par[i] = i;\r\n }\r\n union_find{\r\n par:par,\r\n rank:vec![0;n],\r\n size:vec![1;n],\r\n size_edge:vec![0;n],\r\n }\r\n }\r\n fn find(&mut self, x:usize) ->usize{\r\n if(self.par[x] == x){\r\n x\r\n }\r\n else{\r\n let p = self.par[x];\r\n let res = self.find(p);\r\n self.par[x] = res;\r\n res\r\n }\r\n }\r\n fn same(&mut self, a:usize, b:usize)->bool{\r\n self.find(a) == self.find(b)\r\n }\r\n fn unite(&mut self, a:usize, b:usize){\r\n let x = self.find(a);\r\n let y = self.find(b);\r\n if x != y{\r\n if (self.rank[x] < self.rank[y]){\r\n self.par[x] = y;\r\n self.size[y] += self.size[x];\r\n self.size_edge[y] += self.size_edge[x];\r\n self.size_edge[y] += 1;\r\n }\r\n else{\r\n self.par[y] = x;\r\n self.size[x] += self.size[y];\r\n self.size_edge[x] += self.size_edge[y];\r\n self.size_edge[x] += 1;\r\n if(self.rank[x] == self.rank[y]){ self.rank[x]+=1;}\r\n }\r\n\r\n }\r\n else{\r\n self.size_edge[x] += 1;\r\n }\r\n }\r\n fn check_size(&mut self, a:usize) -> usize{\r\n let x = self.find(a);\r\n let s = self.size[x];\r\n s\r\n }\r\n}\r\n//\u504f\u89d2\u30bd\u30fc\u30c8 \u53cd\u6642\u8a08\u5468\u308a\r\nfn norm(x:f64, y:f64)->f64{\r\n (x*x + y*y).sqrt()\r\n}\r\nfn rad(x:f64, y:f64)->f64{\r\n if y>=0.0{\r\n (x /norm(x, y)).acos()\r\n }\r\n else{\r\n 2.0*PI - (x/norm(x,y)).acos()\r\n }\r\n}\r\nfn acos(v1:Vec, v2:Vec)->f64{\r\n ((v1[0]*v2[0] + v1[1]*v2[1])/(norm(v1[0], v1[1])*norm(v2[0], v2[1]))).acos()\r\n}\r\n\r\nfn argument_sort(xy:&mut Vec>){\r\n xy.sort_by(|a, b| rad(a[0], a[1]).partial_cmp(&(rad(b[0], b[1]))).unwrap());\r\n}\r\nfn argument_sort2(xy:&mut Vec<(f64, f64, usize)>){\r\n xy.sort_by(|a, b| rad(a.0, a.1).partial_cmp(&(rad(b.0, b.1))).unwrap());\r\n}\r\n\r\n//\u884c\u5217\u306e\u639b\u3051\u7b97 A*B\r\n//\r\nfn matmul(A:&Vec>, B:&Vec>) -> Vec>{\r\n let mut C = vec![vec![0;B[0].len()];A.len()];\r\n for i in 0..A.len(){\r\n for k in 0..B.len(){\r\n for j in 0..B[0].len(){\r\n C[i][j] += A[i][k]*B[k][j];\r\n C[i][j] %= MOD;\r\n }\r\n }\r\n }\r\n return C;\r\n}\r\nfn divisor(n:usize) -> Vec{\r\n let mut res:Vec = Vec::new();\r\n for i in 1..n+1{\r\n if i*i>n{break;}\r\n if n%i == 0{\r\n res.push(i);\r\n if i != n/i{\r\n res.push(n/i);\r\n }\r\n }\r\n }\r\n res\r\n}\r\n\r\n\r\n//x\u306b10\u306epow\u4e57\u3092\u639b\u3051\u3066\u5c0f\u6570\u90e8\u5206\u3092\u6d88\u3059\r\nfn f64_trans(x:Vec, pow:usize)->i64{\r\n let mut w = x.len();\r\n let mut a = vec![];\r\n let mut b = vec![];\r\n let mut f = false;\r\n let mut ism = false;\r\n if x[0] == '-'{\r\n ism = true;\r\n }\r\n for i in 0..x.len(){\r\n if x[i] == '-'{\r\n continue;\r\n }\r\n if x[i] == '.'{\r\n w = i;\r\n f = true;\r\n }\r\n else if f{\r\n b.push(x[i]);\r\n }\r\n else{\r\n a.push(x[i]);\r\n }\r\n }\r\n for i in 0..b.len(){\r\n a.push(b[i]);\r\n }\r\n for j in 0..pow-b.len(){\r\n a.push('0');\r\n }\r\n let mut now = 1;\r\n let mut res = 0;\r\n for i in (0..a.len()).rev(){\r\n res += now*(a[i] as i64 - '0' as i64);\r\n now*=10;\r\n }\r\n if ism{\r\n res*=-1;\r\n }\r\n return res;\r\n}\r\n\r\n\r\n\r\n\r\n//\u30ed\u30fc\u30ea\u30f3\u30b0\u30cf\u30c3\u30b7\u30e5\r\nstruct rolling_hash{\r\n base1:usize,\r\n base2:usize,\r\n mod1:usize,\r\n mod2:usize,\r\n hash1:Vec,\r\n hash2:Vec,\r\n power1:Vec,\r\n power2:Vec\r\n}\r\nimpl rolling_hash{\r\n fn new(S:&Vec)->rolling_hash{\r\n let mut n = S.len();\r\n let mut base1 = 1007;\r\n let mut base2 = 2009;\r\n let mut mod1 = 1000000007;\r\n let mut mod2 = 1000000009;\r\n let mut hash1 = vec![0;n+1];\r\n let mut hash2 = vec![0;n+1];\r\n let mut power1 = vec![1;n+1];\r\n let mut power2 = vec![1;n+1];\r\n\r\n for i in 0..n{\r\n hash1[i+1] = (hash1[i] * base1 + S[i])%mod1;\r\n hash2[i+1] = (hash2[i] * base2 + S[i])%mod2;\r\n power1[i+1] = (power1[i] * base1)%mod1;\r\n power2[i+1] = (power2[i] * base2)%mod2;\r\n }\r\n\r\n return rolling_hash{\r\n hash1:hash1,\r\n hash2:hash2,\r\n power1:power1,\r\n power2:power2,\r\n base1:base1,\r\n base2:base2,\r\n mod1:mod1,\r\n mod2:mod2\r\n }\r\n }\r\n // [l, r) \r\n fn get(&self, l:usize, r:usize)->(usize, usize){\r\n let mut res1 = self.hash1[r] as i64 - self.hash1[l] as i64 * self.power1[r-l] as i64%self.mod1 as i64;\r\n if (res1<0) {res1+= self.mod1 as i64;}\r\n let mut res2 = self.hash2[r] as i64 - self.hash2[l] as i64 * self.power2[r-l] as i64%self.mod2 as i64;\r\n if (res2<0) {res2+= self.mod2 as i64;}\r\n return (res1 as usize, res2 as usize);\r\n }\r\n}\r\n\r\n/*\r\n#[macro_use]\r\nextern crate lazy_static;\r\nlazy_static!{\r\n static ref all:Vec={\r\n let n_ = 200001;\r\n let mut a = vec![0;n_+1];\r\n for i in 1..n_+1{\r\n a[i] = (a[i-1]*10%MODu+1)%MODu;\r\n }\r\n a\r\n };\r\n}\r\n*/\r\n//\u4e2d\u56fd\u5270\u4f59\u5b9a\u7406\r\nfn safe_mod(x:i64, m:i64)->i64{\r\n let mut x = x;\r\n let mut m = m;\r\n x%=m;\r\n if x<0{\r\n x+=m;\r\n }\r\n return x;\r\n}\r\nfn inv_gcd(a:i64, b:i64)->(i64, i64){\r\n let mut a = a;\r\n let mut b = b;\r\n a = safe_mod(a, b);\r\n if (a == 0){\r\n return (b, 0);\r\n }\r\n\r\n let mut s = b;\r\n let mut t = a;\r\n let mut m0 = 0;\r\n let mut m1 = 1;\r\n\r\n while (t != 0) {\r\n let mut u = s / t;\r\n s -= t * u;\r\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\r\n\r\n // [3]:\r\n // (s - t * u) * |m1| + t * |m0 - m1 * u|\r\n // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)\r\n // = s * |m1| + t * |m0| <= b\r\n\r\n let mut tmp = s;\r\n s = t;\r\n t = tmp;\r\n tmp = m0;\r\n m0 = m1;\r\n m1 = tmp;\r\n }\r\n // by [3]: |m0| <= b/g\r\n // by g != b: |m0| < b/g\r\n if (m0 < 0){\r\n m0 += b / s;\r\n }\r\n return (s, m0);\r\n}\r\nfn floor_sum(n: i64, m: i64, mut a: i64, mut b: i64) -> i64 {\r\n let mut ans = 0;\r\n if a >= m {\r\n ans += (n - 1) * n * (a / m) / 2;\r\n a %= m;\r\n }\r\n if b >= m {\r\n ans += n * (b / m);\r\n b %= m;\r\n }\r\n\r\n let y_max = (a * n + b) / m;\r\n let x_max = y_max * m - b;\r\n if y_max == 0 {\r\n return ans;\r\n }\r\n ans += (n - (x_max + a - 1) / a) * y_max;\r\n ans += floor_sum(y_max, a, m, (a - x_max % a) % a);\r\n ans\r\n}\r\nfn crt(r: &Vec, m: &Vec) -> (i64, i64) {\r\n assert_eq!(r.len(), m.len());\r\n let (mut r0, mut m0) = (0, 1);\r\n for (&(mut ri), &(mut mi)) in r.iter().zip(m.iter()) {\r\n assert!(1 <= mi);\r\n ri = safe_mod(ri, mi);\r\n if m0 < mi {\r\n mem::swap(&mut r0, &mut ri);\r\n mem::swap(&mut m0, &mut mi);\r\n }\r\n if m0 % mi == 0 {\r\n if r0 % mi != ri {\r\n return (0, 0);\r\n }\r\n continue;\r\n }\r\n \r\n let (g, im) = inv_gcd(m0, mi);\r\n let u1 = mi / g;\r\n if (ri - r0) % g != 0 {\r\n return (0, 0);\r\n }\r\n let x = (ri - r0) / g % u1 * im % u1;\r\n \r\n r0 += x * m0;\r\n m0 *= u1; // -> lcm(m0, mi)\r\n if r0 < 0 {\r\n r0 += m0\r\n };\r\n }\r\n \r\n (r0, m0)\r\n}\r\n//\u7573\u307f\u8fbc\u307f\u8a08\u7b97\r\n\r\n\r\nfn mul_mod(a: u32, b: u32, m: u32, im: u64) -> u32 {\r\n let mut z = a as u64;\r\n z *= b as u64;\r\n let x = (((z as u128) * (im as u128)) >> 64) as u64;\r\n let mut v = z.wrapping_sub(x.wrapping_mul(m as u64)) as u32;\r\n if m <= v {\r\n v = v.wrapping_add(m);\r\n }\r\n v\r\n}\r\n\r\n\r\nfn inv_gcd2(a: i64, b: i64) -> (i64, i64) {\r\n let a = safe_mod(a, b);\r\n if a == 0 {\r\n return (b, 0);\r\n }\r\n\r\n let mut s = b;\r\n let mut t = a;\r\n let mut m0 = 0;\r\n let mut m1 = 1;\r\n\r\n while t != 0 {\r\n let u = s / t;\r\n s -= t * u;\r\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\r\n\r\n\r\n mem::swap(&mut s, &mut t);\r\n mem::swap(&mut m0, &mut m1);\r\n }\r\n if m0 < 0 {\r\n m0 += b / s;\r\n }\r\n (s, m0)\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nuse std::{\r\n cell::RefCell,\r\n convert::{Infallible, TryInto as _},\r\n fmt,\r\n iter::{Product, Sum},\r\n marker::PhantomData,\r\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\r\n str::FromStr,\r\n sync::atomic::{self, AtomicU32, AtomicU64},\r\n thread::LocalKey,\r\n};\r\n\r\npub type ModInt1000000007 = StaticModInt;\r\npub type ModInt998244353 = StaticModInt;\r\n\r\n#[derive(Copy, Clone, Eq, PartialEq)]\r\n#[repr(transparent)]\r\npub struct StaticModInt {\r\n val: u32,\r\n phantom: PhantomData M>,\r\n}\r\n\r\nimpl StaticModInt {\r\n #[inline(always)]\r\n pub fn modulus() -> u32 {\r\n M::VALUE\r\n }\r\n\r\n #[inline]\r\n pub fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(M::VALUE))\r\n }\r\n\r\n #[inline]\r\n pub fn raw(val: u32) -> Self {\r\n Self {\r\n val,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n #[inline]\r\n pub fn val(self) -> u32 {\r\n self.val\r\n }\r\n\r\n #[inline]\r\n pub fn pow(self, n: u64) -> Self {\r\n ::pow(self, n)\r\n }\r\n\r\n #[inline]\r\n pub fn inv(self) -> Self {\r\n if M::HINT_VALUE_IS_PRIME {\r\n if self.val() == 0 {\r\n panic!(\"attempt to divide by zero\");\r\n }\r\n self.pow((M::VALUE - 2).into())\r\n } else {\r\n Self::inv_for_non_prime_modulus(self)\r\n }\r\n }\r\n}\r\n\r\nimpl ModIntBase for StaticModInt {\r\n #[inline(always)]\r\n fn modulus() -> u32 {\r\n Self::modulus()\r\n }\r\n\r\n #[inline]\r\n fn raw(val: u32) -> Self {\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn val(self) -> u32 {\r\n self.val()\r\n }\r\n\r\n #[inline]\r\n fn inv(self) -> Self {\r\n self.inv()\r\n }\r\n}\r\n\r\npub trait Modulus: 'static + Copy + Eq {\r\n const VALUE: u32;\r\n const HINT_VALUE_IS_PRIME: bool;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>>;\r\n}\r\n\r\n#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\npub enum Mod1000000007 {}\r\n\r\nimpl Modulus for Mod1000000007 {\r\n const VALUE: u32 = 1_000_000_007;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n}\r\n\r\n#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\npub enum Mod998244353 {}\r\n\r\nimpl Modulus for Mod998244353 {\r\n const VALUE: u32 = 998_244_353;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n}\r\n\r\npub struct ButterflyCache {\r\n pub(crate) sum_e: Vec>,\r\n pub(crate) sum_ie: Vec>,\r\n}\r\n\r\n\r\n\r\n\r\npub trait ModIntBase:\r\n Default\r\n + FromStr\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + Copy\r\n + Eq\r\n + Hash\r\n + fmt::Display\r\n + fmt::Debug\r\n + Neg\r\n + Add\r\n + Sub\r\n + Mul\r\n + Div\r\n + AddAssign\r\n + SubAssign\r\n + MulAssign\r\n + DivAssign\r\n{\r\n fn modulus() -> u32;\r\n\r\n fn raw(val: u32) -> Self;\r\n\r\n fn val(self) -> u32;\r\n\r\n fn inv(self) -> Self;\r\n\r\n #[inline]\r\n fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(Self::modulus()))\r\n }\r\n\r\n #[inline]\r\n fn pow(self, mut n: u64) -> Self {\r\n let mut x = self;\r\n let mut r = Self::raw(1);\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n r *= x;\r\n }\r\n x *= x;\r\n n >>= 1;\r\n }\r\n r\r\n }\r\n}\r\n\r\npub trait RemEuclidU32 {\r\n /// Calculates `self` _mod_ `modulus` losslessly.\r\n fn rem_euclid_u32(self, modulus: u32) -> u32;\r\n}\r\n\r\nmacro_rules! impl_rem_euclid_u32_for_small_signed {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self as i64).rem_euclid(i64::from(modulus)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\nimpl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\r\n\r\nimpl RemEuclidU32 for i128 {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self.rem_euclid(i128::from(modulus)) as _\r\n }\r\n}\r\n\r\nmacro_rules! impl_rem_euclid_u32_for_small_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self as u32 % modulus\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\nmacro_rules! impl_rem_euclid_u32_for_large_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self % (modulus as $ty)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\nimpl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\r\nimpl_rem_euclid_u32_for_large_unsigned!(u64, u128);\r\n\r\n#[cfg(target_pointer_width = \"32\")]\r\nimpl_rem_euclid_u32_for_small_unsigned!(usize);\r\n\r\n#[cfg(target_pointer_width = \"64\")]\r\nimpl_rem_euclid_u32_for_large_unsigned!(usize);\r\n\r\ntrait InternalImplementations: ModIntBase {\r\n #[inline]\r\n fn inv_for_non_prime_modulus(this: Self) -> Self {\r\n let (gcd, x) = inv_gcd2(this.val().into(), Self::modulus().into());\r\n if gcd != 1 {\r\n panic!(\"the multiplicative inverse does not exist\");\r\n }\r\n Self::new(x)\r\n }\r\n\r\n #[inline]\r\n fn default_impl() -> Self {\r\n Self::raw(0)\r\n }\r\n\r\n #[inline]\r\n fn from_str_impl(s: &str) -> Result {\r\n Ok(s.parse::()\r\n .map(Self::new)\r\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\r\n }\r\n\r\n #[inline]\r\n fn hash_impl(this: &Self, state: &mut impl Hasher) {\r\n this.val().hash(state)\r\n }\r\n\r\n #[inline]\r\n fn display_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Display::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn debug_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Debug::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn neg_impl(this: Self) -> Self {\r\n Self::sub_impl(Self::raw(0), this)\r\n }\r\n\r\n #[inline]\r\n fn add_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val() + rhs.val();\r\n if val >= modulus {\r\n val -= modulus;\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn sub_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val().wrapping_sub(rhs.val());\r\n if val >= modulus {\r\n val = val.wrapping_add(modulus)\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self;\r\n\r\n #[inline]\r\n fn div_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::mul_impl(lhs, rhs.inv())\r\n }\r\n}\r\n\r\nimpl InternalImplementations for StaticModInt {\r\n #[inline]\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::raw((u64::from(lhs.val()) * u64::from(rhs.val()) % u64::from(M::VALUE)) as u32)\r\n }\r\n}\r\n\r\n\r\nmacro_rules! impl_basic_traits {\r\n () => {};\r\n (impl <$generic_param:ident : $generic_param_bound:tt> _ for $self:ty; $($rest:tt)*) => {\r\n impl <$generic_param: $generic_param_bound> Default for $self {\r\n #[inline]\r\n fn default() -> Self {\r\n Self::default_impl()\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> FromStr for $self {\r\n type Err = Infallible;\r\n\r\n #[inline]\r\n fn from_str(s: &str) -> Result {\r\n Self::from_str_impl(s)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound, V: RemEuclidU32> From for $self {\r\n #[inline]\r\n fn from(from: V) -> Self {\r\n Self::new(from)\r\n }\r\n }\r\n\r\n #[allow(clippy::derive_hash_xor_eq)]\r\n impl<$generic_param: $generic_param_bound> Hash for $self {\r\n #[inline]\r\n fn hash(&self, state: &mut H) {\r\n Self::hash_impl(self, state)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Display for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::display_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Debug for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::debug_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n Self::neg_impl(self)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for &'_ $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n <$self>::neg_impl(*self)\r\n }\r\n }\r\n\r\n impl_basic_traits!($($rest)*);\r\n };\r\n}\r\n\r\nimpl_basic_traits! {\r\n impl _ for StaticModInt ;\r\n}\r\n\r\nmacro_rules! impl_bin_ops {\r\n () => {};\r\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~ <$rhs_ty:ty> -> $output:ty { { $lhs_body:expr } ~ { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$($generic_param: $generic_param_bound),*> Add<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn add(self, rhs: $rhs_ty) -> $output {\r\n <$output>::add_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Sub<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn sub(self, rhs: $rhs_ty) -> $output {\r\n <$output>::sub_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Mul<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn mul(self, rhs: $rhs_ty) -> $output {\r\n <$output>::mul_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Div<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn div(self, rhs: $rhs_ty) -> $output {\r\n <$output>::div_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl_bin_ops!($($rest)*);\r\n };\r\n}\r\n\r\nmacro_rules! impl_assign_ops {\r\n () => {};\r\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~= <$rhs_ty:ty> { _ ~= { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$($generic_param: $generic_param_bound),*> AddAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn add_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self + apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> SubAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn sub_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self - apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> MulAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn mul_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self * apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> DivAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn div_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self / apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl_assign_ops!($($rest)*);\r\n };\r\n}\r\n\r\n#[inline]\r\nfn apply O, X, O>(f: F, x: X) -> O {\r\n f(x)\r\n}\r\n\r\nimpl_bin_ops! {\r\n for > ~ > -> StaticModInt { { |x| x } ~ { |x| x } }\r\n for > ~ <&'_ StaticModInt > -> StaticModInt { { |x| x } ~ { |&x| x } }\r\n for <&'_ StaticModInt > ~ > -> StaticModInt { { |&x| x } ~ { |x| x } }\r\n for <&'_ StaticModInt > ~ <&'_ StaticModInt > -> StaticModInt { { |&x| x } ~ { |&x| x } }\r\n\r\n for > ~ -> StaticModInt { { |x| x } ~ { StaticModInt::::new } }\r\n}\r\n\r\nimpl_assign_ops! {\r\n for > ~= > { _ ~= { |x| x } }\r\n for > ~= <&'_ StaticModInt > { _ ~= { |&x| x } }\r\n\r\n for > ~= { _ ~= { StaticModInt::::new } }\r\n}\r\n\r\nmacro_rules! impl_folding {\r\n () => {};\r\n (impl<$generic_param:ident : $generic_param_bound:tt> $trait:ident<_> for $self:ty { fn $method:ident(_) -> _ { _($unit:expr, $op:expr) } } $($rest:tt)*) => {\r\n impl<$generic_param: $generic_param_bound> $trait for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl<'a, $generic_param: $generic_param_bound> $trait<&'a Self> for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl_folding!($($rest)*);\r\n };\r\n}\r\n\r\nimpl_folding! {\r\n impl Sum<_> for StaticModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\r\n impl Product<_> for StaticModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\r\n}\r\n\r\n\r\n\r\n\r\n//convolution.ts\r\n//\r\n\r\n\r\nfn primitive_root(m: i32) -> i32 {\r\n match m {\r\n 2 => return 1,\r\n 167_772_161 => return 3,\r\n 469_762_049 => return 3,\r\n 754_974_721 => return 11,\r\n 998_244_353 => return 3,\r\n _ => {}\r\n }\r\n\r\n let mut divs = [0; 20];\r\n divs[0] = 2;\r\n let mut cnt = 1;\r\n let mut x = (m - 1) / 2;\r\n while x % 2 == 0 {\r\n x /= 2;\r\n }\r\n for i in (3..std::i32::MAX).step_by(2) {\r\n if i as i64 * i as i64 > x as i64 {\r\n break;\r\n }\r\n if x % i == 0 {\r\n divs[cnt] = i;\r\n cnt += 1;\r\n while x % i == 0 {\r\n x /= i;\r\n }\r\n }\r\n }\r\n if x > 1 {\r\n divs[cnt] = x;\r\n cnt += 1;\r\n }\r\n let mut g = 2;\r\n loop {\r\n if (0..cnt).all(|i| modpow2(g, ((m - 1) / divs[i]) as i64, m) != 1) {\r\n break g as i32;\r\n }\r\n g += 1;\r\n }\r\n}\r\n\r\n\r\n\r\nfn ceil_pow2(n: u32) -> u32 {\r\n 32 - n.saturating_sub(1).leading_zeros()\r\n}\r\n\r\n\r\nmacro_rules! modulus {\r\n ($($name:ident),*) => {\r\n $(\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n enum $name {}\r\n\r\n impl Modulus for $name {\r\n const VALUE: u32 = $name as _;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static ::std::thread::LocalKey<::std::cell::RefCell<::std::option::Option>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: ::std::cell::RefCell<::std::option::Option>> = ::std::default::Default::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n }\r\n )*\r\n };\r\n}\r\n\r\n#[allow(clippy::many_single_char_names)]\r\npub fn convolution(a: &[StaticModInt], b: &[StaticModInt]) -> Vec>\r\nwhere\r\n M: Modulus,\r\n{\r\n if a.is_empty() || b.is_empty() {\r\n return vec![];\r\n }\r\n let (n, m) = (a.len(), b.len());\r\n\r\n if cmp::min(n, m) <= 60 {\r\n let (n, m, a, b) = if n < m { (m, n, b, a) } else { (n, m, a, b) };\r\n let mut ans = vec![StaticModInt::new(0); n + m - 1];\r\n for i in 0..n {\r\n for j in 0..m {\r\n ans[i + j] += a[i] * b[j];\r\n }\r\n }\r\n return ans;\r\n }\r\n\r\n let (mut a, mut b) = (a.to_owned(), b.to_owned());\r\n let z = 1 << ceil_pow2((n + m - 1) as _);\r\n a.resize(z, StaticModInt::raw(0));\r\n butterfly(&mut a);\r\n b.resize(z, StaticModInt::raw(0));\r\n butterfly(&mut b);\r\n for (a, b) in a.iter_mut().zip(&b) {\r\n *a *= b;\r\n }\r\n butterfly_inv(&mut a);\r\n a.resize(n + m - 1, StaticModInt::raw(0));\r\n let iz = StaticModInt::new(z).inv();\r\n for a in &mut a {\r\n *a *= iz;\r\n }\r\n a\r\n}\r\n\r\npub fn convolution_raw(a: &[T], b: &[T]) -> Vec\r\nwhere\r\n T: RemEuclidU32 + TryFrom + Clone,\r\n T::Error: fmt::Debug,\r\n M: Modulus,\r\n{\r\n let a = a.iter().cloned().map(Into::into).collect::>();\r\n let b = b.iter().cloned().map(Into::into).collect::>();\r\n convolution::(&a, &b)\r\n .into_iter()\r\n .map(|z| {\r\n z.val()\r\n .try_into()\r\n .expect(\"the numeric type is smaller than the modulus\")\r\n })\r\n .collect()\r\n}\r\n\r\n\r\n#[allow(clippy::many_single_char_names)]\r\nfn butterfly(a: &mut [StaticModInt]) {\r\n let n = a.len();\r\n let h = ceil_pow2(n as u32);\r\n\r\n M::butterfly_cache().with(|cache| {\r\n let mut cache = cache.borrow_mut();\r\n let ButterflyCache { sum_e, .. } = cache.get_or_insert_with(prepare);\r\n for ph in 1..=h {\r\n let w = 1 << (ph - 1);\r\n let p = 1 << (h - ph);\r\n let mut now = StaticModInt::::new(1);\r\n for s in 0..w {\r\n let offset = s << (h - ph + 1);\r\n for i in 0..p {\r\n let l = a[i + offset];\r\n let r = a[i + offset + p] * now;\r\n a[i + offset] = l + r;\r\n a[i + offset + p] = l - r;\r\n }\r\n now *= sum_e[(!s).trailing_zeros() as usize];\r\n }\r\n }\r\n });\r\n}\r\n\r\n#[allow(clippy::many_single_char_names)]\r\nfn butterfly_inv(a: &mut [StaticModInt]) {\r\n let n = a.len();\r\n let h = ceil_pow2(n as u32);\r\n\r\n M::butterfly_cache().with(|cache| {\r\n let mut cache = cache.borrow_mut();\r\n let ButterflyCache { sum_ie, .. } = cache.get_or_insert_with(prepare);\r\n for ph in (1..=h).rev() {\r\n let w = 1 << (ph - 1);\r\n let p = 1 << (h - ph);\r\n let mut inow = StaticModInt::::new(1);\r\n for s in 0..w {\r\n let offset = s << (h - ph + 1);\r\n for i in 0..p {\r\n let l = a[i + offset];\r\n let r = a[i + offset + p];\r\n a[i + offset] = l + r;\r\n a[i + offset + p] = StaticModInt::new(M::VALUE + l.val() - r.val()) * inow;\r\n }\r\n inow *= sum_ie[(!s).trailing_zeros() as usize];\r\n }\r\n }\r\n });\r\n}\r\n\r\nfn prepare() -> ButterflyCache {\r\n let g = StaticModInt::::raw(primitive_root(M::VALUE as i32) as u32);\r\n let mut es = [StaticModInt::::raw(0); 30]; // es[i]^(2^(2+i)) == 1\r\n let mut ies = [StaticModInt::::raw(0); 30];\r\n let cnt2 = (M::VALUE - 1).trailing_zeros() as usize;\r\n let mut e = g.pow(((M::VALUE - 1) >> cnt2).into());\r\n let mut ie = e.inv();\r\n for i in (2..=cnt2).rev() {\r\n es[i - 2] = e;\r\n ies[i - 2] = ie;\r\n e *= e;\r\n ie *= ie;\r\n }\r\n let sum_e = es\r\n .iter()\r\n .scan(StaticModInt::new(1), |acc, e| {\r\n *acc *= e;\r\n Some(*acc)\r\n })\r\n .collect();\r\n let sum_ie = ies\r\n .iter()\r\n .scan(StaticModInt::new(1), |acc, ie| {\r\n *acc *= ie;\r\n Some(*acc)\r\n })\r\n .collect();\r\n ButterflyCache { sum_e, sum_ie }\r\n}\r\n\r\n\r\n\r\n\r\nuse std::{\r\n convert::{TryFrom, TryInto as _},\r\n};\r\n\r\n\r\n\r\n#[allow(clippy::many_single_char_names)]\r\npub fn convolution_i64(a: &[i64], b: &[i64]) -> Vec {\r\n const M1: u64 = 754_974_721; // 2^24\r\n const M2: u64 = 167_772_161; // 2^25\r\n const M3: u64 = 469_762_049; // 2^26\r\n const M2M3: u64 = M2 * M3;\r\n const M1M3: u64 = M1 * M3;\r\n const M1M2: u64 = M1 * M2;\r\n const M1M2M3: u64 = M1M2.wrapping_mul(M3);\r\n\r\n modulus!(M1, M2, M3);\r\n\r\n if a.is_empty() || b.is_empty() {\r\n return vec![];\r\n }\r\n\r\n let (_, i1) = inv_gcd(M2M3 as _, M1 as _);\r\n let (_, i2) = inv_gcd(M1M3 as _, M2 as _);\r\n let (_, i3) = inv_gcd(M1M2 as _, M3 as _);\r\n\r\n let c1 = convolution_raw::(a, b);\r\n let c2 = convolution_raw::(a, b);\r\n let c3 = convolution_raw::(a, b);\r\n\r\n c1.into_iter()\r\n .zip(c2)\r\n .zip(c3)\r\n .map(|((c1, c2), c3)| {\r\n const OFFSET: &[u64] = &[0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3];\r\n\r\n let mut x = [(c1, i1, M1, M2M3), (c2, i2, M2, M1M3), (c3, i3, M3, M1M2)]\r\n .iter()\r\n .map(|&(c, i, m1, m2)| c.wrapping_mul(i).rem_euclid(m1 as _).wrapping_mul(m2 as _))\r\n .fold(0, i64::wrapping_add);\r\n\r\n let mut diff = c1 - safe_mod(x, M1 as _);\r\n if diff < 0 {\r\n diff += M1 as i64;\r\n }\r\n x = x.wrapping_sub(OFFSET[diff.rem_euclid(5) as usize] as _);\r\n x\r\n })\r\n .collect()\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n//suffix array\r\nstruct suffix_array{\r\n n:usize,\r\n S:Vec,\r\n k:usize,\r\n sa:Vec,\r\n rank:Vec,\r\n tmp:Vec,\r\n lcp:Vec,\r\n}\r\n\r\n\r\nimpl suffix_array{\r\n fn compare_sa(&mut self, i:&i64, j:&i64)-> std::cmp::Ordering{\r\n match self.rank[*i as usize].cmp(&(self.rank[*j as usize])){\r\n std::cmp::Ordering::Less => std::cmp::Ordering::Less,\r\n std::cmp::Ordering::Greater => std::cmp::Ordering::Greater,\r\n std::cmp::Ordering::Equal => {\r\n let mut ri = {if (*i as usize+self.k)<=self.n{self.rank[*i as usize+self.k]}else{-1}};\r\n let mut rj = {if (*j as usize+self.k)<=self.n{self.rank[*j as usize+self.k]}else{-1}};\r\n match ri.cmp(&rj){\r\n std::cmp::Ordering::Less => std::cmp::Ordering::Less,\r\n std::cmp::Ordering::Greater => std::cmp::Ordering::Greater,\r\n std::cmp::Ordering::Equal => std::cmp::Ordering::Greater,\r\n }\r\n \r\n }\r\n }\r\n }\r\n\r\n\r\n fn new(S:&Vec)->suffix_array{\r\n let mut n = S.len();\r\n let mut s = vec![];\r\n for i in 0..n{\r\n s.push(S[i] as i64);\r\n }\r\n let mut sa = vec![];\r\n let mut rank = vec![0;n+1];\r\n let mut tmp = vec![0;n+1];\r\n let mut lcp = vec![];\r\n return suffix_array{lcp:lcp, n:n, S:s, sa:sa, rank:rank, tmp:tmp, k:0};\r\n }\r\n fn build(&mut self){\r\n let mut sa = vec![0;self.n+1];\r\n for i in 0..self.n+1{\r\n sa[i] = i as i64;\r\n self.rank[i] = {if iself.n{\r\n break;\r\n }\r\n sa.sort_by(|a, b| self.compare_sa(a, b));\r\n self.tmp[sa[0] as usize] = 0;\r\n for i in 1..self.n+1{\r\n let res = self.compare_sa(&(sa[i-1]), &(sa[i]));\r\n let mut zo = 0;\r\n if res == Ordering::Greater{\r\n zo = 0;\r\n }\r\n else{\r\n zo = 1;\r\n }\r\n self.tmp[sa[i] as usize] = self.tmp[sa[i-1] as usize] + zo;\r\n }\r\n mem::swap(&mut self.rank, &mut self.tmp);\r\n self.k*=2;\r\n }\r\n self.sa = sa;\r\n }\r\n fn contain(&self, T:&Vec)->bool{\r\n let mut a = 0;\r\n let mut b = self.S.len();\r\n let mut t = T.as_slice();\r\n while(b-a>1){\r\n let mut c= (a+b)/2;\r\n if &(self.S[ (self.sa[c] as usize)..(self.sa[c] as usize + T.len()) ]) < t{\r\n a = c;\r\n }\r\n else{\r\n b = c;\r\n }\r\n }\r\n return &(self.S[self.sa[b] as usize ..self.sa[b] as usize+T.len()]) == T.as_slice();\r\n }\r\n\r\n\r\n fn construct_lcp(&mut self){\r\n let mut n = self.S.len();\r\n for i in 0..n+1{\r\n self.rank[self.sa[i] as usize] = i as i64;\r\n }\r\n let mut h = 0;\r\n self.lcp = vec![0;n+1];\r\n self.lcp[0] = 0;\r\n for i in 0..n{\r\n let mut j = self.sa[self.rank[i] as usize -1];\r\n if h>0{\r\n h-=1;\r\n }\r\n while(true){\r\n if( (j as i64+h as i64) , size:usize)->i64{\r\n for i in 0..size{\r\n let a = pat[i];\r\n if x+i>=self.S.len(){\r\n return -1;\r\n }\r\n let b = self.S[x+i];\r\n if ab{\r\n return 1;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n fn search_pattern_sub(&self, pat:&Vec, pat_size:usize)->i64{\r\n let mut low= 0;\r\n let mut high = self.S.len()-1;\r\n while low<=high{\r\n let mut mid =(low+high)/2;\r\n let mut r = self.compare_pat(self.sa[mid] as usize, pat, pat_size);\r\n if r==0{\r\n return mid as i64;\r\n }\r\n else if r>0{\r\n low = mid+1;\r\n }\r\n else{\r\n high = mid-1;\r\n }\r\n }\r\n return -1;\r\n }\r\n fn search_pat(&self, pat:&Vec)->i64{\r\n let mut pat_size = pat.len();\r\n let mut x = self.search_pattern_sub(pat, pat_size);\r\n if x >= 0{\r\n return self.sa[x as usize];\r\n }\r\n return -1;\r\n }\r\n fn search_pattern_all(&self, pat:&Vec)->Vec{\r\n let mut pat_size = pat.len();\r\n let mut x = self.search_pattern_sub(pat, pat_size);\r\n if x<0{\r\n return vec![];\r\n }\r\n let mut s = x-1;\r\n while s>=0 && self.compare_pat(self.sa[s as usize] as usize, pat, pat_size) == 0 {\r\n s -=1;\r\n }\r\n let mut e = x+1;\r\n while (e as usize) < self.S.len() && self.compare_pat(self.sa[e as usize] as usize, pat, pat_size) ==0{\r\n e+=1;\r\n }\r\n return self.sa[s as usize+1..e as usize].to_vec();\r\n }\r\n\r\n\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n//\u7d20\u56e0\u6570\u5206\u89e3\r\nfn prime_factor(n:usize)->HashMap{\r\n let mut res = HashMap::new();\r\n let mut n = n;\r\n for i in 2..n{\r\n if i*i>n{break;}\r\n while(n%i==0){\r\n *res.entry(i).or_insert(0)+=1;\r\n n/=i;\r\n }\r\n }\r\n if n != 1{\r\n res.insert(n, 1);\r\n }\r\n res\r\n}\r\n\r\n//\u7d20\u56e0\u6570\u5206\u89e3\u3000\u30af\u30a8\u30ea\r\n//let mut spf = smallest_prime_factor(10000);\r\n//let mut f = factorization(x, &sfp);\r\nfn smallest_prime_factor(n:usize)->Vec{\r\n let mut spf = vec![0;n+1];\r\n for i in 0..n+1{\r\n spf[i] = i;\r\n }\r\n for i in 2..INFu{\r\n if i*i>n{\r\n break;\r\n }\r\n if spf[i] == i{\r\n let mut j = i*i;\r\n while(j<=n){\r\n if spf[j] == j{\r\n spf[j] = i;\r\n }\r\n j+=i;\r\n }\r\n }\r\n }\r\n\r\n return spf;\r\n}\r\nfn factorization(x:usize, spf:&Vec)->Vec{\r\n let mut res = vec![];\r\n let mut x = x;\r\n while(x != 1){\r\n res.push(spf[x]);\r\n x/=spf[x];\r\n }\r\n res.sort();\r\n return res;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nfn usize_multiply_is_overflow(a:usize, b:usize)->bool{\r\n if a (Vec, Vec){\r\n let mut p:usize = 0;\r\n let mut is_prime = vec![false; n+1];\r\n let mut prime = Vec::new();\r\n for i in 0..n+1{\r\n is_prime[i] = true;\r\n }\r\n is_prime[0] = false;\r\n is_prime[1] = false;\r\n for i in 2..n+1{\r\n if is_prime[i]{\r\n prime.push(i as usize);\r\n let mut j = 2*i;\r\n while(j<=n){\r\n is_prime[j] = false;\r\n j+=i;\r\n }\r\n }\r\n }\r\n (is_prime, prime)\r\n \r\n}\r\n\r\n\r\n\r\n\r\nfn transpose(v: Vec>) -> Vec>\r\nwhere\r\n T: Clone,\r\n{\r\n assert!(!v.is_empty());\r\n (0..v[0].len())\r\n .map(|i| v.iter().map(|inner| inner[i].clone()).collect::>())\r\n .collect()\r\n}\r\nuse std::ops::Bound::Included;\r\nuse std::iter::{once, repeat};\r\n\r\n\r\nfn solve(){\r\n let sssss = std::io::stdin();\r\n let mut sc = Scanner { stdin: sssss.lock() };\r\n //let mut test:usize = sc.read();\r\n let test = 1;\r\n for _ in 0..test{\r\n let mut n:usize = sc.read();\r\n let mut spf = smallest_prime_factor(2*1000000+10);\r\n let mut res = 1;\r\n let mut s = 1;\r\n let mut dp = vec![0;n+1];\r\n dp[1] = 1;\r\n for i in 2..n+1{\r\n let mut f = factorization(i, &spf);\r\n let mut h = HashMap::new();\r\n for j in &f{\r\n *h.entry(*j).or_insert(0)+=1;\r\n }\r\n\r\n let mut ret = 1;\r\n for (j, k) in &h{\r\n ret*= (*k + 1);\r\n\r\n }\r\n dp[i] = (ret + s)%MOD;\r\n s+=dp[i];\r\n s%=MOD;\r\n }\r\n println!(\"{}\", dp[n]);\r\n\r\n\r\n }\r\n\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n \r\nfn main(){\r\n solve();\r\n}\r\n\r\n\r\nconst PI:f64 = std::f64::consts::PI;\r\npub static MOD:i64 = 998244353;\r\npub static MODu:usize = 1000000007;\r\npub static MODi32:i32 = 998244353;\r\npub static eps:f64 = 1e-6;\r\nconst INF: i64 = 1 << 60;\r\nconst INFu:usize = 1<<30;\r\n\r\n\r\n\r\n\r\n\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "962bcd8015b1e4b2832b2aa6f47f0f44", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\n\nconst MOD: i64 = 998244353i64;\n\nfn div(n: usize) -> Vec {\n let mut ans: Vec = vec![0; n + 1];\n for i in 1..=n {\n for j in (i..=n).step_by(i) {\n ans[j] += 1;\n }\n }\n ans\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut sc = cf_scanner::Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n let n: usize = sc.next();\n let div: Vec = div(n);\n let mut dp: Vec = vec![0; n + 1];\n let mut ans: Vec = vec![0; n + 1];\n for i in 1..=n {\n ans[i] = (div[i] + dp[i - 1]) % MOD;\n dp[i] = (ans[i] + dp[i - 1]) % MOD;\n }\n writeln!(out, \"{}\", ans[n]).unwrap();\n}\n\n#[allow(dead_code)]\nmod cf_scanner {\n use std::io;\n use std::str::{FromStr, SplitAsciiWhitespace};\n\n pub struct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n }\n\n impl Scanner {\n pub fn new(reader: R) -> Scanner {\n Scanner {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn next_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n\n pub fn next_str(&mut self) -> Vec {\n self.next::().chars().collect()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "eb5d91a6bd737401007643fc8ff4760c", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use crate::lib::stdio::*;\nuse crate::lib::gf::Gf99 as Int;\n\nfn main() {\n scan!(n: usize);\n\n let mut lpf: Vec<_> = (0..=n).collect();\n for i in 2..=n {\n if lpf[i] == i {\n for j in (i..=n).step_by(i) {\n lpf[j] = lpf[j].min(i);\n }\n }\n }\n let d = |mut n: usize| {\n let mut now = 0;\n let mut cnt = 0;\n let mut ans = 1;\n while n != 1 {\n if now != lpf[n] {\n ans *= cnt + 1;\n cnt = 0;\n now = lpf[n];\n }\n cnt += 1;\n n /= now;\n }\n ans *= cnt + 1;\n ans\n };\n let mut sum = Int::one();\n let mut now = Int::zero();\n for n in 1..=n {\n now = sum + d(n) - 1;\n sum += now;\n }\n prtln!(now);\n}\n\n\npub mod lib {\n\npub mod gf {\n\n// modular arithmetics\n\nuse crate::lib::zo::ZeroOne;\nuse std::marker::PhantomData;\nuse std::{cmp, fmt, iter, ops::*, str};\n\npub trait Mod: Default + Clone + Copy {\n const P: u32;\n const K: u32; // -1 / P mod 2^32\n const R2: u32; // 2^64 mod P\n}\n\n// montgomery reduction (x -> x / 2^32 mod P)\nfn reduce(x: u64) -> u32 {\n let s = M::K.wrapping_mul(x as u32);\n ((x + s as u64 * M::P as u64) >> 32) as u32\n}\n\n#[macro_export]\nmacro_rules! def_prime {\n ($name:ident, $modu:expr, $k:expr) => {\n #[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]\n pub struct $name;\n impl Mod for $name {\n const P: u32 = $modu;\n const K: u32 = $k;\n const R2: u32 = ((1_u128 << 64) % $modu) as u32;\n }\n };\n}\n\ndef_prime!(ModA, 1_000_000_007, 2_226_617_417);\ndef_prime!(ModB, 998_244_353, 998_244_351);\ndef_prime!(ModC, 1_012_924_417, 1_012_924_415);\ndef_prime!(ModD, 924_844_033, 924_844_031);\n\n#[repr(transparent)]\n#[derive(Default, Clone, Copy)]\npub struct Gf {\n val: u32,\n _m: PhantomData<*const M>,\n}\n\npub type GfA = Gf;\npub type GfB = Gf;\npub type GfC = Gf;\npub type GfD = Gf;\npub type Gf17 = GfA;\npub type Gf99 = GfB;\n\nimpl Gf {\n pub const P: u32 = M::P;\n pub fn zero() -> Self { ZeroOne::zero() }\n pub fn one() -> Self { ZeroOne::one() }\n pub fn new(val: u32) -> Self { val.into() }\n pub fn is_zero(&self) -> bool { *self == Self::zero() }\n fn from_raw(val: u32) -> Self { Gf { val, _m: PhantomData } }\n pub fn value(self) -> u32 {\n let v = reduce::(self.val as u64);\n if v >= M::P { v - M::P } else { v }\n }\n pub fn pow(mut self, mut k: u64) -> Self {\n if self.val == 0 && k == 0 { return Self::new(1); }\n k %= (M::P - 1) as u64;\n let mut res = Self::one();\n while !k.is_zero() {\n if k % 2 != 0 { res *= self; }\n self *= self; k >>= 1;\n }\n res\n }\n pub fn inv(self) -> Self {\n let (mut a, mut b, mut u, mut v) = (M::P as i32, self.value() as i32, 0, 1);\n while b != 0 {\n let t = a / b;\n a -= t * b; u -= t * v;\n std::mem::swap(&mut a, &mut b); std::mem::swap(&mut u, &mut v);\n }\n debug_assert_eq!(a, 1);\n if u < 0 { debug_assert_eq!(v, M::P as i32); u += v; }\n Self::new(u as u32)\n }\n}\nimpl From for Gf {\n fn from(x: u32) -> Self { Gf::from_raw(reduce::(x as u64 * M::R2 as u64)) }\n}\nmacro_rules! impl_from_int {\n ($($t:ty),*) => { $(\n impl From<$t> for Gf {\n fn from(x: $t) -> Self {\n Gf::from_raw(reduce::(x.rem_euclid(M::P as _) as u64 * M::R2 as u64))\n }\n }\n )* };\n}\nimpl_from_int!(u64, usize, i32, i64, isize);\nimpl cmp::PartialEq for Gf {\n fn eq(&self, other: &Self) -> bool {\n let val = |obj: &Gf| {\n if obj.val >= M::P { obj.val - M::P } else { obj.val }\n };\n val(self) == val(other)\n }\n}\nimpl cmp::Eq for Gf {}\nimpl>> AddAssign for Gf {\n fn add_assign(&mut self, rhs: T) {\n self.val += rhs.into().val;\n if self.val >= M::P * 2 { self.val -= M::P * 2; }\n }\n}\nimpl>> SubAssign for Gf {\n fn sub_assign(&mut self, rhs: T) {\n let rhs = rhs.into();\n if self.val < rhs.val { self.val += M::P * 2; }\n self.val -= rhs.val;\n }\n}\nimpl>> MulAssign for Gf {\n fn mul_assign(&mut self, rhs: T) {\n self.val = reduce::(self.val as u64 * rhs.into().val as u64);\n }\n}\nimpl>> DivAssign for Gf {\n fn div_assign(&mut self, rhs: T) { *self *= rhs.into().inv(); }\n}\nmacro_rules! impl_binop {\n ($(($Op:ident, $op:ident, $OpAssign:ident, $op_assign:ident)),*) => { $(\n impl>> $Op for Gf {\n type Output = Self;\n fn $op(mut self, rhs: T) -> Self { self.$op_assign(rhs); self }\n }\n )* };\n}\nimpl_binop!(\n (Add, add, AddAssign, add_assign),\n (Sub, sub, SubAssign, sub_assign),\n (Mul, mul, MulAssign, mul_assign),\n (Div, div, DivAssign, div_assign)\n);\nimpl Neg for Gf {\n type Output = Self;\n fn neg(self) -> Self { Gf::from_raw(M::P * 2 - self.val) }\n}\nimpl iter::Sum for Gf {\n fn sum>(iter: I) -> Self { iter.fold(Self::zero(), |b, x| b + x) }\n}\nimpl iter::Product for Gf {\n fn product>(iter: I) -> Self { iter.fold(Self::one(), |b, x| b * x) }\n}\nimpl fmt::Debug for Gf {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value().fmt(f) }\n}\nimpl fmt::Display for Gf {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.value().fmt(f) }\n}\nimpl str::FromStr for Gf {\n type Err = ::Err;\n fn from_str(s: &str) -> Result { u32::from_str(s).map(Self::new) }\n}\nimpl ZeroOne for Gf {\n fn zero() -> Self { Self { val: 0, _m: PhantomData } }\n fn one() -> Self { Self { val: M::P.wrapping_neg() % M::P, _m: PhantomData } }\n}\n\n} // mod gf\n\npub mod stdio {\n\npub use crate::prtln;\npub use crate::scan;\npub use crate::parse;\npub use std::io::Write;\nuse std::io::{stdout, BufWriter, StdoutLock};\n\npub fn stdout_buf() -> BufWriter> {\n let out = Box::leak(Box::new(stdout()));\n BufWriter::new(out.lock())\n}\n\n#[macro_export]\nmacro_rules! prtln {\n (@ $dst:expr, iter=$v:expr) => { $crate::prtln!(@ $dst, iter=$v, sep=\" \"); };\n (@ $dst:expr, iter=$v:expr, sep=$sep:expr) => { {\n let mut iter = $v.into_iter();\n if let Some(expr) = iter.next() {\n std::write!($dst, \"{}\", expr).unwrap();\n for v in iter { std::write!($dst, \"{}{}\", $sep, v).unwrap(); }\n }\n $crate::prtln!(@ $dst, \"\");\n } };\n (@ $dst:expr, bytes=$v:expr) => {\n $crate::prtln!(@ $dst, std::str::from_utf8(&$v).unwrap());\n };\n (@ $dst:expr, YesNo=$v:expr) => { $crate::prtln!(@ $dst, if $v { \"Yes\" } else { \"No\" }); };\n (@ $dst:expr, YESNO=$v:expr) => { $crate::prtln!(@ $dst, if $v { \"YES\" } else { \"NO\" }); };\n (@ $dst:expr, $v:expr, no eol) => { std::write!($dst, \"{}\", $v).unwrap(); };\n (@ $dst:expr, $v:expr) => { std::writeln!($dst, \"{}\", $v).unwrap(); };\n (@ $dst:expr, $v:expr, $($t:tt)*) => { {\n std::write!($dst, \"{} \", $v).unwrap();\n $crate::prtln!(@ $dst, $($t)*);\n } };\n (new $var:ident $(,)?) => { let mut $var = stdout_buf(); };\n (new $var:ident, $($t:tt)*) => {\n $crate::prtln!(new $var);\n $crate::prtln!(to $var, $($t)*);\n };\n (to $var:ident, $($t:tt)*) => { {\n $crate::prtln!(@ $var, $($t)*);\n } };\n ($($t:tt)*) => { {\n $crate::prtln!(new __prtln, $($t)*);\n std::mem::drop(__prtln);\n } };\n}\n\n#[macro_export]\nmacro_rules! scan {\n (@ $iter:expr $(,)?) => {};\n (@ $iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n #[allow(non_snake_case)]\n let mut $var = $crate::parse!($iter.into_iter(), $t);\n $crate::scan!(@ $iter $($r)*)\n };\n (@ $iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n #[allow(non_snake_case)]\n let $var = $crate::parse!($iter.into_iter(), $t);\n $crate::scan!(@ $iter $($r)*)\n };\n (@ $iter:expr, $pat:pat in $t:tt $($r:tt)*) => {\n let $pat = $crate::parse!($iter.into_iter(), $t);\n $crate::scan!(@ $iter $($r)*)\n };\n (from $s:expr, $($r:tt)*) => { $crate::scan!(@ $s, $($r)*); };\n (new $var:ident, $($r:tt)*) => {\n let mut __input = String::new();\n std::io::Read::read_to_string(&mut std::io::stdin(), &mut __input).unwrap();\n let $var = &mut __input.split_ascii_whitespace();\n $crate::scan!(@ $var, $($r)*);\n };\n ($($r:tt)*) => { $crate::scan!(new __scan, $($r)*); };\n}\n\n#[macro_export]\nmacro_rules! parse {\n ($iter:expr, ( $($t:tt),* )) => { ( $($crate::parse!($iter, $t)),* ) };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| $crate::parse!($iter, $t)).collect::>()\n };\n ($iter:expr, bytes) => { $iter.next().expect(\"no input\").as_bytes() };\n ($iter:expr, [u8]) => { $iter.next().expect(\"no input\").as_bytes().to_vec() };\n ($iter:expr, [char]) => { $iter.next().expect(\"no input\").chars().collect::>() };\n ($iter:expr, usize1) => { $crate::parse!($iter, usize) - 1 };\n (@graph $iter:expr, $n:expr, $m:expr) => { {\n let mut graph = vec![Vec::new(); $n];\n for _ in 0..$m {\n let (a, b) = $crate::parse!($iter, (usize1, usize1));\n graph[a].push(b);\n graph[b].push(a);\n }\n ($n, graph)\n } };\n ($iter:expr, graph) => { {\n let (n, m) = $crate::parse!($iter, (usize, usize));\n $crate::parse!(@graph $iter, n, m)\n } };\n ($iter:expr, tree) => { {\n let n = $crate::parse!($iter, usize);\n $crate::parse!(@graph $iter, n, n - 1)\n } };\n ($iter:expr, $t:ty) => { $iter.next().expect(\"no input\").parse::<$t>().expect(\"parse error\") };\n ($iter:expr) => { $iter.next().expect(\"no input\").parse().expect(\"parse error\") };\n}\n\n} // mod stdio\n\npub mod zo {\n\npub trait ZeroOne: Copy + PartialEq {\n fn zero() -> Self;\n fn one() -> Self;\n fn is_zero(self) -> bool { self == Self::zero() }\n}\n\nmacro_rules! impl_zo {\n ($($t:ty),*) => { $(\n impl ZeroOne for $t {\n fn zero() -> Self { 0 as $t }\n fn one() -> Self { 1 as $t }\n }\n )* };\n}\n\nimpl_zo!(i32, i64, i128, isize, u32, u64, u128, usize, f32, f64);\n\n} // mod zo\n\n} // mod lib\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "def0a982269431af268d80d1935eed96", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Write;\n\n// ---------- begin scannner ----------\n#[allow(dead_code)]\nmod scanner {\n use std::str::FromStr;\n pub struct Scanner<'a> {\n it: std::str::SplitWhitespace<'a>,\n }\n impl<'a> Scanner<'a> {\n pub fn new(s: &'a String) -> Scanner<'a> {\n Scanner {\n it: s.split_whitespace(),\n }\n }\n pub fn next(&mut self) -> T {\n self.it.next().unwrap().parse::().ok().unwrap()\n }\n pub fn next_bytes(&mut self) -> Vec {\n self.it.next().unwrap().bytes().collect()\n }\n pub fn next_chars(&mut self) -> Vec {\n self.it.next().unwrap().chars().collect()\n }\n pub fn next_vec(&mut self, len: usize) -> Vec {\n (0..len).map(|_| self.next()).collect()\n }\n }\n}\n// ---------- end scannner ----------\n\nfn main() {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut sc = scanner::Scanner::new(&s);\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n run(&mut sc, &mut out);\n}\n\nconst MOD:i32 = 998244353;\n\nfn solve(n: usize) -> i32 {\n let mut ans = vec![0i32; n + 1];\n let mut sum = 0i32;\n let mut presum = 0i32;\n for i in 1..n+1 {\n let mut j = i;\n while j <= n {\n ans[j] += 1;\n j+=i;\n }\n // println!(\"ans[{}]: {}, sum: {}, presum: {}\", i, ans[i], sum, presum);\n if ans[i] + presum > MOD {\n sum = ans[i] + presum - MOD;\n presum += ans[i] + presum - MOD;\n } else {\n sum = ans[i] + presum;\n presum += ans[i] + presum;\n }\n if presum > MOD {\n presum -= MOD\n }\n }\n return sum\n}\n\nfn run(sc: &mut scanner::Scanner, out: &mut std::io::BufWriter) {\n let n: usize = sc.next();\n writeln!(out, \"{}\", solve(n));\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "6f8d7450b52b1e517b087abebfd1b3ab", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{prelude::*, stdin, stdout, BufReader, BufWriter};\r\n\r\nfn main() {\r\n let std_in = stdin();\r\n let in_lock = std_in.lock();\r\n let input = BufReader::new(in_lock);\r\n\r\n let std_out = stdout();\r\n let out_lock = std_out.lock();\r\n let mut output = BufWriter::new(out_lock);\r\n\r\n let mut lines = input.lines().map(|r| r.unwrap());\r\n\r\n let n = lines.next().unwrap().parse::().unwrap();\r\n\r\n let mut c: Vec<_> = (0..=n).collect();\r\n for p in (2..).take_while(|&p| p * p <= n) {\r\n if c[p] != p {\r\n continue;\r\n }\r\n\r\n for i in (1..).take_while(|&i| p * i <= n) {\r\n c[p * i] = p;\r\n }\r\n }\r\n\r\n let ndivisors = |mut n: usize| -> u64 {\r\n let mut r = 1;\r\n while n > 1 {\r\n let p: usize = c[n];\r\n let mut q = 0;\r\n while n > 1 && c[n] == p {\r\n n /= p;\r\n q += 1;\r\n }\r\n\r\n r *= q + 1;\r\n }\r\n\r\n r\r\n };\r\n\r\n let mut t0 = 0;\r\n let mut t1 = 1;\r\n\r\n const P: u64 = 998244353;\r\n\r\n for i in 2..=n {\r\n t0 = t1;\r\n t1 = (2 * t1 + ndivisors(i)) % P;\r\n }\r\n\r\n let ans = if t0 <= t1 { t1 - t0 } else { (t1 + P) - t0};\r\n\r\n writeln!(&mut output, \"{}\", ans).unwrap();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "14a2fd549aac6b91872c4a8836b0f05b", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\r\nuse std::io::Write;\r\n\r\n/**************************************************\r\n\r\n START OF TEMPLATE CODE\r\n\r\n *************************************************/\r\n#[allow(unused_macros)]\r\nmacro_rules! dbg {\r\n ($first_val:expr, $($val:expr),+ $(,)?) => {\r\n eprint!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n ($(eprint!(\", {} = {:?}\", stringify!($val), &$val)),+,);\r\n eprintln!();\r\n };\r\n ($first_val:expr) => {\r\n eprintln!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n };\r\n}\r\n\r\nenum InputSource {\r\n Stdin,\r\n FromFile(Vec),\r\n}\r\n\r\nstruct Scanner {\r\n buffer: Vec,\r\n input_source: InputSource,\r\n}\r\n\r\n\r\nimpl Scanner {\r\n #[allow(dead_code)]\r\n fn new() -> Self {\r\n Self { buffer: vec![], input_source: InputSource::Stdin }\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn new_file(filename: &str) -> Self {\r\n let file = std::fs::read_to_string(filename).unwrap();\r\n let mut lines: Vec = file.lines().map(|line| String::from(line)).collect();\r\n lines.reverse();\r\n Self { buffer: vec![], input_source: InputSource::FromFile(lines) }\r\n }\r\n\r\n\r\n #[allow(dead_code)]\r\n fn i64(&mut self) -> i64 {\r\n self.next::()\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn i32(&mut self) -> i32 {\r\n self.next::()\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn usize(&mut self) -> usize {\r\n self.next::()\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.next::()).collect()\r\n }\r\n\r\n fn parse_next_line(&mut self) -> bool {\r\n let mut input = String::new();\r\n match &mut self.input_source {\r\n | InputSource::Stdin => {\r\n if std::io::stdin().read_line(&mut input).expect(\"Failed read\") == 0 {\r\n return false;\r\n }\r\n }\r\n | InputSource::FromFile(lines) => {\r\n match lines.pop() {\r\n Some(line) => input = line,\r\n None => return false,\r\n }\r\n }\r\n }\r\n\r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n return true;\r\n }\r\n\r\n fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n\r\n self.parse_next_line();\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn has_more_elements(&mut self) -> bool {\r\n loop {\r\n if !self.buffer.is_empty() {\r\n return true;\r\n }\r\n if !self.parse_next_line() {\r\n return false;\r\n }\r\n }\r\n }\r\n\r\n\r\n #[allow(dead_code)]\r\n fn string(&mut self) -> Vec {\r\n self.next::().into_bytes()\r\n }\r\n}\r\n\r\nmod modulo {\r\n const MODULO: i32 = 998244353;\r\n\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n pub struct Mod(i32);\r\n\r\n impl Mod {\r\n #[allow(unused)]\r\n pub const ZERO: Self = Self(0);\r\n\r\n #[allow(unused)]\r\n pub const ONE: Self = Self(1);\r\n\r\n fn rev_rec(a: i32, m: i32) -> i32 {\r\n if a == 1 {\r\n return a;\r\n }\r\n return ((1 - Self::rev_rec(m % a, a) as i64 * m as i64) / a as i64 + m as i64) as i32;\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn inv(self) -> Mod {\r\n Mod(Self::rev_rec(self.0, MODULO))\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub fn new(mut x: i32) -> Self {\r\n if x < 0 {\r\n x += MODULO;\r\n } else if x >= MODULO {\r\n x -= MODULO;\r\n }\r\n assert!(0 <= x && x < MODULO);\r\n Self(x)\r\n }\r\n }\r\n\r\n impl std::fmt::Display for Mod {\r\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for Mod {\r\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\r\n const MAX: usize = 100;\r\n if self.0 <= MAX as i32 {\r\n write!(f, \"{}\", self.0)\r\n } else if self.0 >= MODULO - MAX as i32 {\r\n write!(f, \"-{}\", MODULO - self.0)\r\n } else {\r\n for denum in 1..MAX {\r\n for num in 1..MAX {\r\n if Mod(num as i32) / Mod(denum as i32) == *self {\r\n return write!(f, \"{}/{}\", num, denum);\r\n }\r\n }\r\n }\r\n write!(f, \"(?? {} ??)\", self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::ops::Add for Mod {\r\n type Output = Mod;\r\n\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let res = self.0 + rhs.0;\r\n if res >= MODULO {\r\n Mod(res - MODULO)\r\n } else {\r\n Mod(res)\r\n }\r\n }\r\n }\r\n\r\n impl std::ops::AddAssign for Mod {\r\n fn add_assign(&mut self, rhs: Self) {\r\n self.0 += rhs.0;\r\n if self.0 >= MODULO {\r\n self.0 -= MODULO;\r\n }\r\n }\r\n }\r\n\r\n impl std::ops::Sub for Mod {\r\n type Output = Mod;\r\n\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let res = self.0 - rhs.0;\r\n if res < 0 {\r\n Mod(res + MODULO)\r\n } else {\r\n Mod(res)\r\n }\r\n }\r\n }\r\n\r\n impl std::ops::SubAssign for Mod {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n self.0 -= rhs.0;\r\n if self.0 < 0 {\r\n self.0 += MODULO;\r\n }\r\n }\r\n }\r\n\r\n impl std::ops::Mul for Mod {\r\n type Output = Mod;\r\n\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n let res = (self.0 as i64) * (rhs.0 as i64) % (MODULO as i64);\r\n Mod(res as i32)\r\n }\r\n }\r\n\r\n impl std::ops::MulAssign for Mod {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n self.0 = ((self.0 as i64) * (rhs.0 as i64) % (MODULO as i64)) as i32;\r\n }\r\n }\r\n\r\n impl std::ops::Div for Mod {\r\n type Output = Mod;\r\n\r\n fn div(self, rhs: Self) -> Self::Output {\r\n let rhs_inv = rhs.inv();\r\n self * rhs_inv\r\n }\r\n }\r\n\r\n impl std::ops::DivAssign for Mod {\r\n fn div_assign(&mut self, rhs: Self) {\r\n *self *= rhs.inv();\r\n }\r\n }\r\n}\r\n\r\nuse modulo::*;\r\n\r\n/**************************************************\r\n\r\n END OF TEMPLATE CODE\r\n\r\n *************************************************/\r\n\r\n\r\npub fn main() {\r\n let stdout = io::stdout();\r\n let mut out = std::io::BufWriter::new(stdout.lock());\r\n let mut sc = Scanner::new();\r\n\r\n let n = sc.usize();\r\n let mut res = vec![Mod::ZERO; n + 1];\r\n for delta in 1..=n {\r\n for sum in (delta..=n).step_by(delta) {\r\n res[sum] += Mod::ONE;\r\n }\r\n }\r\n let mut sum = Mod::ZERO;\r\n for i in 0..=n {\r\n res[i] += sum;\r\n sum += res[i];\r\n }\r\n writeln!(out, \"{}\", res[n]).unwrap();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "927e8d5deb07d024656ea8454f87a346", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\n#[allow(unused_imports)]use std::{io::*,collections::*,fmt::Debug,str::{self,*},cmp::*,ops::{self,*},iter::{self,*}};\nmacro_rules!l{\n\t($($v:ident),+:$t:ty=$e:expr)=>{$(let$v:$t=$e;)+};(mut $($v:ident),+ =$e:expr)=>{$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr)=>{$(let mut$v:$t=$e;)+};($($v:ident),+ =$e:expr)=>{$(let$v=$e;)+};}\nmacro_rules!v{([$d:expr]$($s:tt)+)=>{vec![v!($($s)+);$d]};([])=>{Vec::new()};([$e:expr])=>{Vec::with_capacity($e)};(=$e:expr)=>{$e};}\nfn rio()->(Reader,BufWriter){(Reader::new(),BufWriter::new(stdout()))}\nstruct Reader{buf:Vec,pos:usize,q:StdinLock<'static>}/*'>}*/#[allow(dead_code)]impl Reader{\n\tfn new()->Self{let r=unsafe{&*Box::into_raw(Box::new(stdin()))};Self{q:r.lock(),buf:v!([]),pos:0}}\n\tfn next_line(&mut self)->bool{self.buf.clear();self.pos=0;self.q.read_until(b'\\n',&mut self.buf).unwrap_or(0)>0}\n\tfn byte(&mut self)->Option{\n\t\tif self.pos==self.buf.len(){if!self.next_line(){return None;}}self.pos+=1;Some(self.buf[self.pos-1])}\n\tfn vb(&mut self)->Vec{let mut s=v!([10]);let mut f=false;while let Some(c)=self.byte(){\n\t\tif!c.is_ascii_whitespace(){s.push(c);f=true;}else if f{break;}}s}\n\tfn p(&mut self)->T where T::Err:Debug{let w=self.vb();str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()}\n\tfn u(&mut self) -> usize { self.p() }\n}\n//----------}}}\n\n// Field (mod prime) {{{\nmod field {\n\tuse std::ops::*;\n\t#[allow(dead_code)] pub const Z0: Field = Field(0);\n\t#[allow(dead_code)] pub const Z1: Field = Field(1);\n\tconst P5: i32 = 998_244_353;\n\tconst P6: i64 = P5 as i64;\n\t#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(i32);\n\t#[allow(dead_code)] impl Field {\n\t\tpub fn new>(a: T) -> Self { Self(Self::cv(a)) }\n\t\tpub unsafe fn new_unchecked(a: i32) -> Self { Self(a) }\n\t\tfn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n\t\tfn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n\t\tfn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n\t\tpub fn inv(self) -> Self { self.pow(P5-2) }\n\t\tpub fn pow>(self, b: T) -> Self {\n\t\t\tlet b = b.into(); if b == 0 { Self(1) } else {\n\t\t\t\tlet mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res\n\t\t\t}\n\t\t}\n\t}\n\timpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\n\timpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\n\timpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\n\timpl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}\n\timpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\n\timpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\n\timpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\n\timpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\n\timpl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }\n\tuse std::fmt::{Display, Formatter, Result};\n\timpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n}\n#[allow(unused_imports)] use field::{Field, Field as Z, Z0, Z1};\n//}}}\n\nfn main() {\n\tlet (mut rin,mut rout) = rio();\n\n\tlet n = rin.u();\n\tlet mut div = v!([n+1] = 1);\n\tfor i in 2..=n {\n\t\tif div[i] == 1 {\n\t\t\tdiv[i] = 2;\n\t\t\tlet mut j = i+i;\n\t\t\twhile j <= n {\n\t\t\t\tlet mut c = 2;\n\t\t\t\tlet mut x = j / i;\n\t\t\t\twhile x % i == 0 {\n\t\t\t\t\tx /= i;\n\t\t\t\t\tc += 1;\n\t\t\t\t}\n\t\t\t\tdiv[j] *= c;\n\t\t\t\tj += i;\n\t\t\t}\n\t\t}\n\t}\n\tl!(mut dp,s = v!([n+1] = Z0));\n\tfor i in 1..=n {\n\t\tdp[i] = Z::new(div[i]) + s[i-1];\n\t\ts[i] = dp[i] + s[i-1];\n\t}\n\twriteln!(rout, \"{}\", dp[n]).unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "24260dc138a3a122c70d494e9f2ecac3", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\r\n// \u30e2\u30f3\u30b4\u30e1\u30ea\u4e57\u7b97\u3092\u7528\u3044\u308b\r\n// \u307b\u307cCodeforces\u7528\r\n// \u6ce8\u610f\r\n// new_unchecked \u306f\u5024x\u304c 0 <= x < modulo \u3067\u3042\u308b\u3053\u3068\u3092\u4eee\u5b9a\r\n// ModInt \u306e\u4e2d\u8eab\u306f\u6b63\u898f\u5316\u3055\u308c\u305f\u5024\u3067\u6301\u3063\u3066\u308b\u306e\u3067\u76f4\u63a5\u8aad\u3093\u3060\u308a\u66f8\u3044\u305f\u308a\u3059\u308b\u3068\u3076\u3063\u58ca\u308c\u308b\r\n// \u5947\u7d20\u6570\u306e\u307f\r\nmod modint {\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n fn rem() -> u32;\r\n fn ini() -> u64;\r\n fn reduce(x: u64) -> u32 {\r\n assert!(x < (Self::modulo() as u64) << 32);\r\n let b = (x as u32 * Self::rem()) as u64;\r\n let t = x + b * Self::modulo() as u64;\r\n let mut c = (t >> 32) as u32;\r\n if c >= Self::modulo() {\r\n c -= Self::modulo();\r\n }\r\n c as u32\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod1_000_000_007 {}\r\n\r\n impl Modulo for Mod1_000_000_007 {\r\n fn modulo() -> u32 {\r\n 1_000_000_007\r\n }\r\n fn rem() -> u32 {\r\n 2226617417\r\n }\r\n fn ini() -> u64 {\r\n 582344008\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod998_244_353 {}\r\n\r\n impl Modulo for Mod998_244_353 {\r\n fn modulo() -> u32 {\r\n 998_244_353\r\n }\r\n fn rem() -> u32 {\r\n 998244351\r\n }\r\n fn ini() -> u64 {\r\n 932051910\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub fn generate_umekomi_modulo(p: u32) {\r\n assert!(p < (1 << 31) && p > 2 && p & 1 == 1 && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0));\r\n let mut t = 1u32;\r\n let mut s = !p + 1;\r\n let mut n = !0u32 >> 2;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n let mut ini = (1u64 << 32) % p as u64;\r\n ini = (ini << 32) % p as u64;\r\n assert!(t * p == !0);\r\n println!(\"pub enum Mod{} {{}}\", p);\r\n println!(\"impl Modulo for Mod{} {{\", p);\r\n println!(\" fn modulo() -> u32 {{\");\r\n println!(\" {}\", p);\r\n println!(\" }}\");\r\n println!(\" fn rem() -> u32 {{\");\r\n println!(\" {}\", t);\r\n println!(\" }}\");\r\n println!(\" fn ini() -> u32 {{\");\r\n println!(\" {}\", ini);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n let mut f = vec![];\r\n let mut n = p - 1;\r\n for i in 2.. {\r\n if i * i > n {\r\n break;\r\n }\r\n if n % i == 0 {\r\n f.push(i);\r\n while n % i == 0 {\r\n n /= i;\r\n }\r\n }\r\n }\r\n if n > 1 {\r\n f.push(n);\r\n }\r\n let mut order = 1;\r\n let mut n = p - 1;\r\n while n % 2 == 0 {\r\n n /= 2;\r\n order <<= 1;\r\n }\r\n let z = (2u64..).find(|z| {\r\n f.iter().all(|f| mod_pow(*z, ((p - 1) / *f) as u64, p as u64) != 1)\r\n }).unwrap();\r\n let zeta = mod_pow(z, ((p - 1) / order) as u64, p as u64);\r\n println!(\"impl transform::NTTFriendly for Mod{} {{\", p);\r\n println!(\" fn order() -> usize {{\");\r\n println!(\" {}\", order);\r\n println!(\" }}\");\r\n println!(\" fn zeta() -> u32 {{\");\r\n println!(\" {}\", zeta);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n }\r\n\r\n pub struct ModInt(u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::build(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = T::modulo() + self.0 - rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::build(T::reduce(self.0 as u64 * rhs.0 as u64))\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::build(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n fn build(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n Self::build(0)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n Self::build(T::reduce(d as u64 * T::ini()))\r\n }\r\n pub fn new(d: u32) -> Self {\r\n Self::new_unchecked(d % T::modulo())\r\n }\r\n pub fn one() -> Self {\r\n Self::new_unchecked(1)\r\n }\r\n pub fn get(&self) -> u32 {\r\n T::reduce(self.0 as u64)\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n pub fn inv(&self) -> Self {\r\n assert!(!self.is_zero());\r\n self.pow((T::modulo() - 2) as u64)\r\n }\r\n }\r\n\r\n pub fn mod_pow(mut r: u64, mut n: u64, m: u64) -> u64 {\r\n let mut t = 1 % m;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t = t * r % m;\r\n }\r\n r = r * r % m;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n// ---------- begin Precalc ----------\r\nmod precalc {\r\n use super::modint::*;\r\n #[allow(dead_code)]\r\n pub struct Precalc {\r\n inv: Vec>,\r\n fact: Vec>,\r\n ifact: Vec>,\r\n }\r\n #[allow(dead_code)]\r\n impl Precalc {\r\n pub fn new(n: usize) -> Precalc {\r\n let mut inv = vec![ModInt::one(); n + 1];\r\n let mut fact = vec![ModInt::one(); n + 1];\r\n let mut ifact = vec![ModInt::one(); n + 1];\r\n for i in 2..(n + 1) {\r\n fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);\r\n }\r\n ifact[n] = fact[n].inv();\r\n if n > 0 {\r\n inv[n] = ifact[n] * fact[n - 1];\r\n }\r\n for i in (1..n).rev() {\r\n ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);\r\n inv[i] = ifact[i] * fact[i - 1];\r\n }\r\n Precalc {\r\n inv: inv,\r\n fact: fact,\r\n ifact: ifact,\r\n }\r\n }\r\n pub fn inv(&self, n: usize) -> ModInt {\r\n assert!(n > 0);\r\n self.inv[n]\r\n }\r\n pub fn fact(&self, n: usize) -> ModInt {\r\n self.fact[n]\r\n }\r\n pub fn ifact(&self, n: usize) -> ModInt {\r\n self.ifact[n]\r\n }\r\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[n - k]\r\n }\r\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\r\n }\r\n }\r\n}\r\n// ---------- end Precalc ----------\r\n// ---------- begin NTT ----------\r\n#[allow(dead_code)]\r\nmod transform {\r\n use super::modint::*;\r\n pub trait NTTFriendly: Modulo {\r\n fn order() -> usize;\r\n fn zeta() -> u32;\r\n }\r\n pub fn ntt(f: &mut [ModInt]) {\r\n let n = f.len();\r\n assert!(n.count_ones() == 1);\r\n assert!(n <= T::order());\r\n let len = n.trailing_zeros() as usize;\r\n let mut zeta = Vec::with_capacity(len);\r\n let mut r = ModInt::new_unchecked(T::zeta()).pow((T::order() >> len) as u64);\r\n for _ in 0..len {\r\n zeta.push(r);\r\n r = r * r;\r\n }\r\n let mut q = Vec::with_capacity(len / 2);\r\n for (k, &z) in zeta.iter().rev().enumerate().rev() {\r\n let m = 1 << k;\r\n q.clear();\r\n let mut r = ModInt::one();\r\n for _ in 0..m {\r\n q.push(r);\r\n r *= z;\r\n }\r\n for f in f.chunks_exact_mut(2 * m) {\r\n let (x, y) = f.split_at_mut(m);\r\n for ((x, y), q) in x.iter_mut().zip(y.iter_mut()).zip(q.iter()) {\r\n let a = *x;\r\n let b = *y;\r\n *x = a + b;\r\n *y = (a - b) * *q;\r\n }\r\n }\r\n }\r\n }\r\n pub fn intt(f: &mut [ModInt]) {\r\n let n = f.len();\r\n assert!(n.count_ones() == 1);\r\n assert!(n <= T::order());\r\n let len = n.trailing_zeros() as usize;\r\n let mut zeta = Vec::with_capacity(len);\r\n let mut r = ModInt::new_unchecked(T::zeta()).inv().pow((T::order() >> len) as u64);\r\n for _ in 0..len {\r\n zeta.push(r);\r\n r = r * r;\r\n }\r\n let mut q = Vec::with_capacity(len / 2);\r\n for (k, &z) in zeta.iter().rev().enumerate() {\r\n let m = 1 << k;\r\n q.clear();\r\n let mut r = ModInt::one();\r\n for _ in 0..m {\r\n q.push(r);\r\n r *= z;\r\n }\r\n for f in f.chunks_exact_mut(2 * m) {\r\n let (x, y) = f.split_at_mut(m);\r\n for ((x, y), q) in x.iter_mut().zip(y.iter_mut()).zip(q.iter()) {\r\n let a = *x;\r\n let b = *y * *q;\r\n *x = a + b;\r\n *y = a - b;\r\n }\r\n }\r\n }\r\n let ik = ModInt::new_unchecked((T::modulo() + 1) >> 1).pow(len as u64);\r\n for f in f.iter_mut() {\r\n *f *= ik;\r\n }\r\n }\r\n pub fn multiply(a: &[ModInt], b: &[ModInt]) -> Vec> {\r\n if a.is_empty() || b.is_empty() {\r\n return vec![];\r\n }\r\n let n = a.len() + b.len() - 1;\r\n let k = n.next_power_of_two();\r\n assert!(k <= T::order());\r\n let mut f = Vec::with_capacity(k);\r\n let mut g = Vec::with_capacity(k);\r\n f.extend_from_slice(a);\r\n f.resize(k, ModInt::zero());\r\n ntt(&mut f);\r\n g.extend_from_slice(b);\r\n g.resize(k, ModInt::zero());\r\n ntt(&mut g);\r\n for (f, g) in f.iter_mut().zip(g.iter()) {\r\n *f *= *g;\r\n }\r\n intt(&mut f);\r\n f.truncate(n);\r\n f\r\n }\r\n}\r\n// ---------- end NTT ----------\r\n\r\nuse modint::*;\r\n\r\ntype M = ModInt;\r\n\r\nimpl transform::NTTFriendly for Mod998_244_353 {\r\n fn order() -> usize {\r\n 8388608\r\n }\r\n fn zeta() -> u32 {\r\n 15311432\r\n }\r\n}\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nfn run() {\r\n input! {\r\n n: usize,\r\n }\r\n let mut dp = vec![M::zero(); n + 1];\r\n for i in 1..=n {\r\n for j in 1..=(n / i) {\r\n dp[i * j] += M::one();\r\n }\r\n }\r\n let mut sum = M::zero();\r\n for i in 1..=n {\r\n dp[i] = dp[i] + sum;\r\n sum += dp[i];\r\n }\r\n println!(\"{}\", dp[n]);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "a46ac39868e6791cf6561d185cbba2a2", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::*;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok();\n return ret;\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.is_err() || res.ok().unwrap() == 0 || u8b[0] <= ' ' as u8 {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = std::string::String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\nfn parse(s: &str) -> T { s.parse::().ok().unwrap() }\n\n#[allow(dead_code)]\nfn get() -> T { parse(&get_word()) }\n\nfn main() {\n let n: i64 = get();\n let m: i64 = get();\n let nn = n as usize;\n let mm = m as usize;\n let k: i64 = get();\n let x: usize = get::() - 1;\n let y: usize = get::() - 1;\n let mut tbl = vec![vec![0; mm]; nn];\n let div = if n == 1 { m } else { 2 * (n - 1) * m };\n let ascension = k / div;\n let rem = k % div;\n for i in 0 .. nn {\n for j in 0 .. mm {\n tbl[i][j] = ascension * if i == 0 || i == nn - 1 { 1 } else { 2 };\n }\n }\n for i in 0 .. (rem as usize) {\n let p = i / mm;\n let q = i % mm;\n tbl[if p >= nn { 2 * nn - 2 - p } else { p }][q] += 1;\n }\n let mut ma = 0;\n let mut mi = tbl[0][0];\n for i in 0 .. nn {\n ma = max(ma, *tbl[i].iter().max().unwrap());\n mi = min(mi, *tbl[i].iter().min().unwrap());\n }\n println!(\"{} {} {}\", ma, mi, tbl[x][y]);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "binary search", "implementation"], "code_uid": "7a3e3b7668978253a1546735c2a7707d", "src_uid": "e61debcad37eaa9a6e21d7a2122b8b21", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io::stdin;\n\nfn read_int() -> i32 {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n return line.trim().parse().unwrap();\n}\n\nfn read_ints() -> Vec {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n return line\n .trim()\n .split(\" \")\n .map(|x| x.parse::().unwrap())\n .collect();\n}\n\nfn uniq_nums(v: Vec) -> Vec {\n let mut dict = HashMap::new();\n for num in v {\n dict.insert(num, true);\n }\n\n let mut uniqs = Vec::::new();\n for key in dict.keys() {\n uniqs.push(*key);\n }\n uniqs.sort();\n return uniqs;\n}\n\nfn case_2(v: Vec) {\n assert_eq!(v.len(), 2);\n\n let mid = (v[0] + v[1]) / 2;\n if mid - v[0] == v[1] - mid {\n println!(\"{}\", mid - v[0]);\n } else {\n println!(\"{}\", v[1] - v[0]);\n }\n}\n\nfn case_3(v: Vec) {\n assert_eq!(v.len(), 3);\n if v[2] - v[1] == v[1] - v[0] {\n println!(\"{}\", v[2] - v[1]);\n } else {\n println!(\"-1\")\n }\n}\n\nfn main() {\n let n = read_int();\n let nums = read_ints();\n let mut uniqs = uniq_nums(nums);\n\n match uniqs.len() {\n 1 => println!(\"0\"),\n 2 => case_2(uniqs),\n 3 => case_3(uniqs),\n _ => println!(\"-1\"),\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "c083e85170ae2dc48b6a3d7c903fa652", "src_uid": "d486a88939c132848a7efdf257b9b066", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\n\nfn main() {\n let _ = read_one::();\n let mut an = read::();\n an.sort();\n an.dedup();\n\n if an.len() > 3 { println!(\"-1\"); return; }\n if an.len() == 1 { println!(\"{}\", 0); return; }\n if an.len() == 2 {\n if (an[1] - an[0]) % 2 == 0 {\n println!(\"{}\", cmp::min((an[1] - an[0]) / 2, an[1] - an[0]));\n } else {\n println!(\"{}\", an[1] - an[0]);\n }\n return;\n }\n if an.len() == 3 {\n if an[2] - an[1] == an[1] - an[0] {\n println!(\"{}\", an[1] - an[0]);\n } else {\n println!(\"-1\");\n }\n }\n}\n\n\n#[allow(dead_code)]\nfn read() -> Vec\nwhere T:\nstd::str::FromStr,\nT::Err: std::fmt::Debug {\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.split_whitespace()\n .map(|s| s.trim().parse().unwrap())\n .collect()\n}\n\n#[allow(dead_code)]\nfn read_one() -> T\nwhere T:\nstd::str::FromStr,\nT::Err: std::fmt::Debug {\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1ca709fb5a15a02d85487173c5866252", "src_uid": "d486a88939c132848a7efdf257b9b066", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/**\n * https://codeforces.com/contest/1154/problem/B\n */\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\npub fn main() {\n let _ = parse_line!(i32);\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"n not esist\");\n let mut nums: Vec = buffer.split_whitespace().map(|x| x.parse().expect(\"error\")).collect();\n nums.sort();\n nums.dedup();\n let res = match nums.len() {\n 1 => 0,\n 2 => {\n let d = nums[1] - nums[0];\n if d % 2 == 0 {\n d / 2\n } else {\n d\n }\n }\n 3 => {\n if nums[2] - nums[1] == nums[1] - nums[0] {\n nums[2] - nums[1]\n } else {\n -1\n }\n }\n _ => -1,\n };\n println!(\"{}\", res);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "a74d41c5bd1a00e4321f76446c600360", "src_uid": "d486a88939c132848a7efdf257b9b066", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::char;\nuse std::fs::File;\nuse std::io::Read;\n\n// fn pow_speedt_with_mod(mut p: i64, mut q: i64, m: i64) -> i64 {\n// p %= m;\n// let mut r = p;\n// let mut ret: i64 = 1;\n// while q > 0 {\n// ret *= if q % 2 == 1 {r} else {1};\n// r *= r;\n// r %= m;\n// q /= 2;\n// ret %= m;\n// }\n// return ret;\n// }\n\nfn main() {\n let inputstatus = 1;\n\n let mut buf = String::new();\n let filename = \"inputrust.txt\";\n\n if inputstatus == 0 {\n let mut f = File::open(filename).expect(\"file not found\");\n f.read_to_string(&mut buf)\n .expect(\"something went wrong reading the file\");\n } else {\n std::io::stdin().read_to_string(&mut buf).unwrap();\n }\n\n let mut iter = buf.split_whitespace();\n let n: usize = iter.next().unwrap().parse().unwrap();\n let mut v = Vec::::new();\n let mut v_commpress = Vec::::new();\n\n for _ in 0..n {\n v.push(iter.next().unwrap().parse().unwrap());\n }\n v.sort();\n\n for (i, vi) in v.iter().enumerate() {\n if i == 0 {\n v_commpress.push(*vi);\n } else if v[i - 1] != v[i] {\n v_commpress.push(*vi);\n }\n }\n\n // println!(\"{:?}\", v_commpress);\n\n let ans = if v_commpress.len() <= 1 {\n 0\n } else if v_commpress.len() == 2 && (v_commpress[1] - v_commpress[0]) % 2 == 0 {\n (v_commpress[1] - v_commpress[0]) / 2\n } else if v_commpress.len() == 2 && (v_commpress[1] - v_commpress[0]) % 2 == 1 {\n v_commpress[1] - v_commpress[0]\n } else if v_commpress.len() == 3 && (v_commpress[2] + v_commpress[0]) == 2 * v_commpress[1] {\n v_commpress[1] - v_commpress[0]\n } else {\n -1\n };\n println!(\"{}\", ans);\n\n // if p + 1 >= m\n\n // println!(\"{}\", n);\n // println!(\"{}\", k);\n // println!(\"{:?}\", num);\n // println!(\"{:?}\", cum_num);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "edb956261572d5d08b42e7fbe52a969d", "src_uid": "d486a88939c132848a7efdf257b9b066", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn combination(n: u64, k: u64, m: u64) -> u64 {\n if n == 0 {\n return 1;\n }\n if k == 0 || k == n {\n return 1;\n }\n let new_k = if n - k < k { n - k } else { k };\n let mut res = 1;\n for i in ((n - new_k) + 1)..=n {\n res *= i;\n res %= m;\n }\n let mut den = 1;\n for i in 1..=(new_k) {\n den *= i;\n den %= m;\n }\n let (_one, inverse, _c) = egcd(den as i64, m as i64);\n let inverse = if inverse < 0 {\n m as i64 + inverse\n } else {\n inverse\n } as u64;\n //println!(\"inv: {} {}\", den, inverse);\n res *= inverse;\n res %= m;\n res\n}\n\nuse std::collections::HashSet;\nuse std::iter::FromIterator;\n\nfn n_to_vec(n: u64, l: usize) -> Vec {\n let mut res = vec![0; l];\n let mut n = n;\n for i in (0..l).rev() {\n if n % 2 == 1 {\n res[i] = 1;\n }\n n /= 2;\n }\n res\n}\n\nfn vec_to_n(v: Vec) -> u64 {\n let mut res = 0;\n for i in 0..v.len() {\n res *= 2;\n if v[i] == 1 {\n res += 1;\n }\n }\n res\n}\n\nfn main() -> Result<(), Box> {\n let _n = read_usize();\n let a_vec = read_multiple::();\n let mut v = Vec::new();\n let mut flag = false;\n 'f: for a in a_vec {\n if !v.contains(&a) {\n v.push(a)\n }\n if v.len() > 3 {\n flag = true;\n break 'f;\n }\n }\n if flag {\n println!(\"-1\")\n } else {\n v.sort_unstable();\n if v.len() == 1 {\n println!(\"0\")\n } else if v.len() == 2 {\n if (v[1] - v[0]) % 2 == 0 {\n println!(\"{}\", (v[1] - v[0]) / 2)\n } else {\n println!(\"{}\", v[1] - v[0])\n }\n } else {\n //v.len() == 3\n if v[2] - v[1] != v[1] - v[0] {\n println!(\"-1\")\n } else {\n println!(\"{}\", v[2] - v[1])\n }\n }\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "833c9b95a9893576586ae2fd1eb8ad51", "src_uid": "d486a88939c132848a7efdf257b9b066", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let a:Vec = (0..n).map(|_| read()).collect();\n\n let mut ans = 10000;\n for e in -1000..1000 {\n let mut d = 0;\n for i in 0..n {\n if (a[i]-e).abs() != 0 { d = (a[i]-e).abs(); break; }\n }\n let mut f = true;\n for i in 0..n {\n if (a[i]-e).abs() == 0 { continue; }\n if d != (a[i]-e).abs() {\n f = false;\n }\n }\n if f {\n ans = min(ans, d);\n }\n }\n println!(\"{}\", if ans==10000 {-1} else {ans});\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "f578963a8fee0746b01900a723f2f4cc", "src_uid": "d486a88939c132848a7efdf257b9b066", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n a: [u32; n],\n }\n let mut n = n;\n let mut a = a;\n let mut ans = 0;\n while n > 0 {\n a.sort();\n let v = a[0];\n let mut b = vec![];\n for i in 1..n {\n if a[i] % v != 0 {\n b.push(a[i]);\n }\n }\n a = b;\n n = a.len();\n ans += 1;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "0b7a52a1e936dba606fe550a324bb23a", "src_uid": "63d9b7416aa96129c57d20ec6145e0cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ######### contest shortcuts\n#![allow(unused_imports, dead_code, unused_variables)]\nuse std::io::{stdin, stdout, BufWriter, BufReader, Read, Write};\nuse std::cmp;\n\n#[derive(Default)]\nstruct Scanner (Vec,);\n \nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.0.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.0 = input.split_whitespace().rev()\n .map(String::from).collect();\n }\n }\n}\n// ## END ## contest shortcuts\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n let n = scan.next::();\n // let mut a = scan.next::();\n let a: Vec = (0..n)\n .map(|_| scan.next::())\n .collect();\n let mut s_a: Vec<_> = a.iter()\n .map(|e| e.clone())\n .enumerate()\n .collect();\n s_a.sort_by_key(|&(_, e)| e);\n // println!(\"{:?}\", s_a);\n let mut marks = vec![false; n];\n let mut colors = 0usize;\n for &(j, e) in s_a.iter() {\n if marks[j] { continue; }\n colors += 1;\n \n for (i, ae) in a.iter().enumerate(){\n if marks[i] == false && ae % e == 0 {\n marks[i] = true;\n // println!(\"{:?}\", e);\n }\n }\n }\n write!(out, \"{}\", colors).ok();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "0436b72bf6bdf131eeebfdd085d1814e", "src_uid": "63d9b7416aa96129c57d20ec6145e0cd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::{BTreeSet, VecDeque};\r\nuse std::io::Write;\r\n\r\n#[cfg(feature = \"badcw\")]\r\npub use notes::one_line::*;\r\n\r\n// ---------- begin scannner ----------\r\n#[allow(dead_code, unused_imports)]\r\nmod scanner {\r\n use std::str::FromStr;\r\n pub struct Scanner<'a> {\r\n it: std::str::SplitWhitespace<'a>,\r\n }\r\n impl<'a> Scanner<'a> {\r\n pub fn new(s: &'a String) -> Scanner<'a> {\r\n Scanner {\r\n it: s.split_whitespace(),\r\n }\r\n }\r\n pub fn next(&mut self) -> T {\r\n self.it.next().unwrap().parse::().ok().unwrap()\r\n }\r\n pub fn next_bytes(&mut self) -> Vec {\r\n self.it.next().unwrap().bytes().collect()\r\n }\r\n pub fn next_chars(&mut self) -> Vec {\r\n self.it.next().unwrap().chars().collect()\r\n }\r\n pub fn next_vec(&mut self, len: usize) -> Vec {\r\n (0..len).map(|_| self.next()).collect()\r\n }\r\n pub fn size(&self) -> usize {\r\n self.it.clone().count()\r\n }\r\n }\r\n}\r\n// ---------- end scannner ----------\r\n\r\nfn main() {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n let mut sc = scanner::Scanner::new(&s);\r\n let out = std::io::stdout();\r\n let mut out = std::io::BufWriter::new(out.lock());\r\n run(&mut sc, &mut out);\r\n}\r\n\r\nfn run(sc: &mut scanner::Scanner, out: &mut std::io::BufWriter) {\r\n let T = sc.size()/2;\r\n for kase in 0..T {\r\n let n: usize = sc.next();\r\n let x: usize = sc.next();\r\n let mut qu = VecDeque::new();\r\n let mut st = BTreeSet::new();\r\n qu.push_back((x, 0));\r\n st.insert(x);\r\n let mut f = false;\r\n while let Some((u, dp)) = qu.pop_front() {\r\n if u.to_string().len() > n {\r\n break;\r\n }\r\n if u.to_string().len() == n {\r\n f = true;\r\n writeln!(out, \"{}\", dp);\r\n break;\r\n }\r\n for c in u.to_string().as_bytes() {\r\n if c < &b'2' {\r\n continue;\r\n }\r\n let v = u * ((c - b'0') as usize);\r\n if st.insert(v) {\r\n qu.push_back((v, dp + 1));\r\n }\r\n }\r\n }\r\n if !f {\r\n writeln!(out, \"-1\");\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "411033bc2ede1c3f1778303354ba55ff", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused)]\r\n\r\nmod io {\r\n use std::str::{FromStr, SplitWhitespace};\r\n\r\n pub fn read_from_stdin() -> String {\r\n use std::io::Read;\r\n let mut input = String::new();\r\n\r\n std::io::stdin()\r\n .read_to_string(&mut input)\r\n .expect(\"Error reading from stdin\");\r\n input\r\n .trim()\r\n .to_string()\r\n }\r\n\r\n pub struct Input<'a> {\r\n values: SplitWhitespace<'a>\r\n }\r\n\r\n impl <'a> Input<'a> {\r\n pub fn from(input: &'a str) -> Self {\r\n Self { values: input.split_whitespace() }\r\n }\r\n\r\n pub fn next(&mut self) -> T where T: FromStr {\r\n self\r\n .values\r\n .next()\r\n .unwrap()\r\n .parse::()\r\n .ok()\r\n .unwrap()\r\n }\r\n\r\n pub fn vec(&mut self, n: usize) -> Vec where T: FromStr {\r\n (0..n)\r\n .map(|_| self.next())\r\n .collect()\r\n }\r\n }\r\n}\r\n\r\nuse std::collections::{HashMap, HashSet, VecDeque};\r\nuse std::io::{BufWriter, StdoutLock, Write};\r\n\r\nfn main() {\r\n let stdin = io::read_from_stdin();\r\n let stdout = std::io::stdout();\r\n let mut input = io::Input::from(&stdin);\r\n let mut output = BufWriter::new(stdout.lock());\r\n //let k: usize = input.next();\r\n\r\n //for _ in 0..k { solve(&mut input, &mut output) }\r\n solve(&mut input, &mut output);\r\n}\r\n\r\nconst MAX: i64 = 1e9 as i64 + 10;\r\n\r\nfn solve(input: &mut io::Input, output: &mut BufWriter) {\r\n let n: usize = input.next();\r\n let x: i64 = input.next();\r\n let mut map = HashMap::::new();\r\n let mut ans = dfs(n, x, &mut map);\r\n ans = if ans == MAX { -1 } else { ans };\r\n\r\n writeln!(output, \"{ans}\");\r\n}\r\n\r\n\r\nfn dfs(n: usize, x: i64, map: &mut HashMap) -> i64 {\r\n let s = x.to_string();\r\n let ss: HashSet = s.chars().collect();\r\n let mut min = MAX;\r\n if s.len() > n { return MAX }\r\n if s.len() == n { return 0 }\r\n if let Some(&result) = map.get(&x) { return result }\r\n\r\n for c in ss {\r\n let i = c as u8 - '0' as u8;\r\n if i > 1 {\r\n let p = x * i as i64 ;\r\n min = min.min(1 + dfs(n, p, map));\r\n }\r\n }\r\n *map.entry(x).or_insert(0) = min;\r\n min\r\n}", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "f4b6dbb91d5e682dab847000723d20c6", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io::{self, BufWriter, Write};\r\n\r\nmod scanner {\r\n use std::{io, str};\r\n /* https://github.com/EbTech/rust-algorithms */\r\n\r\n /// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\r\n /// **REQUIRES** Rust 1.34 or higher\r\n pub struct UnsafeScanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitAsciiWhitespace<'static>,\r\n }\r\n\r\n impl UnsafeScanner {\r\n pub fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: Vec::new(),\r\n buf_iter: \"\".split_ascii_whitespace(),\r\n }\r\n }\r\n\r\n /// This function should be marked unsafe, but noone has time for that in a\r\n /// programming contest. Use at your own risk!\r\n pub fn token(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_ascii_whitespace())\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nuse std::cmp::{min, max};\r\n\r\nfn s2vec(s: String) -> Vec {\r\n s.chars().collect()\r\n}\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let (mut scan, mut sout) = (\r\n scanner::UnsafeScanner::new(stdin.lock()),\r\n BufWriter::new(stdout.lock()),\r\n );\r\n use std::collections::{HashSet, VecDeque};\r\n let n: usize = scan.token();\r\n let x: i64 = scan.token();\r\n let mut s: HashSet = HashSet::new();\r\n let mut ret = std::i32::MAX;\r\n let mut q = VecDeque::new();\r\n s.insert(x);\r\n q.push_back((x, 0));\r\n while let Some((x, c)) = q.pop_front() {\r\n let mut x_t = x;\r\n let mut k = 0;\r\n while x_t > 0 {\r\n k += 1;\r\n x_t /= 10;\r\n }\r\n if n == k {\r\n ret = min(ret, c);\r\n } else {\r\n x_t = x;\r\n while x_t > 0 {\r\n if (x_t % 10) > 1 {\r\n let y = x * (x_t % 10);\r\n if !s.contains(&y) {\r\n s.insert(y);\r\n q.push_back((y, c+1));\r\n }\r\n }\r\n x_t /= 10;\r\n }\r\n }\r\n }\r\n if ret == std::i32::MAX {\r\n writeln!(sout, \"-1\").ok();\r\n } else {\r\n writeln!(sout, \"{}\", ret).ok();\r\n }\r\n}", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "0d90955e0d7572d1fa0c70a2d50031c8", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(non_snake_case)]\r\n#![allow(unused_imports)]\r\n\r\n#[macro_use]\r\nmod singleton {\r\n #[macro_export]\r\n macro_rules! singleton {\r\n ($type:ty, $e:expr) => {\r\n static mut INSTANCE: *mut $type = 0 as _;\r\n static mut INIT: bool = false;\r\n \r\n pub fn instance() -> &'static mut $type {\r\n unsafe {\r\n if !INIT {\r\n INSTANCE = Box::into_raw(Box::new($e));\r\n INIT = true;\r\n }\r\n INSTANCE.as_mut().unwrap()\r\n }\r\n }\r\n };\r\n }\r\n \r\n #[macro_export]\r\n macro_rules! defglobal {\r\n ($type:ty, $set:ident, $get:ident) => {\r\n mod $get {\r\n pub(crate) static mut INSTANCE: *mut $type = 0 as _;\r\n }\r\n \r\n pub fn $set(value: $type) {\r\n unsafe {\r\n $get::INSTANCE = Box::into_raw(Box::new(value));\r\n }\r\n }\r\n \r\n pub fn $get() -> &'static mut $type {\r\n unsafe { $get::INSTANCE.as_mut().unwrap() }\r\n }\r\n };\r\n }\r\n \r\n}\r\npub use singleton::*;\r\n\r\n#[macro_use]\r\nmod scanner {\r\n \r\n use std::io::BufRead;\r\n use std::io::BufReader;\r\n \r\n pub struct Scanner {\r\n reader: Box,\r\n buffer: Vec,\r\n }\r\n \r\n impl Default for Scanner {\r\n fn default() -> Self {\r\n let mut reader_opt: Option> = None;\r\n for arg in std::env::args().skip(1) {\r\n if let Ok(fd) = std::fs::File::open(arg) {\r\n reader_opt = Some(Box::new(BufReader::new(fd)));\r\n break;\r\n }\r\n }\r\n let reader = reader_opt.unwrap_or_else(|| Box::new(BufReader::new(std::io::stdin())));\r\n Scanner {\r\n reader,\r\n buffer: vec![],\r\n }\r\n }\r\n }\r\n \r\n singleton!(Scanner, Scanner::default());\r\n \r\n // global scanner\r\n #[macro_export]\r\n macro_rules! scanner_impl {\r\n ( $name2:ident, $name:ident\r\n $(< $( $lt:tt : $clt:tt ),+ >)?\r\n ( $scanner:ident ) -> $ret_type:ty\r\n $body:block\r\n )\r\n =>\r\n {\r\n fn $name2 $(< $( $lt : $clt ),+ >)? ($scanner: &mut Scanner) -> $ret_type\r\n $body\r\n \r\n pub fn $name $(< $( $lt : $clt ),+ >)? () -> $ret_type {\r\n $name2(crate::scanner::instance())\r\n }\r\n \r\n impl Scanner {\r\n pub fn $name $(< $( $lt : $clt ),+ >)? ( &mut self ) -> $ret_type {\r\n $name2(self)\r\n }\r\n }\r\n };\r\n ( $name2:ident, $name:ident\r\n $(< $( $lt:tt : $clt:tt ),+ >)?\r\n ( $scanner:ident, $( $arg:ident : $type:ty ),* ) -> $ret_type:ty\r\n $body:block\r\n )\r\n =>\r\n {\r\n fn $name2 $(< $( $lt : $clt ),+ >)? ( $scanner: &mut Scanner, $( $arg : $type ),* ) -> $ret_type\r\n $body\r\n \r\n pub fn $name $(< $( $lt : $clt ),+ >)? ( $( $arg : $type ),* ) -> $ret_type {\r\n $name2(crate::scanner::instance(), $( $arg ),* )\r\n }\r\n \r\n impl Scanner {\r\n pub fn $name $(< $( $lt : $clt ),+ >)? ( &mut self, $( $arg : $type ),* ) -> $ret_type {\r\n $name2( self, $( $arg ),* )\r\n }\r\n }\r\n };\r\n }\r\n \r\n scanner_impl!(_scan, scan(sc) -> T {\r\n use std::io::Write;\r\n crate::debug!(sc.buffer);\r\n loop {\r\n if let Some(token) = sc.buffer.pop() {\r\n debug_scan(&token);\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n let mut input = String::new();\r\n sc.reader.read_line(&mut input).expect(\"Failed read\");\r\n sc.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n }\r\n });\r\n \r\n #[rustfmt::skip]\r\n macro_rules! scanner_impl_for_type {\r\n ($ty:ty, $name:ident) => {\r\n impl Scanner {\r\n pub fn $name(&mut self) -> $ty {\r\n self.scan()\r\n }\r\n }\r\n impl Token for $ty {\r\n }\r\n pub fn $name() -> $ty {\r\n instance().$name()\r\n }\r\n };\r\n ($ty:ty, $name:ident, $name1:ident) => { \r\n scanner_impl_for_type!($ty, $name);\r\n impl TokenNum for $ty {\r\n }\r\n impl Scanner {\r\n pub fn $name1(&mut self, ofs: $ty) -> $ty { \r\n self.scan1(ofs)\r\n }\r\n }\r\n pub fn $name1(ofs: $ty) -> $ty {\r\n instance().$name1(ofs)\r\n }\r\n };\r\n }\r\n \r\n pub trait Token: std::str::FromStr + std::fmt::Debug {}\r\n pub trait TokenNum: Token + std::ops::Sub {}\r\n \r\n scanner_impl_for_type!(usize, scan_usize, scan1_usize);\r\n scanner_impl_for_type!(isize, scan_isize, scan1_isize);\r\n scanner_impl_for_type!(i32, scan_i32, scan1_i32);\r\n scanner_impl_for_type!(i64, scan_i64, scan1_i64);\r\n scanner_impl_for_type!(u32, scan_u32, scan1_u32);\r\n scanner_impl_for_type!(u64, scan_u64, scan1_u64);\r\n scanner_impl_for_type!(String, scan_string);\r\n \r\n fn debug_scan(val: T) {\r\n if crate::output_writer::macro_use::do_debug_scan() {\r\n let instance = crate::output_writer::macro_use::instance();\r\n instance.push_tok(val.to_string());\r\n }\r\n }\r\n \r\n // extensions\r\n scanner_impl!(_scan1, scan1(sc, ofs: T) -> T {\r\n sc.scan::() - ofs\r\n });\r\n scanner_impl!(_scan_vector, scan_vector(sc, n: usize) -> Vec {\r\n debug_scan(\"[\");\r\n let mut v = Vec::with_capacity(n);\r\n for _ in 0..n { v.push(sc.scan()); }\r\n debug_scan(\"]\");\r\n v\r\n });\r\n scanner_impl!(_scan_pair, scan_pair(sc) -> (T1, T2) {\r\n debug_scan(\"#p[\");\r\n let t1 = sc.scan();\r\n let t2 = sc.scan();\r\n debug_scan(\"]\");\r\n (t1,t2)\r\n });\r\n \r\n}\r\npub use scanner::*;\r\n\r\n#[macro_use]\r\nmod output_writer {\r\n pub mod macro_use {\r\n use std::io::stdout;\r\n use std::io::BufWriter;\r\n use std::io::Stdout;\r\n use std::io::Write;\r\n use std::ops::Deref;\r\n use std::ops::DerefMut;\r\n \r\n static mut DEBUG: bool = false;\r\n static mut DEBUG_SCAN: bool = false;\r\n \r\n // OutputWriterImpl\r\n pub struct OutputWriterImpl {\r\n inner: BufWriter,\r\n pending_tokens: Vec,\r\n }\r\n \r\n impl Default for OutputWriterImpl {\r\n fn default() -> Self {\r\n unsafe {\r\n for arg in std::env::args().skip(1) {\r\n match arg.as_str() {\r\n \"debug\" => DEBUG = true,\r\n \"scan\" => DEBUG_SCAN = true,\r\n _ => {}\r\n }\r\n }\r\n }\r\n OutputWriterImpl {\r\n inner: BufWriter::new(stdout()),\r\n pending_tokens: vec![],\r\n }\r\n }\r\n }\r\n singleton!(OutputWriterImpl, OutputWriterImpl::default());\r\n \r\n impl OutputWriterImpl {\r\n pub fn push_tok(&mut self, tok: String) {\r\n self.pending_tokens.push(tok);\r\n }\r\n }\r\n \r\n impl Deref for OutputWriterImpl {\r\n type Target = BufWriter;\r\n \r\n fn deref(&self) -> &Self::Target {\r\n &instance().inner\r\n }\r\n }\r\n \r\n impl DerefMut for OutputWriterImpl {\r\n fn deref_mut(&mut self) -> &mut Self::Target {\r\n &mut instance().inner\r\n }\r\n }\r\n \r\n #[rustfmt::skip]\r\n pub fn start_debug() -> bool {\r\n crate::output_writer::macro_use::flush_pending_tokens();\r\n \r\n let res = unsafe { DEBUG };\r\n if res { instance().write(b\"\\x1B[33m\").ok(); }\r\n res\r\n }\r\n \r\n #[rustfmt::skip]\r\n pub fn do_debug_scan() -> bool {\r\n unsafe { DEBUG_SCAN }\r\n }\r\n \r\n pub fn end_debug() {\r\n instance().write(b\"\\x1B[0m\").ok();\r\n }\r\n \r\n pub fn flush_pending_tokens() {\r\n if do_debug_scan() {\r\n let mut any = false;\r\n for (i, ref tok) in instance().pending_tokens.drain(..).enumerate() {\r\n let sep = if i == 0 {\r\n instance().write(b\"\\x1B[34m\").ok();\r\n \"DEBUG_SCAN\\t\"\r\n } else {\r\n \" \"\r\n };\r\n \r\n let instance = crate::output_writer::macro_use::instance();\r\n write!(instance, \"{}{}\", sep, &tok).ok();\r\n any = true;\r\n }\r\n if any {\r\n crate::output_writer::macro_use::end_debug();\r\n let instance = crate::output_writer::macro_use::instance();\r\n write!(instance, \"\\n\").ok();\r\n }\r\n }\r\n }\r\n \r\n impl Drop for crate::OutputWriter {\r\n fn drop(&mut self) {\r\n crate::output_writer::macro_use::flush_pending_tokens();\r\n instance().inner.flush().expect(\"flush\");\r\n }\r\n }\r\n }\r\n \r\n // OutputWriter\r\n pub struct OutputWriter;\r\n \r\n #[macro_export]\r\n macro_rules! debug {\r\n () => {\r\n if crate::output_writer::macro_use::start_debug() {\r\n let instance = crate::output_writer::macro_use::instance();\r\n write!(instance, \"DEBUG [{}:{}]\",\r\n file!(), line!()).ok();\r\n crate::output_writer::macro_use::end_debug();\r\n write!(instance, \"\\n\").ok();\r\n instance.flush().ok();\r\n }\r\n };\r\n ($val:expr) => {\r\n if crate::output_writer::macro_use::start_debug() {\r\n let instance = crate::output_writer::macro_use::instance();\r\n write!(instance, \"DEBUG [{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($val), &$val).ok();\r\n crate::output_writer::macro_use::end_debug();\r\n write!(instance, \"\\n\").ok();\r\n instance.flush().ok();\r\n }\r\n };\r\n ($val0:expr, $($val:expr),* $(,)?) => {\r\n if crate::output_writer::macro_use::start_debug() {\r\n let instance = crate::output_writer::macro_use::instance();\r\n write!(instance, \"DEBUG [{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($val0), &$val0).ok();\r\n $(write!(instance, \"\\nDEBUG [{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($val), &$val).ok(); )*\r\n crate::output_writer::macro_use::end_debug();\r\n write!(instance, \"\\n\").ok();\r\n instance.flush().ok();\r\n }\r\n };\r\n }\r\n \r\n #[macro_export]\r\n macro_rules! pp {\r\n () => {\r\n crate::output_writer::macro_use::flush_pending_tokens();\r\n let instance = crate::output_writer::macro_use::instance();\r\n writeln!(instance).ok()\r\n };\r\n ($e:expr $(,)?) => {\r\n crate::output_writer::macro_use::flush_pending_tokens();\r\n let instance = crate::output_writer::macro_use::instance();\r\n writeln!(instance, \"{}\", $e).ok()\r\n };\r\n ($($e:expr),+ $(,)?) => {\r\n crate::output_writer::macro_use::flush_pending_tokens();\r\n let instance = crate::output_writer::macro_use::instance();\r\n $( write!(instance, \"{} \", $e).ok(); )+\r\n writeln!(instance).ok()\r\n };\r\n ($($e:expr),*;!) => {\r\n pp!($($e),*);\r\n let instance = crate::output_writer::macro_use::instance();\r\n instance.flush().ok();\r\n };\r\n }\r\n \r\n #[macro_export]\r\n macro_rules! pf {\r\n ($fmt:tt, $($e:expr),* $(,)?) => {\r\n crate::output_writer::macro_use::flush_pending_tokens();\r\n let instance = crate::output_writer::macro_use::instance();\r\n writeln!(instance, $fmt, $($e),*).ok();\r\n };\r\n ($fmt:tt, $($e:expr),* $(,)?; !) => {\r\n pf!($fmt,$($e),+);\r\n let instance = crate::output_writer::macro_use::instance();\r\n instance.flush().ok();\r\n };\r\n }\r\n \r\n #[macro_export]\r\n macro_rules! pps {\r\n ($v:expr, $ofs:expr) => {\r\n crate::output_writer::macro_use::flush_pending_tokens();\r\n let instance = crate::output_writer::macro_use::instance();\r\n for (i, x) in $v.iter().enumerate() {\r\n let e = if i + 1 == $v.len() { \"\\n\" } else { \" \" };\r\n write!(instance, \"{}{}\", *x + $ofs, e).ok();\r\n }\r\n };\r\n ($v:expr) => {\r\n pps!($v, 0)\r\n };\r\n }\r\n \r\n #[macro_export]\r\n macro_rules! output_init {\r\n () => {\r\n #[warn(unused_variables)]\r\n let __OUTPUT__ = OutputWriter;\r\n let _ = instance();\r\n };\r\n }\r\n \r\n}\r\npub use output_writer::*;\r\n\r\nuse std::io::Write;\r\n\r\nfn digits(n: u64) -> usize {\r\n if n == 0 {\r\n return 0;\r\n }\r\n let mut lo = 1;\r\n let mut d = 1;\r\n while lo * 10 <= n {\r\n lo *= 10;\r\n d += 1;\r\n }\r\n d\r\n}\r\n\r\n#[test]\r\nfn test_d() {\r\n assert_eq!(3, digits(343));\r\n assert_eq!(3, digits(999));\r\n assert_eq!(4, digits(1000));\r\n assert_eq!(0, digits(0));\r\n assert_eq!(1, digits(1));\r\n}\r\n\r\nfn main() {\r\n output_init!();\r\n\r\n let N = scan();\r\n let X = scan_u64();\r\n debug!(N, X);\r\n\r\n let mut vis = std::collections::HashSet::new();\r\n let mut q = std::collections::VecDeque::new();\r\n q.push_back((0, X));\r\n while let Some(x) = q.pop_front() {\r\n if vis.contains(&x.1) {\r\n continue;\r\n }\r\n vis.insert(x.1);\r\n if digits(x.1) == N {\r\n pp!(x.0);\r\n return;\r\n }\r\n let mut mask = 0;\r\n let mut xx = x.1;\r\n while xx > 0 {\r\n let d = xx % 10;\r\n xx /= 10;\r\n if (mask & (1 << d)) != 0 {\r\n continue;\r\n }\r\n mask |= 1 << d;\r\n let y: (usize, u64) = (x.0 + 1, x.1.saturating_mul(d));\r\n q.push_back(y);\r\n }\r\n }\r\n pp!(-1);\r\n}\r\n\r\n", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "8c4fe9b8f9de8492db7442f50c2a212e", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::{BTreeSet, VecDeque};\r\nuse std::io::Write;\r\n\r\n#[cfg(feature = \"badcw\")]\r\npub use notes::one_line::*;\r\n\r\n// ---------- begin scannner ----------\r\n#[allow(dead_code, unused_imports)]\r\nmod scanner {\r\n use std::str::FromStr;\r\n pub struct Scanner<'a> {\r\n it: std::str::SplitWhitespace<'a>,\r\n }\r\n impl<'a> Scanner<'a> {\r\n pub fn new(s: &'a String) -> Scanner<'a> {\r\n Scanner {\r\n it: s.split_whitespace(),\r\n }\r\n }\r\n pub fn next(&mut self) -> T {\r\n self.it.next().unwrap().parse::().ok().unwrap()\r\n }\r\n pub fn next_bytes(&mut self) -> Vec {\r\n self.it.next().unwrap().bytes().collect()\r\n }\r\n pub fn next_chars(&mut self) -> Vec {\r\n self.it.next().unwrap().chars().collect()\r\n }\r\n pub fn next_vec(&mut self, len: usize) -> Vec {\r\n (0..len).map(|_| self.next()).collect()\r\n }\r\n pub fn size(&self) -> usize {\r\n self.it.clone().count()\r\n }\r\n }\r\n}\r\n// ---------- end scannner ----------\r\n\r\nfn main() {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n let mut sc = scanner::Scanner::new(&s);\r\n let out = std::io::stdout();\r\n let mut out = std::io::BufWriter::new(out.lock());\r\n run(&mut sc, &mut out);\r\n}\r\n\r\nfn run(sc: &mut scanner::Scanner, out: &mut std::io::BufWriter) {\r\n let T = sc.size()/2;\r\n for kase in 0..T {\r\n let n: usize = sc.next();\r\n let x: usize = sc.next();\r\n let mut qu = VecDeque::new();\r\n let mut st = BTreeSet::new();\r\n qu.push_back((x, 0));\r\n st.insert(x);\r\n let mut f = false;\r\n while let Some((u, dp)) = qu.pop_front() {\r\n let str = u.to_string();\r\n if str.len() > n {\r\n break;\r\n }\r\n if str.len() == n {\r\n f = true;\r\n writeln!(out, \"{}\", dp);\r\n break;\r\n }\r\n for c in str.as_bytes() {\r\n if c < &b'2' {\r\n continue;\r\n }\r\n let v = u * ((c - b'0') as usize);\r\n if st.insert(v) {\r\n qu.push_back((v, dp + 1));\r\n }\r\n }\r\n }\r\n if !f {\r\n writeln!(out, \"-1\");\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "da94e6a0cc11a2dfcc5f8a7063188b4c", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::{BTreeSet, VecDeque};\r\nuse std::io::Write;\r\n\r\n#[cfg(feature = \"badcw\")]\r\npub use notes::one_line::*;\r\n\r\n// ---------- begin scannner ----------\r\n#[allow(dead_code, unused_imports)]\r\nmod scanner {\r\n use std::str::FromStr;\r\n pub struct Scanner<'a> {\r\n it: std::str::SplitWhitespace<'a>,\r\n }\r\n impl<'a> Scanner<'a> {\r\n pub fn new(s: &'a String) -> Scanner<'a> {\r\n Scanner {\r\n it: s.split_whitespace(),\r\n }\r\n }\r\n pub fn next(&mut self) -> T {\r\n self.it.next().unwrap().parse::().ok().unwrap()\r\n }\r\n pub fn next_bytes(&mut self) -> Vec {\r\n self.it.next().unwrap().bytes().collect()\r\n }\r\n pub fn next_chars(&mut self) -> Vec {\r\n self.it.next().unwrap().chars().collect()\r\n }\r\n pub fn next_vec(&mut self, len: usize) -> Vec {\r\n (0..len).map(|_| self.next()).collect()\r\n }\r\n pub fn size(&self) -> usize {\r\n self.it.clone().count()\r\n }\r\n }\r\n}\r\n// ---------- end scannner ----------\r\n\r\nfn main() {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n let mut sc = scanner::Scanner::new(&s);\r\n let out = std::io::stdout();\r\n let mut out = std::io::BufWriter::new(out.lock());\r\n run(&mut sc, &mut out);\r\n}\r\n\r\nfn run(sc: &mut scanner::Scanner, out: &mut std::io::BufWriter) {\r\n let T = sc.size()/2;\r\n for kase in 0..T {\r\n let n: usize = sc.next();\r\n let x: usize = sc.next();\r\n let mut qu = VecDeque::new();\r\n let mut st = BTreeSet::new();\r\n qu.push_back((x, 0));\r\n st.insert(x);\r\n let mut f = false;\r\n while let Some((u, dp)) = qu.pop_front() {\r\n if u.to_string().len() > n {\r\n break;\r\n }\r\n if u.to_string().len() == n {\r\n f = true;\r\n writeln!(out, \"{}\", dp);\r\n break;\r\n }\r\n for c in u.to_string().as_bytes() {\r\n let v = u * ((c - b'0') as usize);\r\n if st.insert(v) {\r\n qu.push_back((v, dp + 1));\r\n }\r\n }\r\n }\r\n if !f {\r\n writeln!(out, \"-1\");\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "8f7fc6f1752d872a25c9e5f347b8b55e", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\nfn generate_seed() -> u64 {\n let state = RandomState::new();\n let mut hasher = state.build_hasher();\n Instant::now().hash(&mut hasher);\n hasher.finish()\n}\n\n#[derive(Debug, Clone, Copy)]\nstruct SHash(u64, u64);\nimpl SHash {\n pub fn new() -> Self {\n Self::from_seed(generate_seed(), generate_seed())\n }\n \n pub fn from_seed(k: u64, m: u64) -> Self {\n Self(k, m)\n }\n}\nimpl BuildHasher for SHash {\n type Hasher = Self;\n fn build_hasher(&self) -> Self::Hasher {\n *self\n }\n}\nimpl Hasher for SHash {\n fn write(&mut self, mut bytes: &[u8]) {\n while bytes.len() >= 8 {\n let x = bytes.as_ptr() as *const u64;\n let x = unsafe { x.read_unaligned() };\n self.write_u64(x);\n bytes = &bytes[8..];\n }\n if bytes.len() > 0 {\n let mut x = [!0u8; 8];\n unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), x.as_mut_ptr(), bytes.len()) }\n let x = u64::from_ne_bytes(x);\n self.write_u64(x);\n }\n }\n fn write_u8(&mut self, i: u8) { self.write_u64(i as _) }\n fn write_u16(&mut self, i: u16) { self.write_u64(i as _) }\n fn write_u32(&mut self, i: u32) { self.write_u64(i as _) }\n fn write_usize(&mut self, i: usize) { self.write_u64(i as _) }\n #[inline] fn write_u64(&mut self, i: u64) {\n let mut z = i.wrapping_add(self.1);\n z ^= z.rotate_right(25) ^ z.rotate_right(47);\n z = z.wrapping_mul(0x9E6C63D0676A9A99).wrapping_add(self.0);\n z ^= z >> 23 ^ z >> 51;\n z = z.wrapping_mul(0x9E6D62D06F6A9A9B);\n z ^= z >> 23 ^ z >> 51;\n self.0 = z;\n self.1 = self.1.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);\n }\n fn write_u128(&mut self, i: u128) { self.write_u64(i as _); self.write_u64((i >> 64) as _); }\n fn finish(&self) -> u64 {\n self.0\n }\n}\nimpl Default for SHash { fn default() -> Self { Self::new() } }\n\n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n \n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let x = read!(u64);\n\n let mut D = HashMap::with_hasher(SHash::new());\n D.insert(x, 0);\n let mut que = VecDeque::new();\n que.push_back(x);\n\n let ans = (||{\n while let Some(u) = que.pop_front() {\n let s = u.to_string().into_bytes();\n if s.len() > n { continue; }\n let d = D[&u];\n if s.len() == n { return d; }\n\n for c in s {\n let c = (c - b'0') as u64;\n let v = u.saturating_mul(c);\n if D.entry(v).or_insert(i32::MAX).chmin(d + 1) {\n que.push_back(v);\n }\n }\n }\n\n -1\n })();\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "4d6a107ca6f9110a75c331d8dd5446b0", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::{BTreeMap, VecDeque};\n\nfn main() {\n let (r, w) = (std::io::stdin(), std::io::stdout());\n let mut sc = IO::new(r.lock(), w.lock());\n\n let n: usize = sc.read();\n let x: i64 = sc.read();\n\n if n < x.to_string().len() {\n println!(\"-1\");\n return;\n }\n\n let mut dist = BTreeMap::new();\n dist.insert(x, 0);\n let mut q = VecDeque::new();\n q.push_back(x);\n while let Some(v) = q.pop_front() {\n let s = v.to_string();\n if s.len() == n {\n println!(\"{}\", dist[&v]);\n return;\n }\n\n let mut cur = v;\n while cur > 0 {\n let p = cur % 10;\n let next = v * p;\n if next.to_string().len() <= n && !dist.contains_key(&next) {\n let d = dist[&v] + 1;\n dist.insert(next, d);\n q.push_back(next);\n }\n\n cur /= 10;\n }\n }\n println!(\"-1\");\n}\n\npub struct IO(R, std::io::BufWriter);\n\nimpl IO {\n pub fn new(r: R, w: W) -> Self {\n Self(r, std::io::BufWriter::new(w))\n }\n pub fn write(&mut self, s: S) {\n use std::io::Write;\n self.1.write_all(s.to_string().as_bytes()).unwrap();\n }\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let buf = self\n .0\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn usize0(&mut self) -> usize {\n self.read::() - 1\n }\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "3514dd30a6bc53b84823a977a62e0a1d", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n const vowels: [char; 6] = ['a', 'o', 'y', 'e', 'u', 'i'];\n \n let mut input = String::new();\n io::stdin().read_line(&mut input);\n\n for letter in input.trim().to_ascii_lowercase().chars() {\n if vowels.contains(&letter) { continue; }\n print!(\".\");\n print!(\"{}\", letter);\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "0c4812b6d0923f224a46f01db429640c", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut s = String::new();\n\tio::stdin().read_line(&mut s).unwrap();\n\ts = s.trim().to_string();\n\tlet mut result = String::new();\n\tfor mut i in s.chars() {\n\t\tmatch i {\n\t\t\t'a' | 'A' |\n\t\t\t'o' | 'O' |\n\t\t\t'y' | 'Y' |\n\t\t\t'e' | 'E' |\n\t\t\t'u' | 'U' |\n\t\t\t'i' | 'I' => {}\n\t\t\t_ => {\n\t\t\t\tresult.push('.');\n\t\t\t\tif i >= 'A' && i <= 'Z' {\n\t\t\t\t\tresult.push(i.to_lowercase().next().unwrap());\n\t\t\t\t} else {\n\t\t\t\t\tresult.push(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "81eaa613e81f583d22f59313907d481b", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n\n for c in s.trim().chars() {\n match c {\n 'A' | 'O' | 'Y' | 'E' | 'U' | 'I' |\n 'a' | 'o' | 'y' | 'e' | 'u' | 'i' => {\n continue;\n }, _ => {\n print!(\".\");\n if c.is_lowercase() {\n print!(\"{}\", c);\n } else {\n print!(\"{}\", (('a' as u8) + (c as u8) - ('A' as u8)) as char);\n }\n }\n }\n }\n\n println!(\"\");\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "371df44fbada1e89335d6092645f58e1", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn get_line() -> String {\n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input)\n\t\t.expect(\"\");\n\n\tString::from(input.trim())\n}\n\nfn main() {\n\tlet s = get_line();\n\tlet mut r = String::new();\n\n\tfor c in s.chars() {\n\t\tmatch c {\n\t\t\t'A'|'E'|'I'|'O'|'U'|'Y'|'a'|'e'|'i'|'o'|'u'|'y' => {},\n\t\t\td if d.is_uppercase() => { r += \".\"; \n\t\t\t\t\t\t\t\t\t r += &d.to_lowercase()\n\t\t\t\t\t\t\t\t\t \t\t .nth(0)\n\t\t\t\t\t\t\t\t\t \t\t .unwrap()\n\t\t\t\t\t\t\t\t\t \t\t .to_string(); \n\t\t\t\t\t\t\t\t\t },\n\t\t\t_ => { r += \".\"; \n\t\t\t\t r += &c.to_string() \n\t\t\t\t }\n\t\t}\n\t}\n\n\tprintln!(\"{}\", r);\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "5473e43dc07763571d16aa1359a4078a", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let inp = read_string();\n let inp: String = inp.chars().filter(|c| {\n c.to_lowercase().to_string() != \"a\" &&\n c.to_lowercase().to_string() != \"i\" &&\n c.to_lowercase().to_string() != \"u\" &&\n c.to_lowercase().to_string() != \"e\" &&\n c.to_lowercase().to_string() != \"o\" &&\n c.to_lowercase().to_string() != \"y\"\n }).collect();\n for i in inp.chars() {\n print!(\".{}\", i.to_lowercase());\n }\n}\n\nfn read_string() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"x\");\n buffer.trim().to_string()\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d13b3a3ee8faf3bc3c5b86e7d865c0f0", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut input = String::new();\n io::stdin().read_line(&mut input);\n for c in input.to_lowercase().chars(){\n match c{\n 'a' | 'o' | 'e' | 'i' | 'y'| 'u'|'\\r'|'\\n' =>{\n continue;\n }\n _ =>{\n print!(\".{}\", c);\n }\n }\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "bccf9cff33d11d6dd97e67e9349ad483", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn main() {\n let stdin = io::stdin();\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n s = s.trim().to_string();\n \n let mut r = String::new();\n\n for c in s.chars() {\n let mut a = c;\n a.make_ascii_lowercase();\n if \"aoyeui\".contains(a) {\n continue;\n } else {\n r.push('.');\n r.push(a);\n }\n }\n\n println!(\"{}\", r);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "15ad392dad70c58e5c53567a8ed55071", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\n\nfn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut vowels = HashSet::new();\n for c in b\"aeiouy\".iter() {\n vowels.insert(c);\n }\n for c in s.trim().to_lowercase().bytes().filter(|c| !vowels.contains(c)) {\n print!(\".{}\", c as char);\n }\n println!(\"\");\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "409ab934da40b7d898d790658c3a5e7b", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 998_244_353;\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> ModInt {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> ModInt {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> ModInt {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> ModInt {\n if self.0 == 0 {self} else {ModInt(MOD - self.0)}\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(v: u32) -> ModInt {\n ModInt(v % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s;\n }\n s = s * s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n n: usize,\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n n: n,\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n}\n\n// ---------- end Precalc ----------\n// ---------- begin NTT ----------\nfn ntt(f: &mut [ModInt]) {\n let n = f.len();\n assert!(n.count_ones() == 1);\n let len = n.trailing_zeros() as usize;\n for i in 1..(n - 1){\n let mut x = i;\n let mut j = 0;\n for _ in 0..len {\n j = (j << 1) | (x & 1);\n x >>= 1;\n }\n if i < j {\n f.swap(i, j);\n }\n }\n for k in 0..(n.trailing_zeros() as usize) {\n let m = 1 << k;\n let z = ModInt(3).pow((MOD - 1) >> (k + 1) as u32);\n for f in f.chunks_mut(2 * m) {\n let mut q = ModInt::one();\n let (x, y) = f.split_at_mut(m);\n for (x, y) in x.iter_mut().zip(y.iter_mut()) {\n let a = *x;\n let b = q * *y;\n *x = a + b;\n *y = a - b;\n q *= z;\n }\n }\n }\n}\n\nfn intt(f: &mut [ModInt]) {\n ntt(f);\n f[1..].reverse();\n let ik = ModInt(f.len() as u32).inv();\n for f in f.iter_mut() {\n *f *= ik;\n }\n}\n\nfn multiply(a: &[ModInt], b: &[ModInt]) -> Vec {\n let n = a.len() + b.len() - 1;\n let mut k = 1;\n while k < n {\n k *= 2;\n }\n assert!(k <= (1 << 23));\n let mut f = Vec::with_capacity(k);\n let mut g = Vec::with_capacity(k);\n f.extend_from_slice(a);\n f.resize(k, ModInt::zero());\n ntt(&mut f);\n g.extend_from_slice(b);\n g.resize(k, ModInt::zero());\n ntt(&mut g);\n for (f, g) in f.iter_mut().zip(g.iter()) {\n *f *= *g;\n }\n intt(&mut f);\n f.truncate(n);\n f\n}\n\n// ---------- end NTT ----------\n\nfn calc(n: usize, p: ModInt, k: usize) -> Vec {\n if n == 1 {\n let mut ans = vec![ModInt::one()];\n for _ in 1..=k {\n ans.push(p);\n }\n ans\n } else if n % 2 == 1 {\n let mut dp = calc(n - 1, p, k);\n let mut v = calc(1, p, k);\n let pc = Precalc::new(2 * k);\n for i in 0..=k {\n dp[i] *= pc.ifact(i);\n v[i] *= pc.ifact(i);\n }\n let mut ans = multiply(&dp, &v);\n for i in 0..=k {\n ans[i] *= pc.fact(i);\n }\n ans.truncate(k + 1);\n ans\n } else {\n let mut dp = calc(n / 2, p, k);\n let pc = Precalc::new(2 * k);\n for i in 0..=k {\n dp[i] *= pc.ifact(i);\n }\n let mut ans = multiply(&dp, &dp);\n for i in 0..=k {\n ans[i] *= pc.fact(i);\n }\n ans.truncate(k + 1);\n ans\n }\n}\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let n: usize = it.next().unwrap().parse().unwrap();\n let m: u32 = it.next().unwrap().parse().unwrap();\n let k: usize = it.next().unwrap().parse().unwrap();\n let ans = calc(n, ModInt(m).inv(), k);\n println!(\"{}\", ans[k]);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "1e6823bd40b16ab863693d819a255eaa", "src_uid": "e6b3e559b5fd4e05adf9f1cd1b22126b", "difficulty": 2600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by https://atcoder.jp/contests/arc093/submissions/3968098\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData }\n impl ModInt {\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n pub fn pow(self, mut e: i64) -> Self {\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl>> Add for ModInt {\n type Output = Self;\n fn add(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Sub for ModInt {\n type Output = Self;\n fn sub(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Mul for ModInt {\n type Output = Self;\n fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }\n }\n impl>> AddAssign for ModInt {\n fn add_assign(&mut self, other: T) { *self = *self + other; }\n }\n impl>> SubAssign for ModInt {\n fn sub_assign(&mut self, other: T) { *self = *self - other; }\n }\n impl>> MulAssign for ModInt {\n fn mul_assign(&mut self, other: T) { *self = *self * other; }\n }\n impl Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self { ModInt::new(0) - self }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl From for ModInt {\n fn from(x: i64) -> Self { Self::new(x) }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place, verified as NTT only)\n/// R: Ring + Copy\n/// Verified by: https://codeforces.com/contest/1096/submission/47672373\nmod fft {\n use std::ops::*;\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &mut [R], zeta: R, one: R)\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n assert!(n.is_power_of_two());\n {\n let mut i = 0;\n for j in 1 .. n - 1 {\n let mut k = n >> 1;\n loop {\n i ^= k;\n if k <= i { break; }\n k >>= 1;\n }\n if j < i { f.swap(i, j); }\n }\n }\n let mut zetapow = Vec::new();\n {\n let mut m = 1;\n let mut cur = zeta;\n while m < n {\n zetapow.push(cur);\n cur = cur * cur;\n m *= 2;\n }\n }\n let mut m = 1;\n while m < n {\n let base = zetapow.pop().unwrap();\n let mut r = 0;\n while r < n {\n let mut w = one;\n for s in r .. r + m {\n let u = f[s];\n let d = f[s + m] * w;\n f[s] = u + d;\n f[s + m] = u - d;\n w = w * base;\n }\n r += 2 * m;\n }\n m *= 2;\n }\n }\n}\n\nuse fft::*;\n\n// Depends on ModInt.rs\nfn fact_init(w: usize) -> (Vec, Vec) {\n let mut fac = vec![ModInt::new(1); w];\n let mut invfac = vec![0.into(); w];\n for i in 1 .. w {\n fac[i] = fac[i - 1] * i as i64;\n }\n invfac[w - 1] = fac[w - 1].inv();\n for i in (0 .. w - 1).rev() {\n invfac[i] = invfac[i + 1] * (i as i64 + 1);\n }\n (fac, invfac)\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n l: i64,\n }\n const N: usize = 4096;\n let (fac, invfac) = fact_init(N);\n\n let mut p = vec![ModInt::new(0); N];\n let mut q = vec![ModInt::new(0); N];\n p[1] = ModInt::new(2);\n p[2] = -ModInt::new(2);\n q[0] = ModInt::new(1);\n q[1] = -ModInt::new(2);\n q[2] = ModInt::new(2);\n\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n transform(&mut p, zeta, ModInt::new(1));\n transform(&mut q, zeta, ModInt::new(1));\n\n let mut ans = vec![ModInt::new(0); N];\n let mut coef = vec![ModInt::new(0); N];\n for i in k..n + 1 {\n coef[i] = fac[n] * invfac[n - i] * invfac[i];\n }\n for j in 0..N {\n let mut pp = p[j].pow(k as i64);\n let mut qp = q[j].pow((n - k) as i64);\n let mut qinv = q[j].inv();\n for i in k..n + 1 {\n let coef = coef[i];\n ans[j] += pp * qp * coef;\n pp *= p[j];\n qp *= qinv;\n }\n }\n transform(&mut ans, zeta.inv(), ModInt::new(1));\n // eprintln!(\"ans = {:?}\", &ans[0..10]);\n let mut tot = ModInt::new(0);\n for i in 0..2 * n + 1 {\n tot += ans[i] * ModInt::new((i + 1) as i64).inv();\n }\n tot *= ModInt::new(N as i64).inv();\n puts!(\"{}\\n\", tot * l);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["probabilities", "math", "dp", "combinatorics"], "code_uid": "8225ce694aa6eb5f6171cdad9aed2fbd", "src_uid": "c9e79e83928d5d034123ebc3b2f5e064", "difficulty": 2600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 998_244_353;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\n/* \nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n*/\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n pub fn comb(n: u32, k: u32) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n let k = std::cmp::min(k, n - k);\n let mut nu = ModInt::one();\n let mut de = ModInt::one();\n for i in 0..k {\n nu *= ModInt(n - i);\n de *= ModInt(i + 1);\n }\n nu * de.inv()\n }\n}\n\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end ModInt ----------\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let n: usize = it.next().unwrap().parse().unwrap();\n let k: usize = it.next().unwrap().parse().unwrap();\n let l: u32 = it.next().unwrap().parse().unwrap();\n let pc = Precalc::new(2 * n + 1);\n let mut dp = vec![ModInt::zero(); 2 * n + 1];\n dp[0] = ModInt::one();\n for i in 0..n {\n for j in (0..=(2 * i)).rev() {\n let p = dp[j];\n dp[j + 2] -= ModInt(2) * p;\n dp[j + 1] += ModInt(2) * p;\n dp[j] = ModInt(0);\n }\n }\n let mut ans = ModInt::zero();\n for i in (k..=n).rev() {\n let mut eval = ModInt::zero();\n for j in 0..=(2 * n) {\n eval += dp[j] * pc.inv(j + 1)\n }\n ans += pc.comb(n, i) * eval;\n let f = ModInt(2).inv();\n let mut next = vec![ModInt::zero(); 2 * n + 1];\n for j in (2..=(2 * n)).rev() {\n let v = dp[j];\n dp[j - 1] += v;\n next[j - 2] = -v * f;\n }\n dp = next;\n for j in (0..=(2 * (n - 1))).rev() {\n let v = dp[j];\n dp[j + 2] += ModInt(2) * v;\n dp[j + 1] -= ModInt(2) * v;\n }\n }\n ans *= ModInt(l);\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["probabilities", "math", "dp", "combinatorics"], "code_uid": "88214efe7adc776f4c524b57a033a5bb", "src_uid": "c9e79e83928d5d034123ebc3b2f5e064", "difficulty": 2600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn gcd( aa: u64, bb: u64 ) -> u64 {\n let (mut a,mut b) = if aa > bb {\n (bb,aa)\n } else {\n (aa,bb)\n };\n\n loop {\n let r = b % a;\n if r == 0 {\n break;\n }\n b = a;\n a = r;\n }\n a\n}\n\nfn main() -> () {\n\n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n handle.read_to_string(&mut buffer).expect(\"stdin\");\n\n let mut arr : Vec<_> = buffer.split_whitespace().map(|x| x.parse::().unwrap() ).collect();\n\n let a = arr[0] as u64;\n let b = arr[1] as u64;\n let mut x = arr[2] as u64;\n let mut y = arr[3] as u64;\n\n let d = gcd(x,y);\n\n // println!(\"d:{}\",d);\n \n x = x / d;\n y = y / d;\n\n // println!(\"{},{}\",x,y);\n \n let num_numer = a / x;\n let num_denom = b / y;\n use std::cmp;\n let mm = cmp::min( num_numer, num_denom );\n println!(\"{}\",mm);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "50072c6eec4bba1d88ceabce0c31ed20", "src_uid": "907ac56260e84dbb6d98a271bcb2d62d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn get_line() -> String {\n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input)\n\t\t.expect(\"\");\n\n\tString::from(input.trim())\n}\n\nfn main() {\n\tlet s = get_line();\n\n\tlet mut r = String::new();\n\tfor (i, c) in s.chars().enumerate() {\n\t\tlet d = c.to_digit(10).unwrap();\n\n\t\tif (i == 0 && d >= 5 && d < 9) || (i != 0 && d >= 5) {\n\t\t\tr.push(std::char::from_digit((9-d) as u32, 10).unwrap());\n\t\t} else {\n\t\t\tr.push(c);\n\t\t}\n\t}\n\n\tprintln!(\"{}\", r);\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "2070693f315d0bf4ca4aadae3449b4d8", "src_uid": "d5de5052b4e9bbdb5359ac6e05a18b61", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut num: u64 = scan.next();\n let mut result: u64 = 0;\n let mut position: u64 = 1;\n while num/10 > 0 {\n let dig = num%10;\n result += dig.min(9-dig)*position;\n position *= 10;\n num /= 10;\n }\n if num == 9 {\n result += 9*position;\n } else {\n let dig = num%10;\n result += dig.min(9-dig)*position;\n }\n\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "2966284897f5fd50b30e1a79e6dca567", "src_uid": "d5de5052b4e9bbdb5359ac6e05a18b61", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().bytes()\n .map(|value| value - '0' as u8)\n .enumerate()\n .map(|(position, value)| {\n match value {\n 9 => { if position == 0 { 9 } else { 0 } }\n 8 | 7 | 6 | 5 => { 9 - value }\n _ => value\n }\n })\n .for_each(|it| print!(\"{}\", it));\n println!()\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "6f4f386e8203199e55dd3b825b617744", "src_uid": "d5de5052b4e9bbdb5359ac6e05a18b61", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/514/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn min_possible_invert(n: u64) -> u64 {\n if n == 0 { return 0; }\n let (top, bot) = (n / 10, n % 10);\n let inv = 9 - bot;\n if top == 0 && inv == 0 {\n bot\n } else {\n min_possible_invert(top) * 10 + std::cmp::min(bot, inv)\n }\n}\n\nfn main() {\n scanln!(x: u64);\n println!(\"{}\", min_possible_invert(x));\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "6f64e151a0799001bc1fd3c78d5e87d0", "src_uid": "d5de5052b4e9bbdb5359ac6e05a18b61", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let s = readln!();\n let z = s.chars().enumerate().map(|(i,c)|\n if i == 0 && c == '9' {\n c\n } else {\n min(c,((9u8 - (c as u8 - '0' as u8)) + ('0' as u8)) as char)\n }).collect::().chars().skip_while(|&c|c=='0').collect::();\n println!(\"{}\",if z.is_empty() { \"9\" } else { z.as_ref() });\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "d27917fd479f94044df29f09bf27caae", "src_uid": "d5de5052b4e9bbdb5359ac6e05a18b61", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n input.bs().iter().enumerate()\n .for_each(|(i,&c)| {\n let x = if c >= b'5' {\n if i > 0 || c < b'9' {\n b'0' + b'9' - c\n } else {\n c\n }\n } else {\n c\n };\n print!(\"{}\", x as char);\n });\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "01fecf6317d3bd9955d8fac1d9c64e57", "src_uid": "d5de5052b4e9bbdb5359ac6e05a18b61", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let n : i32 = s.trim().parse().unwrap();\n s.clear();\n for _i in 0..n {\n io::stdin().read_line(&mut s).unwrap();\n }\n let a : Vec = s.split_whitespace().map(|s| s.parse().unwrap()).collect();\n let mut cnt = 0;\n for i in 0..n {\n for j in 0..n {\n if a[(i*2) as usize] == a[(j*2+1) as usize] {\n cnt += 1;\n }\n }\n }\n println!(\"{}\", cnt);\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "36352ab8a9524fb096f813c3bf507c0f", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\nuse std::collections::HashSet;\n\nfn read_line(stdin: &Stdin, line: &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s: &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_ts(stdin: &Stdin, ts: &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\npub fn read_i64(stdin: &Stdin) -> i64 {\n let mut line = String::new();\n read_line(&stdin, &mut line);\n match line.trim().parse() {\n Ok(i) => i,\n Err(e) => {\n panic!(\"Could not read i64!\");\n }\n }\n}\n\nstruct Team {\n a: i32,\n b: i32,\n}\n\nfn main() {\n let stdin = io::stdin();\n let n = read_i64(&stdin) as usize;\n let mut k: Vec = vec![];\n for i in 0..n {\n let mut v= vec![];\n read_ts(&stdin, &mut v);\n k.push(Team { a: v[0], b: v[1] });\n }\n let mut s = 0;\n for i in 0..n {\n for j in 0..n {\n if k[i].a == k[j].b {\n s += 1;\n }\n }\n }\n println!(\"{}\", s);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "4a734fe0a9c501131957ec228468b0d6", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n\n let mut cnth = vec![0u32; 101];\n let mut cntg = vec![0u32; 101];\n let (n, ) = R!(usize);\n\n let mut ans = 0;\n for _ in 0..n {\n let (h, g) = R!(usize, usize);\n ans += cnth[g] + cntg[h];\n cnth[h] += 1;\n cntg[g] += 1;\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "96c775d671588df71207c8a3cb81f36d", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\n\nfn input() -> u8 {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n}\n\ntype Pair = (u8, u8);\nfn input_pair() -> Pair {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let buf: Vec = buf\n .trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect();\n (buf[0], buf[1])\n}\n\nfn main() {\n let mut home = HashMap::new();\n let mut away = HashMap::new();\n\n for _ in 0..input() {\n let (h, a) = input_pair();\n home.entry(h).and_modify(|e| *e += 1).or_insert(1);\n away.entry(a).and_modify(|e| *e += 1).or_insert(1);\n }\n\n println!(\n \"{}\",\n home.iter()\n .filter(|h| away.contains_key(&h.0))\n .fold(0, |a, (k, v)| a + v * away[k])\n );\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "bad06c3c73ef4e68e94f2f2d5790cd95", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect()\n}\n\n#[derive(PartialEq, PartialOrd)]\nstruct Team {\n home_uniform: i32,\n guest_uniform: i32,\n}\n\nfn main() {\n let n = readln()[0];\n\n let mut teams: Vec = Vec::new();\n\n for _ in 0..n {\n let input = readln();\n teams.push(Team {\n home_uniform: input[0],\n guest_uniform: input[1],\n })\n }\n\n let mut ans = 0;\n for home_team in &teams {\n for guest_team in &teams {\n if home_team != guest_team && home_team.home_uniform == guest_team.guest_uniform {\n ans += 1;\n }\n }\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "1dbb22cbbee9e02989badc3f01eac38b", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i() as usize;\n let mut a = Vec::with_capacity(n);\n let mut b = Vec::with_capacity(n);\n for _ in 0..n {\n a.push(input.i());\n b.push(input.i());\n }\n let sol = a.iter()\n .map(|x| b.iter().filter(|&y| x == y).count()).sum::();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "a4218041fa52c72c10dd9a6fa8d6da14", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let n: usize = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim_end().parse().unwrap()\n };\n\n let v = {\n let mut v = vec![];\n for _ in 0..n {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let mut ws = buf.split_whitespace();\n let a: usize = ws.next().unwrap().parse().unwrap();\n let b: usize = ws.next().unwrap().parse().unwrap();\n v.push((a, b));\n }\n v\n };\n\n let mut ans = 0;\n for i in 0..n {\n for j in 0..n {\n if i == j {\n continue;\n }\n if v[i].0 == v[j].1 {\n ans += 1;\n }\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "87352f3db73ef0c66eb151f7dac908ed", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn cols_frequency(cols : &Vec, freq : &mut Vec<(u64, u64)>) {\n let mut prev_col = cols[0];\n let mut f = 1;\n for i in 1 .. cols.len() {\n let col = cols[i];\n if col == prev_col {\n f = f + 1;\n } else {\n freq.push((prev_col, f));\n f = 1;\n prev_col = col;\n }\n }\n freq.push((prev_col, f));\n}\n\nfn host_guest(home_freq : &Vec<(u64, u64)>, away_freq : &Vec<(u64, u64)>) -> u64 {\n let home_len = home_freq.len();\n let away_len = away_freq.len();\n let mut num_clashes = 0;\n let mut i = 0;\n let mut j = 0;\n loop {\n if (i >= home_len) || (j >= away_len) {\n break;\n } else {\n let (h, f_h) = home_freq[i];\n let (a, f_a) = away_freq[j];\n if h == a {\n num_clashes = num_clashes + (f_h * f_a);\n i = i + 1;\n j = j + 1;\n } else if h > a {\n j = j + 1;\n } else {\n i = i + 1;\n }\n }\n }\n num_clashes\n}\n\nfn main() {\n let stdin = io::stdin();\n let n : u64 = read_t(&stdin);\n let mut home_cols = vec![];\n let mut away_cols = vec![];\n for _ in 0 .. n {\n let mut cols = vec![];\n read_ts(&stdin, &mut cols);\n home_cols.push(cols[0]);\n away_cols.push(cols[1]);\n }\n home_cols.sort();\n away_cols.sort();\n let mut home_freq = vec![];\n let mut away_freq = vec![];\n cols_frequency(&home_cols, &mut home_freq);\n cols_frequency(&away_cols, &mut away_freq);\n println!(\"{}\", host_guest(&home_freq, &away_freq));\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "e0e34d9d583ccc3b81d9d97ec4a7e371", "src_uid": "745f81dcb4f23254bf6602f9f389771b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let v: Vec = vec![1,0,1,2,9];\n let mut ri = ReadIn::new();\n let tp = ri.int2();\n let mut ans:i64 = 1;\n for kk in 2..tp.1+1 {\n ans += cal(tp.0 as i64, kk as i64) * v[(kk as usize)] ;\n }\n println!(\"{}\", ans)\n}\n\nfn cal(n: i64, k: i64) -> i64{\n let mut up: i64 = 1;\n let mut down: i64 = 1;\n for kk in 0..k {\n up = up * (n - kk);\n down = down * (1 + kk);\n }\n up / down\n}\n\nuse std::iter::Map;\nuse std::str::SplitWhitespace;\nuse std::io::stdin;\nuse std::mem::forget;\n\npub struct ReadIn(pub String);\n\nimpl ReadIn {\n pub fn new() -> ReadIn {\n ReadIn(String::new())\n }\n fn read_i32(s: &str) -> i32 {\n s.parse().unwrap()\n }\n pub fn read_line(&mut self) {\n self.0.clear();\n forget(stdin().read_line(&mut self.0));\n }\n pub fn ints(&mut self) -> Map i32> {\n self.read_line();\n self.0.split_whitespace().map(ReadIn::read_i32)\n }\n pub fn int(&mut self) -> i32 {\n self.ints().next().unwrap()\n }\n pub fn int2(&mut self) -> (i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap())\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "2306860da6d28985c1a708545c2b66fc", "src_uid": "96d839dc2d038f8ae95fc47c217b2e2f", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let (n, k) = get!(u64, u64);\n\n let mut ans = 1;\n\n if k > 1 {\n for i in 2..k + 1 {\n let u = (n - i + 1..n + 1).fold(1, |a, b| a * b);\n let d = (1..i + 1).fold(1, |a, b| a * b);\n\n let c = u / d;\n\n ans += c * [1, 2, 9][(i - 2) as usize];\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "4a12e5d60a2cbf12d76bbfd6cdf27225", "src_uid": "96d839dc2d038f8ae95fc47c217b2e2f", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (a,b) = readln!(i32,i32);\n let mut live = a;\n let mut dead = 0;\n let mut res = 0;\n while live>0 {\n res += live;\n dead += live;\n live = 0;\n live += (dead/b);\n dead %= b;\n }\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "24df0eb5f2da47f5fd184840189418dc", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let input = readln();\n\n let mut count_new_candles = input[0];\n let mut count_old_candles = 0;\n let b = input[1];\n\n let mut total_time = 0;\n while count_new_candles > 0 {\n total_time += 1;\n count_new_candles -= 1;\n count_old_candles += 1;\n if count_old_candles == b {\n count_new_candles += 1;\n count_old_candles = 0;\n }\n }\n\n println!(\"{}\", total_time);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7ea8c94b419223b88f3d4a035a173491", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn num_days(n : u64, m : u64) -> u64 {\n let mut s = n;\n let mut x = n;\n loop {\n if x < m {\n break;\n } else {\n let x_div_m = x / m;\n let x_mod_m = x % m;\n s = s + x_div_m;\n x = x_div_m + x_mod_m;\n }\n }\n s\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut n_m : Vec = vec![];\n read_ts(&stdin, &mut n_m);\n let n = n_m[0];\n let m = n_m[1];\n println!(\"{}\", num_days(n, m));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f0d8e457d238a3cc8a25946e7d5f01e8", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (i64, i64) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\n\nfn main() {\n let (mut a, b) = read_line_pair();\n let mut remain = 0;\n\n let mut sum = 0;\n while a > 0 {\n sum += a;\n remain += a;\n a = remain / b;\n remain = remain % b;\n }\n\n println!(\"{}\", sum);\n \n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b41953a8326a155eed53742a9ed6b85d", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn main() {\n let mut scan = Scan::new();\n let a = scan.next::();\n let b = scan.next::();\n let mut result = a;\n let mut current = a;\n while current>=b {\n result += current / b;\n current = current / b + current % b;\n }\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6389e39fd00c30680566265962b657c2", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n\n let mut iter = input.split_whitespace();\n\n let a: u16 = iter.next().unwrap().trim().parse().unwrap();\n let b: u16 = iter.next().unwrap().trim().parse().unwrap();\n\n let mut hour_count: i32 = 0;\n\n if a >= b {\n let mut candle_count = a as i16;\n\n while candle_count > 0 {\n if (candle_count - (b as i16)) >= 0 {\n candle_count -= b as i16;\n hour_count += b as i32;\n candle_count += 1;\n } else {\n hour_count += candle_count as i32;\n candle_count = 0;\n }\n }\n } else {\n hour_count += a as i32;\n }\n\n println!(\"{}\", hour_count);\n}\n\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7eb83ec8b0c0248eb1781b67643daa5a", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (a, b) = R!(usize, usize);\n let mut ans: usize = 0;\n let mut cur: usize = a;\n let mut curu: usize = 0;\n while cur > 0 {\n ans += cur;\n curu += cur;\n cur = curu / b;\n curu %= b;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e56e3f2e7074b4b70f95b54d03a8bb21", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Pair = (i32, i32);\nfn input_pair() -> Pair {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let buf: Vec = buf.trim().split_whitespace().map(|elem| elem.parse().unwrap()).collect();\n (buf[0], buf[1])\n}\n\nfn solve(n: i32, m: i32, r: i32) -> i32 {\n match n {\n 0 => 0,\n n => n + solve((n+r) / m, m, (n+r) % m)\n }\n}\n\nfn main() {\n let (n, m) = input_pair();\n println!(\"{}\", solve(n, m, 0));\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2a6a23438e795e30ed01fb93cba75250", "src_uid": "a349094584d3fdc6b61e39bffe96dece", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nfn run() {\r\n input! {\r\n s: bytes,\r\n }\r\n if &s == &[b'_'] {\r\n println!(\"1\");\r\n return;\r\n }\r\n let mut x = 1;\r\n if s.contains(&b'X') {\r\n x = 10;\r\n }\r\n let mut ans = 0u64;\r\n for v in 0..x {\r\n let mut s = s.clone();\r\n s.iter_mut().for_each(|s| {\r\n if *s == b'X' {\r\n *s = b'0' + v as u8;\r\n }\r\n });\r\n if s[0] == b'0' && s.len() > 1 {\r\n continue;\r\n }\r\n let mut dp = [0; 25];\r\n dp[0] = 1;\r\n for (i, s) in s.iter().enumerate() {\r\n if *s == b'_' {\r\n let mut s = 0;\r\n if i == 0 {\r\n s = 1;\r\n }\r\n let mut next = [0; 25];\r\n for d in s..10 {\r\n for (i, dp) in dp.iter().enumerate() {\r\n next[(i * 10 + d) % 25] += *dp;\r\n }\r\n }\r\n dp = next;\r\n } else {\r\n assert!(b'0' <= *s && *s <= b'9');\r\n let k = (*s - b'0') as usize;\r\n let mut next = [0; 25];\r\n for d in k..(k + 1) {\r\n for (i, dp) in dp.iter().enumerate() {\r\n next[(i * 10 + d) % 25] += *dp;\r\n }\r\n }\r\n dp = next;\r\n }\r\n }\r\n ans += dp[0];\r\n }\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "dfs and similar"], "code_uid": "f5a33b0eef8fc2b2612bf969de53e88a", "src_uid": "4a905f419550a6c839992b40f1617af3", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\n\nfn get_word() -> String {\n let stdin = std::io::stdin();\n let mut stdin=stdin.lock();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn main() {\n let s: Vec = get_word().chars().collect();\n let mut ans = 0;\n for i in 0..4_000_000 {\n let t: Vec<_> = format!(\"{}\", 25 * i).chars().collect();\n if s.len() == t.len() {\n let mut x = 0;\n let mut ok = true;\n for i in 0..s.len() {\n if s[i] != t[i] && s[i] != '_' && s[i] != 'X' {\n ok = false;\n break;\n }\n if s[i] == 'X' {\n let idx = t[i] as u8 - b'0';\n x |= 1 << idx;\n }\n }\n if ok && (x & -x) == x {\n ans += 1;\n }\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "dfs and similar"], "code_uid": "b20a265736a8deb255546cb421b6e594", "src_uid": "4a905f419550a6c839992b40f1617af3", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\nuse std::collections::*;\n\nstruct IO(R, std::io::BufWriter);\n\nimpl IO {\n pub fn new(r: R, w: W) -> IO {\n IO(r, std::io::BufWriter::new(w))\n }\n pub fn write(&mut self, s: S) {\n use std::io::Write;\n self.1.write_all(s.to_string().as_bytes()).unwrap();\n }\n pub fn writeln(&mut self, s: S) {\n self.write(format!(\"{}\\n\", s.to_string()));\n }\n pub fn writevec(&mut self, v: &[T]) {\n let s = v\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(\" \");\n self.writeln(format!(\"{} \", &s));\n }\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let buf = self\n .0\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn usize(&mut self) -> usize {\n self.read::()\n }\n pub fn i32(&mut self) -> i32 {\n self.read::()\n }\n pub fn i64(&mut self) -> i64 {\n self.read::()\n }\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn vecn(&mut self) -> Vec {\n let n: usize = self.read();\n self.vec(n)\n }\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n\nfn pow(mut a: i64, mut b: i64) -> i64 {\n let mut r = 1;\n loop {\n if b & 1 == 1 {\n r *= a;\n }\n b >>= 1;\n if b == 0 {\n break;\n }\n a *= a;\n }\n r\n}\n\nfn solve_one(s: Vec) -> i64 {\n if [\"__\".to_owned(), \"_X\".to_owned()].contains(&s.iter().collect::()) {\n return 3;\n }\n if s.len() == 1 {\n return if \"0_X\".contains(s[0]) { 1 } else { 0 };\n }\n if s[0] == '0' {\n return 0;\n }\n\n let l = s[s.len() - 1];\n let k = s[s.len() - 2];\n\n let mut combs = HashMap::new();\n\n if !\"05_X\".contains(l) {\n return 0;\n }\n if l == '0' || l == '_' {\n if !\"05_X\".contains(k) {\n if l != '_' {\n return 0;\n }\n } else if k == 'X' {\n *combs.entry(Some(5)).or_insert(0) += 1;\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += 1;\n }\n } else {\n *combs.entry(None).or_insert(0) += if k == '_' { 2 } else { 1 };\n }\n }\n if l == '5' || l == '_' {\n if !\"27_X\".contains(k) {\n if l != '_' {\n return 0;\n }\n } else if k == 'X' {\n *combs.entry(Some(2)).or_insert(0) += 1;\n *combs.entry(Some(7)).or_insert(0) += 1;\n } else {\n *combs.entry(None).or_insert(0) += if k == '_' { 2 } else { 1 };\n }\n }\n if l == 'X' {\n if k == '0' || k == '5' {\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += 1;\n }\n } else if k == '2' || k == '7' {\n *combs.entry(Some(5)).or_insert(0) += 1;\n } else if k == '_' {\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += if s.len() == 2 { 1 } else { 2 };\n }\n *combs.entry(Some(5)).or_insert(0) += 2;\n } else if k == 'X' {\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += 1;\n }\n } else {\n return 0;\n }\n }\n\n let b = s[..s.len() - 2].to_vec();\n let u = b.iter().filter(|&&c| c == '_').count();\n let x = b.iter().filter(|&&c| c == 'X').count();\n\n let mut count = 0;\n\n for (xv, cnt) in combs {\n let a = match xv {\n Some(p) => u,\n None => u + if x > 0 { 1 } else { 0 },\n } as i64;\n\n let mut ch = pow(10, a);\n if s[0] == '_' && s.len() > 2 || xv.is_none() && s[0] == 'X' {\n ch = ch / 10 * 9;\n }\n\n count += ch * cnt;\n }\n\n count\n}\n\n// Wtf is this.......\n\npub fn main() {\n let mut sc = IO::new(std::io::stdin(), std::io::stdout());\n let ans = solve_one(sc.chars());\n sc.writeln(ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "dfs and similar"], "code_uid": "69cb4ea50e406615785226ec4cce9e93", "src_uid": "4a905f419550a6c839992b40f1617af3", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\nuse std::collections::*;\n\nstruct IO(R, std::io::BufWriter);\n\nimpl IO {\n pub fn new(r: R, w: W) -> IO {\n IO(r, std::io::BufWriter::new(w))\n }\n pub fn write(&mut self, s: S) {\n use std::io::Write;\n self.1.write_all(s.to_string().as_bytes()).unwrap();\n }\n pub fn writeln(&mut self, s: S) {\n self.write(format!(\"{}\\n\", s.to_string()));\n }\n pub fn writevec(&mut self, v: &[T]) {\n let s = v\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(\" \");\n self.writeln(format!(\"{} \", &s));\n }\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let buf = self\n .0\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn usize(&mut self) -> usize {\n self.read::()\n }\n pub fn i32(&mut self) -> i32 {\n self.read::()\n }\n pub fn i64(&mut self) -> i64 {\n self.read::()\n }\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn vecn(&mut self) -> Vec {\n let n: usize = self.read();\n self.vec(n)\n }\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n\nfn pow(mut a: i64, mut b: i64) -> i64 {\n let mut r = 1;\n loop {\n if b & 1 == 1 {\n r *= a;\n }\n b >>= 1;\n if b == 0 {\n break;\n }\n a *= a;\n }\n r\n}\n\nfn solve_one(s: Vec) -> i64 {\n if [\"__\".to_owned(), \"_X\".to_owned()].contains(&s.iter().collect::()) {\n return 3;\n }\n if s.len() == 1 {\n return if \"0_X\".contains(s[0]) { 1 } else { 0 };\n }\n if s[0] == '0' {\n return 0;\n }\n\n let l = s[s.len() - 1];\n let k = s[s.len() - 2];\n\n // println!(\"l: {}, k: {}\", l, k);\n\n let mut combs = HashMap::new();\n\n if !\"05_X\".contains(l) {\n return 0;\n }\n if l == '0' || l == '_' {\n if !\"05_X\".contains(k) {\n if l != '_' {\n return 0;\n }\n } else if k == 'X' {\n *combs.entry(Some(5)).or_insert(0) += 1;\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += 1;\n }\n } else {\n *combs.entry(None).or_insert(0) += if k == '_' { 2 } else { 1 };\n }\n }\n if l == '5' || l == '_' {\n if !\"27_X\".contains(k) {\n if l != '_' {\n return 0;\n }\n } else if k == 'X' {\n *combs.entry(Some(2)).or_insert(0) += 1;\n *combs.entry(Some(7)).or_insert(0) += 1;\n } else {\n *combs.entry(None).or_insert(0) += if k == '_' { 2 } else { 1 };\n }\n }\n if l == 'X' {\n if k == '0' || k == '5' {\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += 1;\n }\n } else if k == '2' || k == '7' {\n *combs.entry(Some(5)).or_insert(0) += 1;\n } else if k == '_' {\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += if s.len() == 2 { 1 } else { 2 };\n }\n *combs.entry(Some(5)).or_insert(0) += 2;\n } else if k == 'X' {\n if s[0] != 'X' {\n *combs.entry(Some(0)).or_insert(0) += 1;\n }\n } else {\n return 0;\n }\n }\n\n let b = s[..s.len() - 2].to_vec();\n let u = b.iter().filter(|&&c| c == '_').count();\n let x = b.iter().filter(|&&c| c == 'X').count();\n\n // println!(\"{:?}\", combs);\n\n // let c = pow(10, (u + if) as i64);\n\n let mut count = 0;\n\n for (xv, cnt) in combs {\n let a = match xv {\n Some(p) => u,\n None => u + if x > 0 { 1 } else { 0 },\n } as i64;\n\n let mut ch = pow(10, a);\n if s[0] == '_' && s.len() > 2 || xv == None && s[0] == 'X' {\n ch = ch / 10 * 9;\n }\n\n count += ch * cnt;\n }\n\n count\n}\n\npub fn main() {\n let mut sc = IO::new(std::io::stdin(), std::io::stdout());\n let ans = solve_one(sc.chars());\n sc.writeln(ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "dfs and similar"], "code_uid": "02b12df6368ac8c92ca91bd3fcf67344", "src_uid": "4a905f419550a6c839992b40f1617af3", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::mem;\nuse std::io;\nuse std::string;\nuse std::cmp::*;\nuse std::collections::*;\n\nfn load() -> Vec {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let vec: Vec<&str> = line.split(\" \").collect();\n let mut data : Vec = Vec::new();\n for i in vec {\n let el : i64 = i.trim().parse().unwrap();\n data.push(el);\n }\n data\n}\nfn maxv(v : &Vec) -> i64{\n let mut s=v[0];\n for i in v {s=max(s,*i);}\n return s;\n}\nfn minv(v : &Vec) -> i64{\n let mut s=v[0];\n for i in v {s=min(s,*i);}\n return s;\n}\n\nfn main() {\n let a = load();\n let n=a[0];\n let k=a[1];\n let t=240-k;\n let mut sum = 0;\n let mut last = 0;\n for i in 1..n+1 {\n sum+=i*5;\n if sum > t {break;}\n last = i;\n }\n println!(\"{}\", last);\n}\n// min, max\n// HashSet, insert, contains\n// Vec, len, sort\n// primitive retype: i as f64\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "2225f536c8c0d7d09b6dae10990d6646", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> std::io::Result<()> {\n let stdin = io::stdin();\n let mut input = String::new();\n stdin.read_line(&mut input)?;\n let problems_travel: Vec = input.trim().split(\" \").map(|x| x.parse::().unwrap()).collect();\n let mut minutes_left: i16 = 240 - problems_travel[1];\n for p in 1..=problems_travel[0] {\n if minutes_left - p * 5 < 0 {\n print!(\"{}\", p-1);\n break;\n } else if p == problems_travel[0] {print!(\"{}\",p);}\n else {\n minutes_left -= p * 5;\n }\n }\n\n Ok(())\n}\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "04a199d4647acc674bb41c183faec9bb", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(dead_code)]\nuse std::cmp::min;\nuse std::collections::HashMap;\nuse std::io;\nuse std::str::FromStr;\nuse std::io::Read;\n\nstruct Input {\n tokens: as IntoIterator>::IntoIter,\n read_all: bool,\n}\n\nimpl Input {\n pub fn new(read_all: bool) -> Input {\n if read_all {\n let mut all = String::new();\n io::stdin().read_to_string(&mut all).unwrap();\n let tokens: Vec = all.split_whitespace().map(|s| s.to_string()).collect();\n Input {\n tokens: tokens.into_iter(),\n read_all: true,\n }\n } else {\n Input {\n tokens: vec!().into_iter(),\n read_all: false,\n }\n }\n }\n\n fn refresh_next_line(&mut self) {\n if self.read_all {\n panic!();\n }\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let tokens: Vec = buf.split_whitespace().map(|s| s.to_string()).collect();\n self.tokens = tokens.into_iter();\n }\n\n fn next_impl(&mut self) -> String {\n loop {\n if let Some(next) = self.tokens.next() {\n return next.to_string();\n }\n self.refresh_next_line();\n }\n }\n\n pub fn next(&mut self) -> T where ::Err: std::fmt::Debug {\n let next_str = self.next_impl();\n next_str.parse().unwrap()\n }\n\n pub fn next_vec(&mut self, len: usize) -> Vec where ::Err: std::fmt::Debug {\n (0..len).map(|_i| self.next()).collect()\n }\n\n pub fn next_vec_read_len(&mut self) -> Vec where ::Err: std::fmt::Debug {\n let len = self.next();\n self.next_vec(len)\n }\n}\n\nfn main() {\n let mut input = Input::new(false);\n let n: i64 = input.next();\n let k: i64 = input.next();\n let mut time = 240 - k;\n let mut i = 1;\n while time >= i * 5 && i <= n {\n time -= i * 5;\n i += 1\n }\n println!(\"{}\", i - 1);\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "46a249e02caf1635b3e73ed085c75d76", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (n, k) = R!(usize, usize);\n let mut kk = k;\n let mut ans = 0;\n for i in 1..(n+1) {\n if i*5 + kk > 240 {\n break;\n } else {\n ans = i;\n kk += i*5;\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "562c5b87458c1cbe717c54b710549f03", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nenum Status {\n NotFound,\n Found(u32),\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let params: Vec = reads(sin);\n\n let n = params[0];\n let k = params[1];\n\n let time_limit = 240 - k;\n let mut time_spend = 0;\n\n let mut status = Status::NotFound;\n\n for i in 1..n + 1 {\n time_spend += 5 * i;\n if time_limit < time_spend {\n status = Status::Found(i - 1);\n break;\n }\n }\n\n let ans = match status {\n Status::Found(x) => x,\n Status::NotFound => n,\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "288b5b925971a4993c5c4327ffbd55a2", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{self, stdout, BufWriter, stdin, Write};\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n let n:i32 = scan.next();\n let mut k:i32 = 240 - scan.next::();\n let mut count = 0;\n for i in 1..n+1{\n if k - (5*i) < 0{break;} else {k -= 5*i; count += 1;} \n }\n writeln!(out, \"{}\", count).ok();\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "da7d372b90d22d350ff52483b4bb28db", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Pair = (u8, u8);\nfn input_pair() -> Pair {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let buf: Vec = buf.trim().split_whitespace().map(|elem| elem.parse().unwrap()).collect();\n (buf[0], buf[1])\n}\n\nfn main() {\n let (n, k) = input_pair();\n\n let mut time_left = 240 - k;\n let mut result = 0;\n\n for i in 1..=n {\n if 5 * i <= time_left {\n time_left -= 5*i;\n result += 1;\n } else {\n break;\n }\n }\n \n println!(\"{}\", result);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "e34ddd06e55b15f86b871760917a4298", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/750/A\nuse std::io;\n\nfn cumulative(n: i64) -> i64 {\n let mut sum = 0;\n for i in 1..n+1 {\n sum += i*5;\n }\n sum\n}\n\nfn main() {\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let words: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let n = words[0];\n let k = words[1];\n\n let mut left = 0;\n let mut right = n;\n\n while left <= right {\n let middle = (right+left)/2;\n if (cumulative(middle)+k) <= 240 {\n left = middle+1;\n } else {\n right = middle-1;\n }\n }\n println!(\"{}\", right);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "bbc20868488b5ddfc146b7afa7dece9b", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::collections::VecDeque;\n\nmacro_rules! input{\n ( $s: expr, $t:ty ) => {\n {\n $s.clear();\n let mut _stdin = stdin();\n _stdin.read_line(&mut $s).unwrap();\n $s.trim().parse::<$t>().unwrap()\n }\n };\n ( $s: expr, $($t:ty),* ) => {\n {\n $s.clear();\n let mut _stdin = stdin();\n _stdin.read_line(&mut $s).unwrap();\n let mut iterator = $s.trim().split_whitespace();\n let result = ($(iterator.next().unwrap().parse::<$t>().unwrap(),)*);\n assert!(iterator.next().is_none());\n result\n }\n };\n}\n\nconst LIM: usize = 20001;\n\nfn main() {\n let mut s = String::new();\n let (n, m) = input!(s, usize, usize);\n\n let mut memo = vec![-1; LIM];\n let mut queue = VecDeque::new();\n memo[n] = 0;\n queue.push_back(n);\n while let Some(i) = queue.pop_front() {\n if memo[m] != -1 {\n println!(\"{}\", memo[m]);\n return;\n }\n if 2 * i < LIM && memo[2 * i] == -1 {\n queue.push_back(2 * i);\n memo[2 * i] = memo[i] + 1;\n }\n if i > 0 && memo[i - 1] == -1 {\n queue.push_back(i - 1);\n memo[i - 1] = memo[i] + 1;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "8cadbfb3c284423ec23678690e66ca1a", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use std::io::{self, Read};\nuse std::collections::VecDeque;\n\nfn main() {\n let cin = std::io::stdin();\n let mut s = String::new();\n cin.read_line(&mut s).unwrap();\n let values = s\n .split_whitespace()\n .map(|x| x.parse::())\n .collect::, _>>()\n .unwrap();\n\n let n = values[0];\n let m = values[1];\n\n let mut visited: [i32; 100000] = [0; 100000];\n let mut queue = VecDeque::new();\n queue.push_back((n, 0));\n while !queue.is_empty() {\n if let Some((curr_val, curr_cost)) = queue.pop_front() {\n if visited[curr_val] == 1 {\n continue;\n }\n\n if curr_val == m {\n println!(\"{}\", curr_cost);\n return;\n }\n\n visited[curr_val] = 1;\n\n if curr_val - 1 > 0 {\n queue.push_back((curr_val - 1, curr_cost + 1));\n }\n\n if curr_val < 2 * m {\n queue.push_back((curr_val * 2, curr_cost + 1));\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "893632aa4eed0f0dba59a18a1800e53b", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn dfs_moves(acc: usize, current: usize, goal: usize, dist: &mut [usize;20000]) {\n if dist[current]<=acc { return; }\n dist[current] = acc;\n if current >= goal {\n dist[goal] = dist[goal].min(acc+current-goal);\n return;\n }\n dfs_moves(acc + 1, current*2, goal, dist);\n if current > 1 {\n dfs_moves(acc + 1, current-1, goal, dist);\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let m: usize = scan.next();\n if m<= n {\n println!(\"{}\", n - m);\n return;\n }\n let mut dist = [std::usize::MAX; 20000];\n dfs_moves(0, n, m, &mut dist);\n println!(\"{}\", dist[m]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "2806d01e94c0def2919518ff0da71dbd", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::min;\nuse std::collections::HashMap;\nuse std::collections::hash_map::Entry;\n\nfn explore(visited: &mut HashMap, start: i32, finish: i32, dist: i32) -> i32 {\n\tmatch visited.entry(start) {\n\t\tEntry::Occupied(mut o) => {\n\t\t\tif o.get() > &dist {\n\t\t\t\to.insert(dist);\n\t\t\t} else {\n\t\t\t\treturn std::i32::MAX;\n\t\t\t}\n\t\t},\n\n\t\tEntry::Vacant(v) => {\n\t\t\tv.insert(dist);\n\t\t}\n\t}\n\n\tif start >= finish {\n\t\tdist + start - finish\n\t} else if start == 1 {\n\t\texplore(visited, 2, finish, dist + 1)\n\t} else {\n\t\tmin(\n\t\t\texplore(visited, start - 1, finish, dist + 1),\n\t\t\texplore(visited, start * 2, finish, dist + 1)\n\t\t)\n\t}\n}\n\nfn main() {\n\tlet mut input = String::new();\n\tstdin().read_line(&mut input).unwrap();\n\t\n\tlet mut it = input.split_whitespace();\n\tlet n: i32 = it.next().unwrap().parse().unwrap();\n\tlet m: i32 = it.next().unwrap().parse().unwrap();\n\t\n\tlet mut map: HashMap = HashMap::new();\n\n\tlet res = explore(&mut map, n, m, 0);\n\tprintln!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "27bfea4cce374ee91125b3e3f4478fae", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const ARRAY_SIZE: usize = 20000;\n\nfn update_array(f: &mut [Option; ARRAY_SIZE], x: usize, m: usize, x_stack: &mut Vec) {\n if x == 0 {\n return;\n }\n\n if x >= ARRAY_SIZE {\n return;\n }\n\n let old_value: Option = f[x];\n let mut new_value: Option = old_value;\n if x == m {\n new_value = Some(0);\n } else {\n if x > 1 {\n let value_sub1: Option = f[x + 1];\n if let Some(value_sub1_real) = value_sub1 {\n if let Some(new_value_real) = new_value {\n if (value_sub1_real + 1) < new_value_real {\n new_value = Some(value_sub1_real + 1);\n }\n } else {\n new_value = Some(value_sub1_real + 1);\n }\n }\n }\n\n if (x % 2) == 0 {\n let value_mul2: Option = f[x / 2];\n if let Some(value_mul2_real) = value_mul2 {\n if let Some(new_value_real) = new_value {\n if (value_mul2_real + 1) < new_value_real {\n new_value = Some(value_mul2_real + 1);\n }\n } else {\n new_value = Some(value_mul2_real + 1);\n }\n }\n }\n }\n\n f[x] = new_value;\n\n if new_value != old_value {\n x_stack.push(x - 1);\n x_stack.push(x * 2);\n }\n}\n\nfn get_min_path_length(m: usize, n: usize) -> usize {\n if m > n {\n return m - n;\n }\n\n let mut f: [Option; ARRAY_SIZE] = [None; ARRAY_SIZE];\n\n let mut x_stack: Vec = vec![m];\n\n while let Some(x) = x_stack.pop() {\n update_array(&mut f, x, m, &mut x_stack);\n }\n\n return f[n].unwrap();\n}\n\n#[cfg(test)]\nmod tests {\n use super::get_min_path_length;\n\n #[test]\n fn test1() {\n assert_eq!(get_min_path_length(4, 6), 2);\n }\n #[test]\n fn test2() {\n assert_eq!(get_min_path_length(10, 1), 9);\n }\n #[test]\n fn test3() {\n assert_eq!(get_min_path_length(100, 196), 3);\n }\n}\n\nuse std::io::{stdin, stdout, BufRead, Write};\n\nfn main() {\n let stdin = stdin();\n let mut stdin_lock = stdin.lock();\n\n let mut values_string: String = String::new();\n stdin_lock.read_line(&mut values_string).unwrap();\n let values_vec: Vec = values_string\n .trim()\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n\n let m: usize = values_vec[0];\n let n: usize = values_vec[1];\n\n let result: usize = get_min_path_length(m, n);\n\n let stdout = stdout();\n let mut stdout_lock = stdout.lock();\n\n writeln!(stdout_lock, \"{}\", result).unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "f6324a22156294aaa785524dd2ebd920", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\nfn main() {\n let (n, m) = get!(usize, usize);\n let mut kouho = VecDeque::new();\n kouho.push_back((n, 0));\n let mut used = vec![true; 10004 * 2];\n while !kouho.is_empty() {\n let (a, depth) = kouho.pop_front().unwrap();\n //mydbg!(a);\n if a == m {\n echo!(depth);\n return;\n }\n if a - 1 != 0 && used[a - 1] {\n kouho.push_back((a - 1, depth + 1));\n used[a - 1] = false;\n }\n if a * 2 < m * 2 + 1 && used[a * 2] {\n kouho.push_back((a * 2, depth + 1));\n used[a * 2] = false;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "3453ef30343ad3933e9c6cc591dbcc80", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n\n line.split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect()\n}\n\nconst MAX_N: i32 = 20000;\nconst INF: i32 = 10000;\n\nfn main() {\n let input = readln();\n let n = input[0];\n let m = input[1];\n\n let mut count_clicks: [i32; (MAX_N + 1) as usize] = [INF; (MAX_N + 1) as usize];\n let mut queue: Vec = vec![n];\n count_clicks[n as usize] = 0;\n\n let mut i: usize = 0;\n while i < queue.len() {\n let number = queue[i] as i32;\n let index = number as usize;\n\n if number - 1 >= 0 && count_clicks[index - 1] > count_clicks[index] + 1 {\n count_clicks[index - 1] = count_clicks[index] + 1;\n queue.push(number - 1);\n }\n\n if number * 2 <= MAX_N && count_clicks[index * 2] > count_clicks[index] + 1 {\n count_clicks[index * 2] = count_clicks[index] + 1;\n queue.push(number * 2);\n }\n\n i += 1;\n }\n\n println!(\"{}\", count_clicks[m as usize]);\n}", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "ff3baa93ac067faff2cbca0c8622e82f", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{HashSet,HashMap,VecDeque,BinaryHeap};\n\n// Functions\n\n// Main\nfn main(){\n input!{\n N: usize,\n mut M: usize\n }\n let mut ans = 0;\n while M>N{\n if M%2==0{\n M = M/2;\n ans += 1;\n }else{\n M += 1;\n ans += 1;\n }\n }\n ans += N-M;\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "58391d3faf9f9ece01e4bef0a14e8665", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn compare(x: i32, y: i32) -> i32 {\n if x == y {\n return 0;\n }\n if (x == 2 && y == 4) || (x == 4 && y == 2) {\n return 0;\n }\n\n if x <= 3 && y <= 3 {\n return if x < y { -1 } else { 1 };\n }\n if x >= 3 && y >= 3 {\n return if x < y { 1 } else { -1 };\n }\n\n if x == 1 {\n return -1;\n }\n if y == 1 {\n return 1;\n }\n\n if x <= 3 { 1 } else { -1 }\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut input = String::new();\n stdin.lock().read_line(&mut input).unwrap();\n\n let tokens: Vec<&str> = input.split_whitespace().collect();\n let x = tokens[0].parse::().unwrap();\n let y = tokens[1].parse::().unwrap();\n\n match compare(x, y) {\n -1 => println!(\"<\"),\n 0 => println!(\"=\"),\n 1 => println!(\">\"),\n _ => println!(\"This shouldn't happen...\")\n };\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "c523ca8d7fae34c799c84b0eb2dc7b49", "src_uid": "ec1e44ff41941f0e6436831b5ae543c6", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let x: u32 = it.next().unwrap().parse().unwrap();\n let y: u32 = it.next().unwrap().parse().unwrap();\n\n // x^y y^x\n // exp(y * ln(x)) exp(x * ln(y))\n // y * ln(x) x * ln(y)\n // ln(x) / x ln(y) / y\n\n fn f_cmp(a: u32, b: u32) -> ::std::cmp::Ordering {\n use std::cmp::{self, Ordering};\n\n if a == b {\n Ordering::Equal\n } else if a == 1 {\n Ordering::Less\n } else if b == 1 {\n Ordering::Greater\n } else if a == 3 {\n Ordering::Greater\n } else if b == 3 {\n Ordering::Less\n } else if a == 2 || a == 4 {\n if b == 2 || b == 4 {\n Ordering::Equal\n } else {\n Ordering::Greater\n }\n } else if b == 2 || b == 4 {\n Ordering::Less\n } else {\n b.cmp(&a)\n }\n }\n\n let ans = f_cmp(x, y);\n use std::cmp::Ordering;\n let txt = match ans {\n Ordering::Less => '<',\n Ordering::Equal => '=',\n Ordering::Greater => '>',\n };\n\n println!(\"{}\", txt);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "08d5766e597cc68b079971cc9bd4b1ae", "src_uid": "ec1e44ff41941f0e6436831b5ae543c6", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\nuse std::io;\n\nfn main() {\n let mut mut_line = String::new();\n io::stdin().read_line(&mut mut_line).unwrap();\n let mut iter = mut_line.trim().split(\" \").map(|x| x.parse().unwrap());\n let (x, y): (u64, u64) = (iter.next().unwrap(), iter.next().unwrap());\n if x == y {\n println!(\"=\");\n return;\n }\n let mini = cmp::min(x, y);\n let other = x + y - mini;\n let mut result = if mini >= 3 {\n cmp::Ordering::Greater\n } else if mini == 1 {\n cmp::Ordering::Less\n } else {\n // mini == 2\n if other == 3{\n cmp::Ordering::Less\n } else if other == 4 {\n cmp::Ordering::Equal\n }\n else{\n cmp::Ordering::Greater\n }\n };\n if mini == y {\n result = cmp::Ordering::reverse(result);\n }\n match result{\n cmp::Ordering::Less => println!(\"<\"),\n cmp::Ordering::Equal => println!(\"=\"),\n cmp::Ordering::Greater => println!(\">\")\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "2a46191dff071a1555e88f566eaa5e1b", "src_uid": "ec1e44ff41941f0e6436831b5ae543c6", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let x: u32 = it.next().unwrap().parse().unwrap();\n let y: u32 = it.next().unwrap().parse().unwrap();\n\n // x^y y^x\n // exp(y * ln(x)) exp(x * ln(y))\n // y * ln(x) x * ln(y)\n // ln(x) / x ln(y) / y\n\n struct F {\n x: u32,\n }\n\n use std::cmp::{Ordering, self};\n\n impl PartialEq for F {\n fn eq(&self, other: &F) -> bool {\n match (self.x, other.x) {\n (2, 4) | (4, 2) => true,\n (a, b) => a.eq(&b),\n }\n }\n }\n\n impl Eq for F {}\n\n impl PartialOrd for F {\n fn partial_cmp(&self, other: &F) -> Option {\n Some(self.cmp(other))\n }\n }\n\n impl Ord for F {\n fn cmp(&self, other: &F) -> Ordering {\n match (self.x, other.x) {\n (a, b) if F { x: a } == F { x: b } => Ordering::Equal,\n (3, _) => Ordering::Greater,\n (_, 3) => Ordering::Less,\n (2, _) => Ordering::Greater,\n (_, 2) => Ordering::Less,\n (1, _) => Ordering::Less,\n (_, 1) => Ordering::Greater,\n (a, b) => b.cmp(&a),\n }\n }\n }\n\n let x = F { x: x };\n let y = F { x: y };\n let ans = x.cmp(&y);\n let txt = match ans {\n Ordering::Less => '<',\n Ordering::Equal => '=',\n Ordering::Greater => '>',\n };\n\n println!(\"{}\", txt);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "17505b9f5a3bcd0ec9fbcd827c69f7d8", "src_uid": "ec1e44ff41941f0e6436831b5ae543c6", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let x: f64 = it.next().unwrap().parse().unwrap();\n let y: f64 = it.next().unwrap().parse().unwrap();\n\n // x^y y^x\n // exp(y * ln(x)) exp(x * ln(y))\n // y * ln(x) x * ln(y)\n // ln(x) / x ln(y) / y\n\n let epsilon = 1e-4;\n\n let diff = x * y.ln() - y * x.ln();\n\n let ans = if diff.abs() < epsilon {\n '='\n } else if diff > 0.0 {\n '<'\n } else {\n '>'\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "d2c659895a0a890b1fc395de8e3d358d", "src_uid": "ec1e44ff41941f0e6436831b5ae543c6", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{cell::Cell, cmp::{Reverse, max, min}, collections::{BTreeMap, HashMap, HashSet}, error::Error, fmt::Display, io::{BufWriter, Read, Write}, iter::Peekable, mem::swap, ops::{Not, Range, RangeInclusive, Sub}, process::exit, rc::Rc, str::{FromStr, from_utf8, from_utf8_unchecked}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\nstruct Scanner<'a, R: Read> {\n src: &'a mut R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl<'a, R: Read> Scanner<'a, R> {\n fn new(src: &'a mut R) -> Scanner<'a, R> {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n \n fn char(&mut self) -> char { self.byte() as char }\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n fn token(&mut self) -> String { unsafe { String::from_utf8_unchecked(self.token_bytes()) } }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n fn line(&mut self) -> String { unsafe { String::from_utf8_unchecked(self.line_bytes()) } }\n \n fn read(&mut self) -> T { \n let token = self.token_bytes();\n unsafe { from_utf8_unchecked(&token).parse::().ok().unwrap() }\n }\n fn vec(&mut self, n: usize) -> Vec { (0..n).map(|_| self.read()).collect() }\n fn vec2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.vec(m)).collect() }\n}\n\ntrait ToCharVec { fn to_char_vec(&self) -> Vec; }\nimpl ToCharVec for &str { fn to_char_vec(&self) -> Vec { self.chars().collect() } }\nimpl ToCharVec for String { fn to_char_vec(&self) -> Vec { self.chars().collect() } }\ntrait JoinToStr { \n fn join_to_str(&mut self, sep: &str) -> String;\n fn concat_to_str(&mut self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(&mut self, sep: &str) -> String {\n let mut res = String::new();\n match self.next() {\n None => res,\n Some(first) => {\n res.push_str(&first.to_string());\n loop {\n match self.next() {\n None => break,\n Some(item) => {\n res.push_str(sep);\n res.push_str(&item.to_string())\n }\n }\n }\n res\n }\n }\n }\n \n fn concat_to_str(&mut self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let n = $n;\n let mut list = Vec::with_capacity(n);\n for $i in 0..n {\n list.push($gen);\n }\n list\n }};\n ($n:expr , $gen:expr) => { veci!($n, __: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\n// * end commons * //\n\nmod modint {\n\n use std::{convert::Infallible, iter::Sum, mem::swap, ops::AddAssign};\n\n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n\n fn pow_mod(self, exponent: u64, modulus: u32) -> u32 {\n pow_mod_raw(self.rem_euclid_u32(modulus), exponent, modulus)\n }\n fn mul_mod(self, rhs: Rhs, modulus: u32) -> u32 {\n mul_mod_u32(self.rem_euclid_u32(modulus), rhs.rem_euclid_u32(modulus), modulus)\n }\n\n fn mod_pow_vec(self, n: usize, modulus: u32) -> Vec {\n let a = self.rem_euclid_u32(modulus);\n let mut res = vec![0u32; n+1];\n if modulus == 1 { return res; }\n res[0] = 1;\n for i in 1..=n {\n res[i] = mul_mod_u32(a, res[i-1], modulus);\n }\n res\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n ((a as u64) * (b as u64) % (m as u64)) as u32\n }\n\n // for a, b < m, undefined otherwise\n pub fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n if b >= m - a { a.wrapping_add(b).wrapping_sub(m) } else { a + b }\n }\n pub fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n if a < b { a.wrapping_add(m).wrapping_sub(b) } else { a - b }\n }\n pub fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a= a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n return r as u32;\n }\n\n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n pub fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n std::mem::swap(&mut s, &mut t);\n std::mem::swap(&mut m0, &mut m1);\n }\n\n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\n #[repr(transparent)]\n pub struct ModInt { pub val: u32 }\n\n impl ModInt {\n #[inline]\n pub fn modulus() -> u32 { crate::get_modulus() }\n pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline]\n pub fn raw(val: u32) -> Self { Self { val } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n if gcd != 1 { panic!(\"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus()) }\n Self::raw(x as u32)\n }\n pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n\n #[inline]\n pub fn mi(val: I) -> ModInt { ModInt::new(val) }\n\n impl From for ModInt {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl std::str::FromStr for ModInt {\n type Err = std::convert::Infallible;\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl std::fmt::Display for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Display::fmt(&self.val, f)\n }\n }\n impl std::fmt::Debug for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n Self::raw(if self.val == 0 { 0 } else { Self::modulus() - self.val })\n }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: Self) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: Self) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: Self) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output { self * rhs.inv() }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: I) -> Self::Output { self + Self::new(rhs) }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: I) -> Self::Output { self - Self::new(rhs) }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: I) -> Self::Output { self * Self::new(rhs) }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: I) -> Self::Output { self / Self::new(rhs) }\n }\n\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; }\n }\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: I) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: I) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: I) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: I) { *self = *self / rhs; }\n }\n\n impl std::iter::Sum for ModInt {\n fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), std::ops::Add::add)\n }\n }\n impl std::iter::Product for ModInt {\n fn product>(iter: I) -> Self {\n iter.fold(1.into(), std::ops::Mul::mul)\n }\n }\n}\n\n//const MODULUS: u32 = 998_244_353;\n//const MODULUS: u32 = 1_000_000_007;\nthread_local! {\n static MODULUS: Cell = Cell::new(998_244_353);\n}\nfn get_modulus() -> u32 { MODULUS.with(|x| x.get()) }\nfn set_modulus(value: u32) { MODULUS.with(|x| x.set(value)) }\nuse crate::modint::*;\n\n#[allow(non_snake_case, unused_macros)]\nfn main() -> Result<(), Box> {\n let mut INPUT = std::io::stdin();\n let OUTPUT = std::io::stdout();\n\n let mut inp = Scanner::new(&mut INPUT);\n let mut out = BufWriter::with_capacity(IO_BUF_SIZE, OUTPUT);\n\n macro_rules! inp {\n () => { inp.read(); };\n ($t: ty) => { inp.read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (inp.read::<$t>(), $(inp.read::<$tt>(),)*); };\n [$t: ty; $n: expr] => { inp.vec::<$t>($n); };\n }\n macro_rules! println { \n () => { writeln!(out).unwrap(); };\n ($exp: expr) => { writeln!(out, \"{}\", $exp).unwrap(); }; \n ($fmt: expr, $($arg : tt )*) => { writeln!(out, $fmt, $($arg)*).unwrap(); }\n }\n macro_rules! print { \n ($exp: expr) => { write!(out, \"{}\", $exp).unwrap(); }; \n ($fmt: expr, $($arg : tt )*) => { write!(out, $fmt, $($arg)*).unwrap(); }\n }\n\n { // solution start\n let num_cases = 1;//inp!(usize);\n\n for _case_num in 1..=num_cases {\n let n = inp!(usize);\n set_modulus(inp!());\n\n let mut dp = vec![mi(0); n+1];\n dp[1] = mi(1);\n dp[2] = mi(2);\n for i in 2..n {\n let d = dp[i];\n dp[i+1] += d + d + 1;\n let d = d - dp[i-1];\n for j in (i*2..=n).step_by(i) {\n dp[j] += d;\n }\n }\n\n let ans = dp[n];\n println!(ans);\n }\n } // solution end\n\n out.flush()?;\n Ok(())\n}\n\n\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "1b185d549e5802c79789bc04c0bc86fe", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{cell::{Cell, RefCell}, cmp::{Reverse, max, min}, collections::{BTreeMap, BinaryHeap, HashMap, HashSet}, error::Error, fmt::Display, hash::{Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::Peekable, mem::swap, ops::{Not, Sub}, process::exit, rc::Rc, str::{FromStr, from_utf8, from_utf8_unchecked}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\nstruct Unsync(T);\nunsafe impl Sync for Unsync {}\n\ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(RefCell::new(None)) }\n}\n\nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n\nfn inp R, R>(f: F) -> R {\n f(INPUT.0.borrow_mut().get_or_insert_with(_init_input))\n}\nfn out R, R>(f: F) -> R {\n f(OUTPUT.0.borrow_mut().get_or_insert_with(_init_output))\n}\n\nmacro_rules! read {\n () => { read(); };\n ($t: ty) => { read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$t>(),)*); };\n [$t: ty; $n: expr] => { read_vec::<$t>($n); };\n}\nmacro_rules! println { \n () => { out(|x| writeln!(x).unwrap()); };\n ($exp: expr) => { out(|x| writeln!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| writeln!(x, $fmt, $($arg)*).unwrap()); }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| write!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| write!(x, $fmt, $($arg)*).unwrap()); }\n}\n\nfn out_flush() { out(|x| x.flush().unwrap()); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().unwrap() }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\ntrait JoinToStr { \n fn join_to_str(&mut self, sep: &str) -> String;\n fn concat_to_str(&mut self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(&mut self, sep: &str) -> String {\n let mut res = String::new();\n match self.next() {\n None => res,\n Some(first) => {\n res.push_str(&first.to_string());\n loop {\n match self.next() {\n None => break,\n Some(item) => {\n res.push_str(sep);\n res.push_str(&item.to_string())\n }\n }\n }\n res\n }\n }\n }\n \n fn concat_to_str(&mut self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let n = $n;\n let mut list = Vec::with_capacity(n);\n for $i in 0..n {\n list.push($gen);\n }\n list\n }};\n ($n:expr , $gen:expr) => { veci!($n, __: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\n// * end commons * //\n\nmod modint {\n\n use std::{convert::Infallible, iter::Sum, mem::swap, ops::AddAssign};\n\n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n\n fn pow_mod(self, exponent: u64, modulus: u32) -> u32 {\n pow_mod_raw(self.rem_euclid_u32(modulus), exponent, modulus)\n }\n fn mul_mod(self, rhs: Rhs, modulus: u32) -> u32 {\n mul_mod_u32(self.rem_euclid_u32(modulus), rhs.rem_euclid_u32(modulus), modulus)\n }\n\n fn mod_pow_vec(self, n: usize, modulus: u32) -> Vec {\n let a = self.rem_euclid_u32(modulus);\n let mut res = vec![0u32; n+1];\n if modulus == 1 { return res; }\n res[0] = 1;\n for i in 1..=n {\n res[i] = mul_mod_u32(a, res[i-1], modulus);\n }\n res\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n ((a as u64) * (b as u64) % (m as u64)) as u32\n }\n\n // for a, b < m, undefined otherwise\n #[inline]\n pub fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n sub_mod_raw(a, m-b, m)\n }\n #[inline]\n pub fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n pub fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n return r as u32;\n }\n\n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n pub fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n std::mem::swap(&mut s, &mut t);\n std::mem::swap(&mut m0, &mut m1);\n }\n\n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\n #[repr(transparent)]\n pub struct ModInt { pub val: u32 }\n\n impl ModInt {\n #[inline(always)]\n pub fn modulus() -> u32 { crate::get_modulus() }\n pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline]\n pub fn raw(val: u32) -> Self { Self { val } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n if gcd != 1 { panic!(\"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus()) }\n Self::raw(x as u32)\n }\n pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n\n #[inline]\n pub fn mi(val: I) -> ModInt { ModInt::new(val) }\n\n impl From for ModInt {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl std::str::FromStr for ModInt {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl std::fmt::Display for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Display::fmt(&self.val, f)\n }\n }\n impl std::fmt::Debug for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl std::ops::Neg for ModInt {\n type Output = ModInt;\n\n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n //Self::raw(norm(self.val.wrapping_neg(), Self::modulus()))\n }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output { self * rhs.inv() }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: I) -> Self::Output { self + Self::new(rhs) }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: I) -> Self::Output { self - Self::new(rhs) }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: I) -> Self::Output { self * Self::new(rhs) }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: I) -> Self::Output { self / Self::new(rhs) }\n }\n\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; }\n }\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: I) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: I) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: I) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: I) { *self = *self / rhs; }\n }\n\n impl std::iter::Sum for ModInt {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), std::ops::Add::add)\n }\n }\n impl std::iter::Product for ModInt {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), std::ops::Mul::mul)\n }\n }\n impl<'a> std::iter::Sum<&'a Self> for ModInt {\n #[inline] fn sum>(iter: I) -> ModInt {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a> std::iter::Product<&'a Self> for ModInt {\n #[inline] fn product>(iter: I) -> ModInt {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n}\n\n// const MODULUS: u32 = 998_244_353;\n// //const MODULUS: u32 = 1_000_000_007;\n// #[inline(always)]\n// fn get_modulus() -> u32 { MODULUS }\n\nstatic MODULUS: Unsync> = Unsync(Cell::new(0));\n#[inline] fn get_modulus() -> u32 { MODULUS.0.get() }\n#[inline] fn set_modulus(value: u32) { MODULUS.0.set(value) }\n\nuse crate::modint::*;\n\n#[allow(non_snake_case, unused_macros)]\nfn main() -> Result<(), Box> {\n let num_cases = 1;//read!(i32);\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n set_modulus(read!());\n\n let mut dp = vec![mi(0); n+1];\n dp[1] = mi(1);\n dp[2] = mi(2);\n for i in 2..n {\n let d = dp[i];\n dp[i+1] += d + d + 1;\n let d = d - dp[i-1];\n for j in (i*2..=n).step_by(i) {\n dp[j] += d;\n }\n }\n\n let ans = dp[n];\n println!(ans);\n }\n\n out_flush();\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "dc7003d26c3eaaca519f53b2d4b7376e", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Reverse, max, min}, collections::{BTreeMap, BinaryHeap, HashMap, HashSet}, error::Error, fmt::Display, hash::{Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::Peekable, mem::swap, ops::{Not, Sub}, process::exit, rc::Rc, str::{FromStr, from_utf8, from_utf8_unchecked}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(RefCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n f(INPUT.0.borrow_mut().get_or_insert_with(_init_input))\n}\nfn out R, R>(f: F) -> R {\n f(OUTPUT.0.borrow_mut().get_or_insert_with(_init_output))\n}\n\nmacro_rules! read {\n () => { read(); };\n ($t: ty) => { read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$t>(),)*); };\n [$t: ty; $n: expr] => { read_vec::<$t>($n); };\n}\nmacro_rules! println { \n () => { out(|x| writeln!(x).unwrap()); };\n ($exp: expr) => { out(|x| writeln!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| writeln!(x, $fmt, $($arg)*).unwrap()); }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| write!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| write!(x, $fmt, $($arg)*).unwrap()); }\n}\n\nfn out_flush() { out(|x| x.flush().unwrap()); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().unwrap() }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\ntrait JoinToStr { \n fn join_to_str(&mut self, sep: &str) -> String;\n fn concat_to_str(&mut self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(&mut self, sep: &str) -> String {\n let mut res = String::new();\n match self.next() {\n None => res,\n Some(first) => {\n res.push_str(&first.to_string());\n loop {\n match self.next() {\n None => break,\n Some(item) => {\n res.push_str(sep);\n res.push_str(&item.to_string())\n }\n }\n }\n res\n }\n }\n }\n \n fn concat_to_str(&mut self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let n = $n;\n let mut list = Vec::with_capacity(n);\n for $i in 0..n {\n list.push($gen);\n }\n list\n }};\n ($n:expr , $gen:expr) => { veci!($n, __: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\n// * end commons * //\n\nmod modint {\n\n use std::{convert::Infallible, iter::Sum, mem::swap, ops::AddAssign};\n\n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n\n fn pow_mod(self, exponent: u64, modulus: u32) -> u32 {\n pow_mod_raw(self.rem_euclid_u32(modulus), exponent, modulus)\n }\n fn mul_mod(self, rhs: Rhs, modulus: u32) -> u32 {\n mul_mod_u32(self.rem_euclid_u32(modulus), rhs.rem_euclid_u32(modulus), modulus)\n }\n\n fn mod_pow_vec(self, n: usize, modulus: u32) -> Vec {\n let a = self.rem_euclid_u32(modulus);\n let mut res = vec![0u32; n+1];\n if modulus == 1 { return res; }\n res[0] = 1;\n for i in 1..=n {\n res[i] = mul_mod_u32(a, res[i-1], modulus);\n }\n res\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n ((a as u64) * (b as u64) % (m as u64)) as u32\n }\n\n // for a, b < m, undefined otherwise\n #[inline]\n pub fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n sub_mod_raw(a, m-b, m)\n }\n #[inline]\n pub fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n pub fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n return r as u32;\n }\n\n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n pub fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n std::mem::swap(&mut s, &mut t);\n std::mem::swap(&mut m0, &mut m1);\n }\n\n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\n #[repr(transparent)]\n pub struct ModInt { pub val: u32 }\n\n impl ModInt {\n #[inline(always)]\n pub fn modulus() -> u32 { crate::get_modulus() }\n pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline]\n pub fn raw(val: u32) -> Self { Self { val } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n if gcd != 1 { panic!(\"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus()) }\n Self::raw(x as u32)\n }\n pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n\n #[inline]\n pub fn mi(val: I) -> ModInt { ModInt::new(val) }\n\n impl From for ModInt {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl std::str::FromStr for ModInt {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl std::fmt::Display for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Display::fmt(&self.val, f)\n }\n }\n impl std::fmt::Debug for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl std::ops::Neg for ModInt {\n type Output = ModInt;\n\n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n //Self::raw(norm(self.val.wrapping_neg(), Self::modulus()))\n }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output { self * rhs.inv() }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: I) -> Self::Output { self + Self::new(rhs) }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: I) -> Self::Output { self - Self::new(rhs) }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: I) -> Self::Output { self * Self::new(rhs) }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: I) -> Self::Output { self / Self::new(rhs) }\n }\n\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; }\n }\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: I) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: I) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: I) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: I) { *self = *self / rhs; }\n }\n\n impl std::iter::Sum for ModInt {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), std::ops::Add::add)\n }\n }\n impl std::iter::Product for ModInt {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), std::ops::Mul::mul)\n }\n }\n impl<'a> std::iter::Sum<&'a Self> for ModInt {\n #[inline] fn sum>(iter: I) -> ModInt {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a> std::iter::Product<&'a Self> for ModInt {\n #[inline] fn product>(iter: I) -> ModInt {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n}\n\n// const MODULUS: u32 = 998_244_353;\n// //const MODULUS: u32 = 1_000_000_007;\n// #[inline(always)]\n// fn get_modulus() -> u32 { MODULUS }\n\nstatic MODULUS: Unsync> = Unsync(Cell::new(0));\n#[inline] fn get_modulus() -> u32 { MODULUS.0.get() }\n#[inline] fn set_modulus(value: u32) { MODULUS.0.set(value) }\n\nuse crate::modint::*;\n\n#[allow(non_snake_case, unused_macros)]\nfn main() -> Result<(), Box> {\n let num_cases = 1;//read!(i32);\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n set_modulus(read!());\n\n let mut dp = vec![mi(0); n+1];\n dp[1] = mi(1);\n dp[2] = mi(2);\n for i in 2..n {\n let d = dp[i];\n dp[i+1] += d + d + 1;\n let d = d - dp[i-1];\n for j in (i*2..=n).step_by(i) {\n dp[j] += d;\n }\n }\n\n let ans = dp[n];\n println!(ans); //\n }\n\n out_flush();\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "fb80adf48b5ba3db5d1522644dd7adbe", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Reverse, max, min}, collections::{BTreeMap, BinaryHeap, HashMap, HashSet}, error::Error, fmt::Display, hash::{Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::Peekable, mem::swap, ops::{Not, Sub}, process::exit, rc::Rc, str::{FromStr, from_utf8, from_utf8_unchecked}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read(); };\n ($t: ty) => { read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$t>(),)*); };\n [$t: ty; $n: expr] => { read_vec::<$t>($n); };\n}\nmacro_rules! println { \n () => { out(|x| writeln!(x).unwrap()); };\n ($exp: expr) => { out(|x| writeln!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| writeln!(x, $fmt, $($arg)*).unwrap()); }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| write!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| write!(x, $fmt, $($arg)*).unwrap()); }\n}\n\nfn out_flush() { out(|x| x.flush().unwrap()); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().unwrap() }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\ntrait JoinToStr { \n fn join_to_str(&mut self, sep: &str) -> String;\n fn concat_to_str(&mut self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(&mut self, sep: &str) -> String {\n let mut res = String::new();\n match self.next() {\n None => res,\n Some(first) => {\n res.push_str(&first.to_string());\n loop {\n match self.next() {\n None => break,\n Some(item) => {\n res.push_str(sep);\n res.push_str(&item.to_string())\n }\n }\n }\n res\n }\n }\n }\n \n fn concat_to_str(&mut self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let n = $n;\n let mut list = Vec::with_capacity(n);\n for $i in 0..n {\n list.push($gen);\n }\n list\n }};\n ($n:expr , $gen:expr) => { veci!($n, __: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\n// * end commons * //\n\nmod modint {\n\n use std::{convert::Infallible, iter::Sum, mem::swap, ops::AddAssign};\n\n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n\n fn pow_mod(self, exponent: u64, modulus: u32) -> u32 {\n pow_mod_raw(self.rem_euclid_u32(modulus), exponent, modulus)\n }\n fn mul_mod(self, rhs: Rhs, modulus: u32) -> u32 {\n mul_mod_u32(self.rem_euclid_u32(modulus), rhs.rem_euclid_u32(modulus), modulus)\n }\n\n fn mod_pow_vec(self, n: usize, modulus: u32) -> Vec {\n let a = self.rem_euclid_u32(modulus);\n let mut res = vec![0u32; n+1];\n if modulus == 1 { return res; }\n res[0] = 1;\n for i in 1..=n {\n res[i] = mul_mod_u32(a, res[i-1], modulus);\n }\n res\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n ((a as u64) * (b as u64) % (m as u64)) as u32\n }\n\n // for a, b < m, undefined otherwise\n #[inline]\n pub fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n sub_mod_raw(a, m-b, m)\n }\n #[inline]\n pub fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n pub fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n return r as u32;\n }\n\n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n pub fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n std::mem::swap(&mut s, &mut t);\n std::mem::swap(&mut m0, &mut m1);\n }\n\n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\n #[repr(transparent)]\n pub struct ModInt { pub val: u32 }\n\n impl ModInt {\n #[inline(always)]\n pub fn modulus() -> u32 { crate::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub const fn raw(val: u32) -> Self { Self { val } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n if gcd != 1 { panic!(\"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus()) }\n Self::raw(x as u32)\n }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n\n #[inline]\n pub fn mi(val: I) -> ModInt { ModInt::new(val) }\n\n impl From for ModInt {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl std::str::FromStr for ModInt {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl std::fmt::Display for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Display::fmt(&self.val, f)\n }\n }\n impl std::fmt::Debug for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl std::ops::Neg for ModInt {\n type Output = ModInt;\n\n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n //Self::raw(norm(self.val.wrapping_neg(), Self::modulus()))\n }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output { self * rhs.inv() }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: I) -> Self::Output { self + Self::new(rhs) }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: I) -> Self::Output { self - Self::new(rhs) }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: I) -> Self::Output { self * Self::new(rhs) }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: I) -> Self::Output { self / Self::new(rhs) }\n }\n\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; }\n }\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: I) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: I) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: I) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: I) { *self = *self / rhs; }\n }\n\n impl std::iter::Sum for ModInt {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), std::ops::Add::add)\n }\n }\n impl std::iter::Product for ModInt {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), std::ops::Mul::mul)\n }\n }\n impl<'a> std::iter::Sum<&'a Self> for ModInt {\n #[inline] fn sum>(iter: I) -> ModInt {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a> std::iter::Product<&'a Self> for ModInt {\n #[inline] fn product>(iter: I) -> ModInt {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n}\n\n// const MODULUS: u32 = 998_244_353;\n// //const MODULUS: u32 = 1_000_000_007;\n// #[inline(always)]\n// fn get_modulus() -> u32 { MODULUS }\n\nstatic MODULUS: Unsync> = Unsync(Cell::new(0));\n#[inline] fn get_modulus() -> u32 { MODULUS.0.get() }\n#[inline] fn set_modulus(value: u32) { MODULUS.0.set(value) }\n\nuse crate::modint::*;\n\n#[inline] const fn mir(v: u32) -> ModInt { ModInt::raw(v) }\n\n#[allow(non_snake_case, unused_macros)]\nfn main() -> Result<(), Box> {\n let num_cases = 1;//read!(i32);\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n set_modulus(read!());\n\n let mut dp = vec![mir(0); n+1];\n dp[1] = mir(1);\n dp[2] = mir(2);\n for i in 2..n {\n let d = dp[i];\n dp[i+1] += d + d + mir(1);\n let d = d - dp[i-1];\n for j in (i*2..=n).step_by(i) {\n dp[j] += d;\n }\n }\n\n let ans = dp[n];\n println!(ans); //\n }\n\n out_flush();\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "ffd0769368f8682410118dbd6a3e0421", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{cell::Cell, cmp::{Reverse, max, min}, collections::{BTreeMap, HashMap, HashSet}, error::Error, fmt::Display, io::{BufWriter, Read, Write}, iter::Peekable, mem::swap, ops::{Not, Range, RangeInclusive, Sub}, process::exit, rc::Rc, str::{FromStr, from_utf8, from_utf8_unchecked}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\nstruct Scanner<'a, R: Read> {\n src: &'a mut R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl<'a, R: Read> Scanner<'a, R> {\n fn new(src: &'a mut R) -> Scanner<'a, R> {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n \n fn char(&mut self) -> char { self.byte() as char }\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n fn token(&mut self) -> String { unsafe { String::from_utf8_unchecked(self.token_bytes()) } }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n fn line(&mut self) -> String { unsafe { String::from_utf8_unchecked(self.line_bytes()) } }\n \n fn read(&mut self) -> T { \n let token = self.token_bytes();\n unsafe { from_utf8_unchecked(&token).parse::().ok().unwrap() }\n }\n fn vec(&mut self, n: usize) -> Vec { (0..n).map(|_| self.read()).collect() }\n fn vec2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.vec(m)).collect() }\n}\n\ntrait ToCharVec { fn to_char_vec(&self) -> Vec; }\nimpl ToCharVec for &str { fn to_char_vec(&self) -> Vec { self.chars().collect() } }\nimpl ToCharVec for String { fn to_char_vec(&self) -> Vec { self.chars().collect() } }\ntrait JoinToStr { \n fn join_to_str(&mut self, sep: &str) -> String;\n fn concat_to_str(&mut self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(&mut self, sep: &str) -> String {\n let mut res = String::new();\n match self.next() {\n None => res,\n Some(first) => {\n res.push_str(&first.to_string());\n loop {\n match self.next() {\n None => break,\n Some(item) => {\n res.push_str(sep);\n res.push_str(&item.to_string())\n }\n }\n }\n res\n }\n }\n }\n \n fn concat_to_str(&mut self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let n = $n;\n let mut list = Vec::with_capacity(n);\n for $i in 0..n {\n list.push($gen);\n }\n list\n }};\n ($n:expr , $gen:expr) => { veci!($n, __: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\n// * end commons * //\n\nmod modint {\n\n use std::{convert::Infallible, iter::Sum, mem::swap, ops::AddAssign};\n\n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n\n fn pow_mod(self, exponent: u64, modulus: u32) -> u32 {\n pow_mod_raw(self.rem_euclid_u32(modulus), exponent, modulus)\n }\n fn mul_mod(self, rhs: Rhs, modulus: u32) -> u32 {\n mul_mod_u32(self.rem_euclid_u32(modulus), rhs.rem_euclid_u32(modulus), modulus)\n }\n\n fn mod_pow_vec(self, n: usize, modulus: u32) -> Vec {\n let a = self.rem_euclid_u32(modulus);\n let mut res = vec![0u32; n+1];\n if modulus == 1 { return res; }\n res[0] = 1;\n for i in 1..=n {\n res[i] = mul_mod_u32(a, res[i-1], modulus);\n }\n res\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n ((a as u64) * (b as u64) % (m as u64)) as u32\n }\n\n #[inline]\n fn norm(a: u32, m: u32) -> u32 {\n (((a as i32) >> 31) as u32 & m) + a\n }\n // for a, b < m < 2^31, undefined otherwise\n #[inline]\n pub fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n //if b >= m - a { a.wrapping_add(b).wrapping_sub(m) } else { a + b }\n norm(a.wrapping_add(b).wrapping_sub(m), m)\n }\n #[inline]\n pub fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n //if a < b { a.wrapping_add(m).wrapping_sub(b) } else { a - b }\n norm(a.wrapping_sub(b), m)\n }\n pub fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a= a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n return r as u32;\n }\n\n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n pub fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n std::mem::swap(&mut s, &mut t);\n std::mem::swap(&mut m0, &mut m1);\n }\n\n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\n #[repr(transparent)]\n pub struct ModInt { pub val: u32 }\n\n impl ModInt {\n #[inline(always)]\n pub fn modulus() -> u32 { crate::get_modulus() }\n pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline]\n pub fn raw(val: u32) -> Self { Self { val } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n if gcd != 1 { panic!(\"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus()) }\n Self::raw(x as u32)\n }\n pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n\n #[inline]\n pub fn mi(val: I) -> ModInt { ModInt::new(val) }\n\n impl From for ModInt {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl std::str::FromStr for ModInt {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl std::fmt::Display for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Display::fmt(&self.val, f)\n }\n }\n impl std::fmt::Debug for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl std::ops::Neg for ModInt {\n type Output = ModInt;\n\n #[inline]\n fn neg(self) -> Self::Output {\n //Self::raw(if self.val == 0 { 0 } else { Self::modulus() - self.val })\n Self::raw(norm(self.val.wrapping_neg(), Self::modulus()))\n }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output { self * rhs.inv() }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: I) -> Self::Output { self + Self::new(rhs) }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: I) -> Self::Output { self - Self::new(rhs) }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: I) -> Self::Output { self * Self::new(rhs) }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: I) -> Self::Output { self / Self::new(rhs) }\n }\n\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; }\n }\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: I) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: I) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: I) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: I) { *self = *self / rhs; }\n }\n\n impl std::iter::Sum for ModInt {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), std::ops::Add::add)\n }\n }\n impl std::iter::Product for ModInt {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(1.into(), std::ops::Mul::mul)\n }\n }\n}\n\n// const MODULUS: u32 = 998_244_353;\n// //const MODULUS: u32 = 1_000_000_007;\n// #[inline(always)]\n// fn get_modulus() -> u32 { MODULUS }\n\nstatic mut MODULUS: u32 = 998244353;\n#[inline] fn get_modulus() -> u32 { unsafe { MODULUS } }\n#[inline] fn set_modulus(value: u32) { unsafe { MODULUS = value; } }\n\nuse crate::modint::*;\n\n#[allow(non_snake_case, unused_macros)]\nfn main() -> Result<(), Box> {\n let mut INPUT = std::io::stdin();\n let OUTPUT = std::io::stdout();\n\n let mut inp = Scanner::new(&mut INPUT);\n let mut out = BufWriter::with_capacity(IO_BUF_SIZE, OUTPUT);\n\n macro_rules! inp {\n () => { inp.read(); };\n ($t: ty) => { inp.read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (inp.read::<$t>(), $(inp.read::<$tt>(),)*); };\n [$t: ty; $n: expr] => { inp.vec::<$t>($n); };\n }\n macro_rules! println { \n () => { writeln!(out).unwrap(); };\n ($exp: expr) => { writeln!(out, \"{}\", $exp).unwrap(); }; \n ($fmt: expr, $($arg : tt )*) => { writeln!(out, $fmt, $($arg)*).unwrap(); }\n }\n macro_rules! print { \n ($exp: expr) => { write!(out, \"{}\", $exp).unwrap(); }; \n ($fmt: expr, $($arg : tt )*) => { write!(out, $fmt, $($arg)*).unwrap(); }\n }\n\n { // solution start\n let num_cases = 1;//inp!(usize);\n\n for _case_num in 1..=num_cases {\n let n = inp!(usize);\n set_modulus(inp!());\n\n let mut dp = vec![mi(0); n+1];\n dp[1] = mi(1);\n dp[2] = mi(2);\n for i in 2..n {\n let d = dp[i];\n dp[i+1] += d + d + 1;\n let d = d - dp[i-1];\n for j in (i*2..=n).step_by(i) {\n dp[j] += d;\n }\n }\n\n let ans = dp[n];\n println!(ans);\n }\n } // solution end\n\n out.flush()?;\n Ok(())\n}\n\n\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "399e32fa5a9e8a619a7f7a70944b9703", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Reverse, max, min}, collections::{BTreeMap, BinaryHeap, HashMap, HashSet}, error::Error, fmt::Display, hash::{Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::Peekable, mem::swap, ops::{Not, Sub}, process::exit, rc::Rc, str::{FromStr, from_utf8, from_utf8_unchecked}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read(); };\n ($t: ty) => { read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$t>(),)*); };\n [$t: ty; $n: expr] => { read_vec::<$t>($n); };\n}\nmacro_rules! println { \n () => { out(|x| writeln!(x).unwrap()); };\n ($exp: expr) => { out(|x| writeln!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| writeln!(x, $fmt, $($arg)*).unwrap()); }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| write!(x, \"{}\", $exp).unwrap()); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| write!(x, $fmt, $($arg)*).unwrap()); }\n}\n\nfn out_flush() { out(|x| x.flush().unwrap()); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().unwrap() }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\ntrait JoinToStr { \n fn join_to_str(&mut self, sep: &str) -> String;\n fn concat_to_str(&mut self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(&mut self, sep: &str) -> String {\n let mut res = String::new();\n match self.next() {\n None => res,\n Some(first) => {\n res.push_str(&first.to_string());\n loop {\n match self.next() {\n None => break,\n Some(item) => {\n res.push_str(sep);\n res.push_str(&item.to_string())\n }\n }\n }\n res\n }\n }\n }\n \n fn concat_to_str(&mut self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let n = $n;\n let mut list = Vec::with_capacity(n);\n for $i in 0..n {\n list.push($gen);\n }\n list\n }};\n ($n:expr , $gen:expr) => { veci!($n, __: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\n// * end commons * //\n\nmod modint {\n\n use std::{convert::Infallible, iter::Sum, mem::swap, ops::AddAssign};\n\n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n\n fn pow_mod(self, exponent: u64, modulus: u32) -> u32 {\n pow_mod_raw(self.rem_euclid_u32(modulus), exponent, modulus)\n }\n fn mul_mod(self, rhs: Rhs, modulus: u32) -> u32 {\n mul_mod_u32(self.rem_euclid_u32(modulus), rhs.rem_euclid_u32(modulus), modulus)\n }\n\n fn mod_pow_vec(self, n: usize, modulus: u32) -> Vec {\n let a = self.rem_euclid_u32(modulus);\n let mut res = vec![0u32; n+1];\n if modulus == 1 { return res; }\n res[0] = 1;\n for i in 1..=n {\n res[i] = mul_mod_u32(a, res[i-1], modulus);\n }\n res\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n ((a as u64) * (b as u64) % (m as u64)) as u32\n }\n\n // for a, b < m, undefined otherwise\n #[inline]\n pub fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n sub_mod_raw(a, m-b, m)\n }\n #[inline]\n pub fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n pub fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n return r as u32;\n }\n\n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n pub fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n std::mem::swap(&mut s, &mut t);\n std::mem::swap(&mut m0, &mut m1);\n }\n\n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\n #[repr(transparent)]\n pub struct ModInt { pub val: u32 }\n\n impl ModInt {\n #[inline(always)]\n pub fn modulus() -> u32 { crate::get_modulus() }\n pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline]\n pub fn raw(val: u32) -> Self { Self { val } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n if gcd != 1 { panic!(\"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus()) }\n Self::raw(x as u32)\n }\n pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n\n #[inline]\n pub fn mi(val: I) -> ModInt { ModInt::new(val) }\n\n impl From for ModInt {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl std::str::FromStr for ModInt {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl std::fmt::Display for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Display::fmt(&self.val, f)\n }\n }\n impl std::fmt::Debug for ModInt {\n #[inline]\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl std::ops::Neg for ModInt {\n type Output = ModInt;\n\n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n //Self::raw(norm(self.val.wrapping_neg(), Self::modulus()))\n }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.val, Self::modulus()))\n }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output { self * rhs.inv() }\n }\n\n impl std::ops::Add for ModInt {\n type Output = ModInt;\n #[inline]\n fn add(self, rhs: I) -> Self::Output { self + Self::new(rhs) }\n }\n impl std::ops::Sub for ModInt {\n type Output = ModInt;\n #[inline]\n fn sub(self, rhs: I) -> Self::Output { self - Self::new(rhs) }\n }\n impl std::ops::Mul for ModInt {\n type Output = ModInt;\n #[inline]\n fn mul(self, rhs: I) -> Self::Output { self * Self::new(rhs) }\n }\n impl std::ops::Div for ModInt {\n type Output = ModInt;\n #[inline]\n fn div(self, rhs: I) -> Self::Output { self / Self::new(rhs) }\n }\n\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; }\n }\n impl std::ops::AddAssign for ModInt {\n #[inline]\n fn add_assign(&mut self, rhs: I) { *self = *self + rhs; }\n }\n impl std::ops::SubAssign for ModInt {\n #[inline]\n fn sub_assign(&mut self, rhs: I) { *self = *self - rhs; }\n }\n impl std::ops::MulAssign for ModInt {\n #[inline]\n fn mul_assign(&mut self, rhs: I) { *self = *self * rhs; }\n }\n impl std::ops::DivAssign for ModInt {\n #[inline]\n fn div_assign(&mut self, rhs: I) { *self = *self / rhs; }\n }\n\n impl std::iter::Sum for ModInt {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), std::ops::Add::add)\n }\n }\n impl std::iter::Product for ModInt {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), std::ops::Mul::mul)\n }\n }\n impl<'a> std::iter::Sum<&'a Self> for ModInt {\n #[inline] fn sum>(iter: I) -> ModInt {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a> std::iter::Product<&'a Self> for ModInt {\n #[inline] fn product>(iter: I) -> ModInt {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n}\n\n// const MODULUS: u32 = 998_244_353;\n// //const MODULUS: u32 = 1_000_000_007;\n// #[inline(always)]\n// fn get_modulus() -> u32 { MODULUS }\n\nstatic MODULUS: Unsync> = Unsync(Cell::new(0));\n#[inline] fn get_modulus() -> u32 { MODULUS.0.get() }\n#[inline] fn set_modulus(value: u32) { MODULUS.0.set(value) }\n\nuse crate::modint::*;\n\n#[allow(non_snake_case, unused_macros)]\nfn main() -> Result<(), Box> {\n let num_cases = 1;//read!(i32);\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n set_modulus(read!());\n\n let mut dp = vec![mi(0); n+1];\n dp[1] = mi(1);\n dp[2] = mi(2);\n for i in 2..n {\n let d = dp[i];\n dp[i+1] += d + d + 1;\n let d = d - dp[i-1];\n for j in (i*2..=n).step_by(i) {\n dp[j] += d;\n }\n }\n\n let ans = dp[n];\n println!(ans); //\n }\n\n out_flush();\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "57e7e0ea2e63ff1dcce8ba31c345cd81", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\r\n let (r, w) = (std::io::stdin(), std::io::stdout());\r\n let mut sc = IO::new(r.lock(), w.lock());\r\n\r\n let n: usize = sc.read();\r\n let m: i64 = sc.read();\r\n let mut dp = vec![0; n + 1];\r\n dp[n] = 1;\r\n let mut sum = vec![0; n + 2];\r\n sum[n] = sum[n + 1] + dp[n];\r\n\r\n for i in (1..n).rev() {\r\n dp[i] += sum[i + 1] - sum[n + 1];\r\n dp[i] %= m;\r\n\r\n for z in 2.. {\r\n let from = i * z;\r\n if from > n {\r\n break;\r\n }\r\n let to = from + z;\r\n dp[i] += sum[from] - sum[to.min(n + 1)];\r\n dp[i] %= m;\r\n }\r\n\r\n sum[i] = sum[i + 1] + dp[i];\r\n sum[i] %= m;\r\n }\r\n println!(\"{}\", dp[1]);\r\n}\r\n\r\npub struct IO(R, std::io::BufWriter);\r\n\r\nimpl IO {\r\n pub fn new(r: R, w: W) -> IO {\r\n IO(r, std::io::BufWriter::new(w))\r\n }\r\n pub fn write(&mut self, s: S) {\r\n use std::io::Write;\r\n self.1.write_all(s.to_string().as_bytes()).unwrap();\r\n }\r\n pub fn read(&mut self) -> T {\r\n use std::io::Read;\r\n let buf = self\r\n .0\r\n .by_ref()\r\n .bytes()\r\n .map(|b| b.unwrap())\r\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\r\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\r\n .collect::>();\r\n unsafe { std::str::from_utf8_unchecked(&buf) }\r\n .parse()\r\n .ok()\r\n .expect(\"Parse error.\")\r\n }\r\n pub fn usize0(&mut self) -> usize {\r\n self.read::() - 1\r\n }\r\n pub fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.read()).collect()\r\n }\r\n pub fn chars(&mut self) -> Vec {\r\n self.read::().chars().collect()\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "ab2b738963f53963dac8dc07dc6a645c", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\r\nmod modint {\r\n\r\n #[allow(dead_code)]\r\n pub struct Mod;\r\n impl ConstantModulo for Mod {\r\n const MOD: u32 = 1_000_000_007;\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub struct StaticMod;\r\n static mut STATIC_MOD: u32 = 0;\r\n impl Modulo for StaticMod {\r\n fn modulo() -> u32 {\r\n unsafe { STATIC_MOD }\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl StaticMod {\r\n pub fn set_modulo(p: u32) {\r\n unsafe {\r\n STATIC_MOD = p;\r\n }\r\n }\r\n }\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n }\r\n\r\n pub trait ConstantModulo {\r\n const MOD: u32;\r\n }\r\n\r\n impl Modulo for T\r\n where\r\n T: ConstantModulo,\r\n {\r\n fn modulo() -> u32 {\r\n T::MOD\r\n }\r\n }\r\n\r\n pub struct ModInt(pub u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::new_unchecked(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n ModInt::new_unchecked(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 - rhs.0;\r\n if d >= T::modulo() {\r\n d += T::modulo();\r\n }\r\n ModInt::new_unchecked(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n let v = self.0 as u64 * rhs.0 as u64 % T::modulo() as u64;\r\n ModInt::new_unchecked(v as u32)\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::new_unchecked(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n ModInt::new_unchecked(0)\r\n }\r\n pub fn one() -> Self {\r\n ModInt::new_unchecked(1)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new(d: u32) -> Self {\r\n ModInt::new_unchecked(d % T::modulo())\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n pub fn inv(&self) -> Self {\r\n assert!(self.0 != 0);\r\n self.pow(T::modulo() as u64 - 2)\r\n }\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n\r\nuse modint::*;\r\ntype M = ModInt;\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nfn naive() {\r\n input! {\r\n n: usize,\r\n m: u32,\r\n }\r\n StaticMod::set_modulo(m);\r\n let mut dp = vec![M::zero(); n + 1];\r\n dp[n] = M::one();\r\n for i in (1..n).rev() {\r\n let mut v = dp[i + 1];\r\n for x in (2..).map(|p| p * i).take_while(|x| *x <= n) {\r\n v += dp[x];\r\n }\r\n for x in (2..).map(|p| p * (i + 1)).take_while(|x| *x <= n) {\r\n v -= dp[x];\r\n }\r\n dp[i] = v + dp[i + 1];\r\n }\r\n println!(\"{:?}\", dp[1] - dp[2]);\r\n}\r\n\r\nfn main() {\r\n naive();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "8daa1f09d5def97ed6961ba3a9baf598", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io;\nuse std::cmp;\n\nfn main() {\n if let Err(e) = run() {\n println!(\"{}\", e);\n }\n}\n\nfn run() -> Result<(), Box> {\n io::stdin().read_line(&mut String::new());\n let mut s = String::new();\n io::stdin().read_line(&mut s);\n let mut v = 0;\n let mut max_v = 0;\n for b in s.trim().as_bytes() {\n match *b {\n 65...90 => v += 1,\n 32 => {\n max_v = cmp::max(max_v, v);\n v = 0;\n },\n _ => (),\n }\n }\n println!(\"{}\", cmp::max(max_v, v));\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "fd45bab22b319bd89caa671810b47063", "src_uid": "d3929a9acf1633475ab16f5dfbead13c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn volume_of(word: &str) -> usize {\n word.chars().filter(|x| x.is_uppercase()).count()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let _n: usize = read(sin);\n let s: String = read(sin);\n\n println!(\"{}\", s.split(\" \").map(|x| volume_of(x)).max().unwrap_or(0));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a8d8c9c045f054def4dc118bafe90dd7", "src_uid": "d3929a9acf1633475ab16f5dfbead13c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/problemset/problem/837/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(isize);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\npub trait CharExt: Copy {\n fn is_digit(self, radix: u32) -> bool;\n fn to_digit(self, radix: u32) -> Option;\n fn is_alphabetic(self) -> bool;\n fn is_lowercase(self) -> bool;\n fn is_uppercase(self) -> bool;\n fn is_whitespace(self) -> bool;\n fn is_alphanumeric(self) -> bool;\n fn to_lowercase(self) -> Self;\n fn to_uppercase(self) -> Self;\n}\n\nmacro_rules! impl_u8 {\n ($meth:ident($($arg:ident : $ty:ty),*) -> $ret:ty) => {\n fn $meth(self, $($arg : $ty),*) -> $ret {\n let c = self as char;\n c.$meth($($arg),*)\n }\n }\n}\n\nimpl CharExt for u8 {\n impl_u8!(is_digit(radix: u32) -> bool);\n impl_u8!(to_digit(radix: u32) -> Option);\n impl_u8!(is_alphabetic() -> bool);\n impl_u8!(is_lowercase() -> bool);\n impl_u8!(is_uppercase() -> bool);\n impl_u8!(is_whitespace() -> bool);\n impl_u8!(is_alphanumeric() -> bool);\n fn to_lowercase(self) -> Self {\n let c = self as char;\n c.to_lowercase()\n .next()\n .map(|c| c as u8)\n .unwrap_or(self)\n }\n fn to_uppercase(self) -> Self {\n let c = self as char;\n c.to_uppercase()\n .next()\n .map(|c| c as u8)\n .unwrap_or(self)\n }\n}\n\n// -----------------------------------------------------------------------------\n\nfn volume(word: &[u8]) -> u32 {\n word.iter()\n .filter_map(|&c| if c.is_uppercase() { Some(()) } else { None })\n .count()\n as u32\n}\n\nfn main() {\n use std::io::{self, Write, BufWriter};\n let __stdout = io::stdout();\n let mut __out = BufWriter::with_capacity(4096, __stdout.lock());\n\n macro_rules! put {\n ($fmt:expr) => { write!(__out, $fmt).unwrap(); };\n ($fmt:expr, $($arg:expr),+) => { write!(__out, $fmt, $($arg),+).unwrap(); }\n }\n macro_rules! putln {\n () => { writeln!(__out, \"\").unwrap(); };\n ($fmt:expr) => { writeln!(__out, $fmt).unwrap(); };\n ($fmt:expr, $($arg:expr),+) => { writeln!(__out, $fmt, $($arg),+).unwrap(); }\n }\n macro_rules! fflush {\n () => { __out.flush().unwrap(); }\n }\n\n scanln!(_n: u32);\n scanln!(s: Vec);\n let mut max_volume = 0;\n for word in s {\n let vol = volume(word.as_bytes());\n max_volume = std::cmp::max(vol, max_volume);\n }\n println!(\"{}\", max_volume);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0fcedfae55ea9115ee32928c74b4b063", "src_uid": "d3929a9acf1633475ab16f5dfbead13c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n\nfn read_string() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n input\n}\n\nfn read_int() -> u64 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n let x = input.trim().parse::().unwrap();\n input.clear();\n x\n}\n\n\nfn main(){\n let i = read_int() + 2;\n let s = read_string().replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n let vec: Vec<&str> = s.split(\"\").collect();\n let caps = vec![\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"];\n let mut max = 0;\n let mut tmp = 0;\n for x in 0..i{\n for cap in 0..caps.len(){\n if vec[x as usize] == caps[cap as usize]{\n tmp = tmp + 1;\n } \n }\n if (vec[x as usize] == \" \") || (vec[x as usize] == \"\"){\n if max < tmp{\n max = tmp;\n }\n tmp = 0;\n }\n }\n println!(\"{:?}\", max);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "672bfcb4d51e9eb4bcaa6a50a848536b", "src_uid": "d3929a9acf1633475ab16f5dfbead13c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n let cin = std::io::stdin();\n let mut s = String::new();\n cin.read_line(&mut s)\n .expect(\" \");\n cin.read_line(&mut s)\n .expect(\" \");\n let mut ans = 0;\n for sub in s.trim().split(\" \"){\n let mut ct = 0;\n for c in sub.chars(){\n if c >= 'A' && c <= 'Z' {\n ct += 1;\n }\n }\n if ct > ans {\n ans = ct;\n }\n }\n println!(\"{}\",ans);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "98746dee1c5ddeb0816799b5e83a1222", "src_uid": "d3929a9acf1633475ab16f5dfbead13c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let s = {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n input.clear();\n stdin().read_line(&mut input).unwrap();\n input\n };\n\n let ans = s.split_whitespace().map(|w| {\n w.chars().filter(|c| c.is_uppercase()).count()\n }).max().unwrap();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5fecea22714342097f71ac3127b98b65", "src_uid": "d3929a9acf1633475ab16f5dfbead13c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut a = String::new();\n let mut b = String::new();\n let mut c = String::new();\n\n io::stdin()\n .read_line(&mut a)\n .unwrap();\n\n io::stdin()\n .read_line(&mut b)\n .unwrap();\n\n io::stdin()\n .read_line(&mut c)\n .unwrap();\n\n let a: i64 = a.trim().parse().unwrap();\n let b: i64 = b.trim().parse().unwrap();\n let c: i64 = c.trim().parse().unwrap();\n\n let mut maxima = 0;\n let uno = (a+b)*c;\n let dos = a*b+c;\n maxima = std::cmp::max(uno,dos);\n let tres = a+b*c;\n maxima = std::cmp::max(maxima,tres);\n let cuatro = a+b+c;\n maxima = std::cmp::max(maxima,cuatro);\n let cinco = a*b*c;\n maxima = std::cmp::max(maxima,cinco);\n let seis = a*(b+c);\n maxima = std::cmp::max(maxima,seis);\n\n println!(\"{}\", maxima);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "9a44d15bd27fc4d1d7d6dd3b3aedfe58", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buf = String::new();\n let mut r = [0i32; 3];\n for i in 0..3 {\n buf.clear();\n io::stdin().read_line(&mut buf).unwrap();\n r[i] = buf.trim().parse::().unwrap();\n }\n let s = [\n r[0] + r[1] + r[2],\n (r[0] + r[1]) * r[2],\n r[0] * r[1] + r[2],\n r[0] * r[1] * r[2],\n r[0] * (r[1] + r[2]),\n r[0] + r[1] * r[2],\n ];\n let s = s.iter().max().unwrap();\n println!(\"{}\", s);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "374b7d6e7b54ffd88fe8fa6c17b19ee6", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let a: i32 = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n line.trim().parse().unwrap()\n };\n let b: i32 = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n line.trim().parse().unwrap()\n };\n let c: i32 = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n line.trim().parse().unwrap()\n };\n\n let best = |a, b| std::cmp::max(a + b, a * b);\n let x = std::cmp::max(best(best(a, b), c), best(a, best(b, c)));\n println!(\"{:?}\", x);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "362709dcc2637558f7ab03a15117d1d1", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused)] use std::io::*;\n#[allow(unused)] use std::collections::*;\n#[allow(unused)] use std::mem::*;\n#[allow(unused)] use std::num::*;\n#[allow(unused)] use std::cmp::*;\n#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).collect();\n let mut cnt : usize = 0;\n fn next(cnt: &mut usize, p: &Vec<&str>) -> T where T:std::str::FromStr\n { *cnt += 1; p[*cnt-1].parse().ok().unwrap() }\n ($(next::<$x>(&mut cnt, &s)), +)\n }}; }\n#[allow(unused)] macro_rules! arr { ($n:expr, $T:ty) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let mut s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0);\n let mut v = Vec::new(); v.reserve(($n) as usize);\n for st in s { v.push(st.parse::<$T>().unwrap()); } v\n }}; }\n\n///////////////////////////////////////////////////////////////////////////////\nfn main()\n{\n let a = scan!(i32);\n let b = scan!(i32);\n let c = scan!(i32);\n println!(\"{}\", max(max(max(max(max(\n a + b + c,\n a * b * c),\n (a + b) * c),\n a + b * c),\n a * (b + c)),\n a * b + c));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "b910eaac5855376bcb6b0c0c6b4c196b", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut a = String::new();\n let mut b = String::new();\n let mut c = String::new();\n\n io::stdin()\n .read_line(&mut a)\n .unwrap();\n\n io::stdin()\n .read_line(&mut b)\n .unwrap();\n\n io::stdin()\n .read_line(&mut c)\n .unwrap();\n\n let a: i64 = a.trim().parse().unwrap();\n let b: i64 = b.trim().parse().unwrap();\n let c: i64 = c.trim().parse().unwrap();\n\n println!(\"{}\",\n [\n (a+b)*c,\n a*b+c,\n a+b*c,\n a+b+c,\n a*b*c,\n a*(b+c)\n ]\n .iter()\n .max()\n .unwrap()\n );\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "05c190e47cbe7c377a78691fe452a07e", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use rand::Rng;\n\nuse std::collections::*;\nuse std::io;\n\nfn trim_newline(s: &mut String) {\n if s.ends_with('\\n') {\n s.pop();\n if s.ends_with('\\r') {\n s.pop();\n }\n }\n}\nmacro_rules! parse_input {\n ($t:ident) => {{\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n trim_newline(&mut input_line);\n input_line.parse::<$t>().unwrap()\n }};\n}\n\nmacro_rules! split_input {\n ($t:ident) => {{\n parse_input!(String)\n .split(\" \")\n .map(|z| z.parse::<$t>().unwrap())\n .collect::>()\n }};\n}\n\nfn main() {\n let mut a = parse_input!(usize);\n let mut b = parse_input!(usize);\n let mut c = parse_input!(usize);\n if a == 1 {\n b += 1;\n }\n if b == 1 {\n if c < a {\n c += 1;\n } else {\n a += 1;\n }\n }\n if c == 1 {\n b += 1;\n }\n\n println!(\"{}\", a * b * c);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "533adc0d22340dca38a88a950fe973e1", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut a = String::new();\n let mut b = String::new();\n let mut c = String::new();\n\n io::stdin().read_line(&mut a).unwrap();\n io::stdin().read_line(&mut b).unwrap();\n io::stdin().read_line(&mut c).unwrap();\n\n let a: u16 = a.trim().parse().unwrap();\n let b: u16 = b.trim().parse().unwrap();\n let c: u16 = c.trim().parse().unwrap();\n\n let mut max_value: u16 = 0;\n\n if (a + b + c) > max_value {\n max_value = a + b + c;\n } \n if (a * b * c) > max_value {\n max_value = a * b * c;\n }\n if (a * b + c) > max_value {\n max_value = a * b + c;\n }\n if (a + b * c) > max_value {\n max_value = a + b * c;\n }\n\n if ((a + b) * c) > max_value {\n max_value = (a + b) * c;\n }\n if (a * (b + c)) > max_value {\n max_value = a * (b + c);\n }\n\n if (a + (b * c)) > max_value {\n max_value = a + (b * c);\n }\n if ((a * b) + c) > max_value {\n max_value = (a * b) + c;\n }\n\n println!(\"{}\", max_value);\n}\n\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "182877142a53e1370759682dff223912", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::cmp;\n\nfn main() {\n let (a, ) = R!(i32);\n let (b, ) = R!(i32);\n let (c, ) = R!(i32);\n println!(\"{}\", vec![a+b+c, a+b*c, a*b+c, a*b*c, (a+b)*c, a*(b+c)].into_iter().fold(0, cmp::max));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "2209327d9ca5ce3ccb3ff208ca683db8", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\nuse std::thread;\n\nfn exec() {\n let mut sc = Scanner::new();\n let n: i64 = sc.ne();\n let ans = if is_prime(n) {\n 1\n } else if n & 1 == 0 || is_prime(n - 2) {\n 2\n } else {\n 3\n };\n println!(\"{}\", ans);\n}\n\nfn is_prime(x: i64) -> bool {\n let mut y = 2;\n while y * y <= x {\n if x % y == 0 {\n return false;\n }\n y += 1;\n }\n x != 1\n}\nconst DEFAULT_STACK: usize = 16 * 1024 * 1024;\nfn main() {\n let builder = thread::Builder::new();\n let th = builder.stack_size(DEFAULT_STACK);\n let handle = th.spawn(|| { exec(); }).unwrap();\n let _ = handle.join();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => return None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => panic!(\"parse error\"),\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "0436799f0b3a204acf9991c81de11f47", "src_uid": "684ce84149d6a5f4776ecd1ea6cb455b", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn is_prime(n: u64) -> bool {\n if n <= 1 {\n return false;\n }\n for k in (2..).take_while(|k| k * k <= n) {\n if n % k == 0 {\n return false;\n }\n }\n true\n}\n\nfn run() {\n input! {\n n: u64,\n }\n let ans = if is_prime(n) {\n 1\n } else if n % 2 == 0 {\n 2\n } else if is_prime(n - 2) {\n 2\n } else {\n 3\n };\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "69620c56a290673bece9110d10f8b293", "src_uid": "684ce84149d6a5f4776ecd1ea6cb455b", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nstruct Prime {\n a: Vec,\n al: usize,\n t: Vec,\n}\n\n#[allow(dead_code)]\nimpl Prime {\n fn new(n: usize) -> Self {\n let mut t = vec![2; 1];\n let s = (n as f64).sqrt().round() as usize + 3;\n let mut a = vec![true; s];\n a[0] = false;\n a[1] = false;\n for i in (4..s).step_by(2) {\n a[i] = false;\n }\n for i in (3..s).step_by(2) {\n if !a[i] {\n continue;\n }\n t.push(i);\n if i * i < s {\n for j in ((i * i)..s).step_by(i * 2) {\n a[j] = false;\n }\n }\n }\n let al = a.len();\n Prime { a, al, t }\n }\n\n fn is_prime(&self, x: usize) -> bool {\n if x < self.al {\n return self.a[x];\n }\n\n for c in self.t.iter() {\n if x % c == 0 {\n return false;\n }\n }\n\n true\n }\n}\n\n#[allow(dead_code)]\nfn solve() -> Vec {\n let mut input = \"\".split_ascii_whitespace();\n let mut read = || loop {\n if let Some(word) = input.next() {\n break word;\n }\n input = {\n let mut input = \"\".to_owned();\n io::stdin().read_line(&mut input).unwrap();\n if input.is_empty() {\n panic!(\"reached EOF\");\n }\n Box::leak(input.into_boxed_str()).split_ascii_whitespace()\n };\n };\n macro_rules! read(($ty:ty) => (read().parse::<$ty>().unwrap()));\n\n let mut rr = vec![\"\".to_string(); 0];\n\n let t = 1;\n for _ in 0..t {\n let n = read!(usize);\n\n let mut r = 3;\n if n > 3 && n % 2 == 0 {\n r = 2;\n } else {\n let pr = Prime::new(n);\n if pr.is_prime(n) {\n r = 1;\n } else if pr.is_prime(n - 2) {\n r = 2;\n }\n }\n\n rr.push(format!(\"{}\", r));\n }\n\n rr\n}\n\n#[allow(dead_code)]\nfn main() {\n let output = solve();\n println!(\"{}\", output.join(\"\\n\"));\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "775ebd0ab816fe9c2116becb3a62d212", "src_uid": "684ce84149d6a5f4776ecd1ea6cb455b", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n\n std::io::stdin().read_line(&mut input).expect(\"Read to input failed!\");\n\n let mut input = input.trim().split(' ');\n let mut base_number = input\n .next()\n .unwrap()\n .parse::()\n .expect(\"BASE_NUMBER::Parse to i32 failed!\");\n\n let mut amount = input\n .next()\n .unwrap()\n .parse::()\n .expect(\"AMOUNT::Parse to i32 failed!\");\n\n\n let mut result_number = i32::default();\n\n for i in (0..amount) {\n\n let mut last_digit = base_number % 10;\n\n if last_digit == 0 {\n base_number /= 10;\n }else {\n base_number -= 1;\n }\n\n }\n\n\n println!(\"{}\", base_number);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c8285c24c875372bc836b95b5e4128f5", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut n: usize = scan.next();\n let k: usize = scan.next();\n for _ in 0..k {\n if n % 10 == 0 { n /= 10; }\n else { n -= 1; }\n }\n println!(\"{}\", n);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7c9d38286021b669b12f875165d7c42d", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nfn parse_array() -> Vec {\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n a_str\n .trim()\n .split(\" \")\n .map(|x| x.parse::().expect(\"parse error\"))\n .collect()\n}\n\nfn main() {\n let (mut n,k) = parse_line!(u128, u32);\n for _ in 0..k {\n if n % 10 == 0 {\n n/=10;\n }else{\n n-=1;\n }\n }\n println!(\"{}\", n);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ba785757eb38991d2c2af77c906b5bf2", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn tanya(mut n: i64, k: i64) -> i64 {\n for _ in 0..k {\n if n % 10 == 0 {\n n /= 10;\n } else {\n n -= 1;\n }\n }\n n\n}\n\nfn main() -> io::Result<()> {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer)?;\n let mut parts = buffer.split_whitespace().map(|s| s.parse::());\n match (parts.next(), parts.next()) {\n (Some(Ok(a)), Some(Ok(b))) => println!(\"{}\", tanya(a,b)),\n _ => {},\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9dee8e03ac0856b87c7d787e8dc3ce2f", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn main() {\n let mut line = String::new();\n stdin().read_line(&mut line).ok().expect(\"read error\");\n line = line.trim().to_string();\n\n let split: Vec<&str> = line.trim().split_whitespace().collect();\n\n let mut n: i32 = split[0].parse().ok().unwrap();\n let mut k: i32 = split[1].parse().ok().unwrap();\n\n let output: i32 = subtract_number(n, k);\n println!(\"{}\", output);\n}\n\nfn subtract_number(mut n: i32, mut k: i32) -> i32 {\n if k == 0 {\n return n\n }\n\n if n % 10 != 0 {\n return subtract_number(n - 1, k - 1)\n }\n return subtract_number(n / 10, k - 1)\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4e01972973b650bacdb6f3bb337d666d", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main(){\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"Failed to read input\");\n\n let mut iter = buffer.split_whitespace();\n let mut first_number: i32 = iter.next().unwrap()\n .trim().parse().unwrap();\n let second_number: i32 = iter.next().unwrap()\n .trim().parse().unwrap();\n\n for k in 0..second_number {\n if first_number % 10 == 0 {\n first_number = first_number / 10;\n } else {\n first_number = first_number - 1;\n }\n } \n\n \n println!(\"{}\", first_number);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "24b69c5e9ed03a5c373d1a2ec15ac040", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let (n, k) = parse_arg();\n println!(\"{}\", resolver(n, k));\n}\n\nfn parse_arg() -> (usize, usize) {\n let mut text = String::new();\n stdin().read_line(&mut text).expect(\"msg: &str\");\n let v: Vec<&str> = text.trim().split_whitespace().collect();\n (\n v[0].parse().expect(\"msg: &str\"),\n v[1].parse().expect(\"msg: &str\"),\n )\n}\n\nfn resolver(n: usize, k: usize) -> usize {\n if k == 0 {\n return n;\n }\n if n % 10 == 0 {\n resolver(n / 10, k - 1)\n } else {\n resolver(n - 1, k - 1)\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4f009199b53ee0f4655089bdbc0f885b", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufWriter, stdin, stdout, Write};\n\nstruct Scanner {\n buffer: Vec\n}\n\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n buffer: vec![]\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed To Parse.\");\n }\n\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed To Read.\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scanner = Scanner::new();\n let out = &mut BufWriter::new(stdout());\n let (mut n, mut k) = (scanner.next::(), scanner.next::());\n while k > 0 {\n if n % 10 != 0 {\n n -= 1;\n } else {\n n /= 10;\n }\n\n k -= 1;\n }\n\n writeln!(out, \"{}\", n).ok();\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9386f60145e479ed0e7a719819ed4007", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut text = String::new();\n std::io::stdin().read_line(&mut text).expect(\"\");\n let it : Vec = text.trim().split_whitespace().map(|x| x.parse::().expect(\"\")).collect();\n let k = it[0];\n let n = it[1];\n let w = it[2];\n println!(\"{}\", std::cmp::max((w + 1) * w / 2 * k - n, 0));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "c3cbd802e47d92665f73c9712b7749ab", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::io::prelude::*;\nfn main() {\n let mut inputnum = String::new();\n io::stdin().read_line(&mut inputnum).expect(\"Error\");\n let mut result : Vec = inputnum.split_whitespace().map(|x| x.parse::().unwrap()).collect();\n let totalcost:i64= (result[0]*(result[2]*(result[2]+1)))/2;\n if totalcost-result[1]>0{\n println!(\"{}\",totalcost-result[1]);\n }\n else{\n println!(\"0\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "1ff6fbca56f8fd1ff0e5eeae22bee15e", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let read_in = buf.split_whitespace().map(|c| c.trim().parse::().unwrap()).collect::>();\n let (k, n, w) = (read_in[0], read_in[1], read_in[2]);\n let cost = w * (w + 1) / 2 * k;\n let ret: usize;\n if cost <= n {\n ret = 0;\n } else {\n ret = cost - n;\n }\n println!(\"{}\", ret);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "50ac52ecde0d1a59923e0e0b3ed6e32f", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read, Write, stdin, stdout};\n\npub struct Scanner {\n pub buffer: Vec,\n pub reader: U,\n}\nimpl Scanner {\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_to_string(&mut input).expect(\"Failed read\");\n self.buffer = input.lines().rev().map(String::from).collect();\n }\n }\n\n pub fn new(reader: U) -> Self {\n return Scanner {\n buffer: vec![],\n reader,\n };\n }\n}\n\npub fn solution_of_p546a(input: &mut Read, out: &mut Write) {\n let mut scanner = Scanner::new(input);\n let arr: Vec = scanner.next::().split(' ').map(|e| {\n e.parse::().unwrap()\n }).collect();\n let k = arr[0];\n let n = arr[1];\n let w = arr[2];\n let mut s = 0;\n for i in 1..=w {\n s += i * k;\n }\n if s > n {\n write!(out, \"{}\", s - n).ok();\n } else {\n write!(out, \"{}\", 0).ok();\n }\n}\n\nfn main() {\n solution_of_p546a(&mut stdin(), &mut stdout());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "64e26697dad655011a0249431002d4cc", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut inp = String::new();\n\tio::stdin().read_line(&mut inp).unwrap();\n\tlet inp = inp.trim();\n\tlet k: i32 = inp.split_whitespace().nth(0).unwrap().parse().unwrap();\n\tlet n: i32 = inp.split_whitespace().nth(1).unwrap().parse().unwrap();\n\tlet w: i32 = inp.split_whitespace().nth(2).unwrap().parse().unwrap();\n\tlet mut all_money = 0;\n\tfor i in 1..(w+1) {\n\t\tall_money += i*k;\n\t}\n\tif all_money - n <= 0 {\n\t\tprintln!(\"0\");\n\t} else {\n\t\tprintln!(\"{}\", all_money - n);\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "5387fb85db254194663b91f0c82c4cb2", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::io::prelude::*;\nfn main() {\n let mut inputnum = String::new();\n io::stdin().read_line(&mut inputnum).expect(\"Error\");\n let result : Vec = inputnum.split_whitespace().map(|x| x.parse::().unwrap()).collect();\n let totalcost:i64= (result[0]*(result[2]*(result[2]+1)))/2;\n if totalcost>result[1]{\n println!(\"{}\",totalcost-result[1]);\n }\n else{\n println!(\"0\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "e42c8d2aeb39f977e0e20953e6212909", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::prelude::*;\nuse std::cmp;\nmacro_rules! scan {\n ( $string:expr, $( $x:ty ),+ ) => {{\n let mut iter = $string.split_whitespace();\n ($(iter.next().and_then(|word| word.parse::<$x>().ok()).unwrap(),)*)\n }}\n}\n\n\n\nfn main(){\n\n let mut s= String::new();\n io::stdin().read_line(& mut s);\n\n let mut it= s.split_whitespace();\n let (k,n,w)= scan!(s,i64,i64,i64);\n\n\n let r =cmp::max(0i64, (w*(w+1))/2 *k -n);\n print!(\"{}\",r);\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "aea0cf8c6d301ae6ab35fc14e56243e2", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n io::stdin().read_to_string(&mut input)?;\n let mut ts = input.split_whitespace();\n let k : i64 = ts.next().expect(\"a\").parse().expect(\"b\");\n let n : i64 = ts.next().expect(\"c\").parse().expect(\"d\");\n let w : i64 = ts.next().expect(\"e\").parse().expect(\"f\");\n let a = (w * (w + 1) / 2 * k - n).max(0);\n println!(\"{}\", a);\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "d568a0173c4995a9a8740f8d208466c8", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let sum = (0..2).fold(0, |s,_| s + input.i().abs());\n let s = input.i();\n if s >= sum && (s - sum) % 2 == 0 {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1e2f3a6df1b08860e557fc6d210b8358", "src_uid": "9a955ce0775018ff4e5825700c13ed36", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: isize = scan.next();\n let b: isize = scan.next();\n let s: isize = scan.next();\n let x = a.abs() + b.abs();\n let result: bool = s >= x && (s - x) % 2 == 0;\n println!(\"{}\", if result { \"Yes\" } else { \"No\" });\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "f2cead8447ae579d029cb26562b249b3", "src_uid": "9a955ce0775018ff4e5825700c13ed36", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).unwrap();\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n })\n}\n\nfn main() {\n let (mut n,) = parse_line!(u32);\n if n % 2 != 0 {\n println!(\"{}\", 0);\n return;\n }\n n /= 2;\n println!(\"{}\", n / 2 - ((n % 2) ^ 1));\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "59256a26ec5d09dc92e55dcecbe4c252", "src_uid": "32b59d23f71800bc29da74a3fe2e2b37", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n let sol = if n % 2 == 1 {\n 0\n } else {\n (n - 2) / 4\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "d0412556516d9da92248f6aa3f28a009", "src_uid": "32b59d23f71800bc29da74a3fe2e2b37", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n#[derive(PartialEq, PartialOrd)]\npub struct Total(pub T);\nimpl Eq for Total {}\nimpl Ord for Total { fn cmp(&self, other: &Total) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap() }}\n\nconst MAX:usize = 100006;\nconst MOD:i64 = 1e9 as i64 + 7;\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nfn read_vec() -> Vec {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().split_whitespace()\n .map(|e| e.parse().ok().unwrap()).collect()\n}\n\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nuse std::hash::Hash;\nfn inc(map:&mut BTreeMap, key:T) {\n let count = map.entry(key).or_insert(0);\n *count += 1;\n}\n\nfn mod_pow(x:i64, n:i64, m:i64) -> i64 {\n let mut x = x;\n let mut n = n;\n let mut res = 1i64;\n while n > 0 {\n if n & 1 > 0 {\n res = res * x % m;\n }\n x = x * x % m;\n n >>= 1;\n }\n res\n}\n\n\nfn main() {\n input!{n:i64};\n if n%2 != 0 {\n println!(\"0\");\n return();\n }\n println!(\"{}\", (n/2-1)/2);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "870bf9456f7bf4513af361f964ac6f3f", "src_uid": "32b59d23f71800bc29da74a3fe2e2b37", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{ self, BufRead };\n\nmacro_rules! scan_to_vec {\n ($count:expr, $t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n for _ in 0..$count {\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_to_vec: failed at `handle.read_line`.\");\n result.push(buffer.trim().parse::<$t>()\n .expect(\"scan_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line_to_vec {\n ($t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_line(&mut buffer)\n .expect(\"scan_line_to_vec: failed at `handle.read_line`.\");\n \n for s in chunks.split_whitespace() {\n result.push(s.parse::<$t>()\n .expect(\"scan_line_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line {\n () => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n buffer\n });\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\nfn main() {\n let (n, k) = scan_line!(u64 usize);\n let mut factors = vec![];\n\n let mut i = 1;\n\n while i*i <= n {\n if n % i == 0 {\n factors.push(i);\n }\n i += 1;\n }\n\n for j in 0..factors.len() {\n let x = n / factors[j];\n factors.push(x);\n }\n factors.sort();\n factors.dedup();\n\n if k - 1 >= factors.len() {\n println!(\"-1\");\n } else {\n println!(\"{}\", factors[k - 1]);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "56dc1a9e31f1e01eab48471cbd2c4610", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::LinkedList;\n\nmacro_rules! read_line {\n ($v:ident) => {\n let mut temp = String::new();\n std::io::stdin().read_line(&mut temp).unwrap();\n let $v = temp;\n };\n (var, $t:ty, $($v:ident), *) => {\n read_line!(input_line);\n let mut iter = parse_token!($t, input_line);\n $(\n let $v = iter.next().unwrap();\n )*\n };\n (vec, $t:ty, $v:ident) => {\n read_line!(input_line);\n let iter = parse_token!($t, input_line);\n let $v: Vec<$t> = iter.collect();\n };\n ($($v:ident; $t:ty), *) => {\n read_line!(input_line);\n let mut iter = input_line.split_whitespace();\n $(\n let $v: $t = iter.next().unwrap().parse().unwrap();\n )*\n };\n}\n\nmacro_rules! parse_token {\n ($t:ty, $e:expr) => {\n $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());\n };\n}\n\nfn main() {\n read_line!(k;u64, n;u64);\n let mut divisors = LinkedList::new();\n let mut i = (k as f64).sqrt() as u64;\n if i * i == k {\n divisors.push_back(i);\n i -= 1;\n }\n while i >= 1 {\n if k % i == 0 {\n divisors.push_front(i);\n divisors.push_back(k / i);\n }\n i -= 1;\n }\n if n > divisors.len() as u64 {\n println!(\"-1\");\n } else {\n for (idx, divisor) in divisors.iter().enumerate() {\n if idx as u64 == n - 1 {\n println!(\"{}\", divisor);\n }\n }\n }\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "aab41d73e80a9cf730bcc1aa39821970", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn get_divisors(n: i64) -> Vec {\n let mut ans = vec![1];\n if n > 1 {\n ans.push(n);\n }\n let mut d = 2;\n while d * d <= n {\n if n % d == 0 {\n ans.push(d);\n if d * d < n {\n ans.push(n / d);\n }\n }\n d += 1;\n }\n ans.sort();\n ans\n}\n\nfn kth_smallest_divisor(n: i64, k: i64) -> i64 {\n let k = k as usize;\n let divisors = get_divisors(n);\n if k >= divisors.len() {\n return -1;\n }\n divisors[k]\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: i64 = scan.token();\n let k: i64 = scan.token();\n let ans = kth_smallest_divisor(n, k - 1); \n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "969a457158d531ac941e8e8034f656aa", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input_str = String::new();\n io::stdin().read_line(&mut input_str).expect(\"read error\");\n \n let input: Vec = input_str.split_whitespace()\n .map(|x| x.parse::().expect(\"parse error\"))\n .collect();\n\n let n = input[0];\n let k = input[1];\n\n let mut divisors: Vec = vec![];\n for divisor in 1..n+1 {\n if divisor * divisor > n { break; }\n if n % divisor == 0 { divisors.push(divisor); }\n }\n\n let another_divisors: Vec;\n another_divisors = divisors.iter().map(|x| n / x).filter(|x| x * x != n).rev().collect();\n\n divisors.extend(another_divisors);\n\n if (divisors.len() as i64) < k {\n println!(\"-1\");\n } else {\n println!(\"{}\", divisors[k as usize - 1]);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "8c4e4b67bb095b9e7e735c0ef9abd03e", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn calculate_nth_divisor(n: i64, k: i64) -> Option {\n if k > n {\n return None;\n }\n\n let mut divisors = Vec::::new();\n let max_small_divisor = (n as f64).sqrt().trunc() as i64;\n let mut count = k;\n\n for x in 1..=max_small_divisor {\n if n % x == 0 {\n count -= 1;\n divisors.push(x);\n }\n if count == 0 {\n return Some(x);\n }\n }\n\n let size = divisors.len() as i64;\n let n_is_square = n == divisors.last().unwrap().pow(2);\n if count > size || count == size && n_is_square {\n None\n } else {\n let mut idx = (size as i64 - count) as usize;\n if n_is_square {\n idx -= 1;\n }\n Some(n / divisors[idx])\n }\n}\n\nfn main() {\n let (n, k) = {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut iter = s.trim().split_ascii_whitespace();\n let n = iter.next().unwrap().parse::().unwrap();\n let k = iter.next().unwrap().parse::().unwrap();\n (n, k)\n };\n\n println!(\"{}\", calculate_nth_divisor(n, k).unwrap_or(-1));\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "8b7aa4bb432396afc160710b4a8c0c89", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn run() {\n input! {\n n: u64,\n k: usize1,\n }\n let mut a = vec![];\n for d in 1u64.. {\n if d * d > n {\n break;\n }\n if n % d == 0 {\n a.push(d);\n a.push(n / d);\n }\n }\n a.sort();\n a.dedup();\n if let Some(d) = a.get(k) {\n println!(\"{}\", *d);\n } else {\n println!(\"-1\");\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "1aaa3f6c609ab455f20e89fb7b4a0a94", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::*;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok();\n return ret;\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.is_err() || res.ok().unwrap() == 0 || u8b[0] <= ' ' as u8 {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = std::string::String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\nfn parse(s: &str) -> T { s.parse::().ok().unwrap() }\n\n#[allow(dead_code)]\nfn get() -> T { parse(&get_word()) }\n\nfn main() {\n let n: u64 = get();\n let k: u32 = get();\n let mut fact = Vec::new();\n {\n let mut i = 1;\n while i * i <= n {\n if n % i == 0 {\n fact.push(i);\n if i * i != n {\n fact.push(n / i);\n }\n }\n i += 1;\n }\n }\n fact.sort();\n if (fact.len() as u32) < k {\n println!(\"-1\");\n } else {\n println!(\"{}\", fact[k as usize - 1]);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "dacf198397febabfbcf22c6f1c72a04a", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn vvb(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet n = rin.u();\n\tlet mut c = v!([n+1] = 0);\n\tfor (a,b,v) in vec![(n/2+1,n,1),(1,n/2,-1),(1,2,-1),(1,n/2-1,2)] {\n\t\tfor i in a..=b {\n\t\t\tlet mut x = i;\n\t\t\tfor j in 2..=n {\n\t\t\t\twhile x % j == 0 {\n\t\t\t\t\tx /= j;\n\t\t\t\t\tc[j] += v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlet mut sol = 1_i64;\n\tfor i in 2..=n {\n\t\trep!{[c[i]]\n\t\t\tsol *= i as i64;\n\t\t}\n\t}\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "19e4dce8876cad625f7bc5987b57c270", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\nuse std::io::{stdin, stdout, BufWriter, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n let n = scan.next::() / 2;\n\n let mut res = 1;\n\n for i in 1..n {\n res *= i;\n res *= i + n;\n }\n println!(\"{:?}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "9e627cb9d0540d42b19927c91a8c24f6", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\nuse std::{fmt, ops, str};\n\nmacro_rules! read {\n ( $t:ty ) => {{\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.trim_end().parse::<$t>().ok().unwrap()\n }};\n ( $( $t:ty ),* ) => {{\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let mut iter = input.split_whitespace();\n ( $( iter.next().unwrap().parse::<$t>().unwrap() ),* )\n }};\n}\n\nstruct Ios(Vec);\n\nimpl str::FromStr for Ios {\n type Err = ();\n\n fn from_str(s: &str) -> Result {\n Ok(Ios(s.chars().collect()))\n }\n}\n\nimpl fmt::Display for Ios {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\", self.0.iter().collect::())\n }\n}\n\nstruct Iov(Vec);\n\nimpl str::FromStr for Iov {\n type Err = T::Err;\n\n fn from_str(s: &str) -> Result {\n let iter = s.split_whitespace();\n Ok(Iov(iter.map(|x| x.parse()).collect::>()?))\n }\n}\n\nimpl fmt::Display for Iov {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\",\n self.0.iter().map(|x| x.to_string())\n .collect::>().join(\" \")\n )\n }\n}\n\nimpl ops::Index for Iov {\n type Output = T;\n\n fn index(&self, i: usize) -> &Self::Output {\n self.0.get(i - 1).unwrap()\n }\n}\n\nfn solve(writer: &mut io::BufWriter) {\n let n = read!(i64);\n\n let ans = (1..=(n - 1)).fold(1, |acc, i| acc * i) / (n / 2);\n writeln!(writer, \"{}\", ans).ok();\n}\n\nfn main() {\n let stdout = io::stdout();\n let mut writer = io::BufWriter::new(stdout.lock());\n solve(&mut writer);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "2badeddf152e07886f8cce2b13fd9ced", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// -*- coding:utf-8-unix -*-\n\n#![allow(dead_code)]\n#![allow(unused_imports)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::io::*;\nuse std::mem;\nuse std::str;\nuse std::vec;\n\nconst INF: i64 = 1223372036854775807;\nconst MEM_SIZE: usize = 202020;\nconst MOD: i64 = 1000000007;\n// const MOD: i64 = 998244353;\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::stdin;\nuse std::io::stdout;\nuse std::io::Write;\n#[allow(dead_code)]\nfn read() -> T {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\n#[allow(dead_code)]\nfn readi() -> (i64) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n iter.next().unwrap().parse::().unwrap()\n}\n\n#[allow(dead_code)]\nfn read_vec() -> Vec {\n read::()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n#[allow(dead_code)]\nfn read_vec2(n: u32) -> Vec> {\n (0..n).map(|_| read_vec()).collect()\n}\n\n#[allow(dead_code)]\nfn readii() -> (i64, i64) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\n#[allow(dead_code)]\nfn readiii() -> (i64, i64, i64) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n#[allow(dead_code)]\nfn readuu() -> (usize, usize) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\nfn readcc() -> (char, char) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\n#[allow(dead_code)]\nfn readuuu() -> (usize, usize, usize) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\n#[allow(dead_code)]\nfn readuuuu() -> (usize, usize, usize, usize) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\nfn solve() {\n let n: usize = read();\n if n == 2 {\n println!(\"{:?}\", 1);\n return;\n }\n let mut res: u64 = 1;\n for i in 0..n / 2 {\n res *= (n - i) as u64;\n res /= (1 + i) as u64;\n }\n res /= 2;\n for i in 0..(n / 2) - 1 {\n res *= (i + 1) as u64;\n res *= (i + 1) as u64;\n }\n println!(\"{}\", res);\n return;\n}\n\nfn main() {\n solve()\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "c688f25b542659581f2befa92a0c2040", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead}; // (a)\n// use array2d::Array2D;\nuse std::cmp::{min, max};\n\nmacro_rules! numsin {\n () => (\n io::stdin().lock() // (0)\n .lines().next().unwrap().unwrap() // (1)\n .split(' ').map(|s| s.trim()) // (2)\n .filter(|s| !s.is_empty()) // (3)\n .map(|s| s.parse().unwrap()) // (4)\n .collect()\n )\n}\n\nfn calc_remain(left: i64, k: i64, l: i64, r: i64, a: i64) -> (i64, i64, i64, i64) {\n if (r - l) * k + left < a {\n return (-1, -1, -1, -1);\n }\n let ck = max(0, ((a - left) + k - 1) / k);\n let remain = k * ck + left - a;\n if ck + l < r {\n return (ck, remain, ck+1, k);\n }\n else {\n return (ck, remain, -1, -1);\n }\n}\n\nfn main() {\n let n: Vec = numsin!();\n let n = n[0];\n let mut d1: u64 = 1;\n let mut d2: u64 = 1;\n for i in 0..n/2 {\n d1 = d1 * (n - i);\n d2 = d2 * (i + 1);\n }\n println!(\"{}\", d1 / (n / 2) * d2 / (n / 2) / 2);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "185ab300c0094317150b0344a242b3e9", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\nfn main() {\n let n = get!(u64);\n let mut a = 1;\n let mut q = n;\n for i in 0..n / 2 {\n a *= q;\n q -= 1;\n }\n let mut b = 1;\n for i in (1..((n / 2) + 1)).rev() {\n b *= i;\n }\n let mut c = 1;\n for i in 1..(n / 2) {\n c *= i;\n }\n mydbg!(a, b, c);\n echo!((a / b) / 2 * c * c);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "9218097be8a52ab05390894d63ca9803", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes.by_ref().map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, [graph1; $len:expr]) => {{\n let mut g = vec![vec![]; $len];\n let ab = read_value!($next, [(usize1, usize1)]);\n for (a, b) in ab {\n g[a].push(b);\n g[b].push(a);\n }\n g\n }};\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n ($next:expr, usize1) => (read_value!($next, usize) - 1);\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n read_value!($next, [$t; len])\n }};\n ($next:expr, $t:ty) => ($next().parse::<$t>().expect(\"Parse error\"));\n}\n\n#[allow(unused)]\nmacro_rules! debug {\n ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());\n}\n#[allow(unused)]\nmacro_rules! debugln {\n ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n #[allow(unused)]\n macro_rules! putvec {\n ($v:expr) => {\n for i in 0..$v.len() {\n puts!(\"{}{}\", $v[i], if i + 1 == $v.len() {\"\\n\"} else {\" \"});\n }\n }\n }\n input!(n: usize);\n let mut dp = vec![vec![0u64; n + 1]; n + 1];\n dp[0][0] = 1;\n for i in 1..n + 1 {\n for j in 0..n + 1 {\n dp[i][j] = dp[i - 1][j];\n if j > 0 {\n dp[i][j] += dp[i - 1][j - 1];\n }\n }\n }\n let mut k = dp[n][n / 2] / 2;\n for i in 1..n / 2 {\n k *= i as u64;\n k *= i as u64;\n }\n puts!(\"{}\\n\", k);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "e9905ab81529723d369516467e9beff7", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub trait Zero: PartialEq + Sized {\n fn zero() -> Self;\n #[inline]\n fn is_zero(&self) -> bool {\n self == &Self::zero()\n }\n}\npub trait One: PartialEq + Sized {\n fn one() -> Self;\n #[inline]\n fn is_one(&self) -> bool {\n self == &Self::one()\n }\n}\nmacro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { # [inline] fn $ method () -> Self { $ e } }) *) * } ; }\nzero_one_impls ! ({ Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 0 } { Zero zero f32 f64 , 0. } { One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 1 } { One one f32 f64 , 1. }) ;\n#[macro_export]\nmacro_rules ! min { ($ e : expr) => { $ e } ; ($ e : expr , $ ($ es : expr) ,+) => { std :: cmp :: min ($ e , min ! ($ ($ es) ,+)) } ; }\n#[macro_export]\nmacro_rules ! chmin { ($ dst : expr , $ ($ src : expr) ,+) => { { let x = std :: cmp :: min ($ dst , min ! ($ ($ src) ,+)) ; $ dst = x ; } } ; }\n#[macro_export]\nmacro_rules ! max { ($ e : expr) => { $ e } ; ($ e : expr , $ ($ es : expr) ,+) => { std :: cmp :: max ($ e , max ! ($ ($ es) ,+)) } ; }\n#[macro_export]\nmacro_rules ! chmax { ($ dst : expr , $ ($ src : expr) ,+) => { { let x = std :: cmp :: max ($ dst , max ! ($ ($ src) ,+)) ; $ dst = x ; } } ; }\npub trait IterScan: Sized {\n type Output;\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option;\n}\npub trait MarkedIterScan: Sized {\n type Output;\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option;\n}\n#[derive(Clone, Debug)]\npub struct Scanner<'a> {\n iter: std::str::SplitAsciiWhitespace<'a>,\n}\nmod scanner_impls {\n use super::*;\n impl<'a> Scanner<'a> {\n #[inline]\n pub fn new(s: &'a str) -> Self {\n let iter = s.split_ascii_whitespace();\n Self { iter }\n }\n #[inline]\n pub fn scan(&mut self) -> ::Output {\n ::scan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn mscan(&mut self, marker: T) -> ::Output {\n marker.mscan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn scan_vec(&mut self, size: usize) -> Vec<::Output> {\n (0..size)\n .map(|_| ::scan(&mut self.iter).expect(\"scan error\"))\n .collect()\n }\n #[inline]\n pub fn iter<'b, T: IterScan>(&'b mut self) -> ScannerIter<'a, 'b, T> {\n ScannerIter {\n inner: self,\n _marker: std::marker::PhantomData,\n }\n }\n }\n macro_rules ! iter_scan_impls { ($ ($ t : ty) *) => { $ (impl IterScan for $ t { type Output = Self ; # [inline] fn scan <'a , I : Iterator < Item = &'a str >> (iter : & mut I) -> Option < Self > { iter . next () ?. parse ::<$ t > () . ok () } }) * } ; }\n iter_scan_impls ! (char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String) ;\n macro_rules ! iter_scan_tuple_impl { ($ ($ T : ident) *) => { impl <$ ($ T : IterScan) ,*> IterScan for ($ ($ T ,) *) { type Output = ($ (<$ T as IterScan >:: Output ,) *) ; # [inline] fn scan <'a , It : Iterator < Item = &'a str >> (_iter : & mut It) -> Option < Self :: Output > { Some (($ (<$ T as IterScan >:: scan (_iter) ?,) *)) } } } ; }\n iter_scan_tuple_impl!();\n iter_scan_tuple_impl!(A);\n iter_scan_tuple_impl ! (A B) ;\n iter_scan_tuple_impl ! (A B C) ;\n iter_scan_tuple_impl ! (A B C D) ;\n iter_scan_tuple_impl ! (A B C D E) ;\n iter_scan_tuple_impl ! (A B C D E F) ;\n iter_scan_tuple_impl ! (A B C D E F G) ;\n iter_scan_tuple_impl ! (A B C D E F G H) ;\n iter_scan_tuple_impl ! (A B C D E F G H I) ;\n iter_scan_tuple_impl ! (A B C D E F G H I J) ;\n iter_scan_tuple_impl ! (A B C D E F G H I J K) ;\n pub struct ScannerIter<'a, 'b, T> {\n inner: &'b mut Scanner<'a>,\n _marker: std::marker::PhantomData T>,\n }\n impl<'a, 'b, T: IterScan> Iterator for ScannerIter<'a, 'b, T> {\n type Item = ::Output;\n #[inline]\n fn next(&mut self) -> Option {\n ::scan(&mut self.inner.iter)\n }\n }\n}\npub mod marker {\n use super::*;\n use std::{iter::FromIterator, marker::PhantomData};\n #[derive(Debug, Copy, Clone)]\n pub struct Usize1;\n impl IterScan for Usize1 {\n type Output = usize;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(::scan(iter)?.checked_sub(1)?)\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct Chars;\n impl IterScan for Chars {\n type Output = Vec;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(iter.next()?.chars().collect())\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct CharsWithBase(pub char);\n impl MarkedIterScan for CharsWithBase {\n type Output = Vec;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n iter.next()?\n .chars()\n .map(|c| (c as u8 - self.0 as u8) as usize)\n .collect(),\n )\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct Collect::Output>> {\n size: usize,\n _marker: PhantomData (T, B)>,\n }\n impl::Output>> Collect {\n pub fn new(size: usize) -> Self {\n Self {\n size,\n _marker: PhantomData,\n }\n }\n }\n impl::Output>> MarkedIterScan for Collect {\n type Output = B;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n (0..self.size)\n .map(|_| ::scan(iter).expect(\"scan error\"))\n .collect::(),\n )\n }\n }\n}\nfn main() {\n #![allow(unused_imports, unused_macros)]\n use std::io::{stdin, stdout, BufWriter, Read as _, Write as _};\n let mut _in_buf = Vec::new();\n stdin().read_to_end(&mut _in_buf).expect(\"io error\");\n let _in_buf = unsafe { String::from_utf8_unchecked(_in_buf) };\n let mut scanner = Scanner::new(&_in_buf);\n macro_rules ! scan { () => { scan ! (usize) } ; (($ ($ t : tt) ,*)) => { ($ (scan ! ($ t)) ,*) } ; ([$ t : tt ; $ len : expr]) => { (0 ..$ len) . map (| _ | scan ! ($ t)) . collect ::< Vec < _ >> () } ; ([$ t : ty ; $ len : expr]) => { scanner . scan_vec ::<$ t > ($ len) } ; ([$ t : ty]) => { scanner . iter ::<$ t > () } ; ({ $ e : expr }) => { scanner . mscan ($ e) } ; ($ t : ty) => { scanner . scan ::<$ t > () } ; }\n let _out = stdout();\n let mut _out = BufWriter::new(_out.lock());\n macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules! echo {\n ($ iter : expr) => {\n echo!($iter, '\\n')\n };\n ($ iter : expr , $ sep : expr) => {\n let mut iter = $iter.into_iter();\n if let Some(item) = iter.next() {\n print!(\"{}\", item);\n }\n for item in iter {\n print!(\"{}{}\", $sep, item);\n }\n println!();\n };\n }\n let n = scan!();\n let mut ans = 1u128;\n for i in 0..n as u128 / 2 {\n ans = ans * (n as u128 - i) / (i + 1);\n }\n ans /= 2;\n let mut r = 1;\n for i in 1..n as u128 / 2 {\n r *= i;\n }\n ans *= r * r;\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "1ca4e73d35876cf6c00eeb264e45ecd5", "src_uid": "ad0985c56a207f76afa2ecd642f56728", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn get_in() -> String {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn main() {\n let (n, k) = {\n let i = get_in();\n let i: Vec = i.trim().split(\" \").map(|x| x.parse().unwrap()).collect();\n (i[0], i[1])\n };\n if (n / k) % 2 != 0 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "ffce068e1cd82ffae5834919b38d8251", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(n: u64, k: u64);\n if (n / k) % 2 == 0 {\n println!(\"NO\");\n } else {\n println!(\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "a091e22ee449c718034d3e18f20c4d97", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\nuse std::collections::{HashMap, HashSet};\nuse std::io::{stdin, stdout, BufWriter, Write};\nconst BITS: usize = 19;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn solve () {\n let mut scan = Scanner::default();\n let n: u64 = scan.next ();\n let k: u64 = scan.next ();\n let m = n/k;\n println! (\"{}\", if m%2 == 1 {\"YES\"} else {\"NO\"});\n}\n\nfn main() {\n let mut scan = Scanner::default();\n // let t = scan.next::();\n let t = 1;\n for _ in 0..t {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "47b6bae346bfe241b87c7736728e5f7e", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a: i64 = input.p();\n let b: i64 = input.p();\n if a / b % 2 == 1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "f441cef72a4dab47166781ae46d9c007", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut nk = String::new();\n io::stdin().read_line(&mut nk).expect(\"\");\n let nk: Vec<&str> = nk.trim().split(\" \").collect();\n let n: u64 = nk[0].parse().expect(\"\");\n let k: u64 = nk[1].parse().expect(\"\");\n if (n / k) & 1 == 1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "9c39aaed2a4fea6dc61985ea01718843", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> Vec {\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n return buf.trim().split(\" \")\n .map(|x| {x.parse::().unwrap() })\n .collect();\n}\n\nfn main (){\n let line = read_line();\n let (a, b) = (line[0], line[1]);\n let x = a/b;\n \n if (x % 2 == 0){\n println! (\"NO\");\n }\n else{\n println! (\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "4c7187f980f2476872256ca90feb76f4", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).unwrap();\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n })\n}\n\nfn main() {\n let (n, k) = parse_line!(u64, u64);\n println!(\"{}\", if n / k % 2 == 1 { \"YES\" } else { \"NO\" })\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "102c10eb7d010b2c338115132c025f86", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s)\n .expect(\"failed to read l2\");\n\n let values = s\n .split_whitespace()\n .map(|x| x.parse::())\n .collect::, _>>()\n .unwrap();\n\n assert!(values.len() == 2);\n let n = values[0];\n let k = values[1];\n\n if n <= k {\n println!(\"YES\");\n } else {\n let plays = n / k;\n if plays % 2 == 1{\n println!(\"YES\");\n } else {\n println!(\"NO\")\n }\n }\n\n\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "60c236ddbd351435d4ff897557602390", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let s = buf.trim().parse::().unwrap();\n let r = match s {\n s if s % 2 == 0 => s - s / 2,\n _ => -(s / 2 + 1),\n };\n\n println!(\"{}\", r);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "f49dde758480e3e97b6d9b139f125a2e", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::{Write};\nuse std::str;\n\n/// Reads white-space separated tokens one at a time.\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n /// Use \"turbofish\" syntax token::() to select data type of next token.\n ///\n /// # Panics\n ///\n /// Panics if there's an I/O error or if the token cannot be parsed as T.\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\npub fn scanner_from_file(filename: &str) -> Scanner> {\n let file = std::fs::File::open(filename).expect(\"Input file not found\");\n Scanner::new(io::BufReader::new(file))\n}\n\npub fn writer_to_file(filename: &str) -> io::BufWriter {\n let file = std::fs::File::create(filename).expect(\"Output file not found\");\n io::BufWriter::new(file)\n}\n\nfn solve() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n let n = scan.token::();\n let mut ans = n / 2;\n if n % 2 == 1 {\n ans = -ans-1;\n }\n out.write(format!(\"{}\", ans).as_bytes()).unwrap();\n // let k = scan.token::();\n // let mut arr = scan.token::().chars().collect::>();\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(64 * 1024 * 1024)\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "b86f33f6087080e7a0f9faedca92b143", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n \nfn main() {\n let mut n = String::new();\n stdin().read_line(&mut n).unwrap();\n let n: i64 = n.trim().parse().unwrap();\n \n if n%2 == 0 {\n println!(\"{}\", n/2);\n } else {\n println!(\"{}\",(n+1)/2*-1);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "fbdf665a8e37e8f0a1d6381e0874a427", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_val() -> i64 {\n return read_line().parse().unwrap();\n}\n\nfn f(k: i64) -> i64 {\n let mut res: i64 = 0;\n let mut n = k;\n loop {\n if n == 0 {\n break;\n }\n if n % 2 == 0 {\n res += n;\n } else {\n res -= n;\n }\n n -= 1;\n }\n return res;\n\n}\n\nfn f_(k: i64) -> i64 {\n let r = (k + 1) / 2;\n if k % 2 == 1 {\n return -r;\n }\n return r;\n}\n\nfn main() {\n let mut n = read_line_val();\n\n // for i in 1..n {\n // let res = f(i);\n // // let res_ = f_ (i);\n // println!(\"{} -> {} - {}\", i, res, res_);\n // }\n\n println!(\"{}\", f_(n));\n \n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "73e1bae4f2cd4b15ac7ca26d23bcb914", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\n\nfn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn read_int() -> T{\n read_str().parse::().ok().expect(\"Error\")\n}\n\nfn main() {\n let n: u64 = read_int();\n\n if n % 2 == 0 { println!(\"{}\", n / 2); }\n else { println!(\"-{}\", (n + 1) / 2); }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "41800bc4eee3d2f1aec5e805b1585d30", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_imports)]\nuse std::io::{self,Read};\n\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader : T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.s().parse::().unwrap();\n let sol = if n % 2 == 0 {\n n / 2\n } else {\n n / 2 - n\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "2b7f4b65a94dc3e0509429c17b937c21", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/486/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(n: u64);\n let mut res = ((n + 1) / 2) as i64;\n res *= if n % 2 == 0 { 1 } else { -1 };\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "188b45321fab860033079a2c31876313", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let n: f64 = read(sin);\n\n let ans = (n / 2.).ceil() as i64;\n\n println!(\"{}\", if n as i64 % 2 == 0 { ans } else { -1 * ans });\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "417c5b9123cfcfacd4a1ffbc5ec9bc89", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n line\n}\n\nfn main() {\n\n let luckies = vec![4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777];\n let n = read_line().trim().parse::().unwrap();\n\n if luckies.into_iter().any(|v| n % v == 0) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "c3fa73a94484bd817a3634e11bfbdf6b", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_imports)]\nuse std::io::{self,Read};\n\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader : T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i();\n let a = [4,7,44,47,74,77,444,447,474,477,744,747,774,777];\n let sol = if a.iter().any(|d| n % d == 0) {\n \"YES\"\n } else {\n \"NO\"\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "fc09f4580b81702a540c3b2337e9b260", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut ns = String::new();\n io::stdin().read_line(&mut ns).unwrap();\n let n: u16 = ns.trim().parse::().unwrap();\n let lucky: bool = ns.trim().replace(\"4\",\"\").replace(\"7\",\"\").len() == 0;\n if lucky {\n println!(\"YES\");\n return;\n }\n let nums = [4,7,44,47,74,77,444,447,474,477,744,747,774,777];\n for ni in nums.iter() {\n if n % ni == 0 {\n println!(\"YES\");\n return;\n }\n }\n println!(\"NO\");\n return;\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "31c884f41d0b9015fa60941c8510f67b", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nstatic LUCKY: &[u64] = &[4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777];\n\nfn main() {\n let stdin = io::stdin();\n let mut input = String::new();\n\n stdin.lock().read_line(&mut input).unwrap();\n\n let n: u64 = input.trim().parse().unwrap();\n\n if is_almost_lucky(n) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\nfn is_almost_lucky(n: u64) -> bool {\n for lucky in LUCKY {\n if n % lucky == 0 {\n return true;\n }\n }\n false\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "988a12bcd3ac7dffa60bcf3a43b3aabf", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut ns = String::new();\n io::stdin().read_line(&mut ns).unwrap();\n let n: u16 = ns.trim().parse::().unwrap();\n let nums = [4,7,44,47,74,77,444,447,474,477,744,747,774,777];\n for ni in nums.iter() {\n if n % ni == 0 {\n println!(\"YES\");\n return;\n }\n }\n println!(\"NO\");\n return;\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "b4014ce4f67d34bcecfda28bf73c70e2", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn is_lucky(n: u32) -> bool {\n let decimal = format!(\"{}\", n);\n decimal.chars().all(|x| x == '4' || x == '7')\n}\n\nfn main() {\n let mut n = String::new();\n\n io::stdin()\n .read_line(&mut n)\n .unwrap();\n\n let n : i64 = n.trim().parse().unwrap();\n\n let mut lucky = Vec::::new();\n\n for i in 1..1001 {\n if is_lucky(i) {\n lucky.push(i as i64);\n }\n }\n\n let mut flag = false;\n\n for d in lucky {\n if n % d == 0 {\n flag = true;\n }\n }\n\n if flag {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "2422a7fd6c1f10aa7539eb87c87d998a", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read, Write, stdin, stdout};\npub struct Scanner {\n pub buffer: Vec,\n pub reader: U,\n}\nimpl Scanner {\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_to_string(&mut input).expect(\"Failed read\");\n self.buffer = input.lines().rev().map(String::from).collect();\n }\n }\n\n pub fn new(reader: U) -> Self {\n return Scanner {\n buffer: vec![],\n reader,\n };\n }\n}\n\npub fn solution_of_p122a(input: &mut Read, out: &mut Write) {\n let mut scanner = Scanner::new(input);\n let num = scanner.next::().parse::().unwrap();\n let lucky_nums = vec![4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777];\n if is_almose_lucky(num, lucky_nums) {\n write!(out, \"YES\").ok();\n } else {\n write!(out, \"NO\").ok();\n }\n}\n\nfn is_almose_lucky(num: usize, arr: Vec) -> bool {\n if arr.contains(&num) {\n return true;\n }\n for item in &arr {\n if num % (*item) == 0 {\n return true;\n }\n }\n return false;\n}\n\nfn main() {\n solution_of_p122a(&mut stdin(), &mut stdout());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "a228884bae8d0b0e1e82ab0b41ab0b5a", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n let mut line=String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let line=line.trim().parse::().unwrap();\n let luck=[4,7,44,47,74,77,444,447,474,477,744,747,774,777];\n for c in &luck{\n if line%c==0{\n print!(\"YES\");\n return\n }\n }\n print!(\"NO\")\n}", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "76aa4422ec9c62163b3de2a625087ce9", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn main() {\n let mut ri = ReadIn::new();\n let n = ri.int();\n ri.read_line();\n let s = ri.0;\n let mut c1 = 0;\n let mut c2 = 0;\n for c in s.chars() {\n if c == 'L' {\n c1 -= 1;\n }\n if c == 'R' {\n c1 += 1;\n }\n if c == 'U' {\n c2 -= 1;\n }\n if c == 'D' {\n c2 += 1;\n }\n }\n if c1 < 0 {\n c1 = -c1;\n }\n if c2 < 0 {\n c2 = -c2;\n }\n println!(\"{}\", n - c1 - c2);\n}\n\nuse std::iter::Map;\nuse std::str::SplitWhitespace;\nuse std::io::stdin;\nuse std::mem::forget;\n\npub struct ReadIn(pub String);\n\nimpl ReadIn {\n pub fn new() -> ReadIn {\n ReadIn(String::new())\n }\n fn read_i32(s: &str) -> i32 {\n s.parse().unwrap()\n }\n pub fn read_line(&mut self) {\n self.0.clear();\n forget(stdin().read_line(&mut self.0));\n }\n pub fn ints(&mut self) -> Map i32> {\n self.read_line();\n self.0.split_whitespace().map(ReadIn::read_i32)\n }\n pub fn int(&mut self) -> i32 {\n self.ints().next().unwrap()\n }\n pub fn int2(&mut self) -> (i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap())\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "51700233129e77680ea01ff5351d3b55", "src_uid": "b9fa2bb8001bd064ede531a5281cfd8a", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\nuse std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn max_moves(moves : &str) -> usize {\n let lrud = \"LRUD\".as_bytes();\n let left = lrud[0];\n let right = lrud[1];\n let up = lrud[2];\n let down = lrud[3];\n let mut num_left = 0;\n let mut num_right = 0;\n let mut num_up = 0;\n let mut num_down = 0;\n for &b in moves.as_bytes().iter() {\n if b == left {\n num_left = num_left + 1;\n } else if b == right {\n num_right = num_right + 1;\n } else if b == up {\n num_up = num_up + 1;\n } else if b == down {\n num_down = num_down + 1;\n } else {\n panic!(\"Unknown move!\");\n }\n }\n let x = min(num_left, num_right);\n let y = min(num_up, num_down);\n x + x + y + y\n}\n\nfn main() {\n let stdin = io::stdin();\n let _ : usize = read_t(&stdin);\n let mut moves = String::new();\n read_line(&stdin, &mut moves);\n let moves = moves.trim();\n let x = max_moves(moves);\n println!(\"{}\", x);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "088fa547f0860fe58935a1183506b332", "src_uid": "b9fa2bb8001bd064ede531a5281cfd8a", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\nuse std::io::stdin;\nfn main() {\n let mut _text = String::new();\n stdin().read_line(&mut _text).unwrap();\n let (uc, dc, rc, lc) = command_counter(parse());\n let counter = min(uc, dc) * 2 + min(lc, rc) * 2;\n println!(\"{}\", counter)\n}\n#[derive(Debug, Copy, Clone)]\nenum Command {\n U,\n D,\n L,\n R,\n}\n\nfn parse() -> Vec {\n let mut text = String::new();\n stdin().read_line(&mut text).unwrap();\n let fu = |e: char| -> Command {\n match e {\n 'U' => Command::U,\n 'D' => Command::D,\n 'L' => Command::L,\n _ => Command::R,\n }\n };\n let text: Vec = text.trim().chars().map(fu).collect();\n text\n}\nfn command_counter(arr: Vec) -> (usize, usize, usize, usize) {\n let mut uc = 0;\n let mut dc = 0;\n let mut lc = 0;\n let mut rc = 0;\n for i in arr {\n match i {\n Command::U => uc += 1,\n Command::D => dc += 1,\n Command::L => lc += 1,\n Command::R => rc += 1,\n }\n }\n (uc, dc, rc, lc)\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "b09f2bf7c836a2558b853c0551638b93", "src_uid": "b9fa2bb8001bd064ede531a5281cfd8a", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let _n = get!(usize);\n let seq: Vec = util::line().chars().collect();\n\n let l = seq.iter().filter(|&&c| c == 'L').count();\n let r = seq.iter().filter(|&&c| c == 'R').count();\n let u = seq.iter().filter(|&&c| c == 'U').count();\n let d = seq.iter().filter(|&&c| c == 'D').count();\n\n println!(\"{}\", 2 * min(l, r) + 2 * min(u, d));\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "619e889ed531fd4949e906b98f62f487", "src_uid": "b9fa2bb8001bd064ede531a5281cfd8a", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\n\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n _n: usize,\n commands: chars,\n }\n\n let mut num_command = HashMap::new();\n\n commands\n .iter()\n .for_each(|x| *num_command.entry(x).or_insert(0) += 1);\n\n let num_l = *num_command.get(&'L').unwrap_or(&0);\n let num_r = *num_command.get(&'R').unwrap_or(&0);\n let num_u = *num_command.get(&'U').unwrap_or(&0);\n let num_d = *num_command.get(&'D').unwrap_or(&0);\n\n println!(\n \"{}\",\n std::cmp::min(num_l * 2, num_r * 2) + std::cmp::min(num_u * 2, num_d * 2)\n );\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "80b805f26de717e0e6e0d71bafba318f", "src_uid": "b9fa2bb8001bd064ede531a5281cfd8a", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Read;\n// use std::collections::VecDeque;\n\n\nfn main() {\n let mut input_text = String::new();\n io::stdin().read_to_string(&mut input_text).unwrap();\n let mut iter = input_text.split_whitespace().map(|x| x.parse::().unwrap());\n let year = iter.next().unwrap();\n let mut new_year = year;\n let mut acc = 0;\n loop {\n new_year += 1;\n acc += if is_leap(new_year) {366 % 7} else {365 % 7};\n if acc >= 7 {\n acc -= 7;\n }\n // println!(\"year = {}, acc = {}\", new_year, acc);\n if acc == 0 && is_leap(year) == is_leap(new_year) {\n break;\n }\n }\n println!(\"{}\", new_year);\n\n}\n\nfn is_leap(year: i32) -> bool {\n year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1b1615551fe891a90c2ea09e8fc799d6", "src_uid": "565bbd09f79eb7bfe2f2da46647af0f2", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let y: u32 = s.trim().parse().unwrap();\n let leap = |x: u32| -> bool {\n x % 400 == 0 || (x % 4 == 0 && x % 100 != 0)\n };\n let mut p = 1 + leap(y) as usize;\n let mut q = y + 1;\n while p != 0 || leap(q) != leap(y) {\n p = (p + 1) % 7;\n if leap(q) {\n p = (p + 1) % 7;\n }\n q += 1;\n }\n println!(\"{}\", q);\n}\n\nfn main() {\n run();\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e368298708d661d30882268db7444885", "src_uid": "565bbd09f79eb7bfe2f2da46647af0f2", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn is_leap(n: usize) -> bool {\n n % 400 == 0 || (n % 4 == 0 && n % 100 != 0)\n}\n\nfn solve() {\n let n = parse_line!(usize);\n let mut result = n;\n let mut shift = 0;\n loop {\n if is_leap(result) {\n shift = (shift + 366) % 7;\n }else{\n shift = (shift + 365) % 7;\n }\n result += 1;\n if shift == 0 && is_leap(n) == is_leap(result) {\n break;\n }\n }\n println!(\"{}\", result)\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "692641c60ef170d2b5029d292b748b4e", "src_uid": "565bbd09f79eb7bfe2f2da46647af0f2", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn main() {\n print!(\"{}\", read_str().replace(\"WUB\", \" \").trim().replace(\" \", \" \").replace(\" \", \" \"));\n}", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "92df4ca03910409f11784e8b9a231510", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n\n let mut ret = String::new();\n for i in 0..buf.len() {\n if ret.ends_with(\"WUB\") {\n let len = ret.len();\n// ret.replace_range((len - 3)..len, \"\");\n ret = ret[..len - 3].to_string();\n if ret.ends_with(\" \") == false {\n if ret.len() > 0 {\n ret.push(' ');\n }\n }\n }\n ret.push_str(&buf[i..i + 1]);\n }\n println!(\"{}\", ret.trim());\n}\n", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "a5bcd04f49dd857a9356d8784f9b23ef", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused)] use std::io::*;\n#[allow(unused)] use std::collections::*;\n#[allow(unused)] use std::mem::*;\n#[allow(unused)] use std::num::*;\n#[allow(unused)] use std::cmp::*;\n#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).collect();\n let mut cnt : usize = 0;\n fn next(cnt: &mut usize, p: &Vec<&str>) -> T where T:std::str::FromStr\n { *cnt += 1; p[*cnt-1].parse().ok().unwrap() }\n ($(next::<$x>(&mut cnt, &s)), +)\n }}; }\n#[allow(unused)] macro_rules! arr { ($n:expr, $T:ty) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let mut s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0);\n let mut v = Vec::new(); v.reserve(($n) as usize);\n for st in s { v.push(st.parse::<$T>().unwrap()); } v\n }}; }\n\n///////////////////////////////////////////////////////////////////////////////\nfn main()\n{\n let s = scan!(String);\n s.split(\"WUB\").filter(|x| x.len() != 0).for_each(|x| print!(\"{} \", x));\n}\n", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "2833d0209f1ceab3f2ced422db1891ca", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/208/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(wubs: String);\n let words = wubs.split(\"WUB\");\n let mut result: Vec = Vec::new();\n for word in words {\n if !word.is_empty() { result.push(word.into()); }\n }\n for (i, word) in result.into_iter().enumerate() {\n if i != 0 { print!(\" \"); }\n print!(\"{}\", word);\n }\n println!(\"\");\n}\n", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "ccad0e6be870767949fb56efc1480f10", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n\tlet s = scan.next::();\n let sw = s.replace(\"WUB\", \" \");\n let words = sw.split_whitespace().map(String::from).collect::>();\n\n writeln!(out, \"{}\", words.join(\" \")).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "823476e130d55181cfa870e4d3537a1b", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn main() {\n print!(\"{}\", read_str().replace(\"WUB\", \" \"));\n}", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "8301ab0a874e60b3666af3ebe5deedc1", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut word = String::new();\n std::io::stdin().read_line(&mut word).unwrap();\n\n let word = word.trim();\n let len = word.len();\n let mut i: usize = 0;\n\n while i < len {\n if i as i32 <= len as i32 - 3 &&\n word.as_bytes()[i] == b'W' &&\n word.as_bytes()[i + 1] == b'U' &&\n word.as_bytes()[i + 2] == b'B' {\n print!(\" \");\n i += 3; continue;\n }\n\n print!(\"{}\", word.as_bytes()[i] as char);\n i += 1;\n }\n}", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "a5855ae04f7a41a9b7c241140ffabf33", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader : T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n input.s().replace(\"WUB\", \" \").split_whitespace().map(|x| print!(\"{} \", x)).count();\n}\n\n", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "b87984c94489060d25fe2552ff50942f", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::Chars;\n\nfn main() {\n let mut counter = 0;\n let mut col_checked = false;\n\n for i in 0..8 {\n let mut input_text = String::new();\n io::stdin()\n .read_line(&mut input_text)\n .expect(\"failed to read from stdin\");\n\n let trimmed = input_text.trim();\n if (trimmed.eq(\"BBBBBBBB\")) {\n counter = counter + 1;\n continue;\n }\n\n if (col_checked) {\n continue;\n }\n\n col_checked = true;\n for j in 0..8 {\n let char_at = trimmed.as_bytes()[j];\n if ((char_at as char) == 'B') {\n counter = counter + 1;\n }\n }\n }\n\n println!(\"{}\", counter);\n}", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms"], "code_uid": "788f68f4a30a176309c3f62e4d0662c8", "src_uid": "8b6ae2190413b23f47e2958a7d4e7bc0", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nconst W: char = 'W';\nconst B: char = 'B';\n\nfn parse_problem(input: B) -> io::Result<[[u8; 8]; 8]> {\n let mut matrix = [[0; 8]; 8];\n for (i, maybe_line) in input.lines().enumerate().take(8) {\n let line = maybe_line?;\n for (j, c) in line.chars().enumerate().take(8) {\n match c {\n B => matrix[i][j] = 1,\n W => {},\n _ => return Err(io::Error::new(io::ErrorKind::InvalidInput,\n \"not a B or W\")),\n }\n }\n }\n Ok(matrix)\n}\n\nfn main() -> io::Result<()> {\n let board = parse_problem(io::stdin().lock())?;\n let mut r: u32 = 0;\n let mut c: u32 = 0;\n 'outer_row: for i in 0..8 {\n for j in 0..8 {\n if board[i][j] == 0 {\n continue 'outer_row;\n }\n }\n r += 1;\n }\n 'outer_col: for j in 0..8 {\n for i in 0..8 {\n if board[i][j] == 0 {\n continue 'outer_col;\n }\n }\n c += 1;\n }\n let result = if r < 8 && c < 8 { r + c } else { 8 };\n println!(\"{}\", result);\n Ok(())\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms"], "code_uid": "d24e9bca3325394e7b1c8a00f461b23d", "src_uid": "8b6ae2190413b23f47e2958a7d4e7bc0", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! scanln {\n () => ({\n let mut buffer = String::new();\n ::std::io::stdin().read_line(&mut buffer).expect(\"Unable to read line\");\n buffer\n });\n ($($t: ty),+) => ({\n scanln!($($t),+, |c: char| c.is_whitespace())\n });\n ($($t: ty),+, $sp: expr) => ({\n let mut buffer = scanln!();\n let mut iter = buffer.split($sp);\n ($(iter.next().unwrap().parse::<$t>().expect(\"Unable to parse token\")),+)\n });\n}\n\nfn main() {\n let mut board = Vec::new();\n let mut count = 0;\n let mut checked = false;\n for _ in 0..8 {\n let line = scanln!(String);\n let row: Vec = line.split(' ').flat_map(|s| s.chars()).collect();\n board.push(row);\n }\n for r in board {\n let blacks = r.iter().filter(|c| **c == 'B').count();\n count += if blacks == 8 {\n 1\n } else if blacks > 0 && !checked {\n checked = true;\n blacks\n } else {\n 0\n }\n }\n println!(\"{}\", count);\n}", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms"], "code_uid": "89f63e2693b0d268c5674fce92426854", "src_uid": "8b6ae2190413b23f47e2958a7d4e7bc0", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn read_n() -> (u64, u64) {\n let mut buffer = String::new();\n stdin().read_line(&mut buffer).unwrap();\n let snums: Vec<&str> = buffer.trim().split(\" \").collect();\n (snums[0].parse::().unwrap(), snums[1].parse::().unwrap())\n}\n\nfn div2(x: u64) -> u64{\n if x % 2 == 0 {\n return x / 2;\n } else {\n return x / 2 + 1;\n }\n}\n\nfn get_n(n: u64, k: u64) -> u64 {\n if k == n && n % 2 == 0 {\n return n;\n }\n if k <= div2(n) {\n return k * 2 - 1;\n } else {\n return k % div2(n) * 2;\n }\n}\n\nfn testme() {\n for x in 1..11 {\n print!(\"{} \", get_n(10, x));\n }\n println!(\"Test#1 has been done\");\n\n for x in 1..12 {\n print!(\"{} \", get_n(11, x));\n }\n println!(\"Test#2 has been done\");\n}\n\nfn main() {\n let (n, k) = read_n();\n println!(\"{}\", get_n(n, k));\n //testme();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "5645805c789a3b9b54175449ce640598", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (n, k) = R!(u64, u64);\n let ans = if k > (n+1)/2 { // even\n (k - (n+1)/2) * 2\n } else { // odd\n k*2 - 1\n };\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1466e02effed7cdb9566ed3bca223544", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/318/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(n: u64, k: u64);\n let half = n - (n / 2);\n if k <= half {\n println!(\"{}\", k * 2 - 1);\n } else {\n println!(\"{}\", (k - half) * 2);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "c3948a3587e3dc62a47c74514d6aa55a", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer\n}\n\nfn main() -> io::Result<()> {\n let mut input = get_input().trim().to_string();\n\n let mut substr_iter = input.split_whitespace();\n\n let mut next_num = || -> i64 {\n substr_iter\n .next()\n .expect(\"Not enough input numbers\")\n .parse()\n .expect(\"Input is not a number\")\n };\n\n let n = next_num();\n let k = next_num();\n\n if n % 2 == 0 {\n if k <= n / 2 {\n println!(\"{}\", k * 2 - 1);\n } else {\n println!(\"{}\", (k - n / 2) * 2);\n }\n } else {\n if k <= (n / 2 + 1) {\n println!(\"{}\", k * 2 - 1);\n } else {\n println!(\"{}\", (k - n / 2 - 1) * 2);\n }\n }\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "698ee80bb8c936b48fc20da678154ea4", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused)] use std::io::*;\n#[allow(unused)] use std::collections::*;\n#[allow(unused)] use std::mem::*;\n#[allow(unused)] use std::num::*;\n#[allow(unused)] use std::cmp::*;\n#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).collect();\n let mut cnt : usize = 0;\n fn next(cnt: &mut usize, p: &Vec<&str>) -> T where T:std::str::FromStr\n { *cnt += 1; p[*cnt-1].parse().ok().unwrap() }\n ($(next::<$x>(&mut cnt, &s)), +)\n }}; }\n#[allow(unused)] macro_rules! arr { ($n:expr, $T:ty) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let mut s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0);\n let mut v = Vec::new(); v.reserve(($n) as usize);\n for st in s { v.push(st.parse::<$T>().unwrap()); } v\n }}; }\n\n///////////////////////////////////////////////////////////////////////////////\nfn main()\n{\n let (n, k) = scan!(i64, i64);\n println!(\"{}\", if 2 * k - 1 > n { 2 * (k - ((n + 1) / 2)) } else { k * 2 - 1 } );\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "cb3cdd3a3b0031fdc81d936ba59f646e", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let vec: Vec = get_input().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect();\n let n = vec[0];\n let index = vec[1];\n\n let r = {\n if n % 2 == 0 {\n 0 \n } else {\n 1\n }\n };\n\n if n / 2 + r >= index {\n // ODD NUMBER\n let res = index * 2 - 1;\n println!(\"{}\", res);\n } else {\n // EVEN NUMBER\n let res = (index - n / 2) * 2;\n let res = {\n if n % 2 == 0 {\n res\n } else {\n res - 2\n }\n };\n println!(\"{}\", res);\n }\n}\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer.trim().to_owned()\n}\n\nfn get_input_usize() -> usize {\n get_input().parse().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "e58bb25415f0e8cc1df71aaf516d4141", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let input = readln();\n let n = input[0];\n let k = input[1];\n\n println!(\"{}\", if k <= (n + 1) / 2 {k * 2 - 1} else {(k - (n + 1) / 2) * 2});\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "aa8088cbc75046b6a824f8efa378c116", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\n\nfn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn read_vec(split_char: char) -> Vec {\n read_str()\n .split(split_char)\n .map(|value| value.parse::().ok().expect(\"Error\"))\n .collect()\n}\n\nfn read_tuple() -> (T, T) {\n let buffer: Vec = read_vec(' ');\n (buffer[0], buffer[1])\n}\n\ntrait Utils { fn div_ceil(self, divisor: Self) -> Self; }\nmacro_rules! impl_div { ($($t:ty)+) => { $(\n impl Utils for $t {\n fn div_ceil(self, divisor: Self) -> Self {\n (self + divisor - 1) / divisor\n }\n }\n)*}}\nimpl_div!{u32 u64}\n\nfn main() {\n let (k, n): (u64, u64) = read_tuple();\n let mid: u64 = k.div_ceil(2);\n\n if n > mid { println!(\"{}\", 2 * (n - mid)); }\n else { println!(\"{}\", (2 * n) - 1); }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "6236fff8a19ef62cea3e58cb9d0282e6", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::Ordering;\n\nfn sequence_position(level: u32, idx: u64) -> u32 {\n match level {\n 1 => 1,\n _ => {\n let half_length = 2_u64.pow(level - 1);\n match idx.cmp(&half_length) {\n Ordering::Less => sequence_position(level - 1, idx),\n Ordering::Equal => level,\n Ordering::Greater => sequence_position(level - 1, idx - half_length)\n }\n }\n }\n}\n\nfn main() {\n let mut input_str = String::new();\n io::stdin().read_line(&mut input_str).unwrap();\n\n let mut iter = input_str.trim().split_whitespace();\n let level: u32 = iter.next().unwrap().parse().unwrap();\n let position: u64 = iter.next().unwrap().parse().unwrap();\n\n println!(\"{}\", sequence_position(level, position));\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "binary search", "implementation", "bitmasks"], "code_uid": "e69db62675d7831f08d9a627ce4f3d37", "src_uid": "0af400ea8e25b1a36adec4cc08912b71", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n#![allow(unused_imports)]\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::str::FromStr;\nuse std::collections::{VecDeque, HashMap};\n\nfn main() {\n let stdin = io::stdin();\n let mut input = stdin.lock();\n let mut line = String::new();\n input.read_line(&mut line).unwrap();\n let nums = get_numbers::(&line);\n let n = nums[0];\n let k = nums[1] - 1; // k is numbered from 1\n\n let length = u64::pow(2, n as u32) - 1;\n\n let mut val = n;\n let mut ind = length / 2;\n let mut lower = 0;\n let mut upper = length;\n\n while ind != k {\n val = val - 1;\n if ind > k {\n upper = ind;\n ind = (lower + upper) / 2;\n } else {\n lower = ind;\n ind = (lower + upper) / 2;\n }\n }\n\n println!(\"{}\", val);\n}\n\n/*\n * Utility Functions\n */\n\n// get numbers from line seperated by spaces\nfn get_numbers(line: &str) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n line.split_whitespace()\n .map(|chunk| chunk.parse::().expect(\"failed to parse\"))\n .collect()\n}\n\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "binary search", "implementation", "bitmasks"], "code_uid": "f9ccb4dc0151897c0d89e6e1c2520bfd", "src_uid": "0af400ea8e25b1a36adec4cc08912b71", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn get_input(input: &mut String) {\n input.clear();\n stdin().read_line(input).expect(\"error\");\n}\n\nfn main() {\n let mut input = String::new();\n get_input(&mut input);\n let mut numbers = input.trim().split_whitespace().filter_map(|n| n.parse::().ok());\n let n = numbers.next().unwrap();\n let k = numbers.next().unwrap();\n\n let mut local_n = 1u64;\n let mut local_k = k;\n while local_k % 2 != 1 {\n local_k >>= 1;\n local_n += 1;\n }\n\n println!(\"{}\", local_n);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "binary search", "implementation", "bitmasks"], "code_uid": "f46ac9a58f4273cd1aa4a270a706701a", "src_uid": "0af400ea8e25b1a36adec4cc08912b71", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\ntype Matrix = Vec>;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (u64, u64) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\nfn main() {\n let (_n, mut k) = read_line_pair();\n \n let mut res = 1u32;\n while k & 1 == 0 {\n res += 1;\n k /= 2;\n }\n \n println!(\"{}\", res);\n \n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "binary search", "implementation", "bitmasks"], "code_uid": "01d251c849f87e4b7eeb356c8b65ffd8", "src_uid": "0af400ea8e25b1a36adec4cc08912b71", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, stdin};\n\nfn main() -> io::Result<()> {\n let mut buffer = String::new();\n let input = stdin();\n input.read_line(&mut buffer)?;\n let mut money: u32 = buffer.trim().parse().expect(\"Not int\");\n let mut bills = 0;\n let denoms = [100, 20, 10, 5, 1];\n for denom in &denoms {\n bills += money / denom;\n money %= denom;\n }\n println!(\"{}\", bills);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "d391ae7d0743ff083b5ce989fcb6898e", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut guess = String::new();\n\n io::stdin()\n .read_line(&mut guess)\n .expect(\"Failed to read line\");\n\n let mut bills:u32 = 0;\n let mut n= guess.trim().parse::().unwrap();\n\n while n > 0 {\n if (n % 100) == 0 {\n n = n - 100;\n bills+=1;\n }\n else if (n % 20) == 0\n {\n n = n - 20;\n bills+=1;\n }\n else if (n % 10) == 0\n {\n n = n - 10;\n bills+=1;\n }\n else if (n % 5) == 0\n {\n n = n - 5;\n bills+=1;\n }\n else\n {\n n = n - 1;\n bills+=1;\n }\n }\n print!(\"{}\",bills);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "fa9a129716a0ad4151b0abdae98a772b", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut buffer = String::new();\n let _ = stdin().read_line(&mut buffer);\n\n let mut total = buffer.trim().parse::().expect(\"Error in parsing\");\n\n let mut count = 0;\n while total > 0 {\n if total % 100 == 0 {\n total -= 100;\n count += 1;\n } else if total % 20 == 0 {\n total -= 20;\n count += 1;\n } else if total % 10 == 0 {\n total -= 10;\n count += 1;\n } else if total % 5 == 0 {\n total -= 5;\n count += 1;\n } else if total % 1 == 0 {\n total -= 1;\n count += 1;\n }\n }\n\n println!(\"{}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "dafb5ae55d537886d1b22a54fcf412da", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n\n let mut num = buffer.trim().parse::().unwrap();\n let mut bills = 0;\n\n while num > 0 {\n if num >= 100 {\n num -= 100;\n bills += 1;\n }\n else if num >= 20 {\n num -= 20;\n bills += 1;\n }\n else if num >= 10 {\n num -= 10;\n bills += 1;\n }\n else if num >= 5 {\n num -= 5;\n bills += 1;\n }\n else if num >= 1 {\n num -= 1;\n bills += 1;\n }\n }\n\n println!(\"{}\", bills);\n}", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "7f5aeda0cfcf79f96a6ddd6523a130f4", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main()\n{\n let mut cases = String::new();\n\n io::stdin()\n .read_line(&mut cases)\n .expect(\"no input\");\n\n let mut cases : u32 = cases.trim().parse().expect(\"nan\");\n\n let a = [100, 20, 10, 5, 1];\n let mut i = 0;\n let mut count = 0;\n while cases > 0 {\n if cases >= a[i]\n {\n count+= 1;\n cases -= a[i];\n }\n else\n {\n i += 1;\n }\n }\n println!(\"{}\", count);\n \n}", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "d0ac93341e77b7aa4e22c376439f41f4", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)?;\n\n let mut n = input.trim().parse::().unwrap();\n\n let mut k = 0;\n\n while n >= 100 {\n n -= 100;\n k += 1;\n }\n while n >= 20 {\n n -= 20;\n k += 1;\n }\n while n >= 10 {\n n -= 10;\n k += 1;\n }\n while n >= 5 {\n n -= 5;\n k += 1;\n }\n while n >= 1 {\n n -= 1;\n k += 1;\n }\n\n println!(\"{}\", k);\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "59b21c29857dc8ebcc603c040ca76197", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n let sol = [1,5,10,20,100].into_iter().rev()\n .fold((n,0), |(x,a),y| (x % y, a + x / y)).1;\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "892b33277eb9078418bd99b6d2f37dc8", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\n\nfn min_bills(mut n: usize) -> usize {\n let bills = [100, 20, 10, 5, 1];\n let mut nbills = 0;\n\n for i in &bills {\n nbills += n / i;\n n %= i;\n }\n\n nbills\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n let n: usize = scan.next().trim().parse().unwrap();\n\n writeln!(out, \"{}\", min_bills(n)).ok();\n}\n\npub struct Scanner {\n reader: T,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self { reader }\n }\n\n pub fn next(&mut self) -> String {\n let mut input = String::new();\n self.reader.read_line(&mut input).unwrap();\n\n return input;\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "570080322e18e7d6c01716aa7d8e50e3", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\nuse std::io::{Write, StdinLock, StdoutLock, BufWriter};\n\n/// Reads white-space separated tokens one at a time.\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n /// Use \"turbofish\" syntax token::() to select data type of next token.\n ///\n /// # Panics\n ///\n /// Panics if there's an I/O error or if the token cannot be parsed as T.\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\npub fn scanner_from_file(filename: &str) -> Scanner> {\n let file = std::fs::File::open(filename).expect(\"Input file not found\");\n Scanner::new(io::BufReader::new(file))\n}\n\npub fn writer_to_file(filename: &str) -> io::BufWriter {\n let file = std::fs::File::create(filename).expect(\"Output file not found\");\n io::BufWriter::new(file)\n}\n\nfn solve() { // scan: &mut Scanner, out: &mut BufWriter\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n let n = scan.token::();\n let k = scan.token::();\n let mut arr = scan.token::().chars().collect::>();\n \n for i in 0..k {\n let mut finish = true;\n let mut pos = 0;\n while pos < arr.len() - 1 {\n if arr[pos] == 'B' && arr[pos+1] == 'G' {\n arr.swap(pos, pos+1);\n finish = false;\n pos += 2;\n } else {\n pos += 1;\n }\n }\n\n if finish {\n break;\n }\n }\n\n out.write(arr.iter().collect::().as_bytes());\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(64 * 1024 * 1024)\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "0857b6009d656bb7a08da3d83d64c525", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::char;\nuse std::fmt;\nuse std::fmt::Debug;\nuse std::fmt::Formatter;\nuse std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nenum BoyOrGirl {\n Boy,\n Girl,\n}\n\nimpl BoyOrGirl {\n fn new(c : char) -> BoyOrGirl {\n match c {\n 'B' => BoyOrGirl::Boy,\n 'G' => BoyOrGirl::Girl,\n x => panic!(\"Cannot convert {} to a BoyOrGirl!\", x),\n }\n }\n}\n\nimpl Debug for BoyOrGirl {\n fn fmt(&self, f : &mut Formatter) -> fmt::Result {\n match *self {\n BoyOrGirl::Boy => write!(f, \"B\"),\n BoyOrGirl::Girl => write!(f, \"G\"),\n }\n }\n}\n\nfn step(curr : &Vec, next : &mut Vec) {\n let l = curr.len();\n let mut i = 0;\n while i < l {\n match curr[i] {\n BoyOrGirl::Boy => {\n if (i + 1) < l {\n match curr[i + 1] {\n BoyOrGirl::Girl => {\n next.push(BoyOrGirl::Girl);\n next.push(BoyOrGirl::Boy);\n i = i + 2;\n },\n BoyOrGirl::Boy => {\n next.push(BoyOrGirl::Boy);\n i = i + 1;\n },\n }\n } else {\n next.push(BoyOrGirl::Boy);\n i = i + 1;\n }\n },\n BoyOrGirl::Girl => {\n next.push(BoyOrGirl::Girl);\n i = i + 1;\n }\n }\n }\n}\n\nfn print_queue(q : &Vec) {\n for bg in q {\n print!(\"{:?}\", bg);\n }\n println!();\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut n_t : Vec = vec![];\n read_ts(&stdin, &mut n_t);\n let t = n_t[1];\n let mut s = String::new();\n read_line(&stdin, &mut s);\n let mut queue : Vec = s.trim().chars().map(|c| BoyOrGirl::new(c)).collect();\n for _ in 0 .. t {\n let mut next = vec![];\n step(&queue, &mut next); \n queue = next;\n }\n print_queue(&queue);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "29f51e2a8b354817685c8bb7a460e9fd", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self};\n\nfn main() {\n let mut a_line = String::new();\n io::stdin().read_line(&mut a_line).unwrap();\n let mut it = a_line.trim().split_whitespace();\n let n = it.next().unwrap().parse::().unwrap();\n let t = it.next().unwrap().parse::().unwrap();\n\n let mut line_text = String::new();\n io::stdin().read_line(&mut line_text).unwrap();\n\n let mut line: Vec = line_text.trim().chars().collect();\n\n for _ in 0..t {\n let mut j = 0;\n while j < n - 1 {\n if (line[j] == 'B') && (line[j + 1] == 'G') {\n line[j] = 'G';\n line[j + 1] = 'B';\n j = j + 1;\n }\n j = j + 1;\n }\n }\n println!(\"{}\", line.into_iter().collect::());\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "c76129ee394feeddc37065da081a1c64", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n line\n}\n\nfn main() {\n\n let line = read_line();\n let mut ns = line.split_whitespace().map(|s| s.parse::().unwrap());\n let n = ns.next().unwrap();\n let t = ns.next().unwrap();\n\n let mut buf = read_line().into_bytes();\n for _ in 0..t {\n for i in (0..(n-1)).filter(|i| buf[*i] == 'B' as u8 && buf[*i+1] == 'G' as u8).collect::>() {\n buf[i] = 'G' as u8;\n buf[i+1] = 'B' as u8;\n }\n }\n\n print!(\"{}\", String::from_utf8(buf).unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "a8127b65905dfde1be4ae3766994f1b7", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let states: Vec = reads(sin);\n let mut rail: String = read(sin);\n\n let _n = states[0];\n let gen = states[1];\n\n for _ in 0..gen {\n rail = rail.replace(\"BG\", \"GB\");\n }\n\n println!(\"{}\", rail);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "b9579a14e38049f05605ac83c53c418b", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(dead_code)]\nuse std::io::{self, prelude::*};\n\n\n//use itertools::Itertools;\n//let mut iter = \"\u03b1\u03b2\u03b3\".chars().dropping(2);\n//itertools::assert_equal(iter, \"\u03b3\".chars());\n \nfn solve(mut scan: Scanner, mut w: W) {\n let n = scan.token::();\n let t = scan.token::();\n let mut ans : Vec = Vec::with_capacity(n);\n \n let line = scan.token::();\n for c in line.chars() {\n ans.push(c);\n }\n\n for _ in 1..=t {\n let mut i: usize = 0;\n while i < n-1 {\n if ans[i] == 'B' && ans[i+1] == 'G' {\n ans.swap(i, i+1);\n i += 2;\n continue;\n }\n i += 1;\n }\n }\n let ans: String = ans.into_iter().collect();\n\n writeln!(w, \"{}\", ans);\n}\n \nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n solve(reader, writer);\n}\n \npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace()\n }\n }\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace()) }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "712aacd5ae84cf186ca53fa444d3315f", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/266/B\n\nuse std::io;\n\nfn main() {\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let words: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let n = words[0];\n let t = words[1];\n\n let mut s = String::new();\n\n io::stdin()\n .read_line(&mut s)\n .unwrap();\n\n let mut s: Vec =\n s.chars().collect();\n\n let mut time = 0;\n\n while time < t {\n let mut idx: usize = 0;\n loop {\n if idx as i64 >= n+1 {\n break;\n }\n if s[idx] == 'B' && s[idx+1] == 'G' {\n s[idx] = 'G';\n s[idx+1] = 'B';\n idx += 2;\n } else {\n idx += 1;\n }\n }\n time += 1;\n }\n\n let answer: String = s.into_iter().collect();\n print!(\"{}\", answer);\n}\n\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "ca3024e11f9a86206aaf2189c50580c1", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports, deprecated, dead_code)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{VecDeque,HashMap,HashSet,BTreeMap,BTreeSet,BinaryHeap};\n// Module for v1.15.1\nuse std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead\n\n// Functions\n\n// Main\nfn main() {\n\n input! {\n N: usize,\n T: usize,\n mut S: chars\n }\n\n for _ in 0..T {\n let mut ci = vec![];\n for i in 0..N-1 {\n if S[i]=='B' && S[i+1]=='G' {\n ci.push(i);\n }\n }\n for i in ci {\n S[i] = 'G';\n S[i+1] = 'B';\n }\n }\n\n println!(\"{}\", S.iter().collect::());\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "016844b7a21c35aca3ac8c22dbd3904a", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn main() {\n let message = readln!();\n let message = message.chars().collect::>();\n\n if message.len() % 2 == 0 {\n for index in 0..message.len() / 2 {\n print!(\"{}{}\", message[message.len() / 2 - 1 - index], message[message.len() / 2 + index]);\n }\n } else {\n print!(\"{}\", message[message.len() / 2]);\n for index in 0..message.len() / 2 {\n print!(\"{}{}\", message[message.len() / 2 + 1 + index], message[message.len() / 2 - 1 - index]);\n }\n }\n\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "a67fcb1ceae0587a77f7f165a0bbee42", "src_uid": "992ae43e66f1808f19c86b1def1f6b41", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n let s = s.trim();\n let mut i: usize = 0;\n let mut j: usize = s.len()-1;\n \n let mut r = String::new();\n let mut last = s.len() % 2 == 0;\n\n for _ in 0..s.len() {\n if last {\n let c = s.chars().nth(j).unwrap();\n r.push(c);\n j -= 1;\n } else {\n let c = s.chars().nth(i).unwrap();\n r.push(c);\n i += 1;\n }\n last = !last;\n }\n println!(\"{}\", r.chars().rev().collect::());\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "6c148deff23fbd8e27f5930319c09767", "src_uid": "992ae43e66f1808f19c86b1def1f6b41", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap,BTreeSet};\n#[allow(unused_imports)]\nuse std::ops::*;\n#[allow(unused_imports)]\nuse std::collections::BinaryHeap;\n\n#[allow(unused_macros)]\nmacro_rules! ite {\n ($c:expr, $t:expr, $f:expr) => {{\n if $c { $t } else { $f }\n }};\n}\n\n// ref: tanakh \n// diff: using Parser\n#[macro_export]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut parser = Parser::from_str($s);\n input_inner!{parser, $($r)*}\n };\n (parser = $parser:ident, $($r:tt)*) => {\n input_inner!{$parser, $($r)*}\n };\n (new_stdin_parser = $parser:ident, $($r:tt)*) => {\n let stdin = std::io::stdin();\n let reader = std::io::BufReader::new(stdin.lock());\n let mut $parser = Parser::new(reader);\n input_inner!{$parser, $($r)*}\n };\n ($($r:tt)*) => {\n input!{new_stdin_parser = parser, $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! input_inner {\n ($parser:ident) => {};\n ($parser:ident, ) => {};\n ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($parser, $t);\n input_inner!{$parser $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($parser:ident, ( $($t:tt),* )) => {\n ( $(read_value!($parser, $t)),* )\n };\n ($parser:ident, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($parser, $t)).collect::>()\n };\n ($parser:ident, chars) => {\n read_value!($parser, String).chars().collect::>()\n };\n ($parser:ident, usize1) => {\n read_value!($parser, usize) - 1\n };\n ($parser:ident, $t:ty) => {\n $parser.next::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n s: chars,\n }\n if s.len() % 2 == 0 {\n let n = s.len();\n let m = s.len() / 2;\n let mut res = String::new();\n for i in (0..m).rev() {\n res.push(s[i]);\n res.push(s[n-i-1]);\n }\n println!(\"{}\", res);\n }\n else {\n let n = s.len();\n let m = s.len() / 2;\n let mut res = String::new();\n res.push(s[m]);\n for i in (0..m).rev() {\n res.push(s[n-i-1]);\n res.push(s[i]);\n }\n println!(\"{}\", res);\n }\n}\n\nuse std::io::BufRead;\nuse std::io;\nuse std::str;\n\n// ref: tatsuya6502 \n// ref: wariuni \n// diff: using std::io::BufRead::fill_buf()\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\n\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\n\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len,complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n (len, buf2[len-1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n }\n else {\n self.update_buf();\n }\n }\n }\n}\n\npub fn continuous_division(xs: &[T]) -> Vec<(T,usize)> {\n let mut res = vec![];\n let n = xs.len();\n for i in 0..n {\n if i == 0 || xs[i-1] != xs[i] {\n res.push((xs[i], 1));\n }\n else {\n let m = res.len();\n res[m-1].1 += 1;\n }\n }\n res\n}\n\nuse std::fmt::Display;\n#[allow(dead_code)]\nfn write_vec(xs: &Vec) {\n if xs.len() == 0 {\n println!();\n return;\n }\n print!(\"{}\", xs[0]);\n for i in 1..xs.len() {\n print!(\" {}\", xs[i]);\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "cbd9ddf97f53ae64bd7e18ec81e4a559", "src_uid": "992ae43e66f1808f19c86b1def1f6b41", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n// _ _ _ _____ ___\n// _ __ ___ __ _ _ __ | |_ __ _/ / |___ / / _ \\\n// | '_ ` _ \\ / _` | '_ \\| __/ _` | | | |_ \\| | | |\n// | | | | | | (_| | | | | || (_| | | |___) | |_| |\n// |_| |_| |_|\\__,_|_| |_|\\__\\__,_|_|_|____/ \\___/\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n\nuse input::*;\n\nfn main() {\n let n: usize;\n input!(n);\n let v = input_line_str().to_charvec();\n let mut rc = 0;\n let mut uc = 0;\n let mut dc = 0;\n for c in v {\n if c == 'R' {\n rc = 0;\n if uc == 0 {\n rc += 1;\n } else {\n uc -= 1;\n dc += 1;\n }\n } else {\n uc = 0;\n if rc == 0 {\n uc += 1;\n } else {\n rc -= 1;\n dc += 1;\n }\n }\n }\n p(n - dc);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "98c0a9948a4afd2149be4848458e9321", "src_uid": "986ae418ce82435badadb0bd5588f45b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_variables, dead_code, non_snake_case, unused_macros)]\nuse std::io::{stdin, Read, StdinLock};\nuse std::str::FromStr;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\nfn getline() -> String {\n let mut res = String::new();\n std::io::stdin().read_line(&mut res).ok();\n res\n}\nmacro_rules ! readl { ( $ t : ty ) => { { let s = getline ( ) ; s . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,+ ) => { { let s = getline ( ) ; let mut iter = s . trim ( ) . split ( ' ' ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; }\nmacro_rules ! readlvec { ( $ t : ty ) => { { let s = getline ( ) ; let iter = s . trim ( ) . split ( ' ' ) ; iter . map ( | x | x . parse ( ) . unwrap ( ) ) . collect ::< Vec <$ t >> ( ) } } }\nmacro_rules ! mvec { ( $ v : expr , $ s : expr ) => { vec ! [ $ v ; $ s ] } ; ( $ v : expr , $ s : expr , $ ( $ t : expr ) ,* ) => { vec ! [ mvec ! ( $ v , $ ( $ t ) ,* ) ; $ s ] } ; }\nmacro_rules ! debug { ( $ x : expr ) => { println ! ( \"{}: {:?}\" , stringify ! ( $ x ) , $ x ) } }\nfn printiter<'a, T>(v: &'a T)\nwhere\n &'a T: std::iter::IntoIterator,\n <&'a T as std::iter::IntoIterator>::Item: std::fmt::Display,\n{\n for (i, e) in v.into_iter().enumerate() {\n if i != 0 {\n print!(\" \");\n }\n print!(\"{}\", e);\n }\n println!(\"\");\n}\nstruct ContestPrinter {\n s: String,\n}\nimpl ContestPrinter {\n fn new() -> ContestPrinter {\n ContestPrinter { s: String::new() }\n }\n fn print(&mut self, x: T)\n where\n T: std::fmt::Display,\n {\n self.s.push_str(format!(\"{}\", x).as_str());\n }\n fn println(&mut self, x: T)\n where\n T: std::fmt::Display,\n {\n self.s.push_str(format!(\"{}\\n\", x).as_str());\n }\n}\nimpl std::ops::Drop for ContestPrinter {\n fn drop(&mut self) {\n print!(\"{}\", self.s);\n }\n}\nstatic MOD: i64 = 1e9 as i64 + 7;\nfn is_max_i64(num: i64) -> bool {\n if num == i64::max_value() {\n true\n } else {\n false\n }\n}\nfn main() {\n let mut pr = ContestPrinter::new();\n let N = readl!(usize);\n let s = readl!(String);\n let sc = s.chars().collect::>();\n let mut idx = 1;\n let mut ans = 1;\n if N == 1 {\n pr.println(1);\n return;\n }\n while idx < N {\n if ((sc[idx - 1] == 'R') & (sc[idx] == 'U')) |\n ((sc[idx - 1] == 'U') & (sc[idx] == 'R')) {\n idx += 1;\n }\n idx += 1;\n if idx <= N { ans += 1; }\n }\n pr.println(ans);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "110335cc7741fad2ebc478d3a2db4968", "src_uid": "986ae418ce82435badadb0bd5588f45b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\n let mut n: String = String::new();\n let mut seq: String = String::new();\n\n io::stdin().read_line(&mut n);\n io::stdin().read_line(&mut seq);\n\n let n: i32 = n.trim().parse::().unwrap();\n let seq = seq.trim().chars().collect::>();\n\n let mut ans: i32 = n;\n let mut last: char = 'D';\n for c in seq {\n if c != last && last != 'D' {\n ans = ans - 1;\n last = 'D';\n } else {\n last = c;\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2a073aa48314fc473bb1903c62f9969a", "src_uid": "986ae418ce82435badadb0bd5588f45b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ----------\nuse std::io::Read;\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let n: usize = it.next().unwrap().parse().unwrap();\n let w: usize = it.next().unwrap().parse().unwrap();\n let mut a = vec![vec![]; 3];\n for _ in 0..n {\n let t: usize = it.next().unwrap().parse().unwrap();\n let g: usize = it.next().unwrap().parse().unwrap();\n a[g - 1].push(t);\n }\n let mut way = vec![vec![vec![vec![ModInt::zero(); a[2].len() + 2]; a[1].len() + 2]; a[0].len() + 2]; 3];\n way[0][1][0][0] = ModInt::one();\n way[1][0][1][0] = ModInt::one();\n way[2][0][0][1] = ModInt::one();\n for i in 0..=a[0].len() {\n for j in 0..=a[1].len() {\n for k in 0..=a[2].len() {\n for l in 0..3 {\n let v = way[l][i][j][k];\n for (g, &(x, y, z)) in [(i + 1, j, k), (i, j + 1, k), (i, j, k + 1)].iter().enumerate() {\n if g != l {\n way[g][x][y][z] += v;\n }\n }\n }\n }\n }\n }\n let mut dp1 = vec![vec![vec![ModInt::zero(); w + 1]; a[1].len() + 1]; a[0].len() + 1];\n dp1[0][0][0] = ModInt::one();\n for &b in a[0].iter() {\n for i in (1..=a[0].len()).rev() {\n for t in (b..=w).rev() {\n let v = dp1[i - 1][0][t - b];\n dp1[i][0][t] += v;\n }\n }\n }\n for &b in a[1].iter() {\n for i in 0..=a[0].len() {\n for j in (1..=a[1].len()).rev() {\n for t in (b..=w).rev() {\n let v = dp1[i][j - 1][t - b];\n dp1[i][j][t] += v;\n }\n }\n }\n }\n let mut dp2 = vec![vec![ModInt::zero(); w + 1]; a[2].len() + 1];\n dp2[0][0] = ModInt::one();\n for &b in a[2].iter() {\n for i in (1..=a[2].len()).rev() {\n for t in (b..=w).rev() {\n let v = dp2[i - 1][t - b];\n dp2[i][t] += v;\n }\n }\n }\n let pc = Precalc::new(n);\n let mut ans = ModInt::zero();\n for i in 0..=a[0].len() {\n for j in 0..=a[1].len() {\n for k in 0..=a[2].len() {\n for t in 0..=w {\n let way = way[0][i][j][k] + way[1][i][j][k] + way[2][i][j][k];\n ans += dp1[i][j][t] * dp2[k][w - t] * way * pc.fact(i) * pc.fact(j) * pc.fact(k);\n }\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics"], "code_uid": "6e0960cbbc89051b5fd987ac8dac8439", "src_uid": "ed5f913afe829c65792b54233a256757", "difficulty": 2600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nconst P5: i32 = 1_000_000_007;\nconst P6: i64 = P5 as i64;\n#[derive(Debug,Clone,Copy)]\nstruct Field(i32);\n#[allow(dead_code)]\nimpl Field {\n fn new>(a: T) -> Self { Self(Self::cv(a)) }\n fn new_unchecked(a: i32) -> Self { Self(a) }\n fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n fn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n}\nimpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\nimpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\nimpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\nimpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\nimpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\nimpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\nimpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\nuse std::fmt::{Display, Formatter, Result};\nimpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n// impl Default for Field { fn default() -> Self { Field(0) }}\nimpl Default for &Field { fn default() -> Self { &Field(0) }}\nimpl PartialEq for Field { fn eq(&self, a: &Self) -> bool { self.0 == a.0 } }\nimpl PartialOrd for Field { fn partial_cmp(&self, a: &Self) -> Option { Some(self.0.cmp(&a.0)) } }\nimpl Eq for Field {}\nimpl Ord for Field { fn cmp(&self, a: &Self) -> Ordering { self.0.cmp(&a.0) } }\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let tt = input.i();\n let mut t = vec![0; n];\n let mut g = vec![0; n];\n let mut z = vec![0; 4];\n for i in 0..n {\n t[i] = input.i();\n g[i] = input.i();\n z[g[i] as usize] += 1;\n }\n let sumt: i32 = t.iter().sum();\n\n let dp2 = {\n let mut dp2 = HashMap::<(i32,i32,i32),Field>::new();\n let mut dp = HashMap::<(i32,i32,i32,i32,i32),Field>::new();\n for g in 1..4 {\n dp.insert((0,0,0,0,g), Field(1));\n }\n for _i in 0..n {\n let mut d = HashMap::<(i32,i32,i32,i32,i32),Field>::new();\n for ((h,a,b,c,l), y) in dp.into_iter() {\n let mut p = [0,a,b,c];\n let mut pf = [Field(0),Field(a),Field(b),Field(c)];\n for g in 1..4 {\n let gu = g as usize;\n if (h == 0 && g != l) || (h > 0 && g == l) {\n continue;\n }\n p[gu] += 1;\n pf[gu] += Field(1);\n if (1..4).all(|i| p[i] <= z[i]) {\n let key = (h + 1, p[1], p[2], p[3], g);\n let res = y * pf[g as usize] + *d.get(&key).unwrap_or_default();\n d.insert(key, res);\n }\n p[gu] -= 1;\n pf[gu] -= Field(1);\n }\n }\n\n for (&(_,a,b,c,_),&x) in d.iter() {\n let key = (a,b,c);\n let res = *dp2.get(&key).unwrap_or_default();\n dp2.insert(key, res + x);\n }\n dp = d;\n // println!(\"\\n-----------------------: {}\", _i);\n // for ((h,a,b,c,g),x) in dp.iter() {\n // println!(\"{} {} {} {} {}: {}\", h,a,b,c,g,x);\n // }\n }\n dp2\n };\n // eprintln!(\"DP2\");\n // for ((a,b,c),x) in dp2.iter() {\n // println!(\"dp2 {} {} {} : {}\", a,b,c,x);\n // }\n\n let dp1 = {\n let mut st = [0; 3];\n st[2] = 1;\n st[1] = st[2] * (z[2] + 1);\n st[0] = st[1] * (z[1] + 1);\n let st = st;\n let sz = (st[0] * (sumt + 1)) as usize;\n\n let mut aa = vec![Field(0); sz];\n let mut dp = HashSet::::new();\n dp.insert(0);\n aa[0] = Field(1);\n for i in 0..n {\n if g[i] == 3 { continue; }\n\n let mut d = HashSet::::new();\n let mut a = vec![Field(0); sz];\n let x = t[i];\n let g = g[i] as usize;\n for &s in dp.iter() {\n let key = s + (x * st[0]) + st[g];\n d.insert(key);\n a[key as usize] += aa[s as usize];\n }\n for key in d.into_iter() {\n let s = key as usize;\n aa[s] += a[s];\n dp.insert(key);\n }\n }\n let mut dp1 = HashMap::<(i32,i32,i32),Field>::new();\n for s in dp.into_iter() {\n let t = s / st[0];\n let a = s % st[0] / st[1];\n let b = s % st[1] / st[2];\n dp1.insert((t,a,b),aa[s as usize]);\n }\n dp1\n };\n // eprintln!(\"DP1\");\n // for ((a,b,c),x) in dp1.iter() {\n // println!(\"dp1 {} {} {} : {}\", a,b,c,x);\n // }\n\n let dp3 = {\n let mut st = [0; 4];\n st[3] = 1;\n st[0] = st[3] * (z[3] + 1);\n let st = st;\n let sz = (st[0] * (sumt + 1)) as usize;\n\n let mut aa = vec![Field(0); sz];\n let mut dp = HashSet::::new();\n dp.insert(0);\n aa[0] = Field(1);\n for i in 0..n {\n if g[i] != 3 { continue; }\n\n let mut d = HashSet::::new();\n let mut a = vec![Field(0); sz];\n let x = t[i];\n let g = g[i] as usize;\n for &s in dp.iter() {\n let key = s + (x * st[0]) + st[g];\n d.insert(key);\n a[key as usize] += aa[s as usize];\n }\n for key in d.into_iter() {\n let s = key as usize;\n aa[s] += a[s];\n dp.insert(key);\n }\n }\n let mut dp3 = HashMap::<(i32,i32),Field>::new();\n for s in dp.into_iter() {\n let t = s / st[0];\n let c = s % st[0] / st[3];\n dp3.insert((t,c),aa[s as usize]);\n }\n dp3\n };\n // eprintln!(\"DP3\");\n // for ((a,b),x) in dp3.iter() {\n // println!(\"dp3 {} {} : {}\", a,b,x);\n // }\n\n let dp1 = {\n let mut dp = HashMap::<(i32,i32,i32),Field>::new();\n for ((tab,a,b),res1) in dp1 {\n let tc = tt - tab;\n if tc < 0 { continue; }\n for c in 0..=z[3] {\n if let Some(&res2) = dp3.get(&(tc,c)) {\n let res3 = *dp.get(&(a,b,c)).unwrap_or_default();\n dp.insert((a,b,c), res3 + res1*res2);\n }\n }\n }\n dp\n };\n // println!(\"DP1\");\n // println!(\"DP1\");\n // for ((a,b,c),&x) in dp1.iter() {\n // println!(\"dpX {} {} {} : {}\", a,b,c,x);\n // }\n\n let mut sol = Field::new_unchecked(0);\n for a in 0..=z[1] as i32 {\n for b in 0..=z[2] as i32 {\n for c in 0..=z[3] as i32 {\n let x = *dp1.get(&(a,b,c)).unwrap_or_default();\n let y = *dp2.get(&(a,b,c)).unwrap_or_default();\n sol += x * y;\n }\n }\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics"], "code_uid": "96ec61393b6ccf938bef79ddf37f3699", "src_uid": "ed5f913afe829c65792b54233a256757", "difficulty": 2600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(warnings)]\n\nuse std::io::{self, *};\nuse std::str::{self, *};\n\nfn main() {\n let mut stdin = stdin();\n let mut buffer = String::new();\n let _ = stdin.read_to_string(&mut buffer);\n let mut input = buffer.split_whitespace().map(|w| w.parse::().unwrap());\n let n = input.next().unwrap();\n let l = input.next().unwrap();\n let r = input.next().unwrap();\n\n let mini = (0..l).map(|i| 2_i32.pow(i as u32)).sum::() + (n - l);\n let maxi = (0..r).map(|i| 2_i32.pow(i as u32)).sum::() + (n - r) * 2_i32.pow((r-1) as u32);\n\n println!(\"{} {}\", mini, maxi);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "9540316a7f602a8a0ca64901cc73aa9a", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n#[allow(unused_imports)]\nuse std::io::{stdout, stdin, BufWriter, Write};\n\nfn main() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n\n input!{\n n: usize,\n l: usize,\n r: usize,\n }\n\n let mut min_ans = 0;\n let mut d = 1;\n for _ in 0..l {\n min_ans += d;\n d *= 2;\n }\n min_ans += (n-l) * 1;\n\n let mut max_ans = 0;\n let mut d = 1;\n for _ in 0..r {\n max_ans += d;\n d *= 2;\n }\n\n max_ans += (n-r) * (d/2);\n puts!(\"{} {}\\n\", min_ans, max_ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "2b50908d7a3a2e199bcf1a33a2a70795", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, bytes) => {\n read_value!($next, String).into_bytes()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{BinaryHeap, HashMap};\n\n#[allow(dead_code)]\ntype Graph = Vec>;\n\nfn main() {\n input! {\n n: usize, l: usize, r: usize,\n }\n\n let mini = (1 << l) - 1 + 1 * (n - l);\n let maxi = (1 << r) - 1 + (1 << (r - 1)) * (n - r);\n\n println!(\"{} {}\", mini, maxi);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "3514a08177b8ec85f930385e92053a36", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut line = String::new();\n\tmatch io::stdin().read_line(&mut line) {\n\t\tOk(_) => (),\n\t\tErr(e) => println!(\"Error: {}\", e),\n\t}\n\tline = line.trim().to_string();\n\tlet sint = line.split(\" \");\n\tlet number = sint.into_iter().map(|x| x.parse::().unwrap()).collect::>();\n\n\tlet min_diff = 2i32.pow((number[1]) as u32)-1;\n\tlet max_diff = 2i32.pow(number[2] as u32)-1;\n\tlet min_sum = min_diff + (number[0]-number[1]);\n\tlet max_sum = max_diff + (number[0]-number[2])*2i32.pow((number[2]-1) as u32);\n\tprintln!(\"{} {}\", min_sum, max_sum);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "3b516960f03f42c000faea0e014042cc", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_variables)]\n#![allow(unused_must_use)]\n\nuse std::io::{self, prelude::*};\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let mut input = Input::new(stdin.lock());\n let mut output = io::BufWriter::new(stdout.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(output ,$($format)*).unwrap());\n }\n let n: u32 = input.next();\n let l: u32 = input.next();\n let r: u32 = input.next();\n\n let min: u64 = 2u64.pow(l) - 1 + (n - l) as u64; \n let max: u64 = 2u64.pow(r) - 1 + (n - r) as u64 * 2u64.pow(r - 1);\n puts!(\"{} {}\\n\", min, max);\n\n}\n\nstruct Input {\n lines: io::Lines,\n cur: String,\n split: std::str::SplitAsciiWhitespace<'static>, //'\n}\n\nimpl Input {\n fn new(reader: R) -> Input {\n use std::mem::transmute;\n\n let mut lines = reader.lines();\n let cur = lines.next().unwrap().unwrap();\n let split = unsafe { transmute(cur.split_ascii_whitespace()) };\n Input { lines, cur, split }\n }\n fn update(&mut self) {\n use std::mem::transmute;\n self.cur = self.lines.next().unwrap().unwrap();\n unsafe { self.split = transmute(self.cur.split_ascii_whitespace()) };\n }\n fn next(&mut self) -> F {\n loop {\n if let Some(thing) = self.split.next() {\n return thing.parse().ok().unwrap();\n }\n self.update();\n }\n }\n fn iter(&mut self) -> InputIter {\n InputIter {\n input: self,\n _phantom: std::marker::PhantomData,\n }\n }\n}\n\nstruct InputIter<'a, R, I> {\n input: &'a mut Input,\n _phantom: std::marker::PhantomData,\n}\n\nimpl<'a, R, I> Iterator for InputIter<'a, R, I>\nwhere\n R: BufRead,\n I: std::str::FromStr,\n{\n type Item = I;\n fn next(&mut self) -> Option {\n Some(self.input.next())\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "8761f470fd24b3c2fbb5253af44a0fd6", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[macro_use]\nmod input {\n\nuse std;\nuse std::io;\n\nconst SPLIT_DELIMITER: char = ' ';\n\n#[macro_export]\n#[allow(unused_macros)]\nmacro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n#[allow(dead_code)]\npub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(dead_code)]\npub fn p(t: T)\nwhere\n T: std::fmt::Display,\n{\n println!(\"{}\", t);\n}\n\n#[allow(dead_code)]\npub fn input_vector2d(line: usize) -> Vec>\nwhere\n T: std::str::FromStr,\n{\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n}\n\n#[allow(dead_code)]\npub fn input_vector() -> Vec\nwhere\n T: std::str::FromStr,\n{\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n}\n\n#[allow(dead_code)]\npub fn str2vec(s: &str) -> Vec {\n let mut v: Vec = Vec::new();\n for c in s.chars() {\n v.push(c);\n }\n v\n}\n}\n\n#[allow(unused_imports)]\nuse input::*;\n\nfn main() {\n let (n, l, r): (u64, u64, u64);\n input!(n, l, r);\n\n let mut min;\n min = 2_u64.pow(l as u32) - 1 + n - l;\n\n let max_value = 2_u64.pow(r as u32 - 1);\n let mut max = vec![1];\n\n for z in 1..n {\n let prev = *max.iter().last().unwrap();\n if prev * 2 > max_value {\n max.push(prev);\n } else {\n max.push(prev * 2);\n }\n }\n\n println!(\"{} {}\", min,max.iter().sum::());\n}", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "9c7c158c3a15af31fe2d92c84ed8434a", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(n,l,r = input.u());\n let min = (1 << l) + n - l - 1;\n let max = (n - r) * (1 << (r - 1)) + (1 << r) - 1;\n println!(\"{} {}\", min, max);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "626f3fcad43b9a504192b8b0dee4aa99", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n l: usize,\n r: usize,\n }\n let mut k = 0;\n let mut b = 1;\n let mut x = 0;\n while k < l {\n x += b;\n b <<= 1;\n k += 1;\n }\n x += 1 * (n - k);\n let mut k = 0;\n let mut b = 1;\n let mut y = 0;\n while k + 1 < r {\n y += b;\n b <<= 1;\n k += 1;\n }\n y += (1 << (r - 1)) * (n - k);\n println!(\"{} {}\", x, y);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "226a5949f642ee838a61ad6ae55ba6fc", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get!(i64));\n ($t:ty) => (get().parse::<$t>().unwrap());\n }\n \n let n = 14;\n let mut xs = vec![];\n for _ in 0..n {\n let x = get!();\n xs.push(x);\n }\n let mut ans = 0;\n for i in 0..n {\n let x = xs[i];\n let d = x / 14;\n let r = (x % 14) as usize;\n xs[i] = 0;\n let mut tmp = 0;\n for j in 0..n {\n let mut e = xs[j] + d;\n if i < j && j <= i + r {\n e += 1;\n } else if i < j + 14 && j + 14 <= i + r {\n e += 1;\n }\n if e % 2 == 0 {\n tmp += e;\n }\n }\n ans = std::cmp::max(ans, tmp);\n xs[i] = x;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "c10111b7c49d0f8d09a835c40b7c507c", "src_uid": "1ac11153e35509e755ea15f1d57d156b", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n use std::io::prelude::*;\n use std::io;\n\n let mut input = String::new();\n io::stdin().read_to_string(&mut input).unwrap();\n\n let a: Vec = input.split_whitespace().map(|x| x.parse().unwrap())\n .collect();\n\n let mut max_ans = 0;\n\n let modulo = |a, b| {\n if a < 0 {\n a % b + b\n } else {\n a % b\n }\n };\n let modsub = |a, b| {\n modulo(a - b, 14)\n };\n\n for (i, &ai) in a.iter().enumerate() {\n let q = ai / 14;\n let r = ai % 14;\n\n let mut ans = 0;\n let mut j = i + 1;\n for _ in 0..13 {\n let cnt = a[modulo(j, 14)] + q + if r < modsub(j, i) as i64 { 0 } else { 1 };\n if cnt % 2 == 0 {\n ans += cnt;\n }\n \n j += 1\n }\n\n if q % 2 == 0 {\n ans += q;\n }\n\n if max_ans < ans {\n max_ans = ans;\n }\n }\n\n println!(\"{}\", max_ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "f5b410d4179162232f462f16ccec8717", "src_uid": "1ac11153e35509e755ea15f1d57d156b", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\nfn main() {\n use std::io::Write;\n\n let stdin = io::stdin();\n let stdout = io::stdout();\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n \n let len: usize = scan.token();\n let k: usize = scan.token();\n\n let scores: Vec = (0..len).map(|_| scan.token()).collect();\n\n let test = scores[k - 1];\n let mut count = 0;\n for score in scores {\n if score >= test && score > 0 {\n count += 1;\n }\n }\n writeln!(out, \"{}\", count).ok();\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ae6c92c6dcdeed95c6bf25bd507c49c0", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn main() {\n let mut intro = String::new();\n io::stdin().read_line(&mut intro).unwrap();\n\n let mut start_iter = intro.split_whitespace();\n let n = start_iter.next().unwrap();\n let k = start_iter.next().unwrap();\n\n let n: u8 = n.trim().parse().unwrap();\n let k: u8 = k.trim().parse().unwrap();\n\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n\n let mut iter = input.split_whitespace();\n \n let mut output: u8 = 0;\n let mut cut_off: u8 = 0;\n\n for i in 0..n {\n let num = iter.next().unwrap();\n let num: u8 = num.parse().unwrap();\n\n if num == 0 { break; }\n\n if i + 1 < k { output += 1; }\n else if i + 1 == k { \n cut_off = num;\n output += 1;\n }\n else if num >= cut_off {\n output += 1;\n }\n else { break; }\n }\n\n println!(\"{}\", output);\n}\n\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "aeb7f74863ad982b62cffa0250d1b2d5", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\nfn main() {\n let input = take_input();\n let vals: Vec<&str> = split(&input);\n let k: usize = parse(vals[1]);\n let input = take_input();\n let vals = split(&input);\n let mut a: Vec = Vec::new();\n for num in vals {\n a.push(parse(num));\n }\n let p = next_round(k, a.as_mut_slice());\n println!(\"{}\", p);\n}\n\nfn next_round(k: usize, a: &mut [u32]) -> u32 {\n let mut participants = 0;\n let pivot = a[k - 1];\n for i in a {\n if *i > 0 {\n if *i >= pivot {\n participants += 1;\n }\n else {\n break;\n }\n }\n }\n participants\n}\n\nfn take_input() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn parse(string: &str) -> T {\n let ret: T = match string.trim().parse() {\n Ok(x) => x,\n Err(_) => panic!(\"Not a number\")\n };\n ret\n}\n\nfn split<'a>(string: &'a String) -> Vec<&'a str> {\n let ret: Vec<&'a str> = string.split(' ').collect();\n ret\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "568bac6fb9860c2520e6d0dbf1959c8a", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut first_input = String::new();\n std::io::stdin().read_line(&mut first_input).expect(\"Value Not found\");\n\n let inputs: Vec = first_input.split_whitespace().map(|s| s.parse().expect(\"Parse error\")).collect();\n\n let num_contestants: usize = inputs[0];\n let k_positon: usize = inputs[1];\n\n /*\n *println!(\"{:?}\", inputs);\n */\n /*\n *println!(\"num_contestants = {} k_positon = {}\", num_contestants, k_positon);\n */\n\n if (k_positon > num_contestants) || (num_contestants > 50) {\n return ()\n }\n\n let mut second_input = String::new();\n std::io::stdin().read_line(&mut second_input)\n .expect(\"Value not found\");\n\n let score_input: Vec = second_input.split_whitespace().map(|s| s.parse().expect(\"parse error\")).collect();\n\n let count: usize = score_input.len();\n\n if (num_contestants != count) || (count > 100) {\n return ()\n }\n\n let mut i: usize = 0;\n for _i in 0..num_contestants-1 {\n if (score_input[i] > score_input[i+1]) || (score_input[i] == score_input[i+1]) {\n i += 1;\n }\n else {\n break;\n }\n }\n\n let mut final_count: usize = 0;\n let mut i: usize = 0;\n\n for _i in &score_input {\n if (score_input[k_positon -1] <= score_input[i]) && (score_input[i] > 0) {\n final_count = final_count + 1;\n i += 1;\n }\n }\n println!(\"{}\", final_count);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f956e32c86e3e2cd4866500a0da34629", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin};\n\nfn main() {\n\tlet mut inp = String::from(\"\");\n\n\tlet n: u8;\n\tlet k: u8;\n\tlet mut v: Vec;\n\n\tstdin().read_line(&mut inp).expect(\"\");\n\n\tn = inp.split_whitespace().nth(0).unwrap().parse().unwrap();\n\tk = inp.split_whitespace().nth(1).unwrap().parse::().unwrap() - 1;\n\n\tinp = String::from(\"\");\n\tstdin().read_line(&mut inp).expect(\"\");\n\n\tv = inp.split_whitespace().map(|a| a.parse::().unwrap()).collect();\n\tlet key = v[k as usize];\n\n\tv.sort();\n\n\tlet res = v.iter().position(|x| x >= &key && x != &0);\n\tif let Some(x) = res {\n\t\tprintln!(\"{}\", n - x as u8);\n\t} else {\n\t\tprintln!(\"{}\", 0);\n\t}\t\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f0a0abe5113b0a385bba8a7176a4a23c", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n// use std::str::FromStr;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let ns : Vec = input.split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect::>();\n input.clear();\n io::stdin().read_line(&mut input).unwrap();\n let scores : Vec = input.split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect::>();\n let bar = scores[ns[1] as usize - 1];\n let mut a : i32 = 0;\n for score in &scores {\n if *score <= 0 || *score < bar {\n break;\n }\n a = a + 1;\n }\n println!(\"{}\", a);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7707560ed24c62d5f717ca74adefd40b", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn get_top_k(xs: Vec, k: i32) -> i32 {\n if let Some(&target_score) = xs.get(k as usize - 1) {\n if 0 < target_score {\n xs.into_iter().filter(|&x| x >= target_score).count() as i32\n } else {\n xs.into_iter().filter(|&x| x > 0).count() as i32\n }\n } else {\n 0\n }\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let mut line = String::new();\n\n stdin.read_line(&mut line).unwrap();\n\n if let &[_, k] = line\n .split_whitespace()\n .map(|v| v.parse::().unwrap())\n .collect::>()\n .as_slice()\n {\n line = String::new();\n stdin.read_line(&mut line).unwrap();\n\n let xs = line\n .split_whitespace()\n .map(|v| v.parse::().unwrap())\n .collect::>();\n\n println!(\"{}\", get_top_k(xs, k));\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6dca1945c2554abb368331650724c0ce", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut v = s.split_whitespace().map(|a| a.parse::().unwrap());\n v.next().unwrap();\n let k = v.next().unwrap() as usize;\n s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let arr = s.split_whitespace().map(|a| a.parse::().unwrap());\n let mut c = 1;\n let mut sol = 0;\n\n for (i, x) in arr.enumerate() {\n if x > 0 && i < k {\n c = x;\n }\n if x >= c {\n sol += 1;\n }\n }\n println!(\"{}\", sol);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "49b10b6cbc5bc8853ecfa7a94f3e21da", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::Ordering;\n\ntype Pair = (i8, i8);\nfn input_pair() -> Pair {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let buf: Vec = buf\n .trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect();\n (buf[0], buf[1])\n}\n\nfn main() {\n let (a, b) = input_pair();\n let (mut a_count, mut b_count, mut mid) = (0, 0, 0);\n\n for i in 1..=6 {\n match (a-i).abs().cmp(&(b-i).abs()) {\n Ordering::Less => a_count += 1,\n Ordering::Greater => b_count += 1,\n Ordering::Equal => mid += 1\n }\n }\n\n print!(\"{} {} {}\", a_count, mid, b_count);\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "05ce08e3689a9f1b66a3f5d0afa7df37", "src_uid": "504b8aae3a3abedf873a3b8b127c5dd8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min,Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (a,b) = readln!(i32,i32);\n let mut res = [0,0,0];\n for i in 1..7 {\n res[\n match (a-i).abs().cmp(&(b-i).abs()) {\n Ordering::Greater => 2,\n Ordering::Equal => 1,\n Ordering::Less => 0,\n }\n ] += 1;\n }\n println!(\"{} {} {}\",res[0],res[1],res[2]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "b2c2f87bf72ffb9ef868308b57f39a12", "src_uid": "504b8aae3a3abedf873a3b8b127c5dd8", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let rin = buf.split_whitespace().map(|c| c.parse::().unwrap()).collect::>();\n let n = rin[0] + rin[1];\n\n let ret1 = factors(n, None);\n let x = ret1.last().unwrap();\n let ret3 = factors(rin[0], Some(*x));\n let ret4 = factors(rin[1], Some(*x));\n// println!(\"{:?} {:?}\", ret3, ret4);\n\n let mut p: Option = None;\n 'find: for i in ret1.iter().rev() {\n let x1 = i;\n let y1 = n / x1;\n for j in ret3.iter().rev() {\n let x2 = j;\n let y2 = rin[0] / x2;\n// println!(\"{} {}, {} {}\", x1, y1, x2, y2);\n if x2 <= x1 && y2 <= y1 {\n let _p = (x1 + y1) * 2;\n if p.is_none() || _p < p.unwrap() {\n p = Some(_p);\n }\n break;\n }\n }\n for j in ret4.iter().rev() {\n let x2 = j;\n let y2 = rin[1] / x2;\n// println!(\"{} {}, {} {}\", x1, y1, x2, y2);\n if x2 <= x1 && y2 <= y1 {\n let _p = (x1 + y1) * 2;\n if p.is_none() || _p < p.unwrap() {\n p = Some(_p);\n }\n break 'find;\n }\n }\n }\n println!(\"{}\", p.unwrap());\n}\n\nfn factors(n: u64, max: Option) -> Vec {\n let sqrt = (n as f64).sqrt() as u64;\n let mut ret = Vec::::new();\n for i in 1..=sqrt {\n match max {\n Some(x) if i > x => {\n// println!(\"{}, {}\", i, x);\n break;\n }\n _ => {}\n }\n if n % i == 0 {\n ret.push(i);\n }\n }\n// let ret = (1..=sqrt).rev().filter(|c| n % c == 0).collect::>();\n return ret;\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search", "number theory"], "code_uid": "77d2ab4764c032e1a3f9907d90577a13", "src_uid": "7d0c5f77bca792b6ab4fd4088fe18ff1", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cell::RefCell;\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Formatter, Write as FmtWrite};\nuse std::io::{stderr, stdin, BufRead, Write};\nuse std::mem::{replace, swap};\nuse std::ops::*;\nuse std::rc::Rc;\n\n// -----------------------------------------------\n// Framework \n// -----------------------------------------------\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($t:ty) =>\n (rl().parse::<$t>().unwrap());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($arg:expr),*) => {\n #[cfg(debug_assertions)]\n $(writeln!(stderr(), \"{} = {:?}\", stringify!($arg), $arg).unwrap());*\n };\n}\n\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_owned()\n}\n\ntrait IteratorExt: Iterator + Sized {\n fn vec(self) -> Vec {\n self.collect()\n }\n}\n\nimpl IteratorExt for T {}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\n#[derive(PartialEq, Eq, Clone, Debug)]\npub struct Rev(pub T);\n\nimpl PartialOrd for Rev {\n fn partial_cmp(&self, other: &Rev) -> Option {\n other.0.partial_cmp(&self.0)\n }\n}\n\nimpl Ord for Rev {\n fn cmp(&self, other: &Rev) -> Ordering {\n other.0.cmp(&self.0)\n }\n}\n\nfn divs(n: i64) -> Vec {\n let r = (n as f64).sqrt().ceil() as i64;\n\n let mut xs = vec![];\n\n for k in 1..r + 1 {\n if n % k == 0 {\n xs.push(k);\n }\n }\n\n xs\n}\n\nfn solve_core(a: i64, b: i64) -> i64 {\n let mut ts = divs(a);\n let ss = ts.iter().rev().map(|&t| a / t).vec();\n ts.extend(ss);\n\n let ys = divs(a + b);\n\n // debug!((a, b), ts, ys);\n\n let mut l = 0;\n let mut r = 0;\n let mut q: BinaryHeap<(Rev, usize)> = BinaryHeap::new();\n let mut mi = std::i64::MAX;\n\n for ti in 0..ts.len() {\n let t = ts[ti];\n\n while l < ys.len() && ys[l] < t {\n l += 1;\n }\n\n r = max(r, l);\n\n while r < ys.len() && (a + b) / ys[r] >= a / t {\n let y = ys[r];\n let x = (a + b) / y;\n q.push((Rev(2 * (y + x)), r));\n\n r += 1;\n }\n\n while let Some(&(_, yi)) = q.peek() {\n if l <= yi {\n break;\n }\n\n q.pop();\n }\n\n // debug!((ti, t, l, r));\n\n if let Some((Rev(p), _)) = q.pop() {\n // debug!(p);\n mi = min(mi, p);\n }\n }\n\n mi\n}\n\nfn solve(a: i64, b: i64) -> i64 {\n let mut mi = solve_core(a, b);\n if a != b {\n mi = min(mi, solve_core(b, a));\n }\n mi\n}\n\nfn main() {\n let (a, b) = read!(i64, i64);\n println!(\"{}\", solve(a, b))\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search", "number theory"], "code_uid": "3bcb187588b3277eff9128b2211232f9", "src_uid": "7d0c5f77bca792b6ab4fd4088fe18ff1", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let input: String = read(sin);\n\n for c in input.as_str().chars() {\n match c {\n 'H' | 'Q' | '9' => {\n println!(\"YES\");\n return;\n }\n _ => (),\n }\n }\n\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1503b72ff8b791ac0e0182b3c0030440", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut line = String::new();\n\n io::stdin().read_line(&mut line).expect(\"\");\n if line.contains(\"H\") || line.contains(\"Q\") || line.contains(\"9\") {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d07e625940f43d66abd9c73255a35bc3", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut f = false;\n for c in s.chars() {\n if c == 'H' || c == 'Q' || c == '9' {\n f = true;\n }\n }\n if f {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "50d0cf1cc3e35c3e85eef13de58bb2ca", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n let mut line=String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n if line.find('Q')!=None || line.find('H')!=None || line.find('9')!=None{\n print!(\"YES\");\n }\n else{print!(\"NO\");}\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "29d19831a5ea0bc16103bd27a6d4ba2d", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\n\nfn read() -> String {\n let mut res = String::new();\n std::io::stdin().read_line(&mut res).unwrap();\n res\n}\n\nstruct Scanner {\n curr_iter: std::vec::IntoIter,\n}\n\nimpl Scanner {\n fn get_iter() -> std::vec::IntoIter {\n read().split_whitespace().map(|x| x.to_string())\n .collect::>().into_iter()\n }\n\n fn next > (&mut self) -> T {\n let x = self.curr_iter.next();\n match x {\n Some(y) => { y.parse().unwrap() }\n None => {\n self.curr_iter = Self::get_iter();\n self.next()\n }\n }\n }\n\n fn new() -> Self {\n Self { curr_iter: Self::get_iter() }\n }\n}\n\nfn main() {\n let s = read().into_bytes();\n for c in s {\n if c == b'H' || c == b'Q' || c == b'9' {\n println!(\"YES\");\n return;\n }\n }\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8cdb0075092e2296d711985544d30027", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> std::io::Result<()> {\n let stdin = io::stdin();\n let mut input = String::new();\n stdin.read_line(&mut input)?;\n print!(\"{}\", match hq9plus(input) {\n true => \"YES\",\n false => \"NO\"\n }.to_string());\n Ok(())\n}\n\nfn hq9plus(input: String) -> bool {\n input.trim().chars().filter(|&c|\n c == 'H' || c == 'Q' || c == '9'\n ).collect::().len() > 0\n}\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test() {\n assert_eq!(hq9plus(\"Hi!\".to_string()), true);\n assert_eq!(hq9plus(\"Codeforces\".to_string()), false);\n\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "14bd0a8dc7ba85043e024aba3ccbc9e8", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn check(text: String) -> &'static str {\n for c in text.chars() {\n match c {\n 'H' | 'Q' | '9' => return \"YES\",\n _ => (),\n }\n }\n return \"NO\";\n}\n\nfn input() -> String {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n}\n\nfn main() {\n let text = input();\n println!(\"{}\", check(text));\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "504bfe2000e4e1420b927e014d7adb2e", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut p = String::new();\n\n io::stdin()\n .read_line(&mut p)\n .unwrap();\n\n if p.contains(\"H\") ||\n p.contains(\"Q\") ||\n p.contains(\"9\") {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b12761f0e414cedb1bd641dfdd0806a3", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nfn gcd(a: u128, b: u128) -> u128 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn run() {\n input! {\n x: u128,\n y: u128,\n }\n if gcd(x, y) > 1 {\n println!(\"Impossible\");\n return;\n }\n // a / b < c / d\n let small = |a, b, c, d| a * d < b * c;\n // a / b > c / d\n let large = |a, b, c, d| a * d > b * c;\n let mut l = (0, 1);\n let mut r = (1, 0);\n let mut ans = vec![];\n while l.0 + r.0 < x || l.1 + r.1 < y {\n let (p, q) = (l.0 + r.0, l.1 + r.1);\n if small(p, q, x, y) {\n let mut ok = 1;\n let mut ng = 2;\n while small(l.0 + ng * r.0, l.1 + ng * r.1, x, y) {\n ok = ng;\n ng *= 2;\n }\n while ng - ok > 1 {\n let mid = (ok + ng) / 2;\n if small(l.0 + mid * r.0, l.1 + mid * r.1, x, y) {\n ok = mid;\n } else {\n ng = mid;\n }\n }\n ans.push((ok, 'A'));\n l = (l.0 + ok * r.0, l.1 + ok * r.1);\n } else {\n let mut ok = 1;\n let mut ng = 2;\n while large(ng * l.0 + r.0, ng * l.1 + r.1, x, y) {\n ok = ng;\n ng *= 2;\n }\n while ng - ok > 1 {\n let mid = (ok + ng) / 2;\n if large(mid * l.0 + r.0, mid * l.1 + r.1, x, y) {\n ok = mid;\n } else {\n ng = mid;\n }\n }\n ans.push((ok, 'B'));\n r = (ok * l.0 + r.0, ok * l.1 + r.1);\n }\n }\n let mut s = String::new();\n for (c, op) in ans {\n s.push_str(&format!(\"{}{}\", c, op));\n }\n println!(\"{}\", s);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "e1f27b7d70344ee2858946b582f46ce2", "src_uid": "6a9ec3b23bd462353d985e0c0f2f7671", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s1 = String::new();\n let mut s2 = String::new();\n io::stdin().read_line(&mut s1).unwrap();\n io::stdin().read_line(&mut s2).unwrap();\n s1 = s1.trim().to_string();\n s2 = s2.trim().to_string();\n let n = s1.len();\n let mut flag = true;\n for i in 0..n {\n let c1 = s1.chars().nth(i);\n let c2 = s2.chars().nth(n-1-i);\n if c1 != c2 {\n flag = false;\n }\n }\n if flag {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "3c8e40c71c16237c1f26cd3ad0e86674", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let word = get_input();\n let their_rev = get_input();\n let is_correct = their_rev == word.chars().rev().collect::();\n println!(\"{}\", if is_correct { \"YES\" } else { \"NO\" });\n \n}\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer.trim().to_owned()\n}\n\nfn get_input_usize() -> usize {\n get_input().parse().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "365253cffb8e1561ca58ef01cb0e4657", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s1 = String::new();\n std::io::stdin().read_line(&mut s1);\n let s1 = s1.trim();\n\n let mut s2 = String::new();\n std::io::stdin().read_line(&mut s2);\n let s2 = s2.trim();\n\n let s1_reversed: String = s1.chars().rev().collect();\n if s1_reversed.eq(s2) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "2f820fbbf7d3b554e383a5558daedc37", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn input() -> String {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n}\n\nfn main() {\n let (t, s) = (input(), input());\n if t == s.chars().rev().collect::() {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "24b81fb57b6a01c4781d0f4a3ed7b4fa", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut line1 = String::new();\n let mut line2 = String::new();\n std::io::stdin().read_line(&mut line1).unwrap();\n std::io::stdin().read_line(&mut line2).unwrap();\n let rev = line2.chars().rev().collect::();\n println!(\"{}\", if rev.trim() == line1.trim() { \"YES\" } else { \"NO\"});\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d7fd3a0aef9152c79d503d0ffa5827d7", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let first_string = read_line();\n let second_string = read_line();\n\n if second_string == first_string.chars().rev().collect::() {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n\n}\n\nfn read_line() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"\u041e\u0448\u0438\u0431\u043a\u0430 \u0447\u0442\u0435\u043d\u0438\u044f\");\n\n input.trim().to_string()\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "80c4b578de574684bcc325fc9f0cb8d7", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut s = String::new();\n let mut t = String::new();\n read_line(&stdin, &mut s);\n read_line(&stdin, &mut t);\n let mut c_s = s.trim().chars();\n let mut c_t = t.trim().chars();\n let mut is_translation = false;\n loop {\n let x_s = c_s.next();\n let x_t = c_t.next_back();\n if x_s.is_none() && x_t.is_none() {\n is_translation = true;\n break;\n } else if x_s.is_some() && x_t.is_some() {\n let u_x_s = x_s.unwrap();\n let u_x_t = x_t.unwrap();\n if u_x_s == u_x_t {\n // Do nothing ...\n } else {\n break;\n }\n } else {\n break;\n }\n }\n if is_translation {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "aaf8efc93dfd3ced8f6b73ac47738150", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n s : String,\n t : String,\n };\n let s: Vec = s.chars().collect();\n let t: Vec = t.chars().rev().collect();\n let n = s.len();\n for i in 0..n {\n if s.get(i) != t.get(i) {\n println!(\"NO\");\n return;\n }\n }\n println!(\"YES\");\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "58cd4e28b49dc01c873301a4af895233", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io;\nuse std::io::{stdout, BufWriter, Write};\nuse std::str::FromStr;\n\n#[allow(dead_code)]\nfn read_line() -> String {\n let mut buffer = String::new();\n io::stdin()\n .read_line(&mut buffer)\n .expect(\"failed to read line\");\n\n buffer\n}\n\n#[allow(dead_code)]\nfn read() -> Result {\n read_line().trim().parse::()\n}\n\n#[allow(dead_code)]\nfn read_vec() -> Result, T::Err> {\n read_line()\n .split_whitespace()\n .map(|x| x.parse::())\n .collect()\n}\n\nfn main() {\n let mut writer = BufWriter::new(stdout());\n let n = read().unwrap();\n for _ in 0..n {\n let qq = read().unwrap();\n writeln!(writer, \"{}\", 2u64.pow(qq) - 1).unwrap();\n }\n writer.flush().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "740a4fb4d4f55eb073dd8c266f79936b", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io;\n#[allow(unused)]\nuse std::collections::{HashMap, BTreeMap, VecDeque, HashSet, BinaryHeap};\n \n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim_end().to_string()\n}\n \n#[allow(unused_macros)]\nmacro_rules! read_vec {\n ($ty:ty) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n let mut v = Vec::new();\n while let Some(value) = it.next() {\n v.push(value.parse::<$ty>().unwrap());\n }\n v\n }}\n}\n \n#[allow(unused_macros)]\nmacro_rules! read {\n ( $ty:ty) => {\n gets().split_whitespace().next().unwrap().parse::<$ty>().unwrap()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }};\n ( $( $ty:ty ),+ ,) => {\n\t\tread![ $( $ty ),* ]\n };\n}\n\nfn main() {\n use std::io::Write;\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n\n for _ in 0..read!(usize) {\n let value = read!(usize);\n writeln!(out, \"{}\", (1 << value) - 1).unwrap();\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e794dee85e13fda5426a2adf693b6ef6", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io;\r\n\r\nfn read_integer() -> u32 {\r\n let mut input_text = String::new();\r\n io::stdin().read_line(&mut input_text).unwrap();\r\n return input_text.trim().parse::().unwrap();\r\n}\r\n\r\nfn bin_pow(n: u64, power: u32) -> u64 {\r\n if power == 0 {\r\n return 1;\r\n } else if power % 2 == 0 {\r\n return bin_pow(n * n, power / 2);\r\n } else {\r\n return n * bin_pow(n, power - 1);\r\n }\r\n}\r\n\r\nfn main() {\r\n let t = read_integer();\r\n\r\n for _ in 0..t {\r\n let n = read_integer();\r\n println!(\"{}\", bin_pow(2, n) - 1);\r\n }\r\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b3df23ba295d12da8580bca64d126416", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io;\nuse std::str::FromStr;\n\n#[allow(dead_code)]\nfn read_line() -> String {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n\n buffer.trim().to_string()\n}\n\n#[allow(dead_code)]\nfn read() -> Result{\n read_line().trim().parse::()\n}\n\n#[allow(dead_code)]\nfn read_vec() -> Result< Vec, T::Err>{\n read_line().split_whitespace().map(|x| x.parse::()).collect()\n}\n\nfn solve() {\n let n = read::().unwrap();\n\n println!(\"{}\", i64::pow(2, n) - 1);\n}\n\nfn main() {\n let t = read::().unwrap();\n for _i in 0..t {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "eb76a69e49cd6215bf6176ad0052bd21", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::vec::Vec;\nuse std::string::String;\n\nstruct Inp {\n // reversed input words for O(1) popping\n words: Vec,\n}\n\nimpl Inp {\n fn new() -> Self {\n Inp {\n words: Vec::new(),\n }\n }\n\n fn read(&mut self) -> T {\n if let Some(s) = self.words.pop() {\n match s.parse() {\n Ok(x) => x,\n Err(_) => panic!(\"Parse error\")\n }\n } else {\n loop {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n self.words = buf.trim().split_ascii_whitespace().rev().map(|x| x.to_owned()).collect();\n if let Some(s) = self.words.pop() {\n break match s.parse() {\n Ok(x) => x,\n Err(_) => panic!(\"Parse error\")\n }\n }\n }\n }\n }\n}\n\npub fn solve(n: u32) -> i64 {\n 2i64.pow(n) - 1\n}\n\nfn main() {\n let mut inp = Inp::new();\n\n let tries = inp.read();\n for _ in 0..tries {\n let x = inp.read();\n println!(\"{}\", solve(x));\n }\n}\n\n#[cfg(test)]\nmod test {\n #[test]\n fn given() {\n assert_eq!(crate::solve(3), 7);\n assert_eq!(crate::solve(4), 15);\n assert_eq!(crate::solve(1), 1);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "aa710f5efd14150b742e15a7e403bbea", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\nuse input::*;\nuse std::{\n collections::*,\n io::{self, BufWriter, Write},\n};\nfn run(mut ss: I, mut out: O) {\n let t: u32 = ss.parse();\n for _ in 0..t {\n case(&mut ss, &mut out);\n }\n}\nfn case(mut ss: I, mut out: O) {\n let n: i32 = ss.parse();\n let ans = (1 << n) - 1;\n wln!(out, \"{}\", ans)\n}\nfn main() {\n let stdin = io::stdin();\n let ss = SplitWs::new(stdin.lock());\n let stdout = io::stdout();\n let out = BufWriter::new(stdout.lock());\n run(ss, out);\n}\npub mod input {\n use std::{\n io::{self, prelude::*},\n marker::PhantomData,\n mem,\n };\n pub trait Input {\n fn bytes(&mut self) -> &[u8];\n fn bytes_vec(&mut self) -> Vec {\n self.bytes().to_vec()\n }\n fn str(&mut self) -> &str {\n std::str::from_utf8(self.bytes()).unwrap()\n }\n fn parse(&mut self) -> T {\n self.parse_with(DefaultParser)\n }\n fn parse_with(&mut self, mut parser: impl Parser) -> T {\n parser.parse(self)\n }\n fn seq(&mut self) -> Seq {\n self.seq_with(DefaultParser)\n }\n fn seq_with>(&mut self, parser: P) -> Seq {\n Seq {\n input: self,\n parser,\n marker: PhantomData,\n }\n }\n }\n impl Input for &mut T {\n fn bytes(&mut self) -> &[u8] {\n (**self).bytes()\n }\n }\n pub trait Parser {\n fn parse(&mut self, s: &mut I) -> T;\n }\n impl> Parser for &mut P {\n fn parse(&mut self, s: &mut I) -> T {\n (**self).parse(s)\n }\n }\n pub trait Parse {\n fn parse(s: &mut I) -> Self;\n }\n pub struct DefaultParser;\n impl Parser for DefaultParser {\n fn parse(&mut self, s: &mut I) -> T {\n T::parse(s)\n }\n }\n pub struct Seq<'a, T, I: ?Sized, P> {\n input: &'a mut I,\n parser: P,\n marker: PhantomData<*const T>,\n }\n impl<'a, T, I: Input, P: Parser> Iterator for Seq<'a, T, I, P> {\n type Item = T;\n #[inline]\n fn next(&mut self) -> Option {\n Some(self.input.parse_with(&mut self.parser))\n }\n fn size_hint(&self) -> (usize, Option) {\n (!0, None)\n }\n }\n impl Parse for char {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let s = s.bytes();\n debug_assert_eq!(s.len(), 1);\n *s.first().expect(\"zero length\") as char\n }\n }\n macro_rules ! tuple { ($ ($ T : ident) ,*) => { impl <$ ($ T : Parse) ,*> Parse for ($ ($ T ,) *) { # [inline] # [allow (unused_variables)] # [allow (clippy :: unused_unit)] fn parse < I : Input + ? Sized > (s : & mut I) -> Self { ($ ($ T :: parse (s) ,) *) } } } ; }\n tuple!();\n tuple!(A);\n tuple!(A, B);\n tuple!(A, B, C);\n tuple!(A, B, C, D);\n tuple!(A, B, C, D, E);\n tuple!(A, B, C, D, E, F);\n tuple!(A, B, C, D, E, F, G);\n #[cfg(feature = \"newer\")]\n impl Parse for [T; N] {\n fn parse(s: &mut I) -> Self {\n use std::{mem::MaybeUninit, ptr};\n struct Guard {\n arr: [MaybeUninit; N],\n i: usize,\n }\n impl Drop for Guard {\n fn drop(&mut self) {\n unsafe {\n ptr::drop_in_place(&mut self.arr[..self.i] as *mut _ as *mut [T]);\n }\n }\n }\n let mut g = Guard:: {\n arr: unsafe { MaybeUninit::uninit().assume_init() },\n i: 0,\n };\n while g.i < N {\n g.arr[g.i] = MaybeUninit::new(s.parse());\n g.i += 1;\n }\n unsafe { mem::transmute_copy(&g.arr) }\n }\n }\n macro_rules! uint {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let s = s.bytes();\n s.iter().fold(0, |x, d| 10 * x + (0xf & d) as $ty)\n }\n }\n };\n }\n macro_rules! int {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let f = |s: &[u8]| {\n s.iter()\n .fold(0 as $ty, |x, d| (10 * x).wrapping_add((0xf & d) as $ty))\n };\n let s = s.bytes();\n if let [b'-', s @ ..] = s {\n f(s).wrapping_neg()\n } else {\n f(s)\n }\n }\n }\n };\n }\n macro_rules! float {\n ($ ty : ty) => {\n impl Parse for $ty {\n fn parse(s: &mut I) -> Self {\n const POW: [$ty; 18] = [\n 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13,\n 1e14, 1e15, 1e16, 1e17,\n ];\n let s = s.bytes();\n let (minus, s) = if let Some((b'-', s)) = s.split_first() {\n (true, s)\n } else {\n (false, s)\n };\n let (int, fract) = if let Some(p) = s.iter().position(|c| *c == b'.') {\n (&s[..p], &s[p + 1..])\n } else {\n (s, &[][..])\n };\n let x = int\n .iter()\n .chain(fract)\n .fold(0u64, |x, d| 10 * x + (0xf & *d) as u64);\n let x = x as $ty;\n let x = if minus { -x } else { x };\n let exp = fract.len();\n if exp == 0 {\n x\n } else if let Some(pow) = POW.get(exp) {\n x / pow\n } else {\n x / (10.0 as $ty).powi(exp as i32)\n }\n }\n }\n };\n }\n macro_rules! from_bytes {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n s.bytes().into()\n }\n }\n };\n }\n macro_rules! from_str {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n s.str().into()\n }\n }\n };\n }\n macro_rules ! impls { ($ m : ident , $ ($ ty : ty) ,*) => { $ ($ m ! ($ ty) ;) * } ; }\n impls!(uint, usize, u8, u16, u32, u64, u128);\n impls!(int, isize, i8, i16, i32, i64, i128);\n impls!(float, f32, f64);\n impls!(from_bytes, Vec, Box<[u8]>);\n impls!(from_str, String);\n #[derive(Clone)]\n pub struct SplitWs {\n src: T,\n buf: Vec,\n pos: usize,\n len: usize,\n }\n const BUF_SIZE: usize = 1 << 26;\n impl SplitWs {\n pub fn new(src: T) -> Self {\n Self {\n src,\n buf: vec![0; BUF_SIZE],\n pos: 0,\n len: 0,\n }\n }\n #[inline(always)]\n fn peek(&self) -> &[u8] {\n unsafe { self.buf.get_unchecked(self.pos..self.len) }\n }\n #[inline(always)]\n fn consume(&mut self, n: usize) -> &[u8] {\n let pos = self.pos;\n self.pos += n;\n unsafe { self.buf.get_unchecked(pos..self.pos) }\n }\n fn read(&mut self) -> usize {\n self.buf.copy_within(self.pos..self.len, 0);\n self.len -= self.pos;\n self.pos = 0;\n if self.len == self.buf.len() {\n self.buf.resize(2 * self.buf.len(), 0);\n }\n loop {\n match self.src.read(&mut self.buf[self.len..]) {\n Ok(n) => {\n self.len += n;\n return n;\n }\n Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}\n Err(e) => panic!(\"io error: {:?}\", e),\n }\n }\n }\n }\n impl Input for SplitWs {\n #[inline]\n fn bytes(&mut self) -> &[u8] {\n loop {\n if let Some(del) = self.peek().iter().position(|c| c.is_ascii_whitespace()) {\n if del > 0 {\n let s = self.consume(del + 1);\n return s.split_last().unwrap().1;\n } else {\n self.consume(1);\n }\n } else if self.read() == 0 {\n return self.consume(self.len - self.pos);\n }\n }\n }\n }\n}\npub mod macros {\n #[macro_export]\n macro_rules ! w { ($ ($ arg : tt) *) => { write ! ($ ($ arg) *) . unwrap () ; } }\n #[macro_export]\n macro_rules ! wln { ($ dst : expr $ (, $ ($ arg : tt) *) ?) => { { writeln ! ($ dst $ (, $ ($ arg) *) ?) . unwrap () ; # [cfg (debug_assertions)] $ dst . flush () . unwrap () ; } } }\n #[macro_export]\n macro_rules! w_iter {\n ($ dst : expr , $ fmt : expr , $ iter : expr , $ delim : expr) => {{\n let mut first = true;\n for elem in $iter {\n if first {\n w!($dst, $fmt, elem);\n first = false;\n } else {\n w!($dst, concat!($delim, $fmt), elem);\n }\n }\n }};\n ($ dst : expr , $ fmt : expr , $ iter : expr) => {\n w_iter!($dst, $fmt, $iter, \" \")\n };\n }\n #[macro_export]\n macro_rules ! w_iter_ln { ($ dst : expr , $ ($ t : tt) *) => { { w_iter ! ($ dst , $ ($ t) *) ; wln ! ($ dst) ; } } }\n #[macro_export]\n macro_rules ! e { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprint ! ($ ($ t) *) } }\n #[macro_export]\n macro_rules ! eln { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprintln ! ($ ($ t) *) } }\n #[macro_export]\n #[doc(hidden)]\n macro_rules ! __tstr { ($ h : expr $ (, $ t : expr) +) => { concat ! (__tstr ! ($ ($ t) ,+) , \", \" , __tstr ! (@)) } ; ($ h : expr) => { concat ! (__tstr ! () , \" \" , __tstr ! (@)) } ; () => { \"\\x1B[94m[{}:{}]\\x1B[0m\" } ; (@) => { \"\\x1B[1;92m{}\\x1B[0m = {:?}\" } }\n #[macro_export]\n macro_rules ! d { ($ ($ a : expr) ,*) => { if std :: env :: var (\"ND\") . map (| v | & v == \"0\") . unwrap_or (true) { eln ! (__tstr ! ($ ($ a) ,*) , file ! () , line ! () , $ (stringify ! ($ a) , $ a) ,*) ; } } ; }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "30ead28383643777ccfb5725d21ecabe", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io::{stdin, stdout, BufWriter, Write};\r\n\r\n#[derive(Default)]\r\nstruct Scanner {\r\n\tbuffer: Vec,\r\n}\r\nimpl Scanner {\r\n\tfn next(&mut self) -> T {\r\n\t\tloop {\r\n\t\t\tif let Some(token) = self.buffer.pop() {\r\n\t\t\t\treturn token.parse().ok().expect(\"Failed parse\");\r\n\t\t\t}\r\n\t\t\tlet mut input = String::new();\r\n\t\t\tstdin().read_line(&mut input).expect(\"Failed read\");\r\n\t\t\tself.buffer =\r\n\t\t\t\tinput.split_whitespace().rev().map(String::from).collect();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfn main() {\r\n\tlet mut scan = Scanner::default();\r\n\tlet out = &mut BufWriter::new(stdout());\r\n\tlet test_cases = scan.next::();\r\n\tfor _i in 0..test_cases {\r\n\t\tlet n = scan.next::();\r\n\t\tlet result: u32 = 2u32.pow(n) - 1u32;\r\n\t\twriteln!(out, \"{}\", result).ok();\r\n\t}\r\n}\r\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "03e3248893b0fdea6c6e6c407a0319ac", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn main() {\n let (r, w) = (std::io::stdin(), std::io::stdout());\n let mut sc = IO::new(r.lock(), w.lock());\n\n let t: usize = sc.read();\n for _ in 0..t {\n let n: i64 = sc.read();\n println!(\"{}\", (1 << n) - 1);\n }\n}\n\npub struct IO(R, std::io::BufWriter);\n\nimpl IO {\n pub fn new(r: R, w: W) -> Self {\n Self(r, std::io::BufWriter::new(w))\n }\n pub fn write(&mut self, s: S) {\n use std::io::Write;\n self.1.write_all(s.to_string().as_bytes()).unwrap();\n }\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let buf = self\n .0\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn usize0(&mut self) -> usize {\n self.read::() - 1\n }\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4acc9c2263f71234295d161a888f7d5b", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn find_min(m: usize, s: usize) -> String {\n let mut num = vec![0; m];\n num[0] = 1;\n let mut i = m - 1;\n let mut sum = 1;\n\n while sum + 9 < s {\n num[i] = 9;\n i -= 1;\n sum += 9;\n }\n\n num[i] += (s - sum) as u8;\n vec_to_num(&num)\n}\n\nfn find_max(m: usize, s: usize) -> String {\n let mut num = vec![9; m];\n let mut i = m - 1;\n let mut sum = 9 * m;\n\n while sum - 9 > s {\n num[i] = 0;\n i -= 1;\n sum -= 9;\n }\n\n num[i] -= (sum - s) as u8;\n vec_to_num(&num)\n}\n\nfn vec_to_num(v: &Vec) -> String {\n v.into_iter()\n .map(|digit| (digit + 48) as char)\n .collect::()\n}\n\nfn main() {\n let (m, s) = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let temp: Vec = buf\n .trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect();\n (temp[0], temp[1])\n };\n\n if m == 1 && s == 0 {\n println!(\"0 0\");\n } else if s < 1 || s > 9 * m {\n println!(\"-1 -1\");\n } else {\n println!(\"{} {}\", find_min(m, s), find_max(m, s))\n }\n}", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "588e1ca06ff5d4f7ddfb32be549951bb", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn max_num_with_m_digits_and_digit_sum(m : usize, s : usize, max_num : &mut Vec) {\n if (m * 9) < s {\n // Do nothing ...\n } else {\n if s == 0 {\n if m == 1 {\n max_num.push(0);\n } else {\n // Do nothing ...\n }\n } else {\n let mut cur_sum = 0;\n for _ in 0 .. m {\n let diff = s - cur_sum; \n if diff >= 9 {\n max_num.push(9);\n cur_sum = cur_sum + 9;\n } else {\n max_num.push(diff as u8);\n cur_sum = cur_sum + diff;\n }\n }\n }\n }\n}\n\nfn min_num_with_m_digits_and_digit_sum(m : usize, max_num : &mut Vec) {\n if max_num.is_empty() {\n // Do nothing ...\n } else {\n max_num.reverse();\n if max_num[0] == 0 {\n if m == 1 {\n // Do nothing ...\n } else {\n max_num[0] = 1;\n for i in 1 .. m {\n if max_num[i] == 0 {\n // Do nothing ...\n } else {\n max_num[i] = max_num[i] - 1;\n break;\n }\n }\n }\n }\n }\n}\n\nfn print_vec(v : &Vec) {\n for &x in v.iter() {\n print!(\"{}\", x);\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut m_s = vec![];\n read_ts(&stdin, &mut m_s);\n let m = m_s[0];\n let s = m_s[1];\n let mut max_num = vec![];\n max_num_with_m_digits_and_digit_sum(m, s, &mut max_num);\n if max_num.is_empty() {\n println!(\"-1 -1\");\n } else {\n let mut max_num_copy = max_num.to_vec();\n min_num_with_m_digits_and_digit_sum(m, &mut max_num_copy);\n print_vec(&max_num_copy);\n print!(\" \");\n print_vec(&max_num);\n println!();\n }\n}", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "28c0baf887053072e2333d07dab1b8da", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/489/C\nuse std::io;\nuse std::char;\n\nfn reverse(cadena: &String) -> String {\n let mut ans = String::from(\"\");\n for ch in cadena.chars().rev() {\n ans.push(ch);\n }\n ans\n}\n\nfn main() {\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let words: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let m = words[0] as usize;\n let mut s = words[1];\n let mut _t = words[1];\n\n if s == 0 && m != 1 {\n println!(\"-1 -1\");\n return;\n }\n\n if s == 0 && m == 1 {\n println!(\"0 0\");\n return;\n }\n\n // lets construct maxima\n let mut maxima = String::from(\"\");\n\n while s > 0 {\n if s >= 9 {\n maxima = format!(\"9{}\", maxima);\n s -= 9;\n } else {\n maxima = format!(\"{}{}\", maxima, s);\n s -= s;\n }\n }\n \n if maxima.len() > m {\n println!(\"-1 -1\");\n return;\n }\n\n while maxima.len() < m {\n maxima = format!(\"{}0\", maxima);\n }\n\n // lets construct minima\n let mut chars: Vec = reverse(&maxima).chars().collect();\n let mut minima = String::from(\"\");\n\n if chars[0] == '0' {\n chars[0] = '1';\n for i in 1..chars.len() {\n if chars[i] != '0' {\n chars[i] = char::from_digit(chars[i].to_digit(10).unwrap()-1,10).unwrap();\n break;\n }\n }\n }\n\n for ch in chars {\n minima.push(ch);\n }\n\n println!(\"{} {}\", minima, maxima);\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "fc52fdaea6718ebc036e731d274b9e01", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() -> Result<(), Box> {\n let data = read_input();\n let (len, sum) = (data[0], data[1]);\n\n if 9 * len < sum {\n println!(\"-1 -1\");\n return Ok(());\n }\n\n if sum == 0 {\n if len > 1 {\n println!(\"-1 -1\");\n } else {\n println!(\"0 0\");\n }\n return Ok(());\n }\n\n if sum == 1 {\n let mut ans = String::with_capacity(len);\n ans.push('1');\n \n for _ in 1..len {\n ans.push('0');\n }\n println!(\"{} {}\", ans, ans);\n return Ok(());\n }\n\n if (sum >= 1 && sum <= 9) && (len == 1) {\n println!(\"{} {}\", sum, sum);\n return Ok(());\n }\n\n if sum % 9 == 0 && sum / 9 == len {\n let mut ans = String::with_capacity(len);\n for _ in 0..len {\n ans.push('9')\n }\n println!(\"{} {}\", ans, ans);\n return Ok(());\n }\n\n let mut digits = vec![0; len];\n let mut max_digits = vec![0; len];\n \n let nines = sum / 9;\n let rem = sum % 9;\n\n let start = len - nines;\n for i in (start..len).rev() {\n digits[i] = 9;\n }\n\n if len - nines > 1 {\n if rem > 0 {\n digits[start - 1] = rem - 1;\n digits[0] = 1;\n } else {\n digits[start] -= 1;\n digits[0] = 1;\n }\n } else {\n if rem > 0 {\n digits[0] = rem;\n } else {\n digits[start] -= 1;\n digits[0] = 1;\n }\n }\n\n for i in 0..nines {\n max_digits[i] = 9;\n }\n if rem != 0 {\n max_digits[nines] = rem;\n }\n\n for d in digits {\n print!(\"{}\", d);\n }\n print!(\" \");\n\n for d in max_digits {\n print!(\"{}\", d);\n }\n println!();\n\n Ok(())\n}\n\nfn read_input() -> Vec {\n let mut buffer = String::new();\n\n std::io::stdin()\n .read_line(&mut buffer)\n .expect(\"Failed to get input\");\n\n buffer\n .trim()\n .split_whitespace()\n .map(|x| x.parse().expect(\"Failed to parse number\"))\n .collect()\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "b8f7975ed7e7e0de371d5fc796272411", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i();\n let s = input.i();\n if (s == 0 && n > 1) || n * 9 < s {\n println!(\"-1 -1\");\n } else if n == 1 {\n println!(\"{} {}\", s, s);\n } else {\n let ok = |i,d,t| {\n if i == n - 1 && d == 0 { return false; }\n let t1 = t - d;\n t1 >= 0 && t1 <= 9 * i\n };\n (0..n).rev().fold(s, |t,i| {\n let d = (0..10).filter(|&d| ok(i,d,t)).min().unwrap();\n print!(\"{}\", d);\n t - d\n });\n print!(\" \");\n (0..n).rev().fold(s, |t,i| {\n let d = (0..10).filter(|&d| ok(i,d,t)).max().unwrap();\n print!(\"{}\", d);\n t - d\n });\n println!(\"\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "484324ec763c408d915f32f4a50c006d", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n,m) = readln!(i32,i32);\n if n==1 && m==0 {\n println!(\"0 0\");\n return;\n }\n if (9*n < m || m==0) {\n println!(\"-1 -1\");\n return;\n }\n let mut m1 = m;\n if (9*(n-1) >= m) {\n m1 -= 1;\n }\n\n let mut l = String::from(\"\");\n let mut used = 0;\n for i in 0..n {\n let mut touse = 0;\n if i == n-1 {\n touse = m-used;\n } else {\n touse = std::cmp::min(m1-used,9);\n }\n l.push((('0' as u8) + (touse as u8)) as char);\n used += touse;\n }\n\n let mut r = String::from(\"\");\n let mut used = 0;\n for i in 0..n {\n let touse = std::cmp::min(m-used,9);\n r.push((('0' as u8) + (touse as u8)) as char);\n used += touse;\n }\n println!(\"{} {}\",l.chars().rev().collect::(),r);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "08758ed4a1104a2ad8e102acea6a6202", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line(buf: &mut String) {\n buf.clear();\n match io::stdin().read_line(buf) {\n Err(error) => println!(\"error! {}\",error),\n _ => {}\n }\n}\n\nfn is_valid(m: i32, n: i32) -> bool {\n if n==0 || n>9*m {\n return false;\n }\n return true;\n}\nfn get_max(m:i32,n:i32) {\n let mut max = Vec::::new();\n max.reserve(m as usize);\n for _ in 0..m {\n max.push(0);\n }\n let mut n_copy = n;\n for index in 0..m {\n if n_copy > 9 {\n max[index as usize]+=9;\n n_copy -= 9;\n }\n else {\n max[index as usize]+= n_copy as u8;\n break;\n }\n }\n print!(\" \");\n for x in max {\n print!(\"{}\",x);\n }\n println!(\"\");\n\n}\nfn get_min(m:i32, n:i32) {\n let mut min = Vec::::new();\n min.reserve(m as usize);\n min.push(1);\n for _ in 1..m {\n min.push(0);\n }\n let mut n_copy = n-1;\n for index in (0..(m)).rev() {\n if n_copy > 9 {\n min[index as usize]+=9;\n n_copy -= 9;\n }\n else {\n min[index as usize]+= n_copy as u8;\n break;\n }\n }\n for x in min {\n print!(\"{}\",x);\n }\n\n}\n\nfn main() {\n let mut buf : String = String::new();\n read_line(&mut buf);\n let mut string_iter = buf.trim().split_whitespace();\n let m = string_iter.next().unwrap().parse::().unwrap();\n let n = string_iter.next().unwrap().parse::().unwrap();\n\n if !is_valid(m,n) {\n if m==1 && n==0 {\n println!(\"0 0\");\n }\n else{\n println!(\"-1 -1\");\n }\n }\n else {\n get_min(m,n);\n get_max(m,n);\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "806a367e8266fe10fac456c99dbb0470", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused)] use std::io::*;\n#[allow(unused)] use std::collections::*;\n#[allow(unused)] use std::mem::*;\n#[allow(unused)] use std::num::*;\n#[allow(unused)] use std::cmp::*;\n#[allow(unused)] use std::thread::*;\n#[allow(unused)] use std::ops::*;\n#[allow(unused)] use std::marker::*;\n#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).collect();\n let mut cnt : usize = 0;\n fn next(cnt: &mut usize, p: &Vec<&str>) -> T where T:std::str::FromStr\n { *cnt += 1; p[*cnt-1].parse().ok().unwrap() }\n ($(next::<$x>(&mut cnt, &s)), +)\n }}; }\n#[allow(unused)] macro_rules! arr { ($($n:expr, $T:ty), +) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let mut s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0);\n ($({let mut v = Vec::new(); v.reserve(($n) as usize);\n for _ in 0..$n { let t = s.next(); if t == None { break; }\n v.push(t.unwrap().parse::<$T>().unwrap()); } v }),+)\n }}; }\n///////////////////////////////////////////////////////////////////////////////\n\n\n\nfn main()\n{\n let (n, mut s) = scan!(usize, u64);\n if n == 1 && s == 0 { println!(\"0 0\"); return; }\n if (9 * n as u64) < s || s < 1 { println!(\"-1 -1\"); return; }\n let mut a = vec![0; n];\n for i in 0..n { a[i] += min(s, 9); s -= min(s, 9); }\n let mut b = a.iter().rev().map(|&x| x).collect::>();\n if b[0] == 0 { for i in 0..n { if b[i] > 0 { b[i] -= 1; b[0] += 1; break; } } }\n for i in 0..n { print!(\"{}\", b[i]); } print!(\" \");\n for i in 0..n { print!(\"{}\", a[i]); } println!();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "bb36e089f01f4760f24a5d4f6bb5fa00", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n // r(a_1 a_2 a_3...a_n) = a_2 a_3 .. a_n+1\n // -\n // a_1 a_2 a_3..a_n\n // ----------------\n // rS - S\n // therefore\n // S(r-1)=a_n+1 -a_1\n // S = (a_n+1 - a_1) / (r - 1)\n let result: u64 = 2u64.pow(n as u32 + 1) - 2;\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "c512803a1bbd603e7d1bf9a01b4f6f50", "src_uid": "f1b43baa14d4c262ba616d892525dfde", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n#[derive(PartialEq, PartialOrd)]\npub struct Total(pub T);\nimpl Eq for Total {}\nimpl Ord for Total { fn cmp(&self, other: &Total) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap() }}\n\nconst MAX:usize = 5;\nconst MOD:i64 = 1e9 as i64 + 7;\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nfn read_vec() -> Vec {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().split_whitespace()\n .map(|e| e.parse().ok().unwrap()).collect()\n}\n\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nuse std::hash::Hash;\nfn inc(map:&mut BTreeMap, key:T) {\n let count = map.entry(key).or_insert(0);\n *count += 1;\n}\n\nfn mod_pow(x:i64, n:i64, m:i64) -> i64 {\n let mut x = x;\n let mut n = n;\n let mut res = 1i64;\n while n > 0 {\n if n & 1 > 0 {\n res = res * x % m;\n }\n x = x * x % m;\n n >>= 1;\n }\n res\n}\n\n\nfn main() {\n input!{n:usize};\n let mut ans = 0i64;\n for i in 1..n+1 {\n ans += 2i64.pow(i as u32);\n }\n println!(\"{}\", ans);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "7f6c6e14e30fe261652e3e31d36ffed5", "src_uid": "f1b43baa14d4c262ba616d892525dfde", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let n: u32 = it.next().unwrap().parse().unwrap();\n let s: u32 = it.next().unwrap().parse().unwrap();\n\n let ans = (s - 1) / n + 1;\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "580855b676f97576c3a4c2e13a8c1efe", "src_uid": "04c067326ec897091c3dbcf4d134df96", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty; $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt; $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(input.i; a,b);\n println!(\"{}\", (b + a - 1) / a);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "893fb075146365440cf10be1e544a2f3", "src_uid": "04c067326ec897091c3dbcf4d134df96", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\n\nuse std::error::Error;\n\nfn solve(mut n: i32, mut m: i32) -> i32 {\n n = cmp::min(n, m);\n\n let mut res: i32 = 0;\n while m > 0 {\n res += m / n;\n m %= n;\n n = cmp::min(n, m);\n }\n\n res\n}\n\nfn main() -> Result<(), Box> {\n let mut n_str = String::new();\n std::io::stdin().read_line(&mut n_str)?;\n\n let mut split = n_str.split_whitespace();\n\n let n: i32 = split.next().unwrap().parse().unwrap();\n let m: i32 = split.next().unwrap().parse().unwrap();\n\n println!(\"{}\", solve(n, m));\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "70a4be889caeca6f0893969c25970a26", "src_uid": "04c067326ec897091c3dbcf4d134df96", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp;\n#[allow(unused_imports)]\nuse std::collections::BTreeSet;\n#[allow(unused_imports)]\nuse std::collections::HashMap;\n#[allow(unused_imports)]\nuse std::collections::HashSet;\nuse std::fmt::Display;\nuse std::fs::File;\nuse std::io::Read;\n#[allow(unused_imports)]\nuse std::mem;\n\n#[allow(dead_code)]\nfn pow_speedy_with_mod(mut p: i64, mut q: i64, m: i64) -> i64 {\n p %= m;\n let mut r = p;\n let mut ret: i64 = 1;\n while q > 0 {\n ret *= if q % 2 == 1 { r } else { 1 };\n r *= r;\n r %= m;\n q /= 2;\n ret %= m;\n }\n return ret;\n}\n\n#[allow(dead_code)]\nfn comb(n: usize, k: usize, m: i64, frac: &[i64], frac_inv: &[i64]) -> i64 {\n let mut ret = 1i64;\n if n < k {\n return 0;\n }\n ret *= frac[n] * frac_inv[n - k];\n ret %= m;\n ret *= frac_inv[k];\n ret %= m;\n ret\n}\n\n#[allow(dead_code)]\nfn show1dvec(v: &Vec) {\n let n = v.len();\n for i in 0..n - 1 {\n print!(\"{} \", v[i]);\n }\n println!(\"{} \", v[n - 1]);\n}\n\n#[derive(Debug)]\nstruct Piece {\n mark: char,\n y: i32,\n x: i32,\n}\n\nfn main() {\n let inputstatus = 1;\n\n let mut buf = String::new();\n let filename = \"inputrust.txt\";\n\n if inputstatus == 0 {\n let mut f = File::open(filename).expect(\"file not found\");\n f.read_to_string(&mut buf)\n .expect(\"something went wrong reading the file\");\n } else {\n std::io::stdin().read_to_string(&mut buf).unwrap();\n }\n\n let mut iter = buf.split_whitespace();\n\n let n: usize = iter.next().unwrap().parse().unwrap();\n let m: usize = iter.next().unwrap().parse().unwrap();\n\n println!(\n \"{}\",\n if n > m * 2 {\n m\n } else if n * 2 < m {\n n\n } else {\n (n + m) / 3\n }\n );\n\n // let n = iter.next().unwrap().parse().unwrap();\n\n // println!(\"{}\", n);\n // println!(\"{:?}\", cum_num);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "number theory"], "code_uid": "e854d45eb0e99aeb0e100cad1191d47e", "src_uid": "0718c6afe52cd232a5e942052527f31b", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (mut n,mut m) = readln!(i64,i64);\n n = min(n,m*2);\n m = min(m,n*2);\n println!(\"{}\",(n+m)/3);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "number theory"], "code_uid": "c5b65d6433cd09bcc7e2e610c9258ada", "src_uid": "0718c6afe52cd232a5e942052527f31b", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\n// type Matrix = Vec>;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (i64, i64) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\n\nfn main() {\n \n let (mut n, mut m) = read_line_pair();\n \n let mut count = 0;\n \n while n > 0 && m > 0 {\n if n > m {\n n -= 2;\n m -= 1;\n } else {\n n -= 1;\n m -= 2;\n }\n if n >= 0 && m >= 0 {\n count += 1; \n }\n \n }\n \n println!(\"{}\", count);\n\n // println!(\"{:?} {:?}\", l, r);\n \n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "number theory"], "code_uid": "861770388c8fcfb28a276f3b83b7dcd4", "src_uid": "0718c6afe52cd232a5e942052527f31b", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let mut buffer_iter = buffer.split_whitespace().map(|n| n.parse::().unwrap());\n let n = buffer_iter.next().unwrap();\n let m = buffer_iter.next().unwrap();\n\n if 2 * n <= m {\n println!(\"{}\", n);\n } else if 2 * m <= n {\n println!(\"{}\", m);\n } else {\n println!(\"{}\", (n + m) / 3);\n }\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "number theory"], "code_uid": "6021e2f334c0301c6bba22a4fbb0be76", "src_uid": "0718c6afe52cd232a5e942052527f31b", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let m: usize = scan.next();\n let result = n.min(m).min((n + m) / 3);\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "number theory"], "code_uid": "c9ab8b6df170b5435481a19e566c56e3", "src_uid": "0718c6afe52cd232a5e942052527f31b", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let e = input.i();\n let n = input.i();\n println!(\"{}\", ((n + e) / 3).min(e).min(n));\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "number theory"], "code_uid": "70bda9d1e4617098a29611f65c26fe5d", "src_uid": "0718c6afe52cd232a5e942052527f31b", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n#![allow(unused_imports)]\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::str::FromStr;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let nums: Vec = get_numbers(&input);\n let n = nums[0]; // experienced members\n let m = nums[1]; // newbies\n\n let mut teams = 0;\n let mut exp = n;\n let mut newb = m;\n while exp > 0 && newb > 0 {\n if exp > newb {\n exp -= 2;\n newb -= 1;\n teams += 1;\n } else {\n exp -= 1;\n newb -= 2;\n teams += 1;\n }\n }\n\n if exp == -1 || newb == -1 {\n teams -= 1;\n }\n\n println!(\"{}\", teams);\n}\n\n// get numbers from line seperated by spaces\nfn get_numbers(line: &str) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n line.split_whitespace()\n .map(|chunk| chunk.parse::().expect(\"failed to parse\"))\n .collect()\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "number theory"], "code_uid": "5bedbb07da0b319c240ed9aae796723c", "src_uid": "0718c6afe52cd232a5e942052527f31b", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let n = parse_line!(u64);\n if n % 2 == 1 {\n writeln!(writer, \"0\").unwrap();\n }else{\n writeln!(writer, \"{}\", 1 << (n / 2)).unwrap();\n }\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "bc293ac4f53a742f073bd77665da84f6", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::process::exit;\n\n#[allow(dead_code)]\nfn input_strs() -> Vec {\n let mut st = String::new();\n match stdin().read_line(&mut st) {\n Ok(_) => st.chars().collect(),\n Err(_) => panic!(\"err\"),\n }\n}\n\n#[allow(dead_code)]\nfn input_ints() -> Vec {\n let mut st = String::new();\n match stdin().read_line(&mut st) {\n Ok(_) => st.split_whitespace().map(|s| s.parse().unwrap()).collect(),\n Err(_) => panic!(\"err\"),\n }\n}\n\nfn solve() {\n let l = input_ints();\n let n = l[0] as u32;\n if n % 2 == 0 {\n println!(\"{}\", (2 as u32).pow(n / 2));\n } else {\n println!(\"{}\", 0);\n }\n}\n\nfn main() {\n solve();\n exit(0);\n}", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "fcb5dea4ff6739e18b1ef4d8cb4a9179", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[warn(unused_variables)]\n\nfn main() {\n let n = input_::();\n println!(\"{}\", if n % 2 == 0 {2u64.pow(n/2u32)} else {0})\n}\n\nfn input_str() -> String {\n let mut buff = String::new();\n std::io::stdin().read_line(&mut buff).expect(\"Err\");\n buff\n}\n\nfn input_() -> T\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().parse::().expect(\"Err pars\")\n}\n\n\nfn input_vec(sep: &str) -> Vec \nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().split(sep).map(|c| c.parse::().expect(\"Err pars\")).collect()\n}\n\nfn input_vec_chars() -> Vec {\n input_str().trim().chars().collect()\n}", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "2af8fa49326b281c67b61cd9f28a5262", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{BufWriter, stdin, stdout, Write};\nuse std::cmp::{min, max};\nuse std::collections::{VecDeque, HashMap, BTreeMap, HashSet, BTreeSet, BinaryHeap};\n\nfn main() {\n\tlet mut inp = my_input::default();\n\tlet out = &mut BufWriter::new(stdout());\n\tlet mut n = inp.scan::();\n\tif n % 2 == 1 {\n\t\twriteln!(out, \"0\");\n\t\treturn;\n\t}\n\tn /= 2;\n\tlet mut ans = 1 as i64;\n\tfor i in 0..n {\n\t\tans += ans;\n\t}\n\twriteln!(out, \"{}\", ans);\n}\n\n#[derive(Default)]\nstruct my_input {\n\tbuffer: Vec\n}\n\nimpl my_input {\n\tfn scan(&mut self) -> T {\n\t\tloop {\n\t\t\tif let Some(token) = self.buffer.pop() {\n\t\t\t\treturn token.parse().ok().expect(\"Parsing Error\");\n\t\t\t}\n\t\t\tlet mut s = String::new();\n\t\t\tstdin().read_line(&mut s).expect(\"Reading Error\");\n\t\t\tself.buffer = s.split_whitespace().rev().map(String::from).collect();\n\t\t}\n\t}\n}", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "b6ac34f4e2cb2432f7cb76109eaeddc3", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() -> Result<()> {\n let mut line = String::new();\n let _ = std::io::stdin().read_line(&mut line)?;\n let n: u32 = line.trim().parse()?;\n if (n & 1) == 1 {\n println!(\"0\");\n return Ok(());\n }\n println!(\"{}\", 2_usize.pow(n / 2));\n Ok(())\n}\n\nmacro_rules! decl_error{\n ($($error:ident)*) => {\n #[derive(Debug)]\n pub enum Error {\n $($error($error),)*\n }\n\n $(\n impl From<$error> for Error {\n fn from(e: $error) -> Self {\n Error::$error(e)\n }\n }\n )*\n\n pub type Result = std::result::Result;\n }\n\n}\n\nmod error {\n use std::io::Error as StdError;\n use std::num::ParseIntError;\n decl_error!(StdError ParseIntError);\n}\n\nuse error::Result;\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "7d4979d93f8a35853afbc3806478d80f", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u32 = scan.token();\n let ans = if n % 2 == 0 { 2i64.pow(n / 2) } else { 0 };\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "05ec7894e9c2f4e790e048f9c34ef9f1", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: u32 = scan.next();\n if n < 2 || n % 2 == 1 {\n println!(\"0\");\n } else {\n println!(\"{}\", 2u64.pow(n / 2));\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "2157dd279789da1804c662c595e314a3", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n println!(\"{}\", ((n + 1) % 2) * (1 << (n / 2)));\n\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "fc26cae7f504f12bf794ad5b500af087", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn main() {\n let n = read_one::();\n let an = read::();\n let mut ans = 0;\n\n for i in 0..n {\n ans += an[i] * i * 4;\n }\n println!(\"{}\", ans);\n}\n\n\n#[allow(dead_code)]\nfn read() -> Vec\nwhere T:\n std::str::FromStr,\n T::Err: std::fmt::Debug {\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.split_whitespace()\n .map(|s| s.trim().parse().unwrap())\n .collect()\n}\n\n#[allow(dead_code)]\nfn read_one() -> T\nwhere T:\n std::str::FromStr,\n T::Err: std::fmt::Debug {\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "29ae65985481015357e2b537e9879d21", "src_uid": "a5002ddf9e792cb4b4685e630f1e1b8f", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (a2,a3,a5,a6) = readln!(i32,i32,i32,i32);\n let a256 = min(a2,min(a5,a6));\n let a32 = min(a2-a256,a3);\n println!(\"{}\",32*a32+256*a256);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "brute force"], "code_uid": "3741cc73c6b94780f9a71c3429199d3e", "src_uid": "082b31cc156a7ba1e0a982f07ecc207e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\n\nfn parse_many(string: &str) -> Result, N::Err> {\n string.split_whitespace().map(str::parse).collect()\n}\n\nfn read_problem(br: R) -> Vec {\n let mut lines = br.lines();\n\n let vec = parse_many(&lines.next().unwrap().unwrap()).unwrap();\n assert!(vec.len() == 4);\n assert!(lines.next().is_none());\n vec\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let vec = read_problem(stdin.lock());\n\n use std::cmp::min;\n let twofiftysix = min(vec[0], min(vec[2], vec[3]));\n let thirtytwo = min(vec[0]-twofiftysix, vec[1]);\n\n println!(\"{}\", 256*twofiftysix + 32*thirtytwo);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "brute force"], "code_uid": "291c088f4d6bd5ecab33980f0a8d6ba2", "src_uid": "082b31cc156a7ba1e0a982f07ecc207e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a2: usize = scan.next();\n let a3: usize = scan.next();\n let a5: usize = scan.next();\n let a6: usize = scan.next();\n let n256: usize = a2.min(a5).min(a6);\n let n32: usize = a3.min(a2-n256);\n let result = n256*256 + n32*32;\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "brute force"], "code_uid": "b6515430b2f2b0625fb95a6c900220e3", "src_uid": "082b31cc156a7ba1e0a982f07ecc207e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\n\nmacro_rules! read_line {\n ($v:ident) => {\n let mut temp = String::new();\n std::io::stdin().read_line(&mut temp).unwrap();\n let $v = temp;\n };\n (var, $t:ty, $($v:ident), *) => {\n read_line!(input_line);\n let mut iter = parse_token!($t, input_line);\n $(\n let $v = iter.next().unwrap();\n )*\n };\n (vec, $t:ty, $v:ident) => {\n read_line!(input_line);\n let iter = parse_token!($t, input_line);\n let $v: Vec<$t> = iter.collect();\n };\n ($($v:ident; $t:ty), *) => {\n read_line!(input_line);\n let mut iter = input_line.split_whitespace();\n $(\n let $v: $t = iter.next().unwrap().parse().unwrap();\n )*\n };\n}\n\nmacro_rules! parse_token {\n ($t:ty, $e:expr) => {\n $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());\n };\n}\n\nfn main() {\n read_line!(k2;u32, k3;u32, k5;u32, k6;u32);\n let max_256 = min(min(k2, k5), k6);\n let k2_left = k2 - max_256;\n let max_32 = min(k2_left, k3);\n println!(\"{}\", max_32 * 32 + max_256 * 256);\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "brute force"], "code_uid": "0287a68a9f1b13bafbbcf5a2b093df9c", "src_uid": "082b31cc156a7ba1e0a982f07ecc207e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, std::io::stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut buffer = String::new();\n let mut input = WordReader::from_stdin(&mut buffer);\n\n let (a,b,c,d) = (input.i(), input.i(), input.i(), input.i());\n let x = a.min(c.min(d));\n let y = b.min(a - x);\n println!(\"{}\", x * 256 + y * 32);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "brute force"], "code_uid": "0179bad7dba2893a87579b02d65f2646", "src_uid": "082b31cc156a7ba1e0a982f07ecc207e", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nmod modint {\n\n #[allow(dead_code)]\n pub struct Mod;\n impl ConstantModulo for Mod {\n const MOD: u32 = 998_244_353;\n }\n\n #[allow(dead_code)]\n pub struct StaticMod;\n static mut STATIC_MOD: u32 = 0;\n impl Modulo for StaticMod {\n fn modulo() -> u32 {\n unsafe { STATIC_MOD }\n }\n }\n\n #[allow(dead_code)]\n impl StaticMod {\n pub fn set_modulo(p: u32) {\n unsafe {\n STATIC_MOD = p;\n }\n }\n }\n\n use std::marker::*;\n use std::ops::*;\n\n pub trait Modulo {\n fn modulo() -> u32;\n }\n\n pub trait ConstantModulo {\n const MOD: u32;\n }\n\n impl Modulo for T\n where\n T: ConstantModulo,\n {\n fn modulo() -> u32 {\n T::MOD\n }\n }\n\n pub struct ModInt(pub u32, PhantomData);\n\n impl Clone for ModInt {\n fn clone(&self) -> Self {\n ModInt::new_unchecked(self.0)\n }\n }\n\n impl Copy for ModInt {}\n\n impl Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: Self) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n ModInt::new_unchecked(d)\n }\n }\n\n impl AddAssign for ModInt {\n fn add_assign(&mut self, rhs: Self) {\n *self = *self + rhs;\n }\n }\n\n impl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: Self) -> Self::Output {\n let mut d = T::modulo() + self.0 - rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n ModInt::new_unchecked(d)\n }\n }\n\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: Self) {\n *self = *self - rhs;\n }\n }\n\n impl Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: Self) -> Self::Output {\n let v = self.0 as u64 * rhs.0 as u64 % T::modulo() as u64;\n ModInt::new_unchecked(v as u32)\n }\n }\n\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: Self) {\n *self = *self * rhs;\n }\n }\n\n impl Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n if self.0 == 0 {\n Self::zero()\n } else {\n Self::new_unchecked(T::modulo() - self.0)\n }\n }\n }\n\n impl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n\n impl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n }\n\n impl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: u64) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: i64) -> ModInt {\n let m = T::modulo() as i64;\n ModInt::new((val % m + m) as u32)\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n pub fn new_unchecked(d: u32) -> Self {\n ModInt(d, PhantomData)\n }\n pub fn zero() -> Self {\n ModInt::new_unchecked(0)\n }\n pub fn one() -> Self {\n ModInt::new_unchecked(1)\n }\n pub fn is_zero(&self) -> bool {\n self.0 == 0\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n pub fn new(d: u32) -> Self {\n ModInt::new_unchecked(d % T::modulo())\n }\n pub fn pow(&self, mut n: u64) -> Self {\n let mut t = Self::one();\n let mut s = *self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(&self) -> Self {\n assert!(self.0 != 0);\n self.pow(T::modulo() as u64 - 2)\n }\n }\n\n #[allow(dead_code)]\n pub fn mod_pow(r: u64, mut n: u64, m: u64) -> u64 {\n let mut t = 1 % m;\n let mut s = r % m;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s % m;\n }\n s = s * s % m;\n n >>= 1;\n }\n t\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\nmod precalc {\n use super::modint::*;\n #[allow(dead_code)]\n pub struct Precalc {\n inv: Vec>,\n fact: Vec>,\n ifact: Vec>,\n }\n #[allow(dead_code)]\n impl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);\n }\n ifact[n] = fact[n].inv();\n if n > 0 {\n inv[n] = ifact[n] * fact[n - 1];\n }\n for i in (1..n).rev() {\n ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);\n inv[i] = ifact[i] * fact[i - 1];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n assert!(n > 0);\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[n - k]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n }\n}\n// ---------- end Precalc ----------\n// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nuse modint::*;\ntype M = ModInt;\n\nfn run() {\n input! {\n n: usize,\n }\n let pc = precalc::Precalc::new(n);\n let mut ans = M::zero();\n for i in (0..n).step_by(2) {\n let k = i / 2;\n ans += pc.comb(n - i + k - 1, k);\n }\n ans *= M::new(2).inv().pow(n as u64);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "82ecc991c28b8f5056daa582e996d370", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// codesnip-guard: minmax\n#[macro_export]\nmacro_rules ! min { ($ e : expr) => { $ e } ; ($ e : expr , $ ($ es : expr) ,+) => { std :: cmp :: min ($ e , min ! ($ ($ es) ,+)) } ; }\n#[macro_export]\nmacro_rules ! chmin { ($ dst : expr , $ ($ src : expr) ,+) => { { let x = std :: cmp :: min ($ dst , min ! ($ ($ src) ,+)) ; $ dst = x ; } } ; }\n#[macro_export]\nmacro_rules ! max { ($ e : expr) => { $ e } ; ($ e : expr , $ ($ es : expr) ,+) => { std :: cmp :: max ($ e , max ! ($ ($ es) ,+)) } ; }\n#[macro_export]\nmacro_rules ! chmax { ($ dst : expr , $ ($ src : expr) ,+) => { { let x = std :: cmp :: max ($ dst , max ! ($ ($ src) ,+)) ; $ dst = x ; } } ; }\n// codesnip-guard: scanner\npub trait IterScan: Sized {\n type Output;\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option;\n}\npub trait MarkedIterScan: Sized {\n type Output;\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option;\n}\n#[derive(Clone, Debug)]\npub struct Scanner<'a> {\n iter: std::str::SplitAsciiWhitespace<'a>,\n}\nmod scanner_impls {\n use super::*;\n impl<'a> Scanner<'a> {\n #[inline]\n pub fn new(s: &'a str) -> Self {\n let iter = s.split_ascii_whitespace();\n Self { iter }\n }\n #[inline]\n pub fn scan(&mut self) -> ::Output {\n ::scan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn mscan(&mut self, marker: T) -> ::Output {\n marker.mscan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn scan_vec(&mut self, size: usize) -> Vec<::Output> {\n (0..size)\n .map(|_| ::scan(&mut self.iter).expect(\"scan error\"))\n .collect()\n }\n #[inline]\n pub fn iter<'b, T: IterScan>(&'b mut self) -> ScannerIter<'a, 'b, T> {\n ScannerIter {\n inner: self,\n _marker: std::marker::PhantomData,\n }\n }\n }\n macro_rules ! iter_scan_impls { ($ ($ t : ty) *) => { $ (impl IterScan for $ t { type Output = Self ; # [inline] fn scan <'a , I : Iterator < Item = &'a str >> (iter : & mut I) -> Option < Self > { iter . next () ?. parse ::<$ t > () . ok () } }) * } ; }\n iter_scan_impls ! (char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);\n macro_rules ! iter_scan_tuple_impl { ($ ($ T : ident) *) => { impl <$ ($ T : IterScan) ,*> IterScan for ($ ($ T ,) *) { type Output = ($ (<$ T as IterScan >:: Output ,) *) ; # [inline] fn scan <'a , It : Iterator < Item = &'a str >> (_iter : & mut It) -> Option < Self :: Output > { Some (($ (<$ T as IterScan >:: scan (_iter) ?,) *)) } } } ; }\n iter_scan_tuple_impl!();\n iter_scan_tuple_impl!(A);\n iter_scan_tuple_impl ! (A B);\n iter_scan_tuple_impl ! (A B C);\n iter_scan_tuple_impl ! (A B C D);\n iter_scan_tuple_impl ! (A B C D E);\n iter_scan_tuple_impl ! (A B C D E F);\n iter_scan_tuple_impl ! (A B C D E F G);\n iter_scan_tuple_impl ! (A B C D E F G H);\n iter_scan_tuple_impl ! (A B C D E F G H I);\n iter_scan_tuple_impl ! (A B C D E F G H I J);\n iter_scan_tuple_impl ! (A B C D E F G H I J K);\n pub struct ScannerIter<'a, 'b, T> {\n inner: &'b mut Scanner<'a>,\n _marker: std::marker::PhantomData T>,\n }\n impl<'a, 'b, T: IterScan> Iterator for ScannerIter<'a, 'b, T> {\n type Item = ::Output;\n #[inline]\n fn next(&mut self) -> Option {\n ::scan(&mut self.inner.iter)\n }\n }\n}\npub mod marker {\n use super::*;\n use std::{iter::FromIterator, marker::PhantomData};\n #[derive(Debug, Copy, Clone)]\n pub struct Usize1;\n impl IterScan for Usize1 {\n type Output = usize;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(::scan(iter)?.checked_sub(1)?)\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct Chars;\n impl IterScan for Chars {\n type Output = Vec;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(iter.next()?.chars().collect())\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct CharsWithBase(pub char);\n impl MarkedIterScan for CharsWithBase {\n type Output = Vec;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n iter.next()?\n .chars()\n .map(|c| (c as u8 - self.0 as u8) as usize)\n .collect(),\n )\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct Collect::Output>> {\n size: usize,\n _marker: PhantomData (T, B)>,\n }\n impl::Output>> Collect {\n pub fn new(size: usize) -> Self {\n Self {\n size,\n _marker: PhantomData,\n }\n }\n }\n impl::Output>> MarkedIterScan for Collect {\n type Output = B;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n (0..self.size)\n .map(|_| ::scan(iter).expect(\"scan error\"))\n .collect::(),\n )\n }\n }\n}\n// codesnip-guard: zero_one\npub trait Zero: PartialEq + Sized {\n fn zero() -> Self;\n #[inline]\n fn is_zero(&self) -> bool {\n self == &Self::zero()\n }\n}\npub trait One: PartialEq + Sized {\n fn one() -> Self;\n #[inline]\n fn is_one(&self) -> bool {\n self == &Self::one()\n }\n}\nmacro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { # [inline] fn $ method () -> Self { $ e } }) *) * } ; }\nzero_one_impls ! ({ Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 0 } { Zero zero f32 f64 , 0. } { One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 1 } { One one f32 f64 , 1. });\n// codesnip-guard: main\nfn main() {\n #![allow(unused_imports, unused_macros)]\n use std::io::{stdin, stdout, BufWriter, Read as _, Write as _};\n let mut _in_buf = Vec::new();\n stdin().read_to_end(&mut _in_buf).expect(\"io error\");\n let _in_buf = unsafe { String::from_utf8_unchecked(_in_buf) };\n let mut scanner = Scanner::new(&_in_buf);\n macro_rules ! scan { () => { scan ! (usize) } ; (($ ($ t : tt) ,*)) => { ($ (scan ! ($ t)) ,*) } ; ([$ t : tt ; $ len : expr]) => { (0 ..$ len) . map (| _ | scan ! ($ t)) . collect ::< Vec < _ >> () } ; ([$ t : ty ; $ len : expr]) => { scanner . scan_vec ::<$ t > ($ len) } ; ([$ t : ty]) => { scanner . iter ::<$ t > () } ; ({ $ e : expr }) => { scanner . mscan ($ e) } ; ($ t : ty) => { scanner . scan ::<$ t > () } ; }\n let _out = stdout();\n let mut _out = BufWriter::new(_out.lock());\n macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules! echo {\n ($ iter : expr) => {\n echo!($iter, '\\n')\n };\n ($ iter : expr , $ sep : expr) => {\n let mut iter = $iter.into_iter();\n if let Some(item) = iter.next() {\n print!(\"{}\", item);\n }\n for item in iter {\n print!(\"{}{}\", $sep, item);\n }\n println!();\n };\n }\n let n = scan!();\n let mut dp = vec![M::zero(); n + 1];\n let mut acc1 = vec![M::zero(); n + 1];\n let mut acc2 = vec![M::zero(); n + 1];\n dp[0] = M::one();\n acc1[0] = M::one();\n for i in 0..n {\n dp[i + 1] = if i % 2 == 0 { acc1[i] } else { acc2[i] };\n acc1[i + 1] = acc1[i];\n acc2[i + 1] = acc2[i];\n if i % 2 == 0 {\n acc2[i + 1] += dp[i + 1];\n } else {\n acc1[i + 1] += dp[i + 1];\n }\n }\n println!(\"{}\", dp[n] / M::new_unchecked(2).pow(n));\n}\ntype M = mint_basic::MInt998244353;\n// codesnip-guard: MIntBase\n#[repr(transparent)]\npub struct MInt\nwhere\n M: MIntBase,\n{\n x: M::Inner,\n _marker: std::marker::PhantomData M>,\n}\npub trait MIntBase {\n type Inner: Sized + Copy + Eq + std::fmt::Debug + std::hash::Hash;\n fn get_mod() -> Self::Inner;\n fn mod_zero() -> Self::Inner;\n fn mod_one() -> Self::Inner;\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_neg(x: Self::Inner) -> Self::Inner;\n fn mod_inv(x: Self::Inner) -> Self::Inner;\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n let (mut x, mut y, mut z) = (x, y, Self::mod_one());\n while y > 0 {\n if y & 1 == 1 {\n z = Self::mod_mul(z, x);\n }\n x = Self::mod_mul(x, x);\n y >>= 1;\n }\n z\n }\n}\npub trait MIntConvert::Inner>: MIntBase {\n fn from(x: T) -> ::Inner;\n fn into(x: ::Inner) -> T;\n fn mod_into() -> T;\n}\nmod mint_base {\n use super::*;\n use std::{\n fmt::{self, Debug, Display},\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n };\n impl MInt\n where\n M: MIntConvert,\n {\n #[inline]\n pub fn new(x: M::Inner) -> Self {\n Self::new_unchecked(>::from(x))\n }\n #[inline]\n pub fn inner(self) -> M::Inner {\n >::into(self.x)\n }\n }\n impl MInt\n where\n M: MIntBase,\n {\n #[inline]\n pub fn new_unchecked(x: M::Inner) -> Self {\n Self {\n x,\n _marker: PhantomData,\n }\n }\n #[inline]\n pub fn get_mod() -> M::Inner {\n M::get_mod()\n }\n #[inline]\n pub fn pow(self, y: usize) -> Self {\n Self::new_unchecked(M::mod_pow(self.x, y))\n }\n #[inline]\n pub fn inv(self) -> Self {\n Self::new_unchecked(M::mod_inv(self.x))\n }\n }\n impl Clone for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn clone(&self) -> Self {\n Self {\n x: Clone::clone(&self.x),\n _marker: PhantomData,\n }\n }\n }\n impl Copy for MInt where M: MIntBase {}\n impl Debug for MInt\n where\n M: MIntBase,\n {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Debug::fmt(&self.x, f)\n }\n }\n impl Default for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn default() -> Self {\n ::zero()\n }\n }\n impl PartialEq for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n PartialEq::eq(&self.x, &other.x)\n }\n }\n impl Eq for MInt where M: MIntBase {}\n impl Hash for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn hash(&self, state: &mut H) {\n Hash::hash(&self.x, state)\n }\n }\n macro_rules ! impl_mint_from { ($ ($ t : ty) ,*) => { $ (impl < M > From <$ t > for MInt < M > where M : MIntConvert <$ t >, { # [inline] fn from (x : $ t) -> Self { Self :: new_unchecked (< M as MIntConvert <$ t >>:: from (x)) } } impl < M > From < MInt < M >> for $ t where M : MIntConvert <$ t >, { # [inline] fn from (x : MInt < M >) -> $ t { < M as MIntConvert <$ t >>:: into (x . x) } }) * } ; }\n impl_mint_from!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n impl Zero for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn zero() -> Self {\n Self::new_unchecked(M::mod_zero())\n }\n }\n impl One for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn one() -> Self {\n Self::new_unchecked(M::mod_one())\n }\n }\n impl Add for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_add(self.x, rhs.x))\n }\n }\n impl Sub for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_sub(self.x, rhs.x))\n }\n }\n impl Mul for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_mul(self.x, rhs.x))\n }\n }\n impl Div for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_div(self.x, rhs.x))\n }\n }\n impl Neg for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn neg(self) -> Self::Output {\n Self::new_unchecked(M::mod_neg(self.x))\n }\n }\n impl Sum for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl Product for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl<'a, M: 'a> Sum<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl<'a, M: 'a> Product<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl Display for MInt\n where\n M: MIntConvert,\n M::Inner: Display,\n {\n fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {\n write!(f, \"{}\", self.inner())\n }\n }\n impl FromStr for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Err = ::Err;\n #[inline]\n fn from_str(s: &str) -> Result {\n s.parse::().map(Self::new)\n }\n }\n impl IterScan for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Output = Self;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n iter.next()?.parse::>().ok()\n }\n }\n macro_rules! impl_mint_ref_binop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp<$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: $t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, other)\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(self, *other)\n }\n }\n impl $imp<&$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, *other)\n }\n }\n };\n }\n impl_mint_ref_binop!(Add, add, MInt);\n impl_mint_ref_binop!(Sub, sub, MInt);\n impl_mint_ref_binop!(Mul, mul, MInt);\n impl_mint_ref_binop!(Div, div, MInt);\n macro_rules! impl_mint_ref_unop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp>::Output;\n #[inline]\n fn $method(self) -> <$t as $imp>::Output {\n $imp::$method(*self)\n }\n }\n };\n }\n impl_mint_ref_unop!(Neg, neg, MInt);\n macro_rules! impl_mint_ref_op_assign {\n ($ imp : ident , $ method : ident , $ t : ty , $ fromimp : ident , $ frommethod : ident) => {\n impl $imp<$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, rhs: $t) {\n *self = $fromimp::$frommethod(*self, rhs);\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, other: &$t) {\n $imp::$method(self, *other);\n }\n }\n };\n }\n impl_mint_ref_op_assign!(AddAssign, add_assign, MInt, Add, add);\n impl_mint_ref_op_assign!(SubAssign, sub_assign, MInt, Sub, sub);\n impl_mint_ref_op_assign!(MulAssign, mul_assign, MInt, Mul, mul);\n impl_mint_ref_op_assign!(DivAssign, div_assign, MInt, Div, div);\n}\n// codesnip-guard: MInt\npub mod mint_basic {\n use super::*;\n #[macro_export]\n macro_rules ! define_basic_mintbase { ($ name : ident , $ m : expr , $ basety : ty , $ upperty : ty , [$ ($ unsigned : ty) ,*] , [$ ($ signed : ty) ,*]) => { pub struct $ name ; impl MIntBase for $ name { type Inner = $ basety ; # [inline] fn get_mod () -> Self :: Inner { $ m } # [inline] fn mod_zero () -> Self :: Inner { 0 } # [inline] fn mod_one () -> Self :: Inner { 1 } # [inline] fn mod_add (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { let z = x + y ; let m = Self :: get_mod () ; if z >= m { z - m } else { z } } # [inline] fn mod_sub (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { if x < y { x + Self :: get_mod () - y } else { x - y } } # [inline] fn mod_mul (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { (x as $ upperty * y as $ upperty % Self :: get_mod () as $ upperty) as $ basety } # [inline] fn mod_div (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { Self :: mod_mul (x , Self :: mod_inv (y)) } # [inline] fn mod_neg (x : Self :: Inner) -> Self :: Inner { if x == 0 { 0 } else { Self :: get_mod () - x } } fn mod_inv (x : Self :: Inner) -> Self :: Inner { let mut a = x ; let (mut b , mut u , mut s) = (Self :: get_mod () , 1 , 0) ; let k = a . trailing_zeros () ; a >>= k ; for _ in 0 .. k { if u & 1 == 1 { u += Self :: get_mod () ; } u /= 2 ; } while a != b { if b < a { std :: mem :: swap (& mut a , & mut b) ; std :: mem :: swap (& mut u , & mut s) ; } b -= a ; if s < u { s += Self :: get_mod () ; } s -= u ; let k = b . trailing_zeros () ; b >>= k ; for _ in 0 .. k { if s & 1 == 1 { s += Self :: get_mod () ; } s /= 2 ; } } s } } $ (impl MIntConvert <$ unsigned > for $ name { # [inline] fn from (x : $ unsigned) -> Self :: Inner { (x % < Self as MIntBase >:: get_mod () as $ unsigned) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ unsigned { x as $ unsigned } # [inline] fn mod_into () -> $ unsigned { < Self as MIntBase >:: get_mod () as $ unsigned } }) * $ (impl MIntConvert <$ signed > for $ name { # [inline] fn from (x : $ signed) -> Self :: Inner { let x = x % < Self as MIntBase >:: get_mod () as $ signed ; if x < 0 { (x + < Self as MIntBase >:: get_mod () as $ signed) as $ basety } else { x as $ basety } } # [inline] fn into (x : Self :: Inner) -> $ signed { x as $ signed } # [inline] fn mod_into () -> $ signed { < Self as MIntBase >:: get_mod () as $ signed } }) * } ; }\n #[macro_export]\n macro_rules ! define_basic_mint32 { ($ ([$ name : ident , $ m : expr , $ mint_name : ident]) ,*) => { $ (crate :: define_basic_mintbase ! ($ name , $ m , u32 , u64 , [u32 , u64 , u128 , usize] , [i32 , i64 , i128 , isize]) ; pub type $ mint_name = MInt <$ name >;) * } ; }\n define_basic_mint32!(\n [Modulo998244353, 998_244_353, MInt998244353],\n [Modulo1000000007, 1_000_000_007, MInt1000000007],\n [Modulo1000000009, 1_000_000_009, MInt1000000009],\n [DynModuloU32, unsafe { DYN_MODULUS_U32 }, DynMIntU32]\n );\n static mut DYN_MODULUS_U32: u32 = 1_000_000_007;\n impl DynModuloU32 {\n pub fn set_mod(m: u32) {\n unsafe {\n DYN_MODULUS_U32 = m;\n }\n }\n }\n static mut DYN_MODULUS_U64: u64 = 1_000_000_007;\n define_basic_mintbase!(\n DynModuloU64,\n unsafe { DYN_MODULUS_U64 },\n u64,\n u128,\n [u64, u128, usize],\n [i64, i128, isize]\n );\n impl DynModuloU64 {\n pub fn set_mod(m: u64) {\n unsafe {\n DYN_MODULUS_U64 = m;\n }\n }\n }\n pub type DynMIntU64 = MInt;\n pub struct Modulo2;\n impl MIntBase for Modulo2 {\n type Inner = u32;\n #[inline]\n fn get_mod() -> Self::Inner {\n 2\n }\n #[inline]\n fn mod_zero() -> Self::Inner {\n 0\n }\n #[inline]\n fn mod_one() -> Self::Inner {\n 1\n }\n #[inline]\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x | y\n }\n #[inline]\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n assert_ne!(y, 0);\n x\n }\n #[inline]\n fn mod_neg(x: Self::Inner) -> Self::Inner {\n x\n }\n #[inline]\n fn mod_inv(x: Self::Inner) -> Self::Inner {\n assert_ne!(x, 0);\n x\n }\n #[inline]\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n if y == 0 {\n 1\n } else {\n x\n }\n }\n }\n macro_rules ! impl_to_mint_base_for_modulo2 { ($ name : ident , $ basety : ty , [$ ($ t : ty) ,*]) => { $ (impl MIntConvert <$ t > for $ name { # [inline] fn from (x : $ t) -> Self :: Inner { (x & 1) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ t { x as $ t } # [inline] fn mod_into () -> $ t { 1 } }) * } ; }\n impl_to_mint_base_for_modulo2!(\n Modulo2,\n u32,\n [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]\n );\n pub type MInt2 = MInt;\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "77183ce5e05a841f68cf3779cc156fe3", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n date : 2020 / 5 / 5\n author : quickn (quickn.ga)\n email : quickwshell@gmail.com\n*/\n\nuse std::io::{self, BufWriter, Write};\n\nmod scanner {\n use std::{io, str};\n /* https://github.com/EbTech/rust-algorithms */\n\n /// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n /// **REQUIRES** Rust 1.34 or higher\n pub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n }\n\n impl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n }\n}\n\nconst MOD: i64 = 998244353;\n\nfn pow_mod(a: i64, x: i64) -> i64 {\n let (mut r, mut a_t, mut x_t) = (1, a, x);\n while x_t != 0 {\n if (x_t & 1) == 1 {\n r *= a_t;\n r %= MOD;\n }\n a_t *= a_t;\n a_t %= MOD;\n x_t >>= 1;\n }\n r\n}\n\nfn mod_inv(a: i64) -> i64 {\n pow_mod(a, MOD-2)\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let (mut scan, mut sout) = (\n scanner::UnsafeScanner::new(stdin.lock()),\n BufWriter::new(stdout.lock()),\n );\n let n: i64 = scan.token();\n let mut dp: Vec = vec![0;(n+10) as usize];\n let mut inv2 = mod_inv(2);\n dp[0] = 1;\n dp[1] = inv2;\n dp[2] = (dp[1]*inv2)%MOD;\n for i in 3..=(n as usize) {\n dp[i] = (((dp[i-1]*inv2)%MOD) + ((dp[i-2]*pow_mod(inv2, 2))%MOD))%MOD;\n }\n writeln!(sout, \"{}\", dp[n as usize]).ok();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "14ba3e4f3b00c91ee10133f228ac3943", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufRead, BufWriter, Write, StdinLock, StdoutLock};\n\nfn input(stdin: &mut StdinLock) -> String {\n let mut input = String::new();\n stdin.read_line(&mut input).ok();\n input\n}\n\nmacro_rules! read {\n ($stdin:expr, [$t:tt; $n:expr]) => {\n (0..$n).map(|_| read!($stdin, $t)).collect::>()\n };\n ($stdin:expr, [$t:tt]) => {\n input($stdin)\n .split_whitespace()\n .map(|x| parse!(x, $t))\n .collect::>() \n };\n ($stdin:expr, ($($t:tt),*)) => {\n {\n let input = input($stdin);\n let mut iter = input.split_whitespace(); \n ( $( parse!(iter.next().unwrap(), $t) ),* )\n }\n };\n ($stdin:expr, $t:tt) => {\n parse!(input($stdin).trim(), $t)\n };\n}\n\nmacro_rules! parse {\n ($s:expr, chars) => {\n $s.chars().collect::>()\n };\n ($s:expr, usize1) => {\n parse!($s, usize) - 1\n };\n ($s:expr, $t:ty) => {\n $s.parse::<$t>().unwrap()\n }\n}\n\ntrait ProconWrite {\n fn writeln(&mut self, x: T);\n fn writeln_iter(&mut self, iter: I)\n where\n I::Item: std::fmt::Display\n {\n self.writeln(\n iter.map(|x| x.to_string()).collect::>().join(\" \")\n );\n }\n}\n \nimpl ProconWrite for BufWriter> {\n fn writeln(&mut self, x: T) {\n writeln!(self, \"{}\", x).ok();\n }\n}\n\n#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]\nstruct ModInt(i64);\n\nimpl ModInt {\n const MOD: i64 = 998_244_353;\n\n fn new(x: i64) -> ModInt {\n Self(x % Self::MOD)\n }\n}\n\nimpl std::ops::Add for ModInt {\n type Output = Self;\n\n fn add(self, other: Self) -> Self {\n let x = self.0 + other.0;\n if x < Self::MOD { Self(x) } else { Self(x - Self::MOD) }\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) {\n *self = *self + other;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = Self;\n\n fn sub(self, other: Self) -> Self {\n if self.0 < other.0 {\n Self(self.0 + Self::MOD - other.0)\n } else {\n Self(self.0 - other.0)\n }\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) {\n *self = *self - other;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = Self;\n\n fn mul(self, other: Self) -> Self {\n Self::new(self.0 * other.0)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) {\n *self = *self * other;\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n\n fn from_str(s: &str) -> Result {\n let x = s.parse()?;\n Ok(ModInt(x))\n }\n}\n\nimpl From for ModInt {\n fn from(x: usize) -> Self {\n Self(x as i64)\n }\n}\n\nimpl ModInt {\n fn pow(mut self, mut n: i64) -> Self {\n assert!(n >= 0);\n let mut res = Self(1);\n while n != 0 {\n if n & 1 != 0 {\n res *= self;\n }\n self *= self;\n n >>= 1;\n }\n res\n }\n \n fn inv(self) -> Self {\n self.pow(Self::MOD - 2)\n }\n}\n\nfn solve(stdin: &mut StdinLock, writer: &mut BufWriter) {\n let n = read!(stdin, usize);\n\n let mut sum = [ModInt(0), ModInt(0)];\n let mut a = vec![ModInt(0); n + 1];\n a[0] = ModInt(1);\n for i in 1..=n {\n a[i] = a[i] + a[i - 1];\n if i >= 3 {\n sum[i % 2] += a[i - 3];\n a[i] += sum[i % 2];\n }\n }\n\n writer.writeln(a[n] * ModInt(2).pow(n as i64).inv());\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n\n let stdout = std::io::stdout();\n let mut writer = BufWriter::new(stdout.lock());\n\n solve(&mut stdin, &mut writer);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "6e9ac0c7ba7e04a544f0095903260e97", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::*;\n\n// scanner from https://codeforces.com/contest/1396/submission/91365784\nstruct Scanner {\n stdin: Stdin,\n buffer: VecDeque,\n}\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Self {\n Scanner {\n stdin: stdin(),\n buffer: VecDeque::new(),\n }\n }\n fn cin(&mut self) -> T {\n while self.buffer.is_empty() {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n self.buffer.pop_front().unwrap().parse::().ok().unwrap()\n }\n fn chars(&mut self) -> Vec {\n self.cin::().chars().collect()\n }\n fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.cin()).collect()\n }\n fn u(&mut self) -> usize {\n self.cin()\n }\n fn ll(&mut self) -> i64 {\n self.cin()\n }\n fn ull(&mut self) -> u64 {\n self.cin()\n }\n fn vecu(&mut self, n: usize) -> Vec {\n self.vec(n)\n }\n fn vecll(&mut self, n: usize) -> Vec {\n self.vec(n)\n }\n}\n\n#[derive(Clone, Debug, Default)]\nstruct Solver {}\n\n//\n// ModInt\n//\n\nconst M: i64 = 998244353;\n#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]\nstruct ModInt {\n val: i64,\n}\n#[allow(dead_code)]\nconst M0: ModInt = ModInt { val: 0 };\nconst M1: ModInt = ModInt { val: 1 };\n//const M_ERROR: ModInt = ModInt { val: -1 };\n\nimpl ModInt {\n fn new(v: i64) -> ModInt {\n ModInt {\n val: ModInt::val_from_i64(v),\n }\n }\n #[allow(dead_code)]\n fn new_raw(v: i64) -> ModInt {\n ModInt { val: v }\n }\n fn val_from_i64(v: i64) -> i64 {\n let t = v % M;\n if t < 0 {\n t + M\n } else {\n t\n }\n }\n fn val_from_addval(t: i64) -> i64 {\n if t >= M {\n t - M\n } else {\n t\n }\n }\n\n fn pow(self, exp: i64) -> ModInt {\n if exp == 0 {\n M1\n } else {\n let x = self.pow(exp / 2);\n if exp % 2 == 0 {\n x * x\n } else {\n self * x * x\n }\n }\n }\n\n fn inv(self) -> ModInt {\n self.pow(M - 2)\n }\n}\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> ModInt {\n ModInt {\n val: ModInt::val_from_addval(self.val + rhs.val),\n }\n }\n}\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: i64) -> ModInt {\n ModInt {\n val: ModInt::val_from_i64(self.val + rhs),\n }\n }\n}\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, other: ModInt) {\n self.val = ModInt::val_from_addval(self.val + other.val);\n }\n}\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, other: i64) {\n self.val = ModInt::val_from_i64(self.val + other);\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> ModInt {\n ModInt {\n val: ModInt::val_from_addval(self.val - rhs.val + M),\n }\n }\n}\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: i64) -> ModInt {\n self - ModInt::new(rhs)\n }\n}\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, other: ModInt) {\n self.val = ModInt::val_from_addval(self.val - other.val + M);\n }\n}\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, other: i64) {\n self.val = ModInt::val_from_i64(self.val - other);\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> ModInt {\n ModInt {\n val: if self.val == 0 { 0 } else { M - self.val },\n }\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> ModInt {\n ModInt {\n val: self.val * rhs.val % M,\n }\n }\n}\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: i64) -> ModInt {\n self * ModInt::new(rhs)\n }\n}\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, other: ModInt) {\n self.val = self.val * other.val % M;\n }\n}\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, other: i64) {\n self.mul_assign(ModInt::new(other));\n }\n}\n\nimpl std::ops::Div for ModInt {\n type Output = ModInt;\n fn div(self, rhs: ModInt) -> ModInt {\n self * rhs.inv()\n }\n}\nimpl std::ops::Div for ModInt {\n type Output = ModInt;\n fn div(self, rhs: i64) -> ModInt {\n self / ModInt::new(rhs)\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n // '\n write!(f, \"{}\", self.val)\n }\n}\n\nimpl Solver {\n fn solve(&mut self, scan: &mut Scanner, out: &mut BufWriter) {\n // 1452d\n let n = scan.u();\n let mut dp = vec![M0;n+2]; // dp[i] : \u90fd\u5e02i \u307e\u3067\u304c\u5236\u7d04\u3092\u6e80\u305f\u3059\n let mut dpsum = vec![M0;n+2]; // = dp[i] + dp[i-2] + dp[i-4] + ...\n\n dp[0] = M1;\n dpsum[0] = dp[0];\n\n let mut div = M1;\n for i in 1..=n {\n // dp[i] = dp[i-1] + dp[i-3] + dp[i-5] + ... \n dp[i] = dp[i-1] + if i >= 3 {dpsum[i-3]} else {M0};\n dpsum[i] = dp[i] + if i >= 2 { dpsum[i-2] } else {M0};\n div *= 2;\n }\n //writeln!(out, \"{} {} \", dp[n] , div).ok();\n\n writeln!(out, \"{}\", dp[n] / div).ok();\n }\n}\n\nfn solve() {\n let mut scan = Scanner::new();\n let out = &mut BufWriter::new(stdout());\n\n let testcase = 1;\n //let testcase: usize = scan.cin();\n for _ in 0..testcase {\n let mut s: Solver = Default::default();\n s.solve(&mut scan, out);\n }\n}\n\nfn main() {\n let th = std::thread::Builder::new().stack_size(64 * 1024 * 1024);\n th.spawn(|| solve()).unwrap().join().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "5e22bdef2a82394e9d97591a27c722c3", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn combination(n: u64, k: u64, m: u64) -> u64 {\n if n == 0 {\n return 1;\n }\n if k == 0 || k == n {\n return 1;\n }\n let new_k = if n - k < k { n - k } else { k };\n let mut res = 1;\n for i in ((n - new_k) + 1)..=n {\n res *= i;\n res %= m;\n }\n let mut den = 1;\n for i in 1..=(new_k) {\n den *= i;\n den %= m;\n }\n let (_one, inverse, _c) = egcd(den as i64, m as i64);\n let inverse = if inverse < 0 {\n m as i64 + inverse\n } else {\n inverse\n } as u64;\n //println!(\"inv: {} {}\", den, inverse);\n res *= inverse;\n res %= m;\n res\n}\n\nuse std::collections::HashSet;\nuse std::iter::FromIterator;\n\nfn main() -> Result<(), Box> {\n let modulo = 998244353;\n let n = read_usize();\n let mut num = 1;\n let mut denom = 4;\n let mut a = 1;\n let mut b = 1;\n for _ in 3..=n {\n let tmp = a + b;\n a = b;\n b = tmp % modulo;\n num = b;\n denom *= 2;\n denom %= modulo;\n }\n if n == 1 {\n denom = 2;\n }\n let (_g, mut denom_inv, _y) = egcd(denom, modulo);\n if denom_inv < 0 {\n denom_inv += modulo;\n }\n println!(\"{}\", (num * denom_inv) % modulo);\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "683d5e9ebf87b71b5a4485f9a72ef0f7", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// codesnip-guard: minmax\n#[macro_export]\nmacro_rules ! min { ($ e : expr) => { $ e } ; ($ e : expr , $ ($ es : expr) ,+) => { std :: cmp :: min ($ e , min ! ($ ($ es) ,+)) } ; }\n#[macro_export]\nmacro_rules ! chmin { ($ dst : expr , $ ($ src : expr) ,+) => { { let x = std :: cmp :: min ($ dst , min ! ($ ($ src) ,+)) ; $ dst = x ; } } ; }\n#[macro_export]\nmacro_rules ! max { ($ e : expr) => { $ e } ; ($ e : expr , $ ($ es : expr) ,+) => { std :: cmp :: max ($ e , max ! ($ ($ es) ,+)) } ; }\n#[macro_export]\nmacro_rules ! chmax { ($ dst : expr , $ ($ src : expr) ,+) => { { let x = std :: cmp :: max ($ dst , max ! ($ ($ src) ,+)) ; $ dst = x ; } } ; }\n// codesnip-guard: scanner\npub trait IterScan: Sized {\n type Output;\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option;\n}\npub trait MarkedIterScan: Sized {\n type Output;\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option;\n}\n#[derive(Clone, Debug)]\npub struct Scanner<'a> {\n iter: std::str::SplitAsciiWhitespace<'a>,\n}\nmod scanner_impls {\n use super::*;\n impl<'a> Scanner<'a> {\n #[inline]\n pub fn new(s: &'a str) -> Self {\n let iter = s.split_ascii_whitespace();\n Self { iter }\n }\n #[inline]\n pub fn scan(&mut self) -> ::Output {\n ::scan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn mscan(&mut self, marker: T) -> ::Output {\n marker.mscan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn scan_vec(&mut self, size: usize) -> Vec<::Output> {\n (0..size)\n .map(|_| ::scan(&mut self.iter).expect(\"scan error\"))\n .collect()\n }\n #[inline]\n pub fn iter<'b, T: IterScan>(&'b mut self) -> ScannerIter<'a, 'b, T> {\n ScannerIter {\n inner: self,\n _marker: std::marker::PhantomData,\n }\n }\n }\n macro_rules ! iter_scan_impls { ($ ($ t : ty) *) => { $ (impl IterScan for $ t { type Output = Self ; # [inline] fn scan <'a , I : Iterator < Item = &'a str >> (iter : & mut I) -> Option < Self > { iter . next () ?. parse ::<$ t > () . ok () } }) * } ; }\n iter_scan_impls ! (char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);\n macro_rules ! iter_scan_tuple_impl { ($ ($ T : ident) *) => { impl <$ ($ T : IterScan) ,*> IterScan for ($ ($ T ,) *) { type Output = ($ (<$ T as IterScan >:: Output ,) *) ; # [inline] fn scan <'a , It : Iterator < Item = &'a str >> (_iter : & mut It) -> Option < Self :: Output > { Some (($ (<$ T as IterScan >:: scan (_iter) ?,) *)) } } } ; }\n iter_scan_tuple_impl!();\n iter_scan_tuple_impl!(A);\n iter_scan_tuple_impl ! (A B);\n iter_scan_tuple_impl ! (A B C);\n iter_scan_tuple_impl ! (A B C D);\n iter_scan_tuple_impl ! (A B C D E);\n iter_scan_tuple_impl ! (A B C D E F);\n iter_scan_tuple_impl ! (A B C D E F G);\n iter_scan_tuple_impl ! (A B C D E F G H);\n iter_scan_tuple_impl ! (A B C D E F G H I);\n iter_scan_tuple_impl ! (A B C D E F G H I J);\n iter_scan_tuple_impl ! (A B C D E F G H I J K);\n pub struct ScannerIter<'a, 'b, T> {\n inner: &'b mut Scanner<'a>,\n _marker: std::marker::PhantomData T>,\n }\n impl<'a, 'b, T: IterScan> Iterator for ScannerIter<'a, 'b, T> {\n type Item = ::Output;\n #[inline]\n fn next(&mut self) -> Option {\n ::scan(&mut self.inner.iter)\n }\n }\n}\npub mod marker {\n use super::*;\n use std::{iter::FromIterator, marker::PhantomData};\n #[derive(Debug, Copy, Clone)]\n pub struct Usize1;\n impl IterScan for Usize1 {\n type Output = usize;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(::scan(iter)?.checked_sub(1)?)\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct Chars;\n impl IterScan for Chars {\n type Output = Vec;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(iter.next()?.chars().collect())\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct CharsWithBase(pub char);\n impl MarkedIterScan for CharsWithBase {\n type Output = Vec;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n iter.next()?\n .chars()\n .map(|c| (c as u8 - self.0 as u8) as usize)\n .collect(),\n )\n }\n }\n #[derive(Debug, Copy, Clone)]\n pub struct Collect::Output>> {\n size: usize,\n _marker: PhantomData (T, B)>,\n }\n impl::Output>> Collect {\n pub fn new(size: usize) -> Self {\n Self {\n size,\n _marker: PhantomData,\n }\n }\n }\n impl::Output>> MarkedIterScan for Collect {\n type Output = B;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n (0..self.size)\n .map(|_| ::scan(iter).expect(\"scan error\"))\n .collect::(),\n )\n }\n }\n}\n// codesnip-guard: zero_one\npub trait Zero: PartialEq + Sized {\n fn zero() -> Self;\n #[inline]\n fn is_zero(&self) -> bool {\n self == &Self::zero()\n }\n}\npub trait One: PartialEq + Sized {\n fn one() -> Self;\n #[inline]\n fn is_one(&self) -> bool {\n self == &Self::one()\n }\n}\nmacro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { # [inline] fn $ method () -> Self { $ e } }) *) * } ; }\nzero_one_impls ! ({ Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 0 } { Zero zero f32 f64 , 0. } { One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 1 } { One one f32 f64 , 1. });\n// codesnip-guard: main\nfn main() {\n #![allow(unused_imports, unused_macros)]\n use std::io::{stdin, stdout, BufWriter, Read as _, Write as _};\n let mut _in_buf = Vec::new();\n stdin().read_to_end(&mut _in_buf).expect(\"io error\");\n let _in_buf = unsafe { String::from_utf8_unchecked(_in_buf) };\n let mut scanner = Scanner::new(&_in_buf);\n macro_rules ! scan { () => { scan ! (usize) } ; (($ ($ t : tt) ,*)) => { ($ (scan ! ($ t)) ,*) } ; ([$ t : tt ; $ len : expr]) => { (0 ..$ len) . map (| _ | scan ! ($ t)) . collect ::< Vec < _ >> () } ; ([$ t : ty ; $ len : expr]) => { scanner . scan_vec ::<$ t > ($ len) } ; ([$ t : ty]) => { scanner . iter ::<$ t > () } ; ({ $ e : expr }) => { scanner . mscan ($ e) } ; ($ t : ty) => { scanner . scan ::<$ t > () } ; }\n let _out = stdout();\n let mut _out = BufWriter::new(_out.lock());\n macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules! echo {\n ($ iter : expr) => {\n echo!($iter, '\\n')\n };\n ($ iter : expr , $ sep : expr) => {\n let mut iter = $iter.into_iter();\n if let Some(item) = iter.next() {\n print!(\"{}\", item);\n }\n for item in iter {\n print!(\"{}{}\", $sep, item);\n }\n println!();\n };\n }\n let n = scan!();\n let mut dp = vec![M::zero(); n + 1];\n let mut acc1 = vec![M::zero(); n + 1];\n let mut acc2 = vec![M::zero(); n + 1];\n dp[0] = M::one();\n acc1[0] = M::one();\n for i in 0..n {\n dp[i + 1] = if i % 2 == 0 { acc1[i] } else { acc2[i] };\n acc1[i + 1] = acc1[i];\n acc2[i + 1] = acc2[i];\n if i % 2 == 0 {\n acc2[i + 1] += dp[i + 1];\n } else {\n acc1[i + 1] += dp[i + 1];\n }\n }\n println!(\"{}\", dp[n] / M::new(2).pow(n));\n}\ntype M = montgomery::MInt998244353;\n// codesnip-guard: MIntBase\n#[repr(transparent)]\npub struct MInt\nwhere\n M: MIntBase,\n{\n x: M::Inner,\n _marker: std::marker::PhantomData M>,\n}\npub trait MIntBase {\n type Inner: Sized + Copy + Eq + std::fmt::Debug + std::hash::Hash;\n fn get_mod() -> Self::Inner;\n fn mod_zero() -> Self::Inner;\n fn mod_one() -> Self::Inner;\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_neg(x: Self::Inner) -> Self::Inner;\n fn mod_inv(x: Self::Inner) -> Self::Inner;\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n let (mut x, mut y, mut z) = (x, y, Self::mod_one());\n while y > 0 {\n if y & 1 == 1 {\n z = Self::mod_mul(z, x);\n }\n x = Self::mod_mul(x, x);\n y >>= 1;\n }\n z\n }\n}\npub trait MIntConvert::Inner>: MIntBase {\n fn from(x: T) -> ::Inner;\n fn into(x: ::Inner) -> T;\n fn mod_into() -> T;\n}\nmod mint_base {\n use super::*;\n use std::{\n fmt::{self, Debug, Display},\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n };\n impl MInt\n where\n M: MIntConvert,\n {\n #[inline]\n pub fn new(x: M::Inner) -> Self {\n Self::new_unchecked(>::from(x))\n }\n #[inline]\n pub fn inner(self) -> M::Inner {\n >::into(self.x)\n }\n }\n impl MInt\n where\n M: MIntBase,\n {\n #[inline]\n pub fn new_unchecked(x: M::Inner) -> Self {\n Self {\n x,\n _marker: PhantomData,\n }\n }\n #[inline]\n pub fn get_mod() -> M::Inner {\n M::get_mod()\n }\n #[inline]\n pub fn pow(self, y: usize) -> Self {\n Self::new_unchecked(M::mod_pow(self.x, y))\n }\n #[inline]\n pub fn inv(self) -> Self {\n Self::new_unchecked(M::mod_inv(self.x))\n }\n }\n impl Clone for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn clone(&self) -> Self {\n Self {\n x: Clone::clone(&self.x),\n _marker: PhantomData,\n }\n }\n }\n impl Copy for MInt where M: MIntBase {}\n impl Debug for MInt\n where\n M: MIntBase,\n {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Debug::fmt(&self.x, f)\n }\n }\n impl Default for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn default() -> Self {\n ::zero()\n }\n }\n impl PartialEq for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n PartialEq::eq(&self.x, &other.x)\n }\n }\n impl Eq for MInt where M: MIntBase {}\n impl Hash for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn hash(&self, state: &mut H) {\n Hash::hash(&self.x, state)\n }\n }\n macro_rules ! impl_mint_from { ($ ($ t : ty) ,*) => { $ (impl < M > From <$ t > for MInt < M > where M : MIntConvert <$ t >, { # [inline] fn from (x : $ t) -> Self { Self :: new_unchecked (< M as MIntConvert <$ t >>:: from (x)) } } impl < M > From < MInt < M >> for $ t where M : MIntConvert <$ t >, { # [inline] fn from (x : MInt < M >) -> $ t { < M as MIntConvert <$ t >>:: into (x . x) } }) * } ; }\n impl_mint_from!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n impl Zero for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn zero() -> Self {\n Self::new_unchecked(M::mod_zero())\n }\n }\n impl One for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn one() -> Self {\n Self::new_unchecked(M::mod_one())\n }\n }\n impl Add for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_add(self.x, rhs.x))\n }\n }\n impl Sub for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_sub(self.x, rhs.x))\n }\n }\n impl Mul for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_mul(self.x, rhs.x))\n }\n }\n impl Div for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_div(self.x, rhs.x))\n }\n }\n impl Neg for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn neg(self) -> Self::Output {\n Self::new_unchecked(M::mod_neg(self.x))\n }\n }\n impl Sum for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl Product for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl<'a, M: 'a> Sum<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl<'a, M: 'a> Product<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl Display for MInt\n where\n M: MIntConvert,\n M::Inner: Display,\n {\n fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {\n write!(f, \"{}\", self.inner())\n }\n }\n impl FromStr for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Err = ::Err;\n #[inline]\n fn from_str(s: &str) -> Result {\n s.parse::().map(Self::new)\n }\n }\n impl IterScan for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Output = Self;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n iter.next()?.parse::>().ok()\n }\n }\n macro_rules! impl_mint_ref_binop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp<$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: $t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, other)\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(self, *other)\n }\n }\n impl $imp<&$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, *other)\n }\n }\n };\n }\n impl_mint_ref_binop!(Add, add, MInt);\n impl_mint_ref_binop!(Sub, sub, MInt);\n impl_mint_ref_binop!(Mul, mul, MInt);\n impl_mint_ref_binop!(Div, div, MInt);\n macro_rules! impl_mint_ref_unop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp>::Output;\n #[inline]\n fn $method(self) -> <$t as $imp>::Output {\n $imp::$method(*self)\n }\n }\n };\n }\n impl_mint_ref_unop!(Neg, neg, MInt);\n macro_rules! impl_mint_ref_op_assign {\n ($ imp : ident , $ method : ident , $ t : ty , $ fromimp : ident , $ frommethod : ident) => {\n impl $imp<$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, rhs: $t) {\n *self = $fromimp::$frommethod(*self, rhs);\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, other: &$t) {\n $imp::$method(self, *other);\n }\n }\n };\n }\n impl_mint_ref_op_assign!(AddAssign, add_assign, MInt, Add, add);\n impl_mint_ref_op_assign!(SubAssign, sub_assign, MInt, Sub, sub);\n impl_mint_ref_op_assign!(MulAssign, mul_assign, MInt, Mul, mul);\n impl_mint_ref_op_assign!(DivAssign, div_assign, MInt, Div, div);\n}\n// codesnip-guard: MInt\npub mod mint_basic {\n use super::*;\n #[macro_export]\n macro_rules ! define_basic_mintbase { ($ name : ident , $ m : expr , $ basety : ty , $ upperty : ty , [$ ($ unsigned : ty) ,*] , [$ ($ signed : ty) ,*]) => { pub struct $ name ; impl MIntBase for $ name { type Inner = $ basety ; # [inline] fn get_mod () -> Self :: Inner { $ m } # [inline] fn mod_zero () -> Self :: Inner { 0 } # [inline] fn mod_one () -> Self :: Inner { 1 } # [inline] fn mod_add (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { let z = x + y ; let m = Self :: get_mod () ; if z >= m { z - m } else { z } } # [inline] fn mod_sub (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { if x < y { x + Self :: get_mod () - y } else { x - y } } # [inline] fn mod_mul (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { (x as $ upperty * y as $ upperty % Self :: get_mod () as $ upperty) as $ basety } # [inline] fn mod_div (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { Self :: mod_mul (x , Self :: mod_inv (y)) } # [inline] fn mod_neg (x : Self :: Inner) -> Self :: Inner { if x == 0 { 0 } else { Self :: get_mod () - x } } fn mod_inv (x : Self :: Inner) -> Self :: Inner { let mut a = x ; let (mut b , mut u , mut s) = (Self :: get_mod () , 1 , 0) ; let k = a . trailing_zeros () ; a >>= k ; for _ in 0 .. k { if u & 1 == 1 { u += Self :: get_mod () ; } u /= 2 ; } while a != b { if b < a { std :: mem :: swap (& mut a , & mut b) ; std :: mem :: swap (& mut u , & mut s) ; } b -= a ; if s < u { s += Self :: get_mod () ; } s -= u ; let k = b . trailing_zeros () ; b >>= k ; for _ in 0 .. k { if s & 1 == 1 { s += Self :: get_mod () ; } s /= 2 ; } } s } } $ (impl MIntConvert <$ unsigned > for $ name { # [inline] fn from (x : $ unsigned) -> Self :: Inner { (x % < Self as MIntBase >:: get_mod () as $ unsigned) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ unsigned { x as $ unsigned } # [inline] fn mod_into () -> $ unsigned { < Self as MIntBase >:: get_mod () as $ unsigned } }) * $ (impl MIntConvert <$ signed > for $ name { # [inline] fn from (x : $ signed) -> Self :: Inner { let x = x % < Self as MIntBase >:: get_mod () as $ signed ; if x < 0 { (x + < Self as MIntBase >:: get_mod () as $ signed) as $ basety } else { x as $ basety } } # [inline] fn into (x : Self :: Inner) -> $ signed { x as $ signed } # [inline] fn mod_into () -> $ signed { < Self as MIntBase >:: get_mod () as $ signed } }) * } ; }\n #[macro_export]\n macro_rules ! define_basic_mint32 { ($ ([$ name : ident , $ m : expr , $ mint_name : ident]) ,*) => { $ (crate :: define_basic_mintbase ! ($ name , $ m , u32 , u64 , [u32 , u64 , u128 , usize] , [i32 , i64 , i128 , isize]) ; pub type $ mint_name = MInt <$ name >;) * } ; }\n define_basic_mint32!(\n [Modulo998244353, 998_244_353, MInt998244353],\n [Modulo1000000007, 1_000_000_007, MInt1000000007],\n [Modulo1000000009, 1_000_000_009, MInt1000000009],\n [DynModuloU32, unsafe { DYN_MODULUS_U32 }, DynMIntU32]\n );\n static mut DYN_MODULUS_U32: u32 = 1_000_000_007;\n impl DynModuloU32 {\n pub fn set_mod(m: u32) {\n unsafe {\n DYN_MODULUS_U32 = m;\n }\n }\n }\n static mut DYN_MODULUS_U64: u64 = 1_000_000_007;\n define_basic_mintbase!(\n DynModuloU64,\n unsafe { DYN_MODULUS_U64 },\n u64,\n u128,\n [u64, u128, usize],\n [i64, i128, isize]\n );\n impl DynModuloU64 {\n pub fn set_mod(m: u64) {\n unsafe {\n DYN_MODULUS_U64 = m;\n }\n }\n }\n pub type DynMIntU64 = MInt;\n pub struct Modulo2;\n impl MIntBase for Modulo2 {\n type Inner = u32;\n #[inline]\n fn get_mod() -> Self::Inner {\n 2\n }\n #[inline]\n fn mod_zero() -> Self::Inner {\n 0\n }\n #[inline]\n fn mod_one() -> Self::Inner {\n 1\n }\n #[inline]\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x | y\n }\n #[inline]\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n assert_ne!(y, 0);\n x\n }\n #[inline]\n fn mod_neg(x: Self::Inner) -> Self::Inner {\n x\n }\n #[inline]\n fn mod_inv(x: Self::Inner) -> Self::Inner {\n assert_ne!(x, 0);\n x\n }\n #[inline]\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n if y == 0 {\n 1\n } else {\n x\n }\n }\n }\n macro_rules ! impl_to_mint_base_for_modulo2 { ($ name : ident , $ basety : ty , [$ ($ t : ty) ,*]) => { $ (impl MIntConvert <$ t > for $ name { # [inline] fn from (x : $ t) -> Self :: Inner { (x & 1) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ t { x as $ t } # [inline] fn mod_into () -> $ t { 1 } }) * } ; }\n impl_to_mint_base_for_modulo2!(\n Modulo2,\n u32,\n [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]\n );\n pub type MInt2 = MInt;\n}\n// codesnip-guard: montgomery\npub mod montgomery {\n use super::*;\n pub struct Modulo998244353;\n pub type MInt998244353 = MInt;\n impl MIntBase for M\n where\n M: MontgomeryReduction32,\n {\n type Inner = u32;\n #[inline]\n fn get_mod() -> Self::Inner {\n ::get_mod()\n }\n #[inline]\n fn mod_zero() -> Self::Inner {\n 0\n }\n #[inline]\n fn mod_one() -> Self::Inner {\n Self::n1()\n }\n #[inline]\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n let z = x + y;\n let m = Self::get_mod();\n if z >= m {\n z - m\n } else {\n z\n }\n }\n #[inline]\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n if x < y {\n x + Self::get_mod() - y\n } else {\n x - y\n }\n }\n #[inline]\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n Self::reduce(x as u64 * y as u64)\n }\n #[inline]\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n Self::mod_mul(x, Self::mod_inv(y))\n }\n #[inline]\n fn mod_neg(x: Self::Inner) -> Self::Inner {\n if x == 0 {\n 0\n } else {\n Self::get_mod() - x\n }\n }\n fn mod_inv(x: Self::Inner) -> Self::Inner {\n let mut a = x;\n let m = Self::get_mod();\n let (mut b, mut u, mut s) = (m, 1, 0);\n let k = a.trailing_zeros();\n a >>= k;\n for _ in 0..k {\n if u & 1 == 1 {\n u += m;\n }\n u /= 2;\n }\n while a != b {\n if b < a {\n std::mem::swap(&mut a, &mut b);\n std::mem::swap(&mut u, &mut s);\n }\n b -= a;\n if s < u {\n s += m;\n }\n s -= u;\n let k = b.trailing_zeros();\n b >>= k;\n for _ in 0..k {\n if s & 1 == 1 {\n s += m;\n }\n s /= 2;\n }\n }\n Self::reduce(s as u64 * Self::n3() as u64)\n }\n }\n impl MIntConvert for M\n where\n M: MontgomeryReduction32,\n {\n #[inline]\n fn from(x: u32) -> Self::Inner {\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> u32 {\n Self::reduce(x as u64) as u32\n }\n #[inline]\n fn mod_into() -> u32 {\n ::get_mod() as u32\n }\n }\n impl MIntConvert for M\n where\n M: MontgomeryReduction32,\n {\n #[inline]\n fn from(x: u64) -> Self::Inner {\n Self::reduce(x % Self::get_mod() as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> u64 {\n Self::reduce(x as u64) as u64\n }\n #[inline]\n fn mod_into() -> u64 {\n ::get_mod() as u64\n }\n }\n impl MIntConvert for M\n where\n M: MontgomeryReduction32,\n {\n #[inline]\n fn from(x: usize) -> Self::Inner {\n Self::reduce(x as u64 % Self::get_mod() as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> usize {\n Self::reduce(x as u64) as usize\n }\n #[inline]\n fn mod_into() -> usize {\n ::get_mod() as usize\n }\n }\n impl MIntConvert for Modulo998244353 {\n #[inline]\n fn from(x: i32) -> Self::Inner {\n let x = x % ::get_mod() as i32;\n let x = if x < 0 {\n (x + ::get_mod() as i32) as u64\n } else {\n x as u64\n };\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> i32 {\n Self::reduce(x as u64) as i32\n }\n #[inline]\n fn mod_into() -> i32 {\n ::get_mod() as i32\n }\n }\n impl MIntConvert for Modulo998244353 {\n #[inline]\n fn from(x: i64) -> Self::Inner {\n let x = x % ::get_mod() as i64;\n let x = if x < 0 {\n (x + ::get_mod() as i64) as u64\n } else {\n x as u64\n };\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> i64 {\n Self::reduce(x as u64) as i64\n }\n #[inline]\n fn mod_into() -> i64 {\n ::get_mod() as i64\n }\n }\n impl MIntConvert for Modulo998244353 {\n #[inline]\n fn from(x: isize) -> Self::Inner {\n let x = x % ::get_mod() as isize;\n let x = if x < 0 {\n (x + ::get_mod() as isize) as u64\n } else {\n x as u64\n };\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> isize {\n Self::reduce(x as u64) as isize\n }\n #[inline]\n fn mod_into() -> isize {\n ::get_mod() as isize\n }\n }\n /// m is prime, n = 2^32\n pub trait MontgomeryReduction32 {\n /// m\n fn get_mod() -> u32;\n /// (-m)^{-1} mod n\n fn r() -> u32 {\n let m = Self::get_mod();\n let mut r = 0;\n let mut t = 0;\n for i in 0..32 {\n if t % 2 == 0 {\n t += m;\n r += 1 << i;\n }\n t /= 2;\n }\n r\n }\n /// n^1 mod m\n fn n1() -> u32;\n /// n^2 mod m\n fn n2() -> u32;\n /// n^3 mod m\n fn n3() -> u32;\n /// n^{-1}x = (x + (xr mod n)m) / n\n fn reduce(x: u64) -> u32 {\n let m: u32 = Self::get_mod();\n let r = Self::r();\n let mut x = ((x + r.wrapping_mul(x as u32) as u64 * m as u64) >> 32) as u32;\n if x >= m {\n x -= m;\n }\n x\n }\n }\n macro_rules! impl_montgomery_reduction_32 {\n ($ name : ident , $ m : expr , $ r : expr , $ n1 : expr , $ n2 : expr , $ n3 : expr) => {\n impl MontgomeryReduction32 for $name {\n #[inline]\n fn get_mod() -> u32 {\n $m\n }\n #[inline]\n fn r() -> u32 {\n $r\n }\n #[inline]\n fn n1() -> u32 {\n $n1\n }\n #[inline]\n fn n2() -> u32 {\n $n2\n }\n #[inline]\n fn n3() -> u32 {\n $n3\n }\n }\n };\n }\n impl_montgomery_reduction_32!(\n Modulo998244353,\n 998_244_353,\n 998_244_351,\n 301_989_884,\n 932_051_910,\n 679_058_953\n );\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "2f12ce84f0f573b277fa616699bdf893", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nuse std::collections::HashMap;\n\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\nconst MOD: u64 = 998244353;\n\nstruct Fibo {\n memo: HashMap,\n}\n\nimpl Fibo {\n fn new() -> Self {\n let mut memo = HashMap::new();\n memo.insert(0, 1);\n memo.insert(1, 1);\n Self { memo }\n }\n\n fn get(&mut self, index: u64) -> u64 {\n if let Some(value) = self.memo.get(&index) {\n return *value;\n } else {\n let a = index / 2;\n let b = index - a;\n let result = (self.get(a) * self.get(b) + self.get(a - 1) * self.get(b - 1)) % MOD;\n self.memo.insert(index, result);\n result\n }\n }\n}\n\nfn modpow(mut value: u64, mut exp: u64) -> u64 {\n let mut res = 1;\n\n while exp > 0 {\n if exp & 1 == 1 {\n res = value * res % MOD;\n }\n value = value * value % MOD;\n exp >>= 1;\n }\n\n res\n}\n\nfn run() {\n input! {\n n: u64,\n }\n\n let result = Fibo::new().get(n - 1) * modpow(modpow(2, n), MOD - 2) % MOD;\n println!(\"{:?}\", result);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "7306f43eec2e98b412e4210e2aea5552", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scanner {\n buffer : std::collections::VecDeque\n }\n\n impl Scanner {\n\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn next(&mut self) -> T {\n if self.buffer.len() == 0 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n for word in input.split_whitespace() {\n self.buffer.push_back(word.to_string())\n }\n }\n let front = self.buffer.pop_front().unwrap();\n front.parse::().ok().unwrap()\n }\n\n}\n\nfn main() {\n let mut scanner = Scanner::new();\n let n : usize = scanner.next();\n let mut r: Vec = Vec::new();\n let (mut r_win, mut b_win) = (0, 0);\n for _ in 0..n {\n let num : i32 = scanner.next();\n r.push(num);\n }\n for i in 0..n {\n let num : i32 = scanner.next();\n if num > r[i] {\n b_win += 1;\n } else if num < r[i] {\n r_win += 1;\n }\n }\n if r_win == 0 {\n println!(\"-1\");\n } else {\n println!(\"{}\", b_win / r_win + 1);\n }\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "64304ea901b0f6b3cdb49b43f8b2724c", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let (mut cnt1, mut cnt2);\n\n cnt1 = 0;\n cnt2 = 0;\n\n let mut s = String::new();\n io::stdin().read_line(&mut s).expect(\"Failed to read line\");\n\n let n: usize = s.trim().parse().unwrap();\n\n s = String::new();\n io::stdin().read_line(&mut s).expect(\"Failed to read line\");\n let a = s\n .split_whitespace()\n .map(|x| x.parse::())\n .collect::, _>>()\n .unwrap();\n\n s = String::new();\n io::stdin().read_line(&mut s).expect(\"Failed to read line\");\n let b = s\n .split_whitespace()\n .map(|x| x.parse::())\n .collect::, _>>()\n .unwrap();\n \n for i in 0usize..n {\n if a[i] == 1 && b[i] == 0 {\n cnt1 = cnt1 + 1;\n } else if a[i] == 0 && b[i] == 1 {\n cnt2 = cnt2 + 1;\n }\n }\n\n if cnt1 == 0 {\n println!(\"-1\");\n } else {\n println!(\"{}\", cnt2 / cnt1 + 1);\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "a007d0fd8bd7cacaa53fabc184492149", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).unwrap();\n buffer\n}\n\nfn main() {\n let _n = get_input().trim().parse::().unwrap();\n let ra: Vec = get_input().trim().split(' ').map(|x| x.parse::().unwrap()).collect();\n let rb: Vec = get_input().trim().split(' ').map(|x| x.parse::().unwrap()).collect();\n let mut badv = 0;\n let mut rchn = 0;\n for (rv, bv) in ra.iter().zip(rb) {\n if *rv == 0 && bv == 1 {\n badv += 1;\n } else if *rv == 1 && bv == 0 {\n rchn += 1;\n }\n }\n\n if rchn == 0 {\n println!(\"{}\", -1);\n } else if badv == 0 {\n println!(\"{}\", 1);\n } else {\n let rwin = badv + 1;\n if rwin % rchn != 0 {\n println!(\"{}\", 1 + (rwin / rchn));\n } else {\n println!(\"{}\", rwin / rchn);\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "1a37111c0fa01595c4ca242170105495", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\n\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\nfn main() {\n let mut scan = Scanner::default();\n let responses = scan.next::();\n let mut robo_coder_s = String::new();\n stdin().read_line(&mut robo_coder_s).expect(\"Failed read\");\n let robo_coder = robo_coder_s.split_whitespace().collect::>();\n let mut bionic_solver_s = String::new();\n stdin()\n .read_line(&mut bionic_solver_s)\n .expect(\"Failed read\");\n let bionic_solver = bionic_solver_s.split_whitespace().collect::>();\n\n let mut only_robo_coder_wins = 0.0;\n let mut only_bionic_solver_wins = 0.0;\n for response in 0..responses {\n match (robo_coder[response], bionic_solver[response]) {\n (\"1\", \"0\") => only_robo_coder_wins += 1.0,\n (\"0\", \"1\") => only_bionic_solver_wins += 1.0,\n _ => (),\n }\n }\n let robo_code_minimum_points: f64 = if only_robo_coder_wins == 0.0 {\n -1.0\n } else {\n (only_bionic_solver_wins + 1.0) / only_robo_coder_wins\n };\n println!(\"{}\", robo_code_minimum_points.ceil() as i32);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "737d65d436b255774ee68517fa55867c", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[macro_export]\nmacro_rules ! chmax { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: max ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! chmin { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: min ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! max { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: max ( $ x , max ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! min { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: min ( $ x , min ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! dvec { ( $ t : expr ; $ len : expr ) => { vec ! [ $ t ; $ len ] } ; ( $ t : expr ; $ len : expr , $ ( $ rest : expr ) ,* ) => { vec ! [ dvec ! ( $ t ; $ ( $ rest ) ,* ) ; $ len ] } ; }\n#[macro_export]\nmacro_rules ! cfor { ( ; $ ( $ rest : tt ) * ) => { cfor ! ( ( ) ; $ ( $ rest ) * ) } ; ( $ ( $ init : stmt ) ,+; ; $ ( $ rest : tt ) * ) => { cfor ! ( $ ( $ init ) ,+; ! false ; $ ( $ rest ) * ) } ; ( $ ( $ init : stmt ) ,+; $ cond : expr ; ; $ body : block ) => { cfor ! { $ ( $ init ) ,+; $ cond ; ( ) ; $ body } } ; ( $ ( $ init : stmt ) ,+; $ cond : expr ; $ ( $ step : expr ) ,+; $ body : block ) => { { $ ( $ init ; ) + while $ cond { let mut _first = true ; let mut _continue = false ; loop { if ! _first { _continue = true ; break } _first = false ; $ body } if ! _continue { break } $ ( $ step ; ) + } } } ; }\n#[doc = \" main\"]\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\n#[macro_export]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\nuse std::io;\nuse std::io::BufRead;\nuse std::str;\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len, complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n if len == 0 {\n break;\n }\n (len, buf2[len - 1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n } else {\n self.update_buf();\n }\n }\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\nconst BIG_STACK_SIZE: bool = true;\n#[allow(dead_code)]\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\nfn solve() {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n input!{\n n:usize,\n a:[u8;n],\n b:[u8;n],\n }\n let mut acnt = 0;\n let mut btot = 0;\n for i in 0..n {\n if a[i] == b[i] {\n } else {\n if a[i] == 1 {\n acnt += 1;\n } else {\n btot += 1;\n }\n }\n }\n if acnt == 0 {\n writeln!(out,\"-1\");\n return\n }\n let ars = ArithSeq::new(0,acnt);\n let nxt = ars.next(btot+1);\n writeln!(out,\"{}\",nxt/acnt);\n}\nstruct ArithSeq {\n a: i64,\n b: i64,\n}\nimpl ArithSeq {\n pub fn new(a: i64, b: i64) -> ArithSeq {\n assert!(b > 0);\n ArithSeq { a: a, b: b }\n }\n #[doc = \"a+bi >= x\"]\n pub fn next(&self, x: i64) -> i64 {\n if x >= self.a {\n let d = x - self.a;\n let i = (d - 1 + self.b) / self.b;\n self.a + self.b * i\n } else {\n let d = self.a - x;\n let i = d / self.b;\n self.a - self.b * i\n }\n }\n #[doc = \"a+bi <= x\"]\n pub fn prev(&self, x: i64) -> i64 {\n let next = self.next(x);\n if next == x {\n x\n } else {\n next - self.b\n }\n }\n #[doc = \"[a+bi, n] <= [l, u]\"]\n pub fn range(&self, l: i64, u: i64) -> Option<(i64, i64)> {\n if l > u {\n return None;\n }\n let x = self.next(l);\n let y = self.prev(u);\n if x > y {\n return None;\n }\n assert!(x <= y);\n if l <= x && x <= u {\n let cnt = (y - x) / self.b;\n Some((x, cnt + 1))\n } else {\n None\n }\n }\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "7340e8fdfca48a9b7a5449de5e3eda8e", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let n = scan.next::();\n let mut a = Vec::with_capacity(n);\n for _ in 0..n {\n a.push(scan.next::());\n }\n let mut b = Vec::with_capacity(n);\n for _ in 0..n {\n b.push(scan.next::());\n }\n let mut num_a = 0;\n let mut num_b = 0;\n for i in 0..n {\n if b[i] == 0 && a[i] == 1 {\n num_a += 1;\n } else if b[i] == 1 && a[i] == 0 {\n num_b += 1;\n }\n }\n let mut ans;\n if num_a == 0 {\n ans = -1;\n } else {\n ans = 1;\n while num_a * ans <= num_b {\n ans += 1;\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "6d634c17b041cc2b9dbf50e3b8e0ab03", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n let _ = lines.next().unwrap().unwrap().parse::().unwrap();\n let a: Vec = lines.next().unwrap().unwrap().split(\" \").map(|s| s.parse::().unwrap()).collect();\n let b: Vec = lines.next().unwrap().unwrap().split(\" \").map(|s| s.parse::().unwrap()).collect();\n println!(\"{}\", solve(a, b).unwrap_or(-1));\n}\n\npub fn solve( a: Vec, b: Vec) -> Option {\n let b_score = a.iter().zip(b.iter()).fold(0, |mut acc, (x,y)| {\n if x < y {\n acc += 1;\n }\n acc\n });\n let outperform = a.iter().zip(b.iter()).fold(0, |mut acc, (x,y)| {\n if x > y {\n acc += 1;\n }\n acc\n });\n match outperform {\n 0 => None,\n r => Some(b_score / outperform + 1),\n }\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "dcde3cf3b47e41ab9280447d40b7ff92", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let data = read_input();\n let (n, a, b, c) = (data[0], data[1], data[2], data[3]);\n\n let mut max_count = 0;\n\n let d = n / a;\n for i in 0..=d {\n let rem = n - a * i;\n let d = rem / b;\n for j in 0..=d {\n let rem = n - a * i - b * j;\n let d = rem / c;\n let x = a * i + b * j + c * d;\n let count = i + j + d;\n if x == n && count > max_count {\n max_count = count;\n }\n }\n }\n\n println!(\"{}\", max_count);\n}\nfn read_input() -> Vec {\n let mut buffer = String::new();\n\n std::io::stdin()\n .read_line(&mut buffer)\n .expect(\"Failed to get input\");\n\n buffer\n .trim()\n .split_whitespace()\n .map(|x| x.parse().expect(\"Failed to parse number\"))\n .collect()\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "a3dc397598d789b8848ad8c715e4b1e6", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, stdout, BufRead, Write};\n\nfn get_max_division_size(n: u16, a: u16, b: u16, c: u16) -> u16 {\n let mut max_division_size: u16 = 0;\n\n for num_a in 0..(n / a + 1) {\n let size_left1: u16 = n - num_a * a;\n for num_b in 0..(size_left1 / b + 1) {\n let size_left2: u16 = size_left1 - num_b * b;\n if (size_left2 % c) == 0 {\n let num_c: u16 = size_left2 / c;\n let division_size = num_a + num_b + num_c;\n if division_size > max_division_size {\n max_division_size = division_size;\n }\n }\n }\n }\n\n return max_division_size;\n}\n\n#[cfg(test)]\nmod tests {\n use super::get_max_division_size;\n\n #[test]\n fn test1() {\n assert_eq!(get_max_division_size(5, 5, 3, 2), 2);\n }\n\n #[test]\n fn test2() {\n assert_eq!(get_max_division_size(7, 5, 5, 2), 2);\n }\n\n #[test]\n fn test3() {\n assert_eq!(get_max_division_size(10, 1, 1, 1), 10);\n }\n}\n\nfn main() {\n let stdin = stdin();\n let mut stdin_lock = stdin.lock();\n let stdout = stdout();\n let mut stdout_lock = stdout.lock();\n\n let mut parameters_string: String = String::new();\n stdin_lock.read_line(&mut parameters_string).unwrap();\n let parameters_vec: Vec = parameters_string\n .trim()\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n let n: u16 = parameters_vec[0];\n let a: u16 = parameters_vec[1];\n let b: u16 = parameters_vec[2];\n let c: u16 = parameters_vec[3];\n let result: u16 = get_max_division_size(n, a, b, c);\n\n writeln!(stdout_lock, \"{}\", result).unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "304fd290db5a8e58db56947757745651", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io::*;\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let params: Vec = reads(sin);\n\n let n = params[0];\n let a = params[1];\n let b = params[2];\n let c = params[3];\n\n let lengths: Vec = vec![a, b, c];\n\n let min = *(lengths.iter().min().unwrap());\n if n % min == 0 {\n println!(\"{}\", n / min);\n return;\n }\n\n let mut memo = HashMap::new();\n memo.insert(0, 0);\n\n (min..n + 1).for_each(|x| {\n let mut tmp: Vec = Vec::new();\n for length in &lengths {\n if let Some(val) = memo.get(&(x - length)) {\n tmp.push(val + 1);\n }\n }\n if tmp.len() == 0 {\n return;\n }\n\n let max_ribons: i64 = tmp.into_iter().max().unwrap();\n\n memo.insert(x, max_ribons);\n });\n\n println!(\"{}\", memo.entry(n).or_insert(0));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "98a39a00dd21155a25612dd38a2c30db", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/189/A\nuse std::io;\n\nfn main() {\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let words: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let n = words[0];\n let a = words[1];\n let b = words[2];\n let c = words[3];\n\n let mut maxima = -1;\n for i in 0..4001 {\n for j in 0..4001 {\n let m = n - a*i - b*j;\n if m >= 0 && m%c == 0 {\n maxima = std::cmp::max(maxima, i+j+m/c);\n }\n }\n }\n\n println!(\"{}\", maxima);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "a3a971f68ebe6aee2d5a8d9867cb5096", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 2018-10-11 17:24\nuse std::collections::HashMap;\nfn main() {\n let v: Vec = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect()\n };\n let (n, a, b, c) = (v[0], v[1], v[2], v[3]);\n\n let mut dp: HashMap = HashMap::new();\n dp.insert(0, 0);\n\n for i in 0..n + 1 {\n let mut m = 0;\n if dp.contains_key(&(i - a)) {\n m = std::cmp::max(m, dp[&(i - a)] + 1);\n }\n if dp.contains_key(&(i - b)) {\n m = std::cmp::max(m, dp[&(i - b)] + 1);\n }\n if dp.contains_key(&(i - c)) {\n m = std::cmp::max(m, dp[&(i - c)] + 1);\n }\n if m != 0 {\n dp.insert(i, m);\n }\n }\n println!(\"{:?}\", dp[&n]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "b3dfd8686c12d4a0326b359195f9b887", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_tuple4() -> (i64, i64, i64, i64) {\n let vec = read_line_vec();\n return (vec[0], vec[1], vec[2], vec[3]);\n}\n\n\nfn main() {\n let (n, a, b, c) = read_line_tuple4();\n\n let mut cost = Vec::new();\n cost.push(0i64);\n\n for i in 1..(n + 1) as usize {\n let ca = if i as i64 >= a { cost[i - a as usize] + 1 } else { i64::min_value() };\n let cb = if i as i64 >= b { cost[i - b as usize] + 1 } else { i64::min_value() };\n let cc = if i as i64 >= c { cost[i - c as usize] + 1 } else { i64::min_value() };\n let m = *[ca, cb, cc].iter().max().unwrap();\n // println!(\"{} {}\", i, m);\n cost.push(m);\n }\n\n println!(\"{}\", cost[n as usize]);\n // println!(\"{:?}\", [3,6,8].iter().max().unwrap());\n \n\n}", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "9ccba5048b6e4c297124fbd831742dc8", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn minimun_cuts(n: i32, options: &[i32]) -> i32 {\n let mut table = vec![vec![-1; options.len()]; n as usize + 1];\n\n fn traverse(mut n: i32, options: &[i32], table: &mut Vec>) -> i32 {\n for (i, option) in options.iter().enumerate() {\n if table[n as usize][i] == -1 {\n let mut push_value = -5000;\n let conditional = n - option;\n if conditional == 0 {\n push_value = 1;\n } else if conditional > 0 {\n n -= option;\n push_value = 1 + traverse(n, options, table);\n n += option;\n }\n table[n as usize][i] = push_value;\n }\n }\n *table[n as usize].iter().max().unwrap()\n }\n\n traverse(n, options, &mut table)\n}\n\nfn main() {\n let mut variables = String::new();\n std::io::stdin().read_line(&mut variables).unwrap();\n let variables: Vec = variables\n .split_whitespace()\n .map(|string| string.trim().parse().ok().unwrap())\n .collect();\n let n = variables[0];\n let (a, b, c) = (variables[1], variables[2], variables[3]);\n println!(\"{}\", minimun_cuts(n, &[a, b, c]));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "7050f022ae2ade9b7c8b7cbedccb80f1", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read() -> String {\n let mut res = String::new();\n std::io::stdin().read_line(&mut res).expect(\"???\");\n res\n}\n\nfn parse_int(s: &str) -> usize {\n s.trim().parse().expect(\"???\")\n}\n\nfn parse_ints(s: &str) -> Vec {\n s.split_whitespace().map(parse_int).collect()\n}\n\nfn main() {\n let v = parse_ints(&read());\n let n = v[0];\n let a = v[1];\n let b = v[2];\n let c = v[3];\n\n let mut arr = vec![-1; n+1];\n arr[n] = 0;\n\n for i in (0..n+1).rev() {\n // println!(\"{:?}\", arr);\n let x = arr[i];\n if x > -1 {\n if i >= a {\n arr[i-a] = std::cmp::max(arr[i-a], x+1);\n }\n if i >= b {\n arr[i-b] = std::cmp::max(arr[i-b], x+1);\n }\n if i >= c {\n arr[i-c] = std::cmp::max(arr[i-c], x+1);\n }\n }\n }\n println!(\"{}\", arr[0]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "94b566c8b678f76936020036126c1d50", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::HashSet;\nuse std::io::stdin;\n\nfn solve(n: i32) -> i32 {\n let mut set = HashSet::new();\n for i in 1i128..=((n as f64).sqrt().floor() as i128) {\n set.insert(i*i);\n if i*i*i <= n as i128 {\n set.insert(i * i * i);\n }\n }\n set.len() as i32\n}\n\nfn main() {\n let mut input = Scanner::default();\n let t = input.read_int();\n for _ in 0..t {\n println!(\"{}\", solve(input.read_int()));\n }\n}\n\n/// TEMPLATE\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn read_next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n fn read_int(&mut self) -> i32 {\n self.read_next::()\n }\n}\n\n/// TESTS\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn example1() {\n assert_eq!(solve(10), 4);\n }\n\n #[test]\n fn example2() {\n assert_eq!(solve(1), 1);\n }\n\n #[test]\n fn example3() {\n assert_eq!(solve(25), 6);\n }\n\n #[test]\n fn example4() {\n assert_eq!(solve(1000000000), 32591);\n }\n\n #[test]\n fn example5() {\n assert_eq!(solve(999999999), 32590);\n }\n\n #[test]\n fn example6() {\n assert_eq!(solve(500000000), 23125);\n }\n\n #[test]\n fn example7() {\n assert_eq!(solve(2), 1);\n }\n\n #[test]\n fn example8() {\n assert_eq!(solve(3), 1);\n }\n\n #[test]\n fn example9() {\n assert_eq!(solve(4), 2);\n }\n\n #[test]\n fn example10() {\n assert_eq!(solve(5), 2);\n }\n\n #[test]\n fn example11() {\n assert_eq!(solve(6), 2);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "49eaa274dd5aee93bac409654a1a6b56", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::cmp::{\n max, min,\n Ordering::{Equal, Greater, Less},\n Reverse,\n};\nuse std::collections::{self, BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\nuse std::convert::{From, Into, TryFrom, TryInto};\nuse std::io::{self, BufRead, BufReader, BufWriter, Write};\nuse std::iter::{FromIterator, IntoIterator};\nuse std::marker::PhantomData;\n\nmacro_rules! new_bufio {\n () => {{\n (io::stdin(), io::stdout(), String::new())\n }};\n}\nmacro_rules! init_lockedio {\n ($cin: expr, $cout: expr) => {{\n (BufReader::new($cin.lock()), BufWriter::new($cout.lock()))\n }};\n}\nmacro_rules! scanf {\n ($buf: expr, $div: expr, $($x: ty), +) => {{\n let mut iter = $buf.split($div);\n ($(iter.next().and_then(|token| token.parse::<$x>().ok()),)*)\n }};\n}\nmacro_rules! scan_array {\n ($buf: expr, $div: expr, $x: ty) => {{\n $buf.split($div)\n .filter(|tok| tok.parse::<$x>().is_ok())\n .map(|tok| tok.parse::<$x>().unwrap())\n .collect::>()\n }};\n}\nmacro_rules! getline {\n ($cin: expr, $buf: expr) => {{\n $buf.clear();\n $cin.read_line(&mut $buf)?;\n }};\n}\nmacro_rules! map_or_insert {\n ($map: expr, $key: expr, $fn: expr, $val: expr) => {{\n match $map.get_mut(&$key) {\n Some(v) => {\n $fn(v);\n }\n None => {\n $map.insert($key, $val);\n }\n }\n }};\n}\nmacro_rules! lowbit {\n ($x: expr) => {{\n $x & (!$x + 1)\n }};\n}\nmacro_rules! index {\n ($ch: expr) => {{\n ($ch - b'a') as usize\n }};\n}\n\nfn main() -> io::Result<()> {\n let (cin, cout, mut buf) = new_bufio!();\n let (mut cin, mut cout) = init_lockedio!(cin, cout);\n getline!(cin, buf);\n if let (Some(mut n), ) = scanf!(buf, char::is_whitespace, usize) {\n while n > 0 {\n getline!(cin, buf);\n if let (Some(x), ) = scanf!(buf, char::is_whitespace, i32) {\n let (mut sq, mut cu, mut si) = (0i32, 0i32, 0i32);\n for _ in 0..x {\n if si.pow(6) > x {\n break;\n }\n si += 1;\n }\n if si.pow(6) > x { si -= 1 };\n for _ in 0..x {\n if cu.pow(3) > x {\n break;\n }\n cu += 1;\n }\n if cu.pow(3) > x { cu -= 1 };\n for _ in 0..x {\n if sq.pow(2) > x {\n break;\n }\n sq += 1;\n }\n if sq.pow(2) > x { sq -= 1 };\n writeln!(cout, \"{0}\", sq + cu - si)?;\n }\n n -= 1;\n }\n }\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e66a48f3099b8c4f94b721f2b8b6fe09", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// -------- begin template -------- \r\n \r\n#![allow(\r\n dead_code, unused_imports, unused_variables, \r\n unused_must_use, unused_macros, unused_mut, unused_assignments\r\n)]//\r\n\r\nuse std::io::{self, Read, Write};\r\nuse std::cmp::{min, max};\r\nuse std::mem::swap;\r\nuse std::collections::{VecDeque, HashMap, HashSet, BTreeSet};\r\n \r\nmacro_rules! dbg {\r\n ($first_val:expr, $($val:expr),+ $(,)?) => {\r\n eprint!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n ($(eprint!(\", {} = {:?}\", stringify!($val), &$val)),+,);\r\n eprintln!();\r\n };\r\n ($first_val:expr) => {\r\n eprintln!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n };\r\n}\r\n \r\nenum InputSource {\r\n Stdin,\r\n FromFile(Vec),\r\n}\r\n \r\nstruct Scanner {\r\n buffer: Vec,\r\n input_source: InputSource,\r\n}\r\n \r\nimpl Scanner {\r\n fn new() -> Self {\r\n Self {\r\n buffer: vec![],\r\n input_source: InputSource::Stdin,\r\n }\r\n }\r\n \r\n fn new_file(filename: &str) -> Self {\r\n let file = std::fs::read_to_string(filename).unwrap();\r\n let mut lines: Vec = file.lines().map(|line| String::from(line)).collect();\r\n lines.reverse();\r\n Self {\r\n buffer: vec![],\r\n input_source: InputSource::FromFile(lines),\r\n }\r\n }\r\n \r\n fn usize(&mut self) -> usize { self.next::() }\r\n fn bytes(&mut self) -> Vec { self.next::().into_bytes() }\r\n fn chars(&mut self) -> Vec { self.next::().chars().collect() }\r\n fn string(&mut self) -> String { self.next::() }\r\n fn i64(&mut self) -> i64 { self.next::() }\r\n fn f64(&mut self) -> f64 { self.next::() }\r\n fn i32(&mut self) -> i32 { self.next::() }\r\n fn f32(&mut self) -> f32 { self.next::() }\r\n \r\n fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.next::()).collect()\r\n }\r\n \r\n fn parse_next_line(&mut self) -> bool {\r\n let mut input = String::new();\r\n match &mut self.input_source {\r\n InputSource::Stdin => {\r\n if std::io::stdin().read_line(&mut input).expect(\"Failed read\") == 0 {\r\n return false;\r\n }\r\n }\r\n InputSource::FromFile(lines) => match lines.pop() {\r\n Some(line) => input = line,\r\n None => return false,\r\n },\r\n }\r\n \r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n return true;\r\n }\r\n \r\n fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.parse_next_line();\r\n }\r\n }\r\n \r\n fn has_more_elements(&mut self) -> bool {\r\n loop {\r\n if !self.buffer.is_empty() { return true; }\r\n if !self.parse_next_line() { return false; }\r\n }\r\n }\r\n}\r\n \r\n// -------- end template -------- \r\n\r\n\r\nfn main() {\r\n let stdout = io::stdout();\r\n let mut out = std::io::BufWriter::new(stdout.lock());\r\n let mut sc = Scanner::new();\r\n\r\n let tests = sc.usize();\r\n for _ in 0..tests {\r\n let n = sc.i64();\r\n let mut cache: HashSet = HashSet::new();\r\n for i in 1..=n {\r\n if i * i > n { break; }\r\n cache.insert(i * i);\r\n }\r\n for i in 1..=n {\r\n if i * i * i > n { break; }\r\n cache.insert(i * i * i);\r\n }\r\n writeln!(out, \"{}\", cache.len());\r\n } \r\n}\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n \r\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "c329eb44d762abaf581b1b89c0e8f465", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::HashSet;\nuse std::io::stdin;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let t = scan.next::();\n\n let mut v = HashSet::new();\n\n let mut i = 1;\n while i * i <= 10_usize.pow(9) {\n v.insert(i * i);\n i += 1;\n }\n let mut i = 1;\n while i * i * i <= 10_usize.pow(9) {\n v.insert(i * i * i);\n i += 1;\n }\n\n for _ in 0..t {\n let n = scan.next::();\n let mut ans = 0;\n for k in v.iter() {\n if k <= &n {\n ans += 1;\n }\n }\n println!(\"{}\", ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "f9f44f83d18659f089006451421de22f", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "struct Scanner {\n reader: R,\n line: Vec,\n ptr: usize\n\n}\n\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self{reader, line: vec![], ptr: 0}\n }\n\n fn scan(&mut self) -> T {\n loop {\n while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {\n self.ptr += 1;\n }\n if self.ptr != self.line.len() {\n let start = self.ptr;\n while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {\n self.ptr += 1;\n }\n return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().\n expect(\"parse error\");\n }\n self.line.clear();\n self.reader.read_until(b'\\n', &mut self.line).expect(\"read error\");\n self.ptr = 0;\n }\n }\n\n fn line(&mut self) -> Vec {\n while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {\n self.ptr += 1;\n }\n if self.ptr == self.line.len() {\n self.line.clear();\n self.reader.read_until(b'\\n', &mut self.line).expect(\"read error\");\n self.ptr = 0;\n }\n let result = self.line[self.ptr..].to_vec();\n self.ptr = self.line.len();\n return result;\n }\n\n fn eof(&mut self) -> bool {\n loop {\n while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {\n self.ptr += 1;\n }\n if self.ptr != self.line.len() {\n return false;\n }\n self.line.clear();\n self.ptr = 0;\n if let Ok(0) = self.reader.read_until(b'\\n', &mut self.line) {\n return true;\n }\n }\n }\n\n}\n\nfn binary_search bool>(n: i64, f: F) -> i64 {\n let mut l = 0;\n let mut r = n;\n while l + 1 < r {\n let m = (l + r) / 2;\n if f(m) {\n l = m;\n } else {\n r = m;\n }\n }\n return l;\n}\n\nfn solve(scanner: &mut Scanner, writer: &mut W) {\n let n: i64 = scanner.scan();\n let squares = binary_search(100000, |x| x * x <= n);\n let cubes = binary_search(10000, |x| x * x * x <= n);\n let sixs = binary_search(100, |x| x * x * x * x * x * x <= n);\n let result = squares + cubes - sixs;\n writeln!(writer, \"{}\", result).unwrap();\n}\n\nfn main() {\n let (stdin, stdout) = (std::io::stdin(), std::io::stdout());\n let mut writer = std::io::BufWriter::new(stdout.lock());\n let mut scanner = Scanner::new(stdin.lock());\n let tests: usize = scanner.scan();\n for _ in 0..tests {\n solve(&mut scanner, &mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "6739c3ac034de16c63c55a9f8cb354e1", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io::{BufRead, BufReader, BufWriter, Write, stdin, stdout};\n\nfn main() {\n let stdout = stdout();\n let mut bw = BufWriter::new(stdout);\n\n let stdin = stdin();\n let mut br = BufReader::new(stdin);\n let mut num_tests_str = String::new();\n br.read_line(&mut num_tests_str).unwrap();\n let num_tests: usize = num_tests_str.trim_end().parse::().unwrap();\n\n for _ in 0..num_tests {\n let mut n_string = String::new();\n br.read_line(&mut n_string).unwrap();\n let n: usize = n_string.trim_end().parse().unwrap();\n let squares = count_powers_less_than(2, n);\n let cubes = count_powers_less_than(3, n);\n let sixth_powers = count_powers_less_than(6, n);\n let answer = squares + cubes - sixth_powers;\n writeln!(bw, \"{}\", answer).expect(\"Could not write to stdout\");\n }\n}\n\nfn count_powers_less_than(exponent: u32, n: usize) -> usize {\n let count: usize = (1..=n)\n .into_iter()\n .take_while(|i| i.pow(exponent) <= n)\n .count();\n count\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "347b9c026c41f08f05b8702d93d7c65b", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn read_i64() -> i64 {\r\n let mut line = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.trim().parse().unwrap()\r\n}\r\n\r\nfn bsearch bool>(mut lo: i64, mut hi: i64, f: F) -> i64 {\r\n while lo < hi {\r\n let mi = lo + (hi - lo) / 2;\r\n if f(mi) {\r\n hi = mi;\r\n } else {\r\n lo = mi + 1;\r\n }\r\n }\r\n hi\r\n}\r\n\r\nfn count(m: i64, n: i64) -> i64 {\r\n bsearch(1, m + 1, |x| {\r\n let mut y = m;\r\n for _ in 0..n {\r\n y /= x\r\n }\r\n y == 0\r\n }) - 1\r\n}\r\n\r\nfn main() {\r\n let re = read_i64();\r\n for _ri in 0..re {\r\n let t = read_i64();\r\n println!(\"{}\", count(t, 2) + count(t, 3) - count(t, 6));\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "6960ccba1a94041e38f0c0cb310d5ff6", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn readln() -> String {\r\n let mut line = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n String::from(line.trim())\r\n}\r\nfn readi() -> i64 { readln().parse().unwrap() }\r\nfn readv() -> Vec { readln().split(\" \").map(|x| x.parse::().unwrap()).collect() }\r\nfn main() {\r\n let t = readi();\r\n for T in 1..=t {\r\n let n = readi();\r\n let mut ans = 0;\r\n for i in 1i64.. {\r\n if i.pow(2) <= n {ans += 1;} else { break; }\r\n }\r\n for i in 1i64.. {\r\n if i.pow(3) <= n {ans += 1;} else { break; }\r\n }\r\n for i in 1i64.. {\r\n if i.pow(6) <= n {ans -= 1;} else { break; }\r\n }\r\n println!(\"{}\", ans);\r\n }\r\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "ed0d5f90eb21915aa7e5510a998eb0b2", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::ascii::AsciiExt;\n\nfn read_line() -> String {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n line\n}\n\nfn main() {\n\n let line = read_line();\n let is_cap = line.trim().chars().skip(1).all(|ch| ch.is_uppercase());\n\n if !is_cap {\n print!(\"{}\", line);\n } else {\n print!(\"{}\", line.trim().chars().map(|ch| if ch.is_uppercase() { ch.to_ascii_lowercase() } else { ch.to_ascii_uppercase() }).collect::());\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "e25c697f4e9fbf9105e4770d3b4c544e", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports, deprecated, dead_code)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{VecDeque,HashSet,HashMap,BinaryHeap};\n// Module for v1.15.1\nuse std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead\n\n// Functions\n\n// Main\nfn main() {\n\n input! {\n mut W: chars,\n }\n\n let mut f = true;\n for i in 1..W.len(){\n if W[i].is_ascii_lowercase() {\n f = false;\n break;\n }\n }\n\n if f {\n for i in 0..W.len() {\n if W[i].is_ascii_lowercase() {\n W[i] = W[i].to_ascii_uppercase();\n } else {\n W[i] = W[i].to_ascii_lowercase();\n }\n }\n }\n\n println!(\"{}\", W.into_iter().collect::());\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "5ba2cca860f521ae6ece0a5b7c8f920c", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn is_change_target(s: &String) -> bool {\n let mut is_first_char = true;\n\n for c in s.as_str().chars() {\n if is_first_char {\n is_first_char = false;\n continue;\n }\n\n if c.is_uppercase() == false {\n return false;\n }\n }\n\n true\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let input: String = read(sin);\n\n if !is_change_target(&input) {\n println!(\"{}\", input);\n return;\n }\n\n for c in input.as_str().chars() {\n if c.is_lowercase() {\n print!(\"{}\", c.to_uppercase().nth(0).unwrap());\n continue;\n }\n print!(\"{}\", c.to_lowercase().nth(0).unwrap());\n }\n println!(\"\");\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "521376b4d672b8ebad44e347bb051e8b", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n let line = line.trim();\n let s0 = line.to_string().to_uppercase();\n let ss = s0.as_str();\n let s1 = (&ss[0..1]).to_string().to_lowercase() + &s0[1..];\n \n let s2 = line.to_string().to_lowercase();\n let s3 = (&ss[0..1]).to_string().to_uppercase() + &s2[1..];\n\n if s0.eq(line) {\n println!(\"{}\", s2);\n } else if s1.eq(line) {\n println!(\"{}\", s3);\n } else {\n println!(\"{}\", line);\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "bc0b1350b0e599de705cbc76b7236962", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read, Write, stdin, stdout};\n\npub struct Scanner {\n pub buffer: Vec,\n pub reader: U,\n}\nimpl Scanner {\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_to_string(&mut input).expect(\"Failed read\");\n self.buffer = input.lines().rev().map(String::from).collect();\n }\n }\n\n pub fn new(reader: U) -> Self {\n return Scanner {\n buffer: vec![],\n reader,\n };\n }\n}\n\npub fn solution_of_p131a(input: &mut Read, out: &mut Write) {\n let mut scanner = Scanner::new(input);\n let line = scanner.next::();\n if line.len() == 1 {\n let c = line.chars().nth(0).unwrap();\n if c.is_ascii_uppercase() {\n write!(out, \"{}\", line.to_ascii_lowercase()).ok();\n } else {\n write!(out, \"{}\", line.to_ascii_uppercase()).ok();\n }\n } else if only_uppercase(&line) {\n write!(out, \"{}\", line.to_ascii_lowercase()).ok();\n } else if uppercase_except_first(&line) {\n write!(out, \"{}{}\", &line[0..1].to_ascii_uppercase(), &line[1..].to_ascii_lowercase()).ok();\n } else {\n write!(out, \"{}\", line).ok();\n }\n}\n\nfn only_uppercase(s: &str) -> bool {\n for c in s.chars() {\n if c.is_ascii_lowercase() {\n return false;\n }\n }\n return true;\n}\n\nfn uppercase_except_first(s: &str) -> bool {\n let first_c = s.chars().nth(0).unwrap();\n if first_c.is_ascii_uppercase() {\n return false;\n }\n for c in (&s[1..]).chars() {\n if c.is_ascii_lowercase() {\n return false;\n }\n }\n return true;\n}\n\nfn main() {\n solution_of_p131a(&mut stdin(), &mut stdout());\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "3793d1bf1aa2597d26b1d95e59f0c1b7", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::{Read, Write};\n\nfn solve(input: &mut Read, output: &mut Write) {\n let mut sin = String::new();\n input.read_to_string(&mut sin).unwrap();\n let sin = sin.lines().next().unwrap().trim();\n let res: String;\n if sin.chars().skip(1).all(|x| x.is_uppercase()) || (sin.chars().count() == 1 && sin.chars().next().unwrap().is_uppercase()) {\n let mut chars = sin.chars();\n let first = chars.next().unwrap();\n let first: String = if first.is_uppercase() { first.to_lowercase().collect() } else { first.to_uppercase().collect() };\n res = first + &chars.collect::().to_lowercase();\n } else {\n res = sin.to_string();\n }\n\n output.write(res.to_string().trim().as_bytes()).unwrap();\n}\n\nfn main() {\n solve(&mut io::stdin(), &mut io::stdout());\n}\n\n#[cfg(test)]\nmod tests {\n use std::fs::File;\n use std::io::Read;\n use solve;\n\n #[test]\n fn test() {\n (1..1 + 1).map(|x| {\n println!(\"test #{}\", x);\n let mut fin = File::open(\"./src/in\".to_string() + &x.to_string() + \".txt\").unwrap();\n let mut buf: Vec = Vec::new();\n solve(&mut fin, &mut buf);\n let res = String::from_utf8(buf).unwrap();\n\n let mut fout = File::open(\"./src/out\".to_string() + &x.to_string() + \".txt\").unwrap();\n let mut sout = String::new();\n fout.read_to_string(&mut sout).unwrap();\n assert_eq!(res, sout.trim());\n\n }).count();\n\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "852a0656bb3bca0df55aee33d2cc5202", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n\n let mut caps = true;\n\n for (i, c) in s.chars().enumerate() {\n if i != 0 {\n if c.is_lowercase() {\n caps = false;\n }\n } \n }\n\n if caps {\n let mut temp = String::new();\n for c in s.chars() {\n if c.is_lowercase() {\n temp.push(c.to_ascii_uppercase());\n } else {\n temp.push(c.to_ascii_lowercase());\n }\n }\n\n print!(\"{}\", temp);\n } else {\n print!(\"{}\", s);\n }\n}\n\n\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "c53cdc81e8b8216510e764cde24fe9a2", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n println!(\"{}\",operation());\n}\nfn operation() -> String {\n let (simple,word)=input();\n if word[0].is_lowercase(){\n if word.len()==1{\n return (simple.to_uppercase()).to_string()\n }\n if word[1].is_lowercase(){\n return simple\n }\n let mut n=0;\n for i in 1..word.len(){\n if word[i].is_uppercase(){\n n+=1;\n }\n }\n if n+1==word.len(){\n let mut sum=(word[0].to_uppercase()).to_string();\n for i in 1..word.len(){\n sum+=&((word[i].to_lowercase()).to_string());\n }\n return sum;\n }\n }\n else{\n if word.len()==1{\n return (simple.to_lowercase()).to_string()\n }\n let mut n=0;\n for i in 0..word.len(){\n if word[i].is_uppercase(){\n n+=1;\n }\n }\n if n==word.len(){\n return (simple.to_lowercase()).to_string()\n }\n }\n return simple\n}\nfn read() -> String{\n let mut input=String::new();\n io::stdin().read_line(&mut input).expect(\"unable to read\");\n input.trim().to_string()\n}\n\nfn input() -> (String,Vec){\n let inp=read();\n let l:Vec=inp.chars().collect();\n (inp,l)\n}\n/* let n=read().parse::().expect(\"Failed to parse\");\n let inp=read();\n (n,inp.split_whitespace().map(|x| x.parse::().expect(\"Failed to parse\")).collect())\n let list: Vec<_>=inp.split_whitespace().collect();\n let qu: Vec<_>=read().chars().collect();\n (list[0].parse::().expect(\"Failed to parse\"),\n list[1].parse::().expect(\"Failed to parse\"),qu)\n*/\n\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "6f5dff79a1cb99d41e4e2f72ba84376a", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let (l, r) = parse_line!(u64, u64);\n let mut bit = 1u64 << 63;\n while bit != 0 && l & bit == r & bit {\n bit >>= 1;\n }\n if bit == 0 {\n writeln!(writer, \"0\").unwrap();\n }else{\n writeln!(writer, \"{}\", bit | (bit - 1)).unwrap();\n }\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "bitmasks", "greedy", "implementation"], "code_uid": "98cc010f0e9d0badf243c55e93641aee", "src_uid": "d90e99d539b16590c17328d79a5921e0", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(l,r: i64 = input.p());\n if l == r {\n println!(\"0\");\n } else {\n let mut x = l ^ r;\n for i in 0..=5 {\n x |= x >> (1 << i);\n }\n println!(\"{}\", x);\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "dp", "bitmasks", "greedy", "implementation"], "code_uid": "799842c8b4bac6250ebe8a038166894a", "src_uid": "d90e99d539b16590c17328d79a5921e0", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead, Write};\nuse std::str::{self, FromStr};\nuse std::fmt::Debug;\n\nconst P: i32 = 998244353;\n\nfn mul(x: i32, y: i32) -> i32 {\n ((x as i64) * (y as i64) % (P as i64)) as i32\n}\n\nfn add_mul(z: i32, x: i32, y: i32) -> i32 {\n ((z as i64 + (x as i64) * (y as i64)) % (P as i64)) as i32\n}\n\n#[allow(unused_variables)]\nfn solve(input: &mut FastDynInput<'_>, output: &mut dyn Write) -> io::Result<()> {\n\n let n = input.iread();\n let x = input.iread();\n let mut res: Vec> = vec![vec![0; (x+1) as usize]; (n+1) as usize];\n let mut bin: Vec> = vec![vec![0;(n+1) as usize]; (n+1) as usize];\n for i in 0..=n {\n bin[0 as usize][i as usize] = 1;\n }\n for i in 1..=n {\n bin[i as usize][0 as usize] = 1;\n for j in 1..=n {\n bin[i as usize][j as usize] = (bin[(i - 1) as usize][j as usize] + bin[i as usize][(j - 1) as usize]) % P;\n }\n }\n for i in 2..=n {\n for j in 1..=x {\n let mut cur = 1i32;\n if i - 1 >= j {\n for _ in 0..i {\n cur = mul(cur, j);\n }\n } else {\n for _ in 0..i {\n cur = mul(cur, i - 1);\n }\n let mut mult = 1i32;\n for left in (2..=i).into_iter().rev() {\n let next = res[left as usize][(j - i + 1) as usize];\n cur = add_mul(cur, next, mul(mult, bin[left as usize][(i - left) as usize]));\n mult = mul(mult, i - 1);\n }\n }\n res[i as usize][j as usize] = cur;\n }\n }\n writeln!(output, \"{}\", res[n as usize][x as usize])?;\n Ok(())\n}\n\n#[test]\nfn test1() {\n test_solve(\"2 5\", \"5\");\n test_solve(\"3 3\", \"15\");\n test_solve(\"5 4\", \"1024\");\n test_solve(\"13 37\", \"976890680\");\n}\n\nfn test_solve(input: &str, output: &str) {\n let mut writer = Vec::new();\n solve(&mut FastDynInput::from(input.as_bytes()), &mut writer).unwrap();\n assert_eq!(bytes_to_str(&writer).split_ascii_whitespace().collect::>(),\n output.split_ascii_whitespace().collect::>());\n}\n\nfn bytes_to_str(vec: &[u8]) -> &str {\n str::from_utf8(vec).unwrap()\n}\n\nstruct FastDynInput<'a> {\n stdin: Box,\n}\n\nimpl<'a, R: BufRead + 'a> From for FastDynInput<'a> {\n fn from(r: R) -> Self {\n Self {\n stdin: Box::new(r),\n }\n }\n}\n\n#[allow(dead_code)]\nimpl FastDynInput<'_> {\n fn read_bytes(&mut self) -> Vec {\n let mut bytes: Vec = Vec::new();\n let mut skip_space = true;\n loop {\n if let Ok(buf) = self.stdin.fill_buf() {\n if buf.is_empty() {\n break;\n }\n let mut pos: usize = 0;\n if skip_space {\n while pos < buf.len() && buf[pos] <= 32 {\n pos += 1;\n }\n if pos < buf.len() {\n skip_space = false;\n } else {\n self.stdin.consume(pos);\n continue;\n }\n }\n while pos < buf.len() && buf[pos] > 32 {\n bytes.push(buf[pos]);\n pos += 1;\n }\n if pos < buf.len() {\n self.stdin.consume(pos);\n break;\n }\n self.stdin.consume(pos);\n } else {\n break;\n }\n }\n bytes\n }\n\n fn read_word(&mut self) -> String {\n String::from_utf8(self.read_bytes()).unwrap()\n }\n\n fn try_read_word(&mut self) -> Option {\n let result = self.read_bytes();\n if result.is_empty() {\n return None;\n }\n String::from_utf8(result).ok()\n }\n\n fn read_line_bytes(&mut self) -> Option> {\n let mut bytes: Vec = Vec::new();\n loop {\n if let Ok(buf) = self.stdin.fill_buf() {\n if buf.is_empty() {\n if bytes.is_empty() {\n return None;\n }\n break;\n }\n let mut pos: usize = 0;\n while pos < buf.len() && buf[pos] != b'\\n' {\n if buf[pos] != b'\\r' {\n bytes.push(buf[pos]);\n }\n pos += 1;\n }\n if pos < buf.len() {\n pos += 1;\n self.stdin.consume(pos);\n break;\n }\n self.stdin.consume(pos);\n } else {\n break;\n }\n }\n Some(bytes)\n }\n\n fn read_line(&mut self) -> String {\n String::from_utf8(self.read_line_bytes().unwrap()).unwrap()\n }\n\n fn try_read_line(&mut self) -> Option {\n String::from_utf8(self.read_line_bytes()?).ok()\n }\n\n fn iread(&mut self) -> i32 {\n self.read()\n }\n\n fn uread(&mut self) -> u32 {\n self.read()\n }\n\n fn dread(&mut self) -> f64 {\n self.read()\n }\n\n fn lread(&mut self) -> i64 {\n self.read()\n }\n\n fn read(&mut self) -> V\n where V: FromStr,\n V::Err: Debug {\n self.read_word().parse::().unwrap()\n }\n\n fn parse(&mut self) -> Result {\n self.read_word().parse::()\n }\n}\n\nfn main() -> io::Result<()> {\n let stdin = io::stdin();\n let mut input = FastDynInput::from(stdin.lock());\n let stdout = io::stdout();\n let stdout_lock = stdout.lock();\n let mut output = io::BufWriter::with_capacity(1 << 16, stdout_lock);\n solve(&mut input, &mut output)\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "a46c590cd6b1084ca766927483a8d593", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::*;\r\n\r\nfn read_line() -> String {\r\n let mut line = String::new();\r\n io::stdin().read_line(&mut line).unwrap();\r\n line\r\n}\r\n\r\nfn read_vec() -> Vec {\r\n read_line()\r\n .split_whitespace()\r\n .filter_map(|i| i.parse().ok())\r\n .collect()\r\n}\r\n\r\nfn main() {\r\n const M: i64 = 998244353;\r\n if let [n, m] = read_vec::()[..] {\r\n let mut choose = vec![vec![0; n + 1]; n + 1];\r\n for i in 0..=n {\r\n choose[i][0] = 1;\r\n for j in 1..=i {\r\n choose[i][j] = choose[i - 1][j - 1] + choose[i - 1][j];\r\n if choose[i][j] >= M {\r\n choose[i][j] -= M;\r\n }\r\n }\r\n }\r\n\r\n let mut dp = vec![vec![0; m + 1]; n + 1];\r\n dp[1][1..].fill(1);\r\n for i in 1..n {\r\n let pow = iter::successors(Some(1), |&x| Some(x * i as i64 % M))\r\n .take(i + 1)\r\n .collect::>();\r\n for j in 1..=m {\r\n let mut s = 0;\r\n for k in (i..j).step_by(i) {\r\n let jj = j - k;\r\n for ii in 1..=i {\r\n s += dp[ii][jj] * choose[i + 1][ii] % M * pow[i + 1 - ii] % M;\r\n }\r\n }\r\n dp[i + 1][j] = s % M;\r\n }\r\n }\r\n\r\n let mut ans = 1;\r\n for _ in 0..n {\r\n ans = ans * m as i64 % M;\r\n }\r\n ans -= dp[n].iter().sum::();\r\n println!(\"{}\", ans.rem_euclid(M));\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "ba27d40630d419a2b405ac1730befe99", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\r\n date : 2021 / 4 / 7\r\n author : quickn (quickn.tech)\r\n email : quickwshell@gmail.com\r\n*/\r\n\r\nuse std::io::{self, BufWriter, Write};\r\n\r\nmod scanner {\r\n use std::{io, str};\r\n /* https://github.com/EbTech/rust-algorithms */\r\n\r\n /// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\r\n /// **REQUIRES** Rust 1.34 or higher\r\n pub struct UnsafeScanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitAsciiWhitespace<'static>,\r\n }\r\n\r\n impl UnsafeScanner {\r\n pub fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: Vec::new(),\r\n buf_iter: \"\".split_ascii_whitespace(),\r\n }\r\n }\r\n\r\n /// This function should be marked unsafe, but noone has time for that in a\r\n /// programming contest. Use at your own risk!\r\n pub fn token(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_ascii_whitespace())\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nuse std::cmp::{min, max};\r\n\r\nfn s2vec(s: String) -> Vec {\r\n s.chars().collect()\r\n}\r\n\r\nconst MOD: i64 = 998244353;\r\n\r\nconst MAX: usize = 501;\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let (mut scan, mut sout) = (\r\n scanner::UnsafeScanner::new(stdin.lock()),\r\n BufWriter::new(stdout.lock()),\r\n );\r\n let n: usize = scan.token();\r\n let x: usize = scan.token();\r\n let mut dp: Vec> = vec![vec![0;MAX];n+1];\r\n let mut binom: Vec> = vec![vec![0;MAX+1];MAX+1];\r\n let mut pow_mod: Vec> = vec![vec![0;MAX+1];MAX+1];\r\n for a in 1..MAX {\r\n let mut val = 1;\r\n for x in 0..MAX {\r\n pow_mod[a][x] = val;\r\n val *= a as i64;\r\n val %= MOD;\r\n }\r\n }\r\n binom[0][0] = 1;\r\n for i in 1..=MAX {\r\n binom[i][0] = 1;\r\n binom[i][i] = 1;\r\n for j in 1..i {\r\n binom[i][j] += binom[i-1][j-1];\r\n binom[i][j] %= MOD;\r\n binom[i][j] += binom[i-1][j];\r\n binom[i][j] %= MOD;\r\n }\r\n }\r\n dp[n][0] = 1;\r\n for r in (1..=n).rev() {\r\n for lx in 0..=x {\r\n for y in 0..=(n-r) {\r\n if lx >= y+r-1 {\r\n let d = max(0, min(x-lx+(y+r-1), y+r-1));\r\n dp[r][lx] += (((dp[r+y][lx-(y+r-1)]*binom[y+r][y])%MOD)*pow_mod[d][y])%MOD;\r\n dp[r][lx] %= MOD;\r\n }\r\n }\r\n }\r\n }\r\n let mut all = pow_mod[x][n];\r\n for lx in 0..=x {\r\n all -= (dp[1][lx]*((x - lx) as i64))%MOD;\r\n all += MOD;\r\n all %= MOD;\r\n }\r\n writeln!(sout, \"{}\", all).ok();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "c50d601ba6e67d7af52c8f6c133fc84d", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::convert::TryInto as _;\nuse std::io::{Result, Write as _};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\n\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nconst MOD: i64 = 998_244_353;\n\nconst fn pow(b: i64, mut x: i64) -> i64 {\n let mut m = b;\n let mut ret = 1;\n while x > 0 {\n if (x & 1) > 0 {\n ret = ret * m % MOD;\n }\n m = m * m % MOD;\n x >>= 1;\n }\n\n ret\n}\n\nconst fn inverse(n: i64) -> i64 {\n pow(n, MOD - 2)\n}\n\nconst fn make_factorials() -> ([i64; 501], [i64; 501]) {\n let mut fact = [0; 501];\n let mut inv = [0; 501];\n\n fact[0] = 1;\n inv[0] = 1;\n\n let mut i = 1;\n while i <= 500 {\n let j = i as i64;\n fact[i] = fact[i - 1] * j % MOD;\n i += 1;\n }\n\n inv[500] = inverse(fact[500]);\n\n let mut i = 499;\n while i > 0 {\n let j = i as i64;\n inv[i] = inv[i + 1] * (j + 1) % MOD;\n i -= 1;\n }\n\n (fact, inv)\n}\n\nfn make_powers() -> [[i64; 501]; 501] {\n let mut powers = [[0; 501]; 501];\n\n for b in 1..=500 {\n let bi64 = b.try_into().unwrap();\n powers[b][1] = bi64;\n for x in 2..=500 {\n powers[b][x] = powers[b][x - 1] * bi64 % MOD;\n }\n }\n\n powers\n}\n\nconst FACTORIALS: ([i64; 501], [i64; 501]) = make_factorials();\n\nfn main() -> Result<()> {\n let mut scanner = Scanner::default();\n let out = &mut std::io::BufWriter::new(std::io::stdout());\n\n let (fact, inv) = FACTORIALS;\n let powers = make_powers();\n\n let c = |n, k| fact[n] * inv[k] % MOD * inv[n - k] % MOD;\n\n let n: usize = scanner.next();\n let x = scanner.next();\n\n let mut dp = vec![vec![0; x + 1]; n + 1];\n for i in 1..=x {\n dp[1][i] = n.try_into().unwrap();\n }\n\n for i in 1..n {\n for j in 1..x {\n for k in (i + 1)..=n {\n // dp[i][j] -> dp[k][?]\n let max = (x - j) / (k - 1);\n for l in 1..=max {\n let nj = j + l * (k - 1);\n debug_assert!(nj <= x);\n dp[k][nj] = (dp[k][nj] + dp[i][j] * c(n - i, k - i) % MOD * powers[k - 1][k - i] % MOD) % MOD;\n }\n }\n }\n }\n\n let sum = dp[n].iter().fold(0, |acc, x| (acc + x) % MOD);\n let ret = (pow(x.try_into().unwrap(), n.try_into().unwrap()) + MOD - sum) % MOD;\n\n writeln!(out, \"{}\", ret)?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "faa0e43575e7f33155c74cfe2138910d", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{io, io::prelude::*, str};\n\nstruct Scanner {\n reader: R,\n buffer: Vec,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n fn t(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nuse std::ops;\n\n#[derive(Copy, Clone)]\nstruct ModGroup {\n val: usize,\n}\nimpl ModGroup {\n const MOD: usize = 998244353;\n const MOD64: i64 = Self::MOD as i64;\n\n fn new(v: usize) -> Self {\n Self { val: v }\n }\n\n fn from_usize(v: usize) -> Self {\n Self { val: v % Self::MOD }\n }\n\n fn from_i64(v: i64) -> Self {\n Self {\n val: (v % Self::MOD64) as usize,\n }\n }\n\n fn pow(self, mut p: usize) -> Self {\n let mut base = self;\n let mut res = Self::new(1);\n while p > 0 {\n if p % 2 > 0 {\n res = res * base;\n }\n base = base * base;\n p /= 2;\n }\n\n res\n }\n\n fn inv(self) -> Self {\n self.pow(Self::MOD - 2)\n }\n}\n\nimpl ops::Add for ModGroup {\n type Output = Self;\n\n fn add(self, other: usize) -> Self {\n Self::from_usize(self.val + other)\n }\n}\nimpl ops::Add for ModGroup {\n type Output = Self;\n\n fn add(self, other: Self) -> Self {\n self + other.val\n }\n}\nimpl ops::Sub for ModGroup {\n type Output = Self;\n\n fn sub(self, other: usize) -> Self {\n Self::new(if self.val >= other {\n self.val - other\n } else {\n self.val + Self::MOD - other\n })\n }\n}\nimpl ops::Sub for ModGroup {\n type Output = Self;\n\n fn sub(self, other: Self) -> Self {\n self - other.val\n }\n}\nimpl ops::Mul for ModGroup {\n type Output = Self;\n\n fn mul(self, other: usize) -> Self {\n Self::from_i64(self.val as i64 * other as i64)\n }\n}\nimpl ops::Mul for ModGroup {\n type Output = Self;\n\n fn mul(self, other: Self) -> Self {\n self * other.val\n }\n}\nimpl ops::Div for ModGroup {\n type Output = Self;\n\n fn div(self, other: usize) -> Self {\n self * Self::new(other).inv()\n }\n}\nimpl ops::Div for ModGroup {\n type Output = Self;\n\n fn div(self, other: Self) -> Self {\n self * other.inv()\n }\n}\n\nfn main() -> io::Result<()> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout);\n\n const N: usize = 501;\n\n let fact = {\n let mut fact = vec![ModGroup::from_usize(1); N];\n for i in 1..N {\n fact[i] = fact[i - 1] * i;\n }\n fact\n };\n let bin_coef = {\n let mut bin_coef = vec![vec![ModGroup::from_usize(0); N]; N];\n for i in 1..N {\n for j in 1..=i {\n bin_coef[i][j] = fact[i] / (fact[j] * fact[i - j]);\n }\n }\n bin_coef\n };\n let pow_n = {\n let mut pow_n = vec![vec![ModGroup::from_usize(1); N]; N];\n for i in 1..N {\n for j in 1..N {\n pow_n[i][j] = pow_n[i][j - 1] * i;\n }\n }\n pow_n\n };\n\n let (n, m): (usize, usize) = (scan.t(), scan.t());\n let mut dp = vec![vec![ModGroup::from_usize(0); m + 1]; m + 1];\n for h in 1..=m {\n dp[h][h] = pow_n[h - 1][h - 1] * h;\n for d in 2..h {\n let mut cur = dp[d][d];\n let h1 = h - d + 1;\n for k in 2..=d {\n cur = cur + dp[h1][k] * bin_coef[d][k] * pow_n[d - 1][d - k];\n }\n\n dp[h][d] = cur;\n }\n }\n\n let mut res = ModGroup::from_usize(0);\n if m >= n {\n for i in 1..=m {\n res = res + dp[i][n];\n }\n }\n res = pow_n[m][n] - res;\n writeln!(out, \"{}\", res.val)?;\n\n io::Result::Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "f6ca6c33a4ebd81d29a7bf36c0d160ab", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use crate::mod_int::ModInt;\r\n\r\nfn main() {\r\n let (r, w) = (std::io::stdin(), std::io::stdout());\r\n let mut sc = IO::new(r.lock(), w.lock());\r\n let n: usize = sc.read();\r\n let x: usize = sc.read();\r\n\r\n let comb = Combination::new(n.max(x) * 2 + 1, 998244353);\r\n let mut dp = vec![vec![ModInt::from(0); x + 1]; n + 1];\r\n\r\n for last in 2..=n {\r\n for max_hp in 1..=x {\r\n if max_hp > last - 1 {\r\n break;\r\n }\r\n let c = ModInt::from(comb.get(n, last));\r\n let d = distribution(max_hp, last);\r\n dp[last][max_hp] = c * d;\r\n }\r\n }\r\n\r\n for cur_alive in 2..=n {\r\n for cur_max_hp in 1..=x {\r\n for next_alive in cur_alive..=n {\r\n let cur_dp = dp[cur_alive][cur_max_hp];\r\n let new_people = next_alive - cur_alive;\r\n let damage = next_alive - 1;\r\n if cur_max_hp + damage > x {\r\n break;\r\n }\r\n\r\n let c = comb.get(n - cur_alive, new_people);\r\n let d = ModInt::from(damage).pow(new_people);\r\n dp[next_alive][cur_max_hp + damage] += cur_dp * c * d;\r\n }\r\n }\r\n }\r\n\r\n let mut ans = ModInt::from(0);\r\n for x in 0..=x {\r\n ans += dp[n][x];\r\n }\r\n println!(\"{}\", ans.value());\r\n\r\n // for i in 1..=n {\r\n // for j in 1..=x {\r\n // print!(\"{} \", dp[i][j].value());\r\n // }\r\n // println!();\r\n // }\r\n}\r\n\r\nfn distribution(max_hp: usize, people: usize) -> ModInt {\r\n ModInt::from(max_hp).pow(people) - ModInt::from(max_hp - 1).pow(people)\r\n}\r\n\r\npub struct Combination {\r\n fact: Vec,\r\n inv_fact: Vec,\r\n modulo: usize,\r\n}\r\n\r\nimpl Combination {\r\n pub fn new(max: usize, modulo: usize) -> Self {\r\n let mut inv = vec![0; max + 1];\r\n let mut fact = vec![0; max + 1];\r\n let mut inv_fact = vec![0; max + 1];\r\n inv[1] = 1;\r\n for i in 2..(max + 1) {\r\n inv[i] = inv[modulo % i] * (modulo - modulo / i) % modulo;\r\n }\r\n fact[0] = 1;\r\n inv_fact[0] = 1;\r\n for i in 0..max {\r\n fact[i + 1] = fact[i] * (i + 1) % modulo;\r\n }\r\n for i in 0..max {\r\n inv_fact[i + 1] = inv_fact[i] * inv[i + 1] % modulo;\r\n }\r\n Self {\r\n fact,\r\n inv_fact,\r\n modulo,\r\n }\r\n }\r\n\r\n pub fn get(&self, x: usize, y: usize) -> usize {\r\n assert!(x >= y);\r\n self.fact[x] * self.inv_fact[y] % self.modulo * self.inv_fact[x - y] % self.modulo\r\n }\r\n\r\n pub fn h(&self, n: usize, r: usize) -> usize {\r\n self.get(n + r - 1, r)\r\n }\r\n}\r\npub mod mod_int {\r\n type ModInternalNum = i64;\r\n thread_local!(\r\n static MOD: std::cell::RefCell = std::cell::RefCell::new(0);\r\n );\r\n\r\n pub fn set_mod_int(v: T) {\r\n MOD.with(|x| x.replace(v.to_internal_num()));\r\n }\r\n fn modulo() -> ModInternalNum {\r\n 998244353\r\n }\r\n\r\n #[derive(Debug)]\r\n pub struct ModInt(ModInternalNum);\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n Self(self.0)\r\n }\r\n }\r\n impl Copy for ModInt {}\r\n\r\n impl ModInt {\r\n fn internal_new(mut v: ModInternalNum) -> Self {\r\n let m = modulo();\r\n if v >= m {\r\n v %= m;\r\n }\r\n Self(v)\r\n }\r\n\r\n pub fn internal_pow(&self, mut e: ModInternalNum) -> Self {\r\n let mut result = 1;\r\n let mut cur = self.0;\r\n let modulo = modulo();\r\n while e > 0 {\r\n if e & 1 == 1 {\r\n result *= cur;\r\n result %= modulo;\r\n }\r\n e >>= 1;\r\n cur = (cur * cur) % modulo;\r\n }\r\n Self(result)\r\n }\r\n\r\n pub fn pow(&self, e: T) -> Self\r\n where\r\n T: ToInternalNum,\r\n {\r\n self.internal_pow(e.to_internal_num())\r\n }\r\n\r\n pub fn value(&self) -> ModInternalNum {\r\n self.0\r\n }\r\n }\r\n\r\n pub trait ToInternalNum {\r\n fn to_internal_num(&self) -> ModInternalNum;\r\n }\r\n impl ToInternalNum for ModInt {\r\n fn to_internal_num(&self) -> ModInternalNum {\r\n self.0\r\n }\r\n }\r\n macro_rules! impl_primitive {\r\n ($primitive:ident) => {\r\n impl From<$primitive> for ModInt {\r\n fn from(v: $primitive) -> Self {\r\n let v = v as ModInternalNum;\r\n Self::internal_new(v)\r\n }\r\n }\r\n impl ToInternalNum for $primitive {\r\n fn to_internal_num(&self) -> ModInternalNum {\r\n *self as ModInternalNum\r\n }\r\n }\r\n };\r\n }\r\n impl_primitive!(u8);\r\n impl_primitive!(u16);\r\n impl_primitive!(u32);\r\n impl_primitive!(u64);\r\n impl_primitive!(usize);\r\n impl_primitive!(i8);\r\n impl_primitive!(i16);\r\n impl_primitive!(i32);\r\n impl_primitive!(i64);\r\n impl_primitive!(isize);\r\n\r\n impl std::ops::AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: T) {\r\n let mut rhs = rhs.to_internal_num();\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n\r\n self.0 += rhs;\r\n if self.0 >= m {\r\n self.0 -= m;\r\n }\r\n }\r\n }\r\n\r\n impl std::ops::Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: T) -> Self::Output {\r\n let mut res = self;\r\n res += rhs;\r\n res\r\n }\r\n }\r\n impl std::ops::SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: T) {\r\n let mut rhs = rhs.to_internal_num();\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n if rhs > 0 {\r\n self.0 += m - rhs;\r\n }\r\n if self.0 >= m {\r\n self.0 -= m;\r\n }\r\n }\r\n }\r\n impl std::ops::Sub for ModInt {\r\n type Output = Self;\r\n fn sub(self, rhs: T) -> Self::Output {\r\n let mut res = self;\r\n res -= rhs;\r\n res\r\n }\r\n }\r\n impl std::ops::MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: T) {\r\n let mut rhs = rhs.to_internal_num();\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n self.0 *= rhs;\r\n self.0 %= m;\r\n }\r\n }\r\n impl std::ops::Mul for ModInt {\r\n type Output = Self;\r\n fn mul(self, rhs: T) -> Self::Output {\r\n let mut res = self;\r\n res *= rhs;\r\n res\r\n }\r\n }\r\n\r\n impl std::ops::DivAssign for ModInt {\r\n fn div_assign(&mut self, rhs: T) {\r\n let mut rhs = rhs.to_internal_num();\r\n let m = modulo();\r\n if rhs >= m {\r\n rhs %= m;\r\n }\r\n let inv = Self(rhs).internal_pow(m - 2);\r\n self.0 *= inv.value();\r\n self.0 %= m;\r\n }\r\n }\r\n\r\n impl std::ops::Div for ModInt {\r\n type Output = Self;\r\n fn div(self, rhs: T) -> Self::Output {\r\n let mut res = self;\r\n res /= rhs;\r\n res\r\n }\r\n }\r\n}\r\n\r\npub struct IO(R, std::io::BufWriter);\r\n\r\nimpl IO {\r\n pub fn new(r: R, w: W) -> IO {\r\n IO(r, std::io::BufWriter::new(w))\r\n }\r\n pub fn write(&mut self, s: S) {\r\n use std::io::Write;\r\n self.1.write_all(s.to_string().as_bytes()).unwrap();\r\n }\r\n pub fn read(&mut self) -> T {\r\n use std::io::Read;\r\n let buf = self\r\n .0\r\n .by_ref()\r\n .bytes()\r\n .map(|b| b.unwrap())\r\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\r\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\r\n .collect::>();\r\n unsafe { std::str::from_utf8_unchecked(&buf) }\r\n .parse()\r\n .ok()\r\n .expect(\"Parse error.\")\r\n }\r\n pub fn usize0(&mut self) -> usize {\r\n self.read::() - 1\r\n }\r\n pub fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.read()).collect()\r\n }\r\n pub fn chars(&mut self) -> Vec {\r\n self.read::().chars().collect()\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "2d496dae5d7e625558624f1de2349e9a", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(dead_code)]\n#![allow(unused_variables)]\nuse std::cmp::min;\nuse std::io;\nuse std::{io::prelude::*, io::*, str};\n\nstruct IO {\n buffer: Vec,\n out: BufWriter,\n}\nimpl IO {\n fn new() -> Self {\n Self {\n buffer: vec![],\n out: BufWriter::new(stdout()),\n }\n }\n fn read(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read::()).collect()\n }\n}\n\nconst MOD: u64 = 998244353;\n\nfn fastpow(mut a: u64, mut x: u64) -> u64 {\n let mut r = 1;\n while x != 0 {\n if x & 1 != 0 {\n r = (r * a) % MOD;\n }\n\n a = (a * a) % MOD;\n x >>= 1;\n }\n r\n}\n\nfn modinv(x: u64) -> u64 {\n fastpow(x, MOD - 2)\n}\n\nfn solve(io: &mut IO) -> Result<()> {\n let (n, x): (usize, usize) = (io.read(), io.read());\n let mut comb = vec![vec![1; n + 1]; n + 1];\n let mut comb2 = vec![vec![1; n + 1]; n + 1];\n let mut fact = vec![1; n + 1];\n\n for i in 1..=n {\n fact[i] = (fact[i - 1] * (i as u64)) % MOD;\n\n for j in 1..=i {\n let rem = (fact[j] * fact[i - j]) % MOD;\n let rinv = modinv(rem);\n\n comb[i][j] = (fact[i] * rinv) % MOD;\n\n comb2[i][j] = fastpow(i as u64 - 1, j as u64) * comb[i][j] % MOD;\n }\n }\n\n let mut dp = vec![vec![0; x + 1]; n + 1];\n dp[0] = vec![1; x + 1];\n\n for k in 2..=n {\n let mut sum = 0u64;\n for y in 1..=min(k - 1, x) {\n dp[k][y] = (fastpow(y as u64, k as u64) + MOD - sum) % MOD;\n sum = (sum + dp[k][y]) % MOD\n }\n\n for y in k..=x {\n let mut val = dp[k][y - (k - 1)];\n\n for i in 1..k {\n let a = dp[k - i][y - (k - 1)] * comb2[k][i] % MOD;\n val = (val + a) % MOD;\n }\n dp[k][y] = val;\n }\n }\n\n let mut cnt = 0;\n for y in 1..=x {\n cnt = (cnt + dp[n][y]) % MOD;\n }\n\n writeln!(io.out, \"{}\", cnt % MOD)\n}\n\nfn main() -> io::Result<()> {\n let mut io = IO::new();\n\n //for _ in 0..tc {\n solve(&mut io)\n //}\n //Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "3e0e4b2af42c4a0e2fdb94d04f7922c2", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE.rotate_right(1) >> self.leading_zeros() } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn set_max(&mut self, v: T) -> bool;\n fn set_min(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for T {\n fn set_max(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn set_min(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { r.wrapping_add(m) }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\n\nfn mod_factorials(maxn: usize) -> Vec {\n let mut res = vec![ModInt::default(); maxn+1];\n res[0] = 1.into();\n for i in 1..=maxn {\n res[i] = res[i-1] * i\n }\n return res;\n}\n\nstruct ModCombinatorics {\n factorials: Vec,\n inv_factorials: Vec\n}\nimpl ModCombinatorics {\n fn new(maxn: usize) -> Self {\n let factorials = mod_factorials(maxn);\n let mut inv = vec![ModInt::default(); maxn+1];\n inv[maxn] = factorials[maxn].inv();\n for i in (1..=maxn).rev() {\n inv[i-1] = inv[i] * i;\n }\n Self { factorials, inv_factorials: inv }\n }\n #[inline]\n fn factorial(&self, n: usize) -> ModInt { self.factorials[n] }\n #[inline]\n fn inv_factorial(&self, n: usize) -> ModInt { self.inv_factorials[n] }\n fn P(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(n-k) }\n }\n fn C(&self, n: usize, k: usize) -> ModInt {\n if k > n { ModInt::raw(0) } else { self.factorial(n) * self.inv_factorial(k) * self.inv_factorial(n-k) }\n }\n\n // multi-choose, be sure to adjust maxn accordingly\n fn M(&self, n: usize, k: usize) -> ModInt {\n if k == 0 { 1.into() } else { self.C(n + k - 1, k) }\n }\n}\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n \n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let x = read!(usize);\n\n let mc = ModCombinatorics::new(n);\n\n let pow = veci!(x+1, i: ModInt::pow_vec(mi(i), n));\n\n struct Dp<'a> {\n D: Vec>>>,\n f: &'a dyn Fn(&Dp, usize, usize) -> ModInt\n }\n\n let dp = Dp {\n D: vec![vec![Cell::new(None); x+1]; n+1],\n f: &|dp, i, j| {\n match dp.D[i][j].get() {\n Some(x) => x,\n None => {\n let res = if j < i { pow[j][i] - pow[j-1][i] } else {\n (2..=i).map(|k| (dp.f)(dp, k, j-(i-1)) * mc.C(i, k) * pow[i-1][i-k]).sum()\n };\n\n dp.D[i][j].set(Some(res));\n res\n }\n }\n }\n };\n\n\n let mut ans = mi(0);\n for i in 1..=x { ans += (dp.f)(&dp, n, i); }\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "48f07b9f1a8b823155aeb6ce98e9f2c4", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::*;\n\nfn main () {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let a: i32 = buf.trim().parse().unwrap();\n let out = if a % 2 == 0 { 0 } else { 1 };\n println!(\"{}\", out);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "f5e1d1052675e53bdab001b258a14949", "src_uid": "78e64fdbf59c5ce89d0f0a1d0591f795", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim().to_owned()\n}\n\nfn reads() -> Vec\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n read_line()\n .split_whitespace()\n .map(|w| w.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let n: i32 = reads()[0];\n println!(\"{}\", n % 2);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "2645a3bc4fc4a08ab3a880e2158add33", "src_uid": "78e64fdbf59c5ce89d0f0a1d0591f795", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n \n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input);\n\n\tlet input: i32 = input.trim().parse().unwrap();\n\n\tif input % 2 == 1 {\n\tprintln!(\"1\");\n\t}\n\telse {\n\t\tprintln!(\"0\")\n\t};\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "4de8c0eda1c3c2836d7ce6f70057657f", "src_uid": "78e64fdbf59c5ce89d0f0a1d0591f795", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let arr : Vec = s.split_whitespace().map(|s| s.parse().unwrap()).collect();\n let (mut x, mut y, mut cnt) = (arr[0], arr[1], 0);\n loop {\n cnt += 1;\n x *= 3;\n y *= 2;\n if x > y {\n println!(\"{}\", cnt);\n break;\n }\n };\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e8fa5b3d24a07b05629e47d7511838f7", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::cmp::{min, max};\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Scanner {\n Scanner {\n reader: reader,\n buffer: Vec::new(),\n }\n }\n\n /// Use \"turbofish\" syntax next::() to select data type of next token.\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n\n pub fn next_vec(&mut self, len: usize) -> Vec\n where\n T::Err: ::std::fmt::Debug,\n {\n (0..len).map(|_| self.next::()).collect::>()\n }\n}\n\nfn main1() {\n let stdin = io::stdin();\n let mut input = Scanner::new(stdin.lock());\n let mut a = input.next::();\n let mut b = input.next::();\n let mut answer = 0;\n while a <= b {\n a *= 3;\n b *= 2;\n answer += 1;\n }\n println!(\"{}\", answer);\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "49298c88ec657a889744b52e1620a23d", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut reader = scanner::TokenReader::new();\n let mut a: usize = reader.next();\n let mut b: usize = reader.next();\n let mut n = 0;\n\n while a <= b {\n a *= 3;\n b *= 2;\n n += 1;\n }\n println!(\"{}\", n);\n}\n\n// ---------- Begin Scanner ----------\n#[allow(dead_code)]\nmod scanner {\n use std::fmt::Debug;\n use std::str::FromStr;\n\n pub struct TokenReader {\n reader: std::io::Stdin,\n tokens: Vec,\n index: usize,\n }\n\n impl TokenReader {\n pub fn new() -> Self {\n Self {\n reader: std::io::stdin(),\n tokens: Vec::new(),\n index: 0,\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index += 1;\n self.tokens[self.index - 1].parse().unwrap()\n }\n\n pub fn vector(&mut self) -> Vec\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index = self.tokens.len();\n self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()\n }\n\n pub fn load_next_line(&mut self) {\n let mut line = String::new();\n self.reader.read_line(&mut line).unwrap();\n\n self.tokens = line.split_whitespace().map(String::from).collect();\n self.index = 0;\n }\n }\n}\n// ---------- End Scanner ----------\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8fdb11b0bd68e23412ba73b4eddd4f24", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut buf = String::new();\n\n std::io::stdin().read_line(&mut buf).unwrap();\n\n let mut bears_weight: Vec = buf\n .split_ascii_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let mut count = 0;\n while bears_weight[0] <= bears_weight[1] {\n count += 1;\n bears_weight[0] *= 3;\n bears_weight[1] *= 2;\n }\n println!(\"{}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f32eabee6043608f951a4f1e6829fcc7", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n \n let mut l: u64 = scan.next();\n let mut b: u64 = scan.next();\n \n for i in 1..\n {\n l *= 3u64;\n b *= 2u64;\n if l > b\n {\n writeln!(out, \"{}\", i).ok();\n break;\n }\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f678b99aacfa072477f0cb354ec90d3e", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n let a;\n let b;\n\n unsafe {\n let input: Vec<_> = scan\n .next()\n .split_ascii_whitespace()\n .map(|s| s.parse::().unwrap())\n .collect();\n\n let ptr = input.as_ptr();\n a = *ptr as f64;\n b = *ptr.offset(1) as f64;\n }\n\n writeln!(\n out,\n \"{}\",\n ((a.ln() - b.ln()) / 0.405465108108164f64).abs() as i32 + 1\n )\n .ok();\n}\n\npub struct Scanner {\n reader: T,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self { reader }\n }\n\n pub fn next(&mut self) -> String {\n loop {\n let mut input = String::new();\n self.reader.read_line(&mut input).unwrap();\n\n return input.trim().to_owned();\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1ba0db74392cb306d2be556894eb4a00", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_vec() -> Vec {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer\n .split_whitespace()\n .map(|brother|\n brother.parse::().expect(\"Error\"))\n .collect()\n}\n\nfn main() {\n let (mut a, mut b): (u16, u16) = {\n let brothers: Vec = read_vec();\n (brothers[0], brothers[1])\n };\n\n let mut years: u8 = 0;\n while a <= b {\n a *= 3;\n b *= 2;\n years += 1;\n }\n\n println!(\"{}\", years);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "220a19aa30eb665931d220998b0e3614", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\n\nfn exec() {\n let mut sc = Scanner::new();\n let mut a: u64 = sc.ne();\n let mut b: u64 = sc.ne();\n for i in 0..100 {\n a *= 3;\n b *= 2;\n if a > b {\n println!(\"{}\", i + 1);\n break;\n }\n }\n}\n\nfn main() {\n const STACK: usize = 16 * 1024 * 1024;\n let _ = std::thread::Builder::new()\n .stack_size(STACK)\n .spawn(|| { exec(); })\n .unwrap()\n .join()\n .unwrap();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => {\n panic!(\"parse error, {:?}\",\n String::from_utf8(self.buf[l..r].to_owned()))\n }\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "93a119e39c7518c68bdbeb653cc31888", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\n\nconst MOD: i64 = 1_000_000_007;\n\nfn power(a: i64, p: i64) -> i64 {\n if p == 0 {\n return 1;\n }\n let mut res = power(a, p / 2);\n res = (res * res) % MOD;\n if p % 2 != 0 {\n res = (res * a) % MOD;\n }\n res\n}\n\nfn solve(n: i64, m: i64) -> i64 {\n power((power(2, m) + MOD - 1) % MOD, n)\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let mut handle = stdin.lock();\n let mut buf = String::new();\n handle.read_line(&mut buf).unwrap();\n let mut it = buf.split_whitespace();\n let (n, m): (i64, i64) = (\n it.next().unwrap().parse().unwrap(),\n it.next().unwrap().parse().unwrap(),\n );\n println!(\"{}\", solve(n, m));\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_power() {\n assert_eq!(power(0, 0), 1);\n assert_eq!(power(2, 1), 2);\n assert_eq!(power(2, 2), 4);\n assert_eq!(power(2, 3), 8);\n }\n\n #[test]\n fn test_solve() {\n assert_eq!(solve(1, 3), 7);\n assert_eq!(solve(2, 2), 9);\n assert_eq!(solve(1_000_000_000, 1_000_000_000), 751201557);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "30267f19a59012d156a5af38573d4c74", "src_uid": "71029e5bf085b0f5f39d1835eb801891", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\n/* \nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n*/\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n pub fn comb(n: u32, k: u32) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n let k = std::cmp::min(k, n - k);\n let mut nu = ModInt::one();\n let mut de = ModInt::one();\n for i in 0..k {\n nu *= ModInt(n - i);\n de *= ModInt(i + 1);\n }\n nu * de.inv()\n }\n}\n\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end ModInt ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: u32,\n m: u32,\n }\n let ans = (ModInt(2).pow(m) - ModInt(1)).pow(n);\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "dfacd204f106bc2814e6fae61026d806", "src_uid": "71029e5bf085b0f5f39d1835eb801891", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::cmp;\n\nstatic M: i64 = 1000_000_007;\n\nfn exponentiate( base: i64, mut exponent: i64 ) -> i64 {\n let mut ans = 1;\n let mut accum = base;\n while exponent != 0 {\n if exponent & 1 != 0 {\n ans = (ans * accum) % M;\n }\n accum = (accum * accum) % M;\n exponent = exponent >> 1;\n }\n ans\n}\n\nfn main() -> () {\n \n let mut buffer = String::new();\n \n {\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_to_string(&mut buffer).expect(\"stdin\");\n }\n \n let mut arr : Vec<_> = buffer.split_whitespace().map(|x| x.parse::().unwrap() ).collect();\n\n let n = arr[0];\n let m = arr[1];\n\n let ans = exponentiate((exponentiate(2,m)-1+M)%M,n);\n \n println!(\"{}\",ans);\n\n}\n\n#[test]\nfn test(){\n assert_eq!(27, exponentiate(3,3));\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "77036decb7b602efc385dddde7cb6218", "src_uid": "71029e5bf085b0f5f39d1835eb801891", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\nuse std::io::{StdinLock, stdin, BufRead};\nuse std::collections::*;\nuse std::cmp::*;\n\nfn scan_helper(lock : &mut StdinLock) -> String {\n let mut buffer = String::new();\n lock.read_line(&mut buffer).ok();\n buffer\n}\n\nmacro_rules! scan {\n ($lock:ident, $t:ty) => ({\n scan_helper(&mut $lock).split_whitespace()\n .next().unwrap()\n .parse::<$t>().unwrap()\n });\n ($lock:ident, $($t:ty),+) => ({\n let buffer = scan_helper(&mut $lock);\n let mut iter = buffer.split_whitespace();\n ($(\n {\n iter.next().unwrap()\n .parse::<$t>().unwrap()\n },\n )+)\n })\n}\n\nmacro_rules! scan_iter {\n ($lock:ident, $t:ty) => ({\n scan_helper(&mut $lock).split_whitespace()\n .map(|x| x.parse::<$t>().expect(\"scan_iter\"))\n .collect()\n })\n}\n\ntrait Ext {\n fn idx(&self) -> usize;\n fn num(&self) -> i64;\n}\n\nmacro_rules! ext {\n ($t:ty) => (\n impl Ext for $t {\n #[inline]\n fn idx(&self) -> usize {\n *self as usize\n }\n\n #[inline]\n fn num(&self) -> i64 {\n *self as i64\n }\n }\n )\n}\next!(i64);\next!(usize);\n\nmacro_rules! derive_regular {\n ($t:ty) => (\n impl Ord for $t {\n fn cmp(&self, other : &$t) -> Ordering {\n self.partial_cmp(other).unwrap()\n }\n }\n impl PartialEq for $t {\n fn eq(&self, other : &$t) -> bool {\n self.cmp(other) == Ordering::Equal\n }\n }\n impl Eq for $t {}\n )\n}\n\nfn main() {\n let stdin = stdin();\n let mut s = stdin.lock();\n let x : Vec<_> = scan!(s, String).into_bytes();\n let mut j = x.len() - 1;\n\n while j > 0 && x[j] == b'0' {\n j -= 1;\n }\n\n let mut i = 0;\n let mut result = true;\n while i < j {\n if x[i] != x[j] {\n result = false;\n break;\n }\n i += 1;\n j -= 1;\n }\n\n if result {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "071ee5e933428d5d2de8046109072e99", "src_uid": "d82278932881e3aa997086c909f29051", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec(s: String) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n s.split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let x = get_line().trim().to_string();\n\n let x: String = x.chars().rev().skip_while(|&c| c == '0').collect();\n\n let ans = x.chars().zip(x.chars().rev()).all(|(c1, c2)| c1 == c2);\n\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n };\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "71f3e923f8e56e584a424108c606d1c5", "src_uid": "d82278932881e3aa997086c909f29051", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{min, max};\nuse std::f64::consts::*;\nuse std::mem::swap;\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\n#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone)]\nstruct Pair(A, B);\n\nstruct Input\n{\n\tbuffer: Buf\n}\n\nimpl Input\n{\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\t#[inline]\n\tfn read_int(&mut self) -> i32 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_long(&mut self) -> i64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_usize(&mut self) -> usize {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_double(&mut self) -> f64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n}\nmacro_rules! read {\n () => {};\n\t($inf:ident,$($t:ty),*) => ({($({$inf.read_word().parse::<$t>().expect(\"Parsing error\")}),*)});\n}\nfn gcd + Copy + Clone>(x: T, y: T) -> T {\n\tlet (mut a, mut b) = (x, y);\n\twhile b > T::from(0) {\n\t\ta %= b;\n\t\tswap(&mut a, &mut b);\n\t}\n\ta\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input {\n\t\t\t\tbuffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\"))\n\t\t\t};\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(stdin()) };\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\nfn solve(inf: &mut Input, ouf: &mut Output)\n{\n\tlet mut x = read!(inf,usize);\n\twhile x % 10 == 0 {\n\t\tx /= 10;\n\t}\n\tlet mut y = format!(\"{}\", x).as_bytes().to_vec();\n\ty.reverse();\n\tif format!(\"{}\", x) == String::from_utf8(y).unwrap() {\n\t\twriteln!(ouf, \"YES\");\n\t} else {\n\t\twriteln!(ouf, \"NO\");\n\t}\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "05dcfd1c205a2f21e116773228025ba4", "src_uid": "d82278932881e3aa997086c909f29051", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n#[allow(dead_code)]\nfn main() {\n let mut input = \"\".split_ascii_whitespace();\n let mut read = || loop {\n if let Some(word) = input.next() {\n break word;\n }\n input = {\n let mut input = \"\".to_owned();\n io::stdin().read_line(&mut input).unwrap();\n if input.is_empty() {\n panic!(\"reached EOF\");\n }\n Box::leak(input.into_boxed_str()).split_ascii_whitespace()\n };\n };\n macro_rules! read(($ty:ty) => (read().parse::<$ty>().unwrap()));\n\n let n = read!(usize);\n let m = read!(usize);\n let mut sa = vec![\"\".to_string(); 0];\n for _ in 0..n {\n sa.push(read!(String));\n }\n let mut ca = vec![vec![' '; 0]; n];\n for i in 0..n {\n ca[i] = sa[i].chars().collect::>();\n }\n let mut ba = vec![vec![false; m]; n];\n\n for i in 0..n {\n for j in 0..m {\n if ca[i][j] != 'P' {\n continue;\n }\n if i > 0 && ca[i - 1][j] == 'W' {\n ba[i - 1][j] = true;\n }\n if i < n - 1 && ca[i + 1][j] == 'W' {\n ba[i + 1][j] = true;\n }\n if j > 0 && ca[i][j - 1] == 'W' {\n ba[i][j - 1] = true;\n }\n if j < m - 1 && ca[i][j + 1] == 'W' {\n ba[i][j + 1] = true;\n }\n }\n }\n\n let mut r = 0;\n for i in 0..n {\n for j in 0..m {\n if ba[i][j] {\n r += 1;\n }\n }\n }\n\n println!(\"{}\", r);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "a85ef33bdcffe35ef018dee206261046", "src_uid": "969b24ed98d916184821b2b2f8fd3aac", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::char::*;\n#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\n#[allow(unused_macros)]\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\n#[allow(unused_macros)]\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n#[derive(PartialEq, PartialOrd)]\npub struct Total(pub T);\nimpl Eq for Total {}\nimpl Ord for Total { fn cmp(&self, other: &Total) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap() }}\n\n#[allow(dead_code)]\nconst MAX:usize = 100006;\n#[allow(dead_code)]\nconst MOD:i64 = 1e9 as i64 + 7;\n\n\n#[allow(dead_code)]\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\n#[allow(dead_code)]\nfn read_vec() -> Vec {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().split_whitespace()\n .map(|e| e.parse().ok().unwrap()).collect()\n}\n\n\n#[allow(unused_imports)]\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nuse std::hash::Hash;\nfn inc(map:&mut BTreeMap, key:T) {\n let count = map.entry(key).or_insert(0);\n *count += 1;\n}\n\nfn main() {\n input!{n:usize, s:chars};\n let mut s = s;\n\n let mut ans = 0;\n\n loop {\n if s.len() == 1 { break; }\n let mut f = vec![];\n for i in 0..s.len() {\n if i==0 {\n if s[i] as u8 == s[i+1] as u8 + 1 {\n f.push((s[i],i));\n }\n }\n else if i == s.len()-1 {\n if s[i] as u8 == s[i-1] as u8 + 1 {\n f.push((s[i],i));\n }\n }\n else {\n if s[i] as u8 == s[i-1] as u8 +1 {\n f.push((s[i],i));\n }\n if s[i] as u8 == s[i+1] as u8 + 1 {\n f.push((s[i],i));\n }\n }\n }\n f.sort();\n f.reverse();\n //debug!(f);\n if f.len() == 0 { break; }\n let rem = f[0].1;\n let mut t = vec![];\n for i in 0..s.len() {\n if i != rem {\n t.push(s[i]);\n }\n }\n //debug!(t);\n ans += 1;\n s = t;\n }\n\n println!(\"{}\", ans);\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "strings", "constructive algorithms"], "code_uid": "18aaaea424e876e3e2f86be045f9e61a", "src_uid": "9ce37bc2d361f5bb8a0568fb479b8a38", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\n\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn can_remove(index: usize, phrase: &mut Vec) -> bool {\n let phrase_length = phrase.len();\n let (current, previous, next) = (\n phrase[index] as i32,\n if index == 0 {\n phrase[index] as i32\n } else {\n phrase[index - 1] as i32\n },\n if index == (phrase_length - 1) {\n phrase[index] as i32\n } else {\n phrase[index + 1] as i32\n },\n );\n (current as i32 - next as i32) == 1 || (current as i32 - previous as i32) == 1\n}\n\nfn try_remove_next<'a>(phrase: &mut Vec) -> bool {\n let mut bigger = 'a' as i32 - 1;\n let mut candidate: usize = 101;\n for (i, charac) in phrase.clone().iter().enumerate() {\n if *charac as i32 > bigger && can_remove(i, phrase) {\n candidate = i;\n bigger = *charac as i32;\n }\n }\n if candidate == 101 {\n false\n } else {\n phrase.remove(candidate);\n true\n }\n}\nfn main() {\n let mut scan = Scanner::default();\n let _ = scan.next::();\n let mut stra: Vec = scan.next::().chars().collect();\n let chars: &mut Vec = &mut stra.as_mut();\n let mut totals = 0;\n loop {\n let removed = try_remove_next(chars);\n if removed {\n totals += 1;\n } else {\n break;\n }\n }\n println!(\"{}\", totals)\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "strings", "constructive algorithms"], "code_uid": "4becbe3a716f3e432bc26b5736735f1f", "src_uid": "9ce37bc2d361f5bb8a0568fb479b8a38", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n let _ = lines.next().unwrap().unwrap().parse::().unwrap();\n let s: String = lines.next().unwrap().unwrap();\n println!(\"{}\", s.len() - solve(s, 'a').len());\n}\n\npub fn solve(s: String, ch: char) -> String {\n if &s == \"\" {\n return \"\".to_string();\n }\n let mut result = 0;\n let segments = s.split(ch).map(|s| s.to_string()).collect::>();\n let mut new_string = String::new();\n for segment in segments.iter().cloned() {\n new_string += &solve(segment, (ch as u8 + 1) as char);\n new_string += &ch.to_string();\n }\n new_string.pop();\n\n let pattern1 = ch.to_string() + &((ch as u8 + 1) as char).to_string();\n let pattern2 = ((ch as u8 + 1) as char).to_string() + &ch.to_string();\n while {\n let len = new_string.len();\n new_string = new_string.replace(&pattern1, &ch.to_string());\n new_string = new_string.replace(&pattern2, &ch.to_string());\n len != new_string.len()\n } {}\n //println!(\"{} - {}\", s, new_string);\n\n new_string\n}", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "strings", "constructive algorithms"], "code_uid": "db04659f78ac8d172ac7dca34fa44fb9", "src_uid": "9ce37bc2d361f5bb8a0568fb479b8a38", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\n\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn can_remove(index: usize, phrase: &mut Vec) -> bool {\n let phrase_length = phrase.len();\n let (current, previous, next) = (\n phrase[index] as i32,\n if index == 0 {\n phrase[index] as i32\n } else {\n phrase[index - 1] as i32\n },\n if index == (phrase_length - 1) {\n phrase[index] as i32\n } else {\n phrase[index + 1] as i32\n },\n );\n (current as i32 - next as i32) == 1 || (current as i32 - previous as i32) == 1\n}\n\nfn try_remove_next<'a>(phrase: &mut Vec) -> bool {\n let mut bigger = 'a' as i32 - 1;\n let mut candidate: usize = 101;\n for (i, charac) in phrase.clone().iter().enumerate() {\n if *charac as i32 > bigger && can_remove(i, phrase) {\n candidate = i;\n bigger = *charac as i32;\n }\n }\n if candidate == 101 {\n false\n } else {\n phrase.remove(candidate);\n true\n }\n}\nfn main() {\n let mut scan = Scanner::default();\n let _ = scan.next::();\n let mut stra: Vec = scan.next::().chars().collect();\n let chars: &mut Vec = &mut stra.as_mut();\n let mut totals = 0;\n loop {\n let removed = try_remove_next(chars);\n if removed {\n totals += 1;\n } else {\n break;\n }\n }\n println!(\"{}\", totals)\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "strings", "constructive algorithms"], "code_uid": "9d5002a774eb9d32b37fe1687e6019dc", "src_uid": "9ce37bc2d361f5bb8a0568fb479b8a38", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let n = scan.next::();\n let mut s = scan.next::().into_bytes();\n let mut ans = 0;\n loop {\n let mut ord = Vec::with_capacity(s.len());\n for (pos, val) in s.iter().enumerate() {\n ord.push((val, pos));\n }\n ord.sort();\n ord.reverse();\n \n let mut del_idx = -1;\n for (_, (_, pos)) in ord.iter().enumerate() {\n let i = *pos as i32;\n if (i > 0 && s[(i - 1) as usize] == s[i as usize] - 1)\n || (i < s.len() as i32 - 1 && s[(i + 1) as usize] == s[i as usize] - 1)\n {\n del_idx = i;\n break;\n }\n }\n if del_idx == -1 {\n break;\n }\n s.remove(del_idx as usize);\n ans += 1;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "strings", "constructive algorithms"], "code_uid": "a748799c1ecb40c3284b92e1def4f23e", "src_uid": "9ce37bc2d361f5bb8a0568fb479b8a38", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{Ordering};\n\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\n\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n\n#[allow(unused_macros)]\nmacro_rules! min {\n ($x: expr) => ($x);\n ($x: expr, $($z: expr),+) => {{\n std::cmp::min($x, min!($($z),*))\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! max {\n ($x: expr) => ($x);\n ($x: expr, $($z: expr),+) => {{\n std::cmp::max($x, max!($($z),*))\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! get { \n ([$t: ty]) => { \n { \n let mut line = String::new(); \n stdin().read_line(&mut line).unwrap(); \n line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::>()\n }\n };\n ([$t: ty];$n: expr) => {\n (0..$n).map(|_|get!([$t])).collect::>()\n };\n ($t: ty) => {\n {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t: ty),*) => {\n { \n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n ($(iter.next().unwrap().parse::<$t>().unwrap(),)*)\n }\n };\n ($t: ty; $n: expr) => {\n (0..$n).map(|_|get!($t)).collect::>()\n };\n ($($t: ty),*; $n: expr) => {\n (0..$n).map(|_|get!($($t),*)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*).unwrap();\n }\n}\n\nconst BIG_STACK_SIZE: bool = true;\n\n#[allow(dead_code)]\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\n\n#[derive(Eq, PartialEq, Clone, Debug)]\npub struct Rev(pub T);\nimpl PartialOrd for Rev {\n fn partial_cmp(&self, other: &Rev) -> Option {\n other.0.partial_cmp(&self.0)\n }\n}\nimpl Ord for Rev {\n fn cmp(&self, other: &Rev) -> Ordering {\n other.0.cmp(&self.0)\n }\n}\n\nfn solve() {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n let n = get!(usize);\n let mut s = get!(String).chars().map(|e| e as usize - 'a' as usize).collect::>();\n\n loop {\n let mut flag = false;\n let mut j = 0;\n let mut c = 0;\n for i in 0..s.len() {\n if (i>0 && s[i-1]+1==s[i]) || (i = s.trim().bytes().collect();\n let mut count: u32 = 0;\n if s.len() != 1 {\n for i in 0..s.len() {\n let mut b = false;\n let mut pos = 0;\n let mut max = 0;\n if (s[0] as i16 - s[1] as i16 == 1) {\n max = s[0];\n b = true;\n }\n for j in 1..s.len() - 1 {\n if (s[j] as i16 - s[j - 1] as i16 == 1 || s[j] as i16 - s[j + 1] as i16 == 1) && (s[j] > max) {\n pos = j;\n max = s[j];\n b = true;\n }\n }\n if (s[s.len() - 1] as i16 - s[s.len() - 2] as i16 == 1) && (s[s.len() - 1] > max) {\n pos = s.len() - 1;\n max = s[s.len() - 1];\n b = true;\n }\n if b {\n count += 1;\n s.remove(pos);\n if s.len() == 1 {\n break;\n }\n } else { break; }\n }\n }\n println!(\"{}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "strings", "constructive algorithms"], "code_uid": "2b48ff5699e9c28844e47a1e5b6786f0", "src_uid": "9ce37bc2d361f5bb8a0568fb479b8a38", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\n#[derive(Default)]\nstruct Scanner {\n buf: Vec,\n}\n\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buf = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let _n = scan.next::();\n let mut s: Vec = scan.next::().chars().collect();\n let mut ans = 0;\n loop {\n let mut ord: Vec<(char, usize)> = s.iter().enumerate().map(|(i, &c)| (c, i)).collect();\n ord.sort();\n let mut del_idx = None;\n for &(c, i) in ord.iter().rev() {\n let pc = ((c as u8) - 1) as char;\n if (i > 0 && s[i - 1] == pc) || (i < s.len() - 1 && s[i + 1] == pc) {\n del_idx = Some(i);\n break;\n }\n }\n if let Some(idx) = del_idx {\n s.remove(idx);\n ans += 1;\n } else {\n break;\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "strings", "constructive algorithms"], "code_uid": "22a97fc053af42f8386e7b16a858885f", "src_uid": "9ce37bc2d361f5bb8a0568fb479b8a38", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//---------- begin union_find ----------\n#[allow(dead_code)]\nmod union_find {\n pub struct UF {\n p: Vec,\n }\n impl UF {\n pub fn new(n: usize) -> UF {\n UF {p: vec![-1; n] }\n }\n pub fn init(&mut self) {\n for p in self.p.iter_mut() {\n *p = -1;\n }\n }\n pub fn root(&self, mut x: usize) -> usize {\n while self.p[x] >= 0 {\n x = self.p[x] as usize;\n }\n x\n }\n pub fn same(&self, x: usize, y: usize) -> bool {\n self.root(x) == self.root(y)\n }\n pub fn unite(&mut self, x: usize, y: usize) -> Option<(usize, usize)> {\n let mut x = self.root(x);\n let mut y = self.root(y);\n if x == y {\n return None;\n }\n if self.p[x] > self.p[y] {\n std::mem::swap(&mut x, &mut y);\n }\n self.p[x] += self.p[y];\n self.p[y] = x as i32;\n Some((x, y))\n }\n pub fn parent(&self, x: usize) -> Option {\n let p = self.p[x];\n if p >= 0 {\n Some(p as usize)\n } else {\n None\n }\n }\n pub fn get_size(&self, x: usize) -> usize {\n let r = self.root(x);\n (-self.p[r]) as usize\n }\n }\n}\n//---------- end union_find ----------\n\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n e: [(usize1, usize1); m],\n }\n let mut e = e;\n for e in e.iter_mut() {\n if e.1 < e.0 {\n *e = (e.1, e.0);\n }\n }\n e.sort();\n let mut deg = vec![0; n];\n for &(a, b) in e.iter() {\n deg[a] += 1;\n deg[b] += 1;\n }\n let mut ans = vec![n; n];\n for i in 0..n {\n if deg[i] == n - 1 {\n ans[i] = 1;\n }\n }\n let mut u = union_find::UF::new(n);\n for &(a, b) in e.iter() {\n if deg[a] != n - 1 && deg[b] != n - 1 {\n u.unite(a, b);\n }\n }\n let mut id = 0;\n let mut add = 2;\n for i in 0..n {\n if deg[i] != n - 1 && i == u.root(i) {\n ans[i] = id;\n id += add;\n add = 1;\n }\n }\n if id > 3 {\n println!(\"No\");\n return;\n }\n for i in 0..n {\n for j in (i + 1)..n {\n let x = u.root(i);\n let y = u.root(j);\n if ans[x] == ans[y] || ans[x] == ans[y] + 1 || ans[x] + 1 == ans[y] {\n if e.binary_search(&(i, j)).is_err() {\n println!(\"No\");\n return;\n }\n }\n }\n }\n println!(\"Yes\");\n let mut s = String::new();\n let op: Vec = \"abc\".chars().collect();\n for i in 0..n {\n s.push(op[ans[u.root(i)]]);\n }\n println!(\"{}\", s);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "fc7290d7c3c248158cf0aa9bd61357b5", "src_uid": "e71640f715f353e49745eac5f72e682a", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n use std::io::prelude::*;\n use std::io;\n\n let mut input = String::new();\n io::stdin().read_to_string(&mut input).unwrap();\n\n let necklace: Vec<_> = input.trim().chars().map(|c| {\n match c {\n '-' => Elem::Link,\n 'o' => Elem::Pearl,\n _ => panic!(\"Invalid input\"),\n }\n }).collect();\n\n let link_pearl_sums = necklace.iter().fold((0, 0), |acc, &e| {\n match e {\n Elem::Link => (acc.0 + 1, acc.1),\n Elem::Pearl => (acc.0, acc.1 + 1),\n }\n });\n\n let ans = link_pearl_sums.1 == 0 || link_pearl_sums.0 % link_pearl_sums.1 == 0;\n\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n#[derive(Clone, Copy)]\nenum Elem {\n Link,\n Pearl\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a842b19574857d4acf6217475a2624f7", "src_uid": "6e006ae3df3bcd24755358a5f584ec03", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get!(i64));\n ($t:ty) => (get().parse::<$t>().unwrap());\n }\n \n let n = get().as_bytes();\n \n let mut p = 0;\n let mut s = 0;\n for &c in n {\n if c == b'o' {\n p += 1;\n } else {\n s += 1;\n }\n }\n \n if p < 2 || s == 0 {\n println!(\"YES\");\n return;\n }\n \n if s % p == 0 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n \n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "0ffb60a1fed53d72fb54abbe28e5c71a", "src_uid": "6e006ae3df3bcd24755358a5f584ec03", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! debug_println {\n ($( $args:expr ),*) => { if cfg!(debug_assertions) { println!( $( $args ),* ); }}\n}\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let (l, mut p) = buf.chars().fold((0, 0), |mut cnt, v| {\n match v {\n '-' => cnt.0 += 1,\n 'o' => cnt.1 += 1,\n _ => (),\n }\n cnt\n });\n if p == 0 {\n p = 1\n }\n debug_println!(\"{:?}\", (l, p));\n println!(\"{}\", if l % p == 0 { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "0c370c6e2dccb3b742955dbc2412eebc", "src_uid": "6e006ae3df3bcd24755358a5f584ec03", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub struct Scanner {\n buffer: Vec\n}\n\nimpl Scanner {\n pub fn new() -> Scanner {\n Scanner { buffer: Vec::new() }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn calculate_divs(mut x: u32) -> Vec {\n let mut divs: Vec = Vec::new();\n for p in 2..100_000 {\n if x % p == 0 {\n divs.push(p);\n while x % p == 0 {\n x /= p;\n }\n }\n }\n if x > 1 {\n divs.push(x);\n }\n return divs;\n}\n\nconst MOD: u64 = 1_000_000_007;\n\nfn bin_pow(mut a: u64, mut n: u64) -> u64 {\n let mut x: u64 = 1;\n while n > 0 {\n if (n & 1) == 1 {\n x = x * a % MOD;\n }\n a = a * a % MOD;\n n >>= 1;\n }\n return x;\n}\n\nfn main() {\n let mut scan = Scanner::new();\n let x: u32 = scan.next();\n let n: u64 = scan.next();\n let divs: Vec = calculate_divs(x);\n\n let mut ans: u64 = 1;\n for &d in divs.iter() {\n let mut copy_n: u64 = n;\n let mut power: u64 = 0;\n loop {\n copy_n /= d as u64;\n if copy_n == 0 {\n break;\n }\n power += copy_n;\n }\n ans = ans * bin_pow(d as u64, power) % MOD;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "82a96fd02a35a2b026f128a533ef5300", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read,stdin};\n\nconst M: i128 = 1_000_000_007;\n \nfn main() {\n let mut buf = String::new();\n stdin().read_to_string(&mut buf).unwrap();\n let mut tok = buf.split_whitespace();\n let mut get = || tok.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i128));\n }\n \n let x = get!();\n let n = get!();\n \n let mut ps = vec![];\n let mut y = x;\n for i in 2 ..= x {\n if i * i > y {\n break;\n }\n if y % i != 0 {\n continue;\n }\n ps.push(i);\n while y % i == 0 {\n y /= i;\n }\n }\n if y > 1 {\n ps.push(y);\n }\n let mut ans = 1;\n for &p in ps.iter() {\n let mut es = vec![];\n let mut e = p;\n while e <= n {\n es.push(e);\n e *= p;\n }\n let mut t = 0;\n while let Some(e) = es.pop() {\n let c = n / e - t;\n ans = ans * pow(e, c) % M;\n t = n / e;\n }\n }\n println!(\"{}\", ans);\n}\n\nfn pow(a: i128, b: i128) -> i128 {\n if b == 0 {\n 1\n } else if b % 2 == 0 {\n pow(a * a % M, b / 2)\n } else {\n a * pow(a, b - 1) % M\n }\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "d30f0294c4cb8ce0424d5720d7323451", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nconst MOD: u64 = 1_000_000_007;\n\nfn mod_pow(r: u64, mut n: u64) -> u64 {\n let mut t = 1;\n let mut s = r % MOD;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s % MOD;\n }\n s = s * s % MOD;\n n >>= 1;\n }\n t\n}\n\nfn run() {\n input! {\n x: u64,\n n: u64,\n }\n let mut ans = 1;\n let mut x = x;\n let mut k = 2;\n while k * k <= x {\n if x % k == 0 {\n while x % k == 0 {\n x /= k;\n }\n let mut t = n;\n let mut c = 0;\n while t > 0 {\n c += t / k;\n t /= k;\n }\n ans = ans * mod_pow(k, c) % MOD;\n }\n k += 1;\n }\n if x > 1 {\n let mut t = n;\n let mut c = 0;\n while t > 0 {\n c += t / x;\n t /= x;\n }\n ans = ans * mod_pow(x, c) % MOD;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "697c148144087d1a42675d3d87a3a574", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{BufReader, BufWriter, stdin, stdout, Write};\nuse std::cmp::{min, max};\nuse std::collections::{VecDeque, HashMap, BTreeMap, HashSet, BTreeSet, BinaryHeap};\n\nconst m:i64 = 1000000007;\n\nfn pow(mut x:i64, mut p:i64) -> i64 {\n\tlet mut r:i64 = 1;\n\twhile p > 0 {\n\t\tif p % 2 == 1 {\n\t\t\tr = r * x % m;\n\t\t}\n\t\tx = x * x % m;\n\t\tp /= 2;\n\t}\n\treturn r;\n}\n\nfn main() {\n\tlet mut inp = my_input::default();\n\tlet out = &mut BufWriter::new(stdout());\n\tlet mut x:i64 = inp.scan::();\n\tlet n:i64 = inp.scan::();\n\tlet mut i = 2 as i64;\n\tlet mut ans = 1 as i64;\n\twhile i * i <= x {\n\t\tif x % i == 0 {\n\t\t\tlet mut cnt:i64 = 0;\n\t\t\tlet mut p:i64 = 1;\n\t\t\twhile p <= n / i {\n\t\t\t\tp *= i;\n\t\t\t\tcnt += n / p;\n\t\t\t}\n\t\t\tans = ans * pow(i, cnt) % m;\n\t\t}\n\t\twhile x % i == 0 {\n\t\t\tx /= i;\n\t\t}\n\t\ti += 1;\n\t}\n\tif x > 1 {\n\t\tlet mut cnt:i64 = 0;\n\t\tlet mut p:i64 = 1;\n\t\twhile p <= n / x {\n\t\t\tp *= x;\n\t\t\tcnt += n / p;\n\t\t}\n\t\tans = ans * pow(x, cnt) % m;\n\t}\n\twriteln!(out, \"{}\", ans);\n}\n\n#[derive(Default)]\nstruct my_input {\n\tbuffer: Vec\n}\n\nimpl my_input {\n\tfn scan(&mut self) -> T {\n\t\tloop {\n\t\t\tif let Some(token) = self.buffer.pop() {\n\t\t\t\treturn token.parse().ok().expect(\"Parsing Error\");\n\t\t\t}\n\t\t\tlet mut s = String::new();\n\t\t\tstdin().read_line(&mut s).expect(\"Reading Error\");\n\t\t\tself.buffer = s.split_whitespace().rev().map(String::from).collect();\n\t\t}\n\t}\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "5ce72b006a33139d160fcce8b44f46a3", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nconst MOD: u64 = 1000000007;\n\nfn mod_pow(mut a: u64, mut n: u64) -> u64 {\n let mut result = 1;\n while n != 0 {\n if n % 2 == 1 {\n result = result * a % MOD;\n }\n a = a * a % MOD;\n n /= 2;\n }\n return result;\n}\n\nfn calc(p: u64, mut n: u64) -> u64 {\n let mut cnt = 0;\n while n != 0 {\n n /= p;\n cnt += n;\n }\n return mod_pow(p, cnt);\n}\n\nfn solve(writer: &mut std::io::BufWriter) {\n let (mut x, n) = parse_line!(u64, u64);\n let mut result = 1;\n for i in 2..=x {\n if i * i > x {\n break;\n }\n if x % i == 0 {\n x /= i;\n while x % i == 0 {\n x /= i;\n }\n result = result * calc(i, n) % MOD;\n }\n }\n if x != 1 {\n result = result * calc(x, n) % MOD;\n }\n writeln!(writer, \"{}\", result).unwrap();\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "943c894b3321fba0adbda6ed76e92911", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead, Write};\nuse std::str::{self, FromStr, SplitAsciiWhitespace};\n\nfn main() {\n let stdin = io::stdin();\n solve(Scanner::new(stdin.lock()), io::stdout().lock());\n}\n\ntype Result = std::result::Result>;\n\nstruct Scanner<'a, R> {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'a>,\n}\n\nimpl Scanner<'_, R> {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n fn try_token(&mut self) -> Result\n where T: FromStr,\n ::Err: 'static + std::error::Error\n {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return Ok(token.parse()?);\n }\n self.buf_str.clear();\n let bytes_read = self.reader\n .read_until(b'\\n', &mut self.buf_str)?;\n if bytes_read == 0 {\n return Err(Box::new(io::Error::from(io::ErrorKind::UnexpectedEof)));\n }\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n ::std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n fn token(&mut self) -> T\n where T: FromStr,\n ::Err: 'static + std::error::Error\n {\n self.try_token().unwrap()\n }\n\n fn line_str(&mut self) -> &str {\n self.buf_str.clear();\n let bytes_read = self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n if bytes_read == 0 { panic!(\"unexpected EOF\"); }\n unsafe { str::from_utf8_unchecked(self.buf_str.as_slice()) }\n .trim()\n }\n\n fn line_token(&mut self) -> T {\n self.line_str()\n .parse().ok().expect(\"Failed parse\")\n }\n}\n\nconst MOD: u64 = 1e9 as u64 + 7;\n\nfn solve(mut scan: Scanner, mut output: W) {\n let x: u32 = scan.token();\n let n: u64 = scan.token();\n let mut answer: u64 = 1;\n prime_divs_distinct(x, |prime| {\n let prime = prime as u64;\n let mut k = 0;\n let mut factor = prime;\n while factor <= n {\n k += n / factor;\n factor = factor.saturating_mul(prime);\n }\n answer = (answer * mod_pow(prime, k)) % MOD;\n });\n writeln!(output, \"{}\", answer);\n}\n\nfn prime_divs_distinct(mut n: u32, mut prime: F)\n where F: FnMut(u32)\n{\n if n & 1 == 0 {\n prime(2);\n n >>= 1;\n }\n while n & 1 == 0 { n >>= 1; }\n let mut f = 3;\n let mut prev_f = 0;\n while f * f <= n {\n if n % f == 0 {\n if f != prev_f {\n prime(f);\n prev_f = f;\n }\n n /= f;\n } else {\n f += 2;\n }\n }\n if n != 1 && n != prev_f { prime(n); }\n}\n\nfn mod_pow(mut base: u64, mut exp: u64) -> u64 {\n let mut result = 1;\n base %= MOD;\n while exp > 0 {\n if exp & 1 == 1 {\n result = (result * base) % MOD;\n }\n exp >>= 1;\n base = (base * base) % MOD;\n }\n result\n}\n\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use helpers::t;\n\n #[test]\n fn example1() {\n t!(\"10 2\\n\", \"2\\n\");\n }\n\n #[test]\n fn example2() {\n t!(\"20190929 1605\\n\", \"363165664\\n\");\n }\n\n #[test]\n fn example3() {\n t!(\"947 987654321987654321\\n\", \"593574252\\n\");\n }\n\n #[test]\n fn bounds() {\n t!(\"999999937 999999999999999989\\n\", \"595408334\\n\");\n t!(\"1000000000 1000000000000000000\\n\", \"997440007\\n\");\n }\n\n #[test]\n fn prime_divisors() {\n let mut v = Vec::new();\n prime_divs_distinct(3 * 3 * 3 * 3 * 5 * 5 * 5 * 5 * 17, |p| v.push(p));\n assert_eq!(v, [3, 5, 17]);\n v.clear();\n prime_divs_distinct(1e9 as _, |p| v.push(p));\n assert_eq!(v, [2, 5]);\n v.clear();\n prime_divs_distinct(1e9 as u32 - 1, |p| v.push(p));\n assert_eq!(v, [3, 37, 333667]);\n v.clear();\n prime_divs_distinct(1e9 as u32 - 2, |p| v.push(p));\n assert_eq!(v, [2, 691, 723589]);\n v.clear();\n prime_divs_distinct(1e9 as u32 - 4, |p| v.push(p));\n assert_eq!(v, [2, 3, 83333333]);\n v.clear();\n prime_divs_distinct(1e9 as u32 - 10, |p| v.push(p));\n assert_eq!(v, [2, 3, 5, 11, 73, 101, 137]);\n v.clear();\n prime_divs_distinct(2, |p| v.push(p));\n assert_eq!(v, [2]);\n v.clear();\n prime_divs_distinct(1e9 as u32 - 63, |p| v.push(p));\n assert_eq!(v, [1e9 as u32 - 63]);\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "88469b09d0c8b59d0b38b18130d607ec", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let mut s = String::from(\"A\");\n s += readln!().as_ref();\n s += \"A\";\n let v : Vec = s.chars().enumerate().filter(|&(i,c)|c=='A' || c=='E' || c=='I' || c=='O' || c=='U' || c=='Y').map(|(i,c)|i).collect();\n let u : usize = v.iter().skip(1).zip(v.iter()).map(|(i,j)|i-j).max().unwrap();\n println!(\"{}\",u);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ef5fc101552da32e09eb26304fe5e651", "src_uid": "1fc7e939cdeb015fe31f3cf1c0982fee", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! parse_input {\n ($x:expr, $t:ident) => ($x.parse::<$t>().unwrap())\n}\n\nmacro_rules! parse_inputs {\n ($x:expr, $t:ident) => ($x.map(|s| s.parse::<$t>().unwrap()).collect::>())\n}\n\nmacro_rules! print_err {\n ($($arg:tt)*) => (\n {\n use std::io::Write;\n writeln!(&mut ::std::io::stderr(), $($arg)*).ok();\n }\n )\n}\n\nfn main() {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n let cs = input_line.trim().chars();\n\n let mut max = 0;\n let mut j = 0;\n for c in cs {\n j += 1;\n if c == 'A' || c == 'I' || c == 'U' || c == 'E' || c == 'O' || c == 'Y' {\n if max < j {\n max = j;\n }\n j = 0;\n }\n }\n j += 1;\n if max < j {\n max = j;\n }\n println!(\"{}\", max);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2e50db65f97b8c4fb5fec67e16b9de1a", "src_uid": "1fc7e939cdeb015fe31f3cf1c0982fee", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn is_vowel(c: char) -> bool {\n return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'Y';\n}\nfn _main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n let mut result = 0usize;\n let mut index = 0usize;\n for c in line.trim().chars() {\n index += 1;\n if is_vowel(c) {\n result = result.max(index);\n index = 0;\n }\n }\n index += 1;\n result = result.max(index);\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "dc34b6a3d679f17e29a80eefc6d5891f", "src_uid": "1fc7e939cdeb015fe31f3cf1c0982fee", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let m = \"AEIOUY\".chars().collect::>();\n let mut s = String::from(\"A\");\n s.push_str(input.sl());\n s.push_str(\"A\");\n let i = s.chars().enumerate().filter(|(_,c)| m.contains(c)).map(|(a,_)| a);\n let j = i.clone();\n let sol = i.skip(1).zip(j).map(|(a,b)| a - b).max().unwrap();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "dcce516e54bb95b3c1b348628f0889aa", "src_uid": "1fc7e939cdeb015fe31f3cf1c0982fee", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "mod io {\n use std::io::{self, BufRead};\n use std::str::{self, FromStr, SplitAsciiWhitespace};\n\n pub type Result = std::result::Result>;\n\n pub struct Scanner<'a, R> {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'a>,\n }\n\n impl Scanner<'_, R> {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n pub fn try_token(&mut self) -> Result\n where T: FromStr,\n ::Err: 'static + std::error::Error\n {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return Ok(token.parse()?);\n }\n self.buf_str.clear();\n let bytes_read = self.reader\n .read_until(b'\\n', &mut self.buf_str)?;\n if bytes_read == 0 {\n return Err(Box::new(io::Error::from(io::ErrorKind::UnexpectedEof)));\n }\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n ::std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn token(&mut self) -> T\n where T: FromStr,\n ::Err: 'static + std::error::Error\n {\n self.try_token().unwrap()\n }\n }\n}\n\nuse std::io::{stdin, stdout, BufRead, Write};\nuse io::Scanner;\n\nfn main() {\n let stdin = stdin();\n solve(Scanner::new(stdin.lock()), stdout().lock());\n}\n\nconst M: u64 = 1e9 as u64 + 7;\n\nfn solve(mut scan: Scanner, mut output: W) {\n let n: u64 = scan.token();\n let k: u64 = scan.token();\n let k_1 = k - 1;\n let kp3 = mpow(k_1, n);\n let mut sum = mpow((mpow(k, n) + (M - kp3)) % M, n);\n let mut bcf = 1;\n let mut kp2 = 1;\n for i in 1..=n {\n bcf = (n - i + 1) * mpow(i, M - 2) % M * bcf % M;\n let kp1 = mpow(k, n - i);\n kp2 = kp2 * k_1 % M;\n sum = (sum + mpow(M - 1, i & 1) * bcf % M * mpow((kp1 * kp2 % M + (M - kp3)) % M, n) % M) % M;\n }\n writeln!(output, \"{}\", sum).unwrap();\n}\n\npub fn mpow(mut base: u64, mut exp: u64) -> u64 {\n let mut result = 1;\n while exp > 0 {\n if exp & 1 == 1 {\n result = (result * base) % M;\n }\n exp >>= 1;\n base = (base * base) % M;\n }\n result\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use helpers::t;\n\n\n #[test]\n fn example1() {\n t!(\"2 2\\n\", \"7\\n\");\n }\n\n #[test]\n fn example2() {\n t!(\"123 456789\\n\", \"689974806\\n\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "22471bb92a3568d5d8413db43f0a0ff3", "src_uid": "f67173c973c6f83e88bc0ddb0b9bfa93", "difficulty": 2300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub struct Scanner {\n buffer: Vec\n}\n\nimpl Scanner {\n pub fn new() -> Scanner {\n Scanner { buffer: Vec::new() }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nconst MOD: u64 = 1_000_000_007;\n\nfn bin_pow(mut a: u64, mut n: u64) -> u64 {\n let mut x: u64 = 1;\n while n > 0 {\n if (n & 1) == 1 {\n x = x * a % MOD;\n }\n a = a * a % MOD;\n n >>= 1;\n }\n return x;\n}\n\nfn rev(a: u64) -> u64 {\n return bin_pow(a, MOD - 2);\n}\n\n\nfn main() {\n let mut scan = Scanner::new();\n let n: usize = scan.next();\n let x: usize = scan.next();\n\n let mut f: Vec = vec![0; 1000];\n f[0] = 1;\n for i in 1..1000 {\n f[i] = f[i - 1] * (i as u64) % MOD;\n }\n\n let mut rf: Vec = vec![0; 1000];\n for i in 0..1000 {\n rf[i] = rev(f[i]);\n }\n\n let mut px: Vec = vec![0; 1000];\n px[0] = 1;\n for i in 1..1000 {\n px[i] = px[i - 1] * ((x-1) as u64) % MOD;\n }\n\n let c = |n, k|{ f[n] * rf[n-k] % MOD * rf[k] % MOD };\n\n let mut dp: Vec> = vec![vec![0; n + 1]; n + 1];\n dp[0][0] = 1;\n for ones_now in 1..(n+1) {\n for ones_before in 0..(ones_now+1) {\n let mut ways: u64 = 0;\n for place_non_one in 0..std::cmp::min(ones_before + 1, ones_now) {\n ways += px[place_non_one] * rf[place_non_one] % MOD * rf[ones_before - place_non_one] % MOD;\n }\n ways %= MOD;\n ways = ways * f[ones_before] % MOD;\n ways = ways * c(n-ones_before, ones_now-ones_before) % MOD;\n ways = ways * px[n-ones_now] % MOD;\n for i in 1..(n+1) {\n dp[i][ones_now] = (dp[i][ones_now] + dp[i-1][ones_before] * ways) % MOD;\n }\n }\n }\n\n println!(\"{}\", dp[n][n]);\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "610de92e0c09320acf27ca7534b95fb1", "src_uid": "f67173c973c6f83e88bc0ddb0b9bfa93", "difficulty": 2300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\n/* \nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n*/\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n pub fn comb(n: u32, k: u32) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n let k = std::cmp::min(k, n - k);\n let mut nu = ModInt::one();\n let mut de = ModInt::one();\n for i in 0..k {\n nu *= ModInt(n - i);\n de *= ModInt(i + 1);\n }\n nu * de.inv()\n }\n}\n\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end ModInt ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n k: u32,\n }\n let mut ans = ModInt::zero();\n let pc = Precalc::new(n);\n for i in 0..=n {\n for j in 0..=n {\n let v = (n - i) * (n - j);\n let way = ModInt(k).pow(v as u32) * ModInt(k - 1).pow((n * n - v) as u32);\n ans += ModInt(MOD - 1).pow((i + j) as u32) * pc.comb(n, i) * pc.comb(n, j) * way;\n }\n }\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "b9113c14390a116debcbe6498de963c4", "src_uid": "f67173c973c6f83e88bc0ddb0b9bfa93", "difficulty": 2300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{BufReader, BufWriter, stdin, stdout, Write};\nuse std::cmp::{min, max};\nuse std::collections::{VecDeque, HashMap, BTreeMap, HashSet, BTreeSet, BinaryHeap};\n\nconst m:i64 = 1000000007;\n\nfn main() {\n\tlet mut inp = Iinput::default();\n\tlet out = &mut BufWriter::new(stdout());\n\tlet n:usize = inp.scan::();\n\tlet k:i64 = inp.scan::();\n\tlet mut nCr = vec![vec![0 as i64; n + 1]; n + 1];\n\tnCr[0][0] = 1;\n\tfor i in 1..n+1 {\n\t\tfor j in 0..i+1 {\n\t\t\tif j > 0 {\n\t\t\t\tnCr[i][j] += nCr[i - 1][j - 1];\n\t\t\t}\n\t\t\tif j < i {\n\t\t\t\tnCr[i][j] += nCr[i - 1][j];\n\t\t\t}\n\t\t\tnCr[i][j] %= m;\n\t\t}\n\t}\n\tlet mut dp = vec![0; n + 1];\n\tdp[0] = 1;\n\tlet mut pow2 = vec![1 as i64; n + 1];\n\tfor i in 1..n+1 {\n\t\tpow2[i] = pow2[i - 1] * (k - 1) % m;\n\t}\n\tfor _row in 0..n {\n\t\tlet mut tp = vec![0; n + 1];\n\t\tlet mut powa = 1 as i64;\n\t\tfor i in 0..n+1 {\n\t\t\tfor j in i..n+1 {\n\t\t\t\tlet mut val = pow2[n - j] * powa % m;\n\t\t\t\tif i == j {\n\t\t\t\t\tval += m - pow2[n];\n\t\t\t\t}\n\t\t\t\tval = val * nCr[n - i][n - j] % m;\n\t\t\t\ttp[j] = (tp[j] + val * dp[i]) % m;\n\t\t\t}\n\t\t\tpowa = powa * k % m;\n\t\t}\n\t\tdp = tp;\n\t}\n\twriteln!(out, \"{}\", dp[n]);\n}\n\n#[derive(Default)]\nstruct Iinput {\n\tbuffer: Vec\n}\n\nimpl Iinput {\n\tfn scan(&mut self) -> T {\n\t\tloop {\n\t\t\tif let Some(token) = self.buffer.pop() {\n\t\t\t\treturn token.parse().ok().expect(\"Parsing Error\");\n\t\t\t}\n\t\t\tlet mut s = String::new();\n\t\t\tstdin().read_line(&mut s).expect(\"Reading Error\");\n\t\t\tself.buffer = s.split_whitespace().rev().map(String::from).collect();\n\t\t}\n\t}\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "3fb42c14dfd3e04630e04c6c78efd888", "src_uid": "f67173c973c6f83e88bc0ddb0b9bfa93", "difficulty": 2300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut args = String::new();\n stdin().read_line(&mut args).unwrap();\n let mut amount: u32 = 0;\n for digit in args.trim_end().chars() {\n if digit == '4' || digit == '7' {\n amount += 1;\n }\n }\n if amount.to_string() == \"4\" || amount.to_string() == \"7\" {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6f38dc5e199fcabd2438fe66f4551185", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\t\n\tlet mut guess = String::new();\n\t\n io::stdin().read_line(&mut guess).expect(\"Failed to read line\");\n\n\tlet mut count = 0;\n\t\n\tfor ch in guess.chars() {\n\t\tif ch == '4' || ch == '7' {\n\t\t\tcount += 1;\n\t\t}\n }\n\n\tif count == 4 || count == 7 {\n\t\tprintln!(\"YES\");\n\t}\n\telse {\n\t\tprintln!(\"NO\");\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "fe16b67ef1881f12c09834d32e4de002", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n s : String,\n };\n let v: Vec = s.chars().collect();\n let mut cnt = 0;\n for a in v.iter() {\n if a == &'4' || a == &'7' {\n cnt += 1;\n }\n }\n let w: Vec = cnt.to_string().chars().collect();\n for a in w.iter() {\n if a != &'4' && a != &'7' {\n println!(\"NO\");\n return;\n }\n }\n println!(\"YES\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "73eeabb00bece0d33389b04e88fafa99", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let number = count_lucky_number(parse_arg());\n if number == 7 || number == 4 {\n println!(\"YES\")\n } else {\n println!(\"NO\")\n }\n}\n\nfn parse_arg() -> Vec {\n let mut text = String::new();\n stdin().read_line(&mut text).expect(\"msg: &str\");\n text.trim().chars().collect()\n}\nfn count_lucky_number(v: Vec) -> usize {\n let mut counter = 0;\n for i in v {\n if i == '4' || i == '7' {\n counter += 1;\n }\n }\n counter\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "dd9ebb2e6dcf7423f8760bec6445298c", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn string_lucky(s: &String) -> bool {\n for c in s.as_str().chars() {\n match c {\n '4' | '7' => (),\n _ => return false,\n }\n }\n\n true\n}\n\nfn is_lucky(val: u64) -> bool {\n let s: String = val.to_string();\n string_lucky(&s)\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let inputs: String = read(sin);\n\n let mut num_digits = 0;\n\n for c in inputs.as_str().chars() {\n match c {\n '4' | '7' => {\n num_digits += 1;\n }\n _ => (),\n }\n }\n\n if is_lucky(num_digits) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4c2874a6decc932b720e8c623578cd50", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n\tlet num = scan.next::();\n\n let count = num.chars().filter(|&c| c == '4' || c == '7').count();\n let v: Vec = (1..1000).map(|x| x.to_string())\n .filter(|x| !x.chars().any(|c| c != '4' && c != '7'))\n .map(|x| x.parse::())\n .map(|x| match x { Ok(n) => n, Err(_e) => 0 })\n .collect();\n let res = v.iter().any(|&i| count == i);\n\n writeln!(out, \"{}\", if res { \"YES\" } else { \"NO\" }).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "da1d38e5b5537f3d9c36d396e19b8626", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n\n line.split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let mut input = readln();\n\n let mut n = input[0];\n let mut count_lucky_digits = 0;\n\n while n > 0 {\n if n % 10 == 4 || n % 10 == 7 {\n count_lucky_digits += 1;\n }\n n /= 10;\n }\n\n match count_lucky_digits {\n 4 | 7 => {\n println!{\"YES\"};\n }\n _ => {\n println!(\"NO\");\n }\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e0ad41acc25daa60646034dae5b4713e", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*};\n\n\n#[allow(unused_must_use)]\nfn solve(mut scan: Scanner, mut w: W) {\n //let n = scan.token::();\n let input: Vec = scan.token::().chars().collect();\n let mut i = 0;\n for c in input.iter() {\n if *c == '4' || *c == '7' {\n i += 1;\n }\n }\n let num: Vec = i.to_string().chars().collect();\n let mut ans = \"YES\".to_string();\n for c in num.iter() {\n if *c != '4' && *c != '7' {\n ans = \"NO\".to_string();\n break;\n }\n }\n writeln!(w, \"{}\", ans);\n}\n \nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n solve(reader, writer);\n}\n\n#[allow(dead_code)]\nfn matrix_to_str(matrix: &Vec>, separator: &str) -> String { \n use std::fmt::Write;\n let mut ans = String::new();\n for line in matrix.iter() {\n for elem in line.iter() {\n write!(&mut ans, \"{}{}\", elem.to_string(), separator).unwrap();\n }\n write!(&mut ans, \"\\n\").unwrap();\n }\n ans\n}\npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace()\n }\n }\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace()) }\n }\n }\n pub fn get_matrix(&mut self, m: usize, n: usize) -> Vec> {\n // m rows and n columns\n let mut ans: Vec> = Vec::with_capacity(m);\n for i in 0..m {\n ans.push(Vec::with_capacity(n));\n for _ in 0..n {\n ans[i].push(self.token::());\n }\n }\n ans\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4bad6ea43abef74d17f00790063a10a7", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\npub fn read_line() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).expect(\"Failed to read a line\");\n buf\n}\n\npub fn main() {\n let n: usize = read_line().trim().parse().unwrap();\n let mut a: Vec = read_line()\n .trim()\n .chars()\n .map(|x| x.to_digit(10).unwrap())\n .collect();\n let mut b = a.split_off(n);\n a.sort();\n b.sort();\n println!(\n \"{}\",\n if a.iter().zip(b.iter()).all(|(x, y)| x < y) || a.iter().zip(b.iter()).all(|(x, y)| x > y)\n {\n \"YES\"\n } else {\n \"NO\"\n }\n );\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "greedy"], "code_uid": "77485c1840724e0bb9dd2d81299113a7", "src_uid": "e4419bca9d605dbd63f7884377e28769", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let stdin = std::io::stdin();\n let lock = stdin.lock();\n let mut r = io::Reader::new(lock);\n let mut w = io::Writer::new();\n\n let l = ['c', 'o', 'd', 'e', 'f', 'o', 'r', 'c', 'e', 's'];\n let mut v = vec![1u64; 10];\n let mut max_comb = 1u64;\n let mut selection = 0usize;\n let n: u64 = r.read()[0];\n \n while max_comb < n {\n for i in 0..v.len() {\n let comb = compute(&v, i);\n if comb > max_comb {\n selection = i;\n max_comb = comb;\n }\n }\n v[selection] += 1;\n }\n\n for i in 0..v.len() {\n for _ in 0..v[i] {\n w.push(l[i]);\n }\n }\n w.push('\\n');\n \n w.write();\n}\n\nfn compute(v: &Vec, i: usize) -> u64 {\n let mut comb = 1;\n for j in 0..v.len() {\n comb *= if j == i { v[j] + 1 } else { v[j] }\n }\n\n comb\n}\n\npub mod io {\n use std::fmt::{Debug, Display};\n use std::io::{BufRead, StdinLock};\n use std::str::FromStr;\n\n pub struct Reader<'a> {\n buffer: String,\n lock: StdinLock<'a>,\n }\n\n impl<'a> Reader<'a> {\n pub fn new(lock: StdinLock<'a>) -> Self {\n Reader {\n buffer: String::with_capacity(4 * 1024 * 1024),\n lock,\n }\n }\n\n pub fn read(&mut self) -> Vec\n where\n T: Copy + FromStr + Display,\n ::Err: Debug,\n {\n self.buffer.clear();\n\n self.lock\n .read_line(&mut self.buffer)\n .expect(\"Failed to get input\");\n\n self.buffer\n .trim()\n .split_whitespace()\n .map(|x| x.parse().expect(\"Failed to parse value\"))\n .collect()\n }\n }\n\n pub struct Writer {\n buffer: String,\n }\n\n impl Writer {\n pub fn new() -> Self {\n Writer {\n buffer: String::with_capacity(4 * 1024 * 1024),\n }\n }\n\n pub fn push(&mut self, data: T) {\n self.buffer.push_str(&format!(\"{}\", data));\n }\n\n pub fn pushw(&mut self, data: T) {\n self.buffer.push_str(&format!(\"{} \", data));\n }\n\n pub fn pushln(&mut self, data: T) {\n self.buffer.push_str(&format!(\"{}\\n\", data));\n }\n\n pub fn write(&self) {\n print!(\"{}\", self.buffer);\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "053d287c549419b6121f0cf88836249f", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n k: u64,\n }\n let c: Vec<_> = \"codeforces\".chars().collect();\n let mut ans = vec![1u64; c.len()];\n while ans.iter().fold(1u64, |s, a| s * a) < k {\n let p = ans[0];\n if let Some(x) = ans.iter().position(|v| *v < p) {\n ans[x] += 1;\n } else {\n ans[0] += 1;\n }\n }\n for (c, &a) in c.iter().zip(ans.iter()) {\n for _ in 0..a {\n print!(\"{}\", *c);\n }\n }\n println!();\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "1e16a66eb3582f0606dbc1008e743e08", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn solve() {\n let mut n: u64 = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim_end().parse().unwrap()\n };\n\n let mut v = vec![1; 10];\n\n let mut i = 0;\n loop {\n let mut m = v.iter().fold(1, |mul, a| mul * a);\n if m >= n {\n break;\n }\n v[i] += 1;\n i += 1;\n i %= 10;\n }\n\n for (i, a) in v.iter().enumerate() {\n print!(\n \"{}\",\n \"codeforces\"\n .chars()\n .nth(i)\n .unwrap()\n .to_string()\n .repeat(*a as usize)\n );\n }\n}\n\nfn main() {\n // let t: u32 = {\n // let mut buf = String::new();\n // std::io::stdin().read_line(&mut buf).unwrap();\n // buf.trim_end().parse().unwrap()\n // };\n\n // for _ in 0..t {}\n solve();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "e31814ba3ba2c9f95061b833f4d312c8", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s\n}\n\nfn read() -> T\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n read_stdin().trim().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: std::str::FromStr,\n ::Err: std::fmt::Debug,\n B: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n let s = read_stdin();\n let mut s = s.trim().split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .trim()\n .split_whitespace()\n .map(|x| x.trim().parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let mut iter = iter.collect::>();\n iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\nfn main() -> Result<(), Box> {\n let n = read::();\n let powers = [\n 1u64,\n 1024,\n 59049,\n 1048576,\n 9765625,\n 60466176,\n 282475249,\n 1073741824,\n 3486784401,\n 10000000000,\n 25937424601,\n 61917364224,\n 137858491849,\n 289254654976,\n 576650390625,\n 1099511627776,\n 2015993900449,\n 3570467226624,\n 6131066257801,\n 10240000000000,\n 16679880978201,\n 26559922791424,\n 41426511213649,\n 63403380965376,\n 95367431640625,\n 141167095653376,\n 205891132094649,\n 296196766695424,\n 420707233300201,\n 590490000000000,\n 819628286980801,\n 1125899906842624,\n 1531578985264449,\n 2064377754059776,\n 2758547353515625,\n 3656158440062976,\n 4808584372417849,\n 6278211847988224,\n 8140406085191601,\n ];\n let i = powers.iter().take_while(|i| **i < n).count() as u64;\n let mut v = [i; 10];\n let mut idx = 0;\n while v.iter().product::() < n {\n v[idx] += 1;\n idx += 1;\n }\n let s = \"codeforces\";\n for (c, n) in s.chars().zip(v.iter()) {\n for _ in 0..*n {\n print!(\"{}\", c)\n }\n }\n /*for _ in 0..n {\n let v = read_multiple::();\n let mut a = v[0];\n let mut b = v[1];\n let n = v[2];\n if a < b {\n std::mem::swap(&mut a, &mut b);\n }\n let mut c = 0;\n while a <= n {\n b = a + b;\n std::mem::swap(&mut a, &mut b);\n c += 1;\n }\n println!(\"{}\", c);\n\n }*/\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "a0900a1ed486adcc86f8d3cc77323204", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::fmt::Debug;\nuse std::str::FromStr;\n\npub struct TokenReader {\n reader: std::io::Stdin,\n tokens: Vec,\n index: usize,\n}\n\nimpl TokenReader {\n pub fn new() -> Self {\n Self {\n reader: std::io::stdin(),\n tokens: Vec::new(),\n index: 0,\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index += 1;\n self.tokens[self.index - 1].parse().unwrap()\n }\n\n pub fn vector(&mut self) -> Vec\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index = self.tokens.len();\n self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()\n }\n\n pub fn load_next_line(&mut self) {\n let mut line = String::new();\n self.reader.read_line(&mut line).unwrap();\n\n self.tokens = line\n .split_whitespace()\n .map(|tok| tok.to_string())\n .collect::>();\n self.index = 0;\n }\n}\n\nfn main() {\n let mut reader = TokenReader::new();\n let k = reader.next::();\n\n let name = \"codeforces\".chars().collect::>();\n let mut count = vec![1; name.len()];\n let mut prod: u64 = 1;\n\n while prod < k {\n for i in 0..count.len() {\n prod /= count[i];\n count[i] += 1;\n prod *= count[i];\n\n if prod >= k {\n break;\n }\n }\n }\n\n for i in 0..count.len() {\n for _ in 0..count[i] {\n print!(\"{}\", name[i]);\n }\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "e87120dcb73a518c06119e7ad478379f", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros)]\n\nuse kyoproio::*;\nuse std::{\n collections::*,\n io::{self, prelude::*},\n iter,\n mem::{replace, swap},\n};\n\nfn main() -> io::Result<()> {\n std::thread::Builder::new()\n .stack_size(64 * 1024 * 1024)\n .spawn(|| {\n let stdin = io::stdin();\n let stdout = io::stdout();\n run(KInput::new(stdin.lock()), io::BufWriter::new(stdout.lock()))\n })?\n .join()\n .unwrap();\n Ok(())\n}\n\nfn run(mut kin: I, mut out: O) {\n macro_rules! output { ($($args:expr),+) => { write!(&mut out, $($args),+).unwrap(); }; }\n macro_rules! outputln {\n ($($args:expr),+) => { output!($($args),+); outputln!(); };\n () => { output!(\"\\n\"); if cfg!(debug_assertions) { out.flush().unwrap(); } }\n }\n\n let k: i64 = kin.input();\n let mut a = vec![1; 10];\n for i in 0.. {\n let p: i64 = a.iter().product();\n if p >= k {\n break;\n }\n a[i % 10] += 1;\n }\n let s = b\"codeforces\";\n for i in 0..10 {\n for _ in 0..a[i] {\n output!(\"{}\", s[i] as char);\n }\n }\n outputln!();\n}\n\n// -----------------------------------------------------------------------------\npub mod kyoproio {\n use std::io::prelude::*;\n pub trait Input {\n fn str(&mut self) -> &str;\n fn input(&mut self) -> T {\n T::input(self)\n }\n fn iter(&mut self) -> Iter {\n Iter(self, std::marker::PhantomData)\n }\n fn seq>(&mut self, n: usize) -> B {\n self.iter().take(n).collect()\n }\n }\n pub struct KInput {\n src: R,\n buf: String,\n pos: usize,\n }\n impl KInput {\n pub fn new(src: R) -> Self {\n Self {\n src,\n buf: String::with_capacity(1024),\n pos: 0,\n }\n }\n pub fn src(&mut self) -> &mut R {\n &mut self.src\n }\n }\n impl Input for KInput {\n fn str(&mut self) -> &str {\n loop {\n if self.pos >= self.buf.len() {\n self.pos = 0;\n self.buf.clear();\n if self.src.read_line(&mut self.buf).expect(\"io error\") == 0 {\n return &self.buf;\n }\n }\n let range = self.pos\n ..self.buf[self.pos..]\n .find(|c: char| c.is_ascii_whitespace())\n .map(|i| i + self.pos)\n .unwrap_or_else(|| self.buf.len());\n self.pos = range.end + 1;\n if range.end > range.start {\n return &self.buf[range];\n }\n }\n }\n }\n pub struct Iter<'a, T, I: ?Sized>(&'a mut I, std::marker::PhantomData<*const T>);\n impl<'a, T: InputParse, I: Input + ?Sized> Iterator for Iter<'a, T, I> {\n type Item = T;\n fn next(&mut self) -> Option {\n Some(self.0.input())\n }\n }\n pub trait InputParse: Sized {\n fn input(src: &mut I) -> Self;\n }\n impl InputParse for Vec {\n fn input(src: &mut I) -> Self {\n src.str().as_bytes().to_owned()\n }\n }\n macro_rules! from_str_impl {\n { $($T:ty)* } => {\n $(impl InputParse for $T {\n fn input(src: &mut I) -> Self {\n src.str().parse::<$T>().expect(\"parse error\")\n }\n })*\n }\n }\n from_str_impl! {\n String char bool f32 f64 isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128\n }\n macro_rules! tuple_impl {\n ($H:ident $($T:ident)*) => {\n impl<$H: InputParse, $($T: InputParse),*> InputParse for ($H, $($T),*) {\n fn input(src: &mut I) -> Self {\n ($H::input(src), $($T::input(src)),*)\n }\n }\n tuple_impl!($($T)*);\n };\n () => {}\n }\n tuple_impl!(A B C D E F G);\n #[macro_export]\n macro_rules! kdbg {\n ($($v:expr),*) => {\n if cfg!(debug_assertions) { dbg!($($v),*) } else { ($($v),*) }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "e469083e25d5a0ef0fb1106250f37aa1", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]\nuse std::cmp::*;\nuse std::collections::*;\nuse std::mem::*;\n\nfn main() {\n let (r, w, e) = (std::io::stdin(), std::io::stdout(), std::io::stderr());\n let mut io = IO::new(r.lock(), w.lock(), e.lock());\n assert_eq!(!0usize, std::usize::MAX); //\ud83d\ude4a\n assert!(0 == 0); //\ud83d\ude07\n let mut k = io.read::();\n // 1*1*1*...*1\n // -> 2 * 1 * 1 *1 * ... * 1\n // -> 2 * 2 * ...\n //n^i * (n+1)**j // i+j==10\n for n in 1..111111111 {\n let n = n as i64;\n\n for i in 0..11 {\n let i = i as u32;\n let j = 10 - i;\n let temp = n.pow(i) * (n - 1).pow(j);\n if temp >= k {\n let mut v = \"codeforces\".chars().collect::>();\n for l in 0..10 {\n if l < i {\n for _ in 0..n {\n io.write(v[l as usize]);\n }\n } else {\n for _ in 0..n - 1 {\n io.write(v[l as usize]);\n }\n }\n }\n return;\n }\n }\n }\n}\n\nstatic MX: usize = 1010101;\nstatic MOD: i64 = 1000000007;\nstatic INF: i64 = std::i64::MAX >> 1;\n// IO\nuse std::io::*;\nstruct IO {\n Read: R,\n Write: BufWriter,\n Error: BufWriter,\n}\nimpl IO {\n fn new(r: R, w: W, e: E) -> IO {\n IO {\n Read: r,\n Write: BufWriter::new(w),\n Error: BufWriter::new(e),\n }\n }\n fn read(&mut self) -> T\n where\n T: std::str::FromStr,\n {\n let next: String = self\n .Read\n .by_ref()\n .bytes()\n .map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n next.parse().ok().unwrap()\n }\n fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n fn chari(&mut self) -> Vec {\n self.chars()\n .iter()\n .map(|&c| (c as u8 - b'0') as i64)\n .collect::>()\n }\n fn readn(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read::()).collect::>()\n }\n fn readmat(&mut self, n: usize, m: usize) -> Vec> {\n (0..n).map(|_| self.readn(m)).collect()\n }\n fn write(&mut self, val: S) {\n self.Write.write(val.to_string().as_bytes());\n }\n fn writeln(&mut self, val: S) {\n self.Write.write(val.to_string().as_bytes());\n self.Write.write(b\"\\n\");\n }\n fn debug(&mut self, val: S) {\n writeln!(self.Error, \"(debug) {:?}\", &val);\n }\n fn debug2(&mut self, val1: S, val2: T) {\n writeln!(self.Error, \"(debug2) {:?} -> {:?}\", val1, val2);\n }\n fn debug3(\n &mut self,\n val1: S,\n val2: T,\n val3: U,\n ) {\n writeln!(\n self.Error,\n \"(debug3) {:?} -> {:?} -> {:?}\",\n val1, val2, val3\n );\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "67d08be025d728ef33939c3500afe6d6", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": " \ntype BoxResult = Result>;\n \n \nfn main() {\n let mut scanner = Scanner::new(stdin());\n let k = scanner.read::().unwrap();\n let mut counts = vec![1; 10];\n let mut index = 0;\n let mut pattern = 1;\n while pattern < k {\n counts[index] += 1;\n pattern /= counts[index] - 1;\n pattern *= counts[index];\n index = (index + 1) % 10;\n }\n let mut ans = String::new();\n let chars = \"codeforces\".chars().collect::>();\n for i in 0..10 {\n for _ in 0..counts[i] {\n ans.push(chars[i]);\n }\n }\n println!(\"{}\", ans);\n}\n\n\nuse std::error::Error;\nuse std::fmt::Debug;\nuse std::str::FromStr;\nuse std::io::prelude::*;\nuse std::io::{stdin, BufReader};\n \npub struct Scanner {\n reader: BufReader,\n buffer: String,\n}\nimpl Scanner\nwhere\n R: Read,\n{\n pub fn new(inner: R) -> Scanner {\n let reader = BufReader::new(inner);\n let buffer = String::new();\n Scanner {\n reader: reader,\n buffer: buffer,\n }\n }\n pub fn with_capacity(capacity: usize, inner: R) -> Scanner {\n let reader = BufReader::with_capacity(capacity, inner);\n let buffer = String::new();\n Scanner {\n reader: reader,\n buffer: buffer,\n }\n }\n pub fn read_line(&mut self) -> BoxResult {\n self.reader.read_line(&mut self.buffer)?;\n let cloned = self.buffer.trim().to_string();\n self.buffer.clear();\n Ok(cloned)\n }\n \n pub fn read(&mut self) -> BoxResult\n where\n T: FromStr,\n T::Err: Debug + Error + 'static,\n {\n self.reader.read_line(&mut self.buffer)?;\n let parsed = self.buffer.trim().parse()?;\n self.buffer.clear();\n Ok(parsed)\n }\n pub fn read_two(&mut self) -> BoxResult<(T, U)>\n where\n T: FromStr + Copy,\n T::Err: Debug + Error + 'static,\n U: FromStr + Copy,\n U::Err: Debug + Error + 'static,\n {\n self.reader.read_line(&mut self.buffer)?;\n let (a, b) = {\n let params = self.buffer.trim().split_whitespace().collect::>();\n let a = params[0].parse()?;\n let b = params[1].parse()?;\n (a, b)\n };\n self.buffer.clear();\n Ok((a, b))\n }\n pub fn read_three(&mut self) -> BoxResult<(T, U, V)>\n where\n T: FromStr + Copy,\n T::Err: Debug + Error + 'static,\n U: FromStr + Copy,\n U::Err: Debug + Error + 'static,\n V: FromStr + Copy,\n V::Err: Debug + Error + 'static,\n {\n self.reader.read_line(&mut self.buffer)?;\n let (a, b, c) = {\n let params = self.buffer.trim().split_whitespace().collect::>();\n let a = params[0].parse()?;\n let b = params[1].parse()?;\n let c = params[2].parse()?;\n (a, b, c)\n };\n self.buffer.clear();\n Ok((a, b, c))\n }\n pub fn read_four(&mut self) -> BoxResult<(T, U, V, W)>\n where\n T: FromStr + Copy,\n T::Err: Debug + Error + 'static,\n U: FromStr + Copy,\n U::Err: Debug + Error + 'static,\n V: FromStr + Copy,\n V::Err: Debug + Error + 'static,\n W: FromStr + Copy,\n W::Err: Debug + Error + 'static,\n {\n self.reader.read_line(&mut self.buffer)?;\n let (a, b, c, d) = {\n let params = self.buffer.trim().split_whitespace().collect::>();\n let a = params[0].parse()?;\n let b = params[1].parse()?;\n let c = params[2].parse()?;\n let d = params[3].parse()?;\n (a, b, c, d)\n };\n self.buffer.clear();\n Ok((a, b, c, d))\n }\n pub fn read_vector(&mut self) -> BoxResult>\n where\n T: FromStr + Copy,\n T::Err: Debug + Error + 'static,\n {\n self.reader.read_line(&mut self.buffer)?;\n let parsed_vec = self\n .buffer\n .trim()\n .split_whitespace()\n .map(|s| s.parse())\n .collect::, _>>()?;\n self.buffer.clear();\n Ok(parsed_vec)\n }\n pub fn read_matrix(&mut self, lines: u64) -> BoxResult>>\n where\n T: FromStr + Copy,\n T::Err: Debug + Error + 'static,\n {\n let mut parsed_matrix = vec![];\n for _ in 0..lines {\n self.reader.read_line(&mut self.buffer)?;\n parsed_matrix.push(\n self.buffer\n .trim()\n .split_whitespace()\n .map(|s| s.parse())\n .collect::, _>>()?,\n );\n self.buffer.clear();\n }\n Ok(parsed_matrix)\n }\n pub fn read_chars(&mut self) -> BoxResult> {\n self.reader.read_line(&mut self.buffer)?;\n let chars = self.buffer.trim().chars().collect::>();\n self.buffer.clear();\n Ok(chars)\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "math", "greedy", "strings"], "code_uid": "93fda34fa6c84a013838b0337636e166", "src_uid": "8001a7570766cadcc538217e941b3031", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n\n let mut v: Vec = vec![];\n\n for _i in 0..4 {\n io::stdin().read_line(&mut input)?;\n v.push(input.trim().parse::().unwrap());\n input.clear();\n }\n\n let mut result = 1;\n if v[0] != v[3] || (v[0] == 0 && v[2] != 0) {\n result = 0;\n }\n\n println!(\"{}\", result);\n\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "0def3b322cd60a939fb55302c9f4cfcc", "src_uid": "b99578086043537297d374dc01eeb6f8", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, BufRead, Stdin, StdinLock};\n\nfn regular_sequence_exist(num_ll: usize, _num_lr: usize, num_rl: usize, num_rr: usize) -> bool {\n if num_ll != num_rr {\n return false;\n }\n if num_rl > 0\n {\n if num_ll == 0 {\n return false;\n }\n if num_rr == 0 {\n return false;\n }\n }\n return true;\n}\n\n#[cfg(test)]\nmod test {\n use super::regular_sequence_exist;\n\n #[test]\n fn test1() {\n let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = (3, 1, 4, 3);\n let result: bool = regular_sequence_exist(num_ll, num_lr, num_rl, num_rr);\n assert_eq!(result, true);\n }\n #[test]\n fn test2() {\n let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = (0, 0, 0, 0);\n let result: bool = regular_sequence_exist(num_ll, num_lr, num_rl, num_rr);\n assert_eq!(result, true);\n }\n #[test]\n fn test3() {\n let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = (1, 2, 3, 4);\n let result: bool = regular_sequence_exist(num_ll, num_lr, num_rl, num_rr);\n assert_eq!(result, false);\n }\n}\n\nfn read_data() -> (usize, usize, usize, usize) {\n let stdin_stream: Stdin = stdin();\n let mut stdin_handle: StdinLock = stdin_stream.lock();\n\n let mut data: Vec = Vec::with_capacity(4);\n\n for _ in 0..4 {\n let mut value_str: String = String::new();\n stdin_handle.read_line(&mut value_str).unwrap();\n data.push(value_str.trim().parse::().unwrap());\n }\n\n return (data[0], data[1], data[2], data[3]);\n}\n\nfn main() {\n let (num_ll, num_lr, num_rl, num_rr): (usize, usize, usize, usize) = read_data();\n\n if regular_sequence_exist(num_ll, num_lr, num_rl, num_rr) {\n println!(\"1\");\n } else {\n println!(\"0\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "b19fa50e9ccfb7cd65a5fd6326e985c9", "src_uid": "b99578086043537297d374dc01eeb6f8", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let a: i32 = scan.token();\n let b: i32 = scan.token();\n let c: i32 = scan.token();\n let d: i32 = scan.token();\n\n if a == 0 && (c > 0 || d > 0) {\n writeln!(out, \"0\")?;\n return Ok(());\n }\n\n writeln!(out, \"{}\", match a == d {\n true => 1,\n false => 0,\n })?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "e623e20125a9afca3af37d38c65e8610", "src_uid": "b99578086043537297d374dc01eeb6f8", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n,a,mut b) = readln!(i32,i32,i32);\n if b < 0 {\n b = -b;\n b %= n;\n b = (n-b)%n;\n }\n println!(\"{}\",1+((a-1+b)%n));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "1cfa6930fda506b00086233aa5888365", "src_uid": "cd0e90042a6aca647465f1d51e6dffc4", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n\n let rows_and_lines = input.trim().parse::()\n .expect(\"ROWS_AND_LINES::parse to i32 failed\");\n let mut matrix = vec![vec![i32::default(); rows_and_lines as usize]; rows_and_lines as usize];\n for i in 0..rows_and_lines {\n for j in 0..rows_and_lines {\n matrix[i as usize][j as usize] = cal(i, j);\n }\n }\n\n println!(\"{}\",matrix[(rows_and_lines - 1) as usize][(rows_and_lines - 1) as usize]);\n}\n\nfn cal(i: i32, j: i32) -> i32 {\n if i == 0 || j == 0 {\n 1\n }else {\n cal(i - 1, j) + cal(i, j - 1)\n }\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "24abc9fff68669d3c77075b21392f9a5", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let mut arr: [[usize; 11]; 11] = [[1; 11]; 11];\n\n for i in 1..n {\n for j in 1..n {\n arr[i][j] = arr[i-1][j] + arr[i][j-1];\n }\n }\n println!(\"{}\", arr[n-1][n-1]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "30b47d40a7772248a3acda137ebfcd0e", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn get_elem(i: u8, j: u8) -> u32 {\n\n\n if i == 1 {\n 1\n } else if i == j {\n 2 * get_elem(i - 1, j)\n } else if i < j {\n get_elem(i, j - 1) + get_elem(i - 1, j)\n } else {\n 0\n }\n\n}\n\nfn main() {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let n = line.trim().parse::().unwrap();\n\n println!(\"{}\", get_elem(n , n));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "3dccffd055d7f4a16d6888f717ac52aa", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let n: usize = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n };\n\n let mut table: [[u32; 10]; 10] = [[0; 10]; 10];\n for i in 0..n {\n for j in 0..n {\n table[i][j] = if i == 0 || j == 0 {\n 1\n } else {\n table[i-1][j] + table[i][j-1]\n }\n }\n }\n\n println!(\"{}\", table[n-1][n-1]);\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "a5a2210a1485072b8a3bc1e76f45fea2", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io;\n\nfn get_line() -> io::Result {\n\tlet mut buffer = String::new();\n\tio::stdin().read_line(&mut buffer)?;\n\tOk(buffer)\n}\n\nfn main() -> Result<(), Box> {\n\tlet n = get_line()?.trim().parse::()?;\n\tlet mut table = vec![1; n];\n\tfor _ in 1..n {\n\t\tfor q in 1..n {\n\t\t\ttable[q] += table[q - 1];\n\t\t}\n\t}\n\tprint!(\"{}\", table[n - 1]);\n\tOk(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "609b3a78277323a7c42d4f890ec391ee", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn fact(n: i64) -> i64 {\n if n >= 2 {\n n * fact(n-1)\n } else {\n 1\n }\n}\n\nfn main() {\n let n = readln!(i64)-1;\n println!(\"{}\",(fact(2*n)/fact(n))/fact(n));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "e21c07915c1d2174ca61b025f22b824c", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut n = String::new();\n io::stdin().read_line(&mut n).unwrap();\n let n = n.trim().parse::().unwrap();\n\n let mut x = vec![1; n];\n\n for _i in 0..n-1 {\n let mut n_temp = vec![1; n];\n\n for i in 1..n {\n n_temp[i] = x[i] + n_temp[i - 1];\n }\n\n x = n_temp;\n }\n\n println!(\"{}\", x[n-1]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "c17d30a513b3b43a5b769eccc2fb0a3a", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n println!(\"{}\", [0,1,2,6,20,70,252,924,3432,12870,48620][input.i() as usize]);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "363f2cf58d178b91074878bc50d57d6e", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut string1 = String::new();\n\tio::stdin().read_line(&mut string1).unwrap();\n\tlet string1 = string1.trim();\n\n\tlet mut string2 = String::new();\n\tio::stdin().read_line(&mut string2).unwrap();\n\tlet string2 = string2.trim();\n\n\tfor i in 0..string1.len() {\n\t\tif string1.chars().nth(i) != string2.chars().nth(i) {\n\t\t\tprint!(\"1\");\n\t\t} else {\n\t\t\tprint!(\"0\");\n\t\t}\n\t}\n\tprintln!();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "95754206bd6fe9d9a3ea37396059faeb", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut a = String::new();\n std::io::stdin().read_line(&mut a).unwrap();\n let mut b = String::new();\n std::io::stdin().read_line(&mut b).unwrap();\n\n for i in 0..a.trim().len() {\n if a.as_bytes()[i] != b.as_bytes()[i] {\n print!(\"1\");\n }\n else {\n print!(\"0\");\n }\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6e6852dbce060c748b9c4cca01104705", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/61/A\n// implementation, simulation\nuse std::io;\n\nfn main() {\n let mut a = String::new();\n\n io::stdin()\n .read_line(&mut a)\n .unwrap();\n\n let a = a.trim();\n\n let mut b = String::new();\n\n io::stdin()\n .read_line(&mut b)\n .unwrap();\n\n let b = b.trim();\n\n let mut iter = b.chars();\n\n let mut answer = String::from(\"\");\n\n for ch in a.chars() {\n if ch == iter.next().unwrap() {\n answer.push_str(\"0\");\n } else {\n answer.push_str(\"1\");\n }\n }\n\n println!(\"{}\", answer);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1e2917fc25a91037a9846b457c850cd1", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/61/A\nuse std::io;\n\nfn main() {\n let mut a = String::new();\n\n io::stdin()\n .read_line(&mut a)\n .unwrap();\n\n let a = a.trim();\n\n let a: Vec = a.chars().collect();\n\n let mut b = String::new();\n\n io::stdin()\n .read_line(&mut b)\n .unwrap();\n\n let b = b.trim();\n\n let b: Vec = b.chars().collect();\n\n let mut answer = String::from(\"\");\n\n for i in 0..a.len() {\n if a[i] == b[i] {\n answer.push_str(\"0\");\n } else {\n answer.push_str(\"1\");\n }\n }\n println!(\"{}\", answer);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "797e40699c6fcf1aac7193d139b746f4", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn print_result(s_1 : &String, s_2 : &String) {\n let pair_iter = s_1.trim().chars().zip(s_2.trim().chars());\n for (a, b) in pair_iter {\n if a == b {\n print!(\"0\");\n } else {\n print!(\"1\");\n }\n }\n println!();\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut s_1 = String::new();\n let mut s_2 = String::new();\n read_line(&stdin, &mut s_1);\n read_line(&stdin, &mut s_2);\n print_result(&s_1, &s_2);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5b6f342ec8ce7e8679bde60b325229bd", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n}\n\nfn main() {\n let l1 = read_line();\n let l2 = read_line();\n let ans = l1.chars().zip(l2.chars()).map(|(c1, c2)| if c1 == c2 { '0' } else { '1' }).collect::();\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "fd8487095fe4890b0529724d39faa1b5", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut a = String::new();\n let mut b = String::new();\n stdin().read_line(&mut a).unwrap();\n stdin().read_line(&mut b).unwrap();\n let a: Vec = a.trim().chars().collect();\n let b: Vec = b.trim().chars().collect();\n\n let mut answer = String::new();\n\n for i in 0..a.len() {\n if a[i] != b[i] {\n answer.push_str(\"1\");\n } else {\n answer.push_str(\"0\");\n }\n }\n\n println!(\"{}\", answer);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8a00ef74a21632f65737bf2862027fa5", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n\tlet a = scan.next::();\n\tlet b = scan.next::();\n let ab = a.as_bytes();\n let bb = b.as_bytes();\n\n for i in 0..ab.len() {\n write!(out, \"{}\", ab[i] ^ bb[i]).expect(\"fail\");\n }\n\n writeln!(out, \"\").expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "15d03e15c8e1339006ad22dc0765ec5f", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/**\n * _ _ __ _ _ _ _ _ _ _\n * | | | | / / | | (_) | (_) | | (_) | |\n * | |__ __ _| |_ ___ ___ / /__ ___ _ __ ___ _ __ ___| |_ _| |_ ___ _____ ______ _ __ _ _ ___| |_ ______ ___ _ __ _ _ __ _ __ ___| |_ ___\n * | '_ \\ / _` | __/ _ \\ / _ \\ / / __/ _ \\| '_ ` _ \\| '_ \\ / _ \\ __| | __| \\ \\ / / _ \\______| '__| | | / __| __|______/ __| '_ \\| | '_ \\| '_ \\ / _ \\ __/ __|\n * | | | | (_| | || (_) | (_) / / (_| (_) | | | | | | |_) | __/ |_| | |_| |\\ V / __/ | | | |_| \\__ \\ |_ \\__ \\ | | | | |_) | |_) | __/ |_\\__ \\\n * |_| |_|\\__,_|\\__\\___/ \\___/_/ \\___\\___/|_| |_| |_| .__/ \\___|\\__|_|\\__|_| \\_/ \\___| |_| \\__,_|___/\\__| |___/_| |_|_| .__/| .__/ \\___|\\__|___/\n * | | | | | |\n * |_| |_| |_|\n *\n * https://github.com/hatoo/competitive-rust-snippets\n */\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\nmod util {\n use std::io::{stdin, stdout, BufWriter, StdoutLock};\n use std::str::FromStr;\n use std::fmt::Debug;\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n #[allow(dead_code)]\n pub fn with_bufwriter) -> ()>(f: F) {\n let out = stdout();\n let writer = BufWriter::new(out.lock());\n f(writer)\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n\n#[allow(dead_code)]\npub fn gcd(a: u64, b: u64) -> u64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n#[allow(dead_code)]\npub fn lcm(a: u64, b: u64) -> u64 {\n a / gcd(a, b) * b\n}\n#[allow(dead_code)]\n/// (gcd, x, y)\npub fn extgcd(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (gcd, x, y) = extgcd(b, a % b);\n (gcd, y, x - (a / b) * y)\n }\n}\n#[allow(dead_code)]\npub fn mod_pow(x: u64, n: u64, m: u64) -> u64 {\n let mut res = 1;\n let mut x = x;\n let mut n = n;\n while n > 0 {\n if n & 1 == 1 {\n res = (res * x) % m;\n }\n x = (x * x) % m;\n n >>= 1;\n }\n res\n}\n#[allow(dead_code)]\npub fn mod_inverse(a: u64, m: u64) -> u64 {\n let (_, x, _) = extgcd(a as i64, m as i64);\n ((m as i64 + x) as u64 % m) % m\n}\n#[allow(dead_code)]\npub fn fact_table(len: usize, m: u64) -> Vec {\n let mut res = vec![1; len + 1];\n for i in 1..len + 1 {\n res[i] = (i as u64 * res[i - 1]) % m;\n }\n res\n}\n#[allow(dead_code)]\n/// (a mod p, e when n! = a p\\^e)\npub fn mod_fact(n: u64, p: u64, fact: &[u64]) -> (u64, u64) {\n if n == 0 {\n (1, 0)\n } else {\n let (a, b) = mod_fact(n / p, p, fact);\n let pow = b + n / p;\n if n / p % 2 != 0 {\n (a * (p - fact[(n % p) as usize]) % p, pow)\n } else {\n (a * fact[(n % p) as usize] % p, pow)\n }\n }\n}\n#[allow(dead_code)]\n/// C(n, k) % p\npub fn mod_comb(n: u64, k: u64, p: u64, fact: &[u64]) -> u64 {\n if n < k {\n 0\n } else {\n let (a1, e1) = mod_fact(n, p, fact);\n let (a2, e2) = mod_fact(k, p, fact);\n let (a3, e3) = mod_fact(n - k, p, fact);\n if e1 > e2 + e3 {\n 0\n } else {\n a1 * mod_inverse(a2 * a3 % p, p) % p\n }\n }\n}\n#[allow(dead_code)]\n/// H(n, k) % p\npub fn mod_comb_repetition(n: u64, k: u64, p: u64, fact: &[u64]) -> u64 {\n mod_comb(n - 1 + k, n - 1, p, fact)\n}\n\n#[allow(dead_code)]\npub const M: u64 = 1_000_000_007;\n\nfn rec(m: u64, memo: &mut HashMap) -> u64 {\n if let Some(&res) = memo.get(&m) {\n return res;\n }\n\n let mut s = mod_pow(2, m - 1, M);\n\n for x in (1..).take_while(|&x| x * x <= m) {\n if m % x == 0 {\n if x != 1 {\n s = (s + M - rec(m / x, memo)) % M;\n }\n if m / x != x {\n s = (s + M - rec(x, memo)) % M;\n }\n }\n }\n\n memo.insert(m, s);\n s\n}\n\n#[allow(dead_code)]\nfn main() {\n let (x, y) = get!(u64, u64);\n if y % x != 0 || x > y {\n println!(\"0\");\n return;\n }\n\n let mut memo = HashMap::new();\n let m = y / x;\n println!(\"{}\", rec(m, &mut memo));\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "number theory"], "code_uid": "a04a99403e18b8bafad02007f9a12faf", "src_uid": "de7731ce03735b962ee033613192f7bc", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\n\nfn main() {\n input!{\n n: i64,\n v: i64,\n }\n if v>=n-1 {\n return println!(\"{}\", n-1);\n }\n let mut ans = 0;\n for i in 1..(n-v+1) {\n if i == 1 {\n ans += v;\n } else {\n ans += i;\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp"], "code_uid": "916aee78e7df6e239d57af7a5ebab39c", "src_uid": "f8eb96deeb82d9f011f13d7dac1e1ab7", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*input\n97 99\n*/\nfn main() {\n let mut input = format!(\"\");\n std::io::stdin().read_line(&mut input).ok();\n let v: Vec = input\n .trim()\n .split_whitespace()\n .map(|x| x.parse().expect(\"\"))\n .collect();\n if v[0] - 1 <= v[1] {\n println!(\"{}\", v[0] - 1);\n std::process::exit(0);\n }\n let mut money_to_spent = v[1];\n let mut fuel = v[1];\n for i in 1..v[0] {\n if i != 1 {\n fuel = fuel - 1;\n }\n //println!(\"CITY: {} F: {} SISA: {}\", i, fuel, v[0] - i);\n // 1 2 3 4 5 6 7 8 9\n // 2\n if v[0] - i <= fuel {\n break;\n }\n if i != 1 {\n money_to_spent = money_to_spent + i;\n fuel = fuel + 1;\n }\n }\n println!(\"{}\", money_to_spent);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp"], "code_uid": "57ddccf0ad40484c100b9a4a56918285", "src_uid": "f8eb96deeb82d9f011f13d7dac1e1ab7", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, stdout, BufWriter, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n\n let info: Vec = (0..2).map(|_| scan.next()).collect();\n let mut cost = 0;\n let mut tank = 0;\n\n if info[0] - 1 <= info[1] {\n println!(\"{}\", info[0] - 1);\n return;\n }\n\n for i in 0..info[0] - 1 {\n if tank < (info[0] - 1 - i) {\n cost += (info[1] - tank) * (i + 1);\n tank = info[1];\n }\n tank -= 1;\n }\n\n println!(\"{}\", cost);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp"], "code_uid": "e467b498023b0bcedc188ea0b0d9c190", "src_uid": "f8eb96deeb82d9f011f13d7dac1e1ab7", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[warn(unused_variables)]\nfn main() {\n let input = input_vec::(\" \");\n let n = input[0];\n let v = input[1];\n\n println!(\"{}\", if (n-1) <= v {n-1} else {(n-v+1)*(n-v)/2 + v-1})\n}\n\nfn input_str() -> String {\n let mut buff = String::new();\n std::io::stdin().read_line(&mut buff).expect(\"Err\");\n buff\n}\n\nfn input_() -> T\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().parse::().expect(\"Err pars\")\n}\n\n\nfn input_vec(sep: &str) -> Vec \nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().split(sep).map(|c| c.parse::().expect(\"Err pars\")).collect()\n}\n\nfn input_vec_chars() -> Vec {\n input_str().trim().chars().collect()\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp"], "code_uid": "e0d5dfb5fcbef39a7c5f828d43e779cf", "src_uid": "f8eb96deeb82d9f011f13d7dac1e1ab7", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let field = [\n parse_line!(String).bytes().collect::>(),\n parse_line!(String).bytes().collect::>(),\n parse_line!(String).bytes().collect::>(),\n ];\n let mut xs = 0;\n let mut os = 0;\n for i in 0..3 {\n for j in 0..3 {\n if field[i][j] == b'X' {\n xs += 1;\n }\n if field[i][j] == b'0' {\n os += 1;\n }\n }\n }\n let ok = xs == os || xs == os + 1;\n if !ok {\n return println!(\"illegal\");\n }\n let mut xts = false;\n let mut ots = false;\n for i in 0..3 {\n let mut xcol = true;\n let mut xrow = true;\n let mut ocol = true;\n let mut orow = true;\n for j in 0..3 {\n xcol &= field[j][i] == b'X';\n xrow &= field[i][j] == b'X';\n ocol &= field[j][i] == b'0';\n orow &= field[i][j] == b'0';\n }\n xts |= xcol | xrow;\n ots |= ocol | orow;\n }\n let mut xd1 = true;\n let mut xd2 = true;\n let mut od1 = true;\n let mut od2 = true;\n for i in 0..3 {\n xd1 &= field[i][i] == b'X';\n xd2 &= field[i][2 - i] == b'X';\n od1 &= field[i][i] == b'0';\n od2 &= field[i][2 - i] == b'0';\n }\n xts |= xd1 | xd2;\n ots |= od1 | od2;\n if xts && ots {\n return println!(\"illegal\");\n }\n if xts {\n if xs == os {\n return println!(\"illegal\")\n }\n return println!(\"the first player won\");\n }\n if ots {\n if xs != os {\n return println!(\"illegal\")\n }\n return println!(\"the second player won\");\n }\n if xs + os == 9 {\n return println!(\"draw\");\n }\n if xs == os {\n return println!(\"first\");\n }\n println!(\"second\");\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "games"], "code_uid": "71933380d2d99450a3db2ff3dfef6238", "src_uid": "892680e26369325fb00d15543a96192c", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read as _};\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_to_string(&mut input).unwrap();\n let mut input = input.split_whitespace();\n macro_rules! read(\n ([$tt:tt; $n:expr]) => ((0..$n).map(|_| read!($tt)));\n ($ty:ty) => (input.next().unwrap().parse::<$ty>().unwrap());\n );\n\n let board = read!([String; 3])\n .map(|x| x.as_bytes().to_vec())\n .collect::>();\n let p1 = b'X';\n let p2 = b'0';\n let p1_count = count(&board, p1);\n let p2_count = count(&board, p2);\n let p1_win = win(&board, p1);\n let p2_win = win(&board, p2);\n if p1_count < p2_count || p1_count > p2_count + 1 || p1_win && p2_win {\n println!(\"illegal\");\n } else if p1_win {\n if p1_count == p2_count + 1 {\n println!(\"the first player won\");\n } else {\n println!(\"illegal\");\n }\n } else if p2_win {\n if p1_count == p2_count {\n println!(\"the second player won\");\n } else {\n println!(\"illegal\");\n }\n } else if count(&board, b'.') == 0 {\n println!(\"draw\");\n } else if p1_count == p2_count {\n println!(\"first\");\n } else {\n println!(\"second\");\n }\n}\n\nfn count(board: &Vec>, c: u8) -> usize {\n board\n .iter()\n .map(|xs| xs.iter().filter(|&&x| x == c).count())\n .sum()\n}\n\nfn win(board: &Vec>, c: u8) -> bool {\n (0..3).any(|i| (0..3).all(|j| board[i][j] == c))\n || (0..3).any(|j| (0..3).all(|i| board[i][j] == c))\n || (0..3).all(|i| board[i][i] == c)\n || (0..3).all(|i| board[i][2 - i] == c)\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "games"], "code_uid": "fa5c5a4d07d3b4d205c499852fc0b069", "src_uid": "892680e26369325fb00d15543a96192c", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use std::collections::BTreeSet;\n// use std::collections::BTreeMap;\n// use std::collections::HashSet;\n// use std::collections::HashMap;\nuse std::convert::TryInto;\nuse std::io::Write;\n\nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: std::str::SplitAsciiWhitespace<'static>,\n}\n\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\nenum Answer {\n Illegal,\n First,\n Second,\n FirstWon,\n SecondWon,\n Draw,\n}\n\nfn solve(b: [[u8; 3]; 3]) -> Answer {\n let mut cnt1 = 0;\n let mut cnt2 = 0;\n for i in 0..3 {\n for j in 0..3 {\n if b[i][j] == 'X' as u8 {\n cnt1 += 1;\n } else if b[i][j] == '0' as u8 {\n cnt2 += 1;\n }\n }\n }\n\n if !(cnt1 == cnt2 || cnt1 == cnt2 + 1) {\n return Answer::Illegal;\n }\n\n let win_check = |p: u8| {\n for i in 0..3 {\n if b[i][0] == p && b[i][1] == p && b[i][2] == p {\n return true;\n }\n if b[0][i] == p && b[1][i] == p && b[2][i] == p {\n return true;\n }\n }\n return b[1][1] == p && ((b[0][0] == p && b[2][2] == p) || (b[0][2] == p && b[2][0] == p));\n };\n let first_won = win_check('X' as u8);\n let second_won = win_check('0' as u8);\n if first_won && second_won {\n return Answer::Illegal;\n }\n if first_won {\n if cnt1 == cnt2 {\n return Answer::Illegal;\n }\n return Answer::FirstWon;\n }\n if second_won {\n if cnt1 == cnt2 + 1 {\n return Answer::Illegal;\n }\n return Answer::SecondWon;\n }\n\n let mut is_finished = true;\n for i in 0..3 {\n for j in 0..3 {\n if b[i][j] == '.' as u8 {\n is_finished = false;\n }\n }\n }\n\n if is_finished {\n return Answer::Draw;\n }\n\n if cnt1 == cnt2 {\n Answer::First\n } else {\n Answer::Second\n }\n}\n\nfn main() -> Result<(), Box> {\n let (stdin, stdout) = (std::io::stdin(), std::io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = std::io::BufWriter::new(stdout.lock());\n\n let mut a: Vec = vec![];\n a.push(scan.next());\n a.push(scan.next());\n a.push(scan.next());\n\n let mut b: [[u8; 3]; 3] = [[0; 3]; 3];\n for i in 0..3 {\n b[i] = a[i].as_bytes().try_into().unwrap();\n }\n\n writeln!(\n out,\n \"{}\",\n match solve(b) {\n Answer::Illegal => \"illegal\",\n Answer::First => \"first\",\n Answer::Second => \"second\",\n Answer::FirstWon => \"the first player won\",\n Answer::SecondWon => \"the second player won\",\n Answer::Draw => \"draw\",\n }\n )?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "games"], "code_uid": "cf9a6526c82256eb940a4828d2e1a431", "src_uid": "892680e26369325fb00d15543a96192c", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\n\nconst DIMENSION : usize = 3;\nconst NUM_SQUARES : usize = DIMENSION * DIMENSION;\nconst BLANK : u64 = 0;\nconst X : u64 = 1;\nconst O : u64 = 10;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn read_board(stdin : &Stdin, board : &mut [[u64; DIMENSION]; DIMENSION]) {\n for i in 0 .. DIMENSION {\n let mut row = String::new();\n read_line(stdin, &mut row);\n let mut j = 0;\n for c in row.trim().chars() {\n if c == '.' {\n board[i][j] = BLANK;\n } else if c == 'X' {\n board[i][j] = X;\n } else if c == '0' {\n board[i][j] = O;\n } else {\n panic!(\"Unknown square on board: {}\", c);\n }\n j = j + 1;\n }\n }\n}\n\nfn has_player_won(board: &[[u64; DIMENSION]; DIMENSION], player : u64) -> bool {\n let three_p = 3 * player;\n let row_0 = (board[0][0] + board[0][1] + board[0][2]) == three_p;\n let row_1 = (board[1][0] + board[1][1] + board[1][2]) == three_p;\n let row_2 = (board[2][0] + board[2][1] + board[2][2]) == three_p;\n let col_0 = (board[0][0] + board[1][0] + board[2][0]) == three_p;\n let col_1 = (board[0][1] + board[1][1] + board[2][1]) == three_p;\n let col_2 = (board[0][2] + board[1][2] + board[2][2]) == three_p;\n let dia_1 = (board[0][0] + board[1][1] + board[2][2]) == three_p;\n let dia_2 = (board[0][2] + board[1][1] + board[2][0]) == three_p;\n row_0 || row_1 || row_2 || col_0 || col_1 || col_2 || dia_1 || dia_2\n}\n\nfn has_first_player_won(board : &[[u64; DIMENSION]; DIMENSION]) -> bool {\n has_player_won(board, X)\n}\n\nfn has_second_player_won(board : &[[u64; DIMENSION]; DIMENSION]) -> bool {\n has_player_won(board, O)\n}\n\nfn print_board_state(board : &[[u64; DIMENSION]; DIMENSION]) {\n let mut num_x : i64 = 0;\n let mut num_o : i64 = 0;\n for i in 0 .. DIMENSION {\n for j in 0 .. DIMENSION {\n if board[i][j] == X {\n num_x = num_x + 1;\n } else if board[i][j] == O {\n num_o = num_o + 1;\n } else {\n // Do nothing ...\n }\n }\n }\n let sum = (num_x + num_o) as usize;\n let diff = num_x - num_o;\n let first_player_won = has_first_player_won(&board);\n let second_player_won = has_second_player_won(&board);\n if diff == 0 {\n if first_player_won {\n println!(\"illegal\");\n } else if second_player_won {\n println!(\"the second player won\");\n } else {\n println!(\"first\");\n }\n } else if diff == 1 {\n if second_player_won {\n println!(\"illegal\");\n } else if first_player_won {\n println!(\"the first player won\");\n } else {\n if sum == NUM_SQUARES {\n println!(\"draw\");\n } else {\n println!(\"second\");\n }\n }\n } else {\n println!(\"illegal\");\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut board = [[BLANK; DIMENSION]; DIMENSION];\n read_board(&stdin, &mut board);\n print_board_state(&board);\n // println!(\"{:?}\", board);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "games"], "code_uid": "3b776b567610b78fb1050ab1f3c4afb6", "src_uid": "892680e26369325fb00d15543a96192c", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::prelude::*;\n\nconst PRIMES: [u128; 8] = [2, 3, 5, 7, 11, 13, 17, 19];\nconst WEIGHTS: [u128; 9] = [\n 2 * 7 * 17,\n 2 * 11,\n 2 * 13 * 19,\n 7 * 3,\n 11 * 3 * 19 * 17,\n 3 * 13,\n 5 * 7 * 19,\n 5 * 11,\n 5 * 13 * 17,\n];\n\nfn count_powers_of(x: u128, y: u128) -> u128 {\n let mut x = x;\n let mut n = 0;\n while x != 0 && x % y == 0 {\n n += 1;\n x /= y;\n }\n n\n}\n\nfn ix(c: char) -> usize {\n match c {\n 'X' => 1,\n _ => 0,\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let lines = stdin.lock().lines();\n let board = lines.map(|r| r.unwrap()).take(3).collect::();\n let mut count = vec![0, 0];\n let mut prod = vec![1u128, 1];\n let mut wins = vec![0, 0];\n for (i, c) in board.chars().enumerate().filter(|p| p.1 != '.') {\n count[ix(c)] += 1;\n prod[ix(c)] *= WEIGHTS[i];\n }\n for i in 0..2 {\n for p in PRIMES.iter() {\n if count_powers_of(prod[i], *p) == 3 {\n wins[i] += 1;\n }\n }\n }\n if count[0] != count[1] && count[0] != count[1] - 1\n || wins[0] > 2\n || wins[1] > 2\n || wins[0] * wins[1] != 0\n || wins[0] > 0 && count[0] != count[1]\n || wins[1] > 0 && count[0] != count[1] - 1\n {\n println!(\"illegal\");\n } else if count[0] == 4 && count[1] == 5 && wins[0] + wins[1] == 0 {\n println!(\"draw\");\n } else if wins[0] > 0 {\n println!(\"the second player won\");\n } else if wins[1] > 0 {\n println!(\"the first player won\");\n } else if count[0] == count[1] {\n println!(\"first\");\n } else {\n println!(\"second\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "games"], "code_uid": "9bbad9a59df697606cd27db46001e0b1", "src_uid": "892680e26369325fb00d15543a96192c", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_variables)]\n#![allow(unused_must_use)]\nuse collections::*;\nuse std::io::Write;\nuse std::*;\n\nfn test_case(sc: &mut input::In, out: &mut std::io::BufWriter) {\n let n: usize = sc.read();\n let m: usize = sc.read();\n let modd: usize = 998244353;\n let mut prime: Vec = vec![true; n + 1];\n for i in 2..(n + 1) {\n if prime[i] {\n for j in i..(n / i + 1) {\n prime[j * i] = false;\n }\n }\n }\n let mut ans: usize = 0;\n\n let mut mul = m % modd;\n let mut cnt = m % modd;\n let mut lcm: usize = 1;\n for i in 2..(n + 1) {\n let mut t = 0;\n cnt = cnt * (m % modd) % modd;\n if lcm <= m {\n if prime[i] {\n lcm *= i;\n }\n t = m / lcm;\n }\n mul = mul * (t % modd) % modd;\n ans = (ans + modd + cnt - mul) % modd;\n }\n\n writeln!(out, \"{}\", ans);\n}\n\nfn main() {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut sc = input::In::new(&s);\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n let t = 1;\n // let t: usize = sc.read();\n for _ in 0..t {\n test_case(&mut sc, &mut out);\n }\n}\n\nmod input {\n use std::str::FromStr;\n use std::str::SplitWhitespace;\n pub struct In<'a> {\n iter: SplitWhitespace<'a>,\n }\n impl<'a> In<'a> {\n pub fn new(s: &'a String) -> Self {\n Self {\n iter: s.split_whitespace(),\n }\n }\n pub fn read(&mut self) -> T {\n self.iter.next().unwrap().parse::().ok().unwrap()\n }\n\n pub fn read_bytes(&mut self) -> Vec {\n self.iter.next().unwrap().bytes().collect()\n }\n pub fn read_chars(&mut self) -> Vec {\n self.iter.next().unwrap().chars().collect()\n }\n pub fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "3495abd99d9d26d750be6afd573d058b", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::{str::FromStr, fmt::Debug};\r\nfn read_line() -> String {\r\n let mut line = String::new();\r\n std::io::stdin().read_line(&mut line).expect(\"\");\r\n return line;\r\n}\r\nfn read() -> T where ::Err: Debug{\r\n return read_line().trim().parse::().unwrap();\r\n}\r\nfn reads() -> Vec where ::Err: Debug{\r\n return read_line().trim().split(' ').map(|x| x.parse::().unwrap()).collect();\r\n}\r\nfn main() {\r\n let modint = 998244353;\r\n let nm = reads::();\r\n let n = nm[0];\r\n let m = nm[1];\r\n let mut a = Vec::::new();\r\n a.resize(n as usize + 1, 0);\r\n let mut is_prime = Vec::::new();\r\n is_prime.resize(n as usize + 1, true);\r\n a[1] = m;\r\n let mut lcm = 1;\r\n let mut x = 0;\r\n let mut y = 0;\r\n let mut p = 1;\r\n for i in 2..n + 1 {\r\n if is_prime[i as usize] {\r\n let mut j = i + i;\r\n while j <= n {\r\n is_prime[j as usize] = false;\r\n j += i;\r\n }\r\n }\r\n }\r\n for i in 1..n + 1 {\r\n p = m % modint * p % modint; \r\n x = (x + p) % modint;\r\n if is_prime[i as usize] {\r\n lcm = std::cmp::min(lcm * i, m + 1);\r\n }\r\n a[i as usize] = m / lcm;\r\n }\r\n for i in (1..n + 1).rev() {\r\n y = a[i as usize] % modint * (y + 1) % modint;\r\n }\r\n println!(\"{}\", (x + modint - y) % modint);\r\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "6b677fc2e772b81aa84b9bb357830560", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "type Mint = ModInt998244353;\n\nfn main() {\n let mut sc = Scanner::new();\n let n: u64 = sc.next_num();\n let m: u64 = sc.next_num();\n\n let mut is_prime = vec![true; n as usize + 1];\n is_prime[1] = false;\n for i in 2..n + 1 {\n if !is_prime[i as usize] {\n continue;\n }\n let mut k = 2;\n while i * k <= n {\n is_prime[(i * k) as usize] = false;\n k += 1;\n }\n }\n\n let mut ans = Mint::from(0);\n let mut pow_m = Mint::from(1);\n let mut tmp = Mint::from(1);\n let mut l = 1;\n for i in 1..=n {\n if l <= m && is_prime[i as usize] {\n l *= i;\n }\n pow_m *= m;\n tmp *= m / l;\n ans += pow_m - tmp;\n }\n println!(\"{}\", ans);\n}\n\n//https://github.com/rust-lang-ja/ac-library-rs\n\npub mod internal_math {\n // remove this after dependencies has been added\n #![allow(dead_code)]\n use std::mem::swap;\n\n /// # Arguments\n /// * `m` `1 <= m`\n ///\n /// # Returns\n /// x mod m\n /* const */\n pub(crate) fn safe_mod(mut x: i64, m: i64) -> i64 {\n x %= m;\n if x < 0 {\n x += m;\n }\n x\n }\n\n /// Fast modular by barrett reduction\n /// Reference: https://en.wikipedia.org/wiki/Barrett_reduction\n /// NOTE: reconsider after Ice Lake\n pub(crate) struct Barrett {\n pub(crate) _m: u32,\n pub(crate) im: u64,\n }\n\n impl Barrett {\n /// # Arguments\n /// * `m` `1 <= m`\n /// (Note: `m <= 2^31` should also hold, which is undocumented in the original library.\n /// See the [pull reqeust commment](https://github.com/rust-lang-ja/ac-library-rs/pull/3#discussion_r484661007)\n /// for more details.)\n pub(crate) fn new(m: u32) -> Barrett {\n Barrett {\n _m: m,\n im: (-1i64 as u64 / m as u64).wrapping_add(1),\n }\n }\n\n /// # Returns\n /// `m`\n pub(crate) fn umod(&self) -> u32 {\n self._m\n }\n\n /// # Parameters\n /// * `a` `0 <= a < m`\n /// * `b` `0 <= b < m`\n ///\n /// # Returns\n /// a * b % m\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn mul(&self, a: u32, b: u32) -> u32 {\n mul_mod(a, b, self._m, self.im)\n }\n }\n\n /// Calculates `a * b % m`.\n ///\n /// * `a` `0 <= a < m`\n /// * `b` `0 <= b < m`\n /// * `m` `1 <= m <= 2^31`\n /// * `im` = ceil(2^64 / `m`)\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn mul_mod(a: u32, b: u32, m: u32, im: u64) -> u32 {\n // [1] m = 1\n // a = b = im = 0, so okay\n\n // [2] m >= 2\n // im = ceil(2^64 / m)\n // -> im * m = 2^64 + r (0 <= r < m)\n // let z = a*b = c*m + d (0 <= c, d < m)\n // a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im\n // c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2\n // ((ab * im) >> 64) == c or c + 1\n let mut z = a as u64;\n z *= b as u64;\n let x = (((z as u128) * (im as u128)) >> 64) as u64;\n let mut v = z.wrapping_sub(x.wrapping_mul(m as u64)) as u32;\n if m <= v {\n v = v.wrapping_add(m);\n }\n v\n }\n\n /// # Parameters\n /// * `n` `0 <= n`\n /// * `m` `1 <= m`\n ///\n /// # Returns\n /// `(x ** n) % m`\n /* const */\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn pow_mod(x: i64, mut n: i64, m: i32) -> i64 {\n if m == 1 {\n return 0;\n }\n let _m = m as u32;\n let mut r: u64 = 1;\n let mut y: u64 = safe_mod(x, m as i64) as u64;\n while n != 0 {\n if (n & 1) > 0 {\n r = (r * y) % (_m as u64);\n }\n y = (y * y) % (_m as u64);\n n >>= 1;\n }\n r as i64\n }\n\n /// Reference:\n /// M. Forisek and J. Jancina,\n /// Fast Primality Testing for Integers That Fit into a Machine Word\n ///\n /// # Parameters\n /// * `n` `0 <= n`\n /* const */\n pub(crate) fn is_prime(n: i32) -> bool {\n let n = n as i64;\n match n {\n _ if n <= 1 => return false,\n 2 | 7 | 61 => return true,\n _ if n % 2 == 0 => return false,\n _ => {}\n }\n let mut d = n - 1;\n while d % 2 == 0 {\n d /= 2;\n }\n for &a in &[2, 7, 61] {\n let mut t = d;\n let mut y = pow_mod(a, t, n as i32);\n while t != n - 1 && y != 1 && y != n - 1 {\n y = y * y % n;\n t <<= 1;\n }\n if y != n - 1 && t % 2 == 0 {\n return false;\n }\n }\n true\n }\n\n // omitted\n // template constexpr bool is_prime = is_prime_constexpr(n);\n\n /// # Parameters\n /// * `b` `1 <= b`\n ///\n /// # Returns\n /// (g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n /* const */\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = safe_mod(a, b);\n if a == 0 {\n return (b, 0);\n }\n\n // Contracts:\n // [1] s - m0 * a = 0 (mod b)\n // [2] t - m1 * a = 0 (mod b)\n // [3] s * |m1| + t * |m0| <= b\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\n\n // [3]:\n // (s - t * u) * |m1| + t * |m0 - m1 * u|\n // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)\n // = s * |m1| + t * |m0| <= b\n\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n // by [3]: |m0| <= b/g\n // by g != b: |m0| < b/g\n if m0 < 0 {\n m0 += b / s;\n }\n (s, m0)\n }\n\n /// Compile time (currently not) primitive root\n /// @param m must be prime\n /// @return primitive root (and minimum in now)\n /* const */\n pub(crate) fn primitive_root(m: i32) -> i32 {\n match m {\n 2 => return 1,\n 167_772_161 => return 3,\n 469_762_049 => return 3,\n 754_974_721 => return 11,\n 998_244_353 => return 3,\n _ => {}\n }\n\n let mut divs = [0; 20];\n divs[0] = 2;\n let mut cnt = 1;\n let mut x = (m - 1) / 2;\n while x % 2 == 0 {\n x /= 2;\n }\n for i in (3..std::i32::MAX).step_by(2) {\n if i as i64 * i as i64 > x as i64 {\n break;\n }\n if x % i == 0 {\n divs[cnt] = i;\n cnt += 1;\n while x % i == 0 {\n x /= i;\n }\n }\n }\n if x > 1 {\n divs[cnt] = x;\n cnt += 1;\n }\n let mut g = 2;\n loop {\n if (0..cnt).all(|i| pow_mod(g, ((m - 1) / divs[i]) as i64, m) != 1) {\n break g as i32;\n }\n g += 1;\n }\n }\n // omitted\n // template constexpr int primitive_root = primitive_root_constexpr(m);\n\n #[cfg(test)]\n mod tests {\n #![allow(clippy::unreadable_literal)]\n #![allow(clippy::cognitive_complexity)]\n use crate::internal_math::{inv_gcd, is_prime, pow_mod, primitive_root, safe_mod, Barrett};\n use std::collections::HashSet;\n\n #[test]\n fn test_safe_mod() {\n assert_eq!(safe_mod(0, 3), 0);\n assert_eq!(safe_mod(1, 3), 1);\n assert_eq!(safe_mod(2, 3), 2);\n assert_eq!(safe_mod(3, 3), 0);\n assert_eq!(safe_mod(4, 3), 1);\n assert_eq!(safe_mod(5, 3), 2);\n assert_eq!(safe_mod(73, 11), 7);\n assert_eq!(safe_mod(2306249155046129918, 6620319213327), 1374210749525);\n\n assert_eq!(safe_mod(-1, 3), 2);\n assert_eq!(safe_mod(-2, 3), 1);\n assert_eq!(safe_mod(-3, 3), 0);\n assert_eq!(safe_mod(-4, 3), 2);\n assert_eq!(safe_mod(-5, 3), 1);\n assert_eq!(safe_mod(-7170500492396019511, 777567337), 333221848);\n }\n\n #[test]\n fn test_barrett() {\n let b = Barrett::new(7);\n assert_eq!(b.umod(), 7);\n assert_eq!(b.mul(2, 3), 6);\n assert_eq!(b.mul(4, 6), 3);\n assert_eq!(b.mul(5, 0), 0);\n\n let b = Barrett::new(998244353);\n assert_eq!(b.umod(), 998244353);\n assert_eq!(b.mul(2, 3), 6);\n assert_eq!(b.mul(3141592, 653589), 919583920);\n assert_eq!(b.mul(323846264, 338327950), 568012980);\n\n // make `z - x * self._m as u64` overflow.\n // Thanks @koba-e964 (at https://github.com/rust-lang-ja/ac-library-rs/pull/3#discussion_r484932161)\n let b = Barrett::new(2147483647);\n assert_eq!(b.umod(), 2147483647);\n assert_eq!(b.mul(1073741824, 2147483645), 2147483646);\n }\n\n #[test]\n fn test_pow_mod() {\n assert_eq!(pow_mod(0, 0, 1), 0);\n assert_eq!(pow_mod(0, 0, 3), 1);\n assert_eq!(pow_mod(0, 0, 723), 1);\n assert_eq!(pow_mod(0, 0, 998244353), 1);\n assert_eq!(pow_mod(0, 0, i32::max_value()), 1);\n\n assert_eq!(pow_mod(0, 1, 1), 0);\n assert_eq!(pow_mod(0, 1, 3), 0);\n assert_eq!(pow_mod(0, 1, 723), 0);\n assert_eq!(pow_mod(0, 1, 998244353), 0);\n assert_eq!(pow_mod(0, 1, i32::max_value()), 0);\n\n assert_eq!(pow_mod(0, i64::max_value(), 1), 0);\n assert_eq!(pow_mod(0, i64::max_value(), 3), 0);\n assert_eq!(pow_mod(0, i64::max_value(), 723), 0);\n assert_eq!(pow_mod(0, i64::max_value(), 998244353), 0);\n assert_eq!(pow_mod(0, i64::max_value(), i32::max_value()), 0);\n\n assert_eq!(pow_mod(1, 0, 1), 0);\n assert_eq!(pow_mod(1, 0, 3), 1);\n assert_eq!(pow_mod(1, 0, 723), 1);\n assert_eq!(pow_mod(1, 0, 998244353), 1);\n assert_eq!(pow_mod(1, 0, i32::max_value()), 1);\n\n assert_eq!(pow_mod(1, 1, 1), 0);\n assert_eq!(pow_mod(1, 1, 3), 1);\n assert_eq!(pow_mod(1, 1, 723), 1);\n assert_eq!(pow_mod(1, 1, 998244353), 1);\n assert_eq!(pow_mod(1, 1, i32::max_value()), 1);\n\n assert_eq!(pow_mod(1, i64::max_value(), 1), 0);\n assert_eq!(pow_mod(1, i64::max_value(), 3), 1);\n assert_eq!(pow_mod(1, i64::max_value(), 723), 1);\n assert_eq!(pow_mod(1, i64::max_value(), 998244353), 1);\n assert_eq!(pow_mod(1, i64::max_value(), i32::max_value()), 1);\n\n assert_eq!(pow_mod(i64::max_value(), 0, 1), 0);\n assert_eq!(pow_mod(i64::max_value(), 0, 3), 1);\n assert_eq!(pow_mod(i64::max_value(), 0, 723), 1);\n assert_eq!(pow_mod(i64::max_value(), 0, 998244353), 1);\n assert_eq!(pow_mod(i64::max_value(), 0, i32::max_value()), 1);\n\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 1), 0);\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 3), 1);\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 723), 640);\n assert_eq!(\n pow_mod(i64::max_value(), i64::max_value(), 998244353),\n 683296792\n );\n assert_eq!(\n pow_mod(i64::max_value(), i64::max_value(), i32::max_value()),\n 1\n );\n\n assert_eq!(pow_mod(2, 3, 1_000_000_007), 8);\n assert_eq!(pow_mod(5, 7, 1_000_000_007), 78125);\n assert_eq!(pow_mod(123, 456, 1_000_000_007), 565291922);\n }\n\n #[test]\n fn test_is_prime() {\n assert!(!is_prime(0));\n assert!(!is_prime(1));\n assert!(is_prime(2));\n assert!(is_prime(3));\n assert!(!is_prime(4));\n assert!(is_prime(5));\n assert!(!is_prime(6));\n assert!(is_prime(7));\n assert!(!is_prime(8));\n assert!(!is_prime(9));\n\n // assert!(is_prime(57));\n assert!(!is_prime(57));\n assert!(!is_prime(58));\n assert!(is_prime(59));\n assert!(!is_prime(60));\n assert!(is_prime(61));\n assert!(!is_prime(62));\n\n assert!(!is_prime(701928443));\n assert!(is_prime(998244353));\n assert!(!is_prime(1_000_000_000));\n assert!(is_prime(1_000_000_007));\n\n assert!(is_prime(i32::max_value()));\n }\n\n #[test]\n fn test_is_prime_sieve() {\n let n = 1_000_000;\n let mut prime = vec![true; n];\n prime[0] = false;\n prime[1] = false;\n for i in 0..n {\n assert_eq!(prime[i], is_prime(i as i32));\n if prime[i] {\n for j in (2 * i..n).step_by(i) {\n prime[j] = false;\n }\n }\n }\n }\n\n #[test]\n fn test_inv_gcd() {\n for &(a, b, g) in &[\n (0, 1, 1),\n (0, 4, 4),\n (0, 7, 7),\n (2, 3, 1),\n (-2, 3, 1),\n (4, 6, 2),\n (-4, 6, 2),\n (13, 23, 1),\n (57, 81, 3),\n (12345, 67890, 15),\n (-3141592 * 6535, 3141592 * 8979, 3141592),\n (i64::max_value(), i64::max_value(), i64::max_value()),\n (i64::min_value(), i64::max_value(), 1),\n ] {\n let (g_, x) = inv_gcd(a, b);\n assert_eq!(g, g_);\n let b_ = b as i128;\n assert_eq!(((x as i128 * a as i128) % b_ + b_) % b_, g as i128 % b_);\n }\n }\n\n #[test]\n fn test_primitive_root() {\n for &p in &[\n 2,\n 3,\n 5,\n 7,\n 233,\n 200003,\n 998244353,\n 1_000_000_007,\n i32::max_value(),\n ] {\n assert!(is_prime(p));\n let g = primitive_root(p);\n if p != 2 {\n assert_ne!(g, 1);\n }\n\n let q = p - 1;\n for i in (2..i32::max_value()).take_while(|i| i * i <= q) {\n if q % i != 0 {\n break;\n }\n for &r in &[i, q / i] {\n assert_ne!(pow_mod(g as i64, r as i64, p), 1);\n }\n }\n assert_eq!(pow_mod(g as i64, q as i64, p), 1);\n\n if p < 1_000_000 {\n assert_eq!(\n (0..p - 1)\n .scan(1, |i, _| {\n *i = *i * g % p;\n Some(*i)\n })\n .collect::>()\n .len() as i32,\n p - 1\n );\n }\n }\n }\n }\n}\npub mod modint {\n //! Structs that treat the modular arithmetic.\n //!\n //! For most of the problems, It is sufficient to use [`ModInt1000000007`] or [`ModInt998244353`], which can be used as follows.\n //!\n //! ```\n //! use ac_library_rs::ModInt1000000007 as Mint; // rename to whatever you want\n //! use proconio::{input, source::once::OnceSource};\n //!\n //! input! {\n //! from OnceSource::from(\"1000000006 2\\n\"),\n //! a: Mint,\n //! b: Mint,\n //! }\n //!\n //! println!(\"{}\", a + b); // `1`\n //! ```\n //!\n //! If the modulus is not fixed, you can use [`ModInt`] as follows.\n //!\n //! ```\n //! use ac_library_rs::ModInt as Mint; // rename to whatever you want\n //! use proconio::{input, source::once::OnceSource};\n //!\n //! input! {\n //! from OnceSource::from(\"3 3 7\\n\"),\n //! a: u32,\n //! b: u32,\n //! m: u32,\n //! }\n //!\n //! Mint::set_modulus(m);\n //! let a = Mint::new(a);\n //! let b = Mint::new(b);\n //!\n //! println!(\"{}\", a * b); // `2`\n //! ```\n //!\n //! # Major changes from the original ACL\n //!\n //! - Converted the struct names to PascalCase.\n //! - Renamed `mod` \u2192 `modulus`.\n //! - Moduli are `u32`, not `i32`.\n //! - Each `Id` does not have a identifier number. Instead, they explicitly own `&'static LocalKey>`.\n //! - The type of the argument of `pow` is `u64`, not `i64`.\n //! - Modints implement `FromStr` and `Display`. Modints in the original ACL don't have `operator<<` or `operator>>`.\n //!\n //! [`ModInt1000000007`]: ./type.ModInt1000000007.html\n //! [`ModInt998244353`]: ./type.ModInt998244353.html\n //! [`ModInt`]: ./type.ModInt.html\n\n use crate::internal_math;\n use std::{\n cell::RefCell,\n convert::{Infallible, TryInto as _},\n fmt,\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n sync::atomic::{self, AtomicU32, AtomicU64},\n thread::LocalKey,\n };\n\n pub type ModInt1000000007 = StaticModInt;\n pub type ModInt998244353 = StaticModInt;\n pub type ModInt = DynamicModInt;\n\n /// Represents _\u2124/m\u2124_ where _m_ is a constant value.\n ///\n /// Corresponds to `atcoder::static_modint` in the original ACL.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::ModInt1000000007 as Mint;\n /// use proconio::{input, source::once::OnceSource};\n ///\n /// input! {\n /// from OnceSource::from(\"1000000006 2\\n\"),\n /// a: Mint,\n /// b: Mint,\n /// }\n ///\n /// println!(\"{}\", a + b); // `1`\n /// ```\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct StaticModInt {\n val: u32,\n phantom: PhantomData M>,\n }\n\n impl StaticModInt {\n /// Returns the modulus, which is [`::VALUE`].\n ///\n /// Corresponds to `atcoder::static_modint::mod` in the original ACL.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::ModInt1000000007 as Mint;\n ///\n /// assert_eq!(1_000_000_007, Mint::modulus());\n /// ```\n ///\n /// [`::VALUE`]: ../trait.Modulus.html#associatedconstant.VALUE\n #[inline(always)]\n pub fn modulus() -> u32 {\n M::VALUE\n }\n\n /// Creates a new `StaticModInt`.\n ///\n /// Takes [any primitive integer].\n ///\n /// Corresponds to the constructor of `atcoder::static_modint` in the original ACL.\n ///\n /// [any primitive integer]: ../trait.RemEuclidU32.html\n #[inline]\n pub fn new(val: T) -> Self {\n Self::raw(val.rem_euclid_u32(M::VALUE))\n }\n\n /// Constructs a `StaticModInt` from a `val < Self::modulus()` without checking it.\n ///\n /// Corresponds to `atcoder::static_modint::raw` in the original ACL.\n ///\n /// # Constraints\n ///\n /// - `val` is less than `Self::modulus()`\n ///\n /// See [`ModIntBase::raw`] for more more details.\n ///\n /// [`ModIntBase::raw`]: ./trait.ModIntBase.html#tymethod.raw\n #[inline]\n pub fn raw(val: u32) -> Self {\n Self {\n val,\n phantom: PhantomData,\n }\n }\n\n /// Retruns the representative.\n ///\n /// Corresponds to `atcoder::static_modint::val` in the original ACL.\n #[inline]\n pub fn val(self) -> u32 {\n self.val\n }\n\n /// Returns `self` to the power of `n`.\n ///\n /// Corresponds to `atcoder::static_modint::pow` in the original ACL.\n #[inline]\n pub fn pow(self, n: u64) -> Self {\n ::pow(self, n)\n }\n\n /// Retruns the multiplicative inverse of `self`.\n ///\n /// Corresponds to `atcoder::static_modint::inv` in the original ACL.\n ///\n /// # Panics\n ///\n /// Panics if the multiplicative inverse does not exist.\n #[inline]\n pub fn inv(self) -> Self {\n if M::HINT_VALUE_IS_PRIME {\n if self.val() == 0 {\n panic!(\"attempt to divide by zero\");\n }\n debug_assert!(\n internal_math::is_prime(M::VALUE.try_into().unwrap()),\n \"{} is not a prime number\",\n M::VALUE,\n );\n self.pow((M::VALUE - 2).into())\n } else {\n Self::inv_for_non_prime_modulus(self)\n }\n }\n }\n\n /// These methods are implemented for the struct.\n /// You don't need to `use` `ModIntBase` to call methods of `StaticModInt`.\n impl ModIntBase for StaticModInt {\n #[inline(always)]\n fn modulus() -> u32 {\n Self::modulus()\n }\n\n #[inline]\n fn raw(val: u32) -> Self {\n Self::raw(val)\n }\n\n #[inline]\n fn val(self) -> u32 {\n self.val()\n }\n\n #[inline]\n fn inv(self) -> Self {\n self.inv()\n }\n }\n\n /// Represents a modulus.\n ///\n /// # Example\n ///\n /// ```\n /// macro_rules! modulus {\n /// ($($name:ident($value:expr, $is_prime:expr)),*) => {\n /// $(\n /// #[derive(Copy, Clone, Eq, PartialEq)]\n /// enum $name {}\n ///\n /// impl ac_library_rs::modint::Modulus for $name {\n /// const VALUE: u32 = $value;\n /// const HINT_VALUE_IS_PRIME: bool = $is_prime;\n ///\n /// fn butterfly_cache() -> &'static ::std::thread::LocalKey<::std::cell::RefCell<::std::option::Option>>> {\n /// thread_local! {\n /// static BUTTERFLY_CACHE: ::std::cell::RefCell<::std::option::Option>> = ::std::default::Default::default();\n /// }\n /// &BUTTERFLY_CACHE\n /// }\n /// }\n /// )*\n /// };\n /// }\n ///\n /// use ac_library_rs::StaticModInt;\n ///\n /// modulus!(Mod101(101, true), Mod103(103, true));\n ///\n /// type Z101 = StaticModInt;\n /// type Z103 = StaticModInt;\n ///\n /// assert_eq!(Z101::new(101), Z101::new(0));\n /// assert_eq!(Z103::new(103), Z103::new(0));\n /// ```\n pub trait Modulus: 'static + Copy + Eq {\n const VALUE: u32;\n const HINT_VALUE_IS_PRIME: bool;\n\n fn butterfly_cache() -> &'static LocalKey>>>;\n }\n\n /// Represents _1000000007_.\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum Mod1000000007 {}\n\n impl Modulus for Mod1000000007 {\n const VALUE: u32 = 1_000_000_007;\n const HINT_VALUE_IS_PRIME: bool = true;\n\n fn butterfly_cache() -> &'static LocalKey>>> {\n thread_local! {\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\n }\n &BUTTERFLY_CACHE\n }\n }\n\n /// Represents _998244353_.\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum Mod998244353 {}\n\n impl Modulus for Mod998244353 {\n const VALUE: u32 = 998_244_353;\n const HINT_VALUE_IS_PRIME: bool = true;\n\n fn butterfly_cache() -> &'static LocalKey>>> {\n thread_local! {\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\n }\n &BUTTERFLY_CACHE\n }\n }\n\n /// Cache for butterfly operations.\n pub struct ButterflyCache {\n pub(crate) sum_e: Vec>,\n pub(crate) sum_ie: Vec>,\n }\n\n /// Represents _\u2124/m\u2124_ where _m_ is a dynamic value.\n ///\n /// Corresponds to `atcoder::dynamic_modint` in the original ACL.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::ModInt as Mint;\n /// use proconio::{input, source::once::OnceSource};\n ///\n /// input! {\n /// from OnceSource::from(\"3 3 7\\n\"),\n /// a: u32,\n /// b: u32,\n /// m: u32,\n /// }\n ///\n /// Mint::set_modulus(m);\n /// let a = Mint::new(a);\n /// let b = Mint::new(b);\n ///\n /// println!(\"{}\", a * b); // `2`\n /// ```\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct DynamicModInt {\n val: u32,\n phantom: PhantomData I>,\n }\n\n impl DynamicModInt {\n /// Returns the modulus.\n ///\n /// Corresponds to `atcoder::dynamic_modint::mod` in the original ACL.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::ModInt as Mint;\n ///\n /// assert_eq!(998_244_353, Mint::modulus()); // default modulus\n /// ```\n #[inline]\n pub fn modulus() -> u32 {\n I::companion_barrett().umod()\n }\n\n /// Sets a modulus.\n ///\n /// Corresponds to `atcoder::dynamic_modint::set_mod` in the original ACL.\n ///\n /// # Constraints\n ///\n /// - This function must be called earlier than any other operation of `Self`.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::ModInt as Mint;\n ///\n /// Mint::set_modulus(7);\n /// assert_eq!(7, Mint::modulus());\n /// ```\n #[inline]\n pub fn set_modulus(modulus: u32) {\n if modulus == 0 {\n panic!(\"the modulus must not be 0\");\n }\n I::companion_barrett().update(modulus);\n }\n\n /// Creates a new `DynamicModInt`.\n ///\n /// Takes [any primitive integer].\n ///\n /// Corresponds to the constructor of `atcoder::dynamic_modint` in the original ACL.\n ///\n /// [any primitive integer]: ../trait.RemEuclidU32.html\n #[inline]\n pub fn new(val: T) -> Self {\n ::new(val)\n }\n\n /// Constructs a `DynamicModInt` from a `val < Self::modulus()` without checking it.\n ///\n /// Corresponds to `atcoder::dynamic_modint::raw` in the original ACL.\n ///\n /// # Constraints\n ///\n /// - `val` is less than `Self::modulus()`\n ///\n /// See [`ModIntBase::raw`] for more more details.\n ///\n /// [`ModIntBase::raw`]: ./trait.ModIntBase.html#tymethod.raw\n #[inline]\n pub fn raw(val: u32) -> Self {\n Self {\n val,\n phantom: PhantomData,\n }\n }\n\n /// Retruns the representative.\n ///\n /// Corresponds to `atcoder::static_modint::val` in the original ACL.\n #[inline]\n pub fn val(self) -> u32 {\n self.val\n }\n\n /// Returns `self` to the power of `n`.\n ///\n /// Corresponds to `atcoder::dynamic_modint::pow` in the original ACL.\n #[inline]\n pub fn pow(self, n: u64) -> Self {\n ::pow(self, n)\n }\n\n /// Retruns the multiplicative inverse of `self`.\n ///\n /// Corresponds to `atcoder::dynamic_modint::inv` in the original ACL.\n ///\n /// # Panics\n ///\n /// Panics if the multiplicative inverse does not exist.\n #[inline]\n pub fn inv(self) -> Self {\n Self::inv_for_non_prime_modulus(self)\n }\n }\n\n /// These methods are implemented for the struct.\n /// You don't need to `use` `ModIntBase` to call methods of `DynamicModInt`.\n impl ModIntBase for DynamicModInt {\n #[inline]\n fn modulus() -> u32 {\n Self::modulus()\n }\n\n #[inline]\n fn raw(val: u32) -> Self {\n Self::raw(val)\n }\n\n #[inline]\n fn val(self) -> u32 {\n self.val()\n }\n\n #[inline]\n fn inv(self) -> Self {\n self.inv()\n }\n }\n\n pub trait Id: 'static + Copy + Eq {\n fn companion_barrett() -> &'static Barrett;\n }\n\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum DefaultId {}\n\n impl Id for DefaultId {\n fn companion_barrett() -> &'static Barrett {\n static BARRETT: Barrett = Barrett::default();\n &BARRETT\n }\n }\n\n /// Pair of _m_ and _ceil(2\u2076\u2074/m)_.\n pub struct Barrett {\n m: AtomicU32,\n im: AtomicU64,\n }\n\n impl Barrett {\n /// Creates a new `Barrett`.\n #[inline]\n pub const fn new(m: u32) -> Self {\n Self {\n m: AtomicU32::new(m),\n im: AtomicU64::new((-1i64 as u64 / m as u64).wrapping_add(1)),\n }\n }\n\n #[inline]\n const fn default() -> Self {\n Self::new(998_244_353)\n }\n\n #[inline]\n fn update(&self, m: u32) {\n let im = (-1i64 as u64 / m as u64).wrapping_add(1);\n self.m.store(m, atomic::Ordering::SeqCst);\n self.im.store(im, atomic::Ordering::SeqCst);\n }\n\n #[inline]\n fn umod(&self) -> u32 {\n self.m.load(atomic::Ordering::SeqCst)\n }\n\n #[inline]\n fn mul(&self, a: u32, b: u32) -> u32 {\n let m = self.m.load(atomic::Ordering::SeqCst);\n let im = self.im.load(atomic::Ordering::SeqCst);\n internal_math::mul_mod(a, b, m, im)\n }\n }\n\n impl Default for Barrett {\n #[inline]\n fn default() -> Self {\n Self::default()\n }\n }\n\n /// A trait for [`StaticModInt`] and [`DynamicModInt`].\n ///\n /// Corresponds to `atcoder::internal::modint_base` in the original ACL.\n ///\n /// [`StaticModInt`]: ../struct.StaticModInt.html\n /// [`DynamicModInt`]: ../struct.DynamicModInt.html\n pub trait ModIntBase:\n Default\n + FromStr\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + Copy\n + Eq\n + Hash\n + fmt::Display\n + fmt::Debug\n + Neg\n + Add\n + Sub\n + Mul\n + Div\n + AddAssign\n + SubAssign\n + MulAssign\n + DivAssign\n {\n /// Returns the modulus.\n ///\n /// Corresponds to `atcoder::static_modint::mod` and `atcoder::dynamic_modint::mod` in the original ACL.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::modint::ModIntBase;\n ///\n /// fn f() {\n /// let _: u32 = Z::modulus();\n /// }\n /// ```\n fn modulus() -> u32;\n\n /// Constructs a `Self` from a `val < Self::modulus()` without checking it.\n ///\n /// Corresponds to `atcoder::static_modint::raw` and `atcoder::dynamic_modint::raw` in the original ACL.\n ///\n /// # Constraints\n ///\n /// - `val` is less than `Self::modulus()`\n ///\n /// **Note that all operations assume that inner values are smaller than the modulus.**\n /// If `val` is greater than or equal to `Self::modulus()`, the behaviors are not defined.\n ///\n /// ```should_panic\n /// use ac_library_rs::ModInt1000000007 as Mint;\n ///\n /// let x = Mint::raw(1_000_000_007);\n /// let y = x + x;\n /// assert_eq!(0, y.val());\n /// ```\n ///\n /// ```text\n /// thread 'main' panicked at 'assertion failed: `(left == right)`\n /// left: `0`,\n /// right: `1000000007`', src/modint.rs:8:1\n /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n /// ```\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::modint::ModIntBase;\n ///\n /// fn f() -> Z {\n /// debug_assert!(Z::modulus() >= 100);\n ///\n /// let mut acc = Z::new(0);\n /// for i in 0..100 {\n /// if i % 3 == 0 {\n /// // I know `i` is smaller than the modulus!\n /// acc += Z::raw(i);\n /// }\n /// }\n /// acc\n /// }\n /// ```\n fn raw(val: u32) -> Self;\n\n /// Retruns the representative.\n ///\n /// Corresponds to `atcoder::static_modint::val` and `atcoder::dynamic_modint::val` in the original ACL.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::modint::ModIntBase;\n ///\n /// fn f(x: Z) {\n /// let _: u32 = x.val();\n /// }\n /// ```\n fn val(self) -> u32;\n\n /// Retruns the multiplicative inverse of `self`.\n ///\n /// Corresponds to `atcoder::static_modint::inv` and `atcoder::dynamic_modint::inv` in the original ACL.\n ///\n /// # Panics\n ///\n /// Panics if the multiplicative inverse does not exist.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::modint::ModIntBase;\n ///\n /// fn f(x: Z) {\n /// let _: Z = x.inv();\n /// }\n /// ```\n fn inv(self) -> Self;\n\n /// Creates a new `Self`.\n ///\n /// Takes [any primitive integer].\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::modint::ModIntBase;\n ///\n /// fn f() {\n /// let _ = Z::new(1u32);\n /// let _ = Z::new(1usize);\n /// let _ = Z::new(-1i64);\n /// }\n /// ```\n ///\n /// [any primitive integer]: ../trait.RemEuclidU32.html\n #[inline]\n fn new(val: T) -> Self {\n Self::raw(val.rem_euclid_u32(Self::modulus()))\n }\n\n /// Returns `self` to the power of `n`.\n ///\n /// Corresponds to `atcoder::static_modint::pow` and `atcoder::dynamic_modint::pow` in the original ACL.\n ///\n /// # Example\n ///\n /// ```\n /// use ac_library_rs::modint::ModIntBase;\n ///\n /// fn f() {\n /// let _: Z = Z::new(2).pow(3);\n /// }\n /// ```\n #[inline]\n fn pow(self, mut n: u64) -> Self {\n let mut x = self;\n let mut r = Self::raw(1);\n while n > 0 {\n if n & 1 == 1 {\n r *= x;\n }\n x *= x;\n n >>= 1;\n }\n r\n }\n }\n\n /// A trait for `{StaticModInt, DynamicModInt, ModIntBase}::new`.\n pub trait RemEuclidU32 {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n\n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n}\n\n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n\n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n\n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n}\n\n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n}\n\n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n\n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n\n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n\n trait InternalImplementations: ModIntBase {\n #[inline]\n fn inv_for_non_prime_modulus(this: Self) -> Self {\n let (gcd, x) = internal_math::inv_gcd(this.val().into(), Self::modulus().into());\n if gcd != 1 {\n panic!(\"the multiplicative inverse does not exist\");\n }\n Self::new(x)\n }\n\n #[inline]\n fn default_impl() -> Self {\n Self::raw(0)\n }\n\n #[inline]\n fn from_str_impl(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n\n #[inline]\n fn hash_impl(this: &Self, state: &mut impl Hasher) {\n this.val().hash(state)\n }\n\n #[inline]\n fn display_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\n fmt::Display::fmt(&this.val(), f)\n }\n\n #[inline]\n fn debug_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\n fmt::Debug::fmt(&this.val(), f)\n }\n\n #[inline]\n fn neg_impl(this: Self) -> Self {\n Self::sub_impl(Self::raw(0), this)\n }\n\n #[inline]\n fn add_impl(lhs: Self, rhs: Self) -> Self {\n let modulus = Self::modulus();\n let mut val = lhs.val() + rhs.val();\n if val >= modulus {\n val -= modulus;\n }\n Self::raw(val)\n }\n\n #[inline]\n fn sub_impl(lhs: Self, rhs: Self) -> Self {\n let modulus = Self::modulus();\n let mut val = lhs.val().wrapping_sub(rhs.val());\n if val >= modulus {\n val = val.wrapping_add(modulus)\n }\n Self::raw(val)\n }\n\n fn mul_impl(lhs: Self, rhs: Self) -> Self;\n\n #[inline]\n fn div_impl(lhs: Self, rhs: Self) -> Self {\n Self::mul_impl(lhs, rhs.inv())\n }\n }\n\n impl InternalImplementations for StaticModInt {\n #[inline]\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\n Self::raw((u64::from(lhs.val()) * u64::from(rhs.val()) % u64::from(M::VALUE)) as u32)\n }\n }\n\n impl InternalImplementations for DynamicModInt {\n #[inline]\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\n Self::raw(I::companion_barrett().mul(lhs.val, rhs.val))\n }\n }\n\n macro_rules! impl_basic_traits {\n () => {};\n (impl <$generic_param:ident : $generic_param_bound:tt> _ for $self:ty; $($rest:tt)*) => {\n impl <$generic_param: $generic_param_bound> Default for $self {\n #[inline]\n fn default() -> Self {\n Self::default_impl()\n }\n }\n\n impl <$generic_param: $generic_param_bound> FromStr for $self {\n type Err = Infallible;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::from_str_impl(s)\n }\n }\n\n impl<$generic_param: $generic_param_bound, V: RemEuclidU32> From for $self {\n #[inline]\n fn from(from: V) -> Self {\n Self::new(from)\n }\n }\n\n #[allow(clippy::derive_hash_xor_eq)]\n impl<$generic_param: $generic_param_bound> Hash for $self {\n #[inline]\n fn hash(&self, state: &mut H) {\n Self::hash_impl(self, state)\n }\n }\n\n impl<$generic_param: $generic_param_bound> fmt::Display for $self {\n #[inline]\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Self::display_impl(self, f)\n }\n }\n\n impl<$generic_param: $generic_param_bound> fmt::Debug for $self {\n #[inline]\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Self::debug_impl(self, f)\n }\n }\n\n impl<$generic_param: $generic_param_bound> Neg for $self {\n type Output = $self;\n\n #[inline]\n fn neg(self) -> $self {\n Self::neg_impl(self)\n }\n }\n\n impl<$generic_param: $generic_param_bound> Neg for &'_ $self {\n type Output = $self;\n\n #[inline]\n fn neg(self) -> $self {\n <$self>::neg_impl(*self)\n }\n }\n\n impl_basic_traits!($($rest)*);\n };\n}\n\n impl_basic_traits! {\n impl _ for StaticModInt ;\n impl _ for DynamicModInt;\n }\n\n macro_rules! impl_bin_ops {\n () => {};\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~ <$rhs_ty:ty> -> $output:ty { { $lhs_body:expr } ~ { $rhs_body:expr } } $($rest:tt)*) => {\n impl <$($generic_param: $generic_param_bound),*> Add<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn add(self, rhs: $rhs_ty) -> $output {\n <$output>::add_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Sub<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn sub(self, rhs: $rhs_ty) -> $output {\n <$output>::sub_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Mul<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn mul(self, rhs: $rhs_ty) -> $output {\n <$output>::mul_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Div<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn div(self, rhs: $rhs_ty) -> $output {\n <$output>::div_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl_bin_ops!($($rest)*);\n };\n}\n\n macro_rules! impl_assign_ops {\n () => {};\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~= <$rhs_ty:ty> { _ ~= { $rhs_body:expr } } $($rest:tt)*) => {\n impl <$($generic_param: $generic_param_bound),*> AddAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn add_assign(&mut self, rhs: $rhs_ty) {\n *self = *self + apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> SubAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn sub_assign(&mut self, rhs: $rhs_ty) {\n *self = *self - apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> MulAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn mul_assign(&mut self, rhs: $rhs_ty) {\n *self = *self * apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> DivAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn div_assign(&mut self, rhs: $rhs_ty) {\n *self = *self / apply($rhs_body, rhs);\n }\n }\n\n impl_assign_ops!($($rest)*);\n };\n}\n\n #[inline]\n fn apply O, X, O>(f: F, x: X) -> O {\n f(x)\n }\n\n impl_bin_ops! {\n for > ~ > -> StaticModInt { { |x| x } ~ { |x| x } }\n for > ~ <&'_ StaticModInt > -> StaticModInt { { |x| x } ~ { |&x| x } }\n for <&'_ StaticModInt > ~ > -> StaticModInt { { |&x| x } ~ { |x| x } }\n for <&'_ StaticModInt > ~ <&'_ StaticModInt > -> StaticModInt { { |&x| x } ~ { |&x| x } }\n for > ~ > -> DynamicModInt { { |x| x } ~ { |x| x } }\n for > ~ <&'_ DynamicModInt> -> DynamicModInt { { |x| x } ~ { |&x| x } }\n for <&'_ DynamicModInt> ~ > -> DynamicModInt { { |&x| x } ~ { |x| x } }\n for <&'_ DynamicModInt> ~ <&'_ DynamicModInt> -> DynamicModInt { { |&x| x } ~ { |&x| x } }\n\n for > ~ -> StaticModInt { { |x| x } ~ { StaticModInt::::new } }\n for > ~ -> DynamicModInt { { |x| x } ~ { DynamicModInt::::new } }\n }\n\n impl_assign_ops! {\n for > ~= > { _ ~= { |x| x } }\n for > ~= <&'_ StaticModInt > { _ ~= { |&x| x } }\n for > ~= > { _ ~= { |x| x } }\n for > ~= <&'_ DynamicModInt> { _ ~= { |&x| x } }\n\n for > ~= { _ ~= { StaticModInt::::new } }\n for > ~= { _ ~= { DynamicModInt::::new } }\n }\n\n macro_rules! impl_folding {\n () => {};\n (impl<$generic_param:ident : $generic_param_bound:tt> $trait:ident<_> for $self:ty { fn $method:ident(_) -> _ { _($unit:expr, $op:expr) } } $($rest:tt)*) => {\n impl<$generic_param: $generic_param_bound> $trait for $self {\n #[inline]\n fn $method(iter: S) -> Self\n where\n S: Iterator,\n {\n iter.fold($unit, $op)\n }\n }\n\n impl<'a, $generic_param: $generic_param_bound> $trait<&'a Self> for $self {\n #[inline]\n fn $method(iter: S) -> Self\n where\n S: Iterator,\n {\n iter.fold($unit, $op)\n }\n }\n\n impl_folding!($($rest)*);\n };\n}\n\n impl_folding! {\n impl Sum<_> for StaticModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\n impl Product<_> for StaticModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\n impl Sum<_> for DynamicModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\n impl Product<_> for DynamicModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\n }\n\n #[cfg(test)]\n mod tests {\n use crate::modint::ModInt1000000007;\n\n #[test]\n fn static_modint_new() {\n assert_eq!(0, ModInt1000000007::new(0u32).val);\n assert_eq!(1, ModInt1000000007::new(1u32).val);\n assert_eq!(1, ModInt1000000007::new(1_000_000_008u32).val);\n\n assert_eq!(0, ModInt1000000007::new(0u64).val);\n assert_eq!(1, ModInt1000000007::new(1u64).val);\n assert_eq!(1, ModInt1000000007::new(1_000_000_008u64).val);\n\n assert_eq!(0, ModInt1000000007::new(0usize).val);\n assert_eq!(1, ModInt1000000007::new(1usize).val);\n assert_eq!(1, ModInt1000000007::new(1_000_000_008usize).val);\n\n assert_eq!(0, ModInt1000000007::new(0i64).val);\n assert_eq!(1, ModInt1000000007::new(1i64).val);\n assert_eq!(1, ModInt1000000007::new(1_000_000_008i64).val);\n assert_eq!(1_000_000_006, ModInt1000000007::new(-1i64).val);\n }\n\n #[test]\n fn static_modint_add() {\n fn add(lhs: u32, rhs: u32) -> u32 {\n (ModInt1000000007::new(lhs) + ModInt1000000007::new(rhs)).val\n }\n\n assert_eq!(2, add(1, 1));\n assert_eq!(1, add(1_000_000_006, 2));\n }\n\n #[test]\n fn static_modint_sub() {\n fn sub(lhs: u32, rhs: u32) -> u32 {\n (ModInt1000000007::new(lhs) - ModInt1000000007::new(rhs)).val\n }\n\n assert_eq!(1, sub(2, 1));\n assert_eq!(1_000_000_006, sub(0, 1));\n }\n\n #[test]\n fn static_modint_mul() {\n fn mul(lhs: u32, rhs: u32) -> u32 {\n (ModInt1000000007::new(lhs) * ModInt1000000007::new(rhs)).val\n }\n\n assert_eq!(1, mul(1, 1));\n assert_eq!(4, mul(2, 2));\n assert_eq!(999_999_937, mul(100_000, 100_000));\n }\n\n #[test]\n fn static_modint_prime_div() {\n fn div(lhs: u32, rhs: u32) -> u32 {\n (ModInt1000000007::new(lhs) / ModInt1000000007::new(rhs)).val\n }\n\n assert_eq!(0, div(0, 1));\n assert_eq!(1, div(1, 1));\n assert_eq!(1, div(2, 2));\n assert_eq!(23_809_524, div(1, 42));\n }\n\n #[test]\n fn static_modint_sum() {\n fn sum(values: &[i64]) -> ModInt1000000007 {\n values.iter().copied().map(ModInt1000000007::new).sum()\n }\n\n assert_eq!(ModInt1000000007::new(-3), sum(&[-1, 2, -3, 4, -5]));\n }\n\n #[test]\n fn static_modint_product() {\n fn product(values: &[i64]) -> ModInt1000000007 {\n values.iter().copied().map(ModInt1000000007::new).product()\n }\n\n assert_eq!(ModInt1000000007::new(-120), product(&[-1, 2, -3, 4, -5]));\n }\n\n #[test]\n fn static_modint_binop_coercion() {\n let f = ModInt1000000007::new;\n let a = 10_293_812_usize;\n let b = 9_083_240_982_usize;\n assert_eq!(f(a) + f(b), f(a) + b);\n assert_eq!(f(a) - f(b), f(a) - b);\n assert_eq!(f(a) * f(b), f(a) * b);\n assert_eq!(f(a) / f(b), f(a) / b);\n }\n\n #[test]\n fn static_modint_assign_coercion() {\n let f = ModInt1000000007::new;\n let a = f(10_293_812_usize);\n let b = 9_083_240_982_usize;\n let expected = (((a + b) * b) - b) / b;\n let mut c = a;\n c += b;\n c *= b;\n c -= b;\n c /= b;\n assert_eq!(expected, c);\n }\n }\n}\nuse modint::*;\npub mod scanner {\n use std::{\n fmt::Debug,\n io::{stdin, Read},\n str::{FromStr, SplitWhitespace},\n };\n\n pub struct Scanner<'a> {\n ptr: *mut String,\n iter: SplitWhitespace<'a>,\n }\n\n impl Scanner<'_> {\n pub fn new() -> Scanner<'static> {\n let mut buf = String::new();\n stdin().read_to_string(&mut buf).unwrap();\n let ptr = Box::leak(Box::new(buf));\n Scanner {\n ptr,\n iter: ptr.split_whitespace(),\n }\n }\n\n pub fn next_token(&mut self) -> T\n where\n T: Ord + FromStr,\n ::Err: Debug,\n {\n self.iter.next().unwrap().parse().unwrap()\n }\n\n pub fn next_vec(&mut self, size: usize) -> Vec\n where\n T: Ord + FromStr,\n ::Err: Debug,\n {\n let mut res = Vec::with_capacity(size);\n (0..size).for_each(|_| res.push(self.next_token()));\n res\n }\n pub fn next_chars(&mut self) -> Vec {\n self.iter.next().unwrap().chars().collect()\n }\n pub fn next_bytes(&mut self) -> Vec {\n self.iter.next().unwrap().bytes().collect()\n }\n\n pub fn next_num(&mut self) -> T\n where\n T: Ord + FromStr,\n ::Err: Debug,\n {\n self.iter.next().unwrap().parse().unwrap()\n }\n }\n\n impl Drop for Scanner<'_> {\n fn drop(&mut self) {\n let _x = unsafe { Box::from_raw(self.ptr) };\n }\n }\n}\n\npub mod util {\n pub trait SetMinMax {\n fn set_min(&mut self, v: Self) -> bool;\n fn set_max(&mut self, v: Self) -> bool;\n }\n impl SetMinMax for T {\n fn set_min(&mut self, v: T) -> bool {\n *self > v && {\n *self = v;\n true\n }\n }\n fn set_max(&mut self, v: T) -> bool {\n *self < v && {\n *self = v;\n true\n }\n }\n }\n\n #[macro_export]\n macro_rules! div_floor {\n ($a:expr, $b:expr) => {\n if $b < 0 {\n if $a <= 0 {\n (-$a) / (-$b)\n } else {\n (-$a + 1) / (-$b) - 1\n }\n } else {\n if $a >= 0 {\n $a / $b\n } else {\n ($a + 1) / $b - 1\n }\n }\n };\n }\n #[macro_export]\n macro_rules! div_ceil {\n ($a:expr, $b:expr) => {\n if $b < 0 {\n if $a < 0 {\n (-$a - 1) / (-$b) + 1\n } else {\n (-$a) / (-$b)\n }\n } else {\n if $a > 0 {\n ($a - 1) / $b + 1\n } else {\n $a / $b\n }\n }\n };\n }\n}\n\nuse scanner::*;\nuse util::*;\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "3414fb7c51025222158203a69c75877b", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn main() {\r\n input! {\r\n n: usize,\r\n m: i64,\r\n }\r\n let p = sieve(n);\r\n let mut dp = vec![Z::new(0); n + 1];\r\n dp[0] = Z::new(1);\r\n let mut f = m;\r\n let mut ans = Z::new(0);\r\n for i in 1..=n {\r\n if p[i] {\r\n f /= i as i64;\r\n }\r\n dp[i] = Z::new(f) * dp[i - 1];\r\n ans += Z::new(m).pow(i as u32) - dp[i];\r\n }\r\n println!(\"{}\", ans);\r\n}\r\n\r\npub fn sieve(n: usize) -> Vec {\r\n let mut p = vec![true; n + 1];\r\n p[0] = false;\r\n p[1] = false;\r\n for i in 2..=n {\r\n if p[i] && i * i <= n {\r\n for j in (i * i..=n).step_by(i) {\r\n p[j] = false;\r\n }\r\n }\r\n }\r\n p\r\n}\r\n\r\n#[derive(Copy, Clone, Default)]\r\npub struct Z(i64);\r\n\r\nimpl Z {\r\n const MOD: i64 = 998_244_353;\r\n\r\n pub fn new(mut x: i64) -> Z {\r\n x %= Z::MOD;\r\n if x < 0 {\r\n x += Z::MOD;\r\n }\r\n Z(x)\r\n }\r\n\r\n pub fn pow(self, mut exp: u32) -> Z {\r\n let mut ans = Z::new(1);\r\n let mut base = self;\r\n while exp > 1 {\r\n if exp % 2 == 1 {\r\n ans = ans * base;\r\n }\r\n base = base * base;\r\n exp >>= 1;\r\n }\r\n ans * base\r\n }\r\n\r\n pub fn inv(self) -> Z {\r\n assert_ne!(self.0, 0);\r\n self.pow((Z::MOD - 2) as u32)\r\n }\r\n}\r\n\r\nimpl std::ops::Neg for Z {\r\n type Output = Z;\r\n\r\n fn neg(self) -> Z {\r\n Z::new(-self.0)\r\n }\r\n}\r\n\r\nimpl std::ops::Add for Z {\r\n type Output = Z;\r\n\r\n fn add(self, rhs: Z) -> Z {\r\n Z::new(self.0 + rhs.0)\r\n }\r\n}\r\n\r\nimpl std::ops::Sub for Z {\r\n type Output = Z;\r\n\r\n fn sub(self, rhs: Z) -> Z {\r\n Z::new(self.0 - rhs.0)\r\n }\r\n}\r\n\r\nimpl std::ops::Mul for Z {\r\n type Output = Z;\r\n\r\n fn mul(self, rhs: Z) -> Z {\r\n Z::new(self.0 * rhs.0)\r\n }\r\n}\r\n\r\nimpl std::ops::Div for Z {\r\n type Output = Z;\r\n\r\n fn div(self, rhs: Z) -> Z {\r\n self * rhs.inv()\r\n }\r\n}\r\n\r\nimpl std::ops::AddAssign for Z {\r\n fn add_assign(&mut self, rhs: Z) {\r\n *self = *self + rhs;\r\n }\r\n}\r\n\r\nimpl std::ops::SubAssign for Z {\r\n fn sub_assign(&mut self, rhs: Z) {\r\n *self = *self - rhs;\r\n }\r\n}\r\n\r\nimpl std::ops::MulAssign for Z {\r\n fn mul_assign(&mut self, rhs: Z) {\r\n *self = *self * rhs;\r\n }\r\n}\r\n\r\nimpl std::ops::DivAssign for Z {\r\n fn div_assign(&mut self, rhs: Z) {\r\n *self = *self / rhs;\r\n }\r\n}\r\n\r\nimpl std::fmt::Display for Z {\r\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\r\n self.0.fmt(f)\r\n }\r\n}\r\n\r\nimpl std::fmt::Debug for Z {\r\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\r\n self.0.fmt(f)\r\n }\r\n}\r\n\r\nimpl std::str::FromStr for Z {\r\n type Err = std::num::ParseIntError;\r\n\r\n fn from_str(s: &str) -> Result {\r\n Ok(Z::new(s.parse()?))\r\n }\r\n}\r\n\r\nmod io {\r\n use std::cell::RefCell;\r\n use std::io::*;\r\n\r\n std::thread_local! {\r\n pub static STDIN: RefCell = RefCell::new(stdin());\r\n pub static STDOUT: RefCell> = RefCell::new(BufWriter::new(stdout()));\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! input {\r\n () => {};\r\n (mut $var:ident: $t:tt, $($rest:tt)*) => {\r\n let mut $var = __input_inner!($t);\r\n input!($($rest)*)\r\n };\r\n ($var:ident: $t:tt, $($rest:tt)*) => {\r\n let $var = __input_inner!($t);\r\n input!($($rest)*)\r\n };\r\n (mut $var:ident: $t:tt) => {\r\n let mut $var = __input_inner!($t);\r\n };\r\n ($var:ident: $t:tt) => {\r\n let $var = __input_inner!($t);\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! __input_inner {\r\n (($($t:tt),*)) => {\r\n ($(__input_inner!($t)),*)\r\n };\r\n ([$t:tt; $n:expr]) => {\r\n (0..$n).map(|_| __input_inner!($t)).collect::>()\r\n };\r\n ([$t:tt]) => {{\r\n let n = __input_inner!(usize);\r\n (0..n).map(|_| __input_inner!($t)).collect::>()\r\n }};\r\n (chars) => {\r\n __input_inner!(String).chars().collect::>()\r\n };\r\n (bytes) => {\r\n __input_inner!(String).into_bytes()\r\n };\r\n (usize1) => {\r\n __input_inner!(usize) - 1\r\n };\r\n ($t:ty) => {\r\n $crate::io::STDIN.with(|r| {\r\n use std::io::BufRead;\r\n let r = r.borrow_mut();\r\n let mut r = r.lock();\r\n let mut s = vec![];\r\n loop {\r\n let buf = r.fill_buf().unwrap();\r\n if buf.is_empty() {\r\n break;\r\n }\r\n if let Some(i) = buf.iter().position(u8::is_ascii_whitespace) {\r\n s.extend_from_slice(&buf[..i]);\r\n r.consume(i + 1);\r\n if !s.is_empty() {\r\n break;\r\n }\r\n } else {\r\n s.extend_from_slice(buf);\r\n let n = buf.len();\r\n r.consume(n);\r\n }\r\n }\r\n std::str::from_utf8(&s).unwrap().parse::<$t>().unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! println {\r\n () => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::writeln!(w.borrow_mut()).unwrap()\r\n })\r\n };\r\n ($($arg:tt)*) => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::writeln!(w.borrow_mut(), $($arg)*).unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! print {\r\n ($($arg:tt)*) => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::write!(w.borrow_mut(), $($arg)*).unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! flush {\r\n () => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n w.borrow_mut().flush().unwrap()\r\n })\r\n };\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "165963e8cbdec20db87e658483b2b0b8", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "const MOD: i64 = 998244353;\r\n\r\nfn main() {\r\n input! {\r\n n: usize,\r\n m: i64,\r\n }\r\n let p = sieve(n);\r\n let mut ans = 0;\r\n let mut dp = vec![0; n + 1];\r\n dp[0] = 1;\r\n let mut f = 1;\r\n for i in 1..=n {\r\n if p[i] {\r\n f *= i as i64;\r\n f = f.min(m + 1);\r\n }\r\n dp[i] = m / f;\r\n dp[i] %= MOD;\r\n dp[i] *= dp[i - 1];\r\n dp[i] %= MOD;\r\n ans += modpow(m, i as i64);\r\n ans %= MOD;\r\n ans += MOD - dp[i];\r\n ans %= MOD;\r\n }\r\n println!(\"{}\", ans);\r\n}\r\n\r\npub fn sieve(n: usize) -> Vec {\r\n let mut p = vec![true; n + 1];\r\n p[0] = false;\r\n p[1] = false;\r\n for i in 2..=n {\r\n if p[i] && i * i <= n {\r\n for j in (i * i..=n).step_by(i) {\r\n p[j] = false;\r\n }\r\n }\r\n }\r\n p\r\n}\r\n\r\npub fn modpow(mut base: i64, mut exp: i64) -> i64 {\r\n let mut ans = 1;\r\n base %= MOD;\r\n while exp > 0 {\r\n if exp % 2 == 1 {\r\n ans = ans * base % MOD;\r\n }\r\n base = base * base % MOD;\r\n exp >>= 1;\r\n }\r\n ans\r\n}\r\n\r\nmod io {\r\n use std::cell::RefCell;\r\n use std::io::*;\r\n\r\n std::thread_local! {\r\n pub static STDIN: RefCell = RefCell::new(stdin());\r\n pub static STDOUT: RefCell> = RefCell::new(BufWriter::new(stdout()));\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! input {\r\n () => {};\r\n (mut $var:ident: $t:tt, $($rest:tt)*) => {\r\n let mut $var = __input_inner!($t);\r\n input!($($rest)*)\r\n };\r\n ($var:ident: $t:tt, $($rest:tt)*) => {\r\n let $var = __input_inner!($t);\r\n input!($($rest)*)\r\n };\r\n (mut $var:ident: $t:tt) => {\r\n let mut $var = __input_inner!($t);\r\n };\r\n ($var:ident: $t:tt) => {\r\n let $var = __input_inner!($t);\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! __input_inner {\r\n (($($t:tt),*)) => {\r\n ($(__input_inner!($t)),*)\r\n };\r\n ([$t:tt; $n:expr]) => {\r\n (0..$n).map(|_| __input_inner!($t)).collect::>()\r\n };\r\n ([$t:tt]) => {{\r\n let n = __input_inner!(usize);\r\n (0..n).map(|_| __input_inner!($t)).collect::>()\r\n }};\r\n (chars) => {\r\n __input_inner!(String).chars().collect::>()\r\n };\r\n (bytes) => {\r\n __input_inner!(String).into_bytes()\r\n };\r\n (usize1) => {\r\n __input_inner!(usize) - 1\r\n };\r\n ($t:ty) => {\r\n $crate::io::STDIN.with(|r| {\r\n use std::io::BufRead;\r\n let r = r.borrow_mut();\r\n let mut r = r.lock();\r\n let mut s = vec![];\r\n loop {\r\n let buf = r.fill_buf().unwrap();\r\n if buf.is_empty() {\r\n break;\r\n }\r\n if let Some(i) = buf.iter().position(u8::is_ascii_whitespace) {\r\n s.extend_from_slice(&buf[..i]);\r\n r.consume(i + 1);\r\n if !s.is_empty() {\r\n break;\r\n }\r\n } else {\r\n s.extend_from_slice(buf);\r\n let n = buf.len();\r\n r.consume(n);\r\n }\r\n }\r\n std::str::from_utf8(&s).unwrap().parse::<$t>().unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! println {\r\n () => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::writeln!(w.borrow_mut()).unwrap()\r\n })\r\n };\r\n ($($arg:tt)*) => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::writeln!(w.borrow_mut(), $($arg)*).unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! print {\r\n ($($arg:tt)*) => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n std::write!(w.borrow_mut(), $($arg)*).unwrap()\r\n })\r\n };\r\n }\r\n\r\n #[macro_export]\r\n macro_rules! flush {\r\n () => {\r\n $crate::io::STDOUT.with(|w| {\r\n use std::io::Write;\r\n w.borrow_mut().flush().unwrap()\r\n })\r\n };\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "25d6aea534db37743fe24b04dee5774d", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\nuse input::*;\nuse std::{\n collections::*,\n io::{self, BufWriter, Write},\n};\nfn run(mut ss: I, mut out: O) {\n let t: u32 = 1;\n for _ in 0..t {\n case(&mut ss, &mut out);\n }\n}\ndef_mint!(998244353);\nfn case(mut ss: I, mut out: O) {\n use mod_int::*;\n let (n, m): (usize, i64) = ss.parse();\n let ps = primes::primes(n);\n let mut ans = mint(0);\n let mut c = mint(1);\n let mut x = 1i64;\n let mut j = 0;\n for i in 1..=n {\n if j < ps.len() && i == ps[j] {\n x = x.saturating_mul(ps[j] as i64);\n j += 1;\n }\n c *= Mint::from((m / x) as u64);\n ans += Mint::from(m as u64).pow(i) - c;\n }\n wln!(out, \"{}\", ans);\n}\nfn main() {\n let stdin = io::stdin();\n let ss = SplitWs::new(stdin.lock());\n let stdout = io::stdout();\n let out = BufWriter::new(stdout.lock());\n run(ss, out);\n}\npub mod mod_int {\n use std::{\n cmp,\n fmt::{self, Debug, Display},\n hash::Hash,\n iter::{Product, Sum},\n marker::PhantomData,\n mem,\n ops::*,\n };\n pub struct ModInt {\n x: u32,\n marker: PhantomData<*const M>,\n }\n pub trait Modulo {\n fn modulo() -> u32;\n }\n impl ModInt {\n pub fn new(x: u32) -> Self {\n Self {\n x,\n marker: PhantomData,\n }\n }\n pub fn get(self) -> u32 {\n self.x\n }\n }\n impl ModInt {\n pub fn modulo() -> u32 {\n M::modulo()\n }\n pub fn normalize(self) -> Self {\n Self::new(self.x % M::modulo())\n }\n pub fn inv(self) -> Self {\n assert_ne!(self.get(), 0);\n self.pow(M::modulo() - 2)\n }\n pub fn twice(self) -> Self {\n self + self\n }\n pub fn half(self) -> Self {\n if self.x & 1 == 0 {\n Self::new(self.x >> 1)\n } else {\n Self::new((self.x >> 1) + ((Self::modulo() + 1) >> 1))\n }\n }\n }\n impl Clone for ModInt {\n fn clone(&self) -> Self {\n Self::new(self.x)\n }\n }\n impl Copy for ModInt {}\n impl Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self {\n Self::new(if self.x != 0 { M::modulo() - self.x } else { 0 })\n }\n }\n impl Neg for &ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n -(*self)\n }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, rhs: Self) -> Self {\n let x = self.x + rhs.x;\n Self::new(if x < M::modulo() { x } else { x - M::modulo() })\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, rhs: Self) -> Self {\n let x = if self.x >= rhs.x {\n self.x - rhs.x\n } else {\n M::modulo() + self.x - rhs.x\n };\n Self::new(x)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, rhs: Self) -> Self {\n let x = (self.x as u64 * rhs.x as u64) % M::modulo() as u64;\n Self::new(x as u32)\n }\n }\n impl Div for ModInt {\n type Output = Self;\n #[allow(clippy::suspicious_arithmetic_impl)]\n fn div(self, rhs: Self) -> Self {\n self * rhs.inv()\n }\n }\n macro_rules! biops {\n ($ Op : ident , $ op : ident , $ OpAssign : ident , $ op_assign : ident) => {\n impl $Op<&Self> for ModInt {\n type Output = Self;\n fn $op(self, rhs: &Self) -> Self {\n self.$op(*rhs)\n }\n }\n impl $Op> for &ModInt {\n type Output = ModInt;\n fn $op(self, rhs: ModInt) -> ModInt {\n (*self).$op(rhs)\n }\n }\n impl $Op for &ModInt {\n type Output = ModInt;\n fn $op(self, rhs: Self) -> ModInt {\n (*self).$op(*rhs)\n }\n }\n impl $OpAssign for ModInt {\n fn $op_assign(&mut self, rhs: Self) {\n *self = self.$op(rhs);\n }\n }\n impl $OpAssign<&Self> for ModInt {\n fn $op_assign(&mut self, rhs: &Self) {\n *self = self.$op(rhs);\n }\n }\n };\n }\n biops!(Add, add, AddAssign, add_assign);\n biops!(Sub, sub, SubAssign, sub_assign);\n biops!(Mul, mul, MulAssign, mul_assign);\n biops!(Div, div, DivAssign, div_assign);\n impl Sum for ModInt {\n fn sum>(iter: I) -> Self {\n iter.fold(ModInt::new(0), |x, y| x + y)\n }\n }\n impl Product for ModInt {\n fn product>(iter: I) -> Self {\n iter.fold(ModInt::new(1), |x, y| x * y)\n }\n }\n macro_rules! fold {\n ($ Trait : ident , $ f : ident) => {\n impl<'a, M: Modulo + 'a> $Trait<&'a ModInt> for ModInt {\n fn $f>>(iter: I) -> Self {\n iter.copied().$f()\n }\n }\n };\n }\n fold!(Sum, sum);\n fold!(Product, product);\n pub trait Pow {\n fn pow(self, exp: Exp) -> Self;\n }\n macro_rules! pow {\n ($ uty : ident , $ ity : ident) => {\n impl Pow<$uty> for ModInt {\n fn pow(self, mut exp: $uty) -> Self {\n if exp == 0 {\n return ModInt::new(1);\n }\n let mut res = ModInt::new(1);\n let mut base = self;\n while exp > 1 {\n if exp & 1 != 0 {\n res *= base;\n }\n exp >>= 1;\n base *= base;\n }\n base * res\n }\n }\n impl Pow<$ity> for ModInt {\n fn pow(self, exp: $ity) -> Self {\n if exp >= 0 {\n self.pow(exp as $uty)\n } else {\n self.inv().pow(-exp as $uty)\n }\n }\n }\n };\n }\n macro_rules ! impls { ($ m : ident , $ ($ uty : ident , $ ity : ident) ,*) => { $ ($ m ! ($ uty , $ ity) ;) * } ; }\n impls!(pow, usize, isize, u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);\n impl Default for ModInt {\n fn default() -> Self {\n Self::new(0)\n }\n }\n impl PartialEq for ModInt {\n fn eq(&self, other: &Self) -> bool {\n self.x == other.x\n }\n }\n impl Eq for ModInt {}\n impl PartialOrd for ModInt {\n fn partial_cmp(&self, other: &Self) -> Option {\n self.x.partial_cmp(&other.x)\n }\n }\n impl Ord for ModInt {\n fn cmp(&self, other: &Self) -> cmp::Ordering {\n self.x.cmp(&other.x)\n }\n }\n impl Hash for ModInt {\n fn hash(&self, state: &mut H) {\n self.x.hash(state)\n }\n }\n macro_rules! from_uint {\n ($ ty : ident) => {\n impl From<$ty> for ModInt {\n fn from(x: $ty) -> Self {\n if mem::size_of::<$ty>() <= 4 {\n if ($ty::max_value() as u32) < M::modulo() {\n Self::new(x as u32)\n } else {\n Self::new(x as u32).normalize()\n }\n } else {\n Self::new((x % M::modulo() as $ty) as u32)\n }\n }\n }\n };\n }\n macro_rules ! impls { ($ m : ident , $ ($ ty : ident) ,*) => { $ ($ m ! ($ ty) ;) * } ; }\n impls!(from_uint, usize, u8, u16, u32, u64, u128);\n macro_rules! from_small_int {\n ($ ty : ident) => {\n impl From<$ty> for ModInt {\n fn from(x: $ty) -> Self {\n let mut x = x as i32;\n if x >= 0 {\n Self::from(x as u32)\n } else {\n while x < 0 {\n x += M::modulo() as i32;\n }\n Self::new(x as u32)\n }\n }\n }\n };\n }\n impls!(from_small_int, i8, i16, i32);\n impl Display for ModInt {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Display::fmt(&self.x, f)\n }\n }\n impl Debug for ModInt {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Debug::fmt(&self.x, f)\n }\n }\n #[macro_export]\n macro_rules! def_mint {\n ($ modulo : expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]\n pub struct MintModulo;\n impl crate::mod_int::Modulo for MintModulo {\n fn modulo() -> u32 {\n $modulo\n }\n }\n pub type Mint = crate::mod_int::ModInt;\n pub fn mint(x: u32) -> Mint {\n x.into()\n }\n };\n }\n}\npub mod primes {\n pub fn primes(n: usize) -> Vec {\n const SKIP: [u8; 8] = [6, 4, 2, 4, 2, 4, 6, 2];\n const XTOI: [u8; 15] = [0, 0, 0, 1, 0, 2, 3, 0, 4, 5, 0, 6, 0, 0, 7];\n let mut sieve = vec![0u8; n / 30 + 1];\n let mut ps = vec![2, 3, 5];\n if n <= 4 {\n ps.truncate([0, 0, 1, 2, 2][n]);\n return ps;\n }\n let mut x = 7;\n let mut i = 1;\n while x <= n {\n if sieve[i / 8] & 1 << i % 8 == 0 {\n ps.push(x);\n let mut j = i;\n let mut y = x * x;\n while y <= n {\n sieve[y / 30] |= 1 << XTOI[y / 2 % 15];\n y += x * SKIP[j % 8] as usize;\n j += 1;\n }\n }\n x += SKIP[i % 8] as usize;\n i += 1;\n }\n ps\n }\n}\npub mod input {\n use std::{\n io::{self, prelude::*},\n marker::PhantomData,\n };\n pub trait Input {\n fn bytes(&mut self) -> &[u8];\n fn bytes_vec(&mut self) -> Vec {\n self.bytes().to_vec()\n }\n fn str(&mut self) -> &str {\n std::str::from_utf8(self.bytes()).unwrap()\n }\n fn parse(&mut self) -> T {\n self.parse_with(DefaultParser)\n }\n fn parse_with(&mut self, mut parser: impl Parser) -> T {\n parser.parse(self)\n }\n fn seq(&mut self) -> Seq {\n self.seq_with(DefaultParser)\n }\n fn seq_with>(&mut self, parser: P) -> Seq {\n Seq {\n input: self,\n parser,\n marker: PhantomData,\n }\n }\n fn collect>(&mut self, n: usize) -> C {\n self.seq().take(n).collect()\n }\n }\n impl Input for &mut T {\n fn bytes(&mut self) -> &[u8] {\n (**self).bytes()\n }\n }\n pub trait Parser {\n fn parse(&mut self, s: &mut I) -> T;\n }\n impl> Parser for &mut P {\n fn parse(&mut self, s: &mut I) -> T {\n (**self).parse(s)\n }\n }\n pub trait Parse {\n fn parse(s: &mut I) -> Self;\n }\n pub struct DefaultParser;\n impl Parser for DefaultParser {\n fn parse(&mut self, s: &mut I) -> T {\n T::parse(s)\n }\n }\n pub struct Seq<'a, T, I: ?Sized, P> {\n input: &'a mut I,\n parser: P,\n marker: PhantomData<*const T>,\n }\n impl<'a, T, I: Input + ?Sized, P: Parser> Iterator for Seq<'a, T, I, P> {\n type Item = T;\n #[inline]\n fn next(&mut self) -> Option {\n Some(self.input.parse_with(&mut self.parser))\n }\n fn size_hint(&self) -> (usize, Option) {\n (!0, None)\n }\n }\n impl Parse for char {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let s = s.bytes();\n debug_assert_eq!(s.len(), 1);\n *s.first().expect(\"zero length\") as char\n }\n }\n macro_rules ! tuple { ($ ($ T : ident) ,*) => { impl <$ ($ T : Parse) ,*> Parse for ($ ($ T ,) *) { # [inline] # [allow (unused_variables)] # [allow (clippy :: unused_unit)] fn parse < I : Input + ? Sized > (s : & mut I) -> Self { ($ ($ T :: parse (s) ,) *) } } } ; }\n tuple!();\n tuple!(A);\n tuple!(A, B);\n tuple!(A, B, C);\n tuple!(A, B, C, D);\n tuple!(A, B, C, D, E);\n tuple!(A, B, C, D, E, F);\n tuple!(A, B, C, D, E, F, G);\n #[cfg(feature = \"newer\")]\n impl Parse for [T; N] {\n fn parse(s: &mut I) -> Self {\n use std::{\n mem::{self, MaybeUninit},\n ptr,\n };\n struct Guard {\n arr: [MaybeUninit; N],\n i: usize,\n }\n impl Drop for Guard {\n fn drop(&mut self) {\n unsafe {\n ptr::drop_in_place(&mut self.arr[..self.i] as *mut _ as *mut [T]);\n }\n }\n }\n let mut g = Guard:: {\n arr: unsafe { MaybeUninit::uninit().assume_init() },\n i: 0,\n };\n while g.i < N {\n g.arr[g.i] = MaybeUninit::new(s.parse());\n g.i += 1;\n }\n unsafe { mem::transmute_copy(&g.arr) }\n }\n }\n macro_rules! uint {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let s = s.bytes();\n s.iter().fold(0, |x, d| 10 * x + (0xf & d) as $ty)\n }\n }\n };\n }\n macro_rules! int {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let f = |s: &[u8]| {\n s.iter()\n .fold(0 as $ty, |x, d| (10 * x).wrapping_add((0xf & d) as $ty))\n };\n let s = s.bytes();\n if let Some((b'-', s)) = s.split_first() {\n f(s).wrapping_neg()\n } else {\n f(s)\n }\n }\n }\n };\n }\n macro_rules! float {\n ($ ty : ty) => {\n impl Parse for $ty {\n fn parse(s: &mut I) -> Self {\n const POW: [$ty; 18] = [\n 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13,\n 1e14, 1e15, 1e16, 1e17,\n ];\n let s = s.bytes();\n let (minus, s) = if let Some((b'-', s)) = s.split_first() {\n (true, s)\n } else {\n (false, s)\n };\n let (int, fract) = if let Some(p) = s.iter().position(|c| *c == b'.') {\n (&s[..p], &s[p + 1..])\n } else {\n (s, &[][..])\n };\n let x = int\n .iter()\n .chain(fract)\n .fold(0u64, |x, d| 10 * x + (0xf & *d) as u64);\n let x = x as $ty;\n let x = if minus { -x } else { x };\n let exp = fract.len();\n if exp == 0 {\n x\n } else if let Some(pow) = POW.get(exp) {\n x / pow\n } else {\n x / (10.0 as $ty).powi(exp as i32)\n }\n }\n }\n };\n }\n macro_rules! from_bytes {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n s.bytes().into()\n }\n }\n };\n }\n macro_rules! from_str {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n s.str().into()\n }\n }\n };\n }\n macro_rules ! impls { ($ m : ident , $ ($ ty : ty) ,*) => { $ ($ m ! ($ ty) ;) * } ; }\n impls!(uint, usize, u8, u16, u32, u64, u128);\n impls!(int, isize, i8, i16, i32, i64, i128);\n impls!(float, f32, f64);\n impls!(from_bytes, Vec, Box<[u8]>);\n impls!(from_str, String);\n #[derive(Clone)]\n pub struct SplitWs {\n src: T,\n buf: Vec,\n pos: usize,\n len: usize,\n }\n const BUF_SIZE: usize = 1 << 26;\n impl SplitWs {\n pub fn new(src: T) -> Self {\n Self {\n src,\n buf: vec![0; BUF_SIZE],\n pos: 0,\n len: 0,\n }\n }\n #[inline(always)]\n fn peek(&self) -> &[u8] {\n unsafe { self.buf.get_unchecked(self.pos..self.len) }\n }\n #[inline(always)]\n fn consume(&mut self, n: usize) -> &[u8] {\n let pos = self.pos;\n self.pos += n;\n unsafe { self.buf.get_unchecked(pos..self.pos) }\n }\n fn read(&mut self) -> usize {\n self.buf.copy_within(self.pos..self.len, 0);\n self.len -= self.pos;\n self.pos = 0;\n if self.len == self.buf.len() {\n self.buf.resize(2 * self.buf.len(), 0);\n }\n loop {\n match self.src.read(&mut self.buf[self.len..]) {\n Ok(n) => {\n self.len += n;\n return n;\n }\n Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}\n Err(e) => panic!(\"io error: {:?}\", e),\n }\n }\n }\n }\n impl Input for SplitWs {\n #[inline]\n fn bytes(&mut self) -> &[u8] {\n loop {\n if let Some(del) = self.peek().iter().position(|c| c.is_ascii_whitespace()) {\n if del > 0 {\n let s = self.consume(del + 1);\n return s.split_last().unwrap().1;\n } else {\n self.consume(1);\n }\n } else if self.read() == 0 {\n return self.consume(self.len - self.pos);\n }\n }\n }\n }\n}\npub mod macros {\n #[macro_export]\n macro_rules ! w { ($ ($ arg : tt) *) => { write ! ($ ($ arg) *) . unwrap () ; } }\n #[macro_export]\n macro_rules ! wln { ($ dst : expr $ (, $ ($ arg : tt) *) ?) => { { writeln ! ($ dst $ (, $ ($ arg) *) ?) . unwrap () ; # [cfg (debug_assertions)] $ dst . flush () . unwrap () ; } } }\n #[macro_export]\n macro_rules! w_iter {\n ($ dst : expr , $ fmt : expr , $ iter : expr , $ delim : expr) => {{\n let mut first = true;\n for elem in $iter {\n if first {\n w!($dst, $fmt, elem);\n first = false;\n } else {\n w!($dst, concat!($delim, $fmt), elem);\n }\n }\n }};\n ($ dst : expr , $ fmt : expr , $ iter : expr) => {\n w_iter!($dst, $fmt, $iter, \" \")\n };\n }\n #[macro_export]\n macro_rules ! w_iter_ln { ($ dst : expr , $ ($ t : tt) *) => { { w_iter ! ($ dst , $ ($ t) *) ; wln ! ($ dst) ; } } }\n #[macro_export]\n macro_rules ! e { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprint ! ($ ($ t) *) } }\n #[macro_export]\n macro_rules ! eln { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprintln ! ($ ($ t) *) } }\n #[macro_export]\n #[doc(hidden)]\n macro_rules ! __tstr { ($ h : expr $ (, $ t : expr) +) => { concat ! (__tstr ! ($ ($ t) ,+) , \", \" , __tstr ! (@)) } ; ($ h : expr) => { concat ! (__tstr ! () , \" \" , __tstr ! (@)) } ; () => { \"\\x1B[94m[{}:{}]\\x1B[0m\" } ; (@) => { \"\\x1B[1;92m{}\\x1B[0m = {:?}\" } }\n #[macro_export]\n macro_rules ! d { ($ ($ a : expr) ,*) => { if std :: env :: var (\"ND\") . map (| v | & v == \"0\") . unwrap_or (true) { eln ! (__tstr ! ($ ($ a) ,*) , file ! () , line ! () , $ (stringify ! ($ a) , $ a) ,*) ; } } ; }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "41a73c64948040441d95e4f59780102a", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "pub mod plat {\n pub mod classic {\n pub mod solution {\n use crate::{input, output};\n \n use super::io::Io;\n \n pub const IS_MULTITEST: bool = false;\n \n pub fn solve(io: &mut Io) {\n input! { io =>\n n: usize,\n m: u64\n }\n let mut is_prime = vec![true; n+1];\n for v in 2..=n {\n if !is_prime[v] {\n continue;\n }\n for d in (v..=n).step_by(v).skip(1) {\n is_prime[d] = false;\n }\n }\n let md = 998244353u64;\n let mut tot = m % md;\n let mut pos = m % md;\n let mut ans = 0;\n let mut mul = 1u64;\n for k in 2..=n {\n tot = (tot * (m % md)) % md;\n if is_prime[k] && mul <= m {\n mul *= k as u64;\n }\n pos = (m / mul % md * pos) % md;\n ans = (ans + md + tot - pos) % md;\n }\n output! { io => ans; }\n }\n }\n \n pub mod io {\n use std::{fmt::Debug, io::BufRead, str::FromStr};\n \n use crate::utils::io::{InputSource, OutputTarget};\n \n #[macro_export]\n macro_rules! read_value {\n ($io:ident, [$type:tt; $len:expr]) => {\n (0..$len).map(|_| $crate::read_value!($io, $type)).collect::>()\n };\n ($io:ident, ($($type:tt),+)) => {\n ($( $crate::read_value!($io, $type), )*)\n };\n ($io:ident, usize1) => {\n $crate::read_value!($io, usize) - 1\n };\n ($io:ident, $type:ty) => {\n $io.reader.read::<$type>()\n }\n }\n \n /// # Examples\n /// ```\n /// input! { io =>\n /// (n, m): usize,\n /// a: [[i32; m]; n]\n /// }\n /// input! { io =>\n /// (n, m): usize,\n /// edges: [(usize1, usize1); m]\n /// }\n /// ```\n #[macro_export]\n macro_rules! input {\n ($io:ident => ) => {};\n ($io:ident => $var:ident: $type:tt) => {\n let $var = $crate::read_value!($io, $type);\n };\n ($io:ident => ($($var:ident),+): $type:tt) => {\n $( $crate::input!{ $io => $var: $type } )*\n };\n ($io:ident => $($vars:tt: $type:tt),+) => {\n $( $crate::input!{ $io => $vars: $type } )*\n }\n }\n \n /// # Examples\n /// ```\n /// let (n, m) = (1, 2);\n /// let a = vec![1, 2, 3];\n /// let ans = false;\n /// output! { io =>\n /// n, m;\n /// sl(a);\n /// yn(ans);\n /// }\n /// ```\n #[macro_export]\n macro_rules! output {\n ($io:ident => ) => {};\n ($io:ident => ;) => {\n $io.printer.print(&'\\n');\n };\n ($io:ident => ,) => {\n $io.printer.print(&' ');\n };\n ($io:ident => $val:expr) => {\n $io.printer.print(&$val);\n };\n ($io:ident => sl $val:tt $($tail:tt)*) => {\n $io.printer.print_vec(&$val, ' ');\n $crate::output!{ $io => $($tail)* }\n };\n ($io:ident => nl $val:tt $($tail:tt)*) => {\n $io.printer.print_vec(&$val, '\\n');\n $crate::output!{ $io => $($tail)* }\n };\n ($io:ident => yn $val:tt $($tail:tt)*) => {\n #[allow(unused_parens)]\n $io.printer.print(&(if $val { \"Yes\" } else { \"No\" }));\n $crate::output!{ $io => $($tail)* }\n };\n ($io:ident => $head:tt $($tail:tt)*) => {\n $crate::output!{ $io => $head }\n $crate::output!{ $io => $($tail)* }\n }\n }\n \n #[derive(Default)]\n pub struct Io {\n pub reader: InputReader,\n pub printer: OutputPrinter,\n }\n \n pub struct InputReader {\n source: InputSource,\n splitter: WhitespaceSplitter,\n }\n \n pub struct OutputPrinter {\n target: OutputTarget,\n }\n \n pub trait Parsable {\n fn parse(s: &str) -> Self;\n }\n \n impl Parsable for T\n where\n T: FromStr,\n ::Err: Debug,\n {\n fn parse(s: &str) -> Self {\n T::from_str(s).unwrap()\n }\n }\n \n impl Default for InputReader {\n fn default() -> Self {\n Self {\n source: InputSource::from_env(),\n splitter: WhitespaceSplitter::default(),\n }\n }\n }\n \n impl InputReader {\n pub fn read(&mut self) -> T {\n self.splitter.parse_next(self.source.reader())\n }\n }\n \n impl Default for OutputPrinter {\n fn default() -> Self {\n Self {\n target: OutputTarget::from_env(),\n }\n }\n }\n \n impl OutputPrinter {\n pub fn print(&mut self, v: &T) {\n self.target\n .writer()\n .write(v.to_string().as_bytes())\n .unwrap();\n }\n \n pub fn print_vec(&mut self, a: &Vec, sep: char) {\n let mut is_first = true;\n for item in a {\n if !is_first {\n self.print(&sep)\n }\n is_first = false;\n self.print(item)\n }\n }\n }\n \n #[derive(Default)]\n pub struct WhitespaceSplitter {\n buf: Vec,\n }\n \n impl WhitespaceSplitter {\n pub fn parse_next(&mut self, buf_read: &mut dyn BufRead) -> T {\n self.buf.clear();\n while let Some(byte) = consume_next_byte(buf_read) {\n match byte {\n b'\\r' => {}\n b' ' | b'\\n' => {\n if !self.buf.is_empty() {\n break;\n }\n }\n symbol => {\n self.buf.push(symbol);\n }\n }\n }\n if self.buf.is_empty() {\n panic!(\"Read nothing\")\n }\n let s = std::str::from_utf8(&self.buf).unwrap();\n T::parse(s)\n }\n }\n \n fn consume_next_byte(buf_read: &mut dyn BufRead) -> Option {\n if let Some(&byte) = buf_read.fill_buf().unwrap().get(0) {\n buf_read.consume(1);\n Some(byte)\n } else {\n None\n }\n }\n }\n \n \n pub fn run() {\n let mut io = io::Io::default();\n let test_cnt = if solution::IS_MULTITEST {\n io.reader.read::()\n } else { 1 };\n for _ in 0..test_cnt {\n solution::solve(&mut io);\n }\n }\n }\n \n pub mod leetcode {\n use self::io::{InputReader, OutputPrinter};\n \n pub mod solution {\n impl Solution {\n pub fn hardest_worker(_n: i32, _logs: Vec>) -> i32 {\n 0\n }\n }\n \n use crate::{plat::leetcode::io::{InputReader, ToLeetcodeValueNode}, with_input};\n pub const TEST_COUNT: usize = 1;\n \n pub fn exec(r: &mut InputReader) -> impl ToLeetcodeValueNode {\n with_input!{ r => hardest_worker, 2 }\n }\n \n struct Solution;\n }\n \n pub mod defs {\n use std::{cell::RefCell, rc::Rc};\n \n #[derive(Debug, PartialEq, Eq)]\n pub struct TreeNode {\n pub val: i32,\n pub left: Option>>,\n pub right: Option>>,\n }\n \n impl TreeNode {\n #[inline]\n pub fn new(val: i32) -> Self {\n TreeNode {\n val,\n left: None,\n right: None,\n }\n }\n }\n }\n \n pub mod io {\n use std::{cell::RefCell, collections::VecDeque, rc::Rc};\n \n use crate::utils::io::{InputSource, OutputTarget};\n \n use self::parser::LeetcodeValueNode;\n \n use super::defs::TreeNode;\n \n mod parser {\n #[derive(Debug)]\n pub enum LeetcodeValueNode {\n Null,\n Int(i64),\n Str(String),\n Bool(bool),\n Array(Vec),\n }\n \n impl LeetcodeValueNode {\n pub fn parse_node(s: &str) -> Self {\n let mut rest = s;\n let node = parse_next(&mut rest);\n rest = rest.trim();\n if !rest.is_empty() {\n panic!(\"Unexpected {rest}\");\n }\n node\n }\n }\n \n impl ToString for LeetcodeValueNode {\n fn to_string(&self) -> String {\n match self {\n LeetcodeValueNode::Null => \"null\".to_string(),\n LeetcodeValueNode::Int(v) => v.to_string(),\n LeetcodeValueNode::Str(s) => s.to_string(),\n LeetcodeValueNode::Bool(v) => v.to_string(),\n LeetcodeValueNode::Array(a) => format!(\n \"[{}]\",\n a.iter()\n .map(|el| el.to_string())\n .collect::>()\n .join(\",\")\n ),\n }\n }\n }\n \n fn parse_next(s: &mut &str) -> LeetcodeValueNode {\n trim_start(s);\n match s.chars().next().unwrap() {\n 'n' => parse_next_null(s),\n '0'..='9' => parse_next_int(s),\n 't' | 'f' => parse_next_bool(s),\n '\"' => parse_next_str(s),\n '[' => parse_next_array(s),\n other => panic!(\"Unexpected char {other}\"),\n }\n }\n \n fn parse_next_null(s: &mut &str) -> LeetcodeValueNode {\n if !consume_start(s, \"null\") {\n panic!(\"Can't parse null from {s}\");\n };\n LeetcodeValueNode::Null\n }\n \n fn parse_next_int(s: &mut &str) -> LeetcodeValueNode {\n let mut v = 0;\n while let Some(ch) = s.chars().next() {\n if let Some(d) = ch.to_digit(10) {\n v = 10 * v + d as i64;\n consume_next_char(s);\n } else {\n break;\n }\n }\n LeetcodeValueNode::Int(v)\n }\n \n fn parse_next_str(s: &mut &str) -> LeetcodeValueNode {\n let mut v = String::new();\n consume_next_char(s);\n loop {\n if let Some(ch) = consume_next_char(s) {\n if ch == '\"' {\n break;\n } else {\n v.push(ch);\n }\n } else {\n panic!(\"Failed to find matching \\\"\");\n }\n }\n LeetcodeValueNode::Str(v)\n }\n \n fn parse_next_bool(s: &mut &str) -> LeetcodeValueNode {\n let v = if consume_start(s, \"true\") {\n true\n } else if consume_start(s, \"false\") {\n false\n } else {\n panic!(\"Can't parse bool from {s}\");\n };\n LeetcodeValueNode::Bool(v)\n }\n \n fn parse_next_array(s: &mut &str) -> LeetcodeValueNode {\n let mut res = Vec::new();\n consume_next_char(s);\n trim_start(s);\n loop {\n if let Some(ch) = s.chars().next() {\n match ch {\n ']' => {\n consume_next_char(s);\n break;\n }\n ',' => {\n consume_next_char(s);\n }\n _ => {\n res.push(parse_next(s));\n }\n }\n trim_start(s);\n } else {\n panic!(\"Unmatched [\");\n }\n }\n LeetcodeValueNode::Array(res)\n }\n \n fn consume_start(s: &mut &str, v: &str) -> bool {\n if s.starts_with(v) {\n *s = &s[v.len()..];\n true\n } else { false }\n }\n \n fn trim_start(s: &mut &str) {\n *s = s.trim_start();\n }\n \n fn consume_next_char(s: &mut &str) -> Option {\n let res = s.chars().next();\n *s = &s[1..];\n res\n }\n }\n \n \n pub struct InputReader {\n source: InputSource,\n }\n \n #[macro_export]\n macro_rules! with_input {\n ($r:ident => $func:ident, 1) => {\n crate::plat::leetcode::solution::Solution::$func($r.read())\n };\n ($r:ident => $func:ident, 2) => {\n crate::plat::leetcode::solution::Solution::$func($r.read(), $r.read())\n };\n ($r:ident => $func:ident, 3) => {\n crate::plat::leetcode::solution::Solution::$func($r.read(), $r.read(), $r.read())\n };\n }\n \n pub struct OutputPrinter {\n target: OutputTarget,\n }\n \n impl InputReader {\n pub fn read(&mut self) -> T {\n let mut line = String::new();\n self.source.reader().read_line(&mut line).unwrap();\n let node = LeetcodeValueNode::parse_node(&line);\n T::from_leetcode_input_node(&node)\n }\n }\n \n impl Default for InputReader {\n fn default() -> Self {\n Self {\n source: InputSource::from_env(),\n }\n }\n }\n \n impl OutputPrinter {\n pub fn print(&mut self, v: &impl ToLeetcodeValueNode) {\n let s = v.to_leetcode_value_node();\n self.target\n .writer()\n .write(s.to_string().as_bytes())\n .unwrap();\n }\n }\n \n impl Default for OutputPrinter {\n fn default() -> Self {\n Self {\n target: OutputTarget::from_env(),\n }\n }\n }\n \n pub trait FromLeetcodeValueNode {\n fn from_leetcode_input_node(node: &LeetcodeValueNode) -> Self;\n }\n \n pub trait ToLeetcodeValueNode {\n fn to_leetcode_value_node(&self) -> LeetcodeValueNode;\n }\n \n macro_rules! impl_from_leetcode_int {\n ($($type:ty),+) => {\n $(\n impl FromLeetcodeValueNode for $type {\n fn from_leetcode_input_node(node: &LeetcodeValueNode) -> Self {\n if let LeetcodeValueNode::Int(v) = node {\n (*v) as $type\n } else {\n panic!(\"{:?} is not int\", node)\n }\n }\n }\n )*\n };\n }\n \n impl_from_leetcode_int!(i32, i64);\n \n impl FromLeetcodeValueNode for Option {\n fn from_leetcode_input_node(node: &LeetcodeValueNode) -> Self {\n match node {\n LeetcodeValueNode::Null => None,\n other => Some(T::from_leetcode_input_node(other)),\n }\n }\n }\n \n impl FromLeetcodeValueNode for Option>> {\n fn from_leetcode_input_node(node: &LeetcodeValueNode) -> Self {\n match node {\n LeetcodeValueNode::Array(a) => convert_to_tree_node(a),\n other => panic!(\"{:?} cannot be parsed to TreeNode, expected array\", other),\n }\n }\n }\n \n fn create_tree_node(node: Option<&LeetcodeValueNode>) -> Option>> {\n match node {\n None | Some(LeetcodeValueNode::Null) => None,\n Some(LeetcodeValueNode::Int(v)) => Some(Rc::new(RefCell::new(TreeNode::new(*v as i32)))),\n other => panic!(\"expected int or null, got {:?}\", other),\n }\n }\n \n fn convert_to_tree_node(a: &[LeetcodeValueNode]) -> Option>> {\n let mut q = VecDeque::>>::new();\n let root = create_tree_node(a.get(0));\n if let Some(ref rc) = root {\n q.push_back(rc.clone());\n } else {\n return None;\n }\n let mut i = 1;\n while let Some(rc) = q.pop_front() {\n let mut node = rc.borrow_mut();\n node.left = create_tree_node(a.get(i));\n node.right = create_tree_node(a.get(i + 1));\n i += 2;\n for child in [&node.left, &node.right] {\n if let Some(rc) = child {\n q.push_back(rc.clone());\n }\n }\n }\n if i < a.len() {\n panic!(\"{:?} contains redundant elements, consumed {}\", a, i + 1);\n }\n root\n }\n \n impl FromLeetcodeValueNode for String {\n fn from_leetcode_input_node(node: &LeetcodeValueNode) -> Self {\n if let LeetcodeValueNode::Str(s) = node {\n String::from(s)\n } else {\n panic!(\"{:?} is not str\", node)\n }\n }\n }\n \n impl FromLeetcodeValueNode for bool {\n fn from_leetcode_input_node(node: &LeetcodeValueNode) -> Self {\n if let LeetcodeValueNode::Bool(v) = node {\n *v\n } else {\n panic!(\"{:?} is not bool\", node)\n }\n }\n }\n \n impl FromLeetcodeValueNode for Vec {\n fn from_leetcode_input_node(node: &LeetcodeValueNode) -> Self {\n if let LeetcodeValueNode::Array(a) = node {\n a.iter().map(|el| T::from_leetcode_input_node(el)).collect()\n } else {\n panic!(\"{:?} is not array\", node)\n }\n }\n }\n \n macro_rules! impl_to_leetcode_int {\n ($($type:ty),+) => {\n $(\n impl ToLeetcodeValueNode for $type {\n fn to_leetcode_value_node(&self) -> LeetcodeValueNode {\n LeetcodeValueNode::Int(*self as i64)\n }\n }\n )*\n };\n }\n \n impl_to_leetcode_int!(i32, i64);\n \n impl ToLeetcodeValueNode for Option {\n fn to_leetcode_value_node(&self) -> LeetcodeValueNode {\n match self {\n Some(v) => v.to_leetcode_value_node(),\n None => LeetcodeValueNode::Null,\n }\n }\n }\n \n impl ToLeetcodeValueNode for String {\n fn to_leetcode_value_node(&self) -> LeetcodeValueNode {\n LeetcodeValueNode::Str(String::from(self))\n }\n }\n \n impl ToLeetcodeValueNode for bool {\n fn to_leetcode_value_node(&self) -> LeetcodeValueNode {\n LeetcodeValueNode::Bool(*self)\n }\n }\n \n impl ToLeetcodeValueNode for Vec {\n fn to_leetcode_value_node(&self) -> LeetcodeValueNode {\n LeetcodeValueNode::Array(self.iter().map(|el| el.to_leetcode_value_node()).collect())\n }\n }\n }\n \n \n pub fn run() {\n let mut reader = InputReader::default();\n let mut printer = OutputPrinter::default();\n for _ in 0..solution::TEST_COUNT {\n let res = solution::exec(&mut reader);\n printer.print(&res);\n printer.print(&String::from(\"\\n\"));\n }\n }\n }\n \n}\n\npub mod utils {\n pub mod io {\n use std::{\n env,\n fs::File,\n io::{stdin, stdout, BufRead, BufReader, BufWriter, Stdin, Stdout, Write},\n };\n \n pub enum InputSource {\n Stdin { reader: BufReader },\n File { reader: BufReader },\n }\n \n pub enum OutputTarget {\n Stdout { writer: BufWriter },\n File { writer: BufWriter },\n }\n \n impl InputSource {\n pub fn from_env() -> Self {\n if is_local() {\n Self::from_file()\n } else {\n Self::from_stdin()\n }\n }\n \n pub fn from_stdin() -> Self {\n InputSource::Stdin {\n reader: BufReader::new(stdin()),\n }\n }\n \n pub fn from_file() -> Self {\n let file = File::open(\"input.txt\").unwrap();\n InputSource::File {\n reader: BufReader::new(file),\n }\n }\n \n pub fn reader(&mut self) -> &mut dyn BufRead {\n match self {\n InputSource::Stdin { reader } => reader,\n InputSource::File { reader } => reader,\n }\n }\n }\n \n impl OutputTarget {\n pub fn from_env() -> Self {\n if is_local() {\n Self::from_file()\n } else {\n Self::from_stdout()\n }\n }\n \n pub fn from_stdout() -> Self {\n OutputTarget::Stdout {\n writer: BufWriter::new(stdout()),\n }\n }\n \n pub fn from_file() -> Self {\n OutputTarget::File {\n writer: BufWriter::new(File::create(\"out/output.txt\").unwrap()),\n }\n }\n \n pub fn writer(&mut self) -> &mut dyn Write {\n match self {\n OutputTarget::Stdout { writer } => writer,\n OutputTarget::File { writer } => writer,\n }\n }\n }\n \n fn is_local() -> bool {\n env::var(\"LOCAL\").is_ok()\n }\n }\n \n}\n\n\nfn main() {\n plat::classic::run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "c443340ecf48c1308b1573bf64e3afe6", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "macro_rules! read_line {\r\n ( $($name:ident : $typ:ty),+ ) => {\r\n let line = get_line();\r\n let mut tokens = line.split_ascii_whitespace();\r\n $(\r\n let $name: $typ = tokens.next().unwrap().parse().unwrap();\r\n )+\r\n debug_assert_eq!(tokens.next(), None);\r\n };\r\n}\r\n\r\nconst P: i64 = 998244353;\r\n\r\nfn primes(n: usize) -> Vec {\r\n let mut ps = vec![true; n + 1];\r\n for i in 2..n {\r\n if ps[i] {\r\n for j in (i * i..=n).step_by(i) {\r\n ps[j] = false;\r\n }\r\n }\r\n }\r\n ps\r\n}\r\n\r\nfn primes2(ps: Vec) -> Vec {\r\n ps.iter()\r\n .enumerate()\r\n .filter_map(|(i, &is_prime)| if is_prime && i >= 2 { Some(i) } else { None })\r\n .collect()\r\n}\r\n\r\nfn solve(n: usize, m: i64) -> i64 {\r\n let mut x = m % P;\r\n let mut y = m % P;\r\n let mut ans = 0;\r\n let mut p = 1 as i64;\r\n let ps = primes(n);\r\n for i in 2..=n {\r\n if ps[i] && p <= m {\r\n p = p * (i as i64);\r\n }\r\n x = (x * ((m / p) % P)) % P;\r\n y = (y * (m % P)) % P;\r\n ans = (ans + (y - x + P) % P) % P;\r\n }\r\n ans\r\n}\r\n\r\nfn main() {\r\n read_line!(n: usize, m: i64);\r\n println!(\"{}\", solve(n, m));\r\n}\r\n\r\n#[cfg(test)]\r\nmod tests {\r\n use super::*;\r\n\r\n #[test]\r\n fn test() {\r\n assert_eq!(solve(2, 3), 6);\r\n assert_eq!(solve(4, 2), 26);\r\n assert_eq!(solve(4, 6), 1494);\r\n assert_eq!(solve(1337, 424242424242i64), 119112628);\r\n }\r\n #[test]\r\n fn test_primes() {\r\n assert_eq!(primes2(primes(23)), vec![2, 3, 5, 7, 11, 13, 17, 19, 23]);\r\n }\r\n #[test]\r\n fn div() {\r\n assert_eq!(9 / 4, 2);\r\n }\r\n}\r\n\r\nfn get_line() -> String {\r\n let mut line = String::new();\r\n while line.is_empty() {\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n }\r\n line.pop().unwrap();\r\n line\r\n}\r\n\r\nfn read_line_vec() -> Vec\r\nwhere\r\n T: std::str::FromStr,\r\n T::Err: std::fmt::Debug,\r\n{\r\n get_line()\r\n .split_ascii_whitespace()\r\n .map(|s| s.parse::())\r\n .collect::, _>>()\r\n .unwrap()\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "45fbf3adb13441b9e47f62386a8024e3", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n use std::io;\n use std::io::prelude::*;\n\n let stdin = io::stdin();\n let mut lc = 1;\n let mut str_len = 0;\n for line in stdin.lock().lines() {\n \tmatch lc {\n \t\t1 => {\n \t\t\tstr_len = line.unwrap().parse::().unwrap();\n \t\t},\n \t\t2 => {\n \t\t\tlet s = line.unwrap();\n \t\t\t// println!(\"{:?}\", s);\n \t\t\tlet mut num = 0;\n \t\t\tlet mut chars = s.chars();\n \t\t\tlet mut prev_ch = '1';\n \t\t\tfor ch in chars {\n \t\t\t\tmatch ch {\n\t \t\t\t\t'1' => {\n\t \t\t\t\t\tnum += 1;\n\t \t\t\t\t},\n\t \t\t\t\t'0' if prev_ch == '0' => {\n\t \t\t\t\t\tprint!(\"0\");\n\t \t\t\t\t}\n\t \t\t\t\t'0' => {\n\t \t\t\t\t\tprint!(\"{}\", num);\n\t \t\t\t\t\tnum = 0;\n\t \t\t\t\t}\n\t \t\t\t\t_ => panic!(\"SOS\"),\n \t\t\t\t}\n \t\t\t\tprev_ch = ch;\n \t\t\t}\n \t\t\tif num > 0 {\n\t \t\t\tprintln!(\"{}\", num);\n \t\t\t}\n \t\t\tif prev_ch == '0' {\n \t\t\t\tprint!(\"0\");\n \t\t\t}\n \t\t}\n \t\t_ => {\n \t\t\tpanic!(\"SOS\");\n \t\t}\n \t}\n \tlc += 1;\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "08ec9f041a5689c18fcfce8829a52529", "src_uid": "a4b3da4cb9b6a7ed0a33a862e940cafa", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n io::stdin().read_line(&mut String::new()).expect(\"\");\n let mut s = String::new();\n io::stdin().read_line(&mut s).expect(\"\");\n let mut ans = String::new();\n let mut cnt = 0;\n let mut zcnt = 0;\n for c in s.trim().chars() {\n if c == '0' {\n if cnt > 0 {\n ans += &cnt.to_string();\n cnt = 0;\n } else if zcnt > 0 {\n ans.push_str(\"0\");\n }\n zcnt = 1;\n } else {\n zcnt = 0;\n cnt += 1;\n }\n }\n if cnt > 0 {\n ans += &cnt.to_string();\n } else {\n ans.push_str(\"0\");\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "aa6291df4c52de81fd8d1cf7120e9672", "src_uid": "a4b3da4cb9b6a7ed0a33a862e940cafa", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n use std::io;\n use std::io::prelude::*;\n\n let stdin = io::stdin();\n let mut lc = 1;\n let mut str_len = 0;\n for line in stdin.lock().lines() {\n \tmatch lc {\n \t\t1 => {\n \t\t\tstr_len = line.unwrap().parse::().unwrap();\n \t\t},\n \t\t2 => {\n \t\t\tlet s = line.unwrap();\n \t\t\t// println!(\"{:?}\", s);\n \t\t\tlet mut num = 0;\n \t\t\tlet mut chars = s.chars();\n \t\t\tlet mut prev_ch = '1';\n \t\t\tfor ch in chars {\n \t\t\t\tmatch ch {\n\t \t\t\t\t'1' => num += 1,\n\t \t\t\t\t'0' => { print!(\"{}\", num); num = 0; }, \n\t \t\t\t\t_ => panic!(\"SOS\"),\n \t\t\t\t}\n \t\t\t\tprev_ch = ch;\n \t\t\t}\n \t\t\tif num > 0 {\n\t \t\t\tprintln!(\"{}\", num);\n \t\t\t}\n \t\t\tif prev_ch == '0' {\n \t\t\t\tprint!(\"0\");\n \t\t\t}\n \t\t}\n \t\t_ => {\n \t\t\tpanic!(\"SOS\");\n \t\t}\n \t}\n \tlc += 1;\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c94ee50463444f1c209faf005a17d11f", "src_uid": "a4b3da4cb9b6a7ed0a33a862e940cafa", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/problemset/problem/825/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(isize);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(_n: u32);\n scanln!(n: String);\n for segment in n.split('0') {\n print!(\"{}\", segment.len());\n }\n println!(\"\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9a9cca2350efea86710dc014c14c802d", "src_uid": "a4b3da4cb9b6a7ed0a33a862e940cafa", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! debug(\n ($($arg:tt)*) => { {\n let r = writeln!(&mut ::std::io::stderr(), $($arg)*);\n r.expect(\"failed printing to stderr\");\n } }\n);\n\nstruct Scanner {\n buffer : std::collections::VecDeque\n}\n\nimpl Scanner {\n\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn process(&mut self) -> String {\n if self.buffer.len() == 0 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n for word in input.split_whitespace() {\n self.buffer.push_back(word.to_string())\n }\n }\n\n self.buffer.pop_front().unwrap()\n }\n\n #[allow(dead_code)]\n fn next(&mut self) -> T {\n self.process().parse::().ok().unwrap()\n }\n\n #[allow(dead_code)]\n fn next_char(&mut self) -> char {\n self.process().into_bytes()[0] as char\n }\n}\n\nfn count_char(x : char, y : char, z : char, target : char) -> i32 {\n (if x == target {1} else {0})\n + if y == target {1} else {0}\n + if z == target {1} else {0}\n}\n\nfn check_board(board: &[[char; 4];4]) -> String {\n // horizontal...\n for i in 0..4 {\n for j in 1..3 {\n let x_count = count_char(board[i][j], board[i][j+1], board[i][j-1], 'x');\n let e_count = count_char(board[i][j], board[i][j+1], board[i][j-1], '.');\n\n if x_count == 3 || (x_count == 2 && e_count == 1) {\n return \"YES\".to_string();\n }\n }\n }\n\n // vertical...\n for j in 0..4 {\n for i in 1..3 {\n let x_count = count_char(board[i][j], board[i+1][j], board[i-1][j], 'x');\n let e_count = count_char(board[i][j], board[i+1][j], board[i-1][j], '.');\n\n if x_count == 3 || (x_count == 2 && e_count == 1) {\n return \"YES\".to_string();\n }\n }\n }\n\n // left-diagonal...\n for j in 0..2 {\n for i in 0..2 {\n let x_count = count_char(board[i][j], board[i+1][j+1], board[i+2][j+2], 'x');\n let e_count = count_char(board[i][j], board[i+1][j+1], board[i+2][j+2], '.');\n\n if x_count == 3 || (x_count == 2 && e_count == 1) {\n return \"YES\".to_string();\n }\n }\n }\n\n // right-diagonal..\n for j in 0..2 {\n for i in 2..4 {\n let x_count = count_char(board[i][j], board[i-1][j+1], board[i-2][j+2], 'x');\n let e_count = count_char(board[i][j], board[i-1][j+1], board[i-2][j+2], '.');\n\n if x_count == 3 || (x_count == 2 && e_count == 1) {\n return \"YES\".to_string();\n }\n }\n }\n\n return \"NO\".to_string();\n}\n\nfn main() {\n let mut sin = Scanner::new();\n\n let mut board = [['.';4];4];\n\n for i in 0..4 {\n let line = sin.next::().into_bytes();\n for j in 0..4 {\n board[i][j] = line[j] as char;\n }\n }\n\n println!(\"{}\", check_board(&board));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "ead33e6e352559cf9cf41c5807bad96d", "src_uid": "ca4a77fe9718b8bd0b3cc3d956e22917", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io::stdin;\n\n\nstruct Digits {\n number: u64,\n divisor: u64,\n}\n\nimpl Digits {\n fn new(number: u64) -> Self {\n let mut divisor = 1;\n while number >= divisor * 10 {\n divisor *= 10;\n }\n\n Digits {\n number,\n divisor,\n }\n }\n\n fn reset(&mut self, number: u64){\n let mut divisor = 1;\n while number >= divisor * 10 {\n divisor *= 10;\n }\n self.divisor = divisor;\n self.number = number;\n\n }\n}\n\nimpl Iterator for Digits {\n type Item = u64;\n\n fn next(&mut self) -> Option {\n if self.divisor == 0 {\n None\n } else {\n let v = Some(self.number / self.divisor);\n self.number %= self.divisor;\n self.divisor /= 10;\n v\n }\n\n }\n}\n\nstruct InfinityCounter{\n num: Digits,\n current: u64,\n}\nimpl InfinityCounter{\n pub fn new() -> Self{\n Self{\n current: 0,\n num: Digits::new(1),\n }\n }\n}\n\n\nimpl Iterator for InfinityCounter{\n type Item = u64;\n\n fn next(&mut self) -> Option {\n let next = self.num.next();\n if next.is_none() {\n self.current += 1;\n self.num.reset(self.current);\n return self.num.next();\n }\n next\n }\n}\n\nfn main() -> Result<(), Box> {\n let mut input = String::new();\n stdin().read_line(&mut input)?;\n let number: usize = input.trim().parse()?;\n let mut counter = InfinityCounter::new();\n if let Some(x) = counter.nth(number){\n println!(\"{}\", x);\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f03f34a5b00454b450b3056d4f2c9ad9", "src_uid": "1503d761dd4e129fb7c423da390544ff", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\nuse std::collections::VecDeque;\n\nstruct DigitSequenceIterator {\n inner: u64,\n state: VecDeque,\n}\n\nimpl Iterator for DigitSequenceIterator {\n type Item = char;\n\n fn next(&mut self) -> Option {\n if self.state.len() == 0 {\n self.state.extend(self.inner.to_string().chars());;\n\n self.inner += 1;\n }\n\n self.state.pop_front()\n }\n}\n\nimpl DigitSequenceIterator {\n pub fn new() -> Self {\n DigitSequenceIterator {\n inner: 0,\n state: VecDeque::new(),\n }\n }\n\n pub fn skip(mut to_skip: u64) -> impl Iterator {\n let mut inner = 0;\n\n if to_skip >= 10 {\n inner = 10;\n to_skip -= 10;\n }\n\n let mut can_jump = 90;\n let mut i = 2;\n while to_skip > can_jump * i {\n to_skip -= can_jump * i;\n inner *= 10;\n\n can_jump *= 10;\n i += 1;\n }\n\n // Now, all numbers between inner and the end are `i` wide.\n // So, to_skip/i is the amount of numbers we can still skip.\n if i > 2 {\n inner += to_skip/i;\n to_skip = to_skip % i;\n }\n\n DigitSequenceIterator {\n inner,\n state: VecDeque::new(),\n }.skip(to_skip as usize)\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let line = stdin.lock().lines().next().expect(\"input\").expect(\"UTF-8\");\n let index: u64 = line.parse().expect(\"Numeric value\");\n\n println!(\"{}\", DigitSequenceIterator::skip(index).next().unwrap());\n}\n\n#[test]\nfn vectors() {\n let in_out = [(7, '7'), (21, '5'), (188, '9'), (192, '0'), (417, '5')];\n\n for (i, o) in &in_out {\n let test = DigitSequenceIterator::skip(*i).next().unwrap();\n assert_eq!(test, *o,\n \"{}th should be {}, but got {}\", i, *o, test);\n }\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "implementation", "binary search"], "code_uid": "edc3a7cb243b228a86ec208f0574efea", "src_uid": "1503d761dd4e129fb7c423da390544ff", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Res = u64;\nconst MAX_INP: Res = 1_000_000_000_000;\nconst STEP_SIZE: Res = 1000000000;\n\nfn main() {\n/*\n print!(\"let lookup = [\");\n let mut i = STEP_SIZE;\n let mut result = ('_', 1, 1);\n print!(\"(1,1),\");\n while i <= MAX_INP {\n result = solve_internal(i, result.1, result.2);\n print!(\"({},{}),\", result.1, result.2);\n i += STEP_SIZE;\n }\n println!(\"];\");\n*/\n\n\n let k = {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n input.trim().parse::().unwrap()\n };\n assert!((1 <= k) && (k <= MAX_INP), \"K out of input range. 1<= k <= 10^12\");\n let result = solve(k);\n println!(\"{}\", result);\n}\n\nfn int_len_(inp: Res) -> Res {\n if inp == 0 {\n return 1;\n }\n\n let mut res = 0;\n let mut temp = 1;\n while temp <= inp {\n res += 1;\n temp *= 10\n }\n res\n}\n\nfn int_len(inp: Res) -> Res {\n //debug_assert!(0 <= inp);\n //debug_assert!(inp <= MAX_INP);\n match inp {\n 1000000000000..=9999999999999 => 13,\n 100000000000..=999999999999 => 12,\n 10000000000..=99999999999 => 11,\n 1000000000..=9999999999 => 10,\n 100000000..=999999999 => 9,\n 10000000..=99999999 => 8,\n 1000000..=9999999 => 7,\n 100000..=999999 => 6,\n 10000..=99999 => 5,\n 1000..=9999 => 4,\n 100..=999 => 3,\n 10..=99 => 2,\n 0..=9 => 1,\n _ => unreachable!()\n }\n}\n\nfn solve(k: Res) -> char {\n let lookup = [(1,1),(1000000008,123456790),(2000000007,234567901),(3000000006,345679012),(4000000005,456790123),(5000000004,567901234),(6000000003,679012345),(7000000002,790123456),(8000000001,901234567),(9000000009,1011111111),(10000000009,1111111111),(11000000009,1211111111),(12000000009,1311111111),(13000000009,1411111111),(14000000009,1511111111),(15000000009,1611111111),(16000000009,1711111111),(17000000009,1811111111),(18000000009,1911111111),(19000000009,2011111111),(20000000009,2111111111),(21000000009,2211111111),(22000000009,2311111111),(23000000009,2411111111),(24000000009,2511111111),(25000000009,2611111111),(26000000009,2711111111),(27000000009,2811111111),(28000000009,2911111111),(29000000009,3011111111),(30000000009,3111111111),(31000000009,3211111111),(32000000009,3311111111),(33000000009,3411111111),(34000000009,3511111111),(35000000009,3611111111),(36000000009,3711111111),(37000000009,3811111111),(38000000009,3911111111),(39000000009,4011111111),(40000000009,4111111111),(41000000009,4211111111),(42000000009,4311111111),(43000000009,4411111111),(44000000009,4511111111),(45000000009,4611111111),(46000000009,4711111111),(47000000009,4811111111),(48000000009,4911111111),(49000000009,5011111111),(50000000009,5111111111),(51000000009,5211111111),(52000000009,5311111111),(53000000009,5411111111),(54000000009,5511111111),(55000000009,5611111111),(56000000009,5711111111),(57000000009,5811111111),(58000000009,5911111111),(59000000009,6011111111),(60000000009,6111111111),(61000000009,6211111111),(62000000009,6311111111),(63000000009,6411111111),(64000000009,6511111111),(65000000009,6611111111),(66000000009,6711111111),(67000000009,6811111111),(68000000009,6911111111),(69000000009,7011111111),(70000000009,7111111111),(71000000009,7211111111),(72000000009,7311111111),(73000000009,7411111111),(74000000009,7511111111),(75000000009,7611111111),(76000000009,7711111111),(77000000009,7811111111),(78000000009,7911111111),(79000000009,8011111111),(80000000009,8111111111),(81000000009,8211111111),(82000000009,8311111111),(83000000009,8411111111),(84000000009,8511111111),(85000000009,8611111111),(86000000009,8711111111),(87000000009,8811111111),(88000000009,8911111111),(89000000009,9011111111),(90000000009,9111111111),(91000000009,9211111111),(92000000009,9311111111),(93000000009,9411111111),(94000000009,9511111111),(95000000009,9611111111),(96000000009,9711111111),(97000000009,9811111111),(98000000009,9911111111),(99000000010,10010101010),(100000000000,10101010100),(101000000001,10191919191),(102000000002,10282828282),(103000000003,10373737373),(104000000004,10464646464),(105000000005,10555555555),(106000000006,10646464646),(107000000007,10737373737),(108000000008,10828282828),(109000000009,10919191919),(110000000010,11010101010),(111000000000,11101010100),(112000000001,11191919191),(113000000002,11282828282),(114000000003,11373737373),(115000000004,11464646464),(116000000005,11555555555),(117000000006,11646464646),(118000000007,11737373737),(119000000008,11828282828),(120000000009,11919191919),(121000000010,12010101010),(122000000000,12101010100),(123000000001,12191919191),(124000000002,12282828282),(125000000003,12373737373),(126000000004,12464646464),(127000000005,12555555555),(128000000006,12646464646),(129000000007,12737373737),(130000000008,12828282828),(131000000009,12919191919),(132000000010,13010101010),(133000000000,13101010100),(134000000001,13191919191),(135000000002,13282828282),(136000000003,13373737373),(137000000004,13464646464),(138000000005,13555555555),(139000000006,13646464646),(140000000007,13737373737),(141000000008,13828282828),(142000000009,13919191919),(143000000010,14010101010),(144000000000,14101010100),(145000000001,14191919191),(146000000002,14282828282),(147000000003,14373737373),(148000000004,14464646464),(149000000005,14555555555),(150000000006,14646464646),(151000000007,14737373737),(152000000008,14828282828),(153000000009,14919191919),(154000000010,15010101010),(155000000000,15101010100),(156000000001,15191919191),(157000000002,15282828282),(158000000003,15373737373),(159000000004,15464646464),(160000000005,15555555555),(161000000006,15646464646),(162000000007,15737373737),(163000000008,15828282828),(164000000009,15919191919),(165000000010,16010101010),(166000000000,16101010100),(167000000001,16191919191),(168000000002,16282828282),(169000000003,16373737373),(170000000004,16464646464),(171000000005,16555555555),(172000000006,16646464646),(173000000007,16737373737),(174000000008,16828282828),(175000000009,16919191919),(176000000010,17010101010),(177000000000,17101010100),(178000000001,17191919191),(179000000002,17282828282),(180000000003,17373737373),(181000000004,17464646464),(182000000005,17555555555),(183000000006,17646464646),(184000000007,17737373737),(185000000008,17828282828),(186000000009,17919191919),(187000000010,18010101010),(188000000000,18101010100),(189000000001,18191919191),(190000000002,18282828282),(191000000003,18373737373),(192000000004,18464646464),(193000000005,18555555555),(194000000006,18646464646),(195000000007,18737373737),(196000000008,18828282828),(197000000009,18919191919),(198000000010,19010101010),(199000000000,19101010100),(200000000001,19191919191),(201000000002,19282828282),(202000000003,19373737373),(203000000004,19464646464),(204000000005,19555555555),(205000000006,19646464646),(206000000007,19737373737),(207000000008,19828282828),(208000000009,19919191919),(209000000010,20010101010),(210000000000,20101010100),(211000000001,20191919191),(212000000002,20282828282),(213000000003,20373737373),(214000000004,20464646464),(215000000005,20555555555),(216000000006,20646464646),(217000000007,20737373737),(218000000008,20828282828),(219000000009,20919191919),(220000000010,21010101010),(221000000000,21101010100),(222000000001,21191919191),(223000000002,21282828282),(224000000003,21373737373),(225000000004,21464646464),(226000000005,21555555555),(227000000006,21646464646),(228000000007,21737373737),(229000000008,21828282828),(230000000009,21919191919),(231000000010,22010101010),(232000000000,22101010100),(233000000001,22191919191),(234000000002,22282828282),(235000000003,22373737373),(236000000004,22464646464),(237000000005,22555555555),(238000000006,22646464646),(239000000007,22737373737),(240000000008,22828282828),(241000000009,22919191919),(242000000010,23010101010),(243000000000,23101010100),(244000000001,23191919191),(245000000002,23282828282),(246000000003,23373737373),(247000000004,23464646464),(248000000005,23555555555),(249000000006,23646464646),(250000000007,23737373737),(251000000008,23828282828),(252000000009,23919191919),(253000000010,24010101010),(254000000000,24101010100),(255000000001,24191919191),(256000000002,24282828282),(257000000003,24373737373),(258000000004,24464646464),(259000000005,24555555555),(260000000006,24646464646),(261000000007,24737373737),(262000000008,24828282828),(263000000009,24919191919),(264000000010,25010101010),(265000000000,25101010100),(266000000001,25191919191),(267000000002,25282828282),(268000000003,25373737373),(269000000004,25464646464),(270000000005,25555555555),(271000000006,25646464646),(272000000007,25737373737),(273000000008,25828282828),(274000000009,25919191919),(275000000010,26010101010),(276000000000,26101010100),(277000000001,26191919191),(278000000002,26282828282),(279000000003,26373737373),(280000000004,26464646464),(281000000005,26555555555),(282000000006,26646464646),(283000000007,26737373737),(284000000008,26828282828),(285000000009,26919191919),(286000000010,27010101010),(287000000000,27101010100),(288000000001,27191919191),(289000000002,27282828282),(290000000003,27373737373),(291000000004,27464646464),(292000000005,27555555555),(293000000006,27646464646),(294000000007,27737373737),(295000000008,27828282828),(296000000009,27919191919),(297000000010,28010101010),(298000000000,28101010100),(299000000001,28191919191),(300000000002,28282828282),(301000000003,28373737373),(302000000004,28464646464),(303000000005,28555555555),(304000000006,28646464646),(305000000007,28737373737),(306000000008,28828282828),(307000000009,28919191919),(308000000010,29010101010),(309000000000,29101010100),(310000000001,29191919191),(311000000002,29282828282),(312000000003,29373737373),(313000000004,29464646464),(314000000005,29555555555),(315000000006,29646464646),(316000000007,29737373737),(317000000008,29828282828),(318000000009,29919191919),(319000000010,30010101010),(320000000000,30101010100),(321000000001,30191919191),(322000000002,30282828282),(323000000003,30373737373),(324000000004,30464646464),(325000000005,30555555555),(326000000006,30646464646),(327000000007,30737373737),(328000000008,30828282828),(329000000009,30919191919),(330000000010,31010101010),(331000000000,31101010100),(332000000001,31191919191),(333000000002,31282828282),(334000000003,31373737373),(335000000004,31464646464),(336000000005,31555555555),(337000000006,31646464646),(338000000007,31737373737),(339000000008,31828282828),(340000000009,31919191919),(341000000010,32010101010),(342000000000,32101010100),(343000000001,32191919191),(344000000002,32282828282),(345000000003,32373737373),(346000000004,32464646464),(347000000005,32555555555),(348000000006,32646464646),(349000000007,32737373737),(350000000008,32828282828),(351000000009,32919191919),(352000000010,33010101010),(353000000000,33101010100),(354000000001,33191919191),(355000000002,33282828282),(356000000003,33373737373),(357000000004,33464646464),(358000000005,33555555555),(359000000006,33646464646),(360000000007,33737373737),(361000000008,33828282828),(362000000009,33919191919),(363000000010,34010101010),(364000000000,34101010100),(365000000001,34191919191),(366000000002,34282828282),(367000000003,34373737373),(368000000004,34464646464),(369000000005,34555555555),(370000000006,34646464646),(371000000007,34737373737),(372000000008,34828282828),(373000000009,34919191919),(374000000010,35010101010),(375000000000,35101010100),(376000000001,35191919191),(377000000002,35282828282),(378000000003,35373737373),(379000000004,35464646464),(380000000005,35555555555),(381000000006,35646464646),(382000000007,35737373737),(383000000008,35828282828),(384000000009,35919191919),(385000000010,36010101010),(386000000000,36101010100),(387000000001,36191919191),(388000000002,36282828282),(389000000003,36373737373),(390000000004,36464646464),(391000000005,36555555555),(392000000006,36646464646),(393000000007,36737373737),(394000000008,36828282828),(395000000009,36919191919),(396000000010,37010101010),(397000000000,37101010100),(398000000001,37191919191),(399000000002,37282828282),(400000000003,37373737373),(401000000004,37464646464),(402000000005,37555555555),(403000000006,37646464646),(404000000007,37737373737),(405000000008,37828282828),(406000000009,37919191919),(407000000010,38010101010),(408000000000,38101010100),(409000000001,38191919191),(410000000002,38282828282),(411000000003,38373737373),(412000000004,38464646464),(413000000005,38555555555),(414000000006,38646464646),(415000000007,38737373737),(416000000008,38828282828),(417000000009,38919191919),(418000000010,39010101010),(419000000000,39101010100),(420000000001,39191919191),(421000000002,39282828282),(422000000003,39373737373),(423000000004,39464646464),(424000000005,39555555555),(425000000006,39646464646),(426000000007,39737373737),(427000000008,39828282828),(428000000009,39919191919),(429000000010,40010101010),(430000000000,40101010100),(431000000001,40191919191),(432000000002,40282828282),(433000000003,40373737373),(434000000004,40464646464),(435000000005,40555555555),(436000000006,40646464646),(437000000007,40737373737),(438000000008,40828282828),(439000000009,40919191919),(440000000010,41010101010),(441000000000,41101010100),(442000000001,41191919191),(443000000002,41282828282),(444000000003,41373737373),(445000000004,41464646464),(446000000005,41555555555),(447000000006,41646464646),(448000000007,41737373737),(449000000008,41828282828),(450000000009,41919191919),(451000000010,42010101010),(452000000000,42101010100),(453000000001,42191919191),(454000000002,42282828282),(455000000003,42373737373),(456000000004,42464646464),(457000000005,42555555555),(458000000006,42646464646),(459000000007,42737373737),(460000000008,42828282828),(461000000009,42919191919),(462000000010,43010101010),(463000000000,43101010100),(464000000001,43191919191),(465000000002,43282828282),(466000000003,43373737373),(467000000004,43464646464),(468000000005,43555555555),(469000000006,43646464646),(470000000007,43737373737),(471000000008,43828282828),(472000000009,43919191919),(473000000010,44010101010),(474000000000,44101010100),(475000000001,44191919191),(476000000002,44282828282),(477000000003,44373737373),(478000000004,44464646464),(479000000005,44555555555),(480000000006,44646464646),(481000000007,44737373737),(482000000008,44828282828),(483000000009,44919191919),(484000000010,45010101010),(485000000000,45101010100),(486000000001,45191919191),(487000000002,45282828282),(488000000003,45373737373),(489000000004,45464646464),(490000000005,45555555555),(491000000006,45646464646),(492000000007,45737373737),(493000000008,45828282828),(494000000009,45919191919),(495000000010,46010101010),(496000000000,46101010100),(497000000001,46191919191),(498000000002,46282828282),(499000000003,46373737373),(500000000004,46464646464),(501000000005,46555555555),(502000000006,46646464646),(503000000007,46737373737),(504000000008,46828282828),(505000000009,46919191919),(506000000010,47010101010),(507000000000,47101010100),(508000000001,47191919191),(509000000002,47282828282),(510000000003,47373737373),(511000000004,47464646464),(512000000005,47555555555),(513000000006,47646464646),(514000000007,47737373737),(515000000008,47828282828),(516000000009,47919191919),(517000000010,48010101010),(518000000000,48101010100),(519000000001,48191919191),(520000000002,48282828282),(521000000003,48373737373),(522000000004,48464646464),(523000000005,48555555555),(524000000006,48646464646),(525000000007,48737373737),(526000000008,48828282828),(527000000009,48919191919),(528000000010,49010101010),(529000000000,49101010100),(530000000001,49191919191),(531000000002,49282828282),(532000000003,49373737373),(533000000004,49464646464),(534000000005,49555555555),(535000000006,49646464646),(536000000007,49737373737),(537000000008,49828282828),(538000000009,49919191919),(539000000010,50010101010),(540000000000,50101010100),(541000000001,50191919191),(542000000002,50282828282),(543000000003,50373737373),(544000000004,50464646464),(545000000005,50555555555),(546000000006,50646464646),(547000000007,50737373737),(548000000008,50828282828),(549000000009,50919191919),(550000000010,51010101010),(551000000000,51101010100),(552000000001,51191919191),(553000000002,51282828282),(554000000003,51373737373),(555000000004,51464646464),(556000000005,51555555555),(557000000006,51646464646),(558000000007,51737373737),(559000000008,51828282828),(560000000009,51919191919),(561000000010,52010101010),(562000000000,52101010100),(563000000001,52191919191),(564000000002,52282828282),(565000000003,52373737373),(566000000004,52464646464),(567000000005,52555555555),(568000000006,52646464646),(569000000007,52737373737),(570000000008,52828282828),(571000000009,52919191919),(572000000010,53010101010),(573000000000,53101010100),(574000000001,53191919191),(575000000002,53282828282),(576000000003,53373737373),(577000000004,53464646464),(578000000005,53555555555),(579000000006,53646464646),(580000000007,53737373737),(581000000008,53828282828),(582000000009,53919191919),(583000000010,54010101010),(584000000000,54101010100),(585000000001,54191919191),(586000000002,54282828282),(587000000003,54373737373),(588000000004,54464646464),(589000000005,54555555555),(590000000006,54646464646),(591000000007,54737373737),(592000000008,54828282828),(593000000009,54919191919),(594000000010,55010101010),(595000000000,55101010100),(596000000001,55191919191),(597000000002,55282828282),(598000000003,55373737373),(599000000004,55464646464),(600000000005,55555555555),(601000000006,55646464646),(602000000007,55737373737),(603000000008,55828282828),(604000000009,55919191919),(605000000010,56010101010),(606000000000,56101010100),(607000000001,56191919191),(608000000002,56282828282),(609000000003,56373737373),(610000000004,56464646464),(611000000005,56555555555),(612000000006,56646464646),(613000000007,56737373737),(614000000008,56828282828),(615000000009,56919191919),(616000000010,57010101010),(617000000000,57101010100),(618000000001,57191919191),(619000000002,57282828282),(620000000003,57373737373),(621000000004,57464646464),(622000000005,57555555555),(623000000006,57646464646),(624000000007,57737373737),(625000000008,57828282828),(626000000009,57919191919),(627000000010,58010101010),(628000000000,58101010100),(629000000001,58191919191),(630000000002,58282828282),(631000000003,58373737373),(632000000004,58464646464),(633000000005,58555555555),(634000000006,58646464646),(635000000007,58737373737),(636000000008,58828282828),(637000000009,58919191919),(638000000010,59010101010),(639000000000,59101010100),(640000000001,59191919191),(641000000002,59282828282),(642000000003,59373737373),(643000000004,59464646464),(644000000005,59555555555),(645000000006,59646464646),(646000000007,59737373737),(647000000008,59828282828),(648000000009,59919191919),(649000000010,60010101010),(650000000000,60101010100),(651000000001,60191919191),(652000000002,60282828282),(653000000003,60373737373),(654000000004,60464646464),(655000000005,60555555555),(656000000006,60646464646),(657000000007,60737373737),(658000000008,60828282828),(659000000009,60919191919),(660000000010,61010101010),(661000000000,61101010100),(662000000001,61191919191),(663000000002,61282828282),(664000000003,61373737373),(665000000004,61464646464),(666000000005,61555555555),(667000000006,61646464646),(668000000007,61737373737),(669000000008,61828282828),(670000000009,61919191919),(671000000010,62010101010),(672000000000,62101010100),(673000000001,62191919191),(674000000002,62282828282),(675000000003,62373737373),(676000000004,62464646464),(677000000005,62555555555),(678000000006,62646464646),(679000000007,62737373737),(680000000008,62828282828),(681000000009,62919191919),(682000000010,63010101010),(683000000000,63101010100),(684000000001,63191919191),(685000000002,63282828282),(686000000003,63373737373),(687000000004,63464646464),(688000000005,63555555555),(689000000006,63646464646),(690000000007,63737373737),(691000000008,63828282828),(692000000009,63919191919),(693000000010,64010101010),(694000000000,64101010100),(695000000001,64191919191),(696000000002,64282828282),(697000000003,64373737373),(698000000004,64464646464),(699000000005,64555555555),(700000000006,64646464646),(701000000007,64737373737),(702000000008,64828282828),(703000000009,64919191919),(704000000010,65010101010),(705000000000,65101010100),(706000000001,65191919191),(707000000002,65282828282),(708000000003,65373737373),(709000000004,65464646464),(710000000005,65555555555),(711000000006,65646464646),(712000000007,65737373737),(713000000008,65828282828),(714000000009,65919191919),(715000000010,66010101010),(716000000000,66101010100),(717000000001,66191919191),(718000000002,66282828282),(719000000003,66373737373),(720000000004,66464646464),(721000000005,66555555555),(722000000006,66646464646),(723000000007,66737373737),(724000000008,66828282828),(725000000009,66919191919),(726000000010,67010101010),(727000000000,67101010100),(728000000001,67191919191),(729000000002,67282828282),(730000000003,67373737373),(731000000004,67464646464),(732000000005,67555555555),(733000000006,67646464646),(734000000007,67737373737),(735000000008,67828282828),(736000000009,67919191919),(737000000010,68010101010),(738000000000,68101010100),(739000000001,68191919191),(740000000002,68282828282),(741000000003,68373737373),(742000000004,68464646464),(743000000005,68555555555),(744000000006,68646464646),(745000000007,68737373737),(746000000008,68828282828),(747000000009,68919191919),(748000000010,69010101010),(749000000000,69101010100),(750000000001,69191919191),(751000000002,69282828282),(752000000003,69373737373),(753000000004,69464646464),(754000000005,69555555555),(755000000006,69646464646),(756000000007,69737373737),(757000000008,69828282828),(758000000009,69919191919),(759000000010,70010101010),(760000000000,70101010100),(761000000001,70191919191),(762000000002,70282828282),(763000000003,70373737373),(764000000004,70464646464),(765000000005,70555555555),(766000000006,70646464646),(767000000007,70737373737),(768000000008,70828282828),(769000000009,70919191919),(770000000010,71010101010),(771000000000,71101010100),(772000000001,71191919191),(773000000002,71282828282),(774000000003,71373737373),(775000000004,71464646464),(776000000005,71555555555),(777000000006,71646464646),(778000000007,71737373737),(779000000008,71828282828),(780000000009,71919191919),(781000000010,72010101010),(782000000000,72101010100),(783000000001,72191919191),(784000000002,72282828282),(785000000003,72373737373),(786000000004,72464646464),(787000000005,72555555555),(788000000006,72646464646),(789000000007,72737373737),(790000000008,72828282828),(791000000009,72919191919),(792000000010,73010101010),(793000000000,73101010100),(794000000001,73191919191),(795000000002,73282828282),(796000000003,73373737373),(797000000004,73464646464),(798000000005,73555555555),(799000000006,73646464646),(800000000007,73737373737),(801000000008,73828282828),(802000000009,73919191919),(803000000010,74010101010),(804000000000,74101010100),(805000000001,74191919191),(806000000002,74282828282),(807000000003,74373737373),(808000000004,74464646464),(809000000005,74555555555),(810000000006,74646464646),(811000000007,74737373737),(812000000008,74828282828),(813000000009,74919191919),(814000000010,75010101010),(815000000000,75101010100),(816000000001,75191919191),(817000000002,75282828282),(818000000003,75373737373),(819000000004,75464646464),(820000000005,75555555555),(821000000006,75646464646),(822000000007,75737373737),(823000000008,75828282828),(824000000009,75919191919),(825000000010,76010101010),(826000000000,76101010100),(827000000001,76191919191),(828000000002,76282828282),(829000000003,76373737373),(830000000004,76464646464),(831000000005,76555555555),(832000000006,76646464646),(833000000007,76737373737),(834000000008,76828282828),(835000000009,76919191919),(836000000010,77010101010),(837000000000,77101010100),(838000000001,77191919191),(839000000002,77282828282),(840000000003,77373737373),(841000000004,77464646464),(842000000005,77555555555),(843000000006,77646464646),(844000000007,77737373737),(845000000008,77828282828),(846000000009,77919191919),(847000000010,78010101010),(848000000000,78101010100),(849000000001,78191919191),(850000000002,78282828282),(851000000003,78373737373),(852000000004,78464646464),(853000000005,78555555555),(854000000006,78646464646),(855000000007,78737373737),(856000000008,78828282828),(857000000009,78919191919),(858000000010,79010101010),(859000000000,79101010100),(860000000001,79191919191),(861000000002,79282828282),(862000000003,79373737373),(863000000004,79464646464),(864000000005,79555555555),(865000000006,79646464646),(866000000007,79737373737),(867000000008,79828282828),(868000000009,79919191919),(869000000010,80010101010),(870000000000,80101010100),(871000000001,80191919191),(872000000002,80282828282),(873000000003,80373737373),(874000000004,80464646464),(875000000005,80555555555),(876000000006,80646464646),(877000000007,80737373737),(878000000008,80828282828),(879000000009,80919191919),(880000000010,81010101010),(881000000000,81101010100),(882000000001,81191919191),(883000000002,81282828282),(884000000003,81373737373),(885000000004,81464646464),(886000000005,81555555555),(887000000006,81646464646),(888000000007,81737373737),(889000000008,81828282828),(890000000009,81919191919),(891000000010,82010101010),(892000000000,82101010100),(893000000001,82191919191),(894000000002,82282828282),(895000000003,82373737373),(896000000004,82464646464),(897000000005,82555555555),(898000000006,82646464646),(899000000007,82737373737),(900000000008,82828282828),(901000000009,82919191919),(902000000010,83010101010),(903000000000,83101010100),(904000000001,83191919191),(905000000002,83282828282),(906000000003,83373737373),(907000000004,83464646464),(908000000005,83555555555),(909000000006,83646464646),(910000000007,83737373737),(911000000008,83828282828),(912000000009,83919191919),(913000000010,84010101010),(914000000000,84101010100),(915000000001,84191919191),(916000000002,84282828282),(917000000003,84373737373),(918000000004,84464646464),(919000000005,84555555555),(920000000006,84646464646),(921000000007,84737373737),(922000000008,84828282828),(923000000009,84919191919),(924000000010,85010101010),(925000000000,85101010100),(926000000001,85191919191),(927000000002,85282828282),(928000000003,85373737373),(929000000004,85464646464),(930000000005,85555555555),(931000000006,85646464646),(932000000007,85737373737),(933000000008,85828282828),(934000000009,85919191919),(935000000010,86010101010),(936000000000,86101010100),(937000000001,86191919191),(938000000002,86282828282),(939000000003,86373737373),(940000000004,86464646464),(941000000005,86555555555),(942000000006,86646464646),(943000000007,86737373737),(944000000008,86828282828),(945000000009,86919191919),(946000000010,87010101010),(947000000000,87101010100),(948000000001,87191919191),(949000000002,87282828282),(950000000003,87373737373),(951000000004,87464646464),(952000000005,87555555555),(953000000006,87646464646),(954000000007,87737373737),(955000000008,87828282828),(956000000009,87919191919),(957000000010,88010101010),(958000000000,88101010100),(959000000001,88191919191),(960000000002,88282828282),(961000000003,88373737373),(962000000004,88464646464),(963000000005,88555555555),(964000000006,88646464646),(965000000007,88737373737),(966000000008,88828282828),(967000000009,88919191919),(968000000010,89010101010),(969000000000,89101010100),(970000000001,89191919191),(971000000002,89282828282),(972000000003,89373737373),(973000000004,89464646464),(974000000005,89555555555),(975000000006,89646464646),(976000000007,89737373737),(977000000008,89828282828),(978000000009,89919191919),(979000000010,90010101010),(980000000000,90101010100),(981000000001,90191919191),(982000000002,90282828282),(983000000003,90373737373),(984000000004,90464646464),(985000000005,90555555555),(986000000006,90646464646),(987000000007,90737373737),(988000000008,90828282828),(989000000009,90919191919),(990000000010,91010101010),(991000000000,91101010100),(992000000001,91191919191),(993000000002,91282828282),(994000000003,91373737373),(995000000004,91464646464),(996000000005,91555555555),(997000000006,91646464646),(998000000007,91737373737),(999000000008,91828282828),(1000000000009,91919191919),];\n\n let idx = k / STEP_SIZE;\n let starts = lookup[idx as usize];\n let result = solve_internal(k, starts.0, starts.1);\n result.0\n}\n\nfn solve_internal(k: Res, n: Res, d: Res) -> (char, Res, Res) {\n // counter for digits\n let mut n: Res = n;//1;\n // Potential number of the digit we search\n let mut d: Res = d;//1;\n while n().unwrap();\n println!(\"{}\", seq[input-1]);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "277f03acbd8d399c02c2be5b42a4af12", "src_uid": "1503d761dd4e129fb7c423da390544ff", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Res = u64;\nconst MAX_INP: Res = 1_000_000_000_000;\nconst STEP_SIZE: Res = 1000000000;\n\nfn main() {\n/*\n print!(\"let lookup = [\");\n let mut i = STEP_SIZE;\n let mut result = ('_', 1, 1);\n print!(\"(1,1),\");\n while i <= MAX_INP {\n result = solve_internal(i, result.1, result.2);\n print!(\"({},{}),\", result.1, result.2);\n i += STEP_SIZE;\n }\n println!(\"];\");\n*/\n\n\n let k = {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n input.trim().parse::().unwrap()\n };\n assert!((1 <= k) && (k <= MAX_INP), \"K out of input range. 1<= k <= 10^12\");\n let result = solve(k);\n println!(\"{}\", result);\n}\n\nfn int_len_(inp: Res) -> Res {\n if inp == 0 {\n return 1;\n }\n\n let mut res = 0;\n let mut temp = 1;\n while temp <= inp {\n res += 1;\n temp *= 10\n }\n res\n}\n\nfn int_len(inp: Res) -> Res {\n //debug_assert!(0 <= inp);\n //debug_assert!(inp <= MAX_INP);\n match inp {\n 1000000000000..=9999999999999 => 13,\n 100000000000..=999999999999 => 12,\n 10000000000..=99999999999 => 11,\n 1000000000..=9999999999 => 10,\n 100000000..=999999999 => 9,\n 10000000..=99999999 => 8,\n 1000000..=9999999 => 7,\n 100000..=999999 => 6,\n 10000..=99999 => 5,\n 1000..=9999 => 4,\n 100..=999 => 3,\n 10..=99 => 2,\n 0..=9 => 1,\n _ => unreachable!()\n }\n}\n\nfn solve(k: Res) -> char {\n let lookup = [(1,1),(1000000008,123456790),(2000000007,234567901),(3000000006,345679012),(4000000005,456790123),(5000000004,567901234),(6000000003,679012345),(7000000002,790123456),(8000000001,901234567),(9000000009,1011111111),(10000000009,1111111111),(11000000009,1211111111),(12000000009,1311111111),(13000000009,1411111111),(14000000009,1511111111),(15000000009,1611111111),(16000000009,1711111111),(17000000009,1811111111),(18000000009,1911111111),(19000000009,2011111111),(20000000009,2111111111),(21000000009,2211111111),(22000000009,2311111111),(23000000009,2411111111),(24000000009,2511111111),(25000000009,2611111111),(26000000009,2711111111),(27000000009,2811111111),(28000000009,2911111111),(29000000009,3011111111),(30000000009,3111111111),(31000000009,3211111111),(32000000009,3311111111),(33000000009,3411111111),(34000000009,3511111111),(35000000009,3611111111),(36000000009,3711111111),(37000000009,3811111111),(38000000009,3911111111),(39000000009,4011111111),(40000000009,4111111111),(41000000009,4211111111),(42000000009,4311111111),(43000000009,4411111111),(44000000009,4511111111),(45000000009,4611111111),(46000000009,4711111111),(47000000009,4811111111),(48000000009,4911111111),(49000000009,5011111111),(50000000009,5111111111),(51000000009,5211111111),(52000000009,5311111111),(53000000009,5411111111),(54000000009,5511111111),(55000000009,5611111111),(56000000009,5711111111),(57000000009,5811111111),(58000000009,5911111111),(59000000009,6011111111),(60000000009,6111111111),(61000000009,6211111111),(62000000009,6311111111),(63000000009,6411111111),(64000000009,6511111111),(65000000009,6611111111),(66000000009,6711111111),(67000000009,6811111111),(68000000009,6911111111),(69000000009,7011111111),(70000000009,7111111111),(71000000009,7211111111),(72000000009,7311111111),(73000000009,7411111111),(74000000009,7511111111),(75000000009,7611111111),(76000000009,7711111111),(77000000009,7811111111),(78000000009,7911111111),(79000000009,8011111111),(80000000009,8111111111),(81000000009,8211111111),(82000000009,8311111111),(83000000009,8411111111),(84000000009,8511111111),(85000000009,8611111111),(86000000009,8711111111),(87000000009,8811111111),(88000000009,8911111111),(89000000009,9011111111),(90000000009,9111111111),(91000000009,9211111111),(92000000009,9311111111),(93000000009,9411111111),(94000000009,9511111111),(95000000009,9611111111),(96000000009,9711111111),(97000000009,9811111111),(98000000009,9911111111),(99000000010,10010101010),(100000000000,10101010100),(101000000001,10191919191),(102000000002,10282828282),(103000000003,10373737373),(104000000004,10464646464),(105000000005,10555555555),(106000000006,10646464646),(107000000007,10737373737),(108000000008,10828282828),(109000000009,10919191919),(110000000010,11010101010),(111000000000,11101010100),(112000000001,11191919191),(113000000002,11282828282),(114000000003,11373737373),(115000000004,11464646464),(116000000005,11555555555),(117000000006,11646464646),(118000000007,11737373737),(119000000008,11828282828),(120000000009,11919191919),(121000000010,12010101010),(122000000000,12101010100),(123000000001,12191919191),(124000000002,12282828282),(125000000003,12373737373),(126000000004,12464646464),(127000000005,12555555555),(128000000006,12646464646),(129000000007,12737373737),(130000000008,12828282828),(131000000009,12919191919),(132000000010,13010101010),(133000000000,13101010100),(134000000001,13191919191),(135000000002,13282828282),(136000000003,13373737373),(137000000004,13464646464),(138000000005,13555555555),(139000000006,13646464646),(140000000007,13737373737),(141000000008,13828282828),(142000000009,13919191919),(143000000010,14010101010),(144000000000,14101010100),(145000000001,14191919191),(146000000002,14282828282),(147000000003,14373737373),(148000000004,14464646464),(149000000005,14555555555),(150000000006,14646464646),(151000000007,14737373737),(152000000008,14828282828),(153000000009,14919191919),(154000000010,15010101010),(155000000000,15101010100),(156000000001,15191919191),(157000000002,15282828282),(158000000003,15373737373),(159000000004,15464646464),(160000000005,15555555555),(161000000006,15646464646),(162000000007,15737373737),(163000000008,15828282828),(164000000009,15919191919),(165000000010,16010101010),(166000000000,16101010100),(167000000001,16191919191),(168000000002,16282828282),(169000000003,16373737373),(170000000004,16464646464),(171000000005,16555555555),(172000000006,16646464646),(173000000007,16737373737),(174000000008,16828282828),(175000000009,16919191919),(176000000010,17010101010),(177000000000,17101010100),(178000000001,17191919191),(179000000002,17282828282),(180000000003,17373737373),(181000000004,17464646464),(182000000005,17555555555),(183000000006,17646464646),(184000000007,17737373737),(185000000008,17828282828),(186000000009,17919191919),(187000000010,18010101010),(188000000000,18101010100),(189000000001,18191919191),(190000000002,18282828282),(191000000003,18373737373),(192000000004,18464646464),(193000000005,18555555555),(194000000006,18646464646),(195000000007,18737373737),(196000000008,18828282828),(197000000009,18919191919),(198000000010,19010101010),(199000000000,19101010100),(200000000001,19191919191),(201000000002,19282828282),(202000000003,19373737373),(203000000004,19464646464),(204000000005,19555555555),(205000000006,19646464646),(206000000007,19737373737),(207000000008,19828282828),(208000000009,19919191919),(209000000010,20010101010),(210000000000,20101010100),(211000000001,20191919191),(212000000002,20282828282),(213000000003,20373737373),(214000000004,20464646464),(215000000005,20555555555),(216000000006,20646464646),(217000000007,20737373737),(218000000008,20828282828),(219000000009,20919191919),(220000000010,21010101010),(221000000000,21101010100),(222000000001,21191919191),(223000000002,21282828282),(224000000003,21373737373),(225000000004,21464646464),(226000000005,21555555555),(227000000006,21646464646),(228000000007,21737373737),(229000000008,21828282828),(230000000009,21919191919),(231000000010,22010101010),(232000000000,22101010100),(233000000001,22191919191),(234000000002,22282828282),(235000000003,22373737373),(236000000004,22464646464),(237000000005,22555555555),(238000000006,22646464646),(239000000007,22737373737),(240000000008,22828282828),(241000000009,22919191919),(242000000010,23010101010),(243000000000,23101010100),(244000000001,23191919191),(245000000002,23282828282),(246000000003,23373737373),(247000000004,23464646464),(248000000005,23555555555),(249000000006,23646464646),(250000000007,23737373737),(251000000008,23828282828),(252000000009,23919191919),(253000000010,24010101010),(254000000000,24101010100),(255000000001,24191919191),(256000000002,24282828282),(257000000003,24373737373),(258000000004,24464646464),(259000000005,24555555555),(260000000006,24646464646),(261000000007,24737373737),(262000000008,24828282828),(263000000009,24919191919),(264000000010,25010101010),(265000000000,25101010100),(266000000001,25191919191),(267000000002,25282828282),(268000000003,25373737373),(269000000004,25464646464),(270000000005,25555555555),(271000000006,25646464646),(272000000007,25737373737),(273000000008,25828282828),(274000000009,25919191919),(275000000010,26010101010),(276000000000,26101010100),(277000000001,26191919191),(278000000002,26282828282),(279000000003,26373737373),(280000000004,26464646464),(281000000005,26555555555),(282000000006,26646464646),(283000000007,26737373737),(284000000008,26828282828),(285000000009,26919191919),(286000000010,27010101010),(287000000000,27101010100),(288000000001,27191919191),(289000000002,27282828282),(290000000003,27373737373),(291000000004,27464646464),(292000000005,27555555555),(293000000006,27646464646),(294000000007,27737373737),(295000000008,27828282828),(296000000009,27919191919),(297000000010,28010101010),(298000000000,28101010100),(299000000001,28191919191),(300000000002,28282828282),(301000000003,28373737373),(302000000004,28464646464),(303000000005,28555555555),(304000000006,28646464646),(305000000007,28737373737),(306000000008,28828282828),(307000000009,28919191919),(308000000010,29010101010),(309000000000,29101010100),(310000000001,29191919191),(311000000002,29282828282),(312000000003,29373737373),(313000000004,29464646464),(314000000005,29555555555),(315000000006,29646464646),(316000000007,29737373737),(317000000008,29828282828),(318000000009,29919191919),(319000000010,30010101010),(320000000000,30101010100),(321000000001,30191919191),(322000000002,30282828282),(323000000003,30373737373),(324000000004,30464646464),(325000000005,30555555555),(326000000006,30646464646),(327000000007,30737373737),(328000000008,30828282828),(329000000009,30919191919),(330000000010,31010101010),(331000000000,31101010100),(332000000001,31191919191),(333000000002,31282828282),(334000000003,31373737373),(335000000004,31464646464),(336000000005,31555555555),(337000000006,31646464646),(338000000007,31737373737),(339000000008,31828282828),(340000000009,31919191919),(341000000010,32010101010),(342000000000,32101010100),(343000000001,32191919191),(344000000002,32282828282),(345000000003,32373737373),(346000000004,32464646464),(347000000005,32555555555),(348000000006,32646464646),(349000000007,32737373737),(350000000008,32828282828),(351000000009,32919191919),(352000000010,33010101010),(353000000000,33101010100),(354000000001,33191919191),(355000000002,33282828282),(356000000003,33373737373),(357000000004,33464646464),(358000000005,33555555555),(359000000006,33646464646),(360000000007,33737373737),(361000000008,33828282828),(362000000009,33919191919),(363000000010,34010101010),(364000000000,34101010100),(365000000001,34191919191),(366000000002,34282828282),(367000000003,34373737373),(368000000004,34464646464),(369000000005,34555555555),(370000000006,34646464646),(371000000007,34737373737),(372000000008,34828282828),(373000000009,34919191919),(374000000010,35010101010),(375000000000,35101010100),(376000000001,35191919191),(377000000002,35282828282),(378000000003,35373737373),(379000000004,35464646464),(380000000005,35555555555),(381000000006,35646464646),(382000000007,35737373737),(383000000008,35828282828),(384000000009,35919191919),(385000000010,36010101010),(386000000000,36101010100),(387000000001,36191919191),(388000000002,36282828282),(389000000003,36373737373),(390000000004,36464646464),(391000000005,36555555555),(392000000006,36646464646),(393000000007,36737373737),(394000000008,36828282828),(395000000009,36919191919),(396000000010,37010101010),(397000000000,37101010100),(398000000001,37191919191),(399000000002,37282828282),(400000000003,37373737373),(401000000004,37464646464),(402000000005,37555555555),(403000000006,37646464646),(404000000007,37737373737),(405000000008,37828282828),(406000000009,37919191919),(407000000010,38010101010),(408000000000,38101010100),(409000000001,38191919191),(410000000002,38282828282),(411000000003,38373737373),(412000000004,38464646464),(413000000005,38555555555),(414000000006,38646464646),(415000000007,38737373737),(416000000008,38828282828),(417000000009,38919191919),(418000000010,39010101010),(419000000000,39101010100),(420000000001,39191919191),(421000000002,39282828282),(422000000003,39373737373),(423000000004,39464646464),(424000000005,39555555555),(425000000006,39646464646),(426000000007,39737373737),(427000000008,39828282828),(428000000009,39919191919),(429000000010,40010101010),(430000000000,40101010100),(431000000001,40191919191),(432000000002,40282828282),(433000000003,40373737373),(434000000004,40464646464),(435000000005,40555555555),(436000000006,40646464646),(437000000007,40737373737),(438000000008,40828282828),(439000000009,40919191919),(440000000010,41010101010),(441000000000,41101010100),(442000000001,41191919191),(443000000002,41282828282),(444000000003,41373737373),(445000000004,41464646464),(446000000005,41555555555),(447000000006,41646464646),(448000000007,41737373737),(449000000008,41828282828),(450000000009,41919191919),(451000000010,42010101010),(452000000000,42101010100),(453000000001,42191919191),(454000000002,42282828282),(455000000003,42373737373),(456000000004,42464646464),(457000000005,42555555555),(458000000006,42646464646),(459000000007,42737373737),(460000000008,42828282828),(461000000009,42919191919),(462000000010,43010101010),(463000000000,43101010100),(464000000001,43191919191),(465000000002,43282828282),(466000000003,43373737373),(467000000004,43464646464),(468000000005,43555555555),(469000000006,43646464646),(470000000007,43737373737),(471000000008,43828282828),(472000000009,43919191919),(473000000010,44010101010),(474000000000,44101010100),(475000000001,44191919191),(476000000002,44282828282),(477000000003,44373737373),(478000000004,44464646464),(479000000005,44555555555),(480000000006,44646464646),(481000000007,44737373737),(482000000008,44828282828),(483000000009,44919191919),(484000000010,45010101010),(485000000000,45101010100),(486000000001,45191919191),(487000000002,45282828282),(488000000003,45373737373),(489000000004,45464646464),(490000000005,45555555555),(491000000006,45646464646),(492000000007,45737373737),(493000000008,45828282828),(494000000009,45919191919),(495000000010,46010101010),(496000000000,46101010100),(497000000001,46191919191),(498000000002,46282828282),(499000000003,46373737373),(500000000004,46464646464),(501000000005,46555555555),(502000000006,46646464646),(503000000007,46737373737),(504000000008,46828282828),(505000000009,46919191919),(506000000010,47010101010),(507000000000,47101010100),(508000000001,47191919191),(509000000002,47282828282),(510000000003,47373737373),(511000000004,47464646464),(512000000005,47555555555),(513000000006,47646464646),(514000000007,47737373737),(515000000008,47828282828),(516000000009,47919191919),(517000000010,48010101010),(518000000000,48101010100),(519000000001,48191919191),(520000000002,48282828282),(521000000003,48373737373),(522000000004,48464646464),(523000000005,48555555555),(524000000006,48646464646),(525000000007,48737373737),(526000000008,48828282828),(527000000009,48919191919),(528000000010,49010101010),(529000000000,49101010100),(530000000001,49191919191),(531000000002,49282828282),(532000000003,49373737373),(533000000004,49464646464),(534000000005,49555555555),(535000000006,49646464646),(536000000007,49737373737),(537000000008,49828282828),(538000000009,49919191919),(539000000010,50010101010),(540000000000,50101010100),(541000000001,50191919191),(542000000002,50282828282),(543000000003,50373737373),(544000000004,50464646464),(545000000005,50555555555),(546000000006,50646464646),(547000000007,50737373737),(548000000008,50828282828),(549000000009,50919191919),(550000000010,51010101010),(551000000000,51101010100),(552000000001,51191919191),(553000000002,51282828282),(554000000003,51373737373),(555000000004,51464646464),(556000000005,51555555555),(557000000006,51646464646),(558000000007,51737373737),(559000000008,51828282828),(560000000009,51919191919),(561000000010,52010101010),(562000000000,52101010100),(563000000001,52191919191),(564000000002,52282828282),(565000000003,52373737373),(566000000004,52464646464),(567000000005,52555555555),(568000000006,52646464646),(569000000007,52737373737),(570000000008,52828282828),(571000000009,52919191919),(572000000010,53010101010),(573000000000,53101010100),(574000000001,53191919191),(575000000002,53282828282),(576000000003,53373737373),(577000000004,53464646464),(578000000005,53555555555),(579000000006,53646464646),(580000000007,53737373737),(581000000008,53828282828),(582000000009,53919191919),(583000000010,54010101010),(584000000000,54101010100),(585000000001,54191919191),(586000000002,54282828282),(587000000003,54373737373),(588000000004,54464646464),(589000000005,54555555555),(590000000006,54646464646),(591000000007,54737373737),(592000000008,54828282828),(593000000009,54919191919),(594000000010,55010101010),(595000000000,55101010100),(596000000001,55191919191),(597000000002,55282828282),(598000000003,55373737373),(599000000004,55464646464),(600000000005,55555555555),(601000000006,55646464646),(602000000007,55737373737),(603000000008,55828282828),(604000000009,55919191919),(605000000010,56010101010),(606000000000,56101010100),(607000000001,56191919191),(608000000002,56282828282),(609000000003,56373737373),(610000000004,56464646464),(611000000005,56555555555),(612000000006,56646464646),(613000000007,56737373737),(614000000008,56828282828),(615000000009,56919191919),(616000000010,57010101010),(617000000000,57101010100),(618000000001,57191919191),(619000000002,57282828282),(620000000003,57373737373),(621000000004,57464646464),(622000000005,57555555555),(623000000006,57646464646),(624000000007,57737373737),(625000000008,57828282828),(626000000009,57919191919),(627000000010,58010101010),(628000000000,58101010100),(629000000001,58191919191),(630000000002,58282828282),(631000000003,58373737373),(632000000004,58464646464),(633000000005,58555555555),(634000000006,58646464646),(635000000007,58737373737),(636000000008,58828282828),(637000000009,58919191919),(638000000010,59010101010),(639000000000,59101010100),(640000000001,59191919191),(641000000002,59282828282),(642000000003,59373737373),(643000000004,59464646464),(644000000005,59555555555),(645000000006,59646464646),(646000000007,59737373737),(647000000008,59828282828),(648000000009,59919191919),(649000000010,60010101010),(650000000000,60101010100),(651000000001,60191919191),(652000000002,60282828282),(653000000003,60373737373),(654000000004,60464646464),(655000000005,60555555555),(656000000006,60646464646),(657000000007,60737373737),(658000000008,60828282828),(659000000009,60919191919),(660000000010,61010101010),(661000000000,61101010100),(662000000001,61191919191),(663000000002,61282828282),(664000000003,61373737373),(665000000004,61464646464),(666000000005,61555555555),(667000000006,61646464646),(668000000007,61737373737),(669000000008,61828282828),(670000000009,61919191919),(671000000010,62010101010),(672000000000,62101010100),(673000000001,62191919191),(674000000002,62282828282),(675000000003,62373737373),(676000000004,62464646464),(677000000005,62555555555),(678000000006,62646464646),(679000000007,62737373737),(680000000008,62828282828),(681000000009,62919191919),(682000000010,63010101010),(683000000000,63101010100),(684000000001,63191919191),(685000000002,63282828282),(686000000003,63373737373),(687000000004,63464646464),(688000000005,63555555555),(689000000006,63646464646),(690000000007,63737373737),(691000000008,63828282828),(692000000009,63919191919),(693000000010,64010101010),(694000000000,64101010100),(695000000001,64191919191),(696000000002,64282828282),(697000000003,64373737373),(698000000004,64464646464),(699000000005,64555555555),(700000000006,64646464646),(701000000007,64737373737),(702000000008,64828282828),(703000000009,64919191919),(704000000010,65010101010),(705000000000,65101010100),(706000000001,65191919191),(707000000002,65282828282),(708000000003,65373737373),(709000000004,65464646464),(710000000005,65555555555),(711000000006,65646464646),(712000000007,65737373737),(713000000008,65828282828),(714000000009,65919191919),(715000000010,66010101010),(716000000000,66101010100),(717000000001,66191919191),(718000000002,66282828282),(719000000003,66373737373),(720000000004,66464646464),(721000000005,66555555555),(722000000006,66646464646),(723000000007,66737373737),(724000000008,66828282828),(725000000009,66919191919),(726000000010,67010101010),(727000000000,67101010100),(728000000001,67191919191),(729000000002,67282828282),(730000000003,67373737373),(731000000004,67464646464),(732000000005,67555555555),(733000000006,67646464646),(734000000007,67737373737),(735000000008,67828282828),(736000000009,67919191919),(737000000010,68010101010),(738000000000,68101010100),(739000000001,68191919191),(740000000002,68282828282),(741000000003,68373737373),(742000000004,68464646464),(743000000005,68555555555),(744000000006,68646464646),(745000000007,68737373737),(746000000008,68828282828),(747000000009,68919191919),(748000000010,69010101010),(749000000000,69101010100),(750000000001,69191919191),(751000000002,69282828282),(752000000003,69373737373),(753000000004,69464646464),(754000000005,69555555555),(755000000006,69646464646),(756000000007,69737373737),(757000000008,69828282828),(758000000009,69919191919),(759000000010,70010101010),(760000000000,70101010100),(761000000001,70191919191),(762000000002,70282828282),(763000000003,70373737373),(764000000004,70464646464),(765000000005,70555555555),(766000000006,70646464646),(767000000007,70737373737),(768000000008,70828282828),(769000000009,70919191919),(770000000010,71010101010),(771000000000,71101010100),(772000000001,71191919191),(773000000002,71282828282),(774000000003,71373737373),(775000000004,71464646464),(776000000005,71555555555),(777000000006,71646464646),(778000000007,71737373737),(779000000008,71828282828),(780000000009,71919191919),(781000000010,72010101010),(782000000000,72101010100),(783000000001,72191919191),(784000000002,72282828282),(785000000003,72373737373),(786000000004,72464646464),(787000000005,72555555555),(788000000006,72646464646),(789000000007,72737373737),(790000000008,72828282828),(791000000009,72919191919),(792000000010,73010101010),(793000000000,73101010100),(794000000001,73191919191),(795000000002,73282828282),(796000000003,73373737373),(797000000004,73464646464),(798000000005,73555555555),(799000000006,73646464646),(800000000007,73737373737),(801000000008,73828282828),(802000000009,73919191919),(803000000010,74010101010),(804000000000,74101010100),(805000000001,74191919191),(806000000002,74282828282),(807000000003,74373737373),(808000000004,74464646464),(809000000005,74555555555),(810000000006,74646464646),(811000000007,74737373737),(812000000008,74828282828),(813000000009,74919191919),(814000000010,75010101010),(815000000000,75101010100),(816000000001,75191919191),(817000000002,75282828282),(818000000003,75373737373),(819000000004,75464646464),(820000000005,75555555555),(821000000006,75646464646),(822000000007,75737373737),(823000000008,75828282828),(824000000009,75919191919),(825000000010,76010101010),(826000000000,76101010100),(827000000001,76191919191),(828000000002,76282828282),(829000000003,76373737373),(830000000004,76464646464),(831000000005,76555555555),(832000000006,76646464646),(833000000007,76737373737),(834000000008,76828282828),(835000000009,76919191919),(836000000010,77010101010),(837000000000,77101010100),(838000000001,77191919191),(839000000002,77282828282),(840000000003,77373737373),(841000000004,77464646464),(842000000005,77555555555),(843000000006,77646464646),(844000000007,77737373737),(845000000008,77828282828),(846000000009,77919191919),(847000000010,78010101010),(848000000000,78101010100),(849000000001,78191919191),(850000000002,78282828282),(851000000003,78373737373),(852000000004,78464646464),(853000000005,78555555555),(854000000006,78646464646),(855000000007,78737373737),(856000000008,78828282828),(857000000009,78919191919),(858000000010,79010101010),(859000000000,79101010100),(860000000001,79191919191),(861000000002,79282828282),(862000000003,79373737373),(863000000004,79464646464),(864000000005,79555555555),(865000000006,79646464646),(866000000007,79737373737),(867000000008,79828282828),(868000000009,79919191919),(869000000010,80010101010),(870000000000,80101010100),(871000000001,80191919191),(872000000002,80282828282),(873000000003,80373737373),(874000000004,80464646464),(875000000005,80555555555),(876000000006,80646464646),(877000000007,80737373737),(878000000008,80828282828),(879000000009,80919191919),(880000000010,81010101010),(881000000000,81101010100),(882000000001,81191919191),(883000000002,81282828282),(884000000003,81373737373),(885000000004,81464646464),(886000000005,81555555555),(887000000006,81646464646),(888000000007,81737373737),(889000000008,81828282828),(890000000009,81919191919),(891000000010,82010101010),(892000000000,82101010100),(893000000001,82191919191),(894000000002,82282828282),(895000000003,82373737373),(896000000004,82464646464),(897000000005,82555555555),(898000000006,82646464646),(899000000007,82737373737),(900000000008,82828282828),(901000000009,82919191919),(902000000010,83010101010),(903000000000,83101010100),(904000000001,83191919191),(905000000002,83282828282),(906000000003,83373737373),(907000000004,83464646464),(908000000005,83555555555),(909000000006,83646464646),(910000000007,83737373737),(911000000008,83828282828),(912000000009,83919191919),(913000000010,84010101010),(914000000000,84101010100),(915000000001,84191919191),(916000000002,84282828282),(917000000003,84373737373),(918000000004,84464646464),(919000000005,84555555555),(920000000006,84646464646),(921000000007,84737373737),(922000000008,84828282828),(923000000009,84919191919),(924000000010,85010101010),(925000000000,85101010100),(926000000001,85191919191),(927000000002,85282828282),(928000000003,85373737373),(929000000004,85464646464),(930000000005,85555555555),(931000000006,85646464646),(932000000007,85737373737),(933000000008,85828282828),(934000000009,85919191919),(935000000010,86010101010),(936000000000,86101010100),(937000000001,86191919191),(938000000002,86282828282),(939000000003,86373737373),(940000000004,86464646464),(941000000005,86555555555),(942000000006,86646464646),(943000000007,86737373737),(944000000008,86828282828),(945000000009,86919191919),(946000000010,87010101010),(947000000000,87101010100),(948000000001,87191919191),(949000000002,87282828282),(950000000003,87373737373),(951000000004,87464646464),(952000000005,87555555555),(953000000006,87646464646),(954000000007,87737373737),(955000000008,87828282828),(956000000009,87919191919),(957000000010,88010101010),(958000000000,88101010100),(959000000001,88191919191),(960000000002,88282828282),(961000000003,88373737373),(962000000004,88464646464),(963000000005,88555555555),(964000000006,88646464646),(965000000007,88737373737),(966000000008,88828282828),(967000000009,88919191919),(968000000010,89010101010),(969000000000,89101010100),(970000000001,89191919191),(971000000002,89282828282),(972000000003,89373737373),(973000000004,89464646464),(974000000005,89555555555),(975000000006,89646464646),(976000000007,89737373737),(977000000008,89828282828),(978000000009,89919191919),(979000000010,90010101010),(980000000000,90101010100),(981000000001,90191919191),(982000000002,90282828282),(983000000003,90373737373),(984000000004,90464646464),(985000000005,90555555555),(986000000006,90646464646),(987000000007,90737373737),(988000000008,90828282828),(989000000009,90919191919),(990000000010,91010101010),(991000000000,91101010100),(992000000001,91191919191),(993000000002,91282828282),(994000000003,91373737373),(995000000004,91464646464),(996000000005,91555555555),(997000000006,91646464646),(998000000007,91737373737),(999000000008,91828282828),(1000000000009,91919191919),];\n\n let idx = k / STEP_SIZE;\n let starts = lookup[idx as usize];\n let result = solve_internal(k, starts.0, starts.1);\n result.0\n}\n\nfn solve_internal(k: Res, n: Res, d: Res) -> (char, Res, Res) {\n // counter for digits\n let mut n: Res = n;//1;\n // Potential number of the digit we search\n let mut d: Res = d;//1;\n while n().unwrap();\n println!(\"{}\", seq.chars().nth(input-1).unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "42de97ef5f3231a972664776a92895ba", "src_uid": "1503d761dd4e129fb7c423da390544ff", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn main() {\n let stdin = stdin();\n\n let k: usize = {\n let mut buffer_string = String::new();\n stdin\n .read_line(&mut buffer_string)\n .expect(\"could not read line\");\n buffer_string.trim().parse().unwrap()\n };\n\n let mut digits = 0;\n for n in (1..).map(|m| m.to_string()) {\n let digits_in_n = n.len();\n if digits + digits_in_n < k {\n digits += digits_in_n;\n } else {\n let index_in_n = k - digits - 1;\n println!(\"{}\", n.chars().nth(index_in_n).unwrap());\n return;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3712ca3bbac1cec646b886f17bfd418a", "src_uid": "1503d761dd4e129fb7c423da390544ff", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const SEQ: &str = \"01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277\";\n\nfn user_input(mut r: R) -> usize {\n let mut input = String::new();\n r.read_to_string(&mut input).unwrap();\n input.split_whitespace().nth(0).unwrap().parse::().unwrap()\n}\n\nfn main() {\n let idx = user_input(std::io::stdin());\n println!(\"{}\", SEQ.chars().nth(idx).unwrap());\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "281f76baef99c1cefc0c0d498fdd8bb7", "src_uid": "1503d761dd4e129fb7c423da390544ff", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// -*- coding:utf-8-unix -*-\n\n#![allow(dead_code)]\n#![allow(unused_imports)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::io::*;\nuse std::mem;\nuse std::str;\nuse std::vec;\n\nconst INF: i64 = 1223372036854775807;\nconst MEM_SIZE: usize = 202020;\nconst MOD: i64 = 1000000007;\n// const MOD: i64 = 998244353;\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::stdin;\nuse std::io::stdout;\nuse std::io::Write;\n#[allow(dead_code)]\nfn read() -> T {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\n#[allow(dead_code)]\nfn readi() -> (i64) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n iter.next().unwrap().parse::().unwrap()\n}\n\n#[allow(dead_code)]\nfn read_vec() -> Vec {\n read::()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n#[allow(dead_code)]\nfn read_vec2(n: u32) -> Vec> {\n (0..n).map(|_| read_vec()).collect()\n}\n\n#[allow(dead_code)]\nfn readii() -> (i64, i64) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\n#[allow(dead_code)]\nfn readiii() -> (i64, i64, i64) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n#[allow(dead_code)]\nfn readuu() -> (usize, usize) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\nfn readcc() -> (char, char) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\n#[allow(dead_code)]\nfn readuuu() -> (usize, usize, usize) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\n#[allow(dead_code)]\nfn readuuuu() -> (usize, usize, usize, usize) {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n (\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n iter.next().unwrap().parse::().unwrap(),\n )\n}\n\nfn solve_part() {\n let s: String = read();\n let mut v = s.as_bytes().to_vec();\n let mut x = v[0] - '0' as u8;\n let x = x as usize;\n let mut res = (x - 1) * 10;\n for i in 0..v.len() {\n res += i + 1;\n }\n println!(\"{:?}\", res);\n return;\n}\nfn solve() {\n let n: usize = read();\n for i in 0..n {\n solve_part();\n }\n return;\n}\n\nfn main() {\n solve()\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "60ec4a9a26e2879ddb55ee7ce36c1776", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let input = input.trim();\n let t: i32 = input.parse().unwrap();\n for _tc in 0..t {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let input = input.trim();\n let n: i32 = input.parse().unwrap();\n let d = n % 10;\n let f = [1, 3, 6, 10];\n let answer = (d - 1) * 10 + f[input.len() - 1];\n println!(\"{}\", answer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a73c2bbba9d23a4557a11f7cbae4f876", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\nfn main() -> Result<(), Box> {\n let mut nums = Vec::new();\n for d in 1..=9 {\n let mut n = 0;\n let mut i = 0;\n for _ in 0..4 {\n n *= 10;\n n += d;\n i += 1;\n nums.push((n, i));\n }\n }\n //println!(\"{:?}\", nums);\n for _ in 0..read_usize() {\n let mut chars = 0;\n let target = read_usize();\n for (n, i) in nums.iter() {\n chars += *i;\n if *n == target {\n println!(\"{}\", chars);\n }\n }\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "7f02053ea31aeae98fb4531dc7a101cd", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn one_integer_line() -> i32 {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let input = input.trim();\n let t: i32 = input.parse().unwrap();\n t\n}\nfn main() {\n let t = one_integer_line();\n for _tc in 0..t {\n let n = one_integer_line();\n let d = n % 10;\n let mut answer = (d - 1) * 10;\n for i in 0..4 {\n if n >= (10 as i32).pow(i) {\n answer += (i + 1) as i32;\n }\n }\n println!(\"{}\", answer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "77271e12fc474648daca8520a418f7af", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n\nuse std::cmp::{\n max, min, Ordering,\n Ordering::{Equal, Greater, Less},\n Reverse,\n};\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\nuse std::convert::TryInto;\nuse std::fmt;\nuse std::io::{self, Read as _};\nuse std::mem::swap;\nuse std::num::{NonZeroU32, ParseIntError};\nuse std::ops::{\n Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,\n Index, IndexMut, Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub,\n SubAssign,\n};\nuse std::process::exit;\nuse std::{f32, f64, i128, i16, i32, i64, i8, isize, u128, u16, u32, u64, u8, usize};\n\npub use visualize::*;\npub mod visualize {\n pub trait Visualize {\n fn visualize(&self, split: &str);\n fn continuous(&self) {\n self.visualize(\"\");\n }\n fn spaces(&self) {\n self.visualize(\" \");\n }\n fn lines(&self) {\n self.visualize(\"\\n\");\n }\n }\n macro_rules ! impl_vis_for_sized {($ ($ t : ty ) ,+ ) => {$ (impl Visualize for $ t {fn visualize (& self , _split : & str ) {print ! (\"{}\" , self ) ; } } ) + } ; }\n impl_vis_for_sized! {usize , u8 , u16 , u32 , u64 , u128 , isize , i8 , i16 , i32 , i64 , i128 , String , & str , char }\n impl Visualize for [T] {\n fn visualize(&self, split: &str) {\n let n = self.iter().count();\n print!(\"{}\", {\n let mut buf = String::new();\n for i in 0..n {\n buf += self[i].to_string().as_str();\n if i != n - 1 {\n buf += split;\n }\n }\n buf\n })\n }\n }\n #[macro_export]\n macro_rules ! vis {() => {println ! () ; } ; ($ last : expr ; ) => {$ last . lines () ; vis ! () } ; ($ last : expr => ) => {$ last . continuous () ; vis ! () ; } ; ($ last : expr $ (, ) ? ) => {$ last . spaces () ; vis ! () ; } ; ($ first : expr ; $ ($ rest : tt ) * ) => {$ first . lines () ; println ! () ; vis ! ($ ($ rest ) * ) ; } ; ($ first : expr => $ ($ rest : tt ) * ) => {$ first . continuous () ; vis ! ($ ($ rest ) * ) ; } ; ($ first : expr , $ ($ rest : tt ) * ) => {$ first . spaces () ; print ! (\" \" ) ; vis ! ($ ($ rest ) * ) ; } ; }\n}\n\npub use consts::*;\npub mod consts {\n pub const MOD10E9_7: usize = 1000000007; // 10 ^ 9 + 7\n pub const MOD99_: usize = 998244353;\n pub const MAX: u64 = std::u64::MAX; // = 2 ^ 64 - 1 = 18446744073709551615 \u2248 1.8 * 10 ^ 19\n pub const INF: u64 = 2000000000000000000; // MAX / 9 < 2 * 10e18 < MAX / 10\n pub const FNI: i64 = -2000000000000000000; // == -(INF as i64)\n pub const PI: f64 = std::f64::consts::PI; // 3.141592653589793 -- 10 ^ -15\n pub const ASCII_A_LARGE: u8 = 65;\n pub const ASCII_A_SMALL: u8 = 97;\n pub const ASCII_0: u8 = 48;\n pub const ADJ4: &[(isize, isize); 4] = &[(1, 0), (0, 1), (-1, 0), (0, -1)];\n pub const ADJ8: &[(isize, isize); 8] = &[\n (1, 0),\n (1, 1),\n (0, 1),\n (-1, 1),\n (-1, 0),\n (-1, -1),\n (0, -1),\n (1, -1),\n ];\n}\n\nfn main() {\n let mut input = \"\".to_owned();\n io::stdin().read_to_string(&mut input).unwrap();\n let input = input.trim();\n let mut input = input.split_whitespace();\n\n // generate testcases\n for t in 0..input.next().unwrap().parse::().unwrap() {\n solve(&mut input);\n }\n // not testcase\n // solve(&mut input);\n}\n\nfn solve(input: &mut std::str::SplitWhitespace) {\n macro_rules! read {\n () => ();\n ([$tt:tt]) => (read!([$tt; read!(usize)]));\n ([$tt:tt; $n:expr]) => ((0..$n).map(|_| read!($tt)).collect::>());\n (($($tt:tt),+)) => (($(read!($tt)),*));\n (Usize1) => (read!(usize) - 1);\n (Chars) => (read!(String).chars().collect::>());\n (Byte) => (read!(char) as u8);\n (Bytes) => (read!(String).into_bytes());\n ($ty:ty) => (input.next().unwrap().trim().parse::<$ty>().unwrap());\n }\n macro_rules! input {\n ($($id:ident : $ty:tt),*) => {\n $(\n let $id = read!($ty);\n )*\n }\n }\n\n input! {\n n: usize\n }\n\n let c = n % 10;\n let l = n.to_string().len();\n\n let ans = (c - 1) * sum(4) + sum(l);\n vis!(ans);\n}\n\nfn sum(n: usize) -> usize {\n match n {\n 1 => 1,\n 2 => 3,\n 3 => 6,\n 4 => 10,\n _ => unreachable!()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "725fd287e11cfd9b2edc0d554cc62421", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes.by_ref().map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, [graph1; $len:expr]) => {{\n let mut g = vec![vec![]; $len];\n let ab = read_value!($next, [(usize1, usize1)]);\n for (a, b) in ab {\n g[a].push(b);\n g[b].push(a);\n }\n g\n }};\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n ($next:expr, usize1) => (read_value!($next, usize) - 1);\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n read_value!($next, [$t; len])\n }};\n ($next:expr, $t:ty) => ($next().parse::<$t>().expect(\"Parse error\"));\n}\n\n#[allow(unused)]\nmacro_rules! debug {\n ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());\n}\n#[allow(unused)]\nmacro_rules! debugln {\n ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n #[allow(unused)]\n macro_rules! putvec {\n ($v:expr) => {\n for i in 0..$v.len() {\n puts!(\"{}{}\", $v[i], if i + 1 == $v.len() {\"\\n\"} else {\" \"});\n }\n }\n }\n input!(s: [chars]);\n for s in s {\n let c = (s[0] as u8 - b'0') as usize;\n let n = s.len();\n puts!(\"{}\\n\", 10 * (c - 1) + n * (n + 1) / 2);\n }\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "35e8ed05db5f6e34c730b387c487178d", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\nfn main() {\n let T = get!(usize);\n let mut kouho = vec![];\n for i in 1..10 {\n let mut p = i;\n for j in 0..1000000 {\n kouho.push(p);\n p = p * 10 + i;\n if p > 10000 {\n break;\n }\n }\n }\n mydbg!(kouho);\n\n for testcase in 0..T {\n mydbg!(testcase);\n let mut ans = 0;\n let X = get!(usize);\n for i in 0..kouho.len() {\n let k = kouho[i].to_string().chars().toVec().len();\n ans += k;\n if kouho[i] == X {\n break;\n }\n }\n\n echo!(ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d7d1a01398bd7dc50378bfcb833f8512", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\nuse std::{fmt, ops, str};\n\nmacro_rules! read {\n ( $t:ty ) => {{\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.trim_end().parse::<$t>().ok().unwrap()\n }};\n ( $( $t:ty ),* ) => {{\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let mut iter = input.split_whitespace();\n ( $( iter.next().unwrap().parse::<$t>().unwrap() ),* )\n }};\n}\n\nstruct Ios(Vec);\n\nimpl str::FromStr for Ios {\n type Err = ();\n\n fn from_str(s: &str) -> Result {\n Ok(Ios(s.trim_end().chars().collect()))\n }\n}\n\nimpl fmt::Display for Ios {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\", self.0.iter().collect::())\n }\n}\n\nstruct Iov(Vec);\n\nimpl str::FromStr for Iov {\n type Err = T::Err;\n\n fn from_str(s: &str) -> Result {\n let iter = s.split_whitespace();\n Ok(Iov(iter.map(|x| x.parse()).collect::>()?))\n }\n}\n\nimpl fmt::Display for Iov {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\",\n self.0.iter().map(|x| x.to_string())\n .collect::>().join(\" \")\n )\n }\n}\n\nimpl ops::Index for Iov {\n type Output = T;\n\n fn index(&self, i: usize) -> &Self::Output {\n self.0.get(i - 1).unwrap()\n }\n}\n\nfn solve(writer: &mut io::BufWriter) {\n let x = read!(i32);\n\n let mut ans = 0;\n 'outer: for i in 1..=9 {\n let mut p = 0;\n for j in 1..=4 {\n p = p * 10 + i;\n ans += j;\n if p == x { break 'outer; }\n }\n }\n writeln!(writer, \"{}\", ans).ok();\n}\n\nfn main() {\n let stdout = io::stdout();\n let mut writer = io::BufWriter::new(stdout.lock());\n for _ in 0..read!(usize) { solve(&mut writer); }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "380206470e7810ab93f909df5253ec12", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, stdout, Write, BufReader, BufRead, Read};\n\nfn solve(input: &mut BufRead, output: &mut Write) {\n let mut input = BufReader::new(input);\n\n let mut line = String::with_capacity(100);\n input.read_line(&mut line).unwrap();\n let line = line.trim();\n\n if line.chars().next().unwrap() == '0' {\n output.write(b\"0\\n\");\n } else if line.chars().filter(|&it| it == '1').count() == 1 {\n output.write(format!(\"{}\\n\", line.len() / 2).as_bytes());\n } else {\n output.write(format!(\"{}\\n\", (line.len() + 1) / 2).as_bytes());\n }\n\n}\n\nfn main() {\n let stdin = stdin();\n let stdout = stdout();\n solve(&mut stdin.lock(), &mut stdout.lock());\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "7bb4b237c1c6639adbb1df47329e59cc", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn main() {\n let mut stdin = stdin();\n let mut buffer = String::new();\n let _ = stdin.read_to_string(&mut buffer);\n let s = buffer.trim();\n\n println!(\"{}\", (s.len() + s[1..].contains(\"1\") as usize) / 2);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1a9171fad96c98e1bcd3d099e6da2f4c", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let s = input.bs();\n let n = s.len();\n let sol = n / 2 + (if n % 2 == 1 && s[1..].iter().any(|x| *x == b'1') {1} else {0});\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "2106e96a8f657fd1053017902f4a40b1", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let s = parse_line!(String);\n let mut result = s.len() / 2;\n if s.len() % 2 == 1 {\n for c in s.bytes().skip(1) {\n if c == b'1' {\n result += 1;\n break;\n }\n }\n }\n writeln!(writer, \"{}\", result).unwrap();\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "482ee2c4b7bd2c57c858a77df7252fa9", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let s: u128 = u128::from_str_radix(buf.trim(), 2).unwrap();\n\n let mut k = 0;\n while 4u128.pow(k) < s {\n k += 1;\n }\n\n println!(\"{}\", k);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "4496db0b55d519b377609724a29c0b0e", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n \nfn get_input(input: &mut String) {\n input.clear();\n stdin().read_line(input).expect(\"error\");\n}\n \nfn main() {\n let mut input = String::new();\n \n get_input(&mut input);\n let mut count = input.trim().chars().count();\n if input.trim().chars().map(|c| if c == '1' {1} else {0} ).sum::() >= 2 {\n count += 1;\n }\n count = count / 2;\n\n println!(\"{}\", count);\n\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "5c9e02f31aca5be8749322bb873b5569", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_variables)]\n#![allow(unused_must_use)]\n\nuse std::io::{self, prelude::*};\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let mut input = Input::new(stdin.lock());\n let mut output = io::BufWriter::new(stdout.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(output ,$($format)*).unwrap());\n }\n let s: String = input.next();\n let s = s.into_bytes();\n let mut s2: Vec = s\n .as_slice()\n .rchunks(2)\n .map(|chunk| {\n if chunk.len() == 1 {\n chunk[0] - b'0'\n } else {\n (chunk[0] - b'0') * 2 + chunk[1] - b'0'\n }\n })\n .collect();\n s2.as_mut_slice().reverse();\n if s2[0] > 1 || s2[1..].iter().any(|&c| c != 0) {\n puts!(\"{}\\n\", s2.len());\n return;\n }\n puts!(\"{}\\n\", s2.len() - 1);\n}\n\nstruct Input {\n lines: io::Lines,\n cur: String,\n split: std::str::SplitAsciiWhitespace<'static>, //'\n}\n\nimpl Input {\n fn new(reader: R) -> Input {\n use std::mem::transmute;\n\n let mut lines = reader.lines();\n let cur = lines.next().unwrap().unwrap();\n let split = unsafe { transmute(cur.split_ascii_whitespace()) };\n Input { lines, cur, split }\n }\n fn update(&mut self) {\n use std::mem::transmute;\n self.cur = self.lines.next().unwrap().unwrap();\n unsafe { self.split = transmute(self.cur.split_ascii_whitespace()) };\n }\n fn next(&mut self) -> F {\n loop {\n if let Some(thing) = self.split.next() {\n return thing.parse().ok().unwrap();\n }\n self.update();\n }\n }\n fn iter(&mut self) -> InputIter {\n InputIter {\n input: self,\n _phantom: std::marker::PhantomData,\n }\n }\n}\n\nstruct InputIter<'a, R, I> {\n input: &'a mut Input,\n _phantom: std::marker::PhantomData,\n}\n\nimpl<'a, R, I> Iterator for InputIter<'a, R, I>\nwhere\n R: BufRead,\n I: std::str::FromStr,\n{\n type Item = I;\n fn next(&mut self) -> Option {\n Some(self.input.next())\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "20f84cd4e266397344e86c5a69452fb5", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n s: chars,\n }\n if s[0] == '0' {\n println!(\"0\");\n return;\n }\n let l = s.len();\n if l % 2 == 0 {\n println!(\"{}\", l / 2);\n } else {\n let mut ans = (l + 1) / 2;\n if !s[1..].iter().any(|c| *c == '1') {\n ans -= 1;\n }\n println!(\"{}\", ans);\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "72df3d5e87646c9963a83a6ca7421d5f", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n if self.f[crt] { return; }\n self.c += 1;\n self.f[crt] = true;\n self.v.push(crt);\n self.vc[crt] = self.c;\n self.u[crt] = self.v.len()-1;\n for i in 0..self.e[crt].len() {\n self.dfs(self.e[crt][i]);\n }\n //debug!(crt, self.c, self.vc[crt]);\n self.vc[crt] = self.c - self.vc[crt];\n }\n}\n\nfn divisor(n:usize) -> Vec {\n let mut res = Vec::new();\n let mut i = 1;\n while i*i <= n {\n if n%i == 0 {\n res.push(i);\n if i != n/i { res.push(n/i); }\n }\n i += 1;\n }\n res.sort();\n res\n}\n\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let mut t:Vec = read::().chars().collect();\n\n let div = divisor(n);\n for d in div {\n //debug!(d,t);\n for i in 0..d/2 {\n t.swap(i,d-i-1);\n }\n //debug!(t);\n }\n for e in t {print!(\"{}\",e);} println!();\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "423f20a2069eb931ba9106b60bc6959d", "src_uid": "1b0b2ee44c63cb0634cb63f2ad65cdd3", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let num = read().parse::().unwrap();\n let mut data = read();\n for n in 1..num + 1{\n if num % n == 0{\n let temp = data.clone();\n let (first,last) = temp.split_at(n);\n let first = first.chars().rev().collect::();\n\n data.clear();\n data.push_str(first.as_str());\n data.push_str(last);\n }\n }\n println!(\"{}\",data);\n}\n\nfn read() -> String {\n let mut a = String::new();\n io::stdin().read_line(&mut a).unwrap();\n a.trim().to_string()\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "12deb626986980af56a5d48530f336e2", "src_uid": "1b0b2ee44c63cb0634cb63f2ad65cdd3", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n// use std::collections::*; // HashSet, HashMap, BTreeSet, BTreeMap, ...\n\nfn main() {\n let stdin: io::Stdin = io::stdin();\n let mut lines: io::Lines = stdin.lock().lines();\n\n let next_line = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let flv: Vec<_> = next_line\n .trim()\n .split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n\n let n = flv[0];\n\n let mut s: String = lines.next()\n .unwrap()\n .unwrap()\n .trim()\n .to_string();\n\n for i in 2..n {\n if n % i == 0 {\n let tmp_end = s.split_off(i);\n s = s.chars().rev().collect();\n s.push_str(&tmp_end);\n // println!(\"{}: {}\", i, s);\n }\n }\n s = s.chars().rev().collect();\n\n println!(\"{}\", s);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3c74d8f3dead3a937ee4fcece7abcb61", "src_uid": "1b0b2ee44c63cb0634cb63f2ad65cdd3", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\n let mut input_text = String::new();\n io::stdin().read_line(&mut input_text).expect(\"fail\");\n let n = input_text.trim().parse::().expect(\"parse error\");\n\n let mut string = String::new();\n io::stdin().read_line(&mut string).expect(\"fail\");\n\n let string = string.chars();\n\n let mut vec = Vec::new();\n for c in string {\n vec.push(c);\n }\n\n for d in 1..n+1 {\n if n % d == 0 {\n for i in 0..d/2 {\n let t = vec[i as usize];\n vec[i as usize] = vec[d as usize - i as usize - 1usize];\n vec[d as usize - i as usize - 1usize] = t;\n }\n }\n }\n for i in 0..n {\n print!(\"{}\", vec[i as usize]);\n }\n print!(\"\\n\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e05e69d6400241727b2127bf91679e6a", "src_uid": "1b0b2ee44c63cb0634cb63f2ad65cdd3", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_u8() -> u8 {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().parse().unwrap()\n}\n\nfn read_string() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\nfn main() {\n let n = read_u8();\n let n_sqrt = (n as f64).sqrt() as u8;\n let mut s = read_string();\n\n let mut divs: Vec = vec!();\n for i in 1..=n_sqrt {\n if n%i == 0 {\n divs.push(i as usize);\n if i*i != n {\n divs.push((n/i) as usize);\n }\n }\n }\n divs.sort();\n\n for i in divs.iter() {\n let t = s.split_off(*i);\n s = s.chars().rev().collect();\n s.push_str(&t);\n }\n\n println!(\"{}\", s);\n\n return;\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5b47d2b7a7eb58625d3c24ca61f0a862", "src_uid": "1b0b2ee44c63cb0634cb63f2ad65cdd3", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_ints() -> Vec {\n let mut ln = String::new();\n std::io::stdin().read_line(&mut ln).expect(\"\");\n ln.split_whitespace().filter_map(|w| w.parse().ok()).collect()\n}\n\nfn read_line() -> String {\n let mut ln = String::new();\n std::io::stdin().read_line(&mut ln).expect(\"\");\n String::from(ln.trim_right())\n}\n\nfn main() {\n let n = read_ints()[0] as usize;\n let mut s = read_line();\n assert_eq!(n, s.len());\n\n for i in 2..=n {\n if n % i == 0 {\n let t = s.split_off(i);\n s = s.chars().rev().collect();\n s.push_str(&t);\n }\n }\n println!(\"{}\", s);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5ced1d46a5117ea23aac803ec8eda731", "src_uid": "1b0b2ee44c63cb0634cb63f2ad65cdd3", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use io::*;\n\nfn main() {\n let con = read_string();\n let mut sc = Scanner::new(&con);\n\n let n: usize = sc.next();\n let mut s: Vec = sc.next::().chars().collect();\n\n for i in 1..=n {\n if n % i != 0 {\n continue;\n }\n s[0..i].reverse();\n }\n\n let ans: String = s.iter().collect();\n println!(\"{}\", ans);\n}\n\n//-----\n\npub mod io {\n use std;\n use std::str::FromStr;\n\n pub struct Scanner<'a> {\n iter: std::str::SplitWhitespace<'a>,\n }\n\n impl<'a> Scanner<'a> {\n pub fn new(s: &'a str) -> Scanner<'a> {\n Scanner {\n iter: s.split_whitespace(),\n }\n }\n\n pub fn next(&mut self) -> T {\n let s = self.iter.next().unwrap();\n if let Ok(v) = s.parse::() {\n v\n } else {\n panic!(\"Parse error\")\n }\n }\n\n pub fn next_vec_len(&mut self) -> Vec {\n let n: usize = self.next();\n self.next_vec(n)\n }\n\n pub fn next_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n }\n\n pub fn read_string() -> String {\n use std::io::Read;\n\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n }\n\n pub fn read_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim_right().to_owned()\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b5238fdb61aefcba97b86554a4d8d69c", "src_uid": "1b0b2ee44c63cb0634cb63f2ad65cdd3", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let input : Vec = buffer.split_whitespace()\n .map(|x| x.trim().parse::().unwrap())\n .collect();\n let x = input[0];\n let y = input[1];\n let l = input[2];\n let r = input[3];\n \n let mut powx: Vec = vec![1];\n while r / powx.last().unwrap() >= x {\n powx.push(powx.last().unwrap() * x);\n }\n \n let mut powy: Vec = vec![1];\n while r / powy.last().unwrap() >= y {\n powy.push(powy.last().unwrap() * y);\n }\n \n let mut unluckys : Vec = vec![l-1, r+1];\n for i in &powx {\n for j in &powy {\n if i + j >= l && i + j <= r {\n unluckys.push(i+j);\n }\n }\n }\n unluckys.sort();\n\n let mut max_lucky : i64 = 0;\n for i in 1..unluckys.len() {\n max_lucky = cmp::max(max_lucky, unluckys[i] - unluckys[i-1]);\n }\n println!(\"{}\", max_lucky-1);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "597f49eefa8205465d8917e18d253d1b", "src_uid": "68ca8a8730db27ac2230f9fe9b120f5f", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input_split() -> Vec {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let (y_chr, b_chr) = {\n let temp = input_split();\n (temp[0], temp[1])\n };\n let (y, g, b) = {\n let temp = input_split();\n (temp[0], temp[1], temp[2])\n };\n\n let mut req_chr = 0u64;\n req_chr += u64::from((2 * y + g).max(y_chr) - y_chr);\n req_chr += u64::from((3 * b + g).max(b_chr) - b_chr);\n println!(\"{}\", req_chr);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c3f4a677790e690f9e37e5090943cc11", "src_uid": "35202a4601a03d25e18dda1539c5beba", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\nfn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let crystals = s.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let balls = s.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n\n let mut no_yb = balls[0]*2 - crystals[0];\n let rem_y = if no_yb >= 0 {0} else {let a=-no_yb;no_yb=0;a};\n let mut no_bb = balls[2]*3 - crystals[1];\n let rem_b = if no_bb >= 0 {0} else {let a=-no_bb;no_bb=0;a};\n let no_gby = if balls[1] > rem_y {balls[1] - rem_y} else {0};\n let no_gbb = if balls[1] > rem_b {balls[1] - rem_b} else {0};\n let no_gb = no_gby + no_gbb;\n println!(\"{}\",no_yb + no_gb + no_bb);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "11e174468ba053bd9662628f69866390", "src_uid": "35202a4601a03d25e18dda1539c5beba", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nconst BALLS_SIZE: usize = 3;\nconst CRYST_SIZE: usize = 2;\n\nenum ColorsB{\n Yell,\n Green,\n Blue\n}\n\ntype CrystalsArray = [i64; CRYST_SIZE];\ntype BallsArray = [i64; BALLS_SIZE];\n\nfn count_crystals(balls :BallsArray) -> CrystalsArray{\n fn count_yellow(num: i64 ) -> CrystalsArray {\n [2*num, 0]\n }\n fn count_green(num: i64 ) -> CrystalsArray {\n [num, num]\n }\n fn count_blue(num: i64 ) -> CrystalsArray {\n [0,3*num]\n }\n println!(\"\");\n let mut res: CrystalsArray = [0; CRYST_SIZE];\n for (ind,i) in count_yellow(balls[ColorsB::Yell as usize]).iter().enumerate(){\n res[ind] += *i;\n }\n for (ind,i) in count_green(balls[ColorsB::Green as usize]).iter().enumerate(){\n res[ind] += *i;\n }\n\n for (ind,i) in count_blue(balls[ColorsB::Blue as usize]).iter().enumerate(){\n res[ind] += *i;\n }\n return res ;\n}\n\nfn main() {\n let mut input: String = String::new();\n io::stdin().read_line(&mut input).expect(\"some error\");\n let mut cryst_inp: CrystalsArray = [0; CRYST_SIZE];\n let mut balls_inp: BallsArray = [0; BALLS_SIZE];\n for (ind,i) in input.trim().split(char::is_whitespace).enumerate(){\n cryst_inp[ind] = i.trim().parse().expect(\"failed to parse\");\n }\n input.clear();\n io::stdin().read_line(&mut input).expect(\"some error\");\n for (ind,i) in input.trim().split(char::is_whitespace).enumerate(){\n balls_inp[ind] = i.trim().parse().expect(\"failed to parse\");\n }\n let have_to = count_crystals(balls_inp);\n let mut sum = 0;\n for (ind,i) in cryst_inp.iter().enumerate(){\n let diff = have_to[ind] - i;\n if diff > 0 {\n sum += diff;\n }\n }\n print!(\"{}\", sum);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e71ed74a24ad81f0ff770cda8f2bdf42", "src_uid": "35202a4601a03d25e18dda1539c5beba", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get().parse::().unwrap());\n }\n \n let a = get!();\n let b = get!();\n let x = get!();\n let y = get!();\n let z = get!();\n \n let ra = x * 2 + y;\n let rb = y + z * 3;\n let ans = std::cmp::max(0, ra - a)\n + std::cmp::max(0, rb - b);\n\n println!(\"{}\", ans);\n \n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f5ad21556e617d739fec2cbe7e45783b", "src_uid": "35202a4601a03d25e18dda1539c5beba", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::{stderr, stdin, stdout, BufWriter, StdoutLock, Write};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::{i64, u64, usize};\n#[allow(unused_macros)]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; ( $ next : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , [ $ t : tt ] ) => { { let len = read_value ! ( $ next , usize ) ; ( 0 .. len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n#[allow(dead_code)]\nstruct Writer {\n s: String,\n}\n#[allow(unused_imports)]\nuse std::fmt::Display;\n#[allow(dead_code)]\n#[doc = \" let mut writer = Writer::new();\"]\n#[doc = \" writer.writeln(hoge);\"]\n#[doc = \" writer.flush()\"]\nimpl Writer {\n #[allow(dead_code)]\n pub fn new() -> Writer {\n Writer { s: String::new() }\n }\n #[allow(dead_code)]\n pub fn flush(&mut self) {\n print!(\"{}\", self.s);\n self.s.clear();\n }\n pub fn write(&mut self, x: T) {\n self.s.push_str(&format!(\"{}\", x));\n }\n pub fn writeln(&mut self, x: T) {\n self.s.push_str(&format!(\"{}\", x));\n self.s.push('\\n');\n }\n #[allow(dead_code)]\n pub fn write_vec(&mut self, xs: &Vec) {\n if xs.len() == 0 {\n self.writeln(\"\");\n return;\n }\n self.write(&format!(\"{}\", xs[0]));\n for i in 1..xs.len() {\n self.write(&format!(\" {}\", xs[i]));\n }\n self.writeln(\"\");\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! dbg { ( $ ( $ a : expr ) ,* ) => { writeln ! ( & mut stderr ( ) , concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) . unwrap ( ) ; } }\n#[allow(dead_code)]\nconst INF_U: u64 = 1_000_000_000_000_000;\n#[allow(dead_code)]\nconst INF_I: i64 = 1_000_000_000_000_000;\n#[allow(non_snake_case)]\n#[allow(dead_code)]\nfn main() {\n input! {\n n: usize,\n m: usize,\n r: i64,\n s: [i64; n],\n b: [i64; m]\n }\n let min_s = s.iter().min().unwrap();\n let max_b = b.iter().max().unwrap();\n if min_s >= max_b {\n println!(\"{}\", r);\n return;\n }\n let num = r / min_s;\n let mut ans = r - num * min_s;\n ans += num * max_b;\n //dbg!(num, min_s, max_b);\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "0fd90a4e646ddb9fec324d29d69fa955", "src_uid": "42f25d492bddc12d3d89d39315d63cb9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\nuse std::str::FromStr;\n\nfn main() {\n let n: usize = read();\n let m: usize = read();\n let r: usize = read();\n\n let s: Vec = (0..n).map(|_| read()).collect();\n let b: Vec = (0..m).map(|_| read()).collect();\n\n let mut min = s[0];\n for i in 1..n {\n min = std::cmp::min(min, s[i]);\n }\n let mut max = b[0];\n for i in 1..m {\n max = std::cmp::max(max, b[i]);\n }\n if min > max {\n println!(\"{}\", r);\n } else {\n let po = r / min;\n let nokori = r - po * min;\n println!(\"{}\", po * max + nokori);\n }\n}\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "089ed52c196c2aba164243d5f03460ed", "src_uid": "42f25d492bddc12d3d89d39315d63cb9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\ntype I = usize;\n\nfn main() {\n input!{\n n: usize,\n m: usize,\n r: usize,\n ss: [usize; n],\n bs: [usize; m],\n }\n let s: usize = *ss.iter().min().unwrap();\n let b: usize = *bs.iter().max().unwrap();\n if s > b {\n return println!(\"{}\", r);\n }\n let ans = r%s + r/s*b;\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "1a30f699e74c312d3454e2c86e2607b6", "src_uid": "42f25d492bddc12d3d89d39315d63cb9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! ----------------------------------------------\n//! Framework \n//!\n//! See the bottom of file for solution.\n//! ----------------------------------------------\n\n#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cell::RefCell;\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Display, Formatter, Write as FmtWrite};\nuse std::io::{stderr, stdin, BufRead, Write};\nuse std::mem::{replace, swap};\nuse std::ops::*;\nuse std::rc::Rc;\n\n/// Print values to standard error if debug mode.\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($e:expr),*) => {\n #[cfg(debug_assertions)]\n $({\n let (e, mut err) = (stringify!($e), stderr());\n writeln!(err, \"\\x1B[33m{}\\x1B[0m = {:?}\", e, $e).unwrap()\n })*\n };\n}\n\n/// Read from standard input and parse each word.\n/// - `read!(T, U, ..)` parses a line as a tuple of words.\n/// - `read![[T]]` parses a line as an array of words.\n/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n/// Read a line from standard input.\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n\n #[allow(deprecated)]\n buf.trim_right().to_owned()\n}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\nfn main() {\n let (_, _, r) = read!(usize, usize, i64);\n let S = read![[i64]];\n let B = read![[i64]];\n\n let min_s = *S.iter().min().unwrap();\n let max_b = *B.iter().max().unwrap();\n\n println!(\n \"{}\",\n if min_s >= max_b {\n r\n } else {\n (r % min_s) + (r / min_s) * max_b\n }\n )\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "766992099cc4e38ce6a59a11cc767db3", "src_uid": "42f25d492bddc12d3d89d39315d63cb9", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: isize = scan.next();\n let b: isize = scan.next();\n let c: isize = scan.next();\n let mut result: isize = std::isize::MAX;\n for i in 0..=100 {\n result = result.min((i-a).abs() + (i-b).abs() + (i-c).abs());\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "47c2e52151c41d3cb02fe3577cb65b10", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut friends: Vec = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|a| a.parse().unwrap())\n .collect()\n };\n\n friends.sort_unstable();\n println!(\"{}\", (friends[2] - friends[1]) + (friends[1] - friends[0]));\n}", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "5163cce2a48d858db80c8d2a0e76cb87", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/// All text input is handled through this macro\n#[macro_export]\nmacro_rules! read(\n () => { read!(\"{}\") };\n ($text:expr) => {{\n let value;\n scan!($text, value);\n value\n }};\n ($text:expr, $input:expr) => {{\n let value;\n scan!($input => $text, value);\n value\n }};\n);\n\n/// This macro allows to pass several variables so multiple values can be read\n#[macro_export]\nmacro_rules! scan(\n ($text:expr, $($arg:expr),*) => {\n scan!(::std::io::stdin().bytes().map(|c| c.unwrap()) => $text, $($arg),*) ;\n format_args!($text, $($arg),*);\n };\n ($input:expr => $text:expr, $($arg:expr),*) => {{\n use ::std::io::Read;\n use ::std::str::FromStr;\n // typesafe macros :)\n let text: &'static str = $text;\n let stdin: &mut Iterator = &mut ($input);\n\n let mut text = text.bytes();\n $(\n loop { match text.next() {\n Some(b'{') => match text.next() {\n Some(b'{') => assert_eq!(Some(b'{'), stdin.next()),\n Some(b'}') => {\n let s: Vec = match text.next() {\n Some(c) => stdin.take_while(|&ch| ch != c).collect(),\n None => stdin.take_while(|ch| !b\"\\t\\r\\n \".contains(ch)).collect(),\n };\n let s = match ::std::str::from_utf8(&s) {\n Ok(s) => s,\n Err(e) => {\n let n = e.valid_up_to();\n if n == 0 {\n panic!(\"input was not valid utf8: {:?}\", s);\n } else {\n panic!(\"input was only partially valid utf8: \\\"{}\\\" followed by {:?}\",\n ::std::str::from_utf8(&s[..n]).unwrap(), &s[n..]);\n }\n }\n };\n $arg = FromStr::from_str(s).expect(&format!(\"could not parse {} as target type of {}\", s, stringify!($arg)));\n break;\n }\n Some(_) => panic!(\"found bad curly brace\"),\n None => panic!(\"found single open curly brace at the end of the format string\"),\n },\n Some(c) => assert_eq!(Some(c), stdin.next()),\n None => panic!(\"Bad read! format string: did not contain {{}}\"),\n } }\n )*\n for c in text {\n assert_eq!(Some(c), stdin.next());\n }\n format_args!($text, $($arg),*);\n }};\n);\n\nmacro_rules! max {\n ($x:expr) => ( $x );\n ($x:expr, $($xs:expr),+) => {\n {\n use std::cmp::max;\n max($x, max!( $($xs),+ ))\n }\n };\n}\n\nmacro_rules! min {\n ($x:expr) => ( $x );\n ($x:expr, $($xs:expr),+) => {\n {\n use std::cmp::min;\n min($x, min!( $($xs),+ ))\n }\n };\n}\n\nfn main() {\n let (a, b, c) : (i32, i32, i32) = (read!(), read!(), read!());\n let x: i32 = min!(a, b, c);\n let z: i32 = max!(a, b, c);\n let y: i32 = a ^ b ^ c ^ x ^ z;\n\n println!(\"{}\", (x - y).abs() + (z - y).abs());\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "f4524cc0e4b92dd5a0f10afb257ec89e", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let line: String;\n let numbers: Vec;\n let (min, max): (i32, i32);\n let mut iterator = stdin.lock().lines();\n\n line = iterator.next().unwrap().unwrap();\n numbers = line\n .split_whitespace()\n .map(|n| n.parse().unwrap())\n .collect();\n \n match numbers.iter().min() {\n Some(number) => min = *number,\n None => min = 0,\n }\n match numbers.iter().max() {\n Some(number) => max = *number,\n None => max = 0,\n }\n\n println!(\"{}\", max-min);\n}", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "21e73ad045653133d0f988e69058b189", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s)\n .expect(\"failed to read l2\");\n\n let mut values = s\n .split_whitespace()\n .map(|x| x.parse::())\n .collect::, _>>()\n .unwrap();\n\n assert!(values.len() == 3);\n values.sort();\n\n println!(\"{}\", values[1]-values[0] + values[2]-values[1]);\n\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "cc49a00a4e9aa1ae6f997a4bb02161f1", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\n\nfn max(x: i32, y: i32, z: i32) -> i32{\n cmp::max(x, cmp::max(y, z))\n}\nfn min(x: i32, y: i32, z: i32) -> i32{\n cmp::min(x, cmp::min(y, z))\n}\n\nfn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.split_whitespace().map(|x| {x.parse::().unwrap()});\n \n let x = it.next().unwrap();\n let y = it.next().unwrap();\n let z = it.next().unwrap();\n\n println!(\"{}\", max(x, y, z) - min(x, y, z));\n}", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "a12e54ae3672b9a9f06e9cd5581b0522", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::cmp;\n\nfn main() {\n\tlet mut b = String::new();\n\tio::stdin().read_to_string(&mut b);\n\tlet mut inp = b.split_whitespace();\n\tlet x = inp.next().unwrap().parse::().unwrap();\n\tlet y = inp.next().unwrap().parse::().unwrap();\n\tlet z = inp.next().unwrap().parse::().unwrap();\n\tlet mut ans = 2_000_000_000;\n\tfor i in 0..105 {\n\t\tans = cmp::min(ans, (x-i).abs()+(y-i).abs()+(z-i).abs());\n\t}\n print!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "fb2ddec9b3c011bfacf84ab0b01e9817", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (a,b,c) = readln!(i32,i32,i32);\n let mx = std::cmp::max(a,std::cmp::max(b,c));\n let mn = std::cmp::min(a,std::cmp::min(b,c));\n println!(\"{}\",mx-mn);\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "b627e5b3e56b660d2f084b26f701541f", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_imports)]\nuse std::io::{self,Read};\n\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader : T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let mut y = input.i();\n loop {\n y += 1;\n let s = y.to_string().into_bytes();\n let l = s.len();\n if (0..l).all(|i| (i+1..l).all(|j| s[i] != s[j])) {\n break;\n }\n }\n println!(\"{}\", y);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "2e2a686862c1de0de521a12644b4d039", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\n\nfn main() {\n let mut text = String::new();\n std::io::stdin().read_line(&mut text).unwrap();\n let mut num = text.trim().parse::().unwrap();\n loop {\n num = num + 1;\n let mut digits = HashSet::new();\n let mut x = num;\n while x > 0 {\n digits.insert(x % 10);\n x = x / 10;\n }\n if digits.len() == 4 {\n println!(\"{}\", num);\n return;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "67b2c93de44f151ce2099ee33006d54d", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut year_1 = String::new();\n\tio::stdin().read_line(&mut year_1).unwrap();\n\tlet mut year_1: i32 = year_1.trim().parse().unwrap();\n\n\t'main: loop {\n\t\tyear_1 += 1;\n\t\tlet year_1 = year_1.to_string();\n\t\tlet mut uniq = String::new();\n\t\tfor num in year_1.chars() {\n\t\t\tif !uniq.contains(num) {\n\t\t\t\tuniq.push(num);\n\t\t\t} else {\n\t\t\t\tcontinue 'main;\n\t\t\t}\n\t\t}\n\t\tprintln!(\"{}\", year_1);\n\t\tbreak;\n\t}\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "b28b63449e0dc95b02a91b5b1a707a51", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::collections::{*};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n \nfn main() {\n let mut scanner = Scanner::default();\n let u: u64 = scanner.next();\n let mut v = u + 1;\n while v.to_string().chars().collect::>().len() != (v.to_string().chars().collect::>()).len(){\n \tv+=1;\n }\n print![\"{}\", v];\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "6f0b1bbd02b4b747c1dfa2717dcd66cf", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\nfn main() {\n let mut y: usize = read_line().parse().unwrap();\n\n loop {\n y += 1;\n let h: HashSet = y.to_string().chars().collect();\n if h.len() == 4 {\n println!(\"{}\", y);\n break;\n }\n\n }\n\n}\n\nfn read_line() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"\u041e\u0448\u0438\u0431\u043a\u0430 \u0447\u0442\u0435\u043d\u0438\u044f\");\n\n input.trim().to_string()\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "be9f08cafadb1f0b9f6bb7e18c0595e3", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nconst DECIMAL_RADIX : u64 = 10;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn little_endian_digits(n : u64, ds : &mut Vec) {\n let mut x = n;\n loop {\n let d = x % 10;\n x = x / 10;\n ds.push(d);\n if x == 0 {\n break;\n }\n }\n}\n\nfn big_endian_digits(n : u64, ds : &mut Vec) {\n little_endian_digits(n, ds);\n ds.reverse();\n}\n\nfn big_endian_digits_to_number(ds : &Vec) -> u64 {\n let mut x = 0;\n for d in ds {\n x = (x * 10) + d;\n }\n x\n}\n\nfn contains(y : u64, xs : &Vec) -> bool {\n for &x in xs {\n if y == x {\n return true;\n }\n }\n false\n}\n\nfn has_duplicates_in_prefix(digits : &Vec) -> bool {\n let mut copy_digits = digits.clone();\n // Pop the last digit, because we are only looking\n // for duplicates in prefix.\n copy_digits.pop();\n copy_digits.sort();\n for i in 1 .. copy_digits.len() {\n if copy_digits[i - 1] == copy_digits[i] {\n return true;\n }\n }\n false\n}\n\nfn find_replacement_digit(d : &Option, digits : &Vec) -> Option {\n if has_duplicates_in_prefix(digits) {\n return None;\n }\n let mut s = 0;\n match *d {\n None => (),\n Some(y) => {\n s = y + 1;\n },\n }\n for i in s .. DECIMAL_RADIX {\n if contains(i, digits) {\n // Do nothing ...\n } else {\n return Some(i);\n }\n }\n None\n}\n\nfn next_with_distinct_digits(n : u64) -> u64 {\n let mut b_e_digits = vec![];\n big_endian_digits(n, &mut b_e_digits);\n let orig_level = b_e_digits.len() - 1;\n let mut level = orig_level;\n let mut c_d_o = Some(b_e_digits[level]);\n loop {\n let r_d_o = find_replacement_digit(&c_d_o, &b_e_digits);\n match r_d_o {\n None => {\n b_e_digits.pop();\n level = level - 1;\n c_d_o = Some(b_e_digits[level]);\n },\n Some(r_d) => {\n b_e_digits[level] = r_d;\n if level < orig_level {\n b_e_digits.push(DECIMAL_RADIX);\n }\n level = level + 1;\n c_d_o = None;\n }\n }\n if level > orig_level {\n break;\n }\n }\n big_endian_digits_to_number(&b_e_digits)\n}\n\nfn main() {\n let stdin = io::stdin();\n let n = read_t(&stdin);\n println!(\"{}\", next_with_distinct_digits(n));\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "3fa70d7934eda4b16cb2c1c2c655acf8", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n line\n}\n\nfn valid(n: u32) -> bool {\n let ds = n.to_string().chars().collect::>();\n for i in 0..ds.len() {\n for j in i+1..ds.len() {\n if ds[i] == ds[j] {\n return false;\n }\n }\n }\n return true;\n}\n\nfn main() {\n let mut n = read_line().trim().parse::().unwrap() + 1;\n while !valid(n) {\n n += 1;\n }\n println!(\"{}\", n);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "cd83eb7924a18674ba6668e8ce5dc546", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\n\nfn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn read_int() -> T{\n read_str().parse::().ok().expect(\"Error\")\n}\n\nfn main() {\n let mut year: u16 = read_int();\n\n loop {\n year += 1;\n let hash: std::collections::HashSet = year.to_string().chars().collect();\n if hash.len() == 4 { println!(\"{}\", year); break; }\n }\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "9de8260ff3e2d53f992e49727d387471", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input_split() -> Vec {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let mut bags = input_split();\n bags.sort_unstable_by(|a, b| b.cmp(&a));\n\n let mut first_friend = 0;\n let mut second_friend = 0;\n\n for bag in bags {\n if first_friend < second_friend {\n first_friend += bag;\n } else {\n second_friend += bag;\n }\n }\n\n print!(\n \"{}\",\n if first_friend == second_friend {\n \"YES\"\n } else {\n \"NO\"\n }\n )\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "616dda1a9a2799532c786459d3f988ca", "src_uid": "5a623c49cf7effacfb58bc82f8eaff37", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Write;\n\npub struct Scanner {\n buffer: Vec\n}\n\nimpl Scanner {\n pub fn new() -> Scanner {\n Scanner { buffer: Vec::new() }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let stdout = std::io::stdout();\n let mut out = std::io::BufWriter::new(stdout.lock());\n let mut scan = Scanner::new();\n\n let mut a: Vec = Vec::with_capacity(4);\n for _ in 0..4 {\n a.push(scan.next());\n }\n a.sort();\n let s: i32 = a.iter().sum();\n if a[3] == a[0] + a[1] + a[2] ||\n 2*(a[3] + a[1]) == s ||\n 2*(a[3] + a[0]) == s {\n writeln!(out, \"YES\").unwrap();\n } else {\n writeln!(out, \"NO\").unwrap();\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "8eb82e3327545b94173a62fbdfe86bda", "src_uid": "5a623c49cf7effacfb58bc82f8eaff37", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(a,b,c,d = input.i());\n let mut ans = false;\n let mut f = |x: i32, y: i32| {\n if x == y {\n ans = true;\n }\n };\n f(a, b+c+d);\n f(b, a+c+d);\n f(c, a+b+d);\n f(d, a+b+c);\n f(a+b, c+d);\n f(a+c, b+d);\n f(a+d, b+c);\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "e9db41d09d73afd582e50f42b8388884", "src_uid": "5a623c49cf7effacfb58bc82f8eaff37", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n// _ _ _ _____ ___\n// _ __ ___ __ _ _ __ | |_ __ _/ / |___ / / _ \\\n// | '_ ` _ \\ / _` | '_ \\| __/ _` | | | |_ \\| | | |\n// | | | | | | (_| | | | | || (_| | | |___) | |_| |\n// |_| |_| |_|\\__,_|_| |_|\\__\\__,_|_|_|____/ \\___/\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n\nuse input::*;\n\nfn main() {\n let v = input_vector::();\n for mut i in 0..0x10 {\n let mut a = 0;\n let mut b = 0;\n let mut idx = 0;\n while idx!=4 {\n if i & 1 == 0 {\n a += v[idx];\n } else {\n b += v[idx];\n }\n i >>= 1;\n idx += 1;\n }\n if a == b {\n p(\"YES\");\n return;\n }\n }\n p(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "01d619657d9baf87f392915ff5bfef20", "src_uid": "5a623c49cf7effacfb58bc82f8eaff37", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io;\n use std::io::prelude::*;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let n: u32 = it.next().unwrap().parse().unwrap();\n let a: u32 = it.next().unwrap().parse().unwrap();\n let b: u32 = it.next().unwrap().parse().unwrap();\n\n let oa = a - 1;\n let ob = b - 1;\n\n let logn = 31 - n.leading_zeros();\n\n let mut flag = n >> 1;\n let mut i = 0;\n\n let xor = oa ^ ob;\n\n while flag & xor == 0 {\n i += 1;\n flag >>= 1;\n }\n\n if flag == n >> 1 {\n println!(\"Final!\");\n } else {\n println!(\"{}\", logn - i)\n }\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "f6f89ecd20053218546032d23fb9732b", "src_uid": "a753bfa7bde157e108f34a28240f441f", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn readstring() -> String {\n read_string_from_buffer(&io::stdin())\n}\n\nfn readint() -> i32 {\n read_int_from_buffer(&io::stdin())\n}\n\nfn read_string_from_buffer(buf: &io::Stdin) -> String {\n let mut input_text = String::new();\n buf.read_line(&mut input_text)\n .expect(\"failed to read from stdin\");\n input_text.trim_right().to_string()\n}\n\nfn read_int_from_buffer(buf: &io::Stdin) -> i32 {\n read_string_from_buffer(buf)\n .parse::()\n .expect(\"couldn't parse data to an integer\")\n}\n\nfn read_line_of_integers() -> Vec {\n readstring()\n .split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect()\n}\n\nfn read_line_of_longs() -> Vec {\n readstring()\n .split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect()\n}\n\nfn main() {\n let v = read_line_of_integers();\n let (n, a, b) = (v[0], v[1] - 1, v[2] - 1);\n\n let mut m = 1;\n let mut ans = 0;\n while a / m != b / m {\n m *= 2;\n ans += 1;\n }\n\n if m == n {\n println!(\"Final!\")\n } else {\n println!(\"{}\", ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "23c907adf13e2cbbefb0680a4f1f73be", "src_uid": "a753bfa7bde157e108f34a28240f441f", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\n\nfn exec() {\n let mut sc = Scanner::new();\n let n: usize = sc.ne();\n let mut a = [0, 1, 2];\n let m = n % 6;\n for k in 0..m {\n let tmp = a[1];\n if k & 1 == 0 {\n a[1] = a[0];\n a[0] = tmp;\n } else {\n a[1] = a[2];\n a[2] = tmp;\n }\n\n }\n let k: usize = sc.ne();\n println!(\"{}\", a[k]);\n}\n\nfn main() {\n const STACK: usize = 16 * 1024 * 1024;\n let _ = std::thread::Builder::new()\n .stack_size(STACK)\n .spawn(|| { exec(); })\n .unwrap()\n .join()\n .unwrap();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => {\n panic!(\"parse error, {:?}\",\n String::from_utf8(self.buf[l..r].to_owned()))\n }\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "01cebbcc3ae49ff08a3ac3d0e0cbfb9f", "src_uid": "7853e03d520cd71571a6079cdfc4c4b0", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let n: usize = get_line().trim().parse().unwrap();\n let x = get_line().trim().parse::().unwrap();\n\n // On a une permutation qui d\u00e9pend de n.\n // Premi\u00e8res valeurs :\n // 2 1 3\n // 2 3 1\n // 3 2 1\n // 3 1 2\n // 1 3 2\n // 1 2 3\n\n let perm = |i, n| {\n match i {\n 0 => (n + 1) % 6 / 2,\n 1 => match n % 3 {\n 0 => 1,\n 1 => 0,\n 2 => 2,\n _ => panic!(\"Something is WRONG.\"),\n },\n 2 => (n + 4) % 6 / 2,\n _ => panic!(\"Something is WRONG.\"),\n }\n };\n\n let ans = perm(x, n);\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "df48f5664286f4c4883c3c4e5dcbfd50", "src_uid": "7853e03d520cd71571a6079cdfc4c4b0", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn solve() {\n let n: i64 = get();\n let x: usize = get();\n let tbl = [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 1, 0], [2, 0, 1],\n [0, 2, 1], [0, 1, 2]];\n println!(\"{}\", tbl[(n % 6) as usize][x]);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "0105cce33312c7ecbdcf0d53d50534ad", "src_uid": "7853e03d520cd71571a6079cdfc4c4b0", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self};\nuse std::str::FromStr;\n\nfn main() {\n let n: u8 = (read_num() % 6) as u8;\n let mut x: u8 = read_num() as u8;\n\n for y in 0..n {\n // println!(\" step:{}, x:{}, is_div:{}\", n - y, x, (n - y) % 2 == 0);\n if (n - y) % 2 == 0 {\n // change central and right\n x = match x {\n 0 => 0,\n 1 => 2,\n 2 => 1,\n _ => 0,\n };\n } else {\n // change central and left\n x = match x {\n 0 => 1,\n 1 => 0,\n 2 => 2,\n _ => 0,\n };\n }\n }\n\n println!(\"{}\", x);\n}\n\nfn read_num() -> u32 {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"Error reading data!\");\n let n: u32 = FromStr::from_str(buffer.trim()).unwrap();\n n\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "78d29330befa320d1d85dd5afde42b36", "src_uid": "7853e03d520cd71571a6079cdfc4c4b0", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nuse std::io::Write;\r\nuse std::collections::*;\r\n\r\ntype Map = BTreeMap;\r\ntype Set = BTreeSet;\r\ntype Deque = VecDeque;\r\n\r\nfn calc(x: u64, y: u64) -> bool {\r\n let mut set = Set::new();\r\n let mut s = vec![];\r\n let mut x = x;\r\n while x > 0 {\r\n s.push(x % 2);\r\n x /= 2;\r\n }\r\n set.insert(s.clone());\r\n let fix = |s: &mut Vec| {\r\n while *s.last().unwrap() == 0 {\r\n s.pop();\r\n }\r\n };\r\n let mut dfs = vec![s];\r\n while let Some(s) = dfs.pop() {\r\n for &d in [0, 1].iter() {\r\n let mut s = s.clone();\r\n s.insert(0, d);\r\n s.reverse();\r\n fix(&mut s);\r\n if s.len() <= 60 && set.insert(s.clone()) {\r\n dfs.push(s);\r\n }\r\n }\r\n }\r\n let mut s = vec![];\r\n let mut y = y;\r\n while y > 0 {\r\n s.push(y % 2);\r\n y /= 2;\r\n }\r\n set.contains(&s)\r\n}\r\n\r\nfn run() {\r\n input!(x: u64, y: u64);\r\n if calc(x, y) {\r\n println!(\"YES\");\r\n } else {\r\n println!(\"NO\");\r\n }\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "b60bbf33615bb00feb62859e43747a12", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "//spnauti-rusT {{{\n#[allow(unused_imports)]use std::{io::*,collections::*,fmt::Debug,str::{self,*},cmp::*,ops::{self,*},iter::{self,*}};\nmacro_rules!l{\n\t($($v:ident),+:$t:ty=$e:expr)=>{$(let$v:$t=$e;)+};(mut $($v:ident),+ =$e:expr)=>{$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr)=>{$(let mut$v:$t=$e;)+};($($v:ident),+ =$e:expr)=>{$(let$v=$e;)+};}\nmacro_rules!v{\n\t($(:$t:ty)?=$e:expr)=>{$e$(as$t)?};([$d:expr]$(:$t:ty)?)=>{Vec::$(<$t>::)?with_capacity($d)};\n\t([]$(:$t:ty)?)=>{Vec::$(<$t>::)?new()};([$d:expr]$($s:tt)+)=>{vec![v!($($s)+);$d]};}\nfn rio()->(Reader,BufWriter){(Reader::new(),BufWriter::new(stdout()))}\nstruct Reader{buf:Vec,pos:usize,x:*mut Stdin,q:StdinLock<'static>}//'\n#[allow(dead_code)]impl Reader{\n\tfn new()->Self{let x=Box::into_raw(Box::new(stdin()));let q=unsafe{&*x}.lock();Self{x,q,buf:v!([]),pos:0}}\n\tfn next_line(&mut self)->bool{self.buf.clear();self.pos=0;self.q.read_until(b'\\n',&mut self.buf).unwrap_or(0)>0}\n\tfn byte(&mut self)->Option{\n\t\tif self.pos==self.buf.len(){if!self.next_line(){return None;}}self.pos+=1;Some(self.buf[self.pos-1])}\n\tfn vb(&mut self)->Vec{let mut s=v!([10]);let mut f=false;while let Some(c)=self.byte(){\n\t\tif!c.is_ascii_whitespace(){s.push(c);f=true;}else if f{break;}}s}\n\tfn p(&mut self)->T where T::Err:Debug{let w=self.vb();str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()}\n\tfn l(&mut self) -> i64 { self.p() }\n}impl Drop for Reader{fn drop(&mut self){unsafe{Box::from_raw(self.x)};}}\n//----------}}}\n\nfn main() {\n\tlet (mut rin,mut rout) = rio();\n\n\tl!(x,y = rin.l());\n\tif x == y {\n\t\twriteln!(rout, \"YES\").unwrap();\n\t\treturn;\n\t}\n\tlet mut x1 = x;\n\twhile x1 & 1 == 0 {\n\t\tx1 >>= 1;\n\t}\n\tlet ys = format!(\"{:b}\", y);\n\tfor &x in &[x*2+1, x1] {\n\t\tlet xs = format!(\"{:b}\", x);\n\t\tlet mut a = v!([2]);\n\t\ta.push(xs.chars().rev().collect());\n\t\ta.push(xs);\n\t\tfor xs in a {\n\t\t\tif ys.splitn(2, &xs).filter(|s| s.chars().all(|c| c == '1')).count() == 2 {\n\t\t\t\twriteln!(rout, \"YES\").unwrap();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\twriteln!(rout, \"NO\").unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "af3ef24f320228a9c1a35b36886ea18a", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::ops::Sub;\nuse std::ops::DivAssign;\nuse std::ops::SubAssign;\nuse std::marker::PhantomData;\nuse std::io::Write;\nuse std::ops::Mul;\nuse std::ops::Add;\nuse std::ops::Rem;\nuse std::ops::RemAssign;\nuse std::fmt::Display;\nuse std::io::Read;\nuse std::ops::Div;\nuse std::ops::AddAssign;\nuse std::ops::MulAssign;\n\n\npub trait Addable: Add + AddAssign + Copy {}\nimpl + AddAssign + Copy> Addable for T {}\n\npub trait AddSub: Addable + Sub + SubAssign {}\nimpl + SubAssign> AddSub for T {}\npub trait FromU8 {\n fn from_u8(val: u8) -> Self;\n}\n\nmacro_rules! from_u8_impl {\n ($t: ident) => {\n impl FromU8 for $t {\n fn from_u8(val: u8) -> Self {\n val as $t\n }\n }\n };\n}\n\nfrom_u8_impl!(i128);\nfrom_u8_impl!(i64);\nfrom_u8_impl!(i32);\nfrom_u8_impl!(i16);\nfrom_u8_impl!(i8);\nfrom_u8_impl!(isize);\nfrom_u8_impl!(u128);\nfrom_u8_impl!(u64);\nfrom_u8_impl!(u32);\nfrom_u8_impl!(u16);\nfrom_u8_impl!(u8);\nfrom_u8_impl!(usize);\nfrom_u8_impl!(f32);\nfrom_u8_impl!(f64);\n\npub trait Multable: Mul + MulAssign + Copy {}\nimpl + MulAssign + Copy> Multable for T {}\n\npub trait MulDiv: Multable + Div + DivAssign {}\nimpl + DivAssign> MulDiv for T {}\n\npub trait MulDivRem: MulDiv + Rem + RemAssign {}\nimpl + RemAssign> MulDivRem for T {}\npub trait IsSigned {\n const SIGNED: bool;\n}\n\npub trait Signed: IsSigned {}\n\npub trait Unsigned: IsSigned {}\n\nmacro_rules! unsigned_impl {\n ($t: ident) => {\n impl Unsigned for $t {}\n\n impl IsSigned for $t {\n const SIGNED: bool = false;\n }\n };\n}\n\nunsigned_impl!(u128);\nunsigned_impl!(u64);\nunsigned_impl!(u32);\nunsigned_impl!(u16);\nunsigned_impl!(u8);\nunsigned_impl!(usize);\n\nmacro_rules! signed_impl {\n ($t: ident) => {\n impl Signed for $t {}\n\n impl IsSigned for $t {\n const SIGNED: bool = true;\n }\n };\n}\n\nsigned_impl!(i128);\nsigned_impl!(i64);\nsigned_impl!(i32);\nsigned_impl!(i16);\nsigned_impl!(i8);\nsigned_impl!(isize);\nsigned_impl!(f64);\nsigned_impl!(f32);\npub trait ZeroOne {\n fn zero() -> Self;\n fn one() -> Self;\n}\n\nmacro_rules! zero_one_integer_impl {\n ($t: ident) => {\n impl ZeroOne for $t {\n fn zero() -> Self {\n 0\n }\n\n fn one() -> Self {\n 1\n }\n }\n };\n}\n\nzero_one_integer_impl!(i128);\nzero_one_integer_impl!(i64);\nzero_one_integer_impl!(i32);\nzero_one_integer_impl!(i16);\nzero_one_integer_impl!(i8);\nzero_one_integer_impl!(isize);\nzero_one_integer_impl!(u128);\nzero_one_integer_impl!(u64);\nzero_one_integer_impl!(u32);\nzero_one_integer_impl!(u16);\nzero_one_integer_impl!(u8);\nzero_one_integer_impl!(usize);\n\nmacro_rules! zero_one_float_impl {\n ($t: ident) => {\n impl ZeroOne for $t {\n fn zero() -> Self {\n 0.\n }\n\n fn one() -> Self {\n 1.\n }\n }\n };\n}\n\nzero_one_float_impl!(f32);\nzero_one_float_impl!(f64);\n\npub struct Input<'s> {\n input: &'s mut dyn Read,\n buf: Vec,\n at: usize,\n buf_read: usize,\n}\n\nimpl<'s> Input<'s> {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(input: &'s mut dyn Read) -> Self {\n Self {\n input,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn new_with_size(input: &'s mut dyn Read, buf_size: usize) -> Self {\n Self {\n input,\n buf: vec![0; buf_size],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn get(&mut self) -> Option {\n if self.refill_buffer() {\n let res = self.buf[self.at];\n self.at += 1;\n Some(res)\n } else {\n None\n }\n }\n\n pub fn peek(&mut self) -> Option {\n if self.refill_buffer() {\n Some(self.buf[self.at])\n } else {\n None\n }\n }\n\n pub fn skip_whitespace(&mut self) {\n while let Some(b) = self.peek() {\n if !char::from(b).is_whitespace() {\n return;\n }\n self.get();\n }\n }\n\n pub fn next_token(&mut self) -> Option> {\n self.skip_whitespace();\n let mut res = Vec::new();\n while let Some(c) = self.get() {\n if char::from(c).is_whitespace() {\n break;\n }\n res.push(c);\n }\n if res.is_empty() {\n None\n } else {\n Some(res)\n }\n }\n\n //noinspection RsSelfConvention\n pub fn is_exhausted(&mut self) -> bool {\n self.peek().is_none()\n }\n\n pub fn read(&mut self) -> T {\n T::read(self)\n }\n\n pub fn read_vec(&mut self, size: usize) -> Vec {\n let mut res = Vec::with_capacity(size);\n for _ in 0usize..size {\n res.push(self.read());\n }\n res\n }\n\n pub fn read_line(&mut self) -> String {\n let mut res = String::new();\n while let Some(c) = self.get() {\n if c == b'\\n' {\n break;\n }\n if c == b'\\r' {\n if self.peek() == Some(b'\\n') {\n self.get();\n }\n break;\n }\n res.push(c.into());\n }\n res\n }\n\n #[allow(clippy::should_implement_trait)]\n pub fn into_iter(self) -> InputIterator<'s, T> {\n InputIterator {\n input: self,\n phantom: Default::default(),\n }\n }\n\n fn read_integer(&mut self) -> T {\n self.skip_whitespace();\n let mut c = self.get().unwrap();\n let sgn = if c == b'-' {\n if !T::SIGNED {\n panic!(\"negative integer\")\n }\n c = self.get().unwrap();\n true\n } else if c == b'+' {\n c = self.get().unwrap();\n false\n } else {\n false\n };\n let mut res = T::zero();\n loop {\n if !char::from(c).is_digit(10) {\n panic!(\n \"expected integer, found {}{}{}\",\n if sgn { \"\" } else { \"-\" },\n res,\n char::from(c)\n );\n }\n res *= T::from_u8(10);\n res += T::from_u8(c - b'0');\n match self.get() {\n None => {\n break;\n }\n Some(ch) => {\n if char::from(ch).is_whitespace() {\n break;\n } else {\n c = ch;\n }\n }\n }\n }\n if sgn {\n debug_assert!(T::SIGNED);\n res = T::zero() - res\n }\n res\n }\n\n fn read_string(&mut self) -> String {\n match self.next_token() {\n None => {\n panic!(\"Input exhausted\");\n }\n Some(res) => unsafe { String::from_utf8_unchecked(res) },\n }\n }\n\n fn read_char(&mut self) -> char {\n self.skip_whitespace();\n self.get().unwrap().into()\n }\n\n fn read_float(&mut self) -> f64 {\n self.read_string().parse().unwrap()\n }\n\n fn refill_buffer(&mut self) -> bool {\n if self.at == self.buf_read {\n self.at = 0;\n self.buf_read = self.input.read(&mut self.buf).unwrap();\n self.buf_read != 0\n } else {\n true\n }\n }\n}\n\npub trait Readable {\n fn read(input: &mut Input) -> Self;\n}\n\nimpl Readable for String {\n fn read(input: &mut Input) -> Self {\n input.read_string()\n }\n}\n\nimpl Readable for char {\n fn read(input: &mut Input) -> Self {\n input.read_char()\n }\n}\n\nimpl Readable for f64 {\n fn read(input: &mut Input) -> Self {\n input.read_float()\n }\n}\n\nimpl Readable for Vec {\n fn read(input: &mut Input) -> Self {\n let size = input.read();\n input.read_vec(size)\n }\n}\n\npub struct InputIterator<'s, T: Readable> {\n input: Input<'s>,\n phantom: PhantomData,\n}\n\nimpl<'s, T: Readable> Iterator for InputIterator<'s, T> {\n type Item = T;\n\n fn next(&mut self) -> Option {\n self.input.skip_whitespace();\n self.input.peek().map(|_| self.input.read())\n }\n}\n\nmacro_rules! read_integer {\n ($t:ident) => {\n impl Readable for $t {\n fn read(input: &mut Input) -> Self {\n input.read_integer()\n }\n }\n };\n}\n\nread_integer!(i8);\nread_integer!(i16);\nread_integer!(i32);\nread_integer!(i64);\nread_integer!(i128);\nread_integer!(isize);\nread_integer!(u8);\nread_integer!(u16);\nread_integer!(u32);\nread_integer!(u64);\nread_integer!(u128);\nread_integer!(usize);\n\nmacro_rules! tuple_readable {\n ( $( $name:ident )+ ) => {\n impl<$($name: Readable), +> Readable for ($($name,)+) {\n fn read(input: &mut Input) -> Self {\n ($($name::read(input),)+)\n }\n }\n }\n}\n\ntuple_readable! {T}\ntuple_readable! {T U}\ntuple_readable! {T U V}\ntuple_readable! {T U V X}\ntuple_readable! {T U V X Y}\ntuple_readable! {T U V X Y Z}\ntuple_readable! {T U V X Y Z A}\ntuple_readable! {T U V X Y Z A B}\ntuple_readable! {T U V X Y Z A B C}\ntuple_readable! {T U V X Y Z A B C D}\ntuple_readable! {T U V X Y Z A B C D E}\ntuple_readable! {T U V X Y Z A B C D E F}\n\npub struct Output {\n output: Box,\n buf: Vec,\n at: usize,\n auto_flush: bool,\n}\n\nimpl Output {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: false,\n }\n }\n\n pub fn new_with_auto_flush(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: true,\n }\n }\n\n pub fn flush(&mut self) {\n if self.at != 0 {\n self.output.write_all(&self.buf[..self.at]).unwrap();\n self.at = 0;\n }\n }\n\n pub fn print(&mut self, s: &T) {\n s.write(self);\n }\n\n pub fn put(&mut self, b: u8) {\n self.buf[self.at] = b;\n self.at += 1;\n if self.at == self.buf.len() {\n self.flush();\n }\n }\n\n pub fn maybe_flush(&mut self) {\n if self.auto_flush {\n self.flush();\n }\n }\n\n pub fn print_per_line(&mut self, arg: &[T]) {\n for i in arg {\n i.write(self);\n self.put(b'\\n');\n }\n }\n\n pub fn print_iter>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n\n pub fn print_iter_ref<'a, T: 'a + Writable, I: Iterator>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n}\n\nimpl Write for Output {\n fn write(&mut self, buf: &[u8]) -> std::io::Result {\n let mut start = 0usize;\n let mut rem = buf.len();\n while rem > 0 {\n let len = (self.buf.len() - self.at).min(rem);\n self.buf[self.at..self.at + len].copy_from_slice(&buf[start..start + len]);\n self.at += len;\n if self.at == self.buf.len() {\n self.flush();\n }\n start += len;\n rem -= len;\n }\n if self.auto_flush {\n self.flush();\n }\n Ok(buf.len())\n }\n\n fn flush(&mut self) -> std::io::Result<()> {\n self.flush();\n Ok(())\n }\n}\n\npub trait Writable {\n fn write(&self, output: &mut Output);\n}\n\nimpl Writable for &str {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for String {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for char {\n fn write(&self, output: &mut Output) {\n output.put(*self as u8);\n }\n}\n\nimpl Writable for [T] {\n fn write(&self, output: &mut Output) {\n output.print_iter_ref(self.iter());\n }\n}\n\nimpl Writable for Vec {\n fn write(&self, output: &mut Output) {\n self[..].write(output);\n }\n}\n\nmacro_rules! write_to_string {\n ($t:ident) => {\n impl Writable for $t {\n fn write(&self, output: &mut Output) {\n self.to_string().write(output);\n }\n }\n };\n}\n\nwrite_to_string!(u8);\nwrite_to_string!(u16);\nwrite_to_string!(u32);\nwrite_to_string!(u64);\nwrite_to_string!(u128);\nwrite_to_string!(usize);\nwrite_to_string!(i8);\nwrite_to_string!(i16);\nwrite_to_string!(i32);\nwrite_to_string!(i64);\nwrite_to_string!(i128);\nwrite_to_string!(isize);\nwrite_to_string!(f32);\nwrite_to_string!(f64);\n\nimpl Writable for (T, U) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n }\n}\n\nimpl Writable for (T, U, V) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n output.put(b' ');\n self.2.write(output);\n }\n}\n\npub static mut OUTPUT: Option = None;\n\npub fn output() -> &'static mut Output {\n unsafe {\n match &mut OUTPUT {\n None => {\n panic!(\"Panic\");\n }\n Some(output) => output,\n }\n }\n}\n\n#[macro_export]\nmacro_rules! out {\n ($first: expr $(,$args:expr )*) => {\n output().print(&$first);\n $(output().put(b' ');\n output().print(&$args);\n )*\n }\n}\n\n#[macro_export]\nmacro_rules! out_line {\n ($first: expr $(, $args:expr )* ) => {\n out!($first $(,$args)*);\n output().put(b'\\n');\n };\n () => {\n output().put(b'\\n');\n };\n}\n\nfn solve(input: &mut Input, _test_case: usize) {\n let x: u64 = input.read();\n let y: u64 = input.read();\n\n let mut x_str = format!(\"{:b}\", x);\n let y_str = format!(\"{:b}\", y);\n\n if y % 2 == 0 && x != y {\n out_line!(\"NO\");\n return;\n }\n\n if y_str.contains(&x_str)\n && y.count_ones() - x.count_ones() == (y_str.len() - x_str.len()) as u32\n {\n out_line!(\"YES\");\n return;\n }\n if y_str.contains(&x_str.chars().rev().collect::())\n && y.count_ones() - x.count_ones() == (y_str.len() - x_str.len()) as u32\n {\n out_line!(\"YES\");\n return;\n }\n while x_str.ends_with(\"0\") {\n x_str.pop();\n }\n if y_str.contains(&x_str)\n && y.count_ones() - x.count_ones() == (y_str.len() - x_str.len()) as u32\n {\n out_line!(\"YES\");\n return;\n }\n if y_str.contains(&x_str.chars().rev().collect::())\n && y.count_ones() - x.count_ones() == (y_str.len() - x_str.len()) as u32\n {\n out_line!(\"YES\");\n return;\n }\n out_line!(\"NO\");\n}\n\npub(crate) fn run(mut input: Input) -> bool {\n solve(&mut input, 1);\n output().flush();\n input.skip_whitespace();\n !input.peek().is_some()\n}\n\nfn main() {\n let mut sin = std::io::stdin();\n let input = Input::new(&mut sin);\n unsafe {\n OUTPUT = Some(Output::new(Box::new(std::io::stdout())));\n }\n run(input);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "fb0199dcbdcc3365aadf5032d6b7e8ac", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// -------- begin template -------- \r\n \r\n#![allow(\r\n dead_code, unused_imports, unused_variables, \r\n unused_must_use, unused_macros, unused_mut, unused_assignments\r\n)]\r\n \r\nuse std::io::{self, Read, Write};\r\nuse std::cmp::{min, max};\r\nuse std::mem::swap;\r\nuse std::collections::{VecDeque, HashMap, HashSet, BTreeSet};\r\n \r\nmacro_rules! dbg {\r\n ($first_val:expr, $($val:expr),+ $(,)?) => {\r\n eprint!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n ($(eprint!(\", {} = {:?}\", stringify!($val), &$val)),+,);\r\n eprintln!();\r\n };\r\n ($first_val:expr) => {\r\n eprintln!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n };\r\n}\r\n \r\nenum InputSource {\r\n Stdin,\r\n FromFile(Vec),\r\n}\r\n \r\nstruct Scanner {\r\n buffer: Vec,\r\n input_source: InputSource,\r\n}\r\n \r\nimpl Scanner {\r\n fn new() -> Self {\r\n Self {\r\n buffer: vec![],\r\n input_source: InputSource::Stdin,\r\n }\r\n }\r\n \r\n fn new_file(filename: &str) -> Self {\r\n let file = std::fs::read_to_string(filename).unwrap();\r\n let mut lines: Vec = file.lines().map(|line| String::from(line)).collect();\r\n lines.reverse();\r\n Self {\r\n buffer: vec![],\r\n input_source: InputSource::FromFile(lines),\r\n }\r\n }\r\n \r\n fn usize(&mut self) -> usize { self.next::() }\r\n fn bytes(&mut self) -> Vec { self.next::().into_bytes() }\r\n fn chars(&mut self) -> Vec { self.next::().chars().collect() }\r\n fn string(&mut self) -> String { self.next::() }\r\n fn i64(&mut self) -> i64 { self.next::() }\r\n fn f64(&mut self) -> f64 { self.next::() }\r\n fn i32(&mut self) -> i32 { self.next::() }\r\n fn f32(&mut self) -> f32 { self.next::() }\r\n \r\n fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.next::()).collect()\r\n }\r\n \r\n fn parse_next_line(&mut self) -> bool {\r\n let mut input = String::new();\r\n match &mut self.input_source {\r\n InputSource::Stdin => {\r\n if std::io::stdin().read_line(&mut input).expect(\"Failed read\") == 0 {\r\n return false;\r\n }\r\n }\r\n InputSource::FromFile(lines) => match lines.pop() {\r\n Some(line) => input = line,\r\n None => return false,\r\n },\r\n }\r\n \r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n return true;\r\n }\r\n \r\n fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.parse_next_line();\r\n }\r\n }\r\n \r\n fn has_more_elements(&mut self) -> bool {\r\n loop {\r\n if !self.buffer.is_empty() { return true; }\r\n if !self.parse_next_line() { return false; }\r\n }\r\n }\r\n}\r\n \r\n// -------- end template -------- \r\n \r\nfn to2(x: i64) -> Vec {\r\n let mut res: Vec = Vec::new();\r\n let mut tmp = x;\r\n while tmp > 0 {\r\n res.push(tmp & 1);\r\n tmp >>= 1;\r\n }\r\n res.reverse();\r\n res\r\n}\r\n\r\nfn to10(d: &Vec) -> i64 {\r\n if d.len() > 60 {\r\n return 0;\r\n }\r\n let (mut exp, mut res) = (1, 0);\r\n for i in (0..d.len()).rev() {\r\n if d[i] == 1 {\r\n res += exp;\r\n }\r\n exp *= 2;\r\n }\r\n res\r\n}\r\n\r\nfn go(x: i64, d: i64) -> i64 {\r\n let mut a = to2(x);\r\n a.push(d);\r\n a.reverse();\r\n to10(&a)\r\n}\r\n\r\nfn solve(x: i64, y: i64) -> bool {\r\n let mut q: VecDeque = VecDeque::new();\r\n let mut vis: HashSet = HashSet::new();\r\n q.push_back(x);\r\n while let Some(cur) = q.pop_front() {\r\n if cur == 0 { continue; }\r\n if vis.contains(&cur) { continue; }\r\n vis.insert(cur);\r\n if cur == y { return true; }\r\n\r\n q.push_back(go(cur, 0));\r\n q.push_back(go(cur, 1));\r\n }\r\n false\r\n} \r\n\r\nfn main() {\r\n let stdout = io::stdout();\r\n let mut out = std::io::BufWriter::new(stdout.lock());\r\n let mut sc = Scanner::new();\r\n\r\n \r\n let (x, y) = (sc.i64(), sc.i64());\r\n writeln!(out, \"{}\", if solve(x, y) { \"YES\" } else { \"NO \"});\r\n}\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n \r\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "46e457486016eebca349f1cbd1a74ad6", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\nuse std::{io, io::prelude::*, str};\n\nstruct IO<'a> {\n reader: io::StdinLock<'a>,\n buffer: Vec,\n out: io::BufWriter,\n}\nimpl<'a> IO<'a> {\n fn new(reader: io::StdinLock<'a>, stdout: io::Stdout) -> Self {\n Self {\n reader,\n buffer: vec![],\n out: io::BufWriter::new(stdout),\n }\n }\n\n fn read(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n #[allow(dead_code)]\n fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n\n #[allow(dead_code)]\n fn read_str(&mut self) -> Vec {\n self.read::().into_bytes()\n }\n}\n\nfn to_bits(mut x: u64) -> Vec {\n let mut res = vec![];\n while x > 0 {\n res.push(if x & 1 > 0 { true } else { false });\n x >>= 1;\n }\n res.reverse();\n res\n}\n\n// 10100\n// 1001011111\n// 1001011111\n\nfn all_ones(a: &[bool]) -> bool {\n a.iter().all(|&x| x)\n}\n\nfn contains(src: &[bool], a: &[bool]) -> bool {\n let n = src.len();\n let m = a.len();\n if m > n {\n return false;\n }\n\n for i in 0..=(n - m) {\n if &src[i..i + m] == a && all_ones(&src[0..i]) && all_ones(&src[i + m..]) {\n return true;\n }\n }\n\n false\n}\n\nfn main() -> io::Result<()> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut io = IO::new(stdin.lock(), stdout);\n\n let (x, y): (u64, u64) = (io.read(), io.read());\n let mut x = to_bits(x);\n let y = to_bits(y);\n\n let mut ok = x == y;\n if !ok {\n x.push(true);\n ok = contains(&y, &x) || contains(&y, &x.iter().cloned().rev().collect::>());\n x.pop();\n }\n if !ok {\n while !*x.last().unwrap() {\n x.pop();\n }\n ok = contains(&y, &x) || contains(&y, &x.iter().cloned().rev().collect::>());\n }\n\n if ok {\n writeln!(io.out, \"YES\")?;\n } else {\n writeln!(io.out, \"NO\")?;\n }\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "1c1f6309afb5e0b39c31dc1cbb59ca9a", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn read_line() -> String {\r\n let mut line = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line\r\n}\r\n\r\nfn read_vec() -> Vec {\r\n read_line()\r\n .trim()\r\n .split_whitespace()\r\n .filter_map(|i| i.parse().ok())\r\n .collect()\r\n}\r\n\r\nfn bitrev(mut x: u64) -> u64 {\r\n let mut y = 0u64;\r\n while x > 0 {\r\n y <<= 1;\r\n y |= x & 1;\r\n x >>= 1;\r\n }\r\n y\r\n}\r\n\r\nfn check(x: u64, mut y: u64) -> bool {\r\n let mut m = 0;\r\n while x & ((1 << m) - 1) < x {\r\n m += 1\r\n }\r\n while y > 0 {\r\n if y & ((1 << m) - 1) == x {\r\n y >>= m;\r\n return y & (y + 1) == 0;\r\n } else if y & 1 == 0 {\r\n return false;\r\n } else {\r\n y >>= 1;\r\n }\r\n }\r\n false\r\n}\r\n\r\nfn main() {\r\n let xy = read_vec::();\r\n let (x, y) = (xy[0], xy[1]);\r\n let mut xx = x;\r\n while xx & 1 == 0 {\r\n xx >>= 1\r\n }\r\n if x == y\r\n || check(xx, y)\r\n || check(bitrev(xx), y)\r\n || check(x * 2 + 1, y)\r\n || check(bitrev(x * 2 + 1), y)\r\n {\r\n println!(\"YES\")\r\n } else {\r\n println!(\"NO\")\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "6f1767576a3c02eddf9de19339d60b1d", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_imports)]\n#[rustfmt::skip] mod num {use std::convert::{TryFrom, TryInto};use std::ops::{Add, Div, Mul, Rem, Sub};pub trait Num: Ord + Add + Sub + Mul + Div + Rem + FromPrimitive + IntoPrimitive + Sized { fn zero() -> Self;fn one() -> Self;} pub trait FromPrimitive: Sized { fn from_u64(x: u64) -> Option;fn from_i64(x: i64) -> Option;fn from_usize(x: usize) -> Option { Self::from_u64(x as u64) } fn from_isize(x: isize) -> Option { Self::from_i64(x as i64) } } pub trait IntoPrimitive { fn as_u64(&self) -> Option;fn as_i64(&self) -> Option;fn as_usize(&self) -> Option { self.as_u64().and_then(|x| x.try_into().ok()) } fn as_isize(&self) -> Option { self.as_i64().and_then(|x| x.try_into().ok()) } } pub trait Integer: Num { fn idiv(&self, x: &Self) -> Self;fn imod(&self, x: &Self) -> Self;fn iabs(&self) -> Self;} macro_rules! generate_integer_impl_for_primitive { ($( ($ty:ty, $unsigned:tt) ),+) => { $( impl FromPrimitive for $ty { #[inline(always)] fn from_u64(x: u64) -> Option { <$ty>::try_from(x).ok() } #[inline(always)] fn from_i64(x: i64) -> Option { <$ty>::try_from(x).ok() } } impl IntoPrimitive for $ty { #[inline(always)] fn as_u64(&self) -> Option { u64::try_from(*self).ok() } #[inline(always)] fn as_i64(&self) -> Option { i64::try_from(*self).ok() } } impl Num for $ty { #[inline(always)] fn zero() -> Self { 0 } #[inline(always)] fn one() -> Self { 1 } } impl Integer for $ty { #[inline(always)] fn idiv(&self, x: &Self) -> Self { self.div_euclid(*x) } #[inline(always)] fn imod(&self, x: &Self) -> Self { self.rem_euclid(*x) } generate_iabs_impl!($unsigned);} )+ };} macro_rules! generate_iabs_impl { (true) => { #[inline(always)] fn iabs(&self) -> Self { *self } };(false) => { #[inline(always)] fn iabs(&self) -> Self { self.abs() } };} generate_integer_impl_for_primitive!( (u8, true), (u16, true), (u32, true), (u64, true), (u128, true), (usize, true), (i8, false), (i16, false), (i32, false), (i64, false), (i128, false), (isize, false) );}\n#[rustfmt::skip] mod combinatorics {use crate::{num::Integer, number_theory::mod_mulinv};pub fn next_permutation(perm: &mut [T]) -> bool where T: Ord, { if perm.is_empty() { return false;} let i = match Iterator::zip(perm.iter(), perm[1..].iter()).rposition(|(x, y)| x < y) { None => { perm.reverse();return false;} Some(x) => x, };let j = perm .iter() .rposition(|x| &perm[i] < x) .expect(\"inconsistent Ord implementation\");perm.swap(i, j);perm[i + 1..].reverse();true } #[derive(Debug, Clone)] pub struct Factorials { m: N, fact: Vec, fact_inv: Vec, } impl Factorials where N: Integer + Clone, { #[inline] fn as_n(x: usize) -> N { N::from_usize(x).expect(\"inconsistent Integer implementation\") } #[inline] fn as_usize(x: &N) -> usize { N::as_usize(x).expect(\"inconsistent Integer implementation\") } #[track_caller] pub fn new(n: N, m: N) -> Self { let cap = n .as_usize() .and_then(|x| x.checked_add(1)) .expect(\"required capacity overflowed usize\");assert!(cap > 0, \"n must be non-negative\");let mut fact = Vec::with_capacity(cap);fact.push(N::one());let mut cur = N::one();for i in 1..cap { cur = (cur * Self::as_n(i)).imod(&m);fact.push(cur.clone());} let mut fact_inv = Vec::with_capacity(cap);let mut cur = mod_mulinv(fact[cap - 1].clone(), m.clone());for i in (0..cap).rev() { fact_inv.push(cur.clone());cur = (cur * Self::as_n(i)).imod(&m);} fact_inv.reverse();debug_assert_eq!(fact.len(), cap);debug_assert_eq!(fact_inv.len(), cap);Factorials { m, fact, fact_inv } } pub fn len(&self) -> usize { self.fact.len() } pub fn is_empty(&self) -> bool { false } pub fn n(&self) -> N { Self::as_n(self.fact.len() - 1) } #[track_caller] fn verify_n<'a>(&self, n: &'a N) -> &'a N { assert!( N::zero() <= *n && *n <= self.n(), \"n is outside precomputed range\" );n } #[track_caller] pub fn factorial(&self, n: &N) -> N { let n = self.verify_n(n);self.fact[Self::as_usize(n)].clone() } #[track_caller] pub fn factorial_inverse(&self, n: &N) -> N { let n = self.verify_n(n);self.fact_inv[Self::as_usize(n)].clone() } #[track_caller] pub fn choose(&self, n: N, k: N) -> N { self.verify_n(&n);assert!(k >= N::zero(), \"k is negative\");if k <= n { ((self.fact[Self::as_usize(&n)].clone() * self.fact_inv[Self::as_usize(&k)].clone()) .imod(&self.m) * self.fact_inv[Self::as_usize(&(n - k))].clone()) .imod(&self.m) } else { N::zero() } } } }\n#[rustfmt::skip] mod util { pub trait IntoVec { fn into_vec(self) -> Vec;} #[non_exhaustive] pub struct Owned;impl IntoVec for I where I: Iterator, { fn into_vec(self) -> Vec { self.collect() } } #[non_exhaustive] pub struct Reference;impl<'a, I, T> IntoVec for I where I: Iterator, T: Clone + 'a, { fn into_vec(self) -> Vec { self.cloned().collect() } } pub trait Argmax { fn argmax(self) -> Option;} impl Argmax for I where I: Iterator, I::Item: Ord, { fn argmax(self) -> Option { self.fold((0, None), |(i, mx), next| { if let Some((mx_i, mx_v)) = mx { if next.gt(&mx_v) { (i + 1, Some((i, next))) } else { (i + 1, Some((mx_i, mx_v))) } } else { (i + 1, Some((i, next))) } }) .1 .map(|x| x.0) } } pub trait Sorted { fn sorted(self) -> Self;} impl Sorted for Vec where T: Ord, { fn sorted(mut self) -> Self { self.sort();self } } pub trait Choose { fn choose(self, a: T, b: T) -> T;fn choose_by(self, a: impl FnOnce() -> T, b: impl FnOnce() -> T) -> T;} impl Choose for bool { fn choose(self, a: T, b: T) -> T { if self { a } else { b } } fn choose_by(self, a: impl FnOnce() -> T, b: impl FnOnce() -> T) -> T { if self { a() } else { b() } } } #[macro_export] macro_rules! p { ( $( $x:expr ),* ) => { #[cfg(any(debug_assertions, debug_print))] { dbg!( $( & $x, )* );} };} pub fn fix(f: &dyn Fn(&dyn Fn(A) -> R, A) -> R) -> impl Fn(A) -> R + '_ { move |arg| f(&fix(&f), arg) } }\n#[rustfmt::skip] mod scanner {use std::fmt::Debug;use std::io::{stdin, BufReader, Bytes, Error as IoError, Read, Stdin};use std::str::{self, FromStr, Utf8Error};#[derive(Debug)] pub struct Scanner { bytes: Bytes>, buf: Vec, } #[derive(Debug)] pub enum ScanError { Io(IoError), Parse(T::Err, String), NonUtf8(Utf8Error, Vec), } impl Scanner { pub fn stdin() -> Self { Self::new(stdin()) } } impl Scanner { pub fn new(reader: R) -> Self { Self { bytes: BufReader::new(reader).bytes(), buf: Vec::new(), } } pub fn read(&mut self) -> Result> { debug_assert!(self.buf.is_empty());for b in &mut self.bytes { let b = b.map_err(ScanError::Io)?;if b.is_ascii_whitespace() { if self.buf.is_empty() { continue;} else { break;} } else { self.buf.push(b);} } match str::from_utf8(&self.buf) { Err(err) => Err(ScanError::NonUtf8(err, std::mem::take(&mut self.buf))), Ok(s) => { let ret = s.parse().map_err(|err| ScanError::Parse(err, s.to_owned()));self.buf.clear();ret } } } } #[macro_use] pub mod macros { use super::*;use std::fmt::{self, Debug};use std::io::Read;use std::marker::PhantomData;use std::num::NonZeroUsize;use std::str::FromStr;pub trait ScanCmd { type Target;type Err;fn scan_from(scanner: &mut Scanner) -> Result;} pub struct UsizeM1(());impl ScanCmd for UsizeM1 { type Target = usize;type Err = ScanError;fn scan_from(scanner: &mut Scanner) -> Result { Ok(scanner.read::()?.get() - 1) } } pub struct LenArray(PhantomData);impl ScanCmd for LenArray { type Target = Vec;type Err = LenArrayScanError;fn scan_from(scanner: &mut Scanner) -> Result { let len = scanner.read::().map_err(LenArrayScanError::Len)?;let mut arr = Vec::with_capacity(len);for i in 0..len { let elem = scanner .read::() .map_err(|e| LenArrayScanError::Data(i, e))?;arr.push(elem);} Ok(arr) } } pub enum LenArrayScanError { Len(ScanError), Data(usize, ScanError), } impl Debug for LenArrayScanError where T: Debug + FromStr, T::Err: Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::LenArrayScanError::*;match self { Len(e) => f.debug_tuple(\"Len\").field(e).finish(), Data(i, e) => f.debug_tuple(\"Data\").field(i).field(e).finish(), } } } #[macro_export] macro_rules! scan { (@scan 1 $scan:expr, $type:ty) => { $scan .read::<$type>() .expect(concat!(\"failed to read token of type \", stringify!($type))) };(@scan 2 $scan:expr, $type:ty, $n:expr) => { (0..$n) .map(|_| scan!(@scan 1 $scan, $type)) .collect::>() };(@scan 3 $scan:expr, $type:ty) => { <$type as ScanCmd>::scan_from(&mut $scan) .expect(concat!(\"failed to read token of type \", stringify!($type))) };(@scan 4 $scan:expr, $type:ty, $n:expr) => { (0..$n) .map(|_| scan!(@scan 3 $scan, $type)) .collect::>() };(@accum ($scan:expr) () -> ($($body:tt)*)) => { ($($body)*) };(@accum ($scan:expr) ($type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 1 $scan, $type))) };(@accum ($scan:expr) ($type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 1 $scan, $type),)) };(@accum ($scan:expr) ($n:tt * $type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 2 $scan, $type, $n))) };(@accum ($scan:expr) ($n:tt * $type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 2 $scan, $type, $n),)) };(@accum ($scan:expr) (~$type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 3 $scan, $type))) };(@accum ($scan:expr) (~$type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 3 $scan, $type),)) };(@accum ($scan:expr) ($n:tt * ~$type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 4 $scan, $type, $n))) };(@accum ($scan:expr) ($n:tt * ~$type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 4 $scan, $type, $n),)) };($scan:expr, $($arg:tt)+) => { scan!(@accum ($scan) ($($arg)+) -> ()) };} } }\n#[rustfmt::skip] mod number_theory {use crate::num::Integer;use std::mem;pub fn gcd(mut a: N, mut b: N) -> N { while b != N::zero() { mem::swap(&mut a, &mut b);b = b.imod(&a);} a.iabs() } #[allow(clippy::many_single_char_names)] pub fn egcd(a: N, b: N) -> (N, N, N) { if b == N::zero() { ( a.iabs(), if a >= N::zero() { N::one() } else { N::zero() - N::one() }, N::zero(), ) } else { let (g, s, t) = egcd(b.clone(), a.imod(&b));(g, t.clone(), s - a.idiv(&b) * t) } } #[track_caller] pub fn mod_exp(a: N, mut b: N, m: N) -> N { let zero = N::zero();let one = N::one();let two = N::one() + N::one();assert!(m > zero, \"modulus must be positive\");if b < zero { return mod_exp(mod_mulinv(a, m.clone()), zero - b, m);} let mut x = N::one();let mut pwr = a;while b > N::zero() { if b.imod(&two) == one { x = (x * pwr.clone()).imod(&m);} pwr = (pwr.clone() * pwr).imod(&m);b = b.idiv(&two);} x } #[track_caller] pub fn mod_mulinv(a: N, m: N) -> N { let zero = N::zero();let one = N::one();assert!(m > zero, \"modulus must be positive\");let (g, s, _) = egcd(a, m.clone());assert!(g == one, \"multiplicative inverse does not exist\");s.imod(&m) } #[derive(Debug, Clone)] pub struct PrimeSieve { lowest_factor: Vec, primes: Vec, } impl PrimeSieve where N: Integer + Clone, { #[inline] fn as_n(x: usize) -> N { N::from_usize(x).expect(\"inconsistent Integer implementation\") } #[inline] fn as_usize(x: &N) -> usize { N::as_usize(x).expect(\"inconsistent Integer implementation\") } #[track_caller] pub fn new(n: N) -> Self { let cap = n .as_usize() .and_then(|x| x.checked_add(1)) .expect(\"capacity overflowed usize\");assert!(cap > 0, \"n must be non-negative\");let mut lowest_factor = vec![N::zero(); cap];let mut primes = vec![];for i in 2..cap { if lowest_factor[i] == N::zero() { lowest_factor[i] = Self::as_n(i);primes.push(Self::as_n(i));} let lowest_factor_i = lowest_factor[i].clone();for (p, p_usize) in primes .iter() .map(|p| (p, Self::as_usize(p))) .take_while(|(p, p_usize)| i * p_usize < cap && p <= &&lowest_factor_i) { lowest_factor[i * p_usize] = p.clone();} } PrimeSieve { lowest_factor, primes, } } pub fn len(&self) -> usize { self.lowest_factor.len() } pub fn is_empty(&self) -> bool { false } pub fn n(&self) -> N { Self::as_n(self.lowest_factor.len() - 1) } #[track_caller] pub fn is_prime(&self, x: &N) -> bool { assert!(*x >= N::zero(), \"x must be non-negative\");let n = self.n();if *x <= n { *x > N::zero() && self.lowest_factor[Self::as_usize(x)] == *x } else if *x <= n.clone() * n { for p in self.primes.iter() { if x.imod(p) == N::zero() { return false;} } true } else { panic!(\"unable to determine primality: x > n^2\");} } #[track_caller] pub fn lowest_factor(&self, x: &N) -> N { assert!(*x >= N::zero(), \"x must be non-negative\");let n = self.n();if *x <= n { self.lowest_factor[Self::as_usize(x)].clone() } else if *x <= n.clone() * n { for p in self .primes .iter() .take_while(|&p| p.clone() * p.clone() <= *x) { if x.imod(p) == N::zero() { return p.clone();} } x.clone() } else { panic!(\"unable to determine lowest factor: x > n^2\",) } } #[track_caller] pub fn factorize(&self, mut x: N) -> Vec { let n = self.n();assert!(x > N::zero(), \"cannot factorize non-positive numbers\");assert!(x <= n.clone() * n.clone(), \"unable to factorize: x > n^2\",);let mut factors = Vec::new();let x2 = x.clone();let mut primes = self .primes .iter() .take_while(|&p| p.clone() * p.clone() <= x2);while x > N::one() { if x <= n { let f = &self.lowest_factor[Self::as_usize(&x)];factors.push(f.clone());x = x.idiv(f);} else if let Some(p) = primes.next() { while x.imod(p) == N::zero() { factors.push(p.clone());x = x.idiv(p);} } else { factors.push(x);break;} } factors } } }\n#[rustfmt::skip] mod writer {use std::fmt::Display;use std::io::{stdout, BufWriter, Error as IoError, Stdout, Write};#[derive(Debug)] pub struct Writer { writer: BufWriter, } #[derive(Debug, Clone)] pub struct Format<'a> { separator: &'a str, ending: &'a str, } impl<'a> Format<'a> { pub fn separator(self, separator: &'a str) -> Self { Self { separator, ..self } } pub fn ending(self, ending: &'a str) -> Self { Self { ending, ..self } } } impl Default for Format<'_> { fn default() -> Self { Format { separator: \" \", ending: \"\\n\", } } } impl Writer { pub fn stdout() -> Self { Self::new(stdout()) } } impl Writer { pub fn new(writer: W) -> Self { Self { writer: BufWriter::new(writer), } } pub fn write>(&mut self, val: T) -> Result<(), IoError> { self.write_with(val, &Format::default()) } pub fn write_with>(&mut self, val: T, fmt: &Format) -> Result<(), IoError> { val.write_to(&mut self.writer, fmt) } pub fn flush(&mut self) -> Result<(), IoError> { self.writer.flush() } } pub trait Writable { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError>;} #[non_exhaustive] pub struct Single;impl Writable for T { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError> { write!(w, \"{}{}\", self, fmt.ending) } } #[non_exhaustive] pub struct Many;impl Writable for I where I: Iterator, I::Item: Display, { fn write_to(mut self, w: &mut W, fmt: &Format) -> Result<(), IoError> { if let Some(x) = self.next() { write!(w, \"{}\", x)?;} else { return Ok(());} for x in self { write!(w, \"{}{}\", fmt.separator, x)?;} write!(w, \"{}\", fmt.ending) } } #[non_exhaustive] pub struct Slice;impl Writable for &[T] { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError> { self.iter().write_to(w, fmt) } } #[macro_export] macro_rules! out { ($writer:expr, $val:expr) => { $writer.write($val).expect(\"failed to write token\");};($writer:expr, $val:expr, $($builder_name:ident = $value:expr),+) => { let mut fmt = Format::default();$( fmt = fmt.$builder_name($value);)+ $writer.write_with($val, &fmt).expect(\"failed to write token\");};} }\n#[rustfmt::skip] mod prefix_sum {use std::{ fmt::{self, Debug, Formatter}, marker::PhantomData, ops::{Add, Bound, Range, RangeBounds, Sub}, };#[derive(Clone)] pub struct PrefixOp { fwd: F, inv: Option, marker: PhantomData T>, } impl PrefixOp where F: Fn(&T, &T) -> T, { pub fn new(op: F) -> Self { PrefixOp { fwd: op, inv: None, marker: PhantomData, } } } impl PrefixOp where F: Fn(&T, &T) -> T, I: Fn(&T, &T) -> T, { pub fn new_invertible(op: F, inverse: I) -> Self { PrefixOp { fwd: op, inv: Some(inverse), marker: PhantomData, } } } impl PrefixOp where F: Fn(&T, &T) -> T, I: Clone, { pub fn build(&self, mut arr: Vec) -> PrefixArray { for i in 1..arr.len() { arr[i] = (self.fwd)(&arr[i - 1], &arr[i]);} PrefixArray { pref: arr, fwd: PhantomData, inv: self.inv.clone(), } } } #[derive(Clone)] pub struct PrefixArray { pref: Vec, fwd: PhantomData, inv: Option, } impl PrefixArray { pub fn len(&self) -> usize { self.pref.len() } pub fn is_empty(&self) -> bool { self.pref.is_empty() } #[track_caller] fn verify_range_bounds(&self, range: impl RangeBounds) -> Range { let start = match range.start_bound() { Bound::Unbounded => 0, Bound::Included(&x) => x, Bound::Excluded(&x) => x + 1, };let end = match range.end_bound() { Bound::Unbounded => self.len(), Bound::Included(&x) => x + 1, Bound::Excluded(&x) => x, };assert!( start < end, \"range inverted: start >= end ({} >= {})\", start, end );assert!( end <= self.len(), \"range out of bounds: end > len ({} > {})\", end, self.len() );Range { start, end } } #[track_caller] pub fn query_prefix(&self, range: impl RangeBounds) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);assert!(start == 0, \"query start bound is non-zero: {} > 0\", start);self.pref[end - 1].clone() } } impl PrefixArray where I: Fn(&T, &T) -> T, { #[track_caller] pub fn query(&self, range: impl RangeBounds) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);if start == 0 { self.pref[end - 1].clone() } else { (self .inv .as_ref() .expect(\"range query is not supported on non-invertible operation\"))( &self.pref[end - 1], &self.pref[start - 1], ) } } } impl Debug for PrefixOp where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct(\"PrefixOp\").finish_non_exhaustive() } } impl Debug for PrefixArray where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct(\"PrefixArray\") .field(\"pref\", &self.pref) .finish_non_exhaustive() } } type NextFn = fn(&T, &T) -> T;pub struct PrefixSum(PhantomData);impl PrefixSum where T: Add + Sub + Clone, { pub fn op() -> PrefixOp, NextFn> { PrefixOp::new_invertible(|a, b| a.clone() + b.clone(), |b, a| b.clone() - a.clone()) } pub fn build(arr: Vec) -> PrefixArray, NextFn> { Self::op().build(arr) } } }\n#[rustfmt::skip] mod rng {use std::ops::{Bound, RangeBounds};#[derive(Debug, Clone)] pub struct Rng { state: u64, } impl Rng { pub fn new(seed: u64) -> Rng { assert!(seed > 0, \"xorshift generator cannot be seeded with 0\");Rng { state: seed } } const RDSEED_ITER_LIMIT: i64 = 50_000;#[cfg(target_arch = \"x86_64\")] pub fn hardware() -> Rng { use std::arch::x86_64::_rdseed64_step;unsafe fn rdseed64(limit: i64) -> u64 { let mut seed = 0;let mut iters = 0;while _rdseed64_step(&mut seed) != 1 { iters += 1;assert!( iters <= limit, \"rdseed iteration limit ({}) exceeded, something has gone very wrong\", limit );} seed } assert!(is_x86_feature_detected!(\"rdseed\"), \"rdseed not supported\");unsafe { Rng::new(rdseed64(Self::RDSEED_ITER_LIMIT)) } } #[cfg(target_arch = \"x86\")] pub fn hardware() -> Rng { use std::arch::x86::_rdseed32_step;unsafe fn rdseed32(limit: i64) -> u32 { let mut seed = 0;let mut iters = 0;while _rdseed32_step(&mut seed) != 1 { iters += 1;assert!( iters <= limit, \"rdseed iteration limit ({}) exceeded, something has gone very wrong\", limit );} seed } assert!(is_x86_feature_detected!(\"rdseed\"), \"rdseed not supported\");unsafe { Rng::new( (rdseed32(Self::RDSEED_ITER_LIMIT) as u64) << 32 | rdseed32(Self::RDSEED_ITER_LIMIT) as u64, ) } } #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> u64 { self.state ^= self.state >> 12;self.state ^= self.state << 25;self.state ^= self.state >> 27;self.state.wrapping_mul(0x2545f4914f6cdd1d) } pub fn gen(&mut self) -> T where T: Generatable, { self.gen_dist(&Standard::default()) } pub fn gen_dist(&mut self, dist: &D) -> T where T: Generatable, { T::generate(self, dist) } } pub trait Generatable { fn generate(rng: &mut Rng, dist: &D) -> Self;} #[derive(Debug, Clone, Default)] pub struct Standard(());impl Generatable for u64 { fn generate(rng: &mut Rng, _dist: &Standard) -> u64 { rng.next() } } impl Generatable for f64 { fn generate(rng: &mut Rng, _dist: &Standard) -> f64 { let bits = rng.next();let float = (1023 << 52) + (bits & ((1 << 52) - 1));f64::from_bits(float) - 1.0 } } impl Generatable for bool { fn generate(rng: &mut Rng, _dist: &Standard) -> bool { rng.next() & 1 > 0 } } macro_rules! generate_standard_impl_by_cast { ($( $source:ty => $target:ty ),+) => { $( impl Generatable for $target { fn generate(rng: &mut Rng, _dist: &Standard) -> $target { rng.gen::<$source>() as $target } } )+ };} generate_standard_impl_by_cast!(f64 => f32, u64 => u32, u64 => u16, u64 => u8, u64 => i64, i64 => i32, i64 => i16, i64 => i8);#[derive(Debug, Clone)] pub struct UniformInt { min: u64, max: u64, mask: u64, } impl UniformInt { pub fn new(range: impl RangeBounds) -> UniformInt { let min = match range.start_bound() { Bound::Included(&x) => x, Bound::Excluded(&x) => x.checked_add(1).expect(\"minimum overflowed u64\"), Bound::Unbounded => 0, };let max = match range.end_bound() { Bound::Included(&x) => x, Bound::Excluded(&x) => x.checked_sub(1).expect(\"minimum underflowed u64\"), Bound::Unbounded => u64::MAX, };assert!(min <= max, \"range empty: min > max ({} > {})\", min, max);if max - min == u64::MAX { UniformInt { min, max, mask: !0 } } else { let len = max - min + 1;let bit_len = 0u64.leading_zeros() - len.leading_zeros();UniformInt { min, max, mask: if bit_len == 0u64.leading_zeros() { !0 } else { (1 << bit_len) - 1 }, } } } } impl Generatable for u64 { fn generate(rng: &mut Rng, dist: &UniformInt) -> Self { loop { let x = rng.next() & dist.mask;if x <= dist.max - dist.min { return dist.min + x;} } } } pub trait Shuffle { fn shuffle(&mut self, rng: &mut Rng);} impl Shuffle for [T] { fn shuffle(&mut self, rng: &mut Rng) { for i in (1..self.len()).rev() { let j: u64 = rng.gen_dist(&UniformInt::new(0..=i as u64));self.swap(i, j as usize);} } } }\n\nuse std::collections::HashSet;\n\nuse combinatorics::{next_permutation, Factorials};\nuse number_theory::{egcd, gcd, mod_exp, mod_mulinv, PrimeSieve};\nuse prefix_sum::{PrefixOp, PrefixSum};\nuse rng::{Rng, Shuffle, UniformInt};\nuse scanner::{\n macros::{LenArray, ScanCmd, UsizeM1},\n Scanner,\n};\nuse util::{fix, Argmax, Choose, IntoVec, Sorted};\nuse writer::{Format, Writer};\n\nfn main() {\n let mut sc = Scanner::stdin();\n let mut wr = Writer::stdout();\n\n let (x, y) = scan!(sc, u64, u64);\n let target = format!(\"{:b}\", y);\n\n let mut visited = HashSet::new();\n let mut current = Vec::new();\n current.push(format!(\"{:b}\", x));\n\n for _ in 0..140 {\n let mut next_cur = Vec::new();\n for s in current {\n if s == target {\n out!(wr, \"YES\");\n return;\n }\n for d in ['0', '1'] {\n let mut next = s.clone();\n next.push(d);\n next = next.chars().rev().skip_while(|c| *c == '0').collect();\n if !visited.contains(&next) {\n visited.insert(next.clone());\n next_cur.push(next);\n }\n }\n }\n current = next_cur;\n if current.is_empty() {\n break;\n }\n }\n\n out!(wr, \"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "328b38f86d49944a81a779b41a5183b5", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::{HashSet, VecDeque};\nuse std::io::stdin;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\npub fn flip(mut num: u64) -> u64 {\n let mut result: u64 = 0;\n while num > 0 {\n result = (result << 1) | (num & 1);\n num >>= 1;\n }\n result\n}\n\npub fn add_one(num: u64) -> u64 {\n flip((num << 1) | 1)\n}\n\npub fn main() {\n let mut scanner = Scanner::default();\n let a: u64 = scanner.next();\n let b: u64 = scanner.next();\n let mut visited: HashSet = HashSet::new();\n let mut queue: VecDeque = VecDeque::new();\n queue.push_back(a);\n visited.insert(a);\n let mut current: u64 = a;\n while !queue.is_empty() {\n current = queue.pop_front().unwrap();\n if current == b {\n break;\n }\n if current < b {\n let added: u64 = add_one(current);\n if !visited.contains(&added) {\n visited.insert(added);\n queue.push_back(added);\n }\n }\n let flipped: u64 = flip(current);\n if !visited.contains(&flipped) {\n visited.insert(flipped);\n queue.push_back(flipped);\n }\n }\n println!(\"{}\", if current == b { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "39b9995e5d08dd39c0ec220304f7e7e3", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n for _i in 0..2 {\n s.clear();\n io::stdin().read_line(&mut s).unwrap();\n }\n s = s.trim().to_string();\n s = s.to_lowercase();\n let mut flag = [false; 26];\n for c in s.chars() {\n flag[((c as i32) - ('a' as i32)) as usize] = true;\n }\n for i in 0..26 {\n if flag[i as usize] == false {\n println!(\"NO\");\n ::std::process::exit(0);\n }\n }\n println!(\"YES\");\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "2deae0d3997ef0b18b188f49b6805e43", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn main() {\n\n let n: usize = read_line().parse().unwrap();\n let line = read_line().to_lowercase();\n\n let set: std::collections::HashSet = line.chars().collect();\n\n println!(\"{}\", if set.len() == 26 { \"YES\" } else { \"NO\" });\n \n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "39a5c09488585aebf963dd2065de16a7", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/520/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf);\n buf.clear();\n io::stdin().read_line(&mut buf);\n let bytes = buf.trim().as_bytes();\n let mut seen = vec![false; 26];\n for &byte in bytes {\n seen[(byte.to_lowercase() - b'a') as usize] = true;\n }\n println!(\"{}\", if seen.iter().all(|&b| b) { \"YES\" } else { \"NO\" });\n}\n\n// -----------------------------------------------------------------------------\n\npub trait CharExt: Copy {\n fn is_digit(self, radix: u32) -> bool;\n fn to_digit(self, radix: u32) -> Option;\n fn is_alphabetic(self) -> bool;\n fn is_lowercase(self) -> bool;\n fn is_uppercase(self) -> bool;\n fn is_whitespace(self) -> bool;\n fn is_alphanumeric(self) -> bool;\n fn to_lowercase(self) -> Self;\n fn to_uppercase(self) -> Self;\n}\n\nmacro_rules! impl_u8 {\n ($meth:ident($($arg:ident : $ty:ty),*) -> $ret:ty) => {\n fn $meth(self, $($arg : $ty),*) -> $ret {\n let c = self as char;\n c.$meth($($arg),*)\n }\n }\n}\n\nimpl CharExt for u8 {\n impl_u8!(is_digit(radix: u32) -> bool);\n impl_u8!(to_digit(radix: u32) -> Option);\n impl_u8!(is_alphabetic() -> bool);\n impl_u8!(is_lowercase() -> bool);\n impl_u8!(is_uppercase() -> bool);\n impl_u8!(is_whitespace() -> bool);\n impl_u8!(is_alphanumeric() -> bool);\n fn to_lowercase(self) -> Self {\n let c = self as char;\n c.to_lowercase()\n .next()\n .map(|c| c as u8)\n .unwrap_or(self)\n }\n fn to_uppercase(self) -> Self {\n let c = self as char;\n c.to_uppercase()\n .next()\n .map(|c| c as u8)\n .unwrap_or(self)\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "bdd1a96e0ae92de601091ca2d388e87c", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::BTreeSet;\nuse std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nconst NUM_LETTERS : usize = 26;\n\nfn is_pangram(s : &String) -> bool {\n let t = s.trim().to_lowercase();\n let mut distinct_chars = BTreeSet::new();\n for c in t.chars() {\n distinct_chars.insert(c);\n }\n distinct_chars.len() == NUM_LETTERS\n}\n\nfn main() {\n let stdin = io::stdin();\n let _ : u64 = read_t(&stdin);\n let mut s = String::new();\n read_line(&stdin, &mut s);\n if is_pangram(&s) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "577e2bb3536fe01b22a362d7b7c1c040", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::ascii::AsciiExt;\nuse std::collections::HashSet;\n\nfn main() {\n R!(usize);\n if gets().chars().map(|c| c.to_ascii_lowercase()).collect::>().len() == 26 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "8701b34e71b2c9d829e19ffc8aaa4fcc", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\n\nfn get_int() -> usize {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::().ok().unwrap()\n}\n\nfn get_input(limit: usize) -> HashSet {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.chars()\n .take(limit)\n .map(|x| x.to_ascii_lowercase())\n .filter(|x| x.is_alphabetic())\n .collect()\n}\n\nfn main() {\n let n = get_int();\n let input = get_input(n);\n println!(\"{}\", if input.len() == 26 { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "566911d174f87f4280b57cc53d16552e", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cell::RefCell;\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Formatter, Write as FmtWrite};\nuse std::io::*;\nuse std::mem::{replace, swap};\nuse std::ops::*;\nuse std::rc::Rc;\n\n// -----------------------------------------------\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($t:ty) =>\n (rl().parse::<$t>().unwrap());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n#[allow(dead_code)]\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_owned()\n}\n\ntrait IteratorExt: Iterator + Sized {\n fn vec(self) -> Vec {\n self.collect()\n }\n}\n\nimpl IteratorExt for T {}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\nfn main() {\n // let sin = std::io::stdin();\n // let mut sin = sin.lock();\n // let sin = &mut sin;\n\n // #################################\n\n let _n: u32 = read!(u32);\n let input: String = rl();\n\n let mut set = HashSet::new();\n\n for c in input.to_lowercase().as_str().chars() {\n set.insert(c);\n }\n\n let ans = if set.len() == 26 { \"YES\" } else { \"NO\" };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "fd6b9c72388ac70b54d0ce1f4163b9ab", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\nuse std::collections::HashSet;\n\nfn main() {\n let stdin = io::stdin();\n let _n: i32;\n let mut iterator = stdin.lock().lines();\n let mut line: String;\n\n line = iterator.next().unwrap().unwrap();\n _n = line.parse().unwrap();\n line = iterator.next().unwrap().unwrap();\n let unique = line\n .to_lowercase()\n .chars()\n .collect::>()\n .iter().cloned().collect::>();\n\n if unique.len() as i32 == 26 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "49c06a988335fc249d63dd79bf94ad9b", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::cmp;\n\nfn main() {\n let (n, m, a, b) = R!(usize, usize, usize, usize);\n println!(\"{}\", cmp::min(n*a, cmp::min((n%m)*a + (n/m)*b, (n+m-1)/m*b)));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0648733f8d5c8e560f76cff3e5f2bd2c", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::min;\n\nfn main() {\n let stdin = io::stdin();\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n\n let x: Vec = s.trim()\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let n = x[0];\n let m = x[1];\n let a = x[2];\n let b = x[3];\n\n if m * a <= b {\n println!(\"{}\", a*n);\n } else {\n if m > n { \n println!(\"{}\", min(b, a*n));\n } else {\n if a*(n%m) < b {\n println!(\"{}\", b*(n/m)+a*(n%m));\n } else {\n println!(\"{}\", b*(n/m+1));\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "faaf9ac7b4262ad3a3dc4b682f9715ab", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n,m,a,b) = readln!(i32,i32,i32,i32);\n let r1 = n*a;\n let r2 = b*((n+m-1)/m);\n let r3 = b*(n/m) + a*(n%m);\n println!(\"{}\", std::cmp::min(r1,std::cmp::min(r2,r3)));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "23199290da91942cd59a4f75d0dc1986", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::min;\n\nfn main() {\n let stdin = io::stdin();\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n\n let x: Vec = s.trim()\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let n = x[0];\n let m = x[1];\n let a = x[2];\n let b = x[3];\n\n let ans =\n min( a*n,\n min( b*(n/m + 1),\n b*(n/m) + a*(n%m)\n ));\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "37b8878fc631720d4b2797b9eb90854e", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn solve() {\n let (n, m, a, b) = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let v: Vec = buf.split_whitespace().map(|x| x.parse().unwrap()).collect();\n (v[0], v[1], v[2], v[3])\n };\n\n let mut ans = 0;\n if b < m * a {\n let d = n / m;\n ans += d * b;\n if b < a * (n - d * m) {\n ans += b;\n } else {\n ans += (n - d * m) * a;\n }\n } else {\n ans += n * a;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n // let t: u32 = {\n // let mut buf = String::new();\n // std::io::stdin().read_line(&mut buf).unwrap();\n // buf.trim_end().parse().unwrap()\n // };\n\n solve();\n // for _ in 0..t {}\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d800f0f29347e65de5bebec622d3f6ff", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i();\n let m = input.i();\n let a = input.i();\n let b = input.i();\n let p = n / m;\n let q = n % m;\n let val = [a*n, a*q+b*p, b*(p+1)];\n let sol = val.iter().min().unwrap();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4ba503340730a03199e0bafcf920fda0", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input_split() -> Vec {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let (n, m, a, b) = {\n let temp = input_split();\n (temp[0], temp[1], temp[2], temp[3])\n };\n\n if m * a > b {\n println!(\"{}\", (n / m) * b + b.min((n % m) * a));\n } else {\n println!(\"{}\", n * a);\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "dadf563bd2d1b6bef954543022e58e53", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use rand::Rng;\n\nuse std::collections::*;\nuse std::io;\n\nfn trim_newline(s: &mut String) {\n if s.ends_with('\\n') {\n s.pop();\n if s.ends_with('\\r') {\n s.pop();\n }\n }\n}\nmacro_rules! parse_input {\n ($t:ident) => {{\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n trim_newline(&mut input_line);\n input_line.parse::<$t>().unwrap()\n }};\n}\n\nmacro_rules! split_input {\n ($t:ident) => {{\n parse_input!(String)\n .split(\" \")\n .map(|z| z.parse::<$t>().unwrap())\n .collect::>()\n }};\n}\n\nfn main() {\n let a = split_input!(u64);\n let n = a[0];\n let single = a[2];\n let group = a[3];\n let group_count = a[1];\n let mut best = single * n;\n best = std::cmp::min(best, ((n + (group_count - 1)) / group_count) * group);\n let other = n / group_count * group;\n let rem = n % group_count;\n best = std::cmp::min(other + rem * single, best);\n\n println!(\"{}\", best);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "36ce9619435d10d2423ffb9e60852ed4", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1239/problem/A\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::io::Write;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n// Input macros.\n// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_line {\n ($t:tt) => {\n {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim_right().parse::<$t>().unwrap()\n }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\n// ===\n\nconst MOD: i64 = 1e9 as i64 + 7;\n\nfn not_consequtive3(n: usize) -> Vec {\n let mut dp = dvec![0; n+1, 5];\n dp[1] = vec![1, 0, 1, 0];\n dp[2] = vec![1, 1, 1, 1];\n for i in 2..n {\n for j in 0..4 {\n let base = dp[i][j];\n for next in 0..2 {\n let nj = j+4*next;\n if nj == 7 || nj == 0 {\n continue;\n }\n let nj = ifv!(j == 0, 2*next, nj/2);\n dp[i+1][nj] += base;\n dp[i+1][nj] %= MOD;\n }\n }\n }\n dp.into_iter().map(|row| row.into_iter().fold(0, |acc,x| (acc+x)%MOD)).collect::>()\n}\n\n\nfn solve(h: usize, w: usize) -> i64 {\n if w == 1 {\n return 2;\n }\n let dp = not_consequtive3(w+10);\n // debug!(dp);\n (dp[h] + dp[w] + MOD - 2) % MOD\n}\n\nfn main() {\n input! {\n n: usize, m: usize\n };\n let h = min(n, m);\n let w = max(n, m);\n println!(\"{}\", solve(h, w));\n}\n\n\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "0e44f0d5639df47bbbc6a22409c55266", "src_uid": "0f1ab296cbe0952faa904f2bebe0567b", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\n/* \nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n*/\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n }\n let k = std::cmp::max(n, m);\n let mut dp = vec![ModInt::zero(); k + 1];\n dp[0] = ModInt::one();\n dp[1] = ModInt::one();\n for i in 2..=k {\n dp[i] = dp[i - 1] + dp[i - 2];\n }\n let ans = ModInt(2) * (dp[n] - ModInt::one()) + ModInt(2) * (dp[m] - ModInt::one()) + ModInt(2);\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "bab2debc82fcc191b76366c0ed659a62", "src_uid": "0f1ab296cbe0952faa904f2bebe0567b", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::Write;\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($e:expr),*) => {\n #[cfg(debug_assertions)]\n $({\n let (e, mut err) = (stringify!($e), std::io::stderr());\n writeln!(err, \"{} = {:?}\", e, $e).unwrap()\n })*\n };\n}\n\nfn fibonacchi(n: usize) -> Vec {\n let mut f = vec![0; n + 1];\n f[0] = 1;\n f[1] = 1;\n for i in 2..n + 1 {\n f[i] = (f[i - 1] + f[i - 2]) % 1000_000_007;\n }\n f\n}\n\nfn main() {\n let v = read_vec::();\n let f = fibonacchi(max(v[0], v[1]));\n println!(\"{}\", (2 * (f[v[0]] + f[v[1]] - 1)) % 1000_000_007);\n}\n\nfn read() -> T {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn read_vec() -> Vec {\n read::()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "dba05f480e6638a5f5d86c3e2da7f975", "src_uid": "0f1ab296cbe0952faa904f2bebe0567b", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let ints = s.split_whitespace().map(|x| x.parse().unwrap()).collect::>();\n let mut n = std::collections::HashMap::new();\n n.insert(true,ints[0]);\n n.insert(false,ints[1]);\n let mut default = std::collections::HashMap::new();\n default.insert(true,ints[0]);\n default.insert(false,ints[1]);\n let mut k = std::collections::HashMap::new();\n k.insert(true,ints[2]);\n k.insert(false,ints[3]);\n\n let mut firstplayer = true;\n\n loop {\n if n[&firstplayer] <= 0 {\n break;\n }\n\n *(n.get_mut(&firstplayer).unwrap())-=1; //k[&firstplayer]; \n firstplayer = !firstplayer;\n }\n println!(\"{}\", if !firstplayer {\"First\"} else {\"Second\"});\n }\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "1e5c2048127a24c8399097555fa9a266", "src_uid": "aed24ebab3ed9fd1741eea8e4200f86b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n if input.i() > input.i() {\n println!(\"First\");\n } else {\n println!(\"Second\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "81e6d334bca67215900aeda15527fd9b", "src_uid": "aed24ebab3ed9fd1741eea8e4200f86b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n1,n2,k1,k2) = readln!(i32,i32,i32,i32);\n println!(\"{}\",\n if n1>n2{\n \"First\"\n } else {\n \"Second\"\n });\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "a649014e9f781826537494f8af8448c8", "src_uid": "aed24ebab3ed9fd1741eea8e4200f86b", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::mem;\nuse std::io;\nuse std::string;\nuse std::cmp::*;\n\nfn load() -> Vec {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let vec: Vec<&str> = line.split(\" \").collect();\n let mut data : Vec = Vec::new();\n for i in vec {\n let el : i32 = i.trim().parse().unwrap();\n data.push(el);\n }\n data\n}\n\nfn main() {\n let ar = load();\n let (q,k) = (ar[0],ar[1]);\n let mut a = q;\n let mut b = 0;\n let mut last=-1;\n while last != b {\n last=b;\n b = (a + b)/k;\n }\n println!(\"{}\", a+b);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "de5630e0a6f1d646bd04000a588bf445", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_pair() -> (i32, i32) {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n let v = input.trim()\n .split_whitespace()\n .map(|s| i32::from_str(s).unwrap())\n .collect::>();\n\n (v[0], v[1])\n}\n\nfn main() {\n let (mut n, m) = get_pair();\n\n let mut d = 0;\n while n != 0 {\n n -= 1;\n d += 1;\n\n if d % m == 0 {\n n += 1;\n }\n }\n\n println!(\"{}\", d);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "19352ec4777b17284249f5db2097ec5f", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let input = readln();\n let mut n = input[0];\n let m = input[1];\n\n for i in 0.. {\n\n if n == 0 {\n println!(\"{}\", i);\n return;\n }\n\n if (i + 1) % m == 0 {\n n += 1;\n }\n\n n -= 1;\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "1d767af74a226af3dcb598e559e44a43", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use rand::Rng;\n\nuse std::collections::*;\nuse std::io;\n\nfn trim_newline(s: &mut String) {\n if s.ends_with('\\n') {\n s.pop();\n if s.ends_with('\\r') {\n s.pop();\n }\n }\n}\nmacro_rules! parse_input {\n ($t:ident) => {{\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n trim_newline(&mut input_line);\n input_line.parse::<$t>().unwrap()\n }};\n}\n\nmacro_rules! split_input {\n ($t:ident) => {{\n parse_input!(String)\n .split(\" \")\n .map(|z| z.parse::<$t>().unwrap())\n .collect::>()\n }};\n}\n\nfn main() {\n let s1 = split_input!(usize);\n let n = s1[0];\n let mut extra = 0;\n let m = s1[1];\n let mut days = 0;\n while days < (n + extra) {\n days = n + extra;\n extra = days / m;\n }\n println!(\"{}\", days);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "dfa4b1b78bda9973b7683c1d553794a5", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (i64, i64) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\nfn main() {\n \n let (mut n, m) = read_line_pair();\n\n let mut i = 0;\n\n while n > 0 {\n i += 1;\n n -= 1;\n if i % m == 0 {\n n += 1;\n }\n }\n\n println!(\"{}\", i);\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "a31dd577926e9147b6103b398c4ea74a", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let m: usize = scan.next();\n let mut socks = n;\n let mut days = 0;\n for i in 1.. {\n if socks == 0 { break; }\n socks -= 1;\n days += 1;\n if i%m == 0 { socks += 1; }\n }\n println!(\"{}\", days);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "d2c63c12bba832d7da4ff4d0fd05da78", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let input: Vec = reads(sin);\n\n let initial_socks = input[0];\n let supply = input[1];\n\n let mut day_alived = 0;\n let mut socks = initial_socks;\n\n while socks != 0 {\n day_alived += 1;\n\n if day_alived % supply == 0 {\n socks += 1;\n }\n\n socks -= 1;\n }\n\n // Does not he wash it?\n println!(\"{}\", day_alived);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "fbb16f23a799ba557fcfae751a736f61", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n\n io::stdin()\n .read_line(&mut input)\n .unwrap();\n\n let mut s = input.trim().split(' ');\n\n let a_str = s.next().unwrap();\n let mut a: i32 = a_str.parse().unwrap();\n\n let b_str = s.next().unwrap();\n let b: i32 = b_str.parse().unwrap();\n\n let mut res = 0;\n let mut bcnt = b;\n loop {\n if a==0{\n break;\n }\n a-=1;\n res+=1;\n bcnt-=1;\n if bcnt==0{\n a+=1;\n bcnt=b;\n }\n }\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "9afd28530ff299616982291994989480", "src_uid": "42b25b7335ec01794fbb1d4086aa9dd0", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn linear_sieve(n: u64) -> (Vec, Vec) {\n let n = n as usize;\n let mut mpf = vec![0u64; n + 1];\n let mut primes = Vec::new();\n for i in 2..=n {\n if mpf[i] == 0 {\n mpf[i] = i as u64;\n primes.push(i as u64);\n }\n // for (int j = 0; j < primes.size() && i * primes[j] <= n && primes[j] <= mpf[i]) {\n // mpf[i * primes[j]] = primes[j]\n // }\n for &p in primes.iter() {\n let num = i * p as usize;\n if num > n || p > mpf[i] {\n break;\n }\n mpf[num] = p;\n }\n }\n (primes, mpf)\n}\n\nfn get_mpf(n: u64, primes: &[u64], mpf: &[u64]) -> u64 {\n if (n as usize) < mpf.len() {\n return mpf[n as usize];\n }\n for &p in primes {\n if n % p == 0 {\n return p;\n }\n }\n n\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let (primes, mpf) = linear_sieve(1000000);\n let mut n: u64 = scan.token();\n let mut ans = n;\n while n > 1 {\n let factor = n / get_mpf(n, &primes, &mpf);\n ans += factor;\n n = factor;\n }\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "5e0b356247627e7a6e93f0f9f7df180a", "src_uid": "821c0e3b5fad197a47878bba5e520b6e", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn linear_sieve(n: u64) -> (Vec, Vec) {\n let n = n as usize;\n let mut mpf = vec![0u64; n + 1];\n let mut primes = Vec::new();\n for i in 2..=n {\n if mpf[i] == 0 {\n mpf[i] = i as u64;\n primes.push(i as u64);\n }\n // for (int j = 0; j < primes.size() && i * primes[j] <= n && primes[j] <= mpf[i]) {\n // mpf[i * primes[j]] = primes[j]\n // }\n for &p in primes.iter() {\n let num = i * p as usize;\n if num > n || p > mpf[i] {\n break;\n }\n mpf[num] = p;\n }\n }\n (primes, mpf)\n}\n\nfn get_mpf(n: u64, primes: &[u64], mpf: &[u64]) -> u64 {\n if (n as usize) < mpf.len() {\n return mpf[n as usize];\n }\n for &p in primes {\n if n % p == 0 {\n return p;\n }\n }\n n\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let (primes, mpf) = linear_sieve(1000000);\n let mut n: u64 = scan.token();\n let mut ans = n;\n while n > 1 {\n let factor = n / get_mpf(n, &primes, &mpf);\n ans += factor;\n n = factor;\n }\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "ba613bab3a264ddcd8bb443e5d141801", "src_uid": "821c0e3b5fad197a47878bba5e520b6e", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n\n let mut cnt_diff = 0;\n let mut chars: [bool; 26] = [false; 26];\n\n for ch in line.chars() {\n let x: i32 = (ch as i32) - ('a' as i32);\n /**/\n if x >= 0 && !chars[x as usize] {\n cnt_diff += 1;\n chars[x as usize] = true;\n }\n /**/\n }\n\n if cnt_diff % 2 == 0 {\n println!(\"CHAT WITH HER!\");\n }\n else {\n println!(\"IGNORE HIM!\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "3cd3e4836c653c586f5aebd02179f7af", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/236/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let str = buf.trim().as_bytes();\n let mut uniq: Vec = vec![true; 26];\n let mut chars = 0;\n for &b in str {\n let i = (b - b'a') as usize;\n if uniq[i] {\n uniq[i] = false;\n chars += 1;\n }\n }\n println!(\"{}\",\n if chars % 2 == 0 {\n \"CHAT WITH HER!\"\n } else {\n \"IGNORE HIM!\"\n }\n );\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "9cb10ab6b0694c23856167b9816c5487", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\nuse std::collections::HashSet;\n\nfn main() {\n let mut text : String = String::new();\n std::io::stdin().read_line(&mut text);\n\n let mut chars = HashSet::new();\n for char in text.trim().chars() {\n chars.insert(char);\n }\n println!(\"{}\", if chars.len() % 2 == 0 {\"CHAT WITH HER!\"} else {\"IGNORE HIM!\"});\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "5c0ad55e670565eedf78d20b5d6c8174", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s = s.trim().to_string();\n let mut cnt = 1;\n let mut flag : [bool; 26] = [false; 26];\n for c in s.chars() {\n let x : i32 = (c as i32) - ('a' as i32);\n let x = x as usize;\n if !flag[x] {\n cnt += 1;\n flag[x] = true;\n }\n }\n if cnt % 2 == 1 {\n println!(\"CHAT WITH HER!\");\n } else {\n println!(\"IGNORE HIM!\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "4303050deef571b44cf008ff6ebf6df5", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//jdoodle.com:rustc 1.10.0--codeforces.com:1.19\nfn main(){\n let mut z=String::new();std::io::stdin().read_line(&mut z).unwrap();\n let mut a=0;let mut b=[true;26];\n for i in z.chars(){\n let c=i as i16-'a' as i16;\n if c>=0&&b[c as usize]{a+=1;b[c as usize]=false}\n }\n print!(\"{}\",if a%2==0{\"CHAT WITH HER!\"}else{\"IGNORE HIM!\"})\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "7dddbb4957367b5b612f40900942ebe9", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::collections::HashMap;\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let input = input.trim().parse::().unwrap();\n let mut hash = HashMap::new();\n for ch in input.chars() {\n hash.entry(ch).or_insert(0);\n }\n let c = hash.len();\n if c % 2 == 0 {\n println!(\"CHAT WITH HER!\");\n } else {\n println!(\"IGNORE HIM!\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "346a62da426cca58cc0186a49dc96a7e", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\nuse std::io::{self, Read};\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer\n}\n\nfn main() -> io::Result<()> {\n let input: String = get_input().trim().to_string();\n\n let mut set = HashSet::new();\n for c in input.chars() {\n set.insert(c);\n }\n\n if set.len() % 2 == 0 {\n println!(\"CHAT WITH HER!\");\n } else {\n println!(\"IGNORE HIM!\");\n }\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "fb5ed44acd8de498422b201d33141af8", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::collections::{*};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n \nfn main() {\n let mut scanner = Scanner::default();\n let s: String = scanner.next();\n let set: BTreeSet = s.chars().collect();\n if set.len() % 2 == 0 {\n \tprintln![\"CHAT WITH HER!\"];\n } else {\n \tprintln![\"IGNORE HIM!\"];\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "32dc5d1771b12f36f6682d7bda86fcf8", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n#[allow(dead_code)]\nfn read() -> String\n{\n let mut res = String::new();\n io::stdin().read_line(&mut res).unwrap();\n res\n}\n#[allow(unused_macros)]\nmacro_rules! read \n{\n () => \n {\n read().trim().parse().unwrap(); \n };\n}\n#[allow(dead_code)]\nfn read_vec() -> Vec\n{\n read().split_whitespace().map(|x| x.parse::().unwrap()).collect()\n}\nfn main()\n{\n let n : i32 = read!();\n println!(\"{}\", (2 + (n - 2) * 2) * (n - 1) + 1 + (n - 1) * 2);\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "758cc0bc7cfc2ef7b133b62e79504b0c", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io::{self, Read};\ntype Result = std::result::Result>;\n\nfn main() -> Result<()> {\n let mut input = String::new();\n io::stdin().read_to_string(&mut input)?;\n let mut lines = input.lines();\n let n: u64 = lines.next().unwrap().parse()?;\n let ans = (1..n).fold(0, |acc, x| acc + (2 * x - 1) * 2) + (2 * n - 1);\n println!(\"{}\", ans);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "3909a481d6226d700eb0a0499f35b02d", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let n: u32 = buffer.trim().parse().expect(\"invalid input\");\n\n println!(\"{}\", 2 * n * (n - 1) + 1);\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "c067ddc9f3c4a3d116bb32754d76c627", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::{max, min};\nuse std::io::{stdin, stdout, BufWriter, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scanner = Scanner::default();\n\n let n = scanner.next::();\n\n let mut dp = vec![1];\n\n for i in 1..n {\n dp.push(dp[i - 1] + i * 4);\n }\n\n println!(\"{}\", dp[n - 1]);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "27805b399814a291e90c128b1023ea29", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n let n: i32 = input.trim().parse().unwrap();\n\n println!(\"{}\", 2*n*(n-1)+1);\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "6a9fcdd7c41bffc16f0550103b911c4a", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[warn(unused_variables)]\n\nfn main() {\n let m = input_u64();\n\n fn foo(n: u64) -> u64 {\n if n == 1 {return 1;}\n else {return foo(n - 1) + (n - 1) * 4;}\n }\n\n println!(\"{}\", foo(m));\n}\n\nfn input_str() -> String {\n let mut buff = String::new();\n std::io::stdin().read_line(&mut buff).expect(\"Err\");\n buff\n}\n\nfn input_u64() -> u64 {\n input_str().trim().parse().unwrap()\n}\n\nfn input_vec(sep: &str) -> Vec \nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().split(sep).map(|c| c.parse::().expect(\"Err pars\")).collect()\n}\n\nfn input_vec_chars() -> Vec {\n input_str().trim().chars().collect()\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "381bf1135a63dd866300ddb112f00832", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn compute(order: u64) -> u64 {\n let order = order as i64;\n\n // order * (a1 + an) / 2\n let an = order * 2 - 1;\n let an1 = (order-1) * 2 - 1;\n let a1 = 1;\n\n (order * (a1+an) / 2 + (order - 1) * (a1+an1)/2) as u64\n}\n\nfn main() {\n let stdin = io::stdin();\n let line = stdin.lock().lines().next().expect(\"input\").expect(\"UTF-8\");\n let order: u64 = line.parse().expect(\"Numeric value\");\n\n let sum = compute(order);\n\n println!(\"{}\", sum);\n}\n\n#[test]\nfn vectors() {\n let in_out = [(1, 1), (2, 5), (3, 13)];\n\n for (i, o) in &in_out {\n let test = compute(*i);\n assert_eq!(test, *o,\n \"{}th should be {}, but got {}\", i, *o, test);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "a5c77282fc1f2640c2df9cde9f68bf02", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n\n// f(n) = f(n - 1) + 4 * (n - 1)\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u32 = scan.token();\n let mut ans = 1;\n for i in 2..=n {\n ans += 4 * (i - 1)\n }\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "09ce48072461fe07c61f7d2dea7db78d", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 998_244_353;\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> ModInt {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> ModInt {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> ModInt {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> ModInt {\n if self.0 == 0 {self} else {ModInt(MOD - self.0)}\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(v: u32) -> ModInt {\n ModInt(v % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s;\n }\n s = s * s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin NTT ----------\nfn ntt(f: &mut [ModInt]) {\n let n = f.len();\n assert!(n.count_ones() == 1);\n let len = n.trailing_zeros() as usize;\n for i in 1..(n - 1){\n let mut x = i;\n let mut j = 0;\n for _ in 0..len {\n j = (j << 1) | (x & 1);\n x >>= 1;\n }\n if i < j {\n f.swap(i, j);\n }\n }\n for k in 0..(n.trailing_zeros() as usize) {\n let m = 1 << k;\n let z = ModInt(3).pow((MOD - 1) >> (k + 1) as u32);\n for j in 0..(n / (2 * m)) {\n let mut q = ModInt::one();\n for i in (2 * m * j)..(2 * m * j + m) {\n let a = f[i];\n let b = q * f[i + m];\n f[i] = a + b;\n f[i + m] = a - b;\n q *= z;\n }\n }\n }\n}\n\nfn intt(f: &mut [ModInt]) {\n ntt(f);\n f[1..].reverse();\n let ik = ModInt(f.len() as u32).inv();\n for f in f.iter_mut() {\n *f *= ik;\n }\n}\n// ---------- end NTT ----------\n\nuse std::io::Read;\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let n: usize = it.next().unwrap().parse().unwrap();\n let k = (n * 9 + 1).next_power_of_two();\n let mut f = vec![ModInt::zero(); k];\n it.next();\n for s in it {\n let a: usize = s.parse().unwrap();\n f[a] = ModInt::one();\n }\n ntt(&mut f);\n for f in &mut f {\n *f = f.pow((n / 2) as u32);\n }\n intt(&mut f);\n let ans = f.iter().fold(ModInt::zero(), |s, f| s + *f * *f);\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "7e5fcf58596a446e54e695964dab75f2", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place)\n/// R: Ring + Copy\n/// Verified by: ATC001-C (http://atc001.contest.atcoder.jp/submissions/1175827)\nmod fft {\n use std::ops::*;\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &[R], zeta: R, one: R) -> Vec\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n let mut output = f.to_vec();\n assert!(n.is_power_of_two());\n {\n let mut i = 0;\n for j in 1 .. n - 1 {\n let mut k = n >> 1;\n loop {\n i ^= k;\n if k <= i { break; }\n k >>= 1;\n }\n if j < i {\n output.swap(i, j);\n }\n }\n }\n let mut zetapow = Vec::new();\n {\n let mut m = 1;\n let mut cur = zeta;\n while m < n {\n zetapow.push(cur);\n cur = cur * cur;\n m *= 2;\n }\n }\n let mut m = 1;\n while m < n {\n let m2 = 2 * m;\n let base = zetapow.pop().unwrap();\n for r in 0 .. n / m2 {\n let mut w = one;\n let r = r * m2;\n for x in 0 .. m {\n let s = x + r;\n let u = output[s];\n let d = output[s + m] * w;\n output[s] = u + d;\n output[s + m] = u - d;\n w = w * base;\n }\n }\n m *= 2;\n }\n output\n }\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n d: [usize; k],\n }\n const N: usize = 1 << 20;\n let one = ModInt::new(1);\n let mut f = vec![ModInt::new(0); N];\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n for i in 0 .. k {\n f[d[i]] += one;\n }\n let mut f = fft::transform(&f, zeta, one);\n for i in 0 .. N {\n f[i] = f[i].pow(n as i64 / 2);\n }\n let mut f = fft::transform(&f, zeta.inv(), one);\n let factor = ModInt::new(N as i64).inv();\n for i in 0 .. N {\n f[i] *= factor;\n }\n let mut tot = ModInt::new(0);\n for i in 0 .. N {\n tot += f[i].pow(2);\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "9c862125c7f8f1945c96bcb007dd14c3", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place, verified as NTT only)\n/// R: Ring + Copy\n/// Verified by: https://codeforces.com/contest/1096/submission/47672373\nmod fft {\n use std::ops::*;\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &mut [R], zeta: R, one: R)\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n assert!(n.is_power_of_two());\n {\n let mut i = 0;\n for j in 1 .. n - 1 {\n let mut k = n >> 1;\n loop {\n i ^= k;\n if k <= i { break; }\n k >>= 1;\n }\n if j < i { f.swap(i, j); }\n }\n }\n let mut zetapow = Vec::new();\n {\n let mut m = 1;\n let mut cur = zeta;\n while m < n {\n zetapow.push(cur);\n cur = cur * cur;\n m *= 2;\n }\n }\n let mut m = 1;\n while m < n {\n let base = zetapow.pop().unwrap();\n let mut r = 0;\n while r < n {\n let mut w = one;\n for s in r .. r + m {\n let u = f[s];\n let d = f[s + m] * w;\n f[s] = u + d;\n f[s + m] = u - d;\n w = w * base;\n }\n r += 2 * m;\n }\n m *= 2;\n }\n }\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n d: [usize; k],\n }\n const N: usize = 1 << 22;\n let one = ModInt::new(1);\n let mut f = vec![ModInt::new(0); N];\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n for i in 0 .. k {\n f[d[i]] += one;\n }\n fft::transform(&mut f, zeta, one);\n for i in 0 .. N {\n f[i] = f[i].pow(n as i64 / 2);\n }\n fft::transform(&mut f, zeta.inv(), one);\n let factor = ModInt::new(N as i64).inv();\n for i in 0 .. N {\n f[i] *= factor;\n }\n let mut tot = ModInt::new(0);\n for i in 0 .. N {\n tot += f[i].pow(2);\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "d0d97ba3cb01faf04482cf24f0ed15d0", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place, verified as NTT only)\n/// R: Ring + Copy\n/// Verified by: https://codeforces.com/contest/1096/submission/47672373\nmod fft {\n use std::ops::*;\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &mut [R], zeta: R, one: R)\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n assert!(n.is_power_of_two());\n {\n let mut i = 0;\n for j in 1 .. n - 1 {\n let mut k = n >> 1;\n loop {\n i ^= k;\n if k <= i { break; }\n k >>= 1;\n }\n if j < i { f.swap(i, j); }\n }\n }\n let mut zetapow = Vec::new();\n {\n let mut m = 1;\n let mut cur = zeta;\n while m < n {\n zetapow.push(cur);\n cur = cur * cur;\n m *= 2;\n }\n }\n let mut m = 1;\n while m < n {\n let base = zetapow.pop().unwrap();\n let mut r = 0;\n while r < n {\n let mut w = one;\n for s in r .. r + m {\n let u = f[s];\n let d = f[s + m] * w;\n f[s] = u + d;\n f[s + m] = u - d;\n w = w * base;\n }\n r += 2 * m;\n }\n m *= 2;\n }\n }\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n d: [usize; k],\n }\n const N: usize = 1 << 20;\n let one = ModInt::new(1);\n let mut f = vec![ModInt::new(0); N];\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n for i in 0 .. k {\n f[d[i]] += one;\n }\n fft::transform(&mut f, zeta, one);\n for i in 0 .. N {\n f[i] = f[i].pow(n as i64 / 2);\n }\n fft::transform(&mut f, zeta.inv(), one);\n let factor = ModInt::new(N as i64).inv();\n for i in 0 .. N {\n f[i] *= factor;\n }\n let mut tot = ModInt::new(0);\n for i in 0 .. N {\n tot += f[i].pow(2);\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "f0f79a9c071167cd264ae6e855d50d4c", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place)\n/// R: Ring + Copy\n/// Verified by: ATC001-C (http://atc001.contest.atcoder.jp/submissions/1175827)\nmod fft {\n use std::ops::*;\n fn inplace_internal_fft(\n f: &[R], output: &mut [R], pztbl: &[R], one: R,\n x: usize, fstart: usize, fstep: usize,\n n: usize, ostart: usize)\n where R: Copy +\n Add +\n Sub +\n Mul {\n if n == 1 {\n output[ostart] = f[fstart];\n return;\n }\n inplace_internal_fft(f, output, pztbl, one, x + 1,\n fstart, 2 * fstep, n / 2, ostart);\n inplace_internal_fft(f, output, pztbl, one, x + 1,\n\t\t\t fstart + fstep, 2 * fstep, n / 2, ostart + n / 2);\n let mut cnt = 0;\n for i in 0 .. n / 2 {\n let pzeta = pztbl[cnt];\n let f0 = output[ostart + i];\n let f1 = output[ostart + i + n / 2];\n let tmp = pzeta * f1;\n output[ostart + i] = f0 + tmp;\n output[ostart + i + n / 2] = f0 - tmp;\n cnt += 1 << x;\n }\n }\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &[R], zeta: R, one: R) -> Vec\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n assert!(n.is_power_of_two());\n let mut pztbl = vec![one; n];\n for i in 1 .. n {\n pztbl[i] = pztbl[i - 1] * zeta;\n }\n let mut output = vec![zeta; n];\n inplace_internal_fft(&f, &mut output, &pztbl, one, 0, 0, 1, n, 0);\n output\n }\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n d: [usize; k],\n }\n const N: usize = 1 << 20;\n let one = ModInt::new(1);\n let mut f = vec![ModInt::new(0); N];\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n for i in 0 .. k {\n f[d[i]] += one;\n }\n let mut f = fft::transform(&f, zeta, one);\n for i in 0 .. N {\n f[i] = f[i].pow(n as i64 / 2);\n }\n let mut f = fft::transform(&f, zeta.inv(), one);\n let factor = ModInt::new(N as i64).inv();\n for i in 0 .. N {\n f[i] *= factor;\n }\n let mut tot = ModInt::new(0);\n for i in 0 .. N {\n tot += f[i].pow(2);\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "bc9b4b2401539fba0924d941ed164941", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place, verified as NTT only)\n/// R: Ring + Copy\n/// Verified by: https://codeforces.com/contest/1096/submission/47672373\nmod fft {\n use std::ops::*;\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &mut [R], zeta: R, one: R)\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n assert!(n.is_power_of_two());\n {\n let mut i = 0;\n for j in 1 .. n - 1 {\n let mut k = n >> 1;\n loop {\n i ^= k;\n if k <= i { break; }\n k >>= 1;\n }\n if j < i {\n f.swap(i, j);\n }\n }\n }\n let mut zetapow = Vec::new();\n {\n let mut m = 1;\n let mut cur = zeta;\n while m < n {\n zetapow.push(cur);\n cur = cur * cur;\n m *= 2;\n }\n }\n let mut m = 1;\n while m < n {\n let m2 = 2 * m;\n let base = zetapow.pop().unwrap();\n let mut r = 0;\n while r < n {\n let mut w = one;\n for s in r .. r + m {\n let u = f[s];\n let d = f[s + m] * w;\n f[s] = u + d;\n f[s + m] = u - d;\n w = w * base;\n }\n r += m2;\n }\n m *= 2;\n }\n }\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n d: [usize; k],\n }\n const N: usize = 1 << 22;\n let one = ModInt::new(1);\n let mut f = vec![ModInt::new(0); N];\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n for i in 0 .. k {\n f[d[i]] += one;\n }\n fft::transform(&mut f, zeta, one);\n for i in 0 .. N {\n f[i] = f[i].pow(n as i64 / 2);\n }\n fft::transform(&mut f, zeta.inv(), one);\n let factor = ModInt::new(N as i64).inv();\n for i in 0 .. N {\n f[i] *= factor;\n }\n let mut tot = ModInt::new(0);\n for i in 0 .. N {\n tot += f[i].pow(2);\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "c19b4a558f5413d2b19abbae59343e03", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place)\n/// R: Ring + Copy\n/// Verified by: ATC001-C (http://atc001.contest.atcoder.jp/submissions/1175827)\nmod fft {\n use std::ops::*;\n fn inplace_internal_fft(\n f: &[R], output: &mut [R], pztbl: &[R], one: R,\n x: usize, fstart: usize, fstep: usize,\n n: usize, ostart: usize)\n where R: Copy +\n Add +\n Sub +\n Mul {\n if n == 1 {\n output[ostart] = f[fstart];\n return;\n }\n inplace_internal_fft(f, output, pztbl, one, x + 1,\n fstart, 2 * fstep, n / 2, ostart);\n inplace_internal_fft(f, output, pztbl, one, x + 1,\n\t\t\t fstart + fstep, 2 * fstep, n / 2, ostart + n / 2);\n let mut cnt = 0;\n for i in 0 .. n / 2 {\n let pzeta = pztbl[cnt];\n let f0 = output[ostart + i];\n let f1 = output[ostart + i + n / 2];\n let tmp = pzeta * f1;\n output[ostart + i] = f0 + tmp;\n output[ostart + i + n / 2] = f0 - tmp;\n cnt += 1 << x;\n }\n }\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &[R], zeta: R, one: R) -> Vec\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n assert!(n.is_power_of_two());\n let mut pztbl = vec![one; n];\n for i in 1 .. n {\n pztbl[i] = pztbl[i - 1] * zeta;\n }\n let mut output = vec![zeta; n];\n inplace_internal_fft(&f, &mut output, &pztbl, one, 0, 0, 1, n, 0);\n output\n }\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n d: [usize; k],\n }\n const N: usize = 1 << 22;\n let one = ModInt::new(1);\n let mut f = vec![ModInt::new(0); N];\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n for i in 0 .. k {\n f[d[i]] += one;\n }\n let mut f = fft::transform(&f, zeta, one);\n for i in 0 .. N {\n f[i] = f[i].pow(n as i64 / 2);\n }\n let mut f = fft::transform(&f, zeta.inv(), one);\n let factor = ModInt::new(N as i64).inv();\n for i in 0 .. N {\n f[i] *= factor;\n }\n let mut tot = ModInt::new(0);\n for i in 0 .. N {\n tot += f[i].pow(2);\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "476ed8df9c11638e4afa9f4c0fbcd8f0", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998244353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n/// FFT (in-place)\n/// R: Ring + Copy\n/// Verified by: ATC001-C (http://atc001.contest.atcoder.jp/submissions/1175827)\nmod fft {\n use std::ops::*;\n /// n should be a power of 2. zeta is a primitive n-th root of unity.\n /// one is unity\n /// Note that the result should be multiplied by 1/sqrt(n).\n pub fn transform(f: &mut [R], zeta: R, one: R)\n where R: Copy +\n Add +\n Sub +\n Mul {\n let n = f.len();\n assert!(n.is_power_of_two());\n {\n let mut i = 0;\n for j in 1 .. n - 1 {\n let mut k = n >> 1;\n loop {\n i ^= k;\n if k <= i { break; }\n k >>= 1;\n }\n if j < i {\n f.swap(i, j);\n }\n }\n }\n let mut zetapow = Vec::new();\n {\n let mut m = 1;\n let mut cur = zeta;\n while m < n {\n zetapow.push(cur);\n cur = cur * cur;\n m *= 2;\n }\n }\n let mut m = 1;\n while m < n {\n let m2 = 2 * m;\n let base = zetapow.pop().unwrap();\n let mut r = 0;\n while r < n {\n let mut w = one;\n for x in 0 .. m {\n let s = x + r;\n let u = f[s];\n let d = f[s + m] * w;\n f[s] = u + d;\n f[s + m] = u - d;\n w = w * base;\n }\n r += m2;\n }\n m *= 2;\n }\n }\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize,\n k: usize,\n d: [usize; k],\n }\n const N: usize = 1 << 20;\n let one = ModInt::new(1);\n let mut f = vec![ModInt::new(0); N];\n let zeta = ModInt::new(3).pow((MOD - 1) / N as i64);\n for i in 0 .. k {\n f[d[i]] += one;\n }\n fft::transform(&mut f, zeta, one);\n for i in 0 .. N {\n f[i] = f[i].pow(n as i64 / 2);\n }\n fft::transform(&mut f, zeta.inv(), one);\n let factor = ModInt::new(N as i64).inv();\n for i in 0 .. N {\n f[i] *= factor;\n }\n let mut tot = ModInt::new(0);\n for i in 0 .. N {\n tot += f[i].pow(2);\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "fft"], "code_uid": "454d8ce5e1d8c991395b39def7e8a878", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! debug {\n ( $x:expr ) => {\n if cfg!(debug_assertions) {\n println!(\"{}:{} {} = {:?}\", line!(), column!(), stringify!($x), $x);\n }\n }\n}\n\nmod my {\n pub mod io {\n use std::io::{BufRead, ErrorKind};\n\n pub fn read_word(r: &mut R, buf: &mut Vec)\n -> std::io::Result {\n let mut read = 0;\n loop {\n let (done, used) = {\n let available = match r.fill_buf() {\n Ok(n) => n,\n Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,\n Err(e) => return Err(e)\n };\n match available.iter().position(|&x| x == b'\\n' || x == b' ') {\n Some(i) => {\n buf.extend_from_slice(&available[..i]);\n (true, i + 1)\n }\n None => {\n buf.extend_from_slice(available);\n (false, available.len())\n }\n }\n };\n r.consume(used);\n read += used;\n if done || used == 0 {\n return Ok(read);\n }\n }\n }\n\n pub struct InputReader {\n reader: R,\n buf: Vec,\n }\n\n impl InputReader {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf: Vec::::new(),\n }\n }\n\n pub fn read_word(&mut self) {\n read_word(&mut self.reader, &mut self.buf);\n }\n \n pub fn read(&mut self) -> T\n where T: std::str::FromStr,\n T::Err: std::fmt::Debug\n {\n self.buf.clear();\n self.read_word();\n std::str::from_utf8(&self.buf).unwrap().trim().parse().unwrap()\n }\n }\n }\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let mut stdin = my::io::InputReader::new(stdin.lock());\n\n let n: usize = stdin.read();\n let mut a = Vec::::new();\n\n for i in 0..n {\n a.push(stdin.read());\n }\n let mut result = false;\n for bit in 0..(1 << n) {\n let mut sum = 0;\n for i in 0..n {\n if bit & (1 << i) > 0 {\n sum += a[i];\n } else {\n sum -= a[i];\n }\n }\n if sum.abs() % 360 == 0 {\n result = true;\n break;\n }\n }\n println!(\"{}\", if result { \"YES\" } else { \"NO\" });\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "f818ff54e58d878503e5864ebe1740fa", "src_uid": "01b50fcba4185ceb1eb8e4ba04a0cc10", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn dfs(sum: i32, list: &[i32]) -> bool {\n if list.is_empty() {\n sum == 0\n } else {\n dfs((sum + list[0]) % 360, &list[1..]) || dfs((sum - list[0]) % 360, &list[1..])\n }\n}\n\nfn main() {\n let n: usize = {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim_end().parse().unwrap()\n };\n\n let mut degrees: Vec = Vec::with_capacity(n);\n for _ in 0..n {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n degrees.push(buf.trim().parse().unwrap());\n }\n\n if dfs(0, °rees) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "ac52c7976a31cbbab31c4c63f8430ecb", "src_uid": "01b50fcba4185ceb1eb8e4ba04a0cc10", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn main() {\n let rotate_count = readln!(usize);\n let rotates = {\n let mut rotates = Vec::new();\n for rotate in 0..rotate_count {\n rotates.push(readln!(i32));\n }\n rotates\n };\n\n let mut ans = false;\n for mask in 0..(1 << rotate_count) {\n let mut mask = mask;\n let mut sum = 0;\n for rotate in 0..rotate_count {\n if (mask & 1) == 0 {\n sum += rotates[rotate];\n } else {\n sum -= rotates[rotate];\n }\n mask >>= 1;\n }\n\n if sum % 360 == 0 {\n ans = true;\n break;\n }\n }\n\n println!(\"{}\", if ans { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "c0a10f22a4b450a024c45719e665696c", "src_uid": "01b50fcba4185ceb1eb8e4ba04a0cc10", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap,BTreeSet};\n#[allow(unused_imports)]\nuse std::ops::*;\n#[allow(unused_imports)]\nuse std::collections::BinaryHeap;\n\n#[allow(unused_macros)]\nmacro_rules! ite {\n ($c:expr, $t:expr, $f:expr) => {{\n if $c { $t } else { $f }\n }};\n}\n\n// ref: tanakh \n// diff: using Parser\n#[macro_export]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut parser = Parser::from_str($s);\n input_inner!{parser, $($r)*}\n };\n (parser = $parser:ident, $($r:tt)*) => {\n input_inner!{$parser, $($r)*}\n };\n (new_stdin_parser = $parser:ident, $($r:tt)*) => {\n let stdin = std::io::stdin();\n let reader = std::io::BufReader::new(stdin.lock());\n let mut $parser = Parser::new(reader);\n input_inner!{$parser, $($r)*}\n };\n ($($r:tt)*) => {\n input!{new_stdin_parser = parser, $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! input_inner {\n ($parser:ident) => {};\n ($parser:ident, ) => {};\n ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($parser, $t);\n input_inner!{$parser $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($parser:ident, ( $($t:tt),* )) => {\n ( $(read_value!($parser, $t)),* )\n };\n ($parser:ident, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($parser, $t)).collect::>()\n };\n ($parser:ident, chars) => {\n read_value!($parser, String).chars().collect::>()\n };\n ($parser:ident, usize1) => {\n read_value!($parser, usize) - 1\n };\n ($parser:ident, $t:ty) => {\n $parser.next::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n n: usize,\n xs: [i64; n],\n }\n for bits in 0..1<\n// ref: wariuni \n// diff: using std::io::BufRead::fill_buf()\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\n\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\n\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len,complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n (len, buf2[len-1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n }\n else {\n self.update_buf();\n }\n }\n }\n}\n\nuse std::fmt::Display;\n#[allow(dead_code)]\nfn write_vec(xs: &Vec) {\n if xs.len() == 0 {\n println!();\n return;\n }\n print!(\"{}\", xs[0]);\n for i in 1..xs.len() {\n print!(\" {}\", xs[i]);\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "75ce7090c385fffa38ac092df629f10e", "src_uid": "01b50fcba4185ceb1eb8e4ba04a0cc10", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut cin = io::Input::new();\n\n let n: i32 = cin.next();\n let mut v = Vec::new();\n\n for _ in 0..n {\n let x: i32 = cin.next();\n v.push(x);\n }\n\n println!(\"{}\", match f(0, &v, 0) {\n false => \"NO\",\n true => \"YES\"\n });\n}\n\nfn f(sum: i32, v: &Vec, curr: usize) -> bool {\n if curr == v.len() {\n sum % 360 == 0\n } else {\n f(sum + v[curr], &v, curr + 1) || f(sum - v[curr], &v, curr + 1)\n }\n}\n\n#[allow(unused)]\npub mod io {\n\n const BUFFER_SIZE: usize = 8192;\n\n use std::collections::VecDeque;\n use std::str::FromStr;\n use std::io;\n use std::io::Read;\n\n type AsciiStr = Vec;\n\n pub struct Input {\n token_buffer: VecDeque,\n remaining: String,\n }\n\n impl Input {\n\n pub fn new() -> Input {\n Input {\n token_buffer: VecDeque::with_capacity(100),\n remaining: String::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where T::Err: ::std::fmt::Debug\n {\n self.fill_buffer();\n self.token_buffer.pop_front().unwrap().parse().unwrap()\n }\n\n pub fn next_ascii_string(&mut self) -> AsciiStr {\n self.fill_buffer();\n Vec::from(self.token_buffer.pop_front().unwrap().as_bytes())\n }\n\n fn fill_buffer(&mut self) {\n while self.token_buffer.is_empty() {\n let mut minibuffer = [0u8; BUFFER_SIZE];\n let size = io::stdin().read(&mut minibuffer[..]).unwrap();\n\n self.remaining += &String::from_utf8_lossy(&minibuffer[..size]);\n\n if self.remaining.trim().len() > 0 {\n for token in self.remaining.trim().split_whitespace() {\n self.token_buffer.push_back(String::from(token))\n }\n\n if size > 0 && ! self.remaining.ends_with(|c: char|char::is_ascii_whitespace(&c)) {\n self.remaining = self.token_buffer.pop_back().unwrap();\n } else {\n self.remaining.clear();\n }\n\n } else if size == 0 {\n panic!(\"EOF\");\n }\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "1a4d2b03a3eaf5289a937a0c18dde35b", "src_uid": "01b50fcba4185ceb1eb8e4ba04a0cc10", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn check(sum: i32, list: &[i32]) -> bool {\n if list.is_empty() {\n sum % 360 == 0\n } else {\n check(sum + list[0], &list[1..]) || check(sum - list[0], &list[1..])\n }\n}\n\nfn main() {\n let n: usize = {\n let mut read_buf = String::new();\n io::stdin().read_line(&mut read_buf).unwrap();\n read_buf.trim().parse().unwrap()\n };\n\n let degrees: Vec = {\n let mut res: Vec = Vec::new();\n for _ in 0..n {\n let mut read_buf = String::new();\n io::stdin().read_line(&mut read_buf).unwrap();\n res.push(read_buf.trim().parse().unwrap());\n }\n res\n };\n\n if check(0, °rees) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "bf054443473bb3bdd2a5a69b034042b6", "src_uid": "01b50fcba4185ceb1eb8e4ba04a0cc10", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, StdoutLock, Write};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_macros)]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n#[allow(dead_code)]\npub fn with_bufwriter) -> ()>(f: F) {\n let out = stdout();\n let writer = BufWriter::new(out.lock());\n f(writer)\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) } ; }\n#[allow(dead_code)]\nfn main() {\n input!{\n n: usize,\n a: [i64; n],\n }\n let mut can = false;\n for bit in 0..1< = Vec::new();\n\tlet mut status: bool = false;\n\n for _i in 0..n {\n \tlet mut value = String::new();\n \tio::stdin().read_line(&mut value).expect(\"failed to read input.\");\n\t\tangles.push(value.trim().parse().expect(\"invalid input\"));\n\t}\n\n for t in 0..(1 << n) {\n let mut s: i32 = 0;\n\n\n \tfor k in 0..n {\n \t\tlet angle = angles[k as usize] as i32;\n\t\t\tif (t & (1 << k)) != 0 {\n\t\t\t\ts = s + angle ;\n\t\t\t} else {\n\t\t\t\ts = s - angle;\n\t\t\t}\n \t}\n if s % 360 == 0 {\n status = true;\n }\n }\n\n\tif status { \n\t\tprintln!(\"{}\", \"YES\");\n\t} else {\n\t\tprintln!(\"{}\", \"NO\");\n\t}\n}", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "22d1a7f07e0d625f2dbef7f936576a1c", "src_uid": "01b50fcba4185ceb1eb8e4ba04a0cc10", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn read_line() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).expect(\"Failed to read a line\");\n buf\n}\n\npub fn main() {\n let line = read_line();\n let mut iter = line.trim().split_whitespace().map(|x| x.parse::().unwrap());\n let w = iter.next().unwrap();\n let h = iter.next().unwrap();\n let mut result: u64 = 1;\n for _ in 0..w + h {\n result *= 2;\n result %= 998244353;\n }\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "combinatorics"], "code_uid": "85338e715d8171c22eaa56ce646bba40", "src_uid": "8b2a9ae21740c89079a6011a30cd6aee", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let h = get!(usize);\n let w = get!(usize);\n let p = 998244353;\n let mut ans = 4;\n for i in 1 .. w {\n ans = (ans * 2) % p;\n }\n for j in 1 .. h {\n ans = (ans * 2) % p;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "combinatorics"], "code_uid": "879305e71a69b6e41c70fdaa7cef4ae5", "src_uid": "8b2a9ae21740c89079a6011a30cd6aee", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn pow_mod(base : u64, mut exp : u64, md : u64) -> u64 {\n if exp == 0 {\n return 1;\n }\n\n let mut bin : Vec = Vec::with_capacity(64);\n while exp != 0 {\n bin.push(exp & 1u64 == 1);\n exp >>= 1;\n }\n bin.pop();\n\n bin.iter().rev().fold(base, |acc, &x| if x { (((acc * acc) % md) * base) % md } else { (acc * acc) % md })\n}\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let mut buffer_iter = buffer.split_whitespace();\n let w: u64 = buffer_iter.next().unwrap().parse().unwrap();\n let h: u64 = buffer_iter.next().unwrap().parse().unwrap();\n\n println!(\"{}\", pow_mod(2, w + h, 998244353));\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "combinatorics"], "code_uid": "86846ea5279691245a0e0f19dfb30e0d", "src_uid": "8b2a9ae21740c89079a6011a30cd6aee", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n#[allow(unused_imports)]\nuse std::io::{stdout, stdin, BufWriter, Write};\n\nfn main() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n\n const MOD: u64 = 998244353;\n\n\n input!{\n w: usize,\n h: usize,\n }\n\n let mut ans = 4;\n for _ in 0..w-1 {\n ans *= 2;\n ans %= MOD;\n }\n for _ in 0..h-1 {\n ans *= 2;\n ans %= MOD;\n }\n puts!(\"{}\\n\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "combinatorics"], "code_uid": "daa08a78e9e76a3a9699b578c9055a93", "src_uid": "8b2a9ae21740c89079a6011a30cd6aee", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\n\n//------------------- Start Field\nconst P5: i32 = 998244353;\nconst P6: i64 = P5 as i64;\n#[derive(Debug,Clone,Copy)]\nstruct Field(i32);\n#[allow(dead_code)]\nimpl Field {\n fn new>(a: T) -> Self { Self(Self::cv(a)) }\n fn new_unchecked(a: i32) -> Self { Self(a) }\n fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n fn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n}\nimpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\nimpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\nimpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\nimpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\nimpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\nimpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\nimpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\nuse std::fmt::{Display, Formatter, Result};\nimpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n// impl Default for Field { fn default() -> Self { Field(0) }}\nimpl Default for &Field { fn default() -> Self { &Field(0) }}\nimpl PartialEq for Field { fn eq(&self, a: &Self) -> bool { self.0 == a.0 } }\nimpl PartialOrd for Field { fn partial_cmp(&self, a: &Self) -> Option { Some(self.0.cmp(&a.0)) } }\nimpl Eq for Field {}\nimpl Ord for Field { fn cmp(&self, a: &Self) -> Ordering { self.0.cmp(&a.0) } }\nimpl Sum for Field {\n fn sum(i: I) -> Self where I: Iterator {\n i.fold(Field(0), |a,b| a + b) } }\nimpl<'a> Sum<&'a Self> for Field {\n fn sum(i: I) -> Self where I: Iterator {\n i.fold(Field(0), |a,&b| a + b) } }\nimpl Product for Field {\n fn product(i: I) -> Self where I: Iterator {\n i.fold(Field(1), |a,b| a * b) } }\nimpl<'a> Product<&'a Self> for Field {\n fn product(i: I) -> Self where I: Iterator {\n i.fold(Field(1), |a,&b| a * b) }\n}\n//------------------- End Field\n\n\n\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(a,b = input.i());\n let mut sol = Field(1);\n for _ in 0..a+b {\n sol *= Field(2);\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "combinatorics"], "code_uid": "ea0e6ef1be3851485428413dadeab565", "src_uid": "8b2a9ae21740c89079a6011a30cd6aee", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::collections::{HashSet, HashMap};\nuse std::cmp::{min,max};\nuse std::io::{self, Write};\nuse std::str;\n\nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: Vec::new(), buf_iter: \"\".split_ascii_whitespace() }\n }\n fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\n#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]\npub struct Field {\n pub val: i64,\n}\nimpl Field {\n pub const MOD: i64 = 998_244_353; // 2^23 * 7 * 17 + 1\n\n /// Computes self^exp in O(log(exp)) time\n pub fn pow(mut self, mut exp: u64) -> Self {\n let mut result = Self::from_small(1);\n while exp > 0 {\n if exp % 2 == 1 {\n result = result * self;\n }\n self = self * self;\n exp /= 2;\n }\n result\n }\n /// Computes inverses of 1 to n in O(n) time\n pub fn vec_of_recips(n: i64) -> Vec {\n let mut recips = vec![Self::from(0), Self::from(1)];\n for i in 2..=n {\n let (md, dv) = (Self::MOD % i, Self::MOD / i);\n recips.push(recips[md as usize] * Self::from_small(-dv));\n }\n recips\n }\n /// Computes self^-1 in O(log(Self::MOD)) time\n pub fn recip(self) -> Self {\n self.pow(Self::MOD as u64 - 2)\n }\n /// Avoids the % operation but requires -Self::MOD <= x < Self::MOD\n fn from_small(s: i64) -> Self {\n let val = if s < 0 { s + Self::MOD } else { s };\n Self { val }\n }\n}\nimpl From for Field {\n fn from(val: i64) -> Self {\n // Self { val: val.rem_euclid(Self::MOD) }\n Self::from_small(val % Self::MOD)\n }\n}\nimpl std::ops::Mul for Field {\n type Output = Self;\n fn mul(self, other: Self) -> Self {\n Self::from(self.val * other.val)\n }\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n \n let w = scan.token::();\n let h = scan.token::();\n let ans = Field::from(2).pow(w + h);\n writeln!(out, \"{}\", ans.val).ok();\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "combinatorics"], "code_uid": "72b707ff9fbebda9b86ec1db61974b21", "src_uid": "8b2a9ae21740c89079a6011a30cd6aee", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scanner<'a, T: std::io::Read> {\n reader: &'a mut T,\n buffer: [u8; 4096],\n position: usize,\n size: usize\n}\n\nimpl<'a, T: std::io::Read> Scanner<'a, T> {\n const SPACES: [i32; 4] = [\n ' ' as i32,\n '\\n' as i32,\n '\\t' as i32,\n '\\r' as i32];\n const ZERO: i32 = '0' as i32;\n const NINE: i32 = '9' as i32;\n const NEG: i32 = '-' as i32;\n\n fn new(reader: &'a mut T) -> Scanner<'a, T> {\n Scanner {\n reader,\n buffer: [0; 4096],\n position: 0,\n size: 0\n }\n }\n\n fn read_block(&mut self) {\n self.size = self.reader.read(&mut self.buffer).unwrap();\n self.position = 0;\n }\n\n fn read_char(&mut self) -> i32 {\n if self.position >= self.size {\n self.read_block();\n if self.position >= self.size {\n return -1;\n }\n }\n \n let ch = self.buffer[self.position];\n self.position += 1;\n \n ch as i32\n }\n\n fn read_int(&mut self) -> Option {\n let mut ch = self.read_char();\n while ch != -1 && Scanner::::SPACES.contains(&ch) {\n ch = self.read_char();\n }\n\n if ch == -1 {\n return None;\n }\n\n let mut negative = false;\n if ch == Scanner::::NEG {\n negative = true;\n ch = self.read_char();\n }\n\n let mut result = 0;\n while ch != -1 && ch >= Scanner::::ZERO && ch <= Scanner::::NINE {\n result = result * 10 + ch - Scanner::::ZERO;\n ch = self.read_char();\n }\n\n Some(if negative {\n -result\n } else {\n result\n })\n }\n\n fn read_str(&mut self) -> String {\n let mut ch = self.read_char();\n while ch != -1 && Scanner::::SPACES.contains(&ch) {\n ch = self.read_char();\n }\n \n let mut s = String::new();\n while !Scanner::::SPACES.contains(&ch) {\n s.push(std::char::from_u32(ch as u32).unwrap());\n ch = self.read_char();\n }\n \n return s;\n }\n}\n\nconst MOD: i64 = 998244353i64;\n\nfn main() {\n let mut stdin = std::io::stdin();\n let mut reader = Scanner::new(&mut stdin);\n \n let w = reader.read_int().unwrap();\n let h = reader.read_int().unwrap();\n\n // dp[i][j] = dp[i][j - 1] * 2 = dp[i - 1][j] * 2\n let mut dp = vec![vec![0i64; (w + 1) as usize]; (h + 1) as usize];\n dp[1][1] = 4;\n\n for j in 2..=w as usize {\n dp[1][j] = dp[1][j - 1] * 2 % MOD;\n }\n for i in 2..=h as usize {\n dp[i][1] = dp[i - 1][1] * 2 % MOD;\n }\n \n for i in 2..=h as usize {\n for j in 2..=w as usize {\n dp[i][j] = dp[i][j - 1] * 2 % MOD;\n }\n }\n\n println!(\"{}\", dp[h as usize][w as usize]);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "combinatorics"], "code_uid": "beaa925b599c652794b89ca0e80ba70f", "src_uid": "8b2a9ae21740c89079a6011a30cd6aee", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::prelude::*;\n\nfn main() {\n let l1 = read_line_iter(); //Se lee cada una de las lineas del tablero\n let l2 = read_line_iter();\n let l3 = read_line_iter();\n let l4 = read_line_iter();\n let l5 = read_line_iter();\n let l6 = read_line_iter();\n let l7 = read_line_iter();\n let l8 = read_line_iter();\n\n let L1 = l1.as_bytes(); //Se convierten para poder leerse letra a letra\n let L2 = l2.as_bytes();\n let L3 = l3.as_bytes();\n let L4 = l4.as_bytes();\n let L5 = l5.as_bytes();\n let L6 = l6.as_bytes();\n let L7 = l7.as_bytes();\n let L8 = l8.as_bytes();\n\n let mut white = 0; //Puntaje total de cada jugador\n let mut black = 0;\n\n for i in 0..8{ //Recorre la linea letra a letra\n match L1[i] as char{ //Asigna el puntaje correspondiente a cada jugador\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{ //Se repite lo mismo que en lo anterior para la siguiente linea\n match L2[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L3[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L4[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L5[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L6[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L7[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L8[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n let advantage = white-black; //Calcula la diferencia de puntaje\n match advantage{\n 1..=576 => println!(\"White\"),//Si es positiva va ganando blanco\n -576..=-1 => println!(\"Black\"), //Si es negativa va ganando negro\n _ => println!(\"Draw\"), //En otro caso se considera empate\n }\n \n}\n\nfn read_line_iter() -> String { //Funcion para recibir inputs y convertirlos en strings (Fuente: https://subscription.packtpub.com/book/application_development/9781788623926/1/ch01lvl1sec23/reading-from-stdin)\n let stdin = io::stdin();\n // Read one line of input iterator-style\n let input = stdin.lock().lines().next();\n input\n .expect(\"No lines in buffer\")\n .expect(\"Failed to read line\")\n .trim()\n .to_string()\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2f5075b98fb046f7a1e3ab3e01ff6920", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn calcular_linea(line: String, tipo: i32) -> i32{\n let mut total = 0;\n for c in line.chars(){\n if tipo == 0 {\n match c{\n 'Q' => total += 9,\n 'R' => total += 5,\n 'B' => total += 3,\n 'N' => total += 3,\n 'P' => total += 1,\n _ => (),\n };\n }\n else {\n match c{\n 'q' => total += 9,\n 'r' => total += 5,\n 'b' => total += 3,\n 'n' => total += 3,\n 'p' => total += 1,\n _ => (),\n };\n }\n }\n total\n}\n\nfn main() {\n let mut total_black = 0;\n let mut total_white = 0;\n\n for i in 0..8{\n let mut input = String::new();\n io::stdin().read_line(&mut input);\n let mut input2 = input.clone();\n total_white += calcular_linea(input, 0);\n total_black += calcular_linea(input2, 1);\n }\n \n if total_black > total_white {\n println!(\"Black\");\n }\n else if total_black == total_white {\n println!(\"Draw\");\n }\n else {\n println!(\"White\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "28542bcbc910f1f20e6fc8f8fb8645f7", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn add_from_input(input: String) -> (i32, i32) {\n let mut w :i32 = 0;\n let mut b :i32 = 0;\n for c in input.chars() {\n match c {\n 'Q' => w += 9,\n 'R' => w += 5,\n 'B' | 'N' => w += 3,\n 'P' => w += 1,\n 'q' => b += 9,\n 'r' => b += 5,\n 'b' | 'n' => b += 3,\n 'p' => b += 1,\n _ => (),\n }\n }\n (w, b)\n}\n\nfn main(){\n let mut input = String::new();\n for _t in 0..8 {\n std::io::stdin().read_line(&mut input).unwrap();\n }\n let w_b = add_from_input((*input).to_string());\n if w_b.0 > w_b.1 {\n println!(\"White\");\n } else if w_b.0 < w_b.1 {\n println!(\"Black\");\n } else {\n println!(\"Draw\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "77ad9fc6592d0eefd96184e80186f70c", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn board_calc(mut sc: i32, piece: char) -> i32 {\n\tmatch piece {\n\t 'Q' => sc += 9,\n\t 'q' => sc -= 9,\n\t 'R' => sc += 5,\n\t 'r' => sc -= 5,\n\t 'B' | 'N' => sc += 3,\n\t 'b' | 'n' => sc -= 3,\n\t 'P' => sc += 1,\n\t 'p' => sc -= 1,\n\t _ => sc += 0\n\t};\n\tsc\n}\n\nfn main() {\n let mut inputnum = 0;\n\tlet mut board = String::new();\n\twhile inputnum < 8 {\n\t let mut input = String::new();\n\t io::stdin().read_line(&mut input).unwrap();\n\t board.push_str(&input);\n\t inputnum += 1;\n\t}\n\t\n let mut score = 0;\n\tfor cell in board.chars() {\n\t score = board_calc(score, cell);\n\t}\n\t\n\tlet winner = match score {\n\t 1..=576 => \"White\",\n\t 0 => \"Draw\",\n\t _ => \"Black\"\n\t};\n\t\n println!(\"{}\", winner);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "63f949ecc186a4cc44929971c43874de", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn contar_negras (vector_c: &Vec) -> i32 {\n let mut negras: i32 = 0;\n\n for caracter in vector_c{\n match caracter{\n 'q' => negras +=9,\n 'r' => negras +=5,\n 'b' => negras +=3,\n 'n' => negras +=3,\n 'p' => negras +=1,\n _ => negras +=0,\n }\n }\n negras\n}\n\nfn contar_blancas (vector_c: &Vec) -> i32 {\n let mut blancas: i32 = 0;\n\n for caracter in vector_c{\n match caracter{\n 'Q' => blancas +=9,\n 'R' => blancas +=5,\n 'B' => blancas +=3,\n 'N' => blancas +=3,\n 'P' => blancas +=1,\n _ => blancas +=0,\n }\n }\n blancas\n}\n\n\n\nfn main() {\n use std::io::{stdin};\n let mut blanco :i32 = 0;\n let mut negro :i32 = 0;\n let mut s=String::new();\n for _ in 0..8{\n stdin().read_line(&mut s).expect(\"Error\");\n let char_vec: Vec = s.chars().collect();\n negro = contar_negras(&char_vec);\n blanco = contar_blancas(&char_vec);\n }\n if blanco > negro {\n println!(\"White\");\n } else if blanco == negro{\n println!(\"Draw\");\n } else {\n println!(\"Black\")\n }\n //println!(\"{}, {}\",negro, blanco);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2ba4c46a1bd076fc63fca8e3b02713c4", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::prelude::*;\n\nfn main() {\n let l1 = read_line_iter();\n let l2 = read_line_iter();\n let l3 = read_line_iter();\n let l4 = read_line_iter();\n let l5 = read_line_iter();\n let l6 = read_line_iter();\n let l7 = read_line_iter();\n let l8 = read_line_iter();\n\n let L1 = l1.as_bytes();\n let L2 = l2.as_bytes();\n let L3 = l3.as_bytes();\n let L4 = l4.as_bytes();\n let L5 = l5.as_bytes();\n let L6 = l6.as_bytes();\n let L7 = l7.as_bytes();\n let L8 = l8.as_bytes();\n\n let mut white = 0;\n let mut black = 0;\n\n //println!(\n // \"L1:{},L2:{},L3:{},L4:{},L5:{},L6:{},L7:{},L8:{}\",\n // l1,l2,l3,l4,l5,l6,l7,l8\n //);\n for i in 0..8{\n match L1[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L2[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L3[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L4[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L5[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L6[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L7[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n for i in 0..8{\n match L8[i] as char{\n 'p' => black += 1,\n 'n' => black += 3,\n 'b' => black += 3,\n 'r' => black += 5,\n 'q' => black += 9,\n 'P' => white += 1,\n 'N' => white += 3,\n 'B' => white += 3,\n 'R' => white += 5,\n 'Q' => white += 9,\n _ => (),\n }\n }\n let advantage = white-black;\n match advantage{\n 1..=576 => println!(\"White\"),\n -576..=-1 => println!(\"Black\"),\n _ => println!(\"Draw\"),\n }\n \n}\n\nfn read_line_iter() -> String {\n let stdin = io::stdin();\n // Read one line of input iterator-style\n let input = stdin.lock().lines().next();\n input\n .expect(\"No lines in buffer\")\n .expect(\"Failed to read line\")\n .trim()\n .to_string()\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d795b85e755f7cee2e922a7f1acdf370", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n\tlet mut puntos = 0;\n\tfor _ in 0..8 {\n\t\tlet mut input = String::new();\n\t\tstd::io::stdin().read_line(&mut input).unwrap();\n\t\tpuntos+=getPuntos(input);\n\t}\n\tif puntos > 0 {\n\t\tprintln!(\"White\");\n\t}\n\telse if puntos < 0 {\n\t\tprintln!(\"Black\");\n\t}\n\telse {\n\t\tprintln!(\"Draw\");\n\t}\n}\n\nfn getPuntos(input :String) -> i32{\n\tlet mut white = 0;\n\tlet mut black = 0;\n\tfor letra in input.chars(){\n\t\tmatch letra {\n\t\t\t'Q' => white+=9,\n\t\t\t'q' => black+=9,\n\t\t\t'R' => white+=5,\n\t\t\t'r' => black+=5,\n\t\t\t'B' | 'N' => white+=3,\n\t\t\t'b' | 'n' => black+=3,\n\t\t\t'P' => white+=1,\n\t\t\t'p' => black+=1,\n\t\t\t_ => {},\n\t\t}\n\t}\n\treturn white-black\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7ed742afafe322317f82db85cf521f35", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::HashMap;\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let mut weights : HashMap = HashMap::new();\n weights.insert(String::from(\"q\"),9);\n weights.insert(String::from(\"r\"),5);\n weights.insert(String::from(\"b\"),3);\n weights.insert(String::from(\"n\"),3);\n weights.insert(String::from(\"p\"),1);\n weights.insert(String::from(\"k\"),0);\n let mut a = String::new();\n for _ in 0..8 {\n a += &readln!();\n }\n let w :i32 = a.chars().filter(|c|c.is_uppercase()).map(|x|x.to_lowercase()).map(|x| {\n let sx : String = x.to_string();\n weights.get(&sx).unwrap()\n }).sum();\n let b :i32 = a.chars().filter(|c|c.is_lowercase()).map(|x|{\n let sx : String = x.to_string();\n weights.get(&sx).unwrap()\n }).sum();\n println!(\"{}\",if w>b { \"White\" } else if w i64 {\n if x < 1200 {\n 1200\n } else if x < 1400 {\n 1400\n } else if x < 1600 {\n 1600\n } else if x < 1900 {\n 1900\n } else if x < 2100 {\n 2100\n } else if x < 2300 {\n 2300\n } else if x < 2400 {\n 2400\n } else if x < 2600 {\n 2600\n } else {\n 3000\n }\n}\n\nfn main() {\n let x: i64 = read();\n // (x + 1).println();\n calc(x).println();\n}\n\nuse std::error;\nuse std::fmt;\nuse std::str::FromStr;\n\n#[non_exhaustive]\n#[derive(Debug, PartialEq)]\npub enum Error {\n MissingMatch,\n MissingClosingBrace,\n UnexpectedValue(u8, Option),\n InvalidUtf8(Vec),\n PartialUtf8(usize, Vec),\n Parse(String, &'static str),\n}\n\nimpl error::Error for Error {}\n\nimpl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n use crate::Error::*;\n use std::str::from_utf8;\n\n match *self {\n InvalidUtf8(ref raw) => write!(f, \"input was not valid utf8: {:?}\", raw),\n Parse(ref s, arg) => write!(f, \"could not parse {} as target type of {}\", s, arg),\n UnexpectedValue(exp, act) => write!(\n f,\n \"found value {:?} not matching the pattern value {}\",\n act.map(|b| b as char),\n exp as char\n ),\n PartialUtf8(n, ref raw) => write!(\n f,\n \"input was only partially valid utf8: \\\"{}\\\" followed by {:?}\",\n from_utf8(&raw[..n]).unwrap(),\n &raw[n..]\n ),\n MissingMatch => write!(f, \"Bad read! format string: did not contain {{}}\"),\n MissingClosingBrace => write!(\n f,\n \"found single open curly brace at the end of the format string\"\n ),\n }\n }\n}\n\npub fn match_next(expected: u8, iter: &mut dyn Iterator) -> Result<(), Error> {\n let next = iter.next();\n if next != Some(expected) {\n return Err(Error::UnexpectedValue(expected, next));\n }\n Ok(())\n}\n\npub fn parse_capture(\n name: &'static str,\n next: Option,\n iter: &mut dyn Iterator,\n) -> Result\nwhere\n T: FromStr,\n ::Err: ::std::fmt::Debug,\n{\n static WHITESPACES: &[u8] = b\"\\t\\r\\n \";\n let raw: Vec = match next {\n Some(c) => iter.take_while(|&ch| ch != c).collect(),\n None => iter\n .skip_while(|ch| WHITESPACES.contains(ch))\n .take_while(|ch| !WHITESPACES.contains(ch))\n .collect(),\n };\n match String::from_utf8(raw) {\n Ok(s) => FromStr::from_str(&s).map_err(|_| Error::Parse(s, name)),\n Err(e) => {\n let n = e.utf8_error().valid_up_to();\n let raw = e.into_bytes();\n if n == 0 {\n Err(Error::InvalidUtf8(raw))\n } else {\n Err(Error::PartialUtf8(n, raw))\n }\n }\n }\n}\n\n#[macro_export]\nmacro_rules! try_read(\n () => { $crate::try_read!(\"{}\") };\n ($text:expr) => {{\n (|| -> std::result::Result<_, $crate::Error> {\n let __try_read_var__;\n $crate::try_scan!($text, __try_read_var__);\n Ok(__try_read_var__)\n })()\n }};\n ($text:expr, $input:expr) => {{\n (|| -> std::result::Result<_, $crate::Error> {\n let __try_read_var__;\n $crate::try_scan!($input => $text, __try_read_var__);\n Ok(__try_read_var__)\n })()\n }};\n);\n\n#[macro_export]\nmacro_rules! try_scan(\n ($pattern:expr, $($arg:expr),*) => {\n use ::std::io::Read;\n $crate::try_scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $pattern, $($arg),*);\n };\n ($input:expr => $pattern:expr, $($arg:expr),*) => {{\n $crate::try_scan!(@impl question_mark; $input => $pattern, $($arg),*)\n }};\n (@question_mark: $($e:tt)+) => {{\n ($($e)+)?\n }};\n (@unwrap: $($e:tt)+) => {{\n ($($e)+).unwrap()\n }};\n (@impl $action:tt; $input:expr => $pattern:expr, $($arg:expr),*) => {{\n #![allow(clippy::try_err)]\n use $crate::{Error, match_next, parse_capture};\n\n // typesafe macros :)\n let pattern: &'static str = $pattern;\n let stdin: &mut dyn Iterator = &mut ($input);\n\n let mut pattern = pattern.bytes();\n\n $(\n $arg = loop {\n match $crate::try_scan!(@$action: pattern.next().ok_or(Error::MissingMatch)) {\n b'{' => match $crate::try_scan!(@$action: pattern.next().ok_or(Error::MissingClosingBrace)) {\n b'{' => $crate::try_scan!(@$action: match_next(b'{', stdin)),\n b'}' => break $crate::try_scan!(@$action: parse_capture(stringify!($arg), pattern.next(), stdin)),\n _ => return $crate::try_scan!(@$action: Err(Error::MissingClosingBrace)),\n },\n c => $crate::try_scan!(@$action: match_next(c, stdin)),\n }\n };\n )*\n\n for c in pattern {\n $crate::try_scan!(@$action: match_next(c, stdin))\n }\n\n format_args!($pattern, $($arg),*);\n }};\n);\n\n#[macro_export]\nmacro_rules! read(\n ($($arg:tt)*) => {\n $crate::try_read!($($arg)*).unwrap()\n };\n);\n\n#[macro_export]\nmacro_rules! scan(\n ($text:expr, $($arg:expr),*) => {\n {\n use ::std::io::Read;\n $crate::scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $text, $($arg),*);\n }\n };\n ($input:expr => $pattern:expr, $($arg:expr),*) => {{\n $crate::try_scan!(@impl unwrap; $input => $pattern, $($arg),*)\n }};\n);\nuse std::marker::PhantomData;\r\nuse std::ops;\r\n\r\n// use text_io::read;\r\n\r\n/*** READ and WRITE ***/\r\n\r\npub trait Readable {\r\n fn read() -> Self;\r\n}\r\n\r\npub trait Printable {\r\n fn print(self: &Self);\r\n fn println(self: &Self) {\r\n self.print();\r\n println!();\r\n }\r\n}\r\n\r\nmacro_rules! impl_rp_simple {\r\n ($($t:ident), +) => {\r\n $(\r\n impl Readable for $t {\r\n fn read() -> Self {\r\n read!()\r\n }\r\n }\r\n\r\n impl Printable for $t {\r\n fn print(self: &Self) {\r\n print!(\"{self} \");\r\n }\r\n }\r\n )+\r\n };\r\n}\r\n\r\nimpl_rp_simple!(\r\n String, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, char\r\n);\r\n\r\nmacro_rules! impl_rp_tuple {\r\n () => {};\r\n ($t0:ident, $($t:ident,) *) => {\r\n impl<$t0: Readable, $($t: Readable), *> Readable for ($t0, $($t,)*) {\r\n fn read() -> Self {\r\n (read(), $(read::<$t>(),)*)\r\n }\r\n }\r\n\r\n impl<$t0: Printable, $($t: Printable), *> Printable for ($t0, $($t,)*) {\r\n fn print(self: &Self) {\r\n #[allow(non_snake_case)]\r\n let (ref $t0, $(ref $t,)*) = &self;\r\n $t0.print();\r\n $(\r\n $t.print();\r\n )*\r\n }\r\n }\r\n\r\n impl_rp_tuple!{$($t,) *}\r\n };\r\n}\r\n\r\nimpl Printable for Vec {\r\n fn print(self: &Self) {\r\n for x in self {\r\n x.print();\r\n }\r\n }\r\n}\r\n\r\nimpl Printable for [T] {\r\n fn print(self: &Self) {\r\n for x in self {\r\n x.print();\r\n }\r\n }\r\n}\r\n\r\nimpl_rp_tuple! {T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,}\r\n\r\npub fn read() -> T {\r\n T::read()\r\n}\r\n\r\npub fn readv(size: usize) -> Vec {\r\n let mut res = Vec::with_capacity(size);\r\n for _ in 0..size {\r\n res.push(read());\r\n }\r\n res\r\n}\r\n\r\npub fn readb() -> Vec {\r\n let s: String = read!();\r\n s.as_bytes().into_iter().cloned().collect()\r\n}\r\n\r\n/*** RECURSIVE LAMBDA ***/\r\n\r\nmacro_rules! recursive_fn {\r\n () => {};\r\n ($name0:ident $trait0:ident $_:ident $__:ident, $($name:ident $trait:ident $Arg:ident $arg:ident,)*) => {\r\n pub trait $trait0<$($Arg,)* Output> {\r\n fn call(&mut self, $($arg: $Arg,)*) -> Output;\r\n }\r\n\r\n pub struct $name0\r\n where\r\n F: FnMut(&mut dyn $trait0<$($Arg,)* Output>, $($Arg,)*) -> Output,\r\n {\r\n f: std::cell::UnsafeCell,\r\n $(\r\n $arg: PhantomData<$Arg>,\r\n )*\r\n phantom_output: PhantomData,\r\n }\r\n\r\n impl $name0\r\n where\r\n F: FnMut(&mut dyn $trait0<$($Arg,)* Output>, $($Arg,)*) -> Output,\r\n {\r\n pub fn new(f: F) -> Self {\r\n Self {\r\n f: std::cell::UnsafeCell::new(f),\r\n $(\r\n $arg: PhantomData,\r\n )*\r\n phantom_output: PhantomData,\r\n }\r\n }\r\n }\r\n\r\n impl $trait0<$($Arg,)* Output> for $name0\r\n where\r\n F: FnMut(&mut dyn $trait0<$($Arg,)* Output>, $($Arg,)*) -> Output,\r\n {\r\n fn call(&mut self, $($arg: $Arg,)*) -> Output {\r\n unsafe { (&mut *self.f.get())(self, $($arg,)*) }\r\n }\r\n }\r\n\r\n recursive_fn!{$($name $trait $Arg $arg,)*}\r\n };\r\n}\r\n\r\nrecursive_fn! {\r\n RecursiveFn11 Callable11 Arg11 arg11,\r\n RecursiveFn10 Callable10 Arg10 arg10,\r\n RecursiveFn9 Callable9 Arg9 arg9,\r\n RecursiveFn8 Callable8 Arg8 arg8,\r\n RecursiveFn7 Callable7 Arg7 arg7,\r\n RecursiveFn6 Callable6 Arg6 arg6,\r\n RecursiveFn5 Callable5 Arg5 arg5,\r\n RecursiveFn4 Callable4 Arg4 arg4,\r\n RecursiveFn3 Callable3 Arg3 arg3,\r\n RecursiveFn2 Callable2 Arg2 arg2,\r\n RecursiveFn1 Callable1 Arg1 arg1,\r\n RecursiveFn0 Callable0 Arg0 arg0,\r\n}\r\n\r\n/*** MOD ***/\r\n\r\n// gcd, x, y\r\npub fn extended_gcd(a: i64, b: i64) -> (i64, i64, i64) {\r\n if a == 0 {\r\n (b, 0, 1)\r\n } else {\r\n let (g, y, mut x) = extended_gcd(b % a, a);\r\n x -= (b / a) * y;\r\n (g, x, y)\r\n }\r\n}\r\n\r\npub trait HasConstVal {\r\n const VAL: i64;\r\n}\r\n\r\n// const of V has to be prime\r\n#[derive(Copy, Clone, Eq, PartialEq)]\r\npub struct ModBase {\r\n v: i64,\r\n phantom: PhantomData,\r\n}\r\n\r\nimpl ModBase {\r\n pub fn new(mut v: i64) -> Self {\r\n v %= M::VAL;\r\n if v < 0 {\r\n v = v + M::VAL;\r\n }\r\n Self {\r\n v,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n pub fn inv(&self) -> Self {\r\n let (_, x, _) = extended_gcd(self.v, M::VAL);\r\n Self::new(x)\r\n }\r\n\r\n pub fn pow(&self, n: usize) -> Self {\r\n let v = self.v;\r\n let mut res = Self::new(1);\r\n for _ in 0..n {\r\n res *= v;\r\n }\r\n res\r\n }\r\n}\r\n\r\nimpl ops::Add for ModBase {\r\n type Output = Self;\r\n\r\n fn add(self, rhs: i64) -> Self {\r\n Self::new(self.v + rhs)\r\n }\r\n}\r\n\r\nimpl ops::Add for ModBase {\r\n type Output = Self;\r\n\r\n fn add(self, rhs: Self) -> Self {\r\n Self::new(self.v + rhs.v)\r\n }\r\n}\r\n\r\nimpl ops::AddAssign for ModBase {\r\n fn add_assign(&mut self, rhs: i64) {\r\n self.v = (self.v + rhs) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::AddAssign for ModBase {\r\n fn add_assign(&mut self, rhs: Self) {\r\n self.v = (self.v + rhs.v) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::Sub for ModBase {\r\n type Output = Self;\r\n\r\n fn sub(self, rhs: i64) -> Self {\r\n Self::new(self.v - rhs)\r\n }\r\n}\r\n\r\nimpl ops::Sub for ModBase {\r\n type Output = Self;\r\n\r\n fn sub(self, rhs: Self) -> Self {\r\n Self::new(self.v - rhs.v)\r\n }\r\n}\r\n\r\nimpl ops::SubAssign for ModBase {\r\n fn sub_assign(&mut self, rhs: i64) {\r\n self.v = (self.v - rhs) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::SubAssign for ModBase {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n self.v = (self.v - rhs.v) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::Mul for ModBase {\r\n type Output = Self;\r\n\r\n fn mul(self, rhs: i64) -> Self::Output {\r\n Self::new(self.v * rhs)\r\n }\r\n}\r\n\r\nimpl ops::Mul for ModBase {\r\n type Output = Self;\r\n\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::new(self.v * rhs.v)\r\n }\r\n}\r\n\r\nimpl ops::MulAssign for ModBase {\r\n fn mul_assign(&mut self, rhs: i64) {\r\n self.v = self.v * rhs % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::MulAssign for ModBase {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n self.v = self.v * rhs.v % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::Div for ModBase {\r\n type Output = Self;\r\n\r\n fn div(self, rhs: i64) -> Self::Output {\r\n self * Self::new(rhs).inv()\r\n }\r\n}\r\n\r\nimpl ops::Div for ModBase {\r\n type Output = Self;\r\n\r\n fn div(self, rhs: Self) -> Self::Output {\r\n self * rhs.inv()\r\n }\r\n}\r\n\r\nimpl ops::DivAssign for ModBase {\r\n fn div_assign(&mut self, rhs: i64) {\r\n self.v = (Self::new(self.v) / rhs).v;\r\n }\r\n}\r\n\r\nimpl ops::DivAssign for ModBase {\r\n fn div_assign(&mut self, rhs: Self) {\r\n self.v = (Self::new(self.v) / rhs).v;\r\n }\r\n}\r\n\r\nimpl ops::Neg for ModBase {\r\n type Output = Self;\r\n\r\n fn neg(self) -> Self::Output {\r\n Self::new(-self.v)\r\n }\r\n}\r\n\r\nimpl ops::Deref for ModBase {\r\n type Target = i64;\r\n\r\n fn deref(&self) -> &Self::Target {\r\n &self.v\r\n }\r\n}\r\n\r\n#[macro_export]\r\nmacro_rules! Mod {\r\n ($val: expr) => {\r\n Mod!(Mod, ModV, $val);\r\n };\r\n ($name: ident, $v_name: ident, $val: expr) => {\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n pub struct $v_name {}\r\n\r\n impl crate::HasConstVal for $v_name {\r\n const VAL: i64 = $val as i64;\r\n }\r\n\r\n type $name = ModBase<$v_name>;\r\n };\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "divide and conquer", "implementation"], "code_uid": "90175c35290fa56aab75d976b73cd4f5", "src_uid": "22725effa6dc68b9c2a499d148e613c2", "difficulty": -1, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn gcd(a: u64, b: u64) -> u64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u64 = scan.token();\n let ans: u64;\n if n == 1 {\n ans = 1;\n } else if n == 2 {\n ans = 2;\n } else if n == 3 {\n ans = 6;\n } else if n % 2 == 0 {\n let a = n - 1;\n let b = n - 2;\n let c = n - 3;\n ans = a * b * c;\n } else {\n let a = n;\n let b = n - 1;\n let c = n - 2;\n ans = a * b * c;\n }\n\n // pick n and n - 1, find another number coprime to both\n let mut ans2 = n * (n - 1);\n for p in (1..(n + 1)).rev() {\n if gcd(n, p) == 1 && gcd(n - 1, p) == 1 {\n ans2 *= p;\n break;\n }\n }\n\n writeln!(out, \"{}\", ans.max(ans2)).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "number theory"], "code_uid": "6e64357899e846979cc1f6ff9218640d", "src_uid": "25e5afcdf246ee35c9cef2fcbdd4566e", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[macro_export]\nmacro_rules ! chmax { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: max ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! chmin { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: min ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! max { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: max ( $ x , max ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! min { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: min ( $ x , min ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! dvec { ( $ t : expr ; $ len : expr ) => { vec ! [ $ t ; $ len ] } ; ( $ t : expr ; $ len : expr , $ ( $ rest : expr ) ,* ) => { vec ! [ dvec ! ( $ t ; $ ( $ rest ) ,* ) ; $ len ] } ; }\n#[macro_export]\nmacro_rules ! cfor { ( ; $ ( $ rest : tt ) * ) => { cfor ! ( ( ) ; $ ( $ rest ) * ) } ; ( $ ( $ init : stmt ) ,+; ; $ ( $ rest : tt ) * ) => { cfor ! ( $ ( $ init ) ,+; ! false ; $ ( $ rest ) * ) } ; ( $ ( $ init : stmt ) ,+; $ cond : expr ; ; $ body : block ) => { cfor ! { $ ( $ init ) ,+; $ cond ; ( ) ; $ body } } ; ( $ ( $ init : stmt ) ,+; $ cond : expr ; $ ( $ step : expr ) ,+; $ body : block ) => { { $ ( $ init ; ) + while $ cond { let mut _first = true ; let mut _continue = false ; loop { if ! _first { _continue = true ; break } _first = false ; $ body } if ! _continue { break } $ ( $ step ; ) + } } } ; }\n#[doc = \" main\"]\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\n#[macro_export]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\nuse std::io;\nuse std::io::BufRead;\nuse std::str;\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len, complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n if len == 0 {\n break;\n }\n (len, buf2[len - 1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n } else {\n self.update_buf();\n }\n }\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\nconst BIG_STACK_SIZE: bool = true;\n#[allow(dead_code)]\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\nfn solve() {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n input!{\n n: i64,\n }\n let mut tot = 0;\n let mut n = n;\n while n%2 == 1 {\n let pd = prime_decomposition(n);\n let mut primes = vec![];\n for k in pd.keys() {\n primes.push(k);\n }\n primes.sort();\n let minp = primes[0];\n n -= minp;\n tot += 1;\n }\n tot += n/2;\n writeln!(out,\"{}\",tot);\n}\n#[doc = \"O(root(N))\"]\nfn prime_decomposition(n: i64) -> std::collections::HashMap {\n fn root_int(n: i64) -> i64 {\n let mut d = 1;\n while d * d <= n {\n d += 1;\n }\n d - 1\n }\n let mut n = n;\n let mut m = std::collections::HashMap::new();\n for i in 2..root_int(n) + 1 {\n while n % i == 0 {\n if !m.contains_key(&i) {\n m.insert(i, 0);\n }\n *m.get_mut(&i).unwrap() += 1;\n n /= i;\n }\n }\n if n != 1 {\n m.insert(n, 1);\n }\n m\n}", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "128af6c229fc7be3abb35dd3f41ec94f", "src_uid": "a1e80ddd97026835a84f91bac8eb21e6", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn main() {\n let num = readln!(i64);\n\n println!(\"{}\", if num % 2 != 0 {\n let mut div = 3;\n let end = (num as f64).sqrt() as i64 + 1;\n loop {\n if num % div == 0 {\n break;\n }\n if div >= end {\n div = num;\n break;\n }\n div += 1;\n }\n 1 + (num - div) / 2\n } else {\n num / 2\n });\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "35feac1ad395c51c77083d4ee4963d14", "src_uid": "a1e80ddd97026835a84f91bac8eb21e6", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn get_mpf(n: u64) -> u64 {\n let mut d = 2;\n while d * d <= n {\n if n % d == 0 {\n return d;\n }\n d += 1;\n }\n n\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u64 = scan.token();\n let mpf = get_mpf(n);\n let ans;\n if mpf % 2 != 0 {\n if n == mpf {\n ans = 1;\n } else {\n ans = 1 + (n - mpf) / get_mpf(n - mpf);\n }\n } else {\n ans = n / mpf;\n }\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "bba244abe847c2f82f2257e83849e7f7", "src_uid": "a1e80ddd97026835a84f91bac8eb21e6", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nuse std::io::*;\nuse std::str::FromStr;\nuse std::char::*;\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:i64 = 1000000009;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n flag: bool,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n flag: true,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n self.f[crt] = true;\n self.c = self.e[crt].len() as i64;\n if self.c != 2 {\n self.flag = false;\n }\n\n for i in 0..self.e[crt].len() {\n let v = self.e[crt][i];\n if self.f[v] { continue; }\n self.dfs(v);\n }\n }\n}\n\nfn binary_search(s: &Vec, v:i64) -> usize {\n let mut left = 0;\n let mut right = s.len();\n\n while right-left > 1 {\n let mid = (right+left)/2;\n //debug!(left,mid,right,s[mid]);\n if s[mid] < v { left = mid; }\n else { right = mid; }\n }\n left\n}\n\nfn neighbors(tree: &BTreeSet, val: usize) -> (Option<&usize>, Option<&usize>) {\n use std::ops::Bound::*;\n\n let mut before = tree.range((Unbounded, Excluded(val)));\n let mut after = tree.range((Excluded(val), Unbounded));\n\n (before.next_back(), after.next())\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n\nconst MAX_A:i64 = 1e16 as i64;\n\nfn gcd(a:i64, b:i64) -> i64 {\n if b==0 {return a;}\n gcd(b, a%b)\n}\n\nstruct BIT {\n n: usize,\n bit: Vec,\n}\n\nimpl BIT {\n fn new(n:usize) -> BIT {\n BIT {\n n,\n bit: vec![0;n+1],\n }\n }\n\n fn add(&mut self, a:usize, w:i64) {\n let mut x = a;\n while x <= self.n {\n self.bit[x] += w;\n x += (x as i64 & -(x as i64)) as usize;\n }\n }\n\n fn sum(&self, a:usize) -> i64 {\n let mut ret = 0;\n let mut x = a as i64;\n while x > 0 {\n ret += self.bit[x as usize];\n x -= x & -x;\n }\n ret\n }\n}\n\nfn prime_factor(n: i64) -> BTreeMap {\n let mut n = n;\n let mut map = BTreeMap::new();\n let mut i = 2;\n while i*i <= n {\n while n%i == 0 {\n let count = map.entry(i).or_insert(0);\n *count += 1;\n n /= i;\n }\n i += 1;\n }\n if n!=1 { map.insert(n,1); }\n map\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n\n input! {\n n: i64,\n }\n\n let mut n = n;\n let fac = prime_factor(n);\n let d = *fac.iter().next().unwrap().0;\n //debug!(d);\n let mut ans = 0;\n if d != 2 {\n n -= d;\n ans += 1;\n }\n //debug!(d,n);\n puts!(\"{}\\n\", ans+n/2);\n}\n\n/*\n\nn \u304b\u3089\u6700\u5c0f\u306e\u7d20\u6570\u306e\u7d04\u6570\u3092\u5f15\u3044\u3066\u3044\u304f\u3001\u4f55\u56de\u64cd\u4f5c\u304c\u3067\u304d\u308b\u304b\u3002\n\n34, 32, 30, 28, .., 2, 0\n31, 0\n6, 4, 2, 0\n10, 8, 6, 4,\n9, 6, 4, 2, 0\n25, 20, 18, 16, 14, 12, 10\n3*3 -> 3*2 -> 2*2 -> 2*1 -> 2*0\n5*5 -> 10*2 (5*4) -> 9*2 -> 8*2 -> .. -> 1*2 -> 0*2\n3*3*3 (3*9) -> 3*8 (2*12) -> 2*11 -> .. -> 2*0\n\n\u7d20\u56e0\u6570\u5206\u89e3\u3059\u308b\u3002\u6700\u5c0f\u306e\u7d04\u6570\u304c\uff12\u3058\u3083\u306a\u3044\u306a\u3089\u3001\u305d\u308c\u3067\u5f15\u304f\u3002\n\u6b21\u306e\u6570\u5b57\u306f\u5fc5\u305a\u6700\u5c0f\u306e\u7d20\u6570\u306e\u7d04\u6570\u304c\uff12\u306b\u306a\u308b\u306e\u3067\u7b54\u3048\u306b\uff12\u3067\u5272\u3063\u305f\u6570\u3092\u8db3\u3059\u3002\n\n*/\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "d2871210da31e071a2d1a47b19942c4a", "src_uid": "a1e80ddd97026835a84f91bac8eb21e6", "difficulty": 1200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n let r0 = it.next().unwrap();\n let n = r0.len();\n let r1 = it.next().unwrap();\n\n #[derive(Clone, Copy, Debug)]\n enum Cell {\n Empty,\n Pawn,\n }\n\n let mut grid: Vec<_> = r0.chars().chain(r1.chars()).map(|c| {\n match c {\n '0' => Cell::Empty,\n 'X' => Cell::Pawn,\n _ => panic!(\"Oops!\"),\n }\n }).collect();\n\n let f = |c| {\n match c {\n Cell::Empty => 1,\n Cell::Pawn => 0,\n }\n };\n\n let cnt = |c, grid: &[Cell]| {\n f(grid[c]) + f(grid[n + c])\n };\n\n let mut ans = 0;\n for c in 0..n {\n if cnt(c, &grid) == 2 {\n if c > 0 && cnt(c - 1, &grid) == 1 {\n grid[c] = Cell::Pawn;\n grid[n + c] = Cell::Pawn;\n ans += 1;\n } else if c + 1 < n {\n if let Cell::Empty = grid[c + 1] {\n grid[c + 1] = Cell::Pawn;\n grid[c] = Cell::Pawn;\n grid[n + c] = Cell::Pawn;\n ans += 1;\n } else if let Cell::Empty = grid[n + c + 1] {\n grid[n + c + 1] = Cell::Pawn;\n grid[c] = Cell::Pawn;\n grid[n + c] = Cell::Pawn;\n ans += 1;\n }\n }\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "137a98247510a0386ee7c8af7ec5396f", "src_uid": "e6b3e787919e96fc893a034eae233fc6", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 991D\nuse std::io;\n\nfn main() {\n let mut a = String::new();\n io::stdin().read_line(&mut a).unwrap();\n let a = a.trim();\n let mut b = String::new();\n io::stdin().read_line(&mut b).unwrap();\n let b = b.trim();\n let mut v: Vec = Vec::with_capacity(a.len());\n for (p, q) in a.chars().zip(b.chars()) {\n let mut slots = if p == '0' { 1 } else { 0 } + if q == '0' { 1 } else { 0 };\n v.push(slots);\n }\n let mut bishwocks = 0;\n for i in 0..v.len() {\n if v[i] == 2 {\n if i != 0 && v[i - 1] == 1 {\n v[i] = 0;\n bishwocks += 1;\n } else if i + 1 != v.len() {\n if v[i + 1] != 0 {\n v[i] = 0;\n v[i + 1] -= 1;\n bishwocks += 1;\n }\n }\n }\n }\n println!(\"{}\", bishwocks);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "9ac92a373bf873d29472b7dd8f879b4b", "src_uid": "e6b3e787919e96fc893a034eae233fc6", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_imports)]\n#[rustfmt::skip] mod writer {use std::fmt::Display;use std::io::{stdout, BufWriter, Error as IoError, Stdout, Write};#[derive(Debug)] pub struct Writer { writer: BufWriter, } #[derive(Debug, Clone)] pub struct Format<'a> { separator: &'a str, ending: &'a str, } impl<'a> Format<'a> { pub fn separator(self, separator: &'a str) -> Self { Self { separator, ..self } } pub fn ending(self, ending: &'a str) -> Self { Self { ending, ..self } } } impl Default for Format<'_> { fn default() -> Self { Format { separator: \" \", ending: \"\\n\", } } } impl Writer { pub fn stdout() -> Self { Self::new(stdout()) } } impl Writer { pub fn new(writer: W) -> Self { Self { writer: BufWriter::new(writer), } } pub fn write>(&mut self, val: T) -> Result<(), IoError> { self.write_with(val, &Format::default()) } pub fn write_with>(&mut self, val: T, fmt: &Format) -> Result<(), IoError> { val.write_to(&mut self.writer, fmt) } pub fn flush(&mut self) -> Result<(), IoError> { self.writer.flush() } } pub trait Writable { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError>;} #[non_exhaustive] pub struct Single;impl Writable for T { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError> { write!(w, \"{}{}\", self, fmt.ending) } } #[non_exhaustive] pub struct Many;impl Writable for I where I: Iterator, I::Item: Display, { fn write_to(mut self, w: &mut W, fmt: &Format) -> Result<(), IoError> { if let Some(x) = self.next() { write!(w, \"{}\", x)?;} else { return Ok(());} for x in self { write!(w, \"{}{}\", fmt.separator, x)?;} write!(w, \"{}\", fmt.ending) } } #[non_exhaustive] pub struct Slice;impl Writable for &[T] { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError> { self.iter().write_to(w, fmt) } } #[macro_export] macro_rules! out { ($writer:expr, $val:expr) => { $writer.write($val).expect(\"failed to write token\");};($writer:expr, $val:expr, $($builder_name:ident = $value:expr),+) => { let mut fmt = Format::default();$( fmt = fmt.$builder_name($value);)+ $writer.write_with($val, &fmt).expect(\"failed to write token\");};} }\n#[rustfmt::skip] mod scanner {use std::fmt::Debug;use std::io::{stdin, BufReader, Bytes, Error as IoError, Read, Stdin};use std::str::{self, FromStr, Utf8Error};#[derive(Debug)] pub struct Scanner { bytes: Bytes>, buf: Vec, } pub trait Instructions { type Target;type Error;fn read_from(scanner: &mut Scanner) -> Result;} impl Instructions for T { type Target = T;type Error = ScanError;fn read_from(scanner: &mut Scanner) -> Result { scanner.read_token() } } #[derive(Debug)] pub enum ScanError { Io(IoError), Parse(T::Err, String), NonUtf8(Utf8Error, Vec), } impl Scanner { pub fn stdin() -> Self { Self::new(stdin()) } } impl Scanner { pub fn new(reader: R) -> Self { Self { bytes: BufReader::new(reader).bytes(), buf: Vec::new(), } } pub fn read_token(&mut self) -> Result> { debug_assert!(self.buf.is_empty());for b in &mut self.bytes { let b = b.map_err(ScanError::Io)?;if b.is_ascii_whitespace() { if self.buf.is_empty() { continue;} else { break;} } else { self.buf.push(b);} } match str::from_utf8(&self.buf) { Err(err) => Err(ScanError::NonUtf8(err, std::mem::take(&mut self.buf))), Ok(s) => { let ret = s.parse().map_err(|err| ScanError::Parse(err, s.to_owned()));self.buf.clear();ret } } } pub fn read(&mut self) -> Result { T::read_from(self) } } #[macro_use] pub mod macros { use super::*;use std::fmt::{self, Debug};use std::io::Read;use std::marker::PhantomData;use std::num::NonZeroUsize;use std::str::FromStr;pub struct UsizeM1(());impl Instructions for UsizeM1 { type Target = usize;type Error = ScanError;fn read_from(scanner: &mut Scanner) -> Result { Ok(scanner.read_token::()?.get() - 1) } } pub struct LenArray(PhantomData);impl Instructions for LenArray { type Target = Vec;type Error = LenArrayScanError;fn read_from(scanner: &mut Scanner) -> Result { let len = scanner .read_token::() .map_err(LenArrayScanError::Len)?;let mut arr = Vec::with_capacity(len);for i in 0..len { let elem = scanner .read_token::() .map_err(|e| LenArrayScanError::Data(i, e))?;arr.push(elem);} Ok(arr) } } pub enum LenArrayScanError { Len(ScanError), Data(usize, ScanError), } impl Debug for LenArrayScanError where T: Debug + FromStr, T::Err: Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::LenArrayScanError::*;match self { Len(e) => f.debug_tuple(\"Len\").field(e).finish(), Data(i, e) => f.debug_tuple(\"Data\").field(i).field(e).finish(), } } } #[macro_export] macro_rules! scan { (@scan 1 $scan:expr, $type:ty) => { $scan .read::<$type>() .expect(concat!(\"failed to read token of type \", stringify!($type))) };(@scan 2 $scan:expr, $type:ty, $n:expr) => { (0..$n) .map(|_| scan!(@scan 1 $scan, $type)) .collect::>() };(@accum ($scan:expr) () -> ($($body:tt)*)) => { ($($body)*) };(@accum ($scan:expr) ($type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 1 $scan, $type))) };(@accum ($scan:expr) ($type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 1 $scan, $type),)) };(@accum ($scan:expr) ($n:tt * $type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 2 $scan, $type, $n))) };(@accum ($scan:expr) ($n:tt * $type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 2 $scan, $type, $n),)) };($scan:expr, $($arg:tt)+) => { scan!(@accum ($scan) ($($arg)+) -> ()) };} } }\n#[rustfmt::skip] mod util { use std::cmp::Reverse; pub trait IntoVec { fn into_vec(self) -> Vec;} #[non_exhaustive] pub struct Owned;impl IntoVec for I where I: Iterator, { fn into_vec(self) -> Vec { self.collect() } } #[non_exhaustive] pub struct Reference;impl<'a, I, T> IntoVec for I where I: Iterator, T: Clone + 'a, { fn into_vec(self) -> Vec { self.cloned().collect() } } pub trait Argmax { fn argmax(self) -> Option;fn argmin(self) -> Option;} impl Argmax for I where I: Iterator, I::Item: Ord, { fn argmax(self) -> Option { self.fold((0, None), |(i, mx), next| { if let Some((mx_i, mx_v)) = mx { if next.gt(&mx_v) { (i + 1, Some((i, next))) } else { (i + 1, Some((mx_i, mx_v))) } } else { (i + 1, Some((i, next))) } }) .1 .map(|x| x.0) } fn argmin(self) -> Option { self.map(Reverse).argmax() } } pub trait Sorted { fn sorted(self) -> Self;} impl Sorted for Vec where T: Ord, { fn sorted(mut self) -> Self { self.sort();self } } pub trait SortedBy { fn sorted_by(self, f: F) -> Self where F: FnMut(&T) -> K, K: Ord;} impl SortedBy for Vec { fn sorted_by(mut self, f: F) -> Self where F: FnMut(&T) -> K, K: Ord, { self.sort_by_key(f);self } } pub trait Choose { fn choose(self, a: T, b: T) -> T;fn choose_by(self, a: impl FnOnce() -> T, b: impl FnOnce() -> T) -> T;} impl Choose for bool { fn choose(self, a: T, b: T) -> T { if self { a } else { b } } fn choose_by(self, a: impl FnOnce() -> T, b: impl FnOnce() -> T) -> T { if self { a() } else { b() } } } #[macro_export] macro_rules! p { ( $( $x:expr ),* ) => { #[cfg(any(debug_assertions, debug_print))] { dbg!( $( & $x, )* );} };} pub fn fix(f: &dyn Fn(&dyn Fn(A) -> R, A) -> R) -> impl Fn(A) -> R + '_ { move |arg| f(&fix(&f), arg) } pub trait Assign { fn assign(&mut self, val: T);} impl Assign for Option { fn assign(&mut self, val: T) { assert!(self.is_none(), \".assign() called on Some variant\");*self = Some(val);} } }\n#[rustfmt::skip] mod prefix_sum {use std::{ fmt::{self, Debug, Formatter}, marker::PhantomData, ops::{Add, Bound, Range, RangeBounds, Sub}, };#[derive(Clone)] pub struct PrefixOp { fwd: F, inv: Option, marker: PhantomData T>, } impl PrefixOp where F: Fn(&T, &T) -> T, { pub fn new(op: F) -> Self { PrefixOp { fwd: op, inv: None, marker: PhantomData, } } } impl PrefixOp where F: Fn(&T, &T) -> T, I: Fn(&T, &T) -> T, { pub fn new_invertible(op: F, inverse: I) -> Self { PrefixOp { fwd: op, inv: Some(inverse), marker: PhantomData, } } } impl PrefixOp where F: Fn(&T, &T) -> T, I: Clone, { pub fn build(&self, mut arr: Vec) -> PrefixArray { for i in 1..arr.len() { arr[i] = (self.fwd)(&arr[i - 1], &arr[i]);} PrefixArray { pref: arr, fwd: PhantomData, inv: self.inv.clone(), } } } #[derive(Clone)] pub struct PrefixArray { pref: Vec, fwd: PhantomData, inv: Option, } impl PrefixArray { pub fn len(&self) -> usize { self.pref.len() } pub fn is_empty(&self) -> bool { self.pref.is_empty() } #[track_caller] fn verify_range_bounds(&self, range: impl RangeBounds) -> Range { let start = match range.start_bound() { Bound::Unbounded => 0, Bound::Included(&x) => x, Bound::Excluded(&x) => x + 1, };let end = match range.end_bound() { Bound::Unbounded => self.len(), Bound::Included(&x) => x + 1, Bound::Excluded(&x) => x, };assert!( start < end, \"range inverted: start >= end ({} >= {})\", start, end );assert!( end <= self.len(), \"range out of bounds: end > len ({} > {})\", end, self.len() );Range { start, end } } #[track_caller] pub fn query_prefix(&self, range: impl RangeBounds) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);assert!(start == 0, \"query start bound is non-zero: {} > 0\", start);self.pref[end - 1].clone() } } impl PrefixArray where I: Fn(&T, &T) -> T, { #[track_caller] pub fn query(&self, range: impl RangeBounds) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);if start == 0 { self.pref[end - 1].clone() } else { (self .inv .as_ref() .expect(\"range query is not supported on non-invertible operation\"))( &self.pref[end - 1], &self.pref[start - 1], ) } } } impl Debug for PrefixOp where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct(\"PrefixOp\").finish_non_exhaustive() } } impl Debug for PrefixArray where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct(\"PrefixArray\") .field(\"pref\", &self.pref) .finish_non_exhaustive() } } type NextFn = fn(&T, &T) -> T;pub struct PrefixSum(PhantomData);impl PrefixSum where T: Add + Sub + Clone, { pub fn op() -> PrefixOp, NextFn> { PrefixOp::new_invertible(|a, b| a.clone() + b.clone(), |b, a| b.clone() - a.clone()) } pub fn build(arr: Vec) -> PrefixArray, NextFn> { Self::op().build(arr) } } }\n#[rustfmt::skip] mod combinatorics {use crate::{num::Integer, number_theory::mod_mulinv};pub fn next_permutation(perm: &mut [T]) -> bool where T: Ord, { if perm.is_empty() { return false;} let i = match Iterator::zip(perm.iter(), perm[1..].iter()).rposition(|(x, y)| x < y) { None => { perm.reverse();return false;} Some(x) => x, };let j = perm .iter() .rposition(|x| &perm[i] < x) .expect(\"inconsistent Ord implementation\");perm.swap(i, j);perm[i + 1..].reverse();true } #[derive(Debug, Clone)] pub struct Factorials { m: N, fact: Vec, fact_inv: Vec, } impl Factorials where N: Integer + Clone, { #[inline] fn as_n(x: usize) -> N { N::from_usize(x).expect(\"inconsistent Integer implementation\") } #[inline] fn as_usize(x: &N) -> usize { N::as_usize(x).expect(\"inconsistent Integer implementation\") } #[track_caller] pub fn new(n: N, m: N) -> Self { let cap = n .as_usize() .and_then(|x| x.checked_add(1)) .expect(\"required capacity overflowed usize\");assert!(cap > 0, \"n must be non-negative\");let mut fact = Vec::with_capacity(cap);fact.push(N::one());let mut cur = N::one();for i in 1..cap { cur = (cur * Self::as_n(i)).imod(&m);fact.push(cur.clone());} let mut fact_inv = Vec::with_capacity(cap);let mut cur = mod_mulinv(fact[cap - 1].clone(), m.clone());for i in (0..cap).rev() { fact_inv.push(cur.clone());cur = (cur * Self::as_n(i)).imod(&m);} fact_inv.reverse();debug_assert_eq!(fact.len(), cap);debug_assert_eq!(fact_inv.len(), cap);Factorials { m, fact, fact_inv } } pub fn len(&self) -> usize { self.fact.len() } pub fn is_empty(&self) -> bool { false } pub fn n(&self) -> N { Self::as_n(self.fact.len() - 1) } #[track_caller] fn verify_n<'a>(&self, n: &'a N) -> &'a N { assert!( N::zero() <= *n && *n <= self.n(), \"n is outside precomputed range\" );n } #[track_caller] pub fn factorial(&self, n: &N) -> N { let n = self.verify_n(n);self.fact[Self::as_usize(n)].clone() } #[track_caller] pub fn factorial_inverse(&self, n: &N) -> N { let n = self.verify_n(n);self.fact_inv[Self::as_usize(n)].clone() } #[track_caller] pub fn choose(&self, n: N, k: N) -> N { self.verify_n(&n);assert!(k >= N::zero(), \"k is negative\");if k <= n { ((self.fact[Self::as_usize(&n)].clone() * self.fact_inv[Self::as_usize(&k)].clone()) .imod(&self.m) * self.fact_inv[Self::as_usize(&(n - k))].clone()) .imod(&self.m) } else { N::zero() } } } }\n#[rustfmt::skip] mod number_theory {use crate::num::Integer;use std::mem;pub fn gcd(mut a: N, mut b: N) -> N { while b != N::zero() { mem::swap(&mut a, &mut b);b = b.imod(&a);} a.iabs() } #[allow(clippy::many_single_char_names)] pub fn egcd(a: N, b: N) -> (N, N, N) { if b == N::zero() { ( a.iabs(), if a >= N::zero() { N::one() } else { N::zero() - N::one() }, N::zero(), ) } else { let (g, s, t) = egcd(b.clone(), a.imod(&b));(g, t.clone(), s - a.idiv(&b) * t) } } #[track_caller] pub fn mod_exp(a: N, mut b: N, m: N) -> N { let zero = N::zero();let one = N::one();let two = N::one() + N::one();assert!(m > zero, \"modulus must be positive\");if b < zero { return mod_exp(mod_mulinv(a, m.clone()), zero - b, m);} let mut x = N::one();let mut pwr = a;while b > N::zero() { if b.imod(&two) == one { x = (x * pwr.clone()).imod(&m);} pwr = (pwr.clone() * pwr).imod(&m);b = b.idiv(&two);} x } #[track_caller] pub fn mod_mulinv(a: N, m: N) -> N { let zero = N::zero();let one = N::one();assert!(m > zero, \"modulus must be positive\");let (g, s, _) = egcd(a, m.clone());assert!(g == one, \"multiplicative inverse does not exist\");s.imod(&m) } #[derive(Debug, Clone)] pub struct PrimeSieve { lowest_factor: Vec, primes: Vec, } impl PrimeSieve where N: Integer + Clone, { #[inline] fn as_n(x: usize) -> N { N::from_usize(x).expect(\"inconsistent Integer implementation\") } #[inline] fn as_usize(x: &N) -> usize { N::as_usize(x).expect(\"inconsistent Integer implementation\") } #[track_caller] pub fn new(n: N) -> Self { let cap = n .as_usize() .and_then(|x| x.checked_add(1)) .expect(\"capacity overflowed usize\");assert!(cap > 0, \"n must be non-negative\");let mut lowest_factor = vec![N::zero(); cap];let mut primes = vec![];for i in 2..cap { if lowest_factor[i] == N::zero() { lowest_factor[i] = Self::as_n(i);primes.push(Self::as_n(i));} let lowest_factor_i = lowest_factor[i].clone();for (p, p_usize) in primes .iter() .map(|p| (p, Self::as_usize(p))) .take_while(|(p, p_usize)| i * p_usize < cap && p <= &&lowest_factor_i) { lowest_factor[i * p_usize] = p.clone();} } PrimeSieve { lowest_factor, primes, } } pub fn len(&self) -> usize { self.lowest_factor.len() } pub fn is_empty(&self) -> bool { false } pub fn n(&self) -> N { Self::as_n(self.lowest_factor.len() - 1) } #[track_caller] pub fn is_prime(&self, x: &N) -> bool { assert!(*x >= N::zero(), \"x must be non-negative\");let n = self.n();if *x <= n { *x > N::zero() && self.lowest_factor[Self::as_usize(x)] == *x } else if *x <= n.clone() * n { for p in self.primes.iter() { if x.imod(p) == N::zero() { return false;} } true } else { panic!(\"unable to determine primality: x > n^2\");} } #[track_caller] pub fn lowest_factor(&self, x: &N) -> N { assert!(*x >= N::zero(), \"x must be non-negative\");let n = self.n();if *x <= n { self.lowest_factor[Self::as_usize(x)].clone() } else if *x <= n.clone() * n { for p in self .primes .iter() .take_while(|&p| p.clone() * p.clone() <= *x) { if x.imod(p) == N::zero() { return p.clone();} } x.clone() } else { panic!(\"unable to determine lowest factor: x > n^2\",) } } #[track_caller] pub fn factorize(&self, mut x: N) -> Vec { let n = self.n();assert!(x > N::zero(), \"cannot factorize non-positive numbers\");assert!(x <= n.clone() * n.clone(), \"unable to factorize: x > n^2\",);let mut factors = Vec::new();let x2 = x.clone();let mut primes = self .primes .iter() .take_while(|&p| p.clone() * p.clone() <= x2);while x > N::one() { if x <= n { let f = &self.lowest_factor[Self::as_usize(&x)];factors.push(f.clone());x = x.idiv(f);} else if let Some(p) = primes.next() { while x.imod(p) == N::zero() { factors.push(p.clone());x = x.idiv(p);} } else { factors.push(x);break;} } factors } } }\n#[rustfmt::skip] mod num {use std::convert::{TryFrom, TryInto};use std::ops::{Add, Div, Mul, Rem, Sub};pub trait Num: Ord + Add + Sub + Mul + Div + Rem + FromPrimitive + IntoPrimitive + Sized { fn zero() -> Self;fn one() -> Self;} pub trait FromPrimitive: Sized { fn from_u64(x: u64) -> Option;fn from_i64(x: i64) -> Option;fn from_usize(x: usize) -> Option { Self::from_u64(x as u64) } fn from_isize(x: isize) -> Option { Self::from_i64(x as i64) } } pub trait IntoPrimitive { fn as_u64(&self) -> Option;fn as_i64(&self) -> Option;fn as_usize(&self) -> Option { self.as_u64().and_then(|x| x.try_into().ok()) } fn as_isize(&self) -> Option { self.as_i64().and_then(|x| x.try_into().ok()) } } pub trait Integer: Num { fn idiv(&self, x: &Self) -> Self;fn imod(&self, x: &Self) -> Self;fn iabs(&self) -> Self;} macro_rules! generate_integer_impl_for_primitive { ($( ($ty:ty, $unsigned:tt) ),+) => { $( impl FromPrimitive for $ty { #[inline(always)] fn from_u64(x: u64) -> Option { <$ty>::try_from(x).ok() } #[inline(always)] fn from_i64(x: i64) -> Option { <$ty>::try_from(x).ok() } } impl IntoPrimitive for $ty { #[inline(always)] fn as_u64(&self) -> Option { u64::try_from(*self).ok() } #[inline(always)] fn as_i64(&self) -> Option { i64::try_from(*self).ok() } } impl Num for $ty { #[inline(always)] fn zero() -> Self { 0 } #[inline(always)] fn one() -> Self { 1 } } impl Integer for $ty { #[inline(always)] fn idiv(&self, x: &Self) -> Self { self.div_euclid(*x) } #[inline(always)] fn imod(&self, x: &Self) -> Self { self.rem_euclid(*x) } generate_iabs_impl!($unsigned);} )+ };} macro_rules! generate_iabs_impl { (true) => { #[inline(always)] fn iabs(&self) -> Self { *self } };(false) => { #[inline(always)] fn iabs(&self) -> Self { self.abs() } };} generate_integer_impl_for_primitive!( (u8, true), (u16, true), (u32, true), (u64, true), (u128, true), (usize, true), (i8, false), (i16, false), (i32, false), (i64, false), (i128, false), (isize, false) );}\n\nuse combinatorics::{next_permutation, Factorials};\nuse number_theory::{egcd, gcd, mod_exp, mod_mulinv, PrimeSieve};\nuse prefix_sum::{PrefixOp, PrefixSum};\nuse scanner::{\n macros::{LenArray, UsizeM1},\n Scanner,\n};\nuse util::{fix, Argmax, Assign, Choose, IntoVec, Sorted};\nuse writer::{Format, Writer};\n\nfn main() {\n let mut sc = Scanner::stdin();\n let mut wr = Writer::stdout();\n\n const MOD: i64 = 1_000_000_007;\n const N: i64 = 100_000;\n let n = scan!(sc, i64);\n let primes = PrimeSieve::new(N);\n\n let totient = |n: i64| {\n let mut t = n;\n let mut pf = primes.factorize(n);\n pf.sort();\n pf.dedup();\n for f in pf {\n t -= t / f\n }\n t\n };\n let totient_pre = (0..=N)\n .map(|i| if i <= 1 { 0 } else { totient(i) })\n .into_vec();\n p!(&totient_pre[..10]);\n\n let mut total = 0;\n for c in 1..=n - 2 {\n let mut gs = vec![];\n for g in (1..).take_while(|g| g * g <= n - c) {\n if (n - c) % g == 0 {\n gs.push(g);\n if g * g != n - c {\n gs.push((n - c) / g);\n }\n }\n }\n p!(c, gs);\n\n for g in gs {\n let cnt = totient_pre[((n - c) / g) as usize];\n p!(g, cnt, (n - c) / g);\n total = (total + cnt * c * g / gcd(c, g)) % MOD;\n }\n }\n\n out!(wr, total);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "01e537cd7be1233622dd96f88314486a", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::{\r\n io::{prelude::*, stdin, stdout, BufWriter},\r\n mem::swap,\r\n};\r\n\r\nconst MOD: i64 = 1000000007;\r\n\r\nfn main() {\r\n let std_in = stdin();\r\n let mut input = Scanner::new(std_in.lock());\r\n\r\n let std_out = stdout();\r\n let mut output = BufWriter::new(std_out.lock());\r\n\r\n let n: usize = input.token();\r\n\r\n let mut phi: Vec = (0..=n).collect();\r\n for i in 2..=n {\r\n if phi[i] == i {\r\n for j in (i..=n).step_by(i) {\r\n phi[j] -= phi[j] / i;\r\n }\r\n }\r\n }\r\n\r\n let mut result = 0;\r\n for c in 1..n {\r\n let sum = n - c;\r\n if sum < 2 {\r\n continue;\r\n }\r\n\r\n add_to_result(c as i64, 1, phi[sum] as i64, &mut result);\r\n for x in 2..=sum {\r\n if x * x > sum {\r\n break;\r\n }\r\n if sum % x != 0 {\r\n continue;\r\n }\r\n\r\n let y = sum / x;\r\n if phi[y] != 0 {\r\n add_to_result(c as i64, x as i64, phi[y] as i64, &mut result);\r\n }\r\n if x != y && phi[x] != 0 {\r\n add_to_result(c as i64, y as i64, phi[x] as i64, &mut result);\r\n }\r\n }\r\n }\r\n writeln!(output, \"{}\", result).unwrap();\r\n}\r\n\r\nfn add_m(x: i64, y: i64) -> i64 {\r\n let mut tmp = x + y;\r\n if tmp < 0 {\r\n tmp += MOD;\r\n }\r\n if tmp >= MOD {\r\n tmp -= MOD;\r\n }\r\n tmp\r\n}\r\n\r\nfn mul_m(x: i64, y: i64) -> i64 {\r\n (x * y) % MOD\r\n}\r\n\r\nfn gcd(mut a: i64, mut b: i64) -> i64 {\r\n while b != 0 {\r\n a %= b;\r\n swap(&mut a, &mut b);\r\n }\r\n a\r\n}\r\n\r\nfn add_to_result(c: i64, g: i64, cnt: i64, result: &mut i64) {\r\n *result = add_m(*result, mul_m(cnt, c * g / gcd(c, g)));\r\n}\r\n\r\npub struct Scanner {\r\n reader: B,\r\n buf_str: Vec,\r\n buf_iter: std::str::SplitWhitespace<'static>,\r\n}\r\nimpl Scanner {\r\n pub fn new(reader: B) -> Self {\r\n Self {\r\n reader,\r\n buf_str: Vec::new(),\r\n buf_iter: \"\".split_whitespace(),\r\n }\r\n }\r\n pub fn token(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_whitespace())\r\n }\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "658b5e5b8c7914e46dee0e56fec70817", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::{TryInto, TryFrom}, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self;\n if a == 0 || b == 0 { return a | b; }\n let shift = (a | b).trailing_zeros();\n a >>= a.trailing_zeros();\n b >>= b.trailing_zeros();\n while a != b {\n if a > b { a -= b; a >>= a.trailing_zeros(); }\n else { b -= a; b >>= b.trailing_zeros(); }\n }\n a << shift\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, b: Self) -> Self {\n fn w_abs(x: $ix) -> $ux { (if x.is_negative() { x.wrapping_neg() } else { x }) as _ }\n w_abs(self).gcd(w_abs(b)) as _\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n fn mul(a: u32, b: u32) -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(M::mul(self.val, rhs.into().val))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n fn mul(a: u32, b: u32) -> u32 { \n mul_mod_u32(a, b, Self::get_modulus())\n }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n\n #[derive(Debug, Clone, Copy)]\n pub struct ModulusCalc {\n pub modulus: u32,\n pub inv: u64\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(ModulusCalc { modulus: 0, inv: 0 }));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get().modulus }\n fn mul(a: u32, b: u32) -> u32 {\n let ModulusCalc { modulus, inv } = $modulus.0.get();\n let p = a as u64 * b as u64;\n let g = ((p as u128 * inv as u128) >> 64) as u64;\n let (r, c) = p.overflowing_sub(g * modulus as u64);\n if c { (r as u32).wrapping_add(modulus) } else { r as u32 }\n }\n }\n impl $name {\n pub fn set_modulus(val: u32) { \n let inv = (1u64.wrapping_neg() / val as u64).wrapping_add(1);\n $modulus.0.set(ModulusCalc { modulus: val, inv })\n }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\n// type ModInt = ModInt998_244_353;\ntype ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\nstruct FactorMap {\n map: Vec\n}\nimpl FactorMap {\n pub fn new(limit: usize) -> FactorMap {\n let limit = limit + 1;\n let mut map = vec![0; limit >> 1];\n for p in (3..limit).step_by(2) {\n if map[p >> 1] != 0 { continue; }\n let sq = p * p;\n if sq >= limit { break; }\n for i in (sq..limit).step_by(p*2) {\n if map[i >> 1] == 0 { map[i >> 1] = p as u32; }\n }\n }\n\n FactorMap { map }\n }\n\n pub fn least_prime_factor(&self, n: usize) -> usize {\n if n & 1 == 0 { return 2; }\n let p = self.map[n >> 1] as usize;\n if p == 0 { n } else { p }\n }\n\n pub fn factorize(&self, n: usize) -> FactorIterator {\n FactorIterator { fm: self, n }\n }\n\n pub fn is_prime(&self, n: usize) -> bool { n > 1 && self.least_prime_factor(n) == n }\n\n /// lists divisors, unsorted\n pub fn divisors(&self, mut n: usize) -> Vec {\n let mut res = vec![1];\n\n while n > 1 {\n let p = self.least_prime_factor(n);\n let mut x = 0;\n loop {\n n /= p;\n x += 1;\n if p != self.least_prime_factor(n) { break; }\n }\n for i in 0..res.len() {\n let mut a = res[i];\n for _ in 0..x {\n a *= p;\n res.push(a);\n }\n }\n }\n\n res\n }\n\n pub fn euler_totient(&self, mut n: usize) -> usize {\n let mut res = n;\n\n while n > 1 {\n let p = self.least_prime_factor(n);\n loop {\n n /= p;\n if p != self.least_prime_factor(n) { break; }\n }\n res = res / p * (p-1);\n }\n\n res\n }\n\n pub fn new_with_mobius(limit: usize) -> (FactorMap, Vec) {\n let fm = Self::new(limit);\n let mut mu = vec![1i8; limit + 1];\n mu[0] = 0;\n\n for i in 2..=limit {\n let p = fm.least_prime_factor(i);\n mu[i] = if p == fm.least_prime_factor(i/p) { 0 } else { -mu[i/p] };\n }\n\n (fm, mu)\n }\n}\nstruct FactorIterator<'a> {\n fm: &'a FactorMap,\n n: usize\n}\nimpl Iterator for FactorIterator<'_> {\n type Item = usize;\n\n fn next(&mut self) -> Option {\n if self.n <= 1 { return None; }\n let p = self.fm.least_prime_factor(self.n);\n self.n /= p;\n Some(p)\n }\n\n fn size_hint(&self) -> (usize, Option) { (0, Some(32)) }\n}\n\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n\n let mut ans = 0i128;\n let fm = FactorMap::new(n);\n for c in 1..=n-2 {\n for d in fm.divisors(n-c) { if d != n-c {\n let l = c / c.gcd(d) * d;\n ans += l as i128 * fm.euler_totient((n-c)/d) as i128;\n }}\n }\n\n ans %= 1_000_000_007;\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "c5f291d5569a349ba612891f9335a59a", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin scanner -----------\n#[allow(unused_imports)]\nuse std::io::{BufWriter, stdin, stdout, Read, Write, Stdout};\nuse std::str::FromStr;\n\npub struct Scanner<'a> {\n it: std::str::SplitWhitespace<'a>,\n}\n#[allow(dead_code)]\nimpl<'a> Scanner<'a> {\n pub fn new(s: &'a String) -> Scanner<'a> {\n Scanner {\n it: s.split_whitespace(),\n }\n }\n pub fn next(&mut self) -> T {\n self.it.next().expect(\"read EOF\").parse::().ok().expect(\"parse failed\")\n }\n pub fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n pub fn next_n_index1(&mut self, n: usize) -> Vec {\n std::iter::once(T::default()).chain((0..n).map(|_| self.next())).collect()\n }\n pub fn next_chars(&mut self) -> Vec { self.it.next().unwrap().chars().collect() }\n pub fn next_bytes(&mut self) -> Vec { self.it.next().unwrap().bytes().collect() }\n pub fn next_digits(&mut self) -> Vec {\n self.it.next().unwrap().bytes().map(|c|c-C0).collect()\n }\n}\n// ---------- end scanner -------------\n\n\n// ---------- begin utils -------------\n#[allow(dead_code)]\nconst C0: u8 = '0' as u8;\n\n// ---------- end utils ---------------\n\n\n// ---------- begin debugger ----------\n#[cfg(feature = \"my_debug\")]\n#[macro_export]\nmacro_rules! debug {\n () => {\n eprintln!(\"[{}:{}]\", file!(), line!())\n };\n ($val:expr $(,)?) => {\n eprintln!(\"[{}:{}] {} = {:?}\", file!(), line!(), stringify!($val), &($val))\n };\n ($($val:expr),+ $(,)?) => {\n ($(debug!($val)),+,)\n };\n}\n\n#[cfg(not(feature = \"my_debug\"))]\n#[macro_export]\nmacro_rules! debug {\n ($( $args:expr ),*) => {}\n}\n// ---------- end debugger ------------\n\n\nfn main() {\n debug!(\"Ish: good luck and high rating!\");\n\n #[cfg(not(feature = \"my_debug\"))]\n let s = {\n let mut s = String::new();\n stdin().read_to_string(&mut s).unwrap();\n s\n };\n #[cfg(feature = \"my_debug\")]\n let s = std::fs::read_to_string(\"in.txt\").unwrap();\n\n let mut sc = Scanner::new(&s);\n let out = &mut BufWriter::new(stdout());\n\n // let cases: u32 = sc.next();\n let cases: u32 = 1;\n debug!(cases);\n for _case in 1..=cases { debug!(_case);\n run(&mut sc, out);\n }\n}\n\n\n/** Write your mind here.\n\nlcm(c, gcd(a,b))\n\nc*gcd(a,b)/ gcd(a,b,c)\n\n\u679a\u4e3e c\uff0c\u8bbe m = n-c = a+b, \u6240\u6709\u7684 a+b \u7ec4\u5408\u6210 m\uff0c\u4ed6\u4eec\u7684 gcd \u503c\u548c c \u53d6 lcm\u3002\n\n5000\n1 4999\n2 4998\n\nm \u5206\u5316\u3002\n\u5982\u679c a \u548c b \u7684 gcd \u4e0d\u662f 1\uff0c\u53ea\u6709\u53ef\u80fd\u662f 10 \u5206\u6210 6 \u548c 4\u3002\n\nm \u672c\u8eab\u662f x \u7684\u500d\u6570\n\u5206\u51fa\u6765 ax \u548c bx\u3002\n\n12\n1 11 1 * 2\n2 10 2 * 2\n3 9 3 * 2\n4 8 4 * 2\n5 7 1 * 2\n6 6 6 * 1\n\n\u56e0\u6570\u4e2a\u6570\uff0c\u5982\u679c\u80fd\u679a\uff0c\u8fd8\u662f\u53ef\u4ee5\u7684\u3002\n\n14\n1 2 7\n 6 1\n\n240\n\n\n\n */\n\nfn gcd(a: i32, b: i32) -> i32 {\n if b == 0 { return a; }\n return gcd(b, a%b);\n}\n\nfn lcm(a: i32, b: i32) -> i64 {\n a as i64 * b as i64 / gcd(a, b) as i64\n}\n\nfn run(sc: &mut Scanner, out: &mut BufWriter) {\n let n = sc.next::();\n\n let mut ans = 0;\n for c in 1..=n-2 {\n let m = n-c;\n\n let factors = {\n let mut fc = vec![1];\n for i in 2..m {\n if i*i > m { break; }\n if i*i == m { fc.push(i); continue; }\n if m%i == 0 { fc.push(i); fc.push(m/i); }\n }\n fc.sort();\n fc\n };\n\n let tot = factors.len();\n let cnt = {\n let mut cnt = vec![0; tot];\n for i in (0..tot).rev() {\n cnt[i] = m / factors[i] - 1;\n\n for j in i+1..tot {\n if factors[j] % factors[i] == 0 {\n cnt[i] -= cnt[j];\n }\n }\n }\n cnt\n };\n\n let mut tmp = 0i64;\n for i in 0..tot {\n let p = lcm(c, factors[i]);\n tmp += p * cnt[i] as i64;\n\n }\n // tmp %= 1_000_000_007;\n\n ans = ans + tmp;\n ans %= 1_000_000_007;\n }\n\n\n // let ans = if arr == brr {\"YES\"} else {\"NO\"};\n\n // let ans = 1;\n // let mut ok = true;\n // let ans = if ok {\"Yes\"} else {\"No\"};\n writeln!(out, \"{ans}\").ok();\n // for ans in ans {\n // for num in ans { write!(out, \"{num}\").ok(); }\n // writeln!(out).ok();\n // }\n}\n\n\n\n#[test]\nfn test() {\n let n = 2048;\n let mut count = vec![0; n as usize];\n for a in 1..n {\n let b = n-a;\n let g = gcd(a, b);\n count[g as usize] += 1;\n }\n let mut cnt = 0;\n for i in 0..n as usize {\n if count[i] > 0 {\n debug!((i, count[i]));\n cnt += 1;\n }\n }\n debug!(cnt);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "3c195aac6db477369257a2d0d727a357", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\r\n#![allow(unused_must_use)]\r\n#![allow(unused_macros)]\r\n#![allow(non_snake_case)]\r\n#![allow(clippy::too_many_arguments)]\r\n#![allow(clippy::many_single_char_names)]\r\n#![allow(clippy::needless_range_loop)]\r\n#![allow(clippy::comparison_chain)]\r\n\r\nuse std::cmp::{max, min, Reverse};\r\nuse std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};\r\nuse std::io::{self, prelude::*};\r\nuse std::str;\r\n\r\nfn solve(sc: &mut Scanner, wr: &mut W) {\r\n const MOD: i64 = 1_000_000_007;\r\n let n: usize = sc.tok();\r\n let lowest = sieve(n);\r\n let mut phi = vec![1; n + 1];\r\n for k0 in 2..=n {\r\n let p = lowest[k0];\r\n let mut pow = 1;\r\n let mut k = k0;\r\n while k % p == 0 {\r\n k /= p;\r\n pow *= p;\r\n }\r\n phi[k0] = phi[k] * ((p - 1) * (pow / p)) as i64;\r\n }\r\n let mut res = 0;\r\n for g in 1..=n as i64 - 1 {\r\n let mut s = 2 * g;\r\n while s < n as i64 {\r\n res += phi[(s / g) as usize] * lcm(g, n as i64 - s) % MOD;\r\n if res >= MOD {\r\n res -= MOD;\r\n }\r\n s += g;\r\n }\r\n }\r\n writeln!(wr, \"{}\", res);\r\n}\r\n\r\npub fn gcd(mut a: i64, mut b: i64) -> i64 {\r\n a = a.abs();\r\n b = b.abs();\r\n while b > 0 {\r\n a %= b;\r\n (a, b) = (b, a);\r\n }\r\n a\r\n}\r\n\r\npub fn lcm(a: i64, b: i64) -> i64 {\r\n if (a, b) == (0, 0) {\r\n 0\r\n } else {\r\n a / gcd(a, b) * b\r\n }\r\n}\r\nfn sieve(max: usize) -> Vec {\r\n let mut primes = vec![];\r\n let mut lowest = vec![0; max + 1];\r\n for n in 2..=max {\r\n if lowest[n] == 0 {\r\n lowest[n] = n;\r\n primes.push(n);\r\n }\r\n for &p in &primes {\r\n if p > lowest[n] || p * n > max {\r\n break;\r\n }\r\n lowest[p * n] = p;\r\n }\r\n }\r\n lowest\r\n}\r\n\r\nuse std::marker::PhantomData;\r\nmacro_rules! recursive_function {\r\n ($name: ident, $trait: ident, ($($type: ident $arg: ident,)*)) => {\r\n pub trait $trait<$($type, )*Output> {\r\n fn call(&mut self, $($arg: $type,)*) -> Output;\r\n }\r\n\r\n pub struct $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n f: F,\r\n $($arg: PhantomData<$type>,\r\n )*\r\n phantom_output: PhantomData,\r\n }\r\n\r\n impl $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n pub fn new(f: F) -> Self {\r\n Self {\r\n f,\r\n $($arg: Default::default(),\r\n )*\r\n phantom_output: Default::default(),\r\n }\r\n }\r\n }\r\n\r\n impl $trait<$($type, )*Output> for $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n fn call(&mut self, $($arg: $type,)*) -> Output {\r\n let const_ptr = &self.f as *const F;\r\n let mut_ptr = const_ptr as *mut F;\r\n unsafe { (&mut *mut_ptr)(self, $($arg, )*) }\r\n }\r\n }\r\n }\r\n}\r\n\r\nrecursive_function!(RecursiveFunction0, Callable0, ());\r\nrecursive_function!(RecursiveFunction, Callable, (Arg arg,));\r\nrecursive_function!(RecursiveFunction2, Callable2, (Arg1 arg1, Arg2 arg2,));\r\nrecursive_function!(RecursiveFunction3, Callable3, (Arg1 arg1, Arg2 arg2, Arg3 arg3,));\r\nrecursive_function!(RecursiveFunction4, Callable4, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4,));\r\nrecursive_function!(RecursiveFunction5, Callable5, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5,));\r\nrecursive_function!(RecursiveFunction6, Callable6, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6,));\r\nrecursive_function!(RecursiveFunction7, Callable7, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7,));\r\nrecursive_function!(RecursiveFunction8, Callable8, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8,));\r\nrecursive_function!(RecursiveFunction9, Callable9, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9,));\r\n\r\n#[macro_export]\r\nmacro_rules! dbg{\r\n ($($a:expr),*) => {\r\n #[cfg(debug_assertions)]\r\n eprintln!(\r\n concat!(\"{}:{}:{}: \",$(stringify!($a), \" = {:?}, \"),*),\r\n file!(), line!(), column!(), $($a),*\r\n );\r\n #[cfg(not(debug_assertions))]\r\n {};\r\n }\r\n}\r\nstruct Scanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitWhitespace<'static>,\r\n}\r\nimpl Scanner {\r\n fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: vec![],\r\n buf_iter: \"\".split_whitespace(),\r\n }\r\n }\r\n fn tok(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_whitespace())\r\n }\r\n }\r\n }\r\n}\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let mut scan = Scanner::new(stdin.lock());\r\n let mut out = io::BufWriter::new(stdout.lock());\r\n solve(&mut scan, &mut out);\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "8eef20a36606799954bd75468fad6ca0", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "pub mod solution {\n\nuse crate::io::input::Input;\nuse crate::io::output::output;\nuse crate::math::euclid::gcd;\nuse crate::math::sieve::{euler_function_up_to, get_all_divisors_for_all_up_to};\nuse crate::{out, out_line};\nuse crate::math::modular::primitive::ModularType;\n\ntype Mod = ModularType<1000000007>;\n\nfn solve(input: &mut Input, _test_case: usize) {\n let n = input.read();\n let phi = euler_function_up_to(n);\n let divisors = get_all_divisors_for_all_up_to(n);\n let mut ans = Mod::from(0);\n for c in 1..n - 1 {\n for &g in &divisors[n - c] {\n if g == n - c {\n continue;\n }\n let x = gcd(g as u64, c as u64) as usize;\n ans += Mod::from(c / x) * g.into() * phi[(n - c) / g].into();\n }\n }\n out_line!(ans);\n}\n\npub(crate) fn run(mut input: Input) -> bool {\n solve(&mut input, 1);\n output().flush();\n input.skip_whitespace();\n !input.peek().is_some()\n}\n\n}\npub mod io {\npub mod input {\nuse std::fmt::Debug;\nuse std::io::Read;\nuse std::marker::PhantomData;\nuse std::str::FromStr;\n\npub struct Input<'s> {\n input: &'s mut dyn Read,\n buf: Vec,\n at: usize,\n buf_read: usize,\n}\n\nimpl<'s> Input<'s> {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(input: &'s mut dyn Read) -> Self {\n Self {\n input,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn new_with_size(input: &'s mut dyn Read, buf_size: usize) -> Self {\n Self {\n input,\n buf: vec![0; buf_size],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn get(&mut self) -> Option {\n if self.refill_buffer() {\n let res = self.buf[self.at];\n self.at += 1;\n Some(res)\n } else {\n None\n }\n }\n\n pub fn peek(&mut self) -> Option {\n if self.refill_buffer() {\n Some(self.buf[self.at])\n } else {\n None\n }\n }\n\n pub fn skip_whitespace(&mut self) {\n while let Some(b) = self.peek() {\n if !char::from(b).is_whitespace() {\n return;\n }\n self.get();\n }\n }\n\n pub fn next_token(&mut self) -> Option> {\n self.skip_whitespace();\n let mut res = Vec::new();\n while let Some(c) = self.get() {\n if char::from(c).is_whitespace() {\n break;\n }\n res.push(c);\n }\n if res.is_empty() {\n None\n } else {\n Some(res)\n }\n }\n\n //noinspection RsSelfConvention\n pub fn is_exhausted(&mut self) -> bool {\n self.peek().is_none()\n }\n\n pub fn read(&mut self) -> T {\n T::read(self)\n }\n\n pub fn read_vec(&mut self, size: usize) -> Vec {\n let mut res = Vec::with_capacity(size);\n for _ in 0usize..size {\n res.push(self.read());\n }\n res\n }\n\n pub fn read_line(&mut self) -> String {\n let mut res = String::new();\n while let Some(c) = self.get() {\n if c == b'\\n' {\n break;\n }\n if c == b'\\r' {\n if self.peek() == Some(b'\\n') {\n self.get();\n }\n break;\n }\n res.push(c.into());\n }\n res\n }\n\n #[allow(clippy::should_implement_trait)]\n pub fn into_iter(self) -> InputIterator<'s, T> {\n InputIterator {\n input: self,\n phantom: Default::default(),\n }\n }\n\n fn read_integer(&mut self) -> T\n where\n ::Err: Debug,\n {\n let res = self.read_string();\n res.parse::().unwrap()\n }\n\n fn read_string(&mut self) -> String {\n match self.next_token() {\n None => {\n panic!(\"Input exhausted\");\n }\n Some(res) => unsafe { String::from_utf8_unchecked(res) },\n }\n }\n\n fn read_char(&mut self) -> char {\n self.skip_whitespace();\n self.get().unwrap().into()\n }\n\n fn read_float(&mut self) -> f64 {\n self.read_string().parse().unwrap()\n }\n\n fn refill_buffer(&mut self) -> bool {\n if self.at == self.buf_read {\n self.at = 0;\n self.buf_read = self.input.read(&mut self.buf).unwrap();\n self.buf_read != 0\n } else {\n true\n }\n }\n}\n\npub trait Readable {\n fn read(input: &mut Input) -> Self;\n}\n\nimpl Readable for String {\n fn read(input: &mut Input) -> Self {\n input.read_string()\n }\n}\n\nimpl Readable for char {\n fn read(input: &mut Input) -> Self {\n input.read_char()\n }\n}\n\nimpl Readable for f64 {\n fn read(input: &mut Input) -> Self {\n input.read_float()\n }\n}\n\nimpl Readable for Vec {\n fn read(input: &mut Input) -> Self {\n let size = input.read();\n input.read_vec(size)\n }\n}\n\npub struct InputIterator<'s, T: Readable> {\n input: Input<'s>,\n phantom: PhantomData,\n}\n\nimpl<'s, T: Readable> Iterator for InputIterator<'s, T> {\n type Item = T;\n\n fn next(&mut self) -> Option {\n self.input.skip_whitespace();\n self.input.peek().map(|_| self.input.read())\n }\n}\n\nmacro_rules! read_integer {\n ($t:ident) => {\n impl Readable for $t {\n fn read(input: &mut Input) -> Self {\n input.read_integer()\n }\n }\n };\n}\n\nread_integer!(i8);\nread_integer!(i16);\nread_integer!(i32);\nread_integer!(i64);\nread_integer!(i128);\nread_integer!(isize);\nread_integer!(u8);\nread_integer!(u16);\nread_integer!(u32);\nread_integer!(u64);\nread_integer!(u128);\nread_integer!(usize);\n\nmacro_rules! tuple_readable {\n ( $( $name:ident )+ ) => {\n impl<$($name: Readable), +> Readable for ($($name,)+) {\n fn read(input: &mut Input) -> Self {\n ($($name::read(input),)+)\n }\n }\n }\n}\n\ntuple_readable! {T}\ntuple_readable! {T U}\ntuple_readable! {T U V}\ntuple_readable! {T U V X}\ntuple_readable! {T U V X Y}\ntuple_readable! {T U V X Y Z}\ntuple_readable! {T U V X Y Z A}\ntuple_readable! {T U V X Y Z A B}\ntuple_readable! {T U V X Y Z A B C}\ntuple_readable! {T U V X Y Z A B C D}\ntuple_readable! {T U V X Y Z A B C D E}\ntuple_readable! {T U V X Y Z A B C D E F}\n}\npub mod output {\nuse std::io::Write;\n\npub struct Output {\n output: Box,\n buf: Vec,\n at: usize,\n auto_flush: bool,\n}\n\nimpl Output {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: false,\n }\n }\n\n pub fn new_with_auto_flush(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: true,\n }\n }\n\n pub fn flush(&mut self) {\n if self.at != 0 {\n self.output.write_all(&self.buf[..self.at]).unwrap();\n self.at = 0;\n self.output.flush().expect(\"Couldn't flush output\");\n }\n }\n\n pub fn print(&mut self, s: &T) {\n s.write(self);\n }\n\n pub fn put(&mut self, b: u8) {\n self.buf[self.at] = b;\n self.at += 1;\n if self.at == self.buf.len() {\n self.flush();\n }\n }\n\n pub fn maybe_flush(&mut self) {\n if self.auto_flush {\n self.flush();\n }\n }\n\n pub fn print_per_line(&mut self, arg: &[T]) {\n for i in arg {\n i.write(self);\n self.put(b'\\n');\n }\n }\n\n pub fn print_iter>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n\n pub fn print_iter_ref<'a, T: 'a + Writable, I: Iterator>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n}\n\nimpl Write for Output {\n fn write(&mut self, buf: &[u8]) -> std::io::Result {\n let mut start = 0usize;\n let mut rem = buf.len();\n while rem > 0 {\n let len = (self.buf.len() - self.at).min(rem);\n self.buf[self.at..self.at + len].copy_from_slice(&buf[start..start + len]);\n self.at += len;\n if self.at == self.buf.len() {\n self.flush();\n }\n start += len;\n rem -= len;\n }\n if self.auto_flush {\n self.flush();\n }\n Ok(buf.len())\n }\n\n fn flush(&mut self) -> std::io::Result<()> {\n self.flush();\n Ok(())\n }\n}\n\npub trait Writable {\n fn write(&self, output: &mut Output);\n}\n\nimpl Writable for &str {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for String {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for char {\n fn write(&self, output: &mut Output) {\n output.put(*self as u8);\n }\n}\n\nimpl Writable for [T] {\n fn write(&self, output: &mut Output) {\n output.print_iter_ref(self.iter());\n }\n}\n\nimpl Writable for Vec {\n fn write(&self, output: &mut Output) {\n self[..].write(output);\n }\n}\n\nmacro_rules! write_to_string {\n ($t:ident) => {\n impl Writable for $t {\n fn write(&self, output: &mut Output) {\n self.to_string().write(output);\n }\n }\n };\n}\n\nwrite_to_string!(u8);\nwrite_to_string!(u16);\nwrite_to_string!(u32);\nwrite_to_string!(u64);\nwrite_to_string!(u128);\nwrite_to_string!(usize);\nwrite_to_string!(i8);\nwrite_to_string!(i16);\nwrite_to_string!(i32);\nwrite_to_string!(i64);\nwrite_to_string!(i128);\nwrite_to_string!(isize);\nwrite_to_string!(f32);\nwrite_to_string!(f64);\n\nimpl Writable for (T, U) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n }\n}\n\nimpl Writable for (T, U, V) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n output.put(b' ');\n self.2.write(output);\n }\n}\n\npub static mut OUTPUT: Option = None;\n\npub fn output() -> &'static mut Output {\n unsafe {\n match &mut OUTPUT {\n None => {\n panic!(\"Panic\");\n }\n Some(output) => output,\n }\n }\n}\n\n#[macro_export]\nmacro_rules! out {\n ($first: expr $(,$args:expr )*) => {\n output().print(&$first);\n $(output().put(b' ');\n output().print(&$args);\n )*\n }\n}\n\n#[macro_export]\nmacro_rules! out_line {\n ($first: expr $(, $args:expr )* ) => {\n out!($first $(,$args)*);\n output().put(b'\\n');\n };\n () => {\n output().put(b'\\n');\n };\n}\n}\n}\npub mod math {\npub mod euclid {\n\n\npub fn gcd(mut a: u64, mut b: u64) -> u64 {\n while b != 0 {\n let t = a % b;\n a = b;\n b = t;\n }\n a\n}\n\npub fn lcm(a: u64, b: u64) -> u64 {\n a / gcd(a, b) * b\n}\n}\npub mod modular {\npub mod primitive {\nuse crate::io::output::{Output, Writable};\nuse std::ops::{Add, AddAssign, Mul, Neg};\n\n#[derive(Copy, Clone)]\npub struct ModularType(u32);\n\npub trait Modular:\n Add\n + AddAssign\n + Mul\n + Neg\n + From\n + From\n + From\n + From\n + Writable\n + Copy\n{\n const MODULO: u32;\n fn value(&self) -> u32;\n fn usize(&self) -> usize {\n self.value() as usize\n }\n}\n\nimpl Modular for ModularType {\n const MODULO: u32 = M;\n\n fn value(&self) -> u32 {\n self.0\n }\n}\n\nimpl Add for ModularType {\n type Output = ModularType;\n\n fn add(self, rhs: Self) -> Self::Output {\n let result = self.0 + rhs.0;\n ModularType(if result >= M { result - M } else { result })\n }\n}\n\nimpl AddAssign for ModularType {\n fn add_assign(&mut self, rhs: Self) {\n self.0 += rhs.0;\n if self.0 >= M {\n self.0 -= M;\n }\n }\n}\n\nimpl Mul for ModularType {\n type Output = ModularType;\n\n fn mul(self, rhs: Self) -> Self::Output {\n Self((self.0 as u64 * rhs.0 as u64 % M as u64) as u32)\n }\n}\n\nimpl Neg for ModularType {\n type Output = ModularType;\n\n fn neg(self) -> Self::Output {\n Self(if self.0 == 0 { 0 } else { M - self.0 })\n }\n}\n\nimpl From for ModularType {\n fn from(x: u32) -> Self {\n Self(x % M)\n }\n}\n\nimpl From for ModularType {\n fn from(x: i32) -> Self {\n Self(x.rem_euclid(M as i32) as u32)\n }\n}\n\nimpl From for ModularType {\n fn from(x: usize) -> Self {\n Self((x % M as usize) as u32)\n }\n}\n\nimpl Into for ModularType {\n fn into(self) -> usize {\n self.0 as usize\n }\n}\n\nimpl Writable for ModularType {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n }\n}\n\nimpl From for ModularType {\n fn from(x: u64) -> Self {\n Self((x % M as u64) as u32)\n }\n}\n}\n}\npub mod sieve {\n\n\npub fn get_all_divisors_for_all_up_to(n: usize) -> Vec> {\n let mut d = vec![Vec::new(); n + 1];\n for i in 1..=n {\n for j in (i..=n).step_by(i) {\n d[j].push(i);\n }\n }\n d\n}\n\npub fn euler_function_up_to(n: usize) -> Vec {\n let mut phi = vec![0; n + 1];\n for i in 1..=n {\n phi[i] = i;\n }\n for i in 2..=n {\n if phi[i] == i {\n for j in (i..=n).step_by(i) {\n phi[j] -= phi[j] / i;\n }\n }\n }\n phi\n}\n}\n}\nfn main() {\n let mut sin = std::io::stdin();\n let input = crate::io::input::Input::new(&mut sin);\n unsafe {\n crate::io::output::OUTPUT = Some(crate::io::output::Output::new(Box::new(std::io::stdout())));\n }\n crate::solution::run(input);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "bc2ed4914b9f83fddc76e239ccad5781", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\n\n#[derive(Debug, Copy, Clone, PartialEq)]\nenum Color {\n C,\n Y,\n M,\n U,\n}\n\nimpl Color {\n fn create(c: char) -> Self {\n match c {\n 'C' => Color::C,\n 'Y' => Color::Y,\n 'M' => Color::M,\n _ => Color::U,\n }\n }\n}\n\npub fn main() {\n let input = get_input();\n let length = input.len();\n let mut unknowns = 0;\n let mut two_solutions = false;\n let mut unknown_location = 0;\n //println!(\"{:?}\", input);\n if input[0] == Color::U {\n two_solutions = true;\n }\n for i in 1..length {\n if input[i] == Color::U {\n if i == length - 1 || i == 0 ||\n input[i + 1] == input[i - 1] || input[i - 1] == Color::U {\n two_solutions = true;\n }\n } else if input[i] == input[i - 1] {\n println!(\"No\");\n return;\n }\n }\n if two_solutions {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n}\n\nfn get_input() -> Vec {\n let mut input = String::new();\n io::stdin().read_line(&mut input);\n let mut input = String::new();\n io::stdin().read_line(&mut input);\n input.trim().chars().map(|c| Color::create(c)).collect()\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "79f857ce110f39ddbed6baac5a963561", "src_uid": "f8adfa0dde7ac1363f269dbdf00212c3", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! read {\n ( $( $type_:ty ),+ ) => {\n {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"error while reading line\");\n let tokens : Vec = line.as_str().split_whitespace().map(|x| x.to_string()).collect();\n let mut _tokens : &[String] = &tokens;\n ($(\n {\n let tmp : $type_ = _tokens[0].parse().expect(\"error while parsing value\");\n _tokens = &_tokens[1..];\n tmp\n }\n ),*)\n }\n };\n}\nmacro_rules! read_vec {\n ( $type_:ty ) => {\n {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"error while reading line\");\n line.as_str().split_whitespace().map(|x| x.parse().expect(\"error while parsing\")).collect::>()\n }\n };\n}\nmacro_rules! lazy_constant {\n (static $name:ident: $type_:ty = $initializer:expr;) => {\n use std::sync::{Once, ONCE_INIT};\n use std::boxed::Box;\n static INIT: Once = ONCE_INIT;\n static mut VALUE: *const $type_ = 0 as * const $type_;\n INIT.call_once(|| {\n unsafe {\n VALUE = Box::into_raw(Box::new($initializer));\n }\n });\n let $name: & $type_ = unsafe { VALUE.as_ref().unwrap() };\n };\n}\nuse std::io;\nfn main() {\n let _ = read!(i32);\n let text = read!(String);\n let text = text.as_bytes();\n for i in 1 .. text.len() {\n if text[i - 1] == text[i] && text[i] != b'?' {\n println!(\"No\");\n return;\n }\n }\n for i in 0 .. text.len() {\n if text[i] == b'?' {\n if i == 0 || i == (text.len() - 1) {\n println!(\"Yes\");\n return;\n }\n if text[i + 1] == b'?' {\n println!(\"Yes\");\n return;\n }\n if text[i - 1] == text[i + 1] {\n println!(\"Yes\");\n return;\n }\n }\n }\n println!(\"No\");\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "45f47a033a07e8b8c68f6962780b9b17", "src_uid": "f8adfa0dde7ac1363f269dbdf00212c3", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _gcd(a: usize, b: usize) -> usize {\n let mut x = a.max(b);\n let mut y = a.min(b);\n while y != 0 {\n let aux = x;\n x = y;\n y = aux % y;\n }\n x\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let m: usize = scan.next();\n let z: usize = scan.next();\n let gcd_nm = _gcd(n, m);\n let mcm_nm = n * m / gcd_nm;\n println!(\"{}\", z / mcm_nm);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "d70378f7ad81fb3f6132aa8d5cf25467", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\n#[allow(unused)]\nfn read_string() -> String {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string)\n .ok()\n .expect(\"\u041e\u0448\u0438\u0431\u043a\u0430 \u0447\u0442\u0435\u043d\u0438\u044f \u0432\u0432\u043e\u0434\u0430\");\n string.trim().to_string()\n}\n\n#[allow(unused)]\nfn read_vec_i32() -> Vec:: {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string)\n .ok()\n .expect(\"\u041e\u0448\u0438\u0431\u043a\u0430 \u0447\u0442\u0435\u043d\u0438\u044f \u0432\u0432\u043e\u0434\u0430\");\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n let value = value.parse::().unwrap();\n v.push(value);\n }\n return v;\n}\n\nfn main() {\n\n let params = read_vec_i32();\n let n = params[0] as usize;\n let m = params[1] as usize;\n let z = params[2] as usize;\n\n let mut res: i32 = 0;\n for i in 1 .. z + 1 {\n if i % n == 0 && i % m == 0 {\n res += 1;\n }\n }\n println!(\"{}\", res);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "92341fe046021563cb9e6c616d5e53ce", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min,Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n,m,z) = readln!(i32,i32,i32);\n let mut res = 0;\n for i in 1..(z+1) {\n if (i%n) == 0 && (i%m) == 0 {\n res += 1;\n }\n }\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "ea49c97a4ad51467f0566f54ca69272d", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String{\n let mut line = String::new();\n\n io::stdin().read_line(&mut line)\n .expect(\"Failed to read line\");\n\n line.trim().to_string()\n}\n\nfn gcd(a: i32, b: i32) -> i32{\n if b > a {return gcd(b, a)}\n if b == 0 {return a}\n gcd(b, (a % b))\n}\n\n\nfn main() {\n let vals = read_line()\n .split_whitespace()\n .map(|x| x.parse().expect(\"parse int error\"))\n .collect::>();\n let n = vals.get(0).unwrap();\n let m = vals.get(1).unwrap();\n let z = vals.get(2).unwrap();\n let lcm = n / gcd(*n, *m) * m;\n let res = z / lcm;\n\n println!(\"{}\", res);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "6b89389f0ffe8f79092f1b9361fe8b39", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn gcd(a: i32, b: i32) -> i32 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = input.i();\n let b = input.i();\n let c = input.i();\n println!(\"{}\", c * gcd(a,b) / a / b);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "3253d6a1fb700376360e39f1a03a68ad", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! read_line {\n ($v:ident) => {\n let mut temp = String::new();\n std::io::stdin().read_line(&mut temp).unwrap();\n let $v = temp;\n };\n (var, $t:ty, $($v:ident), *) => {\n read_line!(input_line);\n let mut iter = parse_token!($t, input_line);\n $(\n let $v = iter.next().unwrap();\n )*\n };\n (vec, $t:ty, $v:ident) => {\n read_line!(input_line);\n let iter = parse_token!($t, input_line);\n let $v: Vec<$t> = iter.collect();\n };\n ($($v:ident; $t:ty), *) => {\n read_line!(input_line);\n let mut iter = input_line.split_whitespace();\n $(\n let $v: $t = iter.next().unwrap().parse().unwrap();\n )*\n };\n}\n\nmacro_rules! parse_token {\n ($t:ty, $e:expr) => {\n $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());\n };\n}\n\nfn main() {\n read_line!(call_interval;i32,come_interval;i32,day_length;i32);\n let mut min = come_interval;\n let mut count = 0;\n while min <= day_length {\n if min % call_interval == 0 {\n count += 1;\n }\n min += come_interval;\n }\n println!(\"{}\", count);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "c361a2292060503ba84f40f5a3558bba", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_num() -> usize {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n usize::from_str(input.trim()).unwrap()\n}\n\nfn get_nums() -> Vec {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n input\n .trim()\n .split_whitespace()\n .map(|s| usize::from_str(s).unwrap())\n .collect::>()\n}\n\nfn main() {\n let n = get_num();\n let a = get_nums();\n\n let mut mn = std::usize::MAX;\n for i in 1..n - 1 {\n let mut mx = std::usize::MIN;\n let mut v = a.clone();\n v.remove(i);\n\n for j in 0..v.len() - 1 {\n mx = std::cmp::max(mx, v[j + 1] - v[j]);\n }\n\n mn = std::cmp::min(mn, mx);\n }\n\n println!(\"{}\", mn);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "9dd612e14d77c4b7a59b6d0b080974ac", "src_uid": "8a8013f960814040ac4bf229a0bd5437", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let a = input.vi(n);\n let mut sol = 0;\n for i in 1..n {\n m!(>, sol, a[i] - a[i-1]);\n }\n let mut res = 1000;\n for i in 1..=n-2 {\n m!(<, res, a[i+1] - a[i-1]);\n }\n println!(\"{}\", sol.max(res));\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "30db273482c3d9bd0848658db242d47d", "src_uid": "8a8013f960814040ac4bf229a0bd5437", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let n = {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n iter.next().unwrap().parse::().unwrap()\n };\n\n let a: Vec = {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace().map(|it| it.parse().unwrap()).collect()\n };\n\n let dif: Vec = (1..n)\n .map(|it| a[it] - a[it - 1])\n .collect();\n let min_sum_diff = (1..dif.len())\n .map(|it| dif[it] + dif[it - 1])\n .min()\n .unwrap();\n let max_in_diff = *dif.iter()\n .max()\n .unwrap();\n\n println!(\"{}\", max_in_diff.max(min_sum_diff));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "1a45e296abfb02fdcc37fa6789f8945c", "src_uid": "8a8013f960814040ac4bf229a0bd5437", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n// use proconio::input;\nuse std::cmp::Ordering::*;\nuse std::collections::{BTreeMap, BTreeSet};\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\nmacro_rules! answer {\n ($out:ident, $ans:expr) => {\n writeln!($out, \"{}\", $ans)\n };\n}\n\nfn solve(mut a: Vec, i: usize) -> i32 {\n a.remove(i);\n a.windows(2).map(|v| v[1] - v[0]).max().unwrap()\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let n: usize = scan.token();\n let a: Vec = (0..n).map(|_| scan.token()).collect();\n\n let ans = (1..n-1).map(|i| solve(a.clone(), i)).min().unwrap();\n\n answer!(out, ans)\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "43340bf595590b6da3cecd258cd794ff", "src_uid": "8a8013f960814040ac4bf229a0bd5437", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n//const INF: i32 = 0x3f3f3f3f;\n\nstruct Scanner {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n while self.buffer.is_empty() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n self.buffer = input.split_whitespace().map(ToString::to_string).collect();\n }\n let front = self.buffer.pop_front().unwrap();\n front.parse::().ok().unwrap()\n }\n}\n\nfn gcd(mut a: i64, mut b: i64) -> i64 {\n while b > 0 {\n a %= b;\n let tmp = a;\n a = b;\n b = tmp;\n }\n a\n}\n\nfn solution() {\n let mut scanner = Scanner::new();\n let n: i64 = scanner.next();\n let k: i64 = scanner.next();\n let a: i64 = scanner.next();\n let b: i64 = scanner.next();\n\n let mut x = std::i64::MAX;\n let mut y = 0;\n for i in 0..n {\n if a + i * k >= n * k {\n break;\n }\n for j in [b - a, a + b, a + i * k - b, a + i * k + b, i * k - a + b, i * k - a - b].iter() {\n let mut l = *j;\n if l < 0 {\n l = -l;\n }\n if l == 0 {\n l = n * k;\n }\n let m = n * k / gcd(l, n * k);\n x = std::cmp::min(x, m);\n y = std::cmp::max(y, m);\n }\n }\n println!(\"{} {}\", x, y);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(50 << 20)\n .spawn(solution)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "417a01a1d4b3006ea7b9535208a513c5", "src_uid": "5bb4adff1b332f43144047955eefba0c", "difficulty": 1700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n *\n * Author : fcbruce \n *\n * Time : Sat 10 Feb 2018 19:40:59\n *\n */\n\nfn check(x: i32, y: i32, z: i32) -> bool {\n return x < y && y < z && x + y > z;\n}\n\nfn main() {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).unwrap();\n\n let n: i32 = buffer.trim().parse::().unwrap() + 1;\n\n let mut sum = 0;\n\n for x in 1..n {\n for y in 1..x {\n let z = x ^ y;\n if z < n && check(y, x, z) {\n sum += 1;\n }\n }\n }\n\n println!(\"{}\", sum);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "64734adba1b68f57dda3390970e4a5a7", "src_uid": "838f2e75fdff0f13f002c0dfff0b2e8d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get().parse::().unwrap());\n ($t:ty) => (get().parse::<$t>().unwrap());\n }\n \n let n = get!();\n let mut ans = 0;\n for a in 1..n+1 {\n for b in a..n+1 {\n let c = a ^ b;\n if c >= b && c <= n && a + b > c {\n // println!(\"{} {} {}\", a, b, c);\n ans += 1;\n }\n }\n }\n \n println!(\"{}\", ans);\n \n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "5c35b0ba0c2d69033927daf923bb4bc3", "src_uid": "838f2e75fdff0f13f002c0dfff0b2e8d", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::prelude::*;\nuse std::io;\nuse std::str::FromStr;\n#[cfg(local)]\nuse std::fs::File;\n#[cfg(local)]\nuse std::io::BufReader;\n\n#[cfg(local)]\nfn buf_read() -> io::Result<(Vec)> {\n let f = try!(File::open(\"input.txt\"));\n let input_lines: Vec<_> = BufReader::new(f).lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\n#[cfg(not(local))]\nfn buf_read() -> io::Result<(Vec)> {\n let stdin = io::stdin();\n let input_lines: Vec<_> = stdin.lock().lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\nfn main() {\n type Element = String;\n let input = buf_read().unwrap();\n let mut input_vectors: Vec> = vec![];\n for input_line in input {\n let input_str: Vec = input_line.split(' ').map(String::from).collect();\n let mut input_vector: Vec = vec![];\n for input_elem_str in input_str {\n let elem: Element = Element::from_str(input_elem_str.as_str()).unwrap();\n input_vector.push(elem);\n }\n input_vectors.push(input_vector);\n }\n let mut k = i64::from_str(&input_vectors[0][1]).unwrap();\n let mut i = 0;\n let mut str = input_vectors[1][0].char_indices();\n // let mut str2 = str.clone();\n // let mut str3 = str.clone();\n // let g_position = str2.position(|(u, c)| c == 'G').unwrap() as i64;\n // let t_position = str3.position(|(u, c)| c == 'T').unwrap() as i64;\n let mut start_flag = 0;\n let mut result_flag = 0;\n\n for c in str {\n if start_flag == 1 {\n i += 1;\n if i % k != 0 {\n continue;\n }\n }\n // println!(\"{:?}\", c);\n match c {\n (n, c) => {\n if c == '#' {\n // println!(\"{:?}\", c);\n if start_flag == 1 {\n break;\n }\n } else if c == 'G' || c == 'T' {\n // println!(\"{:?}\", c);\n // println!(\"{:?}\", start_flag);\n\n if start_flag == 0 {\n start_flag = 1;\n } else {\n result_flag = 1;\n break;\n }\n }\n }\n }\n // println!{\"{:?}\", c};\n }\n if result_flag == 0 {\n println!(\"No\");\n } else {\n println!(\"Yes\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d0bb3a271473852742be7ce08156d405", "src_uid": "189a9b5ce669bdb04b9d371d74a5dd41", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\nuse std::thread;\nuse std::cmp::*;\nfn exec() {\n let mut sc = Scanner::new();\n let _: usize = sc.ne();\n let k: usize = sc.ne();\n let a = sc.ne::().into_bytes();\n let start = a.iter().position(|&x| x == b'G').unwrap();\n let goal = a.iter().position(|&x| x == b'T').unwrap();\n let s = min(start, goal);\n let g = max(start, goal);\n let mut ok = true;\n if (g - s) % k != 0 {\n println!(\"NO\");\n std::process::exit(0);\n }\n let mut cur = s;\n while cur != g {\n if a[cur] == b'#' {\n ok = false;\n }\n cur += k;\n }\n println!(\"{}\", if ok { \"YES\" } else { \"NO\" });\n}\n\n\nfn main() {\n const DEFAULT_STACK: usize = 16 * 1024 * 1024;\n let builder = thread::Builder::new();\n let th = builder.stack_size(DEFAULT_STACK);\n let handle = th.spawn(|| { exec(); }).unwrap();\n let _ = handle.join();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => return None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => panic!(\"parse error\"),\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "1e5a862e30de907ed2f535cd5d4db059", "src_uid": "189a9b5ce669bdb04b9d371d74a5dd41", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n\n std::io::stdin().read_line(&mut input).expect(\"INPUT::Read line failed\");\n\n let real_max_len = input.trim().len();\n let a_amount = input.trim().matches('a').collect::>().len();\n let theory_max_len = a_amount + a_amount - 1;\n\n if a_amount > real_max_len / 2 {\n println!(\"{}\", real_max_len);\n }else {\n println!(\"{}\", theory_max_len);\n }\n\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "cf9a9186f6e6f52cdc5a891a30a125f6", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::{stderr, stdin, stdout, BufWriter, StdoutLock, Write};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::{i64, u64, usize};\n#[allow(unused_macros)]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; ( $ next : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , [ $ t : tt ] ) => { { let len = read_value ! ( $ next , usize ) ; ( 0 .. len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n#[allow(dead_code)]\nstruct Writer {\n s: String,\n}\n#[allow(unused_imports)]\nuse std::fmt::Display;\n#[allow(dead_code)]\n#[doc = \" let mut writer = Writer::new();\"]\n#[doc = \" writer.writeln(hoge);\"]\n#[doc = \" writer.flush()\"]\nimpl Writer {\n #[allow(dead_code)]\n pub fn new() -> Writer {\n Writer { s: String::new() }\n }\n #[allow(dead_code)]\n pub fn flush(&mut self) {\n print!(\"{}\", self.s);\n self.s.clear();\n }\n pub fn write(&mut self, x: T) {\n self.s.push_str(&format!(\"{}\", x));\n }\n pub fn writeln(&mut self, x: T) {\n self.s.push_str(&format!(\"{}\", x));\n self.s.push('\\n');\n }\n #[allow(dead_code)]\n pub fn write_vec(&mut self, xs: &Vec) {\n if xs.len() == 0 {\n self.writeln(\"\");\n return;\n }\n self.write(&format!(\"{}\", xs[0]));\n for i in 1..xs.len() {\n self.write(&format!(\" {}\", xs[i]));\n }\n self.writeln(\"\");\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! dbg { ( $ ( $ a : expr ) ,* ) => { writeln ! ( & mut stderr ( ) , concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) . unwrap ( ) ; } }\n#[allow(dead_code)]\nconst INF_U: u64 = 1_000_000_000_000_000;\n#[allow(dead_code)]\nconst INF_I: i64 = 1_000_000_000_000_000;\n#[allow(non_snake_case)]\n#[allow(dead_code)]\nfn main() {\n input! {\n s: chars\n }\n let mut a_num = 0;\n for &ss in &s {\n if ss == 'a' {\n a_num += 1;\n }\n }\n if a_num > s.len() / 2 {\n println!{\"{}\", s.len()};\n } else {\n println!{\"{}\", a_num * 2 - 1};\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "5303c530d01f48ef3606de9bcdd0db72", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, stdin};\n\nfn main() -> io::Result<()> {\n let mut buffer = String::new();\n let input = stdin();\n input.read_line(&mut buffer)?;\n let a = buffer.matches(\"a\").count();\n let len = buffer.trim().len();\n if 2 * a > len {\n println!(\"{}\", len);\n } else {\n println!(\"{}\", a * 2 - 1);\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "29c8958b0e831cbdb33a5c67aa07eee6", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n//const INF: i32 = 0x3f3f3f3f;\n\nstruct Scanner {\n buffer: std::collections::VecDeque\n}\n\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn next(&mut self) -> T {\n while self.buffer.is_empty() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n self.buffer = input.split_whitespace()\n .map(ToString::to_string).collect();\n }\n let front = self.buffer.pop_front().unwrap();\n front.parse::().ok().unwrap()\n }\n}\n\nfn main1() {\n let mut scan = Scanner::new();\n let s = scan.next::();\n let l = s.chars().count();\n let n = s.chars().filter(|&ch| ch == 'a').count();\n let ans = min(2 * n - 1, l);\n println!(\"{}\", ans);\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "e808b3e17bf974290ee1b9d17556f69c", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read,stdin};\n\nfn main() {\n let mut buf = String::new();\n stdin().read_to_string(&mut buf).unwrap();\n let mut tok = buf.split_whitespace();\n let mut get = || tok.next().unwrap();\n \n let s = get().as_bytes();\n let n = s.len();\n let a = s.iter().filter(|c|**c==b'a').count();\n let ans = if a + a > n { n } else { a + a - 1 };\n println!(\"{:?}\", ans);\n \n \n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "b7bf91d3bcd97684db75dc70a2c8b750", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let buf = buf.trim();\n \n let length = buf.len();\n let count_as = buf.chars().filter(|&c| c == 'a').count();\n \n if (2 * count_as) > length {\n println!(\"{}\", length);\n } else {\n println!(\"{}\", 2 * count_as - 1);\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d7f3b15c26fd41ab959efbc49673aac9", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n io::stdin().read_to_string(&mut input)?;\n let input = input.trim();\n\n let mut all_a = 0;\n for letter in input.chars() {\n if letter == 'a' {\n all_a += 1\n }\n }\n let len = input.len();\n if all_a > (len / 2) {\n println!(\"{}\", len);\n } else {\n println!(\"{}\", all_a * 2 - 1);\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "c38aa1b06398d06112a8a3053ba0074f", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n: i64 = input.p();\n let mut a = 1;\n let mut b = 2;\n let mut sol = 0;\n while b <= n {\n let c = a + b;\n a = b;\n b = c;\n sol += 1;\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "e9fbd592acd2622ca9b0aa2d8ab9dcb6", "src_uid": "3d3432b4f7c6a3b901161fa24b415b14", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::prelude::*;\nuse std::io;\nuse std::str::FromStr;\n#[cfg(local)]\nuse std::fs::File;\n#[cfg(local)]\nuse std::io::BufReader;\n\n#[cfg(local)]\nfn buf_read() -> io::Result<(Vec)> {\n let f = try!(File::open(\"input.txt\"));\n let input_lines: Vec<_> = BufReader::new(f).lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\n#[cfg(not(local))]\nfn buf_read() -> io::Result<(Vec)> {\n let stdin = io::stdin();\n let input_lines: Vec<_> = stdin.lock().lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\nfn main() {\n type Element = i64;\n let input = buf_read().unwrap();\n let mut input_vectors: Vec> = vec![];\n for input_line in input {\n let input_str: Vec = input_line.split(' ').map(String::from).collect();\n let mut input_vector: Vec = vec![];\n for input_elem_str in input_str {\n let elem: Element = Element::from_str(input_elem_str.as_str()).unwrap();\n input_vector.push(elem);\n }\n input_vectors.push(input_vector);\n }\n\n let mut match_num = 0;\n let mut minimum_papticipants = 2;\n let mut minimum_papticipants2 = 1;\n let mut paticipants = input_vectors[0][0];\n\n while minimum_papticipants <= paticipants {\n let tmp = minimum_papticipants;\n minimum_papticipants = minimum_papticipants + minimum_papticipants2;\n minimum_papticipants2 = tmp;\n match_num += 1;\n }\n println!(\"{}\", match_num);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "376f649a9bb7c9834be34bc182005536", "src_uid": "3d3432b4f7c6a3b901161fa24b415b14", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: u64,\n }\n let mut ans = 1;\n let mut a = 2;\n let mut b = 3;\n while b <= n {\n ans += 1;\n let c = a + b;\n a = b;\n b = c;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "dp", "combinatorics"], "code_uid": "ead61232a69df4401c2e3a6725456dfb", "src_uid": "3d3432b4f7c6a3b901161fa24b415b14", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let _n: usize = read(sin);\n let mut input: Vec = reads(sin);\n\n input.sort();\n\n let ans: Vec = input.into_iter().map(|x| x.to_string()).collect();\n\n println!(\"{}\", ans.join(\" \"));\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "1569d001378115ae8f13dc11066ce702", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\n\nfn main() {\n let stdin = io::stdin();\n let _ : u64 = read_t(&stdin);\n let mut cs : Vec = vec![];\n read_ts(&stdin, &mut cs);\n cs.sort();\n let mut first = true;\n for c in cs {\n if first {\n first = false;\n print!(\"{}\", c);\n } else {\n print!(\" {}\", c);\n }\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "858187a712593dd3dbc0cecdd2121b1c", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect()\n}\nfn main() {\n let mut n = readln()[0];\n let mut a = readln();\n a.sort();\n\n for x in a {\n print!(\"{} \", x);\n }\n}", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "d80560cf43eddef7576f5e60b59cfec4", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::io::BufRead;\n\nuse std::fmt::Write;\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n\n lines.next().unwrap().expect(\"input reading failed\");\n let input_string = lines.next().unwrap().expect(\"input reading failed\");\n let mut numbers: Vec = input_string.split(\" \").map(|x| x.parse::().unwrap()).collect();\n numbers.sort();\n\n let mut output = String::with_capacity(500);\n let mut sorted_iter = numbers.iter();\n\n let first = sorted_iter.next().unwrap();\n\n write!(output, \"{}\", first).unwrap();\n for x in sorted_iter {\n write!(output, \" {}\", x).unwrap();\n }\n\n println!(\"{}\", output);\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "fd963e1a3b291dcf265cee04e0865df5", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::mem;\nuse std::io;\nuse std::string;\nuse std::cmp::*;\n\nfn load() -> Vec {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let vec: Vec<&str> = line.split(\" \").collect();\n let mut data : Vec = Vec::new();\n for i in vec {\n let el : i32 = i.trim().parse().unwrap();\n data.push(el);\n }\n data\n}\n\nfn main() {\n let s = load();\n let mut a = load();\n a.sort();\n for i in a {\n print!(\"{} \", i);\n }\n println!(\"\");\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "a18d5444cad7186561ad29b6be911200", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.clear();\n io::stdin().read_line(&mut s).unwrap();\n let mut a : Vec = s.split_whitespace().map(|s| s.parse().unwrap()).collect();\n a.sort();\n for e in a.iter() {\n print!(\"{} \", e);\n }\n}", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "dfea8a21b57bddf4c4876cc4bf27a51a", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i() as usize;\n let mut a = input.ai(n);\n a.sort();\n a.iter().for_each(|x| print!(\"{} \", x));\n}\n\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "df74746f79785bac1f2ff18c48230933", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::io::{BufWriter, stdin, stdout, Write};\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n\tlet n = scan.next::();\n let f = (0..n).map(|_| scan.next::()).collect::>();\n let m = f.iter().max().unwrap();\n\n let h = *m;\n let w = n;\n\n let mut mtr = vec![vec![0; n]; *m];\n\n for i in 0..h {\n for j in 0..w {\n let x = j;\n let y = h - i;\n if y <= f[x] {\n mtr[i][j] = 1;\n }\n }\n }\n for i in 0..h {\n mtr[i].sort();\n }\n\n let mut v = vec![0; w];\n for x in 0..w {\n for y in 0..h {\n v[x] = v[x] + mtr[y][x];\n }\n }\n\n writeln!(out, \"{}\", v.iter().fold(String::new(), |acc, &x| acc + &x.to_string() + \" \")).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "fb6abd5bf55d534502775aa7d7f659f1", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"error\");\n\n let size = 'z' as i32 - 'a' as i32 + 1;\n\n let mut sum = 0;\n let mut old_char = 'a';\n\n for c in input.trim().chars() {\n sum += std::cmp::min(\n (old_char as i32 - c as i32).abs(),\n size - (old_char as i32 - c as i32).abs(),\n );\n old_char = c;\n }\n println!(\"{}\", sum);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "43d1ec34a6719d09f686864d2c5502d7", "src_uid": "ecc890b3bdb9456441a2a265c60722dd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, stdout, Write, Read};\nuse std::cmp::{max, min};\n\ntype Result = ::std::result::Result>;\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\n#[allow(dead_code)]\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n fn next_two(&mut self) -> (T, T) {\n let a;\n loop {\n if let Some(token) = self.buffer.pop() {\n a = token.parse().ok().expect(\"Failed parse\");\n break;\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n\n loop {\n if let Some(token) = self.buffer.pop() {\n return (a, token.parse().ok().expect(\"Failed parse\"));\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() -> Result<()>{\n let mut scan = Scanner::default();\n\n let word: String = scan.next();\n\n let word: Vec = word.chars().map(|ch| ch as i32).collect();\n let mut pos = 1;\n let mut dist = 0;\n for ch in word {\n dist += min((pos - ch + 96).abs(), 26 - max(ch - 96, pos) + min(ch - 96, pos));\n pos = ch - 96;\n\n }\n println!(\"{}\", dist);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "6b119f4c7c61220ac8bc6486a84e00a6", "src_uid": "ecc890b3bdb9456441a2a265c60722dd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let input: String = scan.next();\n let mut current = 0isize;\n let mut result = 0isize;\n for item in input.chars() {\n let dst: isize = item as isize - 'a' as isize;\n result += (dst - current).abs()\n .min(26 - current + dst)\n .min(26 - dst + current);\n current = dst;\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "2072c25954a9cc2416202dbe31d7a654", "src_uid": "ecc890b3bdb9456441a2a265c60722dd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/731/problem/A\n\nfn forward_dist(mut c1: u8, c2: u8) -> u64 {\n let mut dist = 0;\n while c1 != c2 {\n c1 = (c1 + 1) % 26;\n dist += 1;\n }\n dist\n}\n\nfn backward_dist(mut c1: u8, c2: u8) -> u64 {\n let mut dist = 0;\n while c1 != c2 {\n if c1 == 0 { c1 = 25; }\n else { c1 -= 1; }\n dist += 1;\n }\n dist\n}\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let bytes = buf.trim().as_bytes();\n let mut last = 0;\n let mut total = 0;\n for &b in bytes {\n let b = b - b'a';\n total += std::cmp::min(forward_dist(last, b), backward_dist(last, b));\n last = b;\n }\n println!(\"{}\", total);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "4a30d27a40e8413388ff38c056925378", "src_uid": "ecc890b3bdb9456441a2a265c60722dd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::mem::size_of_val;\nuse std::cmp::{max, min};\nuse std::rc::Rc;\nuse std::collections::btree_map::BTreeMap;\nuse std::io::{Write, BufRead};\nuse std::collections::HashMap;\nuse std::ptr::write_volatile;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused)]\nfn read_strings() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n v\n}\n\n#[allow(unused)]\nfn read_array_i32() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.split_whitespace().map(|x| x.parse::().unwrap()).collect()\n}\n\n\n#[allow(unused_macros)]\nmacro_rules! read_array {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap())\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n// mod math;\n// mod binary_search;\n// mod graph;\n// mod structure;\n// mod fibonacci;\n// mod string;\n// mod permutations;\n// mod patterns;\n\n\n#[allow(dead_code)]\nfn memory_properties(value: &T)\n where\n T: std::fmt::Display + ?Sized,\n{\n println!(\n \"Variable address in memory = {:p}, Allocated bytes for type = {}\",\n value,\n size_of_val(value)\n );\n}\n\n#[allow(unused_macros)]\nmacro_rules! sum {\n ($($x:expr), *) => {\n {\n let mut res = 0;\n $(res += $x;)*\n res\n }\n };\n}\n\nstatic mut array: [[u8;51];51] = [[0u8; 51]; 51];\n\nfn main() {\n use std::io::Write;\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n\n let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];\n let s = gets();\n let mut res = 0;\n let mut idx = 26;\n for ch in s.bytes() {\n let mut l = idx;\n let mut r = idx;\n\n while l > 0 && arr[l as usize] as u8 != ch {\n l -= 1;\n }\n while r < arr.len() as u8 && arr[r as usize] as u8 != ch {\n r += 1;\n }\n if idx - l <= r - idx {\n res += (idx - l) as i32;\n idx = l % 26 + 26;\n }else {\n res += (r - idx) as i32;\n idx = r % 26 + 26;\n }\n }\n writeln!(out, \"{}\", res);\n\n // writeln!(out, \"{}\", \"Hello Rust\").unwrap();\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "dfc26193486a6a3351ee843bc5fdba79", "src_uid": "ecc890b3bdb9456441a2a265c60722dd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let sol = input.bs().iter().fold((b'a',0), |(c,res),&a| {\n let d = (a as i32) - (c as i32);\n let t = [-26, 0, 26].iter()\n .map(|x| (d + x).abs()).min().unwrap();\n (a, res + t)\n }).1;\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "83e28e9848231a358f272b9ed3e80336", "src_uid": "ecc890b3bdb9456441a2a265c60722dd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let s = String::from(\"a\") + readln!().as_ref();\n let ans = s.chars().zip(s.chars().skip(1)).map(|(x,y)|{ min((x as u8 + 26 - y as u8) % 26, (y as u8 + 26 - x as u8) % 26) as i32 } ).sum::();\n println!(\"{}\",ans);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "423563f1af904b49237a29f5f125baed", "src_uid": "ecc890b3bdb9456441a2a265c60722dd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn hash(a: &[usize], cnt: &[usize]) -> usize {\n let mut hash = 0;\n for i in 0..10 {\n hash = (cnt[i] + 1) * hash + a[i];\n }\n hash\n}\n\nfn decode(mut hash: usize, cnt: &[usize]) -> Vec {\n let mut d = vec![];\n for i in (0..10).rev() {\n d.push(hash % (cnt[i] + 1));\n hash /= cnt[i] + 1;\n }\n d.reverse();\n d\n}\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let mut n: u64 = it.next().unwrap().parse().unwrap();\n let m: usize = it.next().unwrap().parse().unwrap();\n let mut cnt = vec![0; 10];\n while n > 0 {\n let k = (n % 10) as usize;\n cnt[k] += 1;\n n /= 10;\n }\n let mut step = vec![1; 10];\n for i in (0..9).rev() {\n step[i] = step[i + 1] * (cnt[i + 1] + 1);\n }\n let hash_sup = hash(&cnt, &cnt) + 1;\n let mut dp = vec![0u64; hash_sup * m];\n let mut used = vec![false; hash_sup * m];\n dp[(hash_sup - 1) * m + 0] = 1;\n used[(hash_sup - 1) * m + 0] = true;\n let mut q = std::collections::VecDeque::new();\n q.push_back((hash_sup - 1) * m + 0);\n while let Some(v) = q.pop_front() {\n let rem = v % m;\n let h = v / m;\n let a = decode(h, &cnt);\n for d in 0..10 {\n if a[d] > 0 && !(d == 0 && a == cnt) {\n let r = (10 * rem + d) % m;\n let u = (h - step[d]) * m + r;\n dp[u] += dp[v];\n if !used[u] {\n used[u] = true;\n q.push_back(u);\n }\n }\n }\n }\n let ans = dp[0 * m + 0];\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "combinatorics", "bitmasks", "number theory"], "code_uid": "0b4dd4caa38956c4c4109484e27cd015", "src_uid": "5eb90c23ffa3794fdddc5670c0373829", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let mut n: u64 = it.next().unwrap().parse().unwrap();\n let m: usize = it.next().unwrap().parse().unwrap();\n let p = 10;\n let mut cnt = vec![0; p];\n while n > 0 {\n let k = (n % p as u64) as usize;\n cnt[k] += 1;\n n /= p as u64;\n }\n let mut step = vec![1; p + 1];\n for i in (0..p).rev() {\n step[i] = step[i + 1] * (cnt[i] + 1);\n }\n let len = step[0];\n let mut dp = vec![vec![0u64; len]; m];\n dp[0][len - 1] = 1;\n let mut q = std::collections::VecDeque::new();\n q.push_back((0, len - 1));\n while let Some((rem, v)) = q.pop_front() {\n for d in 0..p {\n let a = v % step[d] / step[d + 1];\n if a > 0 && !(d == 0 && v == len - 1) {\n let u = v - step[d + 1];\n let r = (10 * rem + d) % m;\n if dp[r][u] == 0 {\n q.push_back((r, u));\n }\n dp[r][u] += dp[rem][v];\n }\n }\n }\n let ans = dp[0][0];\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "combinatorics", "bitmasks", "number theory"], "code_uid": "d97e615c4cc666cc36e42aa3f8d05354", "src_uid": "5eb90c23ffa3794fdddc5670c0373829", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt,$x:expr,$y:expr) => {{\n\t\tlet b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet mut c0 = vec![1; 10];\n\tfor x in rin.vb() {\n\t\tc0[(x - b'0') as usize] += 1;\n\t}\n\tlet m = rin.u();\n\tlet mut ns = 1;\n\tfor &c in c0.iter() {\n\t\tns *= c;\n\t}\n\tlet encode = |a: &[usize]| -> usize {\n\t\tlet mut res = 0;\n\t\tfor i in 0..10 {\n\t\t\tres = res * c0[i] + a[i];\n\t\t}\n\t\tres\n\t};\n\tlet decode = |a: &mut [usize], mut x: usize| {\n\t\tfor i in (0..10).rev() {\n\t\t\ta[i] = x % c0[i];\n\t\t\tx /= c0[i];\n\t\t}\n\t};\n\tlet mut dp = vec![vec![0; m]; ns];\n\tdp[0][0] = 1_i64;\n\tfor s in 0..ns {\n\t\tlet mut a = vec![0; 10];\n\t\tdecode(&mut a, s);\n\t\tlet st = if s == 0 {1} else {0};\n\t\tfor r in 0..m {\n\t\t\tlet v = dp[s][r];\n\t\t\tif v == 0 { continue; }\n\t\t\tfor i in st..10 {\n\t\t\t\tif a[i]+1 < c0[i] {\n\t\t\t\t\ta[i] += 1;\n\t\t\t\t\tlet ss = encode(&a);\n\t\t\t\t\tdp[ss][(r * 10 + i) % m] += v;\n\t\t\t\t\ta[i] -= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlet sol = dp[ns-1][0];\n\twriteln!(rout, \"{}\", sol).ok();\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "combinatorics", "bitmasks", "number theory"], "code_uid": "74468a07999a1313856bf0c851223416", "src_uid": "5eb90c23ffa3794fdddc5670c0373829", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn hash(a: &[u64], cnt: &[u64]) -> u64 {\n let mut hash = 0;\n for i in 0..10 {\n hash = (cnt[i] + 1) * hash + a[i];\n }\n hash\n}\n\nfn decode(mut hash: u64, cnt: &[u64]) -> Vec {\n let mut d = vec![];\n for i in (0..10).rev() {\n d.push(hash % (cnt[i] + 1));\n hash /= cnt[i] + 1;\n }\n d.reverse();\n d\n}\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let mut n: u64 = it.next().unwrap().parse().unwrap();\n let m: usize = it.next().unwrap().parse().unwrap();\n let mut cnt = vec![0; 10];\n let mut len = 0;\n while n > 0 {\n let k = (n % 10) as usize;\n cnt[k] += 1;\n len += 1;\n n /= 10;\n }\n let mut now = std::collections::BTreeMap::new();\n now.insert((hash(&cnt, &cnt), 0), 1u64);\n for p in 0..len {\n let mut next = std::collections::BTreeMap::new();\n for (k, v) in now.iter() {\n let (h, rem) = *k;\n let a = decode(h, &cnt);\n for d in 0..10 {\n if a[d] > 0 && !(p == 0 && d == 0) {\n let mut b = a.clone();\n b[d] -= 1;\n let r = (10 * rem + d) % m;\n *next.entry((hash(&b, &cnt), r)).or_insert(0u64) += *v;\n }\n }\n }\n now = next;\n }\n let mut ans = 0;\n for (k, v) in now.iter() {\n if k.1 == 0 {\n ans += *v;\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "combinatorics", "bitmasks", "number theory"], "code_uid": "1b1737773a3a5f32d68ee1a6cb09e875", "src_uid": "5eb90c23ffa3794fdddc5670c0373829", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let _n: usize = scan.next();\n let input: Vec = scan.next::().chars().collect();\n let mut cnt = 0usize;\n let mut res = 0usize;\n if input[0] == 'x' {\n cnt += 1\n };\n for i in 1..input.len() {\n if input[i] == 'x' {\n if input[i - 1] == 'x' {\n if cnt + 1 >= 3 {\n res += 1;\n } else {\n cnt += 1;\n }\n } else {\n cnt = 1;\n }\n } else {\n cnt = 0;\n }\n }\n println!(\"{}\", res);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "b17b2646bf0de5edb2465c12bea803ac", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\nuse std::io;\nuse std::io::Read;\n\nfn main() {\n let mut mut_line = String::new();\n io::stdin().read_line(&mut mut_line).unwrap();\n io::stdin().read_line(&mut mut_line).unwrap();\n\n let mut remove_count = 0;\n let mut con_count = 0;\n\n for i in mut_line.into_bytes() {\n if i == 0x78 {\n con_count += 1;\n } else {\n remove_count += cmp::max(0, con_count - 2);\n con_count = 0;\n }\n }\n // We don't need the final one because the loop goes on for\n // len(input string) + 1 because of the trailing new line.\n println!(\"{}\", remove_count);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "e687cb7bb0ea8a3a6f47198e8f24678c", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Basics\n\n#![allow(unused_imports)]\n#![allow(dead_code)]\n\n//extern crate rand;\n\nuse std::io::prelude::*;\nuse std::mem;\nuse std::io;\nuse std::io::BufRead;\nuse std::io::BufReader;\nuse std::string;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::vec::Vec;\nuse std::collections::LinkedList;\nuse std::num;\nuse std::ops;\nuse std::ops::Index;\nuse std::fmt::Debug;\nuse std::str::FromStr;\nuse std::ops::Shr;\n\nstruct Cin {\n data: LinkedList,\n}\n\nimpl Cin {\n fn new() -> Self {\n Cin { data: LinkedList::new() }\n }\n fn read_line(&self) -> String {\n let mut s: String = String::new();\n io::stdin().read_line(&mut s).expect(\"err\");\n s\n }\n fn read_str(&mut self) -> String {\n if self.data.len() == 0 {\n let s = self.read_line();\n// let split = s.split(\"\\\\s+\");\n let split = s.split_whitespace();\n for el in split {\n self.data.push_back(String::from(el));\n }\n }\n self.data.pop_front().expect(\"empty\")\n }\n fn read_int(&mut self) -> i64 {\n self.read_str().parse().expect(\"err parse\")\n }\n fn read_vec(&mut self, ref size: i64) -> Vec {\n let mut v: Vec = Vec::new();\n for _i in 0..*size {\n v.push(self.read_int());\n }\n v\n }\n}\n\nfn main() {\n let mut cin = Cin::new();\n let n = cin.read_int() as usize;\n let line = cin.read_str();\n let mut sum = 0;\n for i in 0..n - 2 {\n sum += if line.index(i..i + 3) == \"xxx\" { 1 } else { 0 };\n }\n println!(\"{}\", sum);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "a4d2b16b098663afb41b5897f42d465b", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn main() {\n let mut text = String::new();\n std::io::stdin().read_to_string(&mut text).unwrap();\n\n let res: usize = text\n .split_whitespace()\n .skip(1)\n .map(|e| e.parse::().unwrap())\n .next()\n .unwrap()\n .split(|c| c != 'x')\n .filter_map(|s| if s.len() > 2 { Some(s.len() - 2 ) } else { None })\n .sum();\n println!(\"{}\", res);\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "cad57fa1c3e405afe6fdd1c0659f3bd4", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let _n = input.u();\n let sol = input.bs().split(|&c| c != b'x').map(|z| z.len().max(2) - 2).sum::();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "cff939567f92eaca468ffebcf69d7be7", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n if self.f[crt] { return; }\n self.c += 1;\n self.f[crt] = true;\n self.v.push(crt);\n self.vc[crt] = self.c;\n self.u[crt] = self.v.len()-1;\n for i in 0..self.e[crt].len() {\n self.dfs(self.e[crt][i]);\n }\n //debug!(crt, self.c, self.vc[crt]);\n self.vc[crt] = self.c - self.vc[crt];\n }\n}\n\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let s:Vec = read::().chars().collect();\n\n let mut cnt = 0;\n let mut ans = 0;\n for i in 0..n {\n if s[i]=='x' {\n cnt += 1;\n } else {\n if cnt >= 3 {\n ans += cnt-2;\n }\n cnt = 0;\n }\n }\n println!(\"{}\", ans+max(0,cnt-2));\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "b5078d79230146f3fec99153f513b856", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n\n let amount = input.trim().parse::().expect(\"AMOUNT::parse to usize failed\");\n input.clear();\n\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n let mut chars = input.trim().chars();\n\n let mut max_length = i32::default();\n let mut vec = vec![];\n loop {\n match chars.next() {\n Some(value) => {\n if value == 'x' {\n max_length += 1;\n } else {\n vec.push(max_length);\n max_length = 0;\n }\n\n },\n\n None => {\n if max_length != 0 {\n vec.push(max_length);\n }\n break;\n }\n }\n }\n\n\n\n let mut modify_times = i32::default();\n for item in vec.iter() {\n if *item >= 3 {\n modify_times += item - 2;\n }\n }\n\n println!(\"{}\", modify_times);\n\n}", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "4ec3e8d8ed4057c9ccf4306561aa466b", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn raw_input() -> String {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n}\n\nfn main() {\n {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n }\n\n let input = raw_input();\n let (mut x_count, mut to_remove) = (0, 0);\n for c in input.chars() {\n if c == 'x' {\n if x_count >= 2 {\n to_remove += 1;\n }\n x_count += 1;\n } else {\n x_count = 0;\n }\n }\n\n print!(\"{}\", to_remove);\n}", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "2f133830cdbe8abd0d7da94a7bff0377", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1242/problem/A\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::io::Write;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn gcd(a: i64, b: i64) -> i64 {\n if b == 0 {\n a\n } else {\n gcd(b, a%b)\n }\n}\n\nfn main() {\n input! {\n n: i64\n };\n\n let mut ans = n;\n for i in 1..n+1 {\n if i * i > n {\n break;\n }\n if n % i == 0 {\n if i >= 2 {\n ans = gcd(ans, i);\n }\n if n/i >= 2 {\n ans = gcd(ans, n/i);\n }\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "number theory"], "code_uid": "e2c9b17e648f6fb2caa17183ba73d7d2", "src_uid": "f553e89e267c223fd5acf0dd2bc1706b", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub trait Readable {\n type Output;\n fn words_count() -> usize;\n fn read_words(words: &[&str]) -> Result;\n}\n#[macro_export]\nmacro_rules! readable {\n ( $ t : ty , $ words_count : expr , |$ words : ident | $ read_words : expr ) => {\n impl Readable for $t {\n type Output = $t;\n fn words_count() -> usize {\n $words_count\n }\n fn read_words($words: &[&str]) -> Result<$t, String> {\n Ok($read_words)\n }\n }\n };\n}\nreadable!((), 1, |_ss| ());\nreadable!(String, 1, |ss| ss[0].to_string());\nimpl Readable for char {\n type Output = char;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result {\n let chars: Vec = words[0].chars().collect();\n if chars.len() == 1 {\n Ok(chars[0])\n } else {\n Err(format!(\"cannot parse `{}` as a char\", words[0]))\n }\n }\n}\npub struct Chars();\nimpl Readable for Chars {\n type Output = Vec;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result, String> {\n Ok(words[0].chars().collect())\n }\n}\nmacro_rules ! impl_readable_for_ints { ( $ ( $ t : ty ) * ) => { $ ( impl Readable for $ t { type Output = Self ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result <$ t , String > { use std :: str :: FromStr ; <$ t >:: from_str ( words [ 0 ] ) . map_err ( | _ | { format ! ( \"cannot parse `{}` as {}\" , words [ 0 ] , stringify ! ( $ t ) ) } ) } } ) * } ; }\nimpl_readable_for_ints ! ( i8 u8 i16 u16 i32 u32 i64 u64 isize usize f32 f64 ) ;\nmacro_rules ! define_one_origin_int_types { ( $ new_t : ident $ int_t : ty ) => { # [ doc = \" Converts 1-origin integer into 0-origin when read from stdin.\" ] # [ doc = \"\" ] # [ doc = \" # Example\" ] # [ doc = \"\" ] # [ doc = \" ```no_run\" ] # [ doc = \" # #[macro_use] extern crate atcoder_snippets;\" ] # [ doc = \" # use atcoder_snippets::read::*;\" ] # [ doc = \" // Stdin: \\\"1\\\"\" ] # [ doc = \" read!(a = usize_);\" ] # [ doc = \" assert_eq!(a, 0);\" ] # [ doc = \" ```\" ] # [ allow ( non_camel_case_types ) ] pub struct $ new_t ; impl Readable for $ new_t { type Output = $ int_t ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { <$ int_t >:: read_words ( words ) . map ( | n | n - 1 ) } } } ; ( $ new_t : ident $ int_t : ty ; $ ( $ inner_new_t : ident $ inner_int_t : ty ) ;* ) => { define_one_origin_int_types ! ( $ new_t $ int_t ) ; define_one_origin_int_types ! ( $ ( $ inner_new_t $ inner_int_t ) ;* ) ; } ; }\ndefine_one_origin_int_types ! ( u8_ u8 ; u16_ u16 ; u32_ u32 ; u64_ u64 ; usize_ usize ) ;\nmacro_rules ! impl_readable_for_tuples { ( $ t : ident $ var : ident ) => ( ) ; ( $ t : ident $ var : ident ; $ ( $ inner_t : ident $ inner_var : ident ) ;* ) => { impl_readable_for_tuples ! ( $ ( $ inner_t $ inner_var ) ;* ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,*> Readable for ( $ t , $ ( $ inner_t ) ,* ) { type Output = ( <$ t >:: Output , $ ( <$ inner_t >:: Output ) ,* ) ; fn words_count ( ) -> usize { let mut n = <$ t >:: words_count ( ) ; $ ( n += <$ inner_t >:: words_count ( ) ; ) * n } # [ allow ( unused_assignments ) ] fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { let mut start = 0 ; let $ var = <$ t >:: read_words ( & words [ start .. start +<$ t >:: words_count ( ) ] ) ?; start += <$ t >:: words_count ( ) ; $ ( let $ inner_var = <$ inner_t >:: read_words ( & words [ start .. start +<$ inner_t >:: words_count ( ) ] ) ?; start += <$ inner_t >:: words_count ( ) ; ) * Ok ( ( $ var , $ ( $ inner_var ) ,* ) ) } } } ; }\nimpl_readable_for_tuples ! ( T8 x8 ; T7 x7 ; T6 x6 ; T5 x5 ; T4 x4 ; T3 x3 ; T2 x2 ; T1 x1 ) ;\npub trait ReadableFromLine {\n type Output;\n fn read_line(line: &str) -> Result;\n}\nfn split_into_words(line: &str) -> Vec<&str> {\n #[allow(deprecated)]\n line.trim_right_matches('\\n').split_whitespace().collect()\n}\nimpl ReadableFromLine for T {\n type Output = T::Output;\n fn read_line(line: &str) -> Result {\n let words = split_into_words(line);\n if words.len() != T::words_count() {\n return Err(format!(\n \"line `{}` has {} words, expected {}\",\n line,\n words.len(),\n T::words_count()\n ));\n }\n T::read_words(&words)\n }\n}\nmacro_rules ! impl_readable_from_line_for_tuples_with_from_iterator { ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident ) => { impl <$ u : Readable > ReadableFromLine for $ seq_in where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = $ seq_out ; fn read_line ( line : & str ) -> Result <$ seq_out , String > { let n = $ u :: words_count ( ) ; let words = split_into_words ( line ) ; if words . len ( ) % n != 0 { return Err ( format ! ( \"line `{}` has {} words, expected multiple of {}\" , line , words . len ( ) , n ) ) ; } let mut result = Vec :: new ( ) ; for chunk in words . chunks ( n ) { match $ u :: read_words ( chunk ) { Ok ( v ) => result . push ( v ) , Err ( msg ) => { let flagment_msg = if n == 1 { format ! ( \"word {}\" , result . len ( ) ) } else { let l = result . len ( ) ; format ! ( \"words {}-{}\" , n * l + 1 , ( n + 1 ) * l ) } ; return Err ( format ! ( \"{} of line `{}`: {}\" , flagment_msg , line , msg ) ) ; } } } Ok ( result . into_iter ( ) . collect ( ) ) } } impl < T : Readable , $ u : Readable > ReadableFromLine for ( T , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( T :: Output , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let n = T :: words_count ( ) ; # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; Ok ( ( T :: read_words ( words ) ?, <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident , $ ( $ inner_t : ident $ inner_var : ident ) ,+ ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ seq_in , $ seq_out ; $ ( $ inner_t $ inner_var ) ,+ ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,+ , $ u : Readable > ReadableFromLine for ( $ t , $ ( $ inner_t ) ,+ , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( $ t :: Output , $ ( $ inner_t :: Output ) ,+ , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let mut n = $ t :: words_count ( ) ; $ ( n += $ inner_t :: words_count ( ) ; ) + # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; let ( $ var , $ ( $ inner_var ) ,* ) = < ( $ t , $ ( $ inner_t ) ,+ ) >:: read_words ( words ) ?; Ok ( ( $ var , $ ( $ inner_var ) ,* , <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; }\n#[macro_export]\nmacro_rules ! readable_collection { ( $ u : ident => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 x4 , T3 x3 , T2 x2 , T1 x1 ) ; } ; ( $ u : ident : $ ( $ bound : path ) ,* => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 x4 , T3 x3 , T2 x2 , T1 x1 ) ; } }\nreadable_collection ! ( U => Vec < U >, Vec < U :: Output > ) ;\nreadable_collection ! ( U => std :: collections :: VecDeque < U >, std :: collections :: VecDeque < U :: Output > ) ;\nreadable_collection ! ( U : Eq , std :: hash :: Hash => std :: collections :: HashSet < U >, std :: collections :: HashSet < U :: Output > ) ;\nreadable_collection ! ( U : Ord => std :: collections :: BTreeSet < U >, std :: collections :: BTreeSet < U :: Output > ) ;\nreadable_collection ! ( U : Ord => std :: collections :: BinaryHeap < U >, std :: collections :: BinaryHeap < U :: Output > ) ;\npub fn read() -> T::Output {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n T::read_line(&line).unwrap()\n}\n#[macro_export]\nmacro_rules ! read { ( ) => { let mut line = String :: new ( ) ; std :: io :: stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; } ; ( $ pat : pat = $ t : ty ) => { let $ pat = read ::<$ t > ( ) ; } ; ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { read ! ( ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) ) ; } ; }\n#[macro_export]\nmacro_rules ! readls { ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { $ ( read ! ( $ pat = $ t ) ; ) * } ; }\npub fn readx() -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result = stdin\n .lock()\n .lines()\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n result\n}\n#[macro_export]\nmacro_rules ! readx_loop { ( |$ pat : pat = $ t : ty | $ body : expr ) => { { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; for line in stdin . lock ( ) . lines ( ) { let line = line . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readx_loop ! ( | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub fn readn(n: usize) -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result: Vec = stdin\n .lock()\n .lines()\n .take(n)\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n if result.len() < n {\n panic!(\n \"expected reading {} lines, but only {} lines are read\",\n n,\n result.len()\n );\n }\n result\n}\n#[macro_export]\nmacro_rules ! readn_loop { ( $ n : expr , |$ pat : pat = $ t : ty | $ body : expr ) => { { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; let mut lock = stdin . lock ( ) ; for _ in 0 ..$ n { let mut line = String :: new ( ) ; lock . read_line ( & mut line ) . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( $ n : expr , |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readn_loop ! ( $ n , | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub trait Words {\n fn read(&self) -> T::Output;\n}\nimpl<'a> Words for [&'a str] {\n fn read(&self) -> T::Output {\n T::read_words(self).unwrap()\n }\n}\nimpl<'a> Words for &'a str {\n fn read(&self) -> T::Output {\n T::read_words(&[self]).unwrap()\n }\n}\n\nmacro_rules! forward_ref_unop {\n ( impl $ op : ident , $ method : ident for $ t : ty ) => {\n impl std::ops::$op for &$t {\n type Output = <$t as std::ops::$op>::Output;\n fn $method(self) -> <$t as std::ops::$op>::Output {\n std::ops::$op::$method(*self)\n }\n }\n };\n}\nmacro_rules! forward_ref_binop {\n ( impl $ op : ident , $ method : ident for $ t : ty , $ u : ty ) => {\n impl<'a> std::ops::$op<$u> for &'a $t {\n type Output = <$t as std::ops::$op<$u>>::Output;\n fn $method(self, other: $u) -> <$t as std::ops::$op<$u>>::Output {\n std::ops::$op::$method(*self, other)\n }\n }\n impl std::ops::$op<&$u> for $t {\n type Output = <$t as std::ops::$op<$u>>::Output;\n fn $method(self, other: &$u) -> <$t as std::ops::$op<$u>>::Output {\n std::ops::$op::$method(self, *other)\n }\n }\n impl std::ops::$op<&$u> for &$t {\n type Output = <$t as std::ops::$op<$u>>::Output;\n fn $method(self, other: &$u) -> <$t as std::ops::$op<$u>>::Output {\n std::ops::$op::$method(*self, *other)\n }\n }\n };\n}\nmacro_rules! forward_ref_op_assign {\n ( impl $ op : ident , $ method : ident for $ t : ty , $ u : ty ) => {\n impl std::ops::$op<&$u> for $t {\n fn $method(&mut self, other: &$u) {\n std::ops::$op::$method(self, *other);\n }\n }\n };\n}\npub trait PrimitiveInteger:\nSized\n + Ord\n + std::ops::Add\n + std::ops::Sub\n + std::ops::Div\n{\n fn one() -> Self;\n fn abs_diff(self, rhs: Self) -> Self;\n fn rem_euclid(self, rhs: Self) -> Self;\n}\nmacro_rules ! impl_primitive_integer { ( $ ( $ t : ty ) * ) => { $ ( impl PrimitiveInteger for $ t { fn one ( ) -> $ t { 1 } fn abs_diff ( self , rhs : $ t ) -> $ t { if self < rhs { rhs - self } else { self - rhs } } # [ allow ( unused_comparisons ) ] fn rem_euclid ( self , rhs : $ t ) -> $ t { let r = self % rhs ; if r < 0 { if rhs < 0 { r - rhs } else { r + rhs } } else { r } } } ) * } }\nimpl_primitive_integer ! ( u8 u16 u32 u64 usize i8 i16 i32 i64 isize ) ;\npub trait PrimitiveUnsigned: PrimitiveInteger {\n fn ceil_div(self, rhs: Self) -> Self;\n fn round_div(self, rhs: Self) -> Self;\n fn log2(self) -> Option;\n fn ceil_log2(self) -> Option;\n fn sqrt(self) -> Self;\n}\nmacro_rules ! impl_primitive_unsigned { ( $ ( $ t : ty ) * ) => { $ ( impl PrimitiveUnsigned for $ t { fn ceil_div ( self , rhs : $ t ) -> $ t { ( self + rhs - 1 ) / rhs } fn round_div ( self , rhs : $ t ) -> $ t { ( self + rhs / 2 ) / rhs } fn log2 ( mut self ) -> Option <$ t > { if self == 0 { None } else { let mut ans = 0 ; while self > 1 { ans += 1 ; self /= 2 ; } Some ( ans ) } } fn ceil_log2 ( self ) -> Option <$ t > { self . log2 ( ) . map ( | x | { ( self + ( ( 1 << x ) - 1 ) ) . log2 ( ) . unwrap ( ) } ) } fn sqrt ( self ) -> $ t { ( self as f64 ) . sqrt ( ) as $ t } } ) * } }\nimpl_primitive_unsigned ! ( u8 u16 u32 u64 usize ) ;\npub fn gcd(a: u64, b: u64) -> u64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\npub fn bezout(a: i64, b: i64) -> (i64, i64, u64) {\n let (x, y, g) = bezout_sub((a * a.signum()) as u64, (b * b.signum()) as u64);\n (x * a.signum(), y * b.signum(), g)\n}\nfn bezout_sub(a: u64, b: u64) -> (i64, i64, u64) {\n if b == 0 {\n (1, 0, a)\n } else {\n let m = (a / b) as i64;\n let (x, y, g) = bezout_sub(b, a % b);\n (y, x - m * y, g)\n }\n}\n\nfn divs(n: u64) -> Vec {\n let mut res = Vec::new();\n for d in 2..((n as f64).sqrt() as u64)+1 {\n if n % d == 0 {\n res.push(d);\n if n != d*d {\n res.push(n / d);\n }\n }\n }\n res\n}\n\nfn main() {\n read!(n = u64);\n let ans = divs(n).into_iter().fold(n, |acc, d| gcd(acc, d));\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "number theory"], "code_uid": "774860cc20a8dfa509943d53e8122458", "src_uid": "f553e89e267c223fd5acf0dd2bc1706b", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::collections::{HashSet, BTreeSet};\n\nmacro_rules! readln {\n () => {{ let mut line = String::new(); stdin().read_line(&mut line).unwrap(); line }};\n ($type:ty) => {{ readln!().split_whitespace().next().unwrap().parse::<$type>().unwrap() }};\n (|$type_vec:ty|) => {{ readln!().split_whitespace().map(|it| it.parse().unwrap()).collect::>() }};\n ($($type:ty),*) => {{ let line = readln!(); let mut iter = line.split_whitespace(); ($(iter.next().unwrap().parse::<$type>().unwrap(),)*) }};\n ($($type:ty),*, |$type_vec:ty|) => {{ let line = readln!(); let mut iter = line.split_whitespace();\n ($(iter.next().unwrap().parse::<$type>().unwrap(),)*iter.map(|it| it.parse().unwrap()).collect::>(),)}};\n}\n\nfn re2(mut n: u64) -> BTreeSet {\n let mut res = BTreeSet::new();\n let mut mb = BTreeSet::new();\n let copy = n;\n let mut i = 2;\n while n != 1 && i * i <= copy && res.len() != 2 {\n if n % i == 0 {\n n /= i;\n res.insert(i);\n mb.insert(copy / i);\n } else {\n i += 1;\n }\n }\n mb.insert(n);\n res.remove(&1);\n if res.len() == 2 {\n return res;\n }\n mb.iter().for_each(|it| {\n let mut flag = true;\n for j in res.iter() {\n if *it % *j == 0 {\n flag = false;\n }\n }\n if flag {\n res.insert(*it);\n }\n });\n res.remove(&1);\n if res.is_empty() {\n res.insert(copy);\n return res;\n }\n\n res\n}\n\nfn main() {\n let mut n = readln!(u64);\n\n let res = re2(n);\n \n if res.is_empty() {\n println!(\"{}\", n);\n } else if res.len() == 1 {\n println!(\"{}\", res.iter().next().unwrap());\n } else {\n println!(\"1\")\n }\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "abca82ca1fd9c4b0b25579d5fbb65ce8", "src_uid": "f553e89e267c223fd5acf0dd2bc1706b", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case, unused)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::*;\n\nmacro_rules! eprint {\n\t($($t:tt)*) => {{\n\t\tuse ::std::io::Write;\n\t\tlet _ = write!(::std::io::stderr(), $($t)*);\n\t}};\n}\nmacro_rules! eprintln {\n\t() => { eprintln!(\"\"); };\n\t($($t:tt)*) => {{\n\t\tuse ::std::io::Write;\n\t\tlet _ = writeln!(::std::io::stderr(), $($t)*);\n\t}};\n}\nmacro_rules! dbg {\n\t($v:expr) => {{\n\t\tlet val = $v;\n\t\teprintln!(\"[{}:{}] {} = {:?}\", file!(), line!(), stringify!($v), val);\n\t\tval\n\t}}\n}\n\nmacro_rules! mat {\n\t($($e:expr),*) => { Vec::from(vec![$($e),*]) };\n\t($($e:expr,)*) => { Vec::from(vec![$($e),*]) };\n\t($e:expr; $d:expr) => { Vec::from(vec![$e; $d]) };\n\t($e:expr; $d:expr $(; $ds:expr)+) => { Vec::from(vec![mat![$e $(; $ds)*]; $d]) };\n}\n\nmacro_rules! ok {\n\t($a:ident$([$i:expr])*.$f:ident()$(@$t:ident)*) => {\n\t\t$a$([$i])*.$f($($t),*)\n\t};\n\t($a:ident$([$i:expr])*.$f:ident($e:expr$(,$es:expr)*)$(@$t:ident)*) => { {\n\t\tlet t = $e;\n\t\tok!($a$([$i])*.$f($($es),*)$(@$t)*@t)\n\t} };\n}\n\npub fn readln() -> String {\n\tlet mut line = String::new();\n\t::std::io::stdin().read_line(&mut line).unwrap_or_else(|e| panic!(\"{}\", e));\n\tline\n}\n\nmacro_rules! read {\n\t($($t:tt),*; $n:expr) => {{\n\t\tlet stdin = ::std::io::stdin();\n\t\tlet ret = ::std::io::BufRead::lines(stdin.lock()).take($n).map(|line| {\n\t\t\tlet line = line.unwrap();\n\t\t\tlet mut it = line.split_whitespace();\n\t\t\t_read!(it; $($t),*)\n\t\t}).collect::>();\n\t\tret\n\t}};\n\t($($t:tt),*) => {{\n\t\tlet line = readln();\n\t\tlet mut it = line.split_whitespace();\n\t\t_read!(it; $($t),*)\n\t}};\n}\n\nmacro_rules! _read {\n\t($it:ident; [char]) => {\n\t\t_read!($it; String).chars().collect::>()\n\t};\n\t($it:ident; [u8]) => {\n\t\tVec::from(_read!($it; String).into_bytes())\n\t};\n\t($it:ident; usize1) => {\n\t\t$it.next().unwrap_or_else(|| panic!(\"input mismatch\")).parse::().unwrap_or_else(|e| panic!(\"{}\", e)) - 1\n\t};\n\t($it:ident; [usize1]) => {\n\t\t$it.map(|s| s.parse::().unwrap_or_else(|e| panic!(\"{}\", e)) - 1).collect::>()\n\t};\n\t($it:ident; [$t:ty]) => {\n\t\t$it.map(|s| s.parse::<$t>().unwrap_or_else(|e| panic!(\"{}\", e))).collect::>()\n\t};\n\t($it:ident; $t:ty) => {\n\t\t$it.next().unwrap_or_else(|| panic!(\"input mismatch\")).parse::<$t>().unwrap_or_else(|e| panic!(\"{}\", e))\n\t};\n\t($it:ident; $($t:tt),+) => {\n\t\t($(_read!($it; $t)),*)\n\t};\n}\n\npub fn main() {\n\tlet _ = ::std::thread::Builder::new().name(\"run\".to_string()).stack_size(32 * 1024 * 1024).spawn(run).unwrap().join();\n}\n\nconst MOD: u32 = 1_000_000_007;\nconst INF: i64 = std::i64::MAX;\n\npub trait SetMinMax {\n\tfn setmin(&mut self, v: Self) -> bool;\n\tfn setmax(&mut self, v: Self) -> bool;\n}\nimpl SetMinMax for T where T: PartialOrd {\n\tfn setmin(&mut self, v: T) -> bool {\n\t\t*self > v && { *self = v; true }\n\t}\n\tfn setmax(&mut self, v: T) -> bool {\n\t\t*self < v && { *self = v; true }\n\t}\n}\n\nuse std::cmp::Ordering;\n\n/// Equivalent to std::lowerbound and std::upperbound in c++\npub trait BinarySearch {\n fn lower_bound(&self, x: &T) -> usize;\n fn upper_bound(&self, x: &T) -> usize;\n}\n\nimpl BinarySearch for [T] {\n // \u914d\u5217a\u5185\u306ev\u4ee5\u4e0a\u306e\u6700\u5c0f\u306eindex\n fn lower_bound(&self, x: &T) -> usize {\n let mut low = 0;\n let mut high = self.len();\n\n while low != high {\n let mid = (low + high) / 2;\n match self[mid].cmp(x) {\n Ordering::Less => {\n low = mid + 1;\n }\n Ordering::Equal | Ordering::Greater => {\n high = mid;\n }\n }\n }\n low\n }\n // \u914d\u5217a\u5185\u306ev\u3088\u308a\u5927\u304d\u3044\u306e\u6700\u5c0f\u306eindex\n fn upper_bound(&self, x: &T) -> usize {\n let mut low = 0;\n let mut high = self.len();\n\n while low != high {\n let mid = (low + high) / 2;\n match self[mid].cmp(x) {\n Ordering::Less | Ordering::Equal => {\n low = mid + 1;\n }\n Ordering::Greater => {\n high = mid;\n }\n }\n }\n low\n }\n}\n\nfn swap(a: usize, b: usize, sv: &mut [char], tv: &mut [char]) {\n\tlet tmp = sv[a];\n\tsv[a] = tv[b];\n\ttv[b] = tmp;\n}\n\nfn solve() {\n\tlet n = read!(i64);\n\tlet mut sum = 0;\n\tlet mut v = vec![];\n\tif n==1 {\n\t\tprintln!(\"{}\", 1);\n\t\treturn;\n\t}\n\tfor i in 2..((n as f64).sqrt() as i64+1) {\n\t\tif n%i==0 {\n\t\t\tsum+=2;\n\t\t\tv.push(i);\n\t\t\tv.push(n/i);\n\t\t}\n\t}\n\tif sum==0 {\n\t\tprintln!(\"{}\", n);\n\t\treturn;\n\t}\n\tlet mi = v[0];\n\tlet mut flag = true;\n\tfor &i in &v {\n\t\tif i%mi!=0 {flag=false;}\n\t}\n\tif !flag {println!(\"{}\", 1);}\n\telse{ println!(\"{}\", mi);}\n\n}\n\nfn run() {\n solve();\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "c62b2d41070ce8311db1f187b6fcb99a", "src_uid": "f553e89e267c223fd5acf0dd2bc1706b", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut _n: u64 = scan.next();\n println!(\"25\");\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "86811b857aeddfd0677cfb5666d6229f", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){\n println!(\"25\");\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "309bdc37313975e27ca17f28ae0ba565", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n readln!();\n println!(\"25\");\n}\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "d632b805720b40538f79cbe355306488", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main(){print!(\"25\");}\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "92c26b93ef5cac2833ab5d10ffdceffe", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n println!(\"25\");\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "24167ed62d14705e98355c051f17f390", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n Geometry, math - https://codeforces.com/problemset/problem/1369/A\n Completed: 4/7/20 14:06\n*/\n\nuse std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n\n // This is so retarded\n println!(\"25\");\n\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "ade890f0d3108bb77286e66c722cb651", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n println!(\"{}\", 25);\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "912379223c7d9007b0e42498dc85785b", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::mem::size_of_val;\nuse std::cmp::{max, min};\nuse std::rc::Rc;\nuse std::collections::btree_map::BTreeMap;\nuse std::io::{Write, BufRead};\nuse std::collections::HashMap;\nuse std::ptr::write_volatile;\nuse std::ops::Add;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused)]\nfn read_strings() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n v\n}\n\n#[allow(unused)]\nfn read_array_i32() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.split_whitespace().map(|x| x.parse::().unwrap()).collect()\n}\n\n\n#[allow(unused_macros)]\nmacro_rules! read_array {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap())\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n// mod math;\n// mod binary_search;\n// mod graph;\n// mod structure;\n// mod fibonacci;\n// mod string;\n// mod permutations;\n\n// mod patterns;\n\n\n#[allow(dead_code)]\nfn memory_properties(value: &T)\n where\n T: std::fmt::Display + ?Sized,\n{\n println!(\n \"Variable address in memory = {:p}, Allocated bytes for type = {}\",\n value,\n size_of_val(value)\n );\n}\n\n#[allow(unused_macros)]\nmacro_rules! sum {\n ($($x:expr), *) => {\n {\n let mut res = 0;\n $(res += $x;)*\n res\n }\n };\n}\n\nfn main() {\n use std::io::Write;\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n\n gets();\n writeln!(out, \"{}\", 25);\n\n // writeln!(out, \"{}\", \"Hello Rust\").unwrap();\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "efe765b713ddbf88b7136b154a2ada58", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin ModInt ----------\r\n// \u30e2\u30f3\u30b4\u30e1\u30ea\u4e57\u7b97\u3092\u7528\u3044\u308b\r\n// \u307b\u307cCodeforces\u7528\r\n// \u6ce8\u610f\r\n// new_unchecked \u306f\u5024x\u304c 0 <= x < modulo \u3067\u3042\u308b\u3053\u3068\u3092\u4eee\u5b9a\r\n// ModInt \u306e\u4e2d\u8eab\u306f\u6b63\u898f\u5316\u3055\u308c\u305f\u5024\u3067\u6301\u3063\u3066\u308b\u306e\u3067\u76f4\u63a5\u8aad\u3093\u3060\u308a\u66f8\u3044\u305f\u308a\u3059\u308b\u3068\u3076\u3063\u58ca\u308c\u308b\r\n// \u5947\u7d20\u6570\u306e\u307f\r\nmod modint {\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n fn rem() -> u32;\r\n fn ini() -> u64;\r\n fn reduce(x: u64) -> u32 {\r\n debug_assert!(x < (Self::modulo() as u64) << 32);\r\n let b = (x as u32 * Self::rem()) as u64;\r\n let t = x + b * Self::modulo() as u64;\r\n let mut c = (t >> 32) as u32;\r\n if c >= Self::modulo() {\r\n c -= Self::modulo();\r\n }\r\n c as u32\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod1_000_000_007 {}\r\n\r\n impl Modulo for Mod1_000_000_007 {\r\n fn modulo() -> u32 {\r\n 1_000_000_007\r\n }\r\n fn rem() -> u32 {\r\n 2226617417\r\n }\r\n fn ini() -> u64 {\r\n 582344008\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod998_244_353 {}\r\n\r\n impl Modulo for Mod998_244_353 {\r\n fn modulo() -> u32 {\r\n 998_244_353\r\n }\r\n fn rem() -> u32 {\r\n 998244351\r\n }\r\n fn ini() -> u64 {\r\n 932051910\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub fn generate_umekomi_modulo(p: u32) {\r\n assert!(\r\n p < (1 << 31)\r\n && p > 2\r\n && p & 1 == 1\r\n && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0)\r\n );\r\n let mut t = 1u32;\r\n let mut s = !p + 1;\r\n let mut n = !0u32 >> 2;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n let mut ini = (1u64 << 32) % p as u64;\r\n ini = (ini << 32) % p as u64;\r\n assert!(t * p == !0);\r\n println!(\"pub enum Mod{} {{}}\", p);\r\n println!(\"impl Modulo for Mod{} {{\", p);\r\n println!(\" fn modulo() -> u32 {{\");\r\n println!(\" {}\", p);\r\n println!(\" }}\");\r\n println!(\" fn rem() -> u32 {{\");\r\n println!(\" {}\", t);\r\n println!(\" }}\");\r\n println!(\" fn ini() -> u64 {{\");\r\n println!(\" {}\", ini);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n let mut f = vec![];\r\n let mut n = p - 1;\r\n for i in 2.. {\r\n if i * i > n {\r\n break;\r\n }\r\n if n % i == 0 {\r\n f.push(i);\r\n while n % i == 0 {\r\n n /= i;\r\n }\r\n }\r\n }\r\n if n > 1 {\r\n f.push(n);\r\n }\r\n let mut order = 1;\r\n let mut n = p - 1;\r\n while n % 2 == 0 {\r\n n /= 2;\r\n order <<= 1;\r\n }\r\n let z = (2u64..)\r\n .find(|z| {\r\n f.iter()\r\n .all(|f| mod_pow(*z, ((p - 1) / *f) as u64, p as u64) != 1)\r\n })\r\n .unwrap();\r\n let zeta = mod_pow(z, ((p - 1) / order) as u64, p as u64);\r\n println!(\"impl transform::NTTFriendly for Mod{} {{\", p);\r\n println!(\" fn order() -> usize {{\");\r\n println!(\" {}\", order);\r\n println!(\" }}\");\r\n println!(\" fn zeta() -> u32 {{\");\r\n println!(\" {}\", zeta);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n }\r\n\r\n pub struct ModInt(u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::build(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 - rhs.0;\r\n if self.0 < rhs.0 {\r\n d += T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::build(T::reduce(self.0 as u64 * rhs.0 as u64))\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::build(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n fn build(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n Self::build(0)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n Self::build(T::reduce(d as u64 * T::ini()))\r\n }\r\n pub fn new(d: u32) -> Self {\r\n Self::new_unchecked(d % T::modulo())\r\n }\r\n pub fn one() -> Self {\r\n Self::new_unchecked(1)\r\n }\r\n pub fn get(&self) -> u32 {\r\n T::reduce(self.0 as u64)\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n pub fn inv(&self) -> Self {\r\n assert!(!self.is_zero());\r\n self.pow((T::modulo() - 2) as u64)\r\n }\r\n }\r\n\r\n pub fn mod_pow(mut r: u64, mut n: u64, m: u64) -> u64 {\r\n let mut t = 1 % m;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t = t * r % m;\r\n }\r\n r = r * r % m;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n// ---------- begin Precalc ----------\r\nmod precalc {\r\n use super::modint::*;\r\n #[allow(dead_code)]\r\n pub struct Precalc {\r\n inv: Vec>,\r\n fact: Vec>,\r\n ifact: Vec>,\r\n }\r\n #[allow(dead_code)]\r\n impl Precalc {\r\n pub fn new(n: usize) -> Precalc {\r\n let mut inv = vec![ModInt::one(); n + 1];\r\n let mut fact = vec![ModInt::one(); n + 1];\r\n let mut ifact = vec![ModInt::one(); n + 1];\r\n for i in 2..(n + 1) {\r\n fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);\r\n }\r\n ifact[n] = fact[n].inv();\r\n if n > 0 {\r\n inv[n] = ifact[n] * fact[n - 1];\r\n }\r\n for i in (1..n).rev() {\r\n ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);\r\n inv[i] = ifact[i] * fact[i - 1];\r\n }\r\n Precalc {\r\n inv: inv,\r\n fact: fact,\r\n ifact: ifact,\r\n }\r\n }\r\n pub fn inv(&self, n: usize) -> ModInt {\r\n assert!(n > 0);\r\n self.inv[n]\r\n }\r\n pub fn fact(&self, n: usize) -> ModInt {\r\n self.fact[n]\r\n }\r\n pub fn ifact(&self, n: usize) -> ModInt {\r\n self.ifact[n]\r\n }\r\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[n - k]\r\n }\r\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\r\n }\r\n }\r\n}\r\n// ---------- end Precalc ----------\r\n\r\nuse modint::*;\r\n\r\npub trait NTTFriendly: modint::Modulo {\r\n fn order() -> usize;\r\n fn zeta() -> u32;\r\n}\r\n\r\ntype M = ModInt;\r\n\r\nimpl NTTFriendly for Mod998_244_353 {\r\n fn order() -> usize {\r\n 8388608\r\n }\r\n fn zeta() -> u32 {\r\n 15311432\r\n }\r\n}\r\n\r\n// \u5217\u306b\u5bfe\u3059\u308b\u547d\u4ee4\u3092\u30c6\u30ad\u30c8\u30fc\u306b\u8a70\u3081\u3042\u308f\u305b\r\n// modint, primitive type \u306e\uff12\u3064\u3042\u305f\u308a\u3067\u4f7f\u3046\u3053\u3068\u3092\u60f3\u5b9a\r\n// +, -, *\r\n// zero \u3092\u8981\u6c42\u3057\u3066\u306a\u3044\u306e\u306b\u4eee\u5b9a\u3057\u3066\u308b\u5834\u6240\u304c\u3042\u308b\r\n//\r\n// \u4f55\u3082\u8003\u3048\u305a\u306b\u66f8\u304d\u59cb\u3081\u305f\u3089\u3044\u308d\u3044\u308d\u3088\u304f\u308f\u304b\u3089\u306a\u3044\u3053\u3068\u306b\u306a\u3063\u305f\r\n// \u6574\u7406\r\n// \u9577\u3055\u304c\u7b49\u3057\u3044\u3068\u304d\u306e\u52a0\u7b97\u3001\u6e1b\u7b97\u3001dot\u7a4d\u306fok\r\n// \u9577\u3055\u304c\u7570\u306a\u308b\u3068\u304d\u306f\u3069\u3046\u3059\u308b\uff1f\r\n// 0\u57cb\u3081\u3055\u308c\u3066\u308b\u3068\u3044\u3046\u30a4\u30e1\u30fc\u30b8\u306a\u306e\u3067\r\n// \u52a0\u7b97\u3001\u6e1b\u7b97\u306f\u7d20\u76f4\u3060\u304cdot\u7a4d\u306f\u30a4\u30de\u30a4\u30c1\r\n// dot\u7a4d\u3060\u3051\u9577\u3055\u304c\u7b49\u3057\u3044\u3068\u3057\u3066\u304a\u304f?\r\n// \u3042\u308b\u3044\u306f0\u57cb\u3081\u306e\u30a4\u30e1\u30fc\u30b8\u3092\u6d88\u3059\u304b\r\n\r\nuse std::ops::*;\r\n\r\npub trait Zero: Sized + Add {\r\n fn zero() -> Self;\r\n}\r\n\r\npub fn zero() -> T {\r\n T::zero()\r\n}\r\n\r\nimpl Zero for ModInt {\r\n fn zero() -> Self {\r\n Self::zero()\r\n }\r\n}\r\n\r\nimpl Zero for usize {\r\n fn zero() -> Self {\r\n 0\r\n }\r\n}\r\n\r\npub trait ArrayAdd {\r\n type Item;\r\n fn add(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayAdd for [T]\r\nwhere\r\n T: Zero + Copy,\r\n{\r\n type Item = T;\r\n fn add(&self, rhs: &[Self::Item]) -> Vec {\r\n let mut c = vec![T::zero(); self.len().max(rhs.len())];\r\n c[..self.len()].copy_from_slice(self);\r\n c.add_assign(rhs);\r\n c\r\n }\r\n}\r\n\r\npub trait ArrayAddAssign {\r\n type Item;\r\n fn add_assign(&mut self, rhs: &[Self::Item]);\r\n}\r\n\r\nimpl ArrayAddAssign for [T]\r\nwhere\r\n T: Add + Copy,\r\n{\r\n type Item = T;\r\n fn add_assign(&mut self, rhs: &[Self::Item]) {\r\n assert!(self.len() >= rhs.len());\r\n self.iter_mut().zip(rhs).for_each(|(x, a)| *x = *x + *a);\r\n }\r\n}\r\n\r\nimpl ArrayAddAssign for Vec\r\nwhere\r\n T: Zero + Add + Copy,\r\n{\r\n type Item = T;\r\n fn add_assign(&mut self, rhs: &[Self::Item]) {\r\n if self.len() < rhs.len() {\r\n self.resize(rhs.len(), T::zero());\r\n }\r\n self.as_mut_slice().add_assign(rhs);\r\n }\r\n}\r\n\r\npub trait ArraySub {\r\n type Item;\r\n fn sub(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArraySub for [T]\r\nwhere\r\n T: Zero + Sub + Copy,\r\n{\r\n type Item = T;\r\n fn sub(&self, rhs: &[Self::Item]) -> Vec {\r\n let mut c = vec![T::zero(); self.len().max(rhs.len())];\r\n c[..self.len()].copy_from_slice(self);\r\n c.sub_assign(rhs);\r\n c\r\n }\r\n}\r\n\r\npub trait ArraySubAssign {\r\n type Item;\r\n fn sub_assign(&mut self, rhs: &[Self::Item]);\r\n}\r\n\r\nimpl ArraySubAssign for [T]\r\nwhere\r\n T: Sub + Copy,\r\n{\r\n type Item = T;\r\n fn sub_assign(&mut self, rhs: &[Self::Item]) {\r\n assert!(self.len() >= rhs.len());\r\n self.iter_mut().zip(rhs).for_each(|(x, a)| *x = *x - *a);\r\n }\r\n}\r\n\r\nimpl ArraySubAssign for Vec\r\nwhere\r\n T: Zero + Sub + Copy,\r\n{\r\n type Item = T;\r\n fn sub_assign(&mut self, rhs: &[Self::Item]) {\r\n if self.len() < rhs.len() {\r\n self.resize(rhs.len(), T::zero());\r\n }\r\n self.as_mut_slice().sub_assign(rhs);\r\n }\r\n}\r\n\r\npub trait ArrayDot {\r\n type Item;\r\n fn dot(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayDot for [T]\r\nwhere\r\n T: Mul + Copy,\r\n{\r\n type Item = T;\r\n fn dot(&self, rhs: &[Self::Item]) -> Vec {\r\n assert!(self.len() == rhs.len());\r\n self.iter().zip(rhs).map(|p| *p.0 * *p.1).collect()\r\n }\r\n}\r\n\r\npub trait ArrayDotAssign {\r\n type Item;\r\n fn dot_assign(&mut self, rhs: &[Self::Item]);\r\n}\r\n\r\nimpl ArrayDotAssign for [T]\r\nwhere\r\n T: MulAssign + Copy,\r\n{\r\n type Item = T;\r\n fn dot_assign(&mut self, rhs: &[Self::Item]) {\r\n assert!(self.len() == rhs.len());\r\n self.iter_mut().zip(rhs).for_each(|(x, a)| *x *= *a);\r\n }\r\n}\r\n\r\npub trait ArrayMul {\r\n type Item;\r\n fn mul(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayMul for [T]\r\nwhere\r\n T: Zero + Mul + Copy,\r\n{\r\n type Item = T;\r\n fn mul(&self, rhs: &[Self::Item]) -> Vec {\r\n if self.is_empty() || rhs.is_empty() {\r\n return vec![];\r\n }\r\n let mut res = vec![zero(); self.len() + rhs.len() - 1];\r\n for (i, a) in self.iter().enumerate() {\r\n for (c, b) in res[i..].iter_mut().zip(rhs) {\r\n *c = *c + *a * *b;\r\n }\r\n }\r\n res\r\n }\r\n}\r\n\r\npub trait ArrayNTT {\r\n type Item;\r\n fn ntt(&mut self);\r\n fn intt(&mut self);\r\n fn multiply(&self, rhs: &[Self::Item]) -> Vec;\r\n}\r\n\r\nimpl ArrayNTT for [ModInt]\r\nwhere\r\n T: NTTFriendly,\r\n{\r\n type Item = ModInt;\r\n fn ntt(&mut self) {\r\n let f = self;\r\n let n = f.len();\r\n assert!(n.count_ones() == 1);\r\n assert!(n <= T::order());\r\n let len = n.trailing_zeros() as usize;\r\n let mut es = [ModInt::zero(); 30];\r\n let mut ies = [ModInt::zero(); 30];\r\n let mut sum_e = [ModInt::zero(); 30];\r\n let cnt2 = T::order().trailing_zeros() as usize;\r\n let mut e = ModInt::new_unchecked(T::zeta());\r\n let mut ie = e.inv();\r\n for i in (2..=cnt2).rev() {\r\n es[i - 2] = e;\r\n ies[i - 2] = ie;\r\n e = e * e;\r\n ie = ie * ie;\r\n }\r\n let mut now = ModInt::one();\r\n for i in 0..(cnt2 - 1) {\r\n sum_e[i] = es[i] * now;\r\n now *= ies[i];\r\n }\r\n for ph in 1..=len {\r\n let p = 1 << (len - ph);\r\n let mut now = ModInt::one();\r\n for (i, f) in f.chunks_exact_mut(2 * p).enumerate() {\r\n let (x, y) = f.split_at_mut(p);\r\n for (x, y) in x.iter_mut().zip(y.iter_mut()) {\r\n let l = *x;\r\n let r = *y * now;\r\n *x = l + r;\r\n *y = l - r;\r\n }\r\n now *= sum_e[(!i).trailing_zeros() as usize];\r\n }\r\n }\r\n }\r\n fn intt(&mut self) {\r\n let f = self;\r\n let n = f.len();\r\n assert!(n.count_ones() == 1);\r\n assert!(n <= T::order());\r\n let len = n.trailing_zeros() as usize;\r\n let mut es = [ModInt::zero(); 30];\r\n let mut ies = [ModInt::zero(); 30];\r\n let mut sum_ie = [ModInt::zero(); 30];\r\n let cnt2 = T::order().trailing_zeros() as usize;\r\n let mut e = ModInt::new_unchecked(T::zeta());\r\n let mut ie = e.inv();\r\n for i in (2..=cnt2).rev() {\r\n es[i - 2] = e;\r\n ies[i - 2] = ie;\r\n e = e * e;\r\n ie = ie * ie;\r\n }\r\n let mut now = ModInt::one();\r\n for i in 0..(cnt2 - 1) {\r\n sum_ie[i] = ies[i] * now;\r\n now *= es[i];\r\n }\r\n for ph in (1..=len).rev() {\r\n let p = 1 << (len - ph);\r\n let mut inow = ModInt::one();\r\n for (i, f) in f.chunks_exact_mut(2 * p).enumerate() {\r\n let (x, y) = f.split_at_mut(p);\r\n for (x, y) in x.iter_mut().zip(y.iter_mut()) {\r\n let l = *x;\r\n let r = *y;\r\n *x = l + r;\r\n *y = (l - r) * inow;\r\n }\r\n inow *= sum_ie[(!i).trailing_zeros() as usize];\r\n }\r\n }\r\n let ik = ModInt::new_unchecked((T::modulo() + 1) >> 1).pow(len as u64);\r\n for f in f.iter_mut() {\r\n *f *= ik;\r\n }\r\n }\r\n fn multiply(&self, rhs: &[Self::Item]) -> Vec {\r\n if self.len().min(rhs.len()) <= 32 {\r\n return self.mul(rhs);\r\n }\r\n let size = (self.len() + rhs.len() - 1).next_power_of_two();\r\n let mut f = vec![ModInt::zero(); size];\r\n let mut g = vec![ModInt::zero(); size];\r\n f[..self.len()].copy_from_slice(self);\r\n g[..rhs.len()].copy_from_slice(rhs);\r\n f.ntt();\r\n g.ntt();\r\n f.dot_assign(&g);\r\n f.intt();\r\n f.truncate(self.len() + rhs.len() - 1);\r\n f\r\n }\r\n}\r\n\r\npub trait PolynomialOperation {\r\n type Item;\r\n fn eval(&self, x: Self::Item) -> Self::Item;\r\n fn derivative(&self) -> Vec;\r\n fn integral(&self) -> Vec;\r\n}\r\n\r\nimpl PolynomialOperation for [ModInt] {\r\n type Item = ModInt;\r\n fn eval(&self, x: Self::Item) -> Self::Item {\r\n self.iter().rev().fold(ModInt::zero(), |s, a| s * x + *a)\r\n }\r\n fn derivative(&self) -> Vec {\r\n if self.len() <= 1 {\r\n return vec![];\r\n }\r\n self[1..]\r\n .iter()\r\n .enumerate()\r\n .map(|(k, a)| ModInt::new_unchecked(k as u32 + 1) * *a)\r\n .collect()\r\n }\r\n fn integral(&self) -> Vec {\r\n if self.is_empty() {\r\n return vec![];\r\n }\r\n let mut inv = vec![ModInt::one(); self.len() + 1];\r\n let mut mul = ModInt::zero();\r\n for i in 1..=self.len() {\r\n mul += ModInt::one();\r\n inv[i] = inv[i - 1] * mul;\r\n }\r\n let mut prod = inv[self.len()].inv();\r\n for i in (1..=self.len()).rev() {\r\n inv[i] = self[i - 1] * inv[i - 1] * prod;\r\n prod *= mul;\r\n mul -= ModInt::one();\r\n }\r\n inv[0] = ModInt::zero();\r\n inv\r\n }\r\n}\r\n\r\npub trait FPSOperation {\r\n type Item;\r\n fn inverse(&self, n: usize) -> Vec;\r\n fn log(&self, n: usize) -> Vec;\r\n fn exp(&self, n: usize) -> Vec;\r\n}\r\n\r\nimpl FPSOperation for [ModInt] {\r\n type Item = ModInt;\r\n fn inverse(&self, n: usize) -> Vec {\r\n assert!(self.len() > 0 && !self[0].is_zero());\r\n let len = n.next_power_of_two();\r\n assert!(2 * len <= T::order());\r\n let mut b = vec![ModInt::zero(); n];\r\n b[0] = self[0].inv();\r\n let mut f = Vec::with_capacity(2 * len);\r\n let mut g = Vec::with_capacity(2 * len);\r\n let mut size = 1;\r\n while size < n {\r\n g.clear();\r\n g.extend(b.iter().take(size));\r\n g.resize(2 * size, ModInt::zero());\r\n f.clear();\r\n f.extend(self.iter().take(2 * size));\r\n f.resize(2 * size, ModInt::zero());\r\n f.ntt();\r\n g.ntt();\r\n f.dot_assign(&g);\r\n f.intt();\r\n f[..size].iter_mut().for_each(|f| *f = ModInt::zero());\r\n f.ntt();\r\n f.dot_assign(&g);\r\n f.intt();\r\n for (b, g) in b[size..].iter_mut().zip(&f[size..]) {\r\n *b = *b - *g;\r\n }\r\n size *= 2;\r\n }\r\n b\r\n }\r\n fn log(&self, n: usize) -> Vec {\r\n assert!(self.get(0).map_or(false, |p| p.get() == 1));\r\n let mut b = self.derivative().multiply(&self.inverse(n));\r\n b.truncate(n - 1);\r\n let mut b = b.integral();\r\n b.resize(n, ModInt::zero());\r\n b\r\n }\r\n fn exp(&self, n: usize) -> Vec {\r\n assert!(self.get(0).map_or(true, |a| a.is_zero()));\r\n assert!(n <= T::order());\r\n let mut b = vec![ModInt::one()];\r\n let mut size = 1;\r\n while size < n {\r\n size <<= 1;\r\n let f = b.log(size);\r\n let g = self[..self.len().min(size)].sub(&f);\r\n b = b.multiply(&g).add(&b);\r\n b.truncate(size);\r\n }\r\n b.truncate(n);\r\n b.resize(n, ModInt::zero());\r\n b\r\n }\r\n}\r\n\r\n// test\r\n// yuki907: https://yukicoder.me/submissions/712523\r\n// hhkb2020: https://atcoder.jp/contests/hhkb2020/submissions/26997806\r\n//\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nuse std::io::Write;\r\nuse std::collections::*;\r\n\r\ntype Map = BTreeMap;\r\ntype Set = BTreeSet;\r\ntype Deque = VecDeque;\r\n\r\nfn run() {\r\n input! {\r\n n: usize,\r\n k: usize,\r\n }\r\n let pc = precalc::Precalc::new(n * n + k);\r\n let mut dp = vec![M::zero(); n];\r\n dp[n - 1] = M::one();\r\n for i in 0..k {\r\n let mut next = dp.clone();\r\n for (j, dp) in dp.iter().enumerate() {\r\n for a in 1..=j {\r\n let mut w = *dp;\r\n w *= pc.comb(j, a);\r\n w *= M::from(k - i).pow((a * (a - 1) / 2 + a * (n - 1 - j)) as u64);\r\n next[j - a] += w;\r\n }\r\n }\r\n dp = next;\r\n }\r\n println!(\"{}\", dp[0]);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graph matchings"], "code_uid": "a06a83d9350dbf6271fc617afb27fc1d", "src_uid": "b2d7ac8e75cbdb828067aeafd803ac62", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::vec;\r\nfn ksm(mut a:isize, mut b:isize, c:isize) -> isize {\r\n a = a%c;\r\n let mut ret = 1;\r\n while b >= 1{\r\n if b % 2 == 1 {\r\n ret = (ret*a % c) as isize;\r\n }\r\n a = a*a % c;\r\n b /= 2;\r\n }\r\n return ret;\r\n}\r\nfn inv(mut a:isize, c:isize) -> isize {\r\n if a == 0{\r\n return 1;\r\n }\r\n return ksm(a, c-2, c);\r\n}\r\nfn main() {\r\n let mut input = String::new();\r\n std::io::stdin().read_line(&mut input);\r\n let mut n = 0;\r\n let mut m = 0;\r\n let mut i = 0;\r\n let p:isize = 998244353;\r\n for word in input.split_whitespace(){\r\n if i == 0 {\r\n n = word.to_string().parse::().unwrap();\r\n }\r\n if i == 1{\r\n m = word.to_string().parse::().unwrap();\r\n }\r\n i += 1;\r\n }\r\n n -= 1;\r\n let mut f= vec![vec![0;(m+1) as usize];(n+1) as usize];\r\n for i in 0..(m+1) as usize {\r\n f[0][i] = 1;\r\n }\r\n\r\n let mut jc = vec![1];\r\n for i in 1..n+2 {\r\n jc.insert(i as usize, jc[(i-1) as usize] * i %p);\r\n }\r\n\r\n // println!(\"{:?}\",jc);\r\n\r\n let mut ans = 0;\r\n for i in 1..(n+1) as usize {\r\n for j in 1..(m+1) as usize {\r\n f[i][j] = f[i][j-1];\r\n for k in 0..i {\r\n let mut mi = 0;\r\n let mut t = i - k;\r\n f[i][j] = (f[i][j] + f[k][j-1]*ksm(m-j as isize+1, (k*t) as isize, p)%p*ksm(m-j as isize+1, (t*(t-1)/2) as isize , p)%p*jc[i]%p*inv(jc[t] as isize, p)%p*inv(jc[k] as isize, p)%p)%p;\r\n }\r\n }\r\n }\r\n // println!(\"{:?}\", f);\r\n println!(\"{}\", f[n as usize][m as usize]);\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graph matchings"], "code_uid": "bcef79379ecaf98bb8158faa5747e40b", "src_uid": "b2d7ac8e75cbdb828067aeafd803ac62", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\nuse input::*;\nuse std::{\n collections::*,\n io::{self, BufWriter, Write},\n};\nfn run(mut ss: I, mut out: O) {\n let t: u32 = 1;\n for _ in 0..t {\n case(&mut ss, &mut out);\n }\n}\nuse mod_int::*;\ndef_mint!(998244353);\nfn case(mut ss: I, mut out: O) {\n let (n, k): (usize, usize) = ss.parse();\n let f = fact::Fact::new(n + k);\n let mut dp = vec![mint(0); n + 1];\n dp[1] = mint(1);\n for i in 1..=k {\n let mut dp_next = dp.clone();\n for a in 1..n {\n for b in a + 1..=n {\n let d = b - a;\n let c = d * (a - 1) + d * (d - 1) / 2;\n let w = k - i + 1;\n d!(c, w);\n dp_next[b] += dp[a] * f.binom(b - 1, d) * Mint::from(w).pow(c);\n }\n }\n dp = dp_next;\n d!(dp);\n }\n let ans = dp[n];\n wln!(out, \"{}\", ans);\n}\nfn main() {\n let stdin = io::stdin();\n let ss = SplitWs::new(stdin.lock());\n let stdout = io::stdout();\n let out = BufWriter::new(stdout.lock());\n run(ss, out);\n}\npub mod fact {\n use super::mod_int::*;\n pub struct Fact {\n f: Vec>,\n finv: Vec>,\n }\n impl Fact {\n pub fn new(n: usize) -> Self {\n let mut f = vec![ModInt::new(0); n + 1];\n f[0] = ModInt::new(1);\n for i in 1..=n {\n f[i] = ModInt::new(i as u32) * f[i - 1];\n }\n let mut finv = vec![ModInt::new(0); n + 1];\n finv[n] = f[n].inv();\n for i in (1..=n).rev() {\n finv[i - 1] = finv[i] * ModInt::new(i as u32);\n }\n Self { f, finv }\n }\n pub fn fact(&self, x: usize) -> ModInt {\n self.f[x]\n }\n pub fn fact_inv(&self, x: usize) -> ModInt {\n self.finv[x]\n }\n pub fn binom(&self, n: usize, k: usize) -> ModInt {\n if n >= k {\n self.fact(n) * self.fact_inv(n - k) * self.fact_inv(k)\n } else {\n ModInt::new(0)\n }\n }\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\n if n >= k {\n self.fact(n) * self.fact_inv(n - k)\n } else {\n ModInt::new(0)\n }\n }\n }\n}\npub mod mod_int {\n use std::{\n cmp,\n fmt::{self, Debug, Display},\n hash::Hash,\n iter::{Product, Sum},\n marker::PhantomData,\n mem,\n ops::*,\n };\n pub struct ModInt {\n x: u32,\n marker: PhantomData<*const M>,\n }\n pub trait Modulo {\n fn modulo() -> u32;\n }\n impl ModInt {\n pub fn new(x: u32) -> Self {\n Self {\n x,\n marker: PhantomData,\n }\n }\n pub fn get(self) -> u32 {\n self.x\n }\n }\n impl ModInt {\n pub fn modulo() -> u32 {\n M::modulo()\n }\n pub fn normalize(self) -> Self {\n Self::new(self.x % M::modulo())\n }\n pub fn inv(self) -> Self {\n assert_ne!(self.get(), 0);\n self.pow(M::modulo() - 2)\n }\n pub fn twice(self) -> Self {\n self + self\n }\n pub fn half(self) -> Self {\n if self.x & 1 == 0 {\n Self::new(self.x >> 1)\n } else {\n Self::new((self.x >> 1) + ((Self::modulo() + 1) >> 1))\n }\n }\n }\n impl Clone for ModInt {\n fn clone(&self) -> Self {\n Self::new(self.x)\n }\n }\n impl Copy for ModInt {}\n impl Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self {\n Self::new(if self.x != 0 { M::modulo() - self.x } else { 0 })\n }\n }\n impl Neg for &ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n -(*self)\n }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, rhs: Self) -> Self {\n let x = self.x + rhs.x;\n Self::new(if x < M::modulo() { x } else { x - M::modulo() })\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, rhs: Self) -> Self {\n let x = if self.x >= rhs.x {\n self.x - rhs.x\n } else {\n M::modulo() + self.x - rhs.x\n };\n Self::new(x)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, rhs: Self) -> Self {\n let x = (self.x as u64 * rhs.x as u64) % M::modulo() as u64;\n Self::new(x as u32)\n }\n }\n impl Div for ModInt {\n type Output = Self;\n #[allow(clippy::suspicious_arithmetic_impl)]\n fn div(self, rhs: Self) -> Self {\n self * rhs.inv()\n }\n }\n macro_rules! biops {\n ($ Op : ident , $ op : ident , $ OpAssign : ident , $ op_assign : ident) => {\n impl $Op<&Self> for ModInt {\n type Output = Self;\n fn $op(self, rhs: &Self) -> Self {\n self.$op(*rhs)\n }\n }\n impl $Op> for &ModInt {\n type Output = ModInt;\n fn $op(self, rhs: ModInt) -> ModInt {\n (*self).$op(rhs)\n }\n }\n impl $Op for &ModInt {\n type Output = ModInt;\n fn $op(self, rhs: Self) -> ModInt {\n (*self).$op(*rhs)\n }\n }\n impl $OpAssign for ModInt {\n fn $op_assign(&mut self, rhs: Self) {\n *self = self.$op(rhs);\n }\n }\n impl $OpAssign<&Self> for ModInt {\n fn $op_assign(&mut self, rhs: &Self) {\n *self = self.$op(rhs);\n }\n }\n };\n }\n biops!(Add, add, AddAssign, add_assign);\n biops!(Sub, sub, SubAssign, sub_assign);\n biops!(Mul, mul, MulAssign, mul_assign);\n biops!(Div, div, DivAssign, div_assign);\n impl Sum for ModInt {\n fn sum>(iter: I) -> Self {\n iter.fold(ModInt::new(0), |x, y| x + y)\n }\n }\n impl Product for ModInt {\n fn product>(iter: I) -> Self {\n iter.fold(ModInt::new(1), |x, y| x * y)\n }\n }\n macro_rules! fold {\n ($ Trait : ident , $ f : ident) => {\n impl<'a, M: Modulo + 'a> $Trait<&'a ModInt> for ModInt {\n fn $f>>(iter: I) -> Self {\n iter.copied().$f()\n }\n }\n };\n }\n fold!(Sum, sum);\n fold!(Product, product);\n pub trait Pow {\n fn pow(self, exp: Exp) -> Self;\n }\n macro_rules! pow {\n ($ uty : ident , $ ity : ident) => {\n impl Pow<$uty> for ModInt {\n fn pow(self, mut exp: $uty) -> Self {\n if exp == 0 {\n return ModInt::new(1);\n }\n let mut res = ModInt::new(1);\n let mut base = self;\n while exp > 1 {\n if exp & 1 != 0 {\n res *= base;\n }\n exp >>= 1;\n base *= base;\n }\n base * res\n }\n }\n impl Pow<$ity> for ModInt {\n fn pow(self, exp: $ity) -> Self {\n if exp >= 0 {\n self.pow(exp as $uty)\n } else {\n self.inv().pow(-exp as $uty)\n }\n }\n }\n };\n }\n macro_rules ! impls { ($ m : ident , $ ($ uty : ident , $ ity : ident) ,*) => { $ ($ m ! ($ uty , $ ity) ;) * } ; }\n impls!(pow, usize, isize, u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);\n impl Default for ModInt {\n fn default() -> Self {\n Self::new(0)\n }\n }\n impl PartialEq for ModInt {\n fn eq(&self, other: &Self) -> bool {\n self.x == other.x\n }\n }\n impl Eq for ModInt {}\n impl PartialOrd for ModInt {\n fn partial_cmp(&self, other: &Self) -> Option {\n self.x.partial_cmp(&other.x)\n }\n }\n impl Ord for ModInt {\n fn cmp(&self, other: &Self) -> cmp::Ordering {\n self.x.cmp(&other.x)\n }\n }\n impl Hash for ModInt {\n fn hash(&self, state: &mut H) {\n self.x.hash(state)\n }\n }\n macro_rules! from_uint {\n ($ ty : ident) => {\n impl From<$ty> for ModInt {\n fn from(x: $ty) -> Self {\n if mem::size_of::<$ty>() <= 4 {\n if ($ty::max_value() as u32) < M::modulo() {\n Self::new(x as u32)\n } else {\n Self::new(x as u32).normalize()\n }\n } else {\n Self::new((x % M::modulo() as $ty) as u32)\n }\n }\n }\n };\n }\n macro_rules ! impls { ($ m : ident , $ ($ ty : ident) ,*) => { $ ($ m ! ($ ty) ;) * } ; }\n impls!(from_uint, usize, u8, u16, u32, u64, u128);\n macro_rules! from_small_int {\n ($ ty : ident) => {\n impl From<$ty> for ModInt {\n fn from(x: $ty) -> Self {\n let mut x = x as i32;\n if x >= 0 {\n Self::from(x as u32)\n } else {\n while x < 0 {\n x += M::modulo() as i32;\n }\n Self::new(x as u32)\n }\n }\n }\n };\n }\n impls!(from_small_int, i8, i16, i32);\n impl Display for ModInt {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Display::fmt(&self.x, f)\n }\n }\n impl Debug for ModInt {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Debug::fmt(&self.x, f)\n }\n }\n #[macro_export]\n macro_rules! def_mint {\n ($ modulo : expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]\n pub struct MintModulo;\n impl crate::mod_int::Modulo for MintModulo {\n fn modulo() -> u32 {\n $modulo\n }\n }\n pub type Mint = crate::mod_int::ModInt;\n pub fn mint>(x: T) -> Mint {\n x.into()\n }\n };\n }\n}\npub mod input {\n use std::{\n io::{self, prelude::*},\n marker::PhantomData,\n mem,\n };\n pub trait Input {\n fn bytes(&mut self) -> &[u8];\n fn bytes_vec(&mut self) -> Vec {\n self.bytes().to_vec()\n }\n fn str(&mut self) -> &str {\n std::str::from_utf8(self.bytes()).unwrap()\n }\n fn parse(&mut self) -> T {\n self.parse_with(DefaultParser)\n }\n fn parse_with(&mut self, mut parser: impl Parser) -> T {\n parser.parse(self)\n }\n fn seq(&mut self) -> Seq {\n self.seq_with(DefaultParser)\n }\n fn seq_with>(&mut self, parser: P) -> Seq {\n Seq {\n input: self,\n parser,\n marker: PhantomData,\n }\n }\n }\n impl Input for &mut T {\n fn bytes(&mut self) -> &[u8] {\n (**self).bytes()\n }\n }\n pub trait Parser {\n fn parse(&mut self, s: &mut I) -> T;\n }\n impl> Parser for &mut P {\n fn parse(&mut self, s: &mut I) -> T {\n (**self).parse(s)\n }\n }\n pub trait Parse {\n fn parse(s: &mut I) -> Self;\n }\n pub struct DefaultParser;\n impl Parser for DefaultParser {\n fn parse(&mut self, s: &mut I) -> T {\n T::parse(s)\n }\n }\n pub struct Seq<'a, T, I: ?Sized, P> {\n input: &'a mut I,\n parser: P,\n marker: PhantomData<*const T>,\n }\n impl<'a, T, I: Input, P: Parser> Iterator for Seq<'a, T, I, P> {\n type Item = T;\n #[inline]\n fn next(&mut self) -> Option {\n Some(self.input.parse_with(&mut self.parser))\n }\n fn size_hint(&self) -> (usize, Option) {\n (!0, None)\n }\n }\n impl Parse for char {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let s = s.bytes();\n debug_assert_eq!(s.len(), 1);\n *s.first().expect(\"zero length\") as char\n }\n }\n macro_rules ! tuple { ($ ($ T : ident) ,*) => { impl <$ ($ T : Parse) ,*> Parse for ($ ($ T ,) *) { # [inline] # [allow (unused_variables)] # [allow (clippy :: unused_unit)] fn parse < I : Input + ? Sized > (s : & mut I) -> Self { ($ ($ T :: parse (s) ,) *) } } } ; }\n tuple!();\n tuple!(A);\n tuple!(A, B);\n tuple!(A, B, C);\n tuple!(A, B, C, D);\n tuple!(A, B, C, D, E);\n tuple!(A, B, C, D, E, F);\n tuple!(A, B, C, D, E, F, G);\n #[cfg(feature = \"newer\")]\n impl Parse for [T; N] {\n fn parse(s: &mut I) -> Self {\n use std::{mem::MaybeUninit, ptr};\n struct Guard {\n arr: [MaybeUninit; N],\n i: usize,\n }\n impl Drop for Guard {\n fn drop(&mut self) {\n unsafe {\n ptr::drop_in_place(&mut self.arr[..self.i] as *mut _ as *mut [T]);\n }\n }\n }\n let mut g = Guard:: {\n arr: unsafe { MaybeUninit::uninit().assume_init() },\n i: 0,\n };\n while g.i < N {\n g.arr[g.i] = MaybeUninit::new(s.parse());\n g.i += 1;\n }\n unsafe { mem::transmute_copy(&g.arr) }\n }\n }\n macro_rules! uint {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let s = s.bytes();\n s.iter().fold(0, |x, d| 10 * x + (0xf & d) as $ty)\n }\n }\n };\n }\n macro_rules! int {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n let f = |s: &[u8]| {\n s.iter()\n .fold(0 as $ty, |x, d| (10 * x).wrapping_add((0xf & d) as $ty))\n };\n let s = s.bytes();\n if let [b'-', s @ ..] = s {\n f(s).wrapping_neg()\n } else {\n f(s)\n }\n }\n }\n };\n }\n macro_rules! float {\n ($ ty : ty) => {\n impl Parse for $ty {\n fn parse(s: &mut I) -> Self {\n const POW: [$ty; 18] = [\n 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13,\n 1e14, 1e15, 1e16, 1e17,\n ];\n let s = s.bytes();\n let (minus, s) = if let Some((b'-', s)) = s.split_first() {\n (true, s)\n } else {\n (false, s)\n };\n let (int, fract) = if let Some(p) = s.iter().position(|c| *c == b'.') {\n (&s[..p], &s[p + 1..])\n } else {\n (s, &[][..])\n };\n let x = int\n .iter()\n .chain(fract)\n .fold(0u64, |x, d| 10 * x + (0xf & *d) as u64);\n let x = x as $ty;\n let x = if minus { -x } else { x };\n let exp = fract.len();\n if exp == 0 {\n x\n } else if let Some(pow) = POW.get(exp) {\n x / pow\n } else {\n x / (10.0 as $ty).powi(exp as i32)\n }\n }\n }\n };\n }\n macro_rules! from_bytes {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n s.bytes().into()\n }\n }\n };\n }\n macro_rules! from_str {\n ($ ty : ty) => {\n impl Parse for $ty {\n #[inline]\n fn parse(s: &mut I) -> Self {\n s.str().into()\n }\n }\n };\n }\n macro_rules ! impls { ($ m : ident , $ ($ ty : ty) ,*) => { $ ($ m ! ($ ty) ;) * } ; }\n impls!(uint, usize, u8, u16, u32, u64, u128);\n impls!(int, isize, i8, i16, i32, i64, i128);\n impls!(float, f32, f64);\n impls!(from_bytes, Vec, Box<[u8]>);\n impls!(from_str, String);\n #[derive(Clone)]\n pub struct SplitWs {\n src: T,\n buf: Vec,\n pos: usize,\n len: usize,\n }\n const BUF_SIZE: usize = 1 << 26;\n impl SplitWs {\n pub fn new(src: T) -> Self {\n Self {\n src,\n buf: vec![0; BUF_SIZE],\n pos: 0,\n len: 0,\n }\n }\n #[inline(always)]\n fn peek(&self) -> &[u8] {\n unsafe { self.buf.get_unchecked(self.pos..self.len) }\n }\n #[inline(always)]\n fn consume(&mut self, n: usize) -> &[u8] {\n let pos = self.pos;\n self.pos += n;\n unsafe { self.buf.get_unchecked(pos..self.pos) }\n }\n fn read(&mut self) -> usize {\n self.buf.copy_within(self.pos..self.len, 0);\n self.len -= self.pos;\n self.pos = 0;\n if self.len == self.buf.len() {\n self.buf.resize(2 * self.buf.len(), 0);\n }\n loop {\n match self.src.read(&mut self.buf[self.len..]) {\n Ok(n) => {\n self.len += n;\n return n;\n }\n Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}\n Err(e) => panic!(\"io error: {:?}\", e),\n }\n }\n }\n }\n impl Input for SplitWs {\n #[inline]\n fn bytes(&mut self) -> &[u8] {\n loop {\n if let Some(del) = self.peek().iter().position(|c| c.is_ascii_whitespace()) {\n if del > 0 {\n let s = self.consume(del + 1);\n return s.split_last().unwrap().1;\n } else {\n self.consume(1);\n }\n } else if self.read() == 0 {\n return self.consume(self.len - self.pos);\n }\n }\n }\n }\n}\npub mod macros {\n #[macro_export]\n macro_rules ! w { ($ ($ arg : tt) *) => { write ! ($ ($ arg) *) . unwrap () ; } }\n #[macro_export]\n macro_rules ! wln { ($ dst : expr $ (, $ ($ arg : tt) *) ?) => { { writeln ! ($ dst $ (, $ ($ arg) *) ?) . unwrap () ; # [cfg (debug_assertions)] $ dst . flush () . unwrap () ; } } }\n #[macro_export]\n macro_rules! w_iter {\n ($ dst : expr , $ fmt : expr , $ iter : expr , $ delim : expr) => {{\n let mut first = true;\n for elem in $iter {\n if first {\n w!($dst, $fmt, elem);\n first = false;\n } else {\n w!($dst, concat!($delim, $fmt), elem);\n }\n }\n }};\n ($ dst : expr , $ fmt : expr , $ iter : expr) => {\n w_iter!($dst, $fmt, $iter, \" \")\n };\n }\n #[macro_export]\n macro_rules ! w_iter_ln { ($ dst : expr , $ ($ t : tt) *) => { { w_iter ! ($ dst , $ ($ t) *) ; wln ! ($ dst) ; } } }\n #[macro_export]\n macro_rules ! e { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprint ! ($ ($ t) *) } }\n #[macro_export]\n macro_rules ! eln { ($ ($ t : tt) *) => { # [cfg (debug_assertions)] eprintln ! ($ ($ t) *) } }\n #[macro_export]\n #[doc(hidden)]\n macro_rules ! __tstr { ($ h : expr $ (, $ t : expr) +) => { concat ! (__tstr ! ($ ($ t) ,+) , \", \" , __tstr ! (@)) } ; ($ h : expr) => { concat ! (__tstr ! () , \" \" , __tstr ! (@)) } ; () => { \"\\x1B[94m[{}:{}]\\x1B[0m\" } ; (@) => { \"\\x1B[1;92m{}\\x1B[0m = {:?}\" } }\n #[macro_export]\n macro_rules ! d { ($ ($ a : expr) ,*) => { if std :: env :: var (\"ND\") . map (| v | & v == \"0\") . unwrap_or (true) { eln ! (__tstr ! ($ ($ a) ,*) , file ! () , line ! () , $ (stringify ! ($ a) , $ a) ,*) ; } } ; }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graph matchings"], "code_uid": "e3e1f5116a7b1b92b3347321610daa6b", "src_uid": "b2d7ac8e75cbdb828067aeafd803ac62", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "pub fn main() {\r\n crate::prepare!();\r\n sc!(n, k);\r\n let mut dp = vec![M::zero(); n + 1];\r\n dp[1] = M::one();\r\n let f = MemorizedFactorial::new(n);\r\n for i in 1..=k {\r\n let mut ndp = vec![M::zero(); n + 1];\r\n for j in 1..=n {\r\n if dp[j].is_zero() {\r\n continue;\r\n }\r\n for x in 0..=n - j {\r\n let d = dp[j] * f.combination(n - j, x);\r\n let nj = j + x;\r\n let e = (nj * nj.saturating_sub(1) - j * j.saturating_sub(1)) / 2;\r\n ndp[nj] += d * M::from(k - i + 1).pow(e - x);\r\n }\r\n }\r\n dp = ndp;\r\n }\r\n pp!(dp[n]);\r\n}\r\npub type M = mint_basic::MInt998244353;\r\n#[allow(unused_imports)]use std::{cmp::{Ordering,Reverse},collections::{BTreeMap,BTreeSet,BinaryHeap,HashMap,HashSet,VecDeque}};\r\nmod main_macros{#[doc=\" Prepare useful macros.\"]#[doc=\" - `prepare!();`: default (all input scanner (`sc!`, `sv!`) + buf print (`pp!`))\"]#[doc=\" - `prepare!(?);`: interactive (line scanner (`scln!`) + buf print (`pp!`))\"]#[macro_export]macro_rules!prepare{(@normal($dol:tt))=>{#[allow(unused_imports)]use std::io::Write as _;let __out=std::io::stdout();#[allow(unused_mut,unused_variables)]let mut __out=std::io::BufWriter::new(__out.lock());#[allow(unused_macros)]macro_rules!pp{($dol($dol t:tt)*)=>{$dol crate::iter_print!(__out,$dol($dol t)*)}}let __in_buf=read_stdin_all_unchecked();#[allow(unused_mut,unused_variables)]let mut __scanner=Scanner::new(&__in_buf);#[allow(unused_macros)]macro_rules!sc{($dol($dol t:tt)*)=>{$dol crate::scan!(__scanner,$dol($dol t)*)}}#[allow(unused_macros)]macro_rules!sv{($dol($dol t:tt)*)=>{$dol crate::scan_value!(__scanner,$dol($dol t)*)}}};(@interactive($dol:tt))=>{#[allow(unused_imports)]use std::io::Write as _;let __out=std::io::stdout();#[allow(unused_mut,unused_variables)]let mut __out=std::io::BufWriter::new(__out.lock());#[allow(unused_macros)]#[doc=\" - to flush: `pp!(@flush);`\"]macro_rules!pp{($dol($dol t:tt)*)=>{$dol crate::iter_print!(__out,$dol($dol t)*)}}#[allow(unused_macros)]#[doc=\" Scan a line, and previous line will be truncated in the next call.\"]macro_rules!scln{($dol($dol t:tt)*)=>{let __in_buf=read_stdin_line();#[allow(unused_mut,unused_variables)]let mut __scanner=Scanner::new(&__in_buf);$dol crate::scan!(__scanner,$dol($dol t)*)}}};()=>{$crate::prepare!(@normal($))};(?)=>{$crate::prepare!(@interactive($))};}}\r\npub use self::iter_print::IterPrint;\r\nmod iter_print{use std::{fmt::Display,io::{Error,Write}};pub trait IterPrint{fn iter_print(self,writer:&mut W,sep:S,is_head:bool)->Result<(),Error>where W:Write,S:Display;}macro_rules!iter_print_tuple_impl{(@impl$($A:ident$a:ident)?,$($B:ident$b:ident)*)=>{impl<$($A,)?$($B),*>IterPrint for($($A,)?$($B),*)where$($A:Display,)?$($B:Display),*{#[allow(unused_variables)]fn iter_print(self,writer:&mut W,sep:S,is_head:bool)->Result<(),Error>where W:Write,S:Display{let($($a,)?$($b,)*)=self;$(if is_head{::std::write!(writer,\"{}\",$a)?;}else{::std::write!(writer,\"{}{}\",sep,$a)?;})?$(::std::write!(writer,\"{}{}\",sep,$b)?;)*Ok(())}}};(@inc,,$C:ident$c:ident$($D:ident$d:ident)*)=>{iter_print_tuple_impl!(@impl,);iter_print_tuple_impl!(@inc$C$c,,$($D$d)*);};(@inc$A:ident$a:ident,$($B:ident$b:ident)*,$C:ident$c:ident$($D:ident$d:ident)*)=>{iter_print_tuple_impl!(@impl$A$a,$($B$b)*);iter_print_tuple_impl!(@inc$A$a,$($B$b)*$C$c,$($D$d)*);};(@inc$A:ident$a:ident,$($B:ident$b:ident)*,)=>{iter_print_tuple_impl!(@impl$A$a,$($B$b)*);};($($t:tt)*)=>{iter_print_tuple_impl!(@inc,,$($t)*);};}iter_print_tuple_impl!(A a B b C c D d E e F f G g H h I i J j K k);#[doc=\" Print expressions with a separator.\"]#[doc=\" - `iter_print!(writer, args...)`\"]#[doc=\" - `@sep $expr`: set separator (default: `' '`)\"]#[doc=\" - `@fmt $lit => {$($expr),*}`: print `format!($lit, $($expr),*)`\"]#[doc=\" - `@flush`: flush writer (auto insert `!`)\"]#[doc=\" - `@iter $expr`: print iterator\"]#[doc=\" - `@iterns $expr`: print iterator with no separators\"]#[doc=\" - `@iterln $expr`: print iterator with separator `'\\\\n'`\"]#[doc=\" - `@iter2d $expr`: print 2d-iterator\"]#[doc=\" - `@tuple $expr`: print tuple (need to import [`IterPrint`], each elements impls `Display`)\"]#[doc=\" - `$expr`: print expr\"]#[doc=\" - `;`: print `'\\\\n'`\"]#[doc=\" - `!`: not print `'\\\\n'` at the end\"]#[macro_export]macro_rules!iter_print{(@@fmt$writer:expr,$sep:expr,$is_head:expr,$lit:literal,$($e:expr),*)=>{if!$is_head{::std::write!($writer,\"{}\",$sep).expect(\"io error\");}::std::write!($writer,$lit,$($e),*).expect(\"io error\");};(@@item$writer:expr,$sep:expr,$is_head:expr,$e:expr)=>{$crate::iter_print!(@@fmt$writer,$sep,$is_head,\"{}\",$e);};(@@line_feed$writer:expr$(,)?)=>{::std::writeln!($writer).expect(\"io error\");};(@@iter$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@item$writer,$sep,$is_head,item);}for item in iter{$crate::iter_print!(@@item$writer,$sep,false,item);}}};(@@iterns$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@item$writer,$sep,$is_head,item);}for item in iter{$crate::iter_print!(@@item$writer,$sep,true,item);}}};(@@iterln$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@item$writer,'\\n',$is_head,item);}for item in iter{$crate::iter_print!(@@item$writer,'\\n',false,item);}}};(@@iter2d$writer:expr,$sep:expr,$is_head:expr,$iter:expr)=>{let mut iter=$iter.into_iter();if let Some(item)=iter.next(){$crate::iter_print!(@@iter$writer,$sep,$is_head,item);}for item in iter{$crate::iter_print!(@@line_feed$writer);$crate::iter_print!(@@iter$writer,$sep,true,item);}};(@@tuple$writer:expr,$sep:expr,$is_head:expr,$tuple:expr)=>{IterPrint::iter_print($tuple,&mut$writer,$sep,$is_head).expect(\"io error\");};(@@assert_tag item)=>{};(@@assert_tag iter)=>{};(@@assert_tag iterns)=>{};(@@assert_tag iterln)=>{};(@@assert_tag iter2d)=>{};(@@assert_tag tuple)=>{};(@@assert_tag$tag:ident)=>{::std::compile_error!(::std::concat!(\"invalid tag in `iter_print!`: `\",std::stringify!($tag),\"`\"));};(@@inner$writer:expr,$sep:expr,$is_head:expr,@sep$e:expr,$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$e,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@flush$($t:tt)*)=>{$writer.flush().expect(\"io error\");$crate::iter_print!(@@inner$writer,$sep,$is_head,!$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@fmt$lit:literal=>{$($e:expr),*$(,)?}$($t:tt)*)=>{$crate::iter_print!(@@fmt$writer,$sep,$is_head,$lit,$($e),*);$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$e:expr,$($t:tt)*)=>{$crate::iter_print!(@@assert_tag$tag);$crate::iter_print!(@@$tag$writer,$sep,$is_head,$e);$crate::iter_print!(@@inner$writer,$sep,false,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$e:expr;$($t:tt)*)=>{$crate::iter_print!(@@assert_tag$tag);$crate::iter_print!(@@$tag$writer,$sep,$is_head,$e);$crate::iter_print!(@@line_feed$writer);$crate::iter_print!(@@inner$writer,$sep,true,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$e:expr)=>{$crate::iter_print!(@@assert_tag$tag);$crate::iter_print!(@@$tag$writer,$sep,$is_head,$e);$crate::iter_print!(@@inner$writer,$sep,false,);};(@@inner$writer:expr,$sep:expr,$is_head:expr,@$tag:ident$($t:tt)*)=>{::std::compile_error!(::std::concat!(\"invalid expr in `iter_print!`: `\",std::stringify!($($t)*),\"`\"));};(@@inner$writer:expr,$sep:expr,$is_head:expr,,$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,;$($t:tt)*)=>{$crate::iter_print!(@@line_feed$writer);$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,!$(,)?)=>{};(@@inner$writer:expr,$sep:expr,$is_head:expr,!$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$sep,$is_head,$($t)*);};(@@inner$writer:expr,$sep:expr,$is_head:expr,)=>{$crate::iter_print!(@@line_feed$writer);};(@@inner$writer:expr,$sep:expr,$is_head:expr,$($t:tt)*)=>{$crate::iter_print!(@@inner$writer,$sep,$is_head,@item$($t)*);};($writer:expr,$($t:tt)*)=>{{$crate::iter_print!(@@inner$writer,' ',true,$($t)*);}};}}\r\npub use self::scanner::*;\r\nmod scanner{use std::{iter::{from_fn,repeat_with,FromIterator},marker::PhantomData};pub fn read_stdin_all()->String{use std::io::Read as _;let mut s=String::new();std::io::stdin().read_to_string(&mut s).expect(\"io error\");s}pub fn read_stdin_all_unchecked()->String{use std::io::Read as _;let mut buf=Vec::new();std::io::stdin().read_to_end(&mut buf).expect(\"io error\");unsafe{String::from_utf8_unchecked(buf)}}pub fn read_all(mut reader:impl std::io::Read)->String{let mut s=String::new();reader.read_to_string(&mut s).expect(\"io error\");s}pub fn read_all_unchecked(mut reader:impl std::io::Read)->String{let mut buf=Vec::new();reader.read_to_end(&mut buf).expect(\"io error\");unsafe{String::from_utf8_unchecked(buf)}}pub fn read_stdin_line()->String{let mut s=String::new();std::io::stdin().read_line(&mut s).expect(\"io error\");s}pub trait IterScan:Sized{type Output;fn scan<'a,I:Iterator>(iter:&mut I)->Option;}pub trait MarkedIterScan:Sized{type Output;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option;}#[derive(Clone,Debug)]pub struct Scanner<'a>{iter:std::str::SplitAsciiWhitespace<'a>}impl<'a>Scanner<'a>{#[inline]pub fn new(s:&'a str)->Self{let iter=s.split_ascii_whitespace();Self{iter}}#[inline]pub fn scan(&mut self)->::Output where T:IterScan{::scan(&mut self.iter).expect(\"scan error\")}#[inline]pub fn mscan(&mut self,marker:T)->::Output where T:MarkedIterScan{marker.mscan(&mut self.iter).expect(\"scan error\")}#[inline]pub fn scan_vec(&mut self,size:usize)->Vec<::Output>where T:IterScan{(0..size).map(|_|::scan(&mut self.iter).expect(\"scan error\")).collect()}#[inline]pub fn iter<'b,T>(&'b mut self)->ScannerIter<'a,'b,T>where T:IterScan{ScannerIter{inner:self,_marker:std::marker::PhantomData}}}macro_rules!iter_scan_impls{($($t:ty)*)=>{$(impl IterScan for$t{type Output=Self;#[inline]fn scan<'a,I:Iterator>(iter:&mut I)->Option{iter.next()?.parse::<$t>().ok()}})*};}iter_scan_impls!(char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);macro_rules!iter_scan_tuple_impl{(@impl$($T:ident)*)=>{impl<$($T:IterScan),*>IterScan for($($T,)*){type Output=($(<$T as IterScan>::Output,)*);#[inline]fn scan<'a,It:Iterator>(_iter:&mut It)->Option{Some(($(<$T as IterScan>::scan(_iter)?,)*))}}};(@inner$($T:ident)*,)=>{iter_scan_tuple_impl!(@impl$($T)*);};(@inner$($T:ident)*,$U:ident$($Rest:ident)*)=>{iter_scan_tuple_impl!(@impl$($T)*);iter_scan_tuple_impl!(@inner$($T)*$U,$($Rest)*);};($($T:ident)*)=>{iter_scan_tuple_impl!(@inner,$($T)*);};}iter_scan_tuple_impl!(A B C D E F G H I J K);pub struct ScannerIter<'a,'b,T>{inner:&'b mut Scanner<'a>,_marker:std::marker::PhantomDataT>}impl<'a,'b,T>Iterator for ScannerIter<'a,'b,T>where T:IterScan{type Item=::Output;#[inline]fn next(&mut self)->Option{::scan(&mut self.inner.iter)}}#[doc=\" - `scan_value!(scanner, ELEMENT)`\"]#[doc=\"\"]#[doc=\" ELEMENT :=\"]#[doc=\" - `$ty`: IterScan\"]#[doc=\" - `@$expr`: MarkedIterScan\"]#[doc=\" - `[ELEMENT; $expr]`: vector\"]#[doc=\" - `[ELEMENT]`: iterator\"]#[doc=\" - `($(ELEMENT)*,)`: tuple\"]#[macro_export]macro_rules!scan_value{(@repeat$scanner:expr,[$($t:tt)*]$($len:expr)?)=>{::std::iter::repeat_with(||$crate::scan_value!(@inner$scanner,[]$($t)*))$(.take($len).collect::>())?};(@tuple$scanner:expr,[$([$($args:tt)*])*])=>{($($($args)*,)*)};(@$tag:ident$scanner:expr,[[$($args:tt)*]])=>{$($args)*};(@$tag:ident$scanner:expr,[$($args:tt)*]@$e:expr)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.mscan($e)]])};(@$tag:ident$scanner:expr,[$($args:tt)*]@$e:expr,$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.mscan($e)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*]($($tuple:tt)*)$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@tuple$scanner,[]$($tuple)*)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][@$e:expr;$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[@$e]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][[$($tt:tt)*];$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[[$($tt)*]]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][($($tt:tt)*);$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[($($tt)*)]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][$ty:ty;$len:expr]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[$ty]$len)]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*][$($tt:tt)*]$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$crate::scan_value!(@repeat$scanner,[$($tt)*])]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*]$ty:ty)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.scan::<$ty>()]])};(@$tag:ident$scanner:expr,[$($args:tt)*]$ty:ty,$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*[$scanner.scan::<$ty>()]]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*],$($t:tt)*)=>{$crate::scan_value!(@$tag$scanner,[$($args)*]$($t)*)};(@$tag:ident$scanner:expr,[$($args:tt)*])=>{::std::compile_error!(::std::stringify!($($args)*))};($scanner:expr,$($t:tt)*)=>{$crate::scan_value!(@inner$scanner,[]$($t)*)}}#[doc=\" - `scan!(scanner, $($pat $(: ELEMENT)?),*)`\"]#[macro_export]macro_rules!scan{(@assert$p:pat)=>{};(@assert$($p:tt)*)=>{::std::compile_error!(::std::concat!(\"expected pattern, found `\",::std::stringify!($($p)*),\"`\"));};(@pat$scanner:expr,[][])=>{};(@pat$scanner:expr,[][],$($t:tt)*)=>{$crate::scan!(@pat$scanner,[][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]$x:ident$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*$x][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]::$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*::][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]&$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*&][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]($($x:tt)*)$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*($($x)*)][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][][$($x:tt)*]$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*[$($x)*]][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]{$($x:tt)*}$($t:tt)*)=>{$crate::scan!(@pat$scanner,[$($p)*{$($x)*}][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]:$($t:tt)*)=>{$crate::scan!(@ty$scanner,[$($p)*][]$($t)*)};(@pat$scanner:expr,[$($p:tt)*][]$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][usize]$($t)*)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]@$e:expr)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*@$e])};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]@$e:expr,$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*@$e],$($t)*)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]($($x:tt)*)$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*($($x)*)]$($t)*)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*][$($x:tt)*]$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*[$($x)*]]$($t)*)};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]$ty:ty)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*$ty])};(@ty$scanner:expr,[$($p:tt)*][$($tt:tt)*]$ty:ty,$($t:tt)*)=>{$crate::scan!(@let$scanner,[$($p)*][$($tt)*$ty],$($t)*)};(@let$scanner:expr,[$($p:tt)*][$($tt:tt)*]$($t:tt)*)=>{$crate::scan!{@assert$($p)*}let$($p)* =$crate::scan_value!($scanner,$($tt)*);$crate::scan!(@pat$scanner,[][]$($t)*)};($scanner:expr,$($t:tt)*)=>{$crate::scan!(@pat$scanner,[][]$($t)*)}}#[derive(Debug,Copy,Clone)]pub struct Usize1;impl IterScan for Usize1{type Output=usize;#[inline]fn scan<'a,I:Iterator>(iter:&mut I)->Option{::scan(iter)?.checked_sub(1)}}#[derive(Debug,Copy,Clone)]pub struct CharWithBase(pub char);impl MarkedIterScan for CharWithBase{type Output=usize;#[inline]fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some((::scan(iter)?as u8-self.0 as u8)as usize)}}#[derive(Debug,Copy,Clone)]pub struct Chars;impl IterScan for Chars{type Output=Vec;#[inline]fn scan<'a,I:Iterator>(iter:&mut I)->Option{Some(iter.next()?.chars().collect())}}#[derive(Debug,Copy,Clone)]pub struct CharsWithBase(pub char);impl MarkedIterScan for CharsWithBase{type Output=Vec;#[inline]fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some(iter.next()?.chars().map(|c|(c as u8-self.0 as u8)as usize).collect())}}#[derive(Debug,Copy,Clone)]pub struct ByteWithBase(pub u8);impl MarkedIterScan for ByteWithBase{type Output=usize;#[inline]fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some((::scan(iter)?as u8-self.0)as usize)}}#[derive(Debug,Copy,Clone)]pub struct Bytes;impl IterScan for Bytes{type Output=Vec;#[inline]fn scan<'a,I:Iterator>(iter:&mut I)->Option{Some(iter.next()?.bytes().collect())}}#[derive(Debug,Copy,Clone)]pub struct BytesWithBase(pub u8);impl MarkedIterScan for BytesWithBase{type Output=Vec;#[inline]fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{Some(iter.next()?.bytes().map(|c|(c-self.0)as usize).collect())}}#[derive(Debug,Copy,Clone)]pub struct Collect::Output>>where T:IterScan,B:FromIterator<::Output>{size:usize,_marker:PhantomData(T,B)>}implCollectwhere T:IterScan,B:FromIterator<::Output>{pub fn new(size:usize)->Self{Self{size,_marker:PhantomData}}}implMarkedIterScan for Collectwhere T:IterScan,B:FromIterator<::Output>{type Output=B;#[inline]fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{repeat_with(||::scan(iter)).take(self.size).collect()}}#[derive(Debug,Copy,Clone)]pub struct SizedCollect::Output>>where T:IterScan,B:FromIterator<::Output>{_marker:PhantomData(T,B)>}implIterScan for SizedCollectwhere T:IterScan,B:FromIterator<::Output>{type Output=B;#[inline]fn scan<'a,I:Iterator>(iter:&mut I)->Option{let size=usize::scan(iter)?;repeat_with(||::scan(iter)).take(size).collect()}}#[derive(Debug,Copy,Clone)]pub struct Splittedwhere T:IterScan{pat:P,_marker:PhantomDataT>}implSplittedwhere T:IterScan{pub fn new(pat:P)->Self{Self{pat,_marker:PhantomData}}}implMarkedIterScan for Splittedwhere T:IterScan{type Output=Vec<::Output>;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{let mut iter=iter.next()?.split(self.pat);Some(from_fn(||::scan(&mut iter)).collect())}}implMarkedIterScan for Splittedwhere T:IterScan{type Output=Vec<::Output>;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{let mut iter=iter.next()?.split(self.pat);Some(from_fn(||::scan(&mut iter)).collect())}}implMarkedIterScan for F where F:Fn(&str)->Option{type Output=T;fn mscan<'a,I:Iterator>(self,iter:&mut I)->Option{self(iter.next()?)}}}\r\npub mod mint_basic{use super::*;#[macro_export]macro_rules!define_basic_mintbase{($name:ident,$m:expr,$basety:ty,$signedty:ty,$upperty:ty,[$($unsigned:ty),*],[$($signed:ty),*])=>{pub struct$name;impl MIntBase for$name{type Inner=$basety;#[inline]fn get_mod()->Self::Inner{$m}#[inline]fn mod_zero()->Self::Inner{0}#[inline]fn mod_one()->Self::Inner{1}#[inline]fn mod_add(x:Self::Inner,y:Self::Inner)->Self::Inner{let z=x+y;let m=Self::get_mod();if z>=m{z-m}else{z}}#[inline]fn mod_sub(x:Self::Inner,y:Self::Inner)->Self::Inner{if xSelf::Inner{(x as$upperty*y as$upperty%Self::get_mod()as$upperty)as$basety}#[inline]fn mod_div(x:Self::Inner,y:Self::Inner)->Self::Inner{Self::mod_mul(x,Self::mod_inv(y))}#[inline]fn mod_neg(x:Self::Inner)->Self::Inner{if x==0{0}else{Self::get_mod()-x}}fn mod_inv(x:Self::Inner)->Self::Inner{let p=Self::get_mod()as$signedty;let(mut a,mut b)=(x as$signedty,p);let(mut u,mut x)=(1,0);while a!=0{let k=b/a;x-=k*u;b-=k*a;std::mem::swap(&mut x,&mut u);std::mem::swap(&mut b,&mut a);}(if x<0{x+p}else{x})as _}}$(impl MIntConvert<$unsigned>for$name{#[inline]fn from(x:$unsigned)->Self::Inner{(x%::get_mod()as$unsigned)as$basety}#[inline]fn into(x:Self::Inner)->$unsigned{x as$unsigned}#[inline]fn mod_into()->$unsigned{::get_mod()as$unsigned}})*$(impl MIntConvert<$signed>for$name{#[inline]fn from(x:$signed)->Self::Inner{let x=x%::get_mod()as$signed;if x<0{(x+::get_mod()as$signed)as$basety}else{x as$basety}}#[inline]fn into(x:Self::Inner)->$signed{x as$signed}#[inline]fn mod_into()->$signed{::get_mod()as$signed}})*};}#[macro_export]macro_rules!define_basic_mint32{($([$name:ident,$m:expr,$mint_name:ident]),*)=>{$(crate::define_basic_mintbase!($name,$m,u32,i32,u64,[u32,u64,u128,usize],[i32,i64,i128,isize]);pub type$mint_name=MInt<$name>;)*};}define_basic_mint32!([Modulo998244353,998_244_353,MInt998244353],[Modulo1000000007,1_000_000_007,MInt1000000007],[Modulo1000000009,1_000_000_009,MInt1000000009],[DynModuloU32,DYN_MODULUS_U32.with(|cell|unsafe{*cell.get()}),DynMIntU32]);thread_local!(static DYN_MODULUS_U32:std::cell::UnsafeCell =std::cell::UnsafeCell::new(1_000_000_007));impl DynModuloU32{pub fn set_mod(m:u32){DYN_MODULUS_U32.with(|cell|unsafe{*cell.get()=m})}}thread_local!(static DYN_MODULUS_U64:std::cell::UnsafeCell =std::cell::UnsafeCell::new(1_000_000_007));define_basic_mintbase!(DynModuloU64,DYN_MODULUS_U64.with(|cell|unsafe{*cell.get()}),u64,i64,u128,[u64,u128,usize],[i64,i128,isize]);impl DynModuloU64{pub fn set_mod(m:u64){DYN_MODULUS_U64.with(|cell|unsafe{*cell.get()=m})}}pub type DynMIntU64=MInt;pub struct Modulo2;impl MIntBase for Modulo2{type Inner=u32;#[inline]fn get_mod()->Self::Inner{2}#[inline]fn mod_zero()->Self::Inner{0}#[inline]fn mod_one()->Self::Inner{1}#[inline]fn mod_add(x:Self::Inner,y:Self::Inner)->Self::Inner{x^y}#[inline]fn mod_sub(x:Self::Inner,y:Self::Inner)->Self::Inner{x^y}#[inline]fn mod_mul(x:Self::Inner,y:Self::Inner)->Self::Inner{x&y}#[inline]fn mod_div(x:Self::Inner,y:Self::Inner)->Self::Inner{assert_ne!(y,0);x}#[inline]fn mod_neg(x:Self::Inner)->Self::Inner{x}#[inline]fn mod_inv(x:Self::Inner)->Self::Inner{assert_ne!(x,0);x}#[inline]fn mod_pow(x:Self::Inner,y:usize)->Self::Inner{if y==0{1}else{x}}}macro_rules!impl_to_mint_base_for_modulo2{($name:ident,$basety:ty,[$($t:ty),*])=>{$(impl MIntConvert<$t>for$name{#[inline]fn from(x:$t)->Self::Inner{(x&1)as$basety}#[inline]fn into(x:Self::Inner)->$t{x as$t}#[inline]fn mod_into()->$t{1}})*};}impl_to_mint_base_for_modulo2!(Modulo2,u32,[u8,u16,u32,u64,u128,usize,i8,i16,i32,i64,i128,isize]);pub type MInt2=MInt;}\r\n#[repr(transparent)]pub struct MIntwhere M:MIntBase{x:M::Inner,_marker:std::marker::PhantomDataM>}\r\npub trait MIntBase{type Inner:Sized+Copy+Eq+std::fmt::Debug+std::hash::Hash;fn get_mod()->Self::Inner;fn mod_zero()->Self::Inner;fn mod_one()->Self::Inner;fn mod_add(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_sub(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_mul(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_div(x:Self::Inner,y:Self::Inner)->Self::Inner;fn mod_neg(x:Self::Inner)->Self::Inner;fn mod_inv(x:Self::Inner)->Self::Inner;fn mod_pow(x:Self::Inner,y:usize)->Self::Inner{let(mut x,mut y,mut z)=(x,y,Self::mod_one());while y>0{if y&1==1{z=Self::mod_mul(z,x);}x=Self::mod_mul(x,x);y>>=1;}z}}\r\npub trait MIntConvert::Inner>:MIntBase{fn from(x:T)->::Inner;fn into(x:::Inner)->T;fn mod_into()->T;}\r\nmod mint_base{use super::*;use std::{fmt::{self,Debug,Display},hash::{Hash,Hasher},iter::{Product,Sum},marker::PhantomData,ops::{Add,AddAssign,Div,DivAssign,Mul,MulAssign,Neg,Sub,SubAssign},str::FromStr};implMIntwhere M:MIntConvert{#[inline]pub fn new(x:M::Inner)->Self{Self::new_unchecked(>::from(x))}#[inline]pub fn inner(self)->M::Inner{>::into(self.x)}}implMIntwhere M:MIntBase{#[inline]pub fn new_unchecked(x:M::Inner)->Self{Self{x,_marker:PhantomData}}#[inline]pub fn get_mod()->M::Inner{M::get_mod()}#[inline]pub fn pow(self,y:usize)->Self{Self::new_unchecked(M::mod_pow(self.x,y))}#[inline]pub fn inv(self)->Self{Self::new_unchecked(M::mod_inv(self.x))}}implClone for MIntwhere M:MIntBase{#[inline]fn clone(&self)->Self{Self{x:Clone::clone(&self.x),_marker:PhantomData}}}implCopy for MIntwhere M:MIntBase{}implDebug for MIntwhere M:MIntBase{fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{Debug::fmt(&self.x,f)}}implDefault for MIntwhere M:MIntBase{#[inline]fn default()->Self{::zero()}}implPartialEq for MIntwhere M:MIntBase{#[inline]fn eq(&self,other:&Self)->bool{PartialEq::eq(&self.x,&other.x)}}implEq for MIntwhere M:MIntBase{}implHash for MIntwhere M:MIntBase{#[inline]fn hash(&self,state:&mut H){Hash::hash(&self.x,state)}}macro_rules!impl_mint_from{($($t:ty),*)=>{$(implFrom<$t>for MIntwhere M:MIntConvert<$t>,{#[inline]fn from(x:$t)->Self{Self::new_unchecked(>::from(x))}}implFrom>for$t where M:MIntConvert<$t>,{#[inline]fn from(x:MInt)->$t{>::into(x.x)}})*};}impl_mint_from!(u8,u16,u32,u64,u128,usize,i8,i16,i32,i64,i128,isize);implZero for MIntwhere M:MIntBase{#[inline]fn zero()->Self{Self::new_unchecked(M::mod_zero())}}implOne for MIntwhere M:MIntBase{#[inline]fn one()->Self{Self::new_unchecked(M::mod_one())}}implAdd for MIntwhere M:MIntBase{type Output=Self;#[inline]fn add(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_add(self.x,rhs.x))}}implSub for MIntwhere M:MIntBase{type Output=Self;#[inline]fn sub(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_sub(self.x,rhs.x))}}implMul for MIntwhere M:MIntBase{type Output=Self;#[inline]fn mul(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_mul(self.x,rhs.x))}}implDiv for MIntwhere M:MIntBase{type Output=Self;#[inline]fn div(self,rhs:Self)->Self::Output{Self::new_unchecked(M::mod_div(self.x,rhs.x))}}implNeg for MIntwhere M:MIntBase{type Output=Self;#[inline]fn neg(self)->Self::Output{Self::new_unchecked(M::mod_neg(self.x))}}implSum for MIntwhere M:MIntBase{#[inline]fn sum>(iter:I)->Self{iter.fold(::zero(),Add::add)}}implProduct for MIntwhere M:MIntBase{#[inline]fn product>(iter:I)->Self{iter.fold(::one(),Mul::mul)}}impl<'a,M:'a>Sum<&'a MInt>for MIntwhere M:MIntBase{#[inline]fn sum>(iter:I)->Self{iter.fold(::zero(),Add::add)}}impl<'a,M:'a>Product<&'a MInt>for MIntwhere M:MIntBase{#[inline]fn product>(iter:I)->Self{iter.fold(::one(),Mul::mul)}}implDisplay for MIntwhere M:MIntConvert,M::Inner:Display{fn fmt<'a>(&self,f:&mut fmt::Formatter<'a>)->Result<(),fmt::Error>{write!(f,\"{}\",self.inner())}}implFromStr for MIntwhere M:MIntConvert,M::Inner:FromStr{type Err=::Err;#[inline]fn from_str(s:&str)->Result{s.parse::().map(Self::new)}}implIterScan for MIntwhere M:MIntConvert,M::Inner:FromStr{type Output=Self;#[inline]fn scan<'a,I:Iterator>(iter:&mut I)->Option{iter.next()?.parse::>().ok()}}macro_rules!impl_mint_ref_binop{($imp:ident,$method:ident,$t:ty)=>{impl$imp<$t>for&$t where M:MIntBase,{type Output=<$t as$imp<$t>>::Output;#[inline]fn$method(self,other:$t)-><$t as$imp<$t>>::Output{$imp::$method(*self,other)}}impl$imp<&$t>for$t where M:MIntBase,{type Output=<$t as$imp<$t>>::Output;#[inline]fn$method(self,other:&$t)-><$t as$imp<$t>>::Output{$imp::$method(self,*other)}}impl$imp<&$t>for&$t where M:MIntBase,{type Output=<$t as$imp<$t>>::Output;#[inline]fn$method(self,other:&$t)-><$t as$imp<$t>>::Output{$imp::$method(*self,*other)}}};}impl_mint_ref_binop!(Add,add,MInt);impl_mint_ref_binop!(Sub,sub,MInt);impl_mint_ref_binop!(Mul,mul,MInt);impl_mint_ref_binop!(Div,div,MInt);macro_rules!impl_mint_ref_unop{($imp:ident,$method:ident,$t:ty)=>{impl$imp for&$t where M:MIntBase,{type Output=<$t as$imp>::Output;#[inline]fn$method(self)-><$t as$imp>::Output{$imp::$method(*self)}}};}impl_mint_ref_unop!(Neg,neg,MInt);macro_rules!impl_mint_ref_op_assign{($imp:ident,$method:ident,$t:ty,$fromimp:ident,$frommethod:ident)=>{impl$imp<$t>for$t where M:MIntBase,{#[inline]fn$method(&mut self,rhs:$t){*self=$fromimp::$frommethod(*self,rhs);}}impl$imp<&$t>for$t where M:MIntBase,{#[inline]fn$method(&mut self,other:&$t){$imp::$method(self,*other);}}};}impl_mint_ref_op_assign!(AddAssign,add_assign,MInt,Add,add);impl_mint_ref_op_assign!(SubAssign,sub_assign,MInt,Sub,sub);impl_mint_ref_op_assign!(MulAssign,mul_assign,MInt,Mul,mul);impl_mint_ref_op_assign!(DivAssign,div_assign,MInt,Div,div);}\r\npub use self::zero_one::{One,Zero};\r\nmod zero_one{pub trait Zero:Sized{fn zero()->Self;#[inline]fn is_zero(&self)->bool where Self:PartialEq{self==&Self::zero()}#[inline]fn set_zero(&mut self){*self=Self::zero();}}pub trait One:Sized{fn one()->Self;#[inline]fn is_one(&self)->bool where Self:PartialEq{self==&Self::one()}#[inline]fn set_one(&mut self){*self=Self::one();}}macro_rules!zero_one_impls{($({$Trait:ident$method:ident$($t:ty)*,$e:expr})*)=>{$($(impl$Trait for$t{fn$method()->Self{$e}})*)*};}zero_one_impls!({Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128,0}{Zero zero f32 f64,0.}{One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128,1}{One one f32 f64,1.});}\r\n#[derive(Clone,Debug)]pub struct MemorizedFactorial>{pub fact:Vec>,pub inv_fact:Vec>}\r\nimpl>MemorizedFactorial{pub fn new(max_n:usize)->Self{let mut fact=vec![MInt::one();max_n+1];let mut inv_fact=vec![MInt::one();max_n+1];for i in 2..=max_n{fact[i]=fact[i-1]*MInt::from(i);}inv_fact[max_n]=fact[max_n].inv();for i in(3..=max_n).rev(){inv_fact[i-1]=inv_fact[i]*MInt::from(i);}Self{fact,inv_fact}}#[inline]pub fn combination(&self,n:usize,r:usize)->MInt{debug_assert!(nMInt{debug_assert!(nMInt{debug_assert!(n+rMInt{debug_assert!(n0);self.inv_fact[n]*self.fact[n-1]}}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graph matchings"], "code_uid": "824b6813d2106e0f496f84565c35e0db", "src_uid": "b2d7ac8e75cbdb828067aeafd803ac62", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() -> () {\n\n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n handle.read_to_string(&mut buffer).expect(\"stdin\");\n\n let mut arr : Vec<_> = buffer.split_whitespace().map(|x| x.parse::().unwrap() ).collect();\n\n let n = arr[0] as usize;\n let a = arr[1] as usize;\n let b = arr[2] as usize;\n\n let v = arr.drain(3..).collect::>();\n\n let mut cost = 0usize;\n \n for i in 0..n / 2 + n % 2 {\n if v[i] != 2 && v[n-1-i] != 2 {\n if v[i] != v[n-1-i] {\n println!(\"-1\");\n return\n }\n } else if v[i] == 2 && v[n-1-i] == 2 {\n use std::cmp;\n cost += cmp::min( a, b ) * if i != n-1-i { 2 } else { 1 };\n } else if v[i] != 2 && i != n-1-i {\n cost += if v[i] == 0 { a } else { b };\n } else if v[n-1-i] != 2 && i != n-1-i {\n cost += if v[n-1-i] == 0 { a } else { b };\n } else {\n panic!();\n }\n }\n \n println!(\"{:?}\",cost);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "865a63b50dd05ec6dc16f7daee8d8328", "src_uid": "af07223819aeb5bd6ded4340c472b2b6", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main(){\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"read_line error\");\n \n let n : Vec<_> = input.trim().split_ascii_whitespace()\n .map(|num| {\n num.parse::()\n .expect(\"Parsing error\")\n }).collect();\n\n input.clear();\n io::stdin().read_line(&mut input)\n .expect(\"read_line error\");\n\n let mut v : Vec<_> = input.trim().split_ascii_whitespace()\n .map(|num| {\n num.parse::()\n .expect(\"Parsing error\")\n }).collect();\n \n v.sort();\n let mut best = v[n[1] - 1] - v[0];\n for i in 0 .. n[1] - n[0] + 1{\n best = if v[i + n[0] -1] - v[i] < best { v[i + n[0] -1] - v[i] } else { best};\n } \n \n println!(\"{}\", best);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "8684f05c24193cd9f37829d124268190", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_pair() -> (i32, i32) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\n\n\nfn main() {\n let (n, m) = read_line_pair();\n let mut f = read_line_vec();\n f.sort();\n\n let mut best_diff = i32::max_value();\n // println!(\"best_diff: {}\", best_diff);\n\n for i in 0..(m + 1) - n {\n let from_value = f[i as usize];\n let to_value = f[(i + n - 1) as usize];\n let diff = to_value - from_value;\n if diff < best_diff {\n best_diff = diff;\n }\n }\n \n println!(\"{:?}\", best_diff);\n\n \n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "5d5699690a8b4b758b2f89cbbaceaea7", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp;\nuse std::io::{stdin, stdout, BufWriter, Write};\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n //rust headache\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n //input headache\n let m: usize = scan.next();\n let n: usize = scan.next();\n let mut v: Vec = (0..n).map(|_| scan.next()).collect();\n v.sort_unstable();\n let mut min=1e6 as i32;\n for i in 0..=n-m as usize {\n min = cmp::min((v[i]-v[i+m-1]).abs(),min);\n }\n write!(out,\"{}\", min);\n\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "5a76f409c75b1413b42443b51fa05afd", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! rt {\n ( $( $type:ty ),+ ) => ({\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut iter = s.split_whitespace();\n (\n $(\n iter.next().unwrap().parse::<$type>().unwrap(),\n )+\n )\n })\n}\n\nmacro_rules! rv {\n ( $type:ty ) => ({\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let v: Vec<$type> = s.split_whitespace().map(|x|\n x.parse::<$type>().unwrap()).collect();\n v\n })\n}\n\nfn main() {\n let (n, m) = rt!(usize, usize);\n let mut v = rv!(usize);\n\n v.sort();\n\n let mut d = v[n-1] - v[0];\n for i in 1..m-n+1 {\n let diff = v[i+n-1] - v[i];\n if diff < d {\n d = diff;\n }\n }\n\n println!(\"{}\", d);\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "17eac8e25a55dd72edab56cb2fced06d", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn min_difference(n : u64, fs : &mut Vec) -> u64 {\n let mut min_diff = u64::max_value();\n let n_u = n as usize;\n let f_l_u = fs.len() as usize;\n fs.sort();\n for i in (n_u - 1) .. f_l_u {\n let diff = fs[i] - fs[(i + 1) - n_u];\n if diff < min_diff {\n min_diff = diff;\n }\n }\n min_diff\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut n_m = vec![];\n let mut fs = vec![];\n read_ts(&stdin, &mut n_m);\n read_ts(&stdin, &mut fs);\n let d = min_difference(n_m[0], &mut fs);\n println!(\"{}\", d);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "6ca1769f1c6d6130fffb5e7ef0ddd719", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_imports)]\nuse std::io::{self,Read};\n\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader : T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = (input.i() - 1) as usize;\n let m = input.i() as usize;\n let mut a = Vec::with_capacity(m);\n for _ in 0..m {\n a.push(input.i());\n }\n a.sort();\n let mut sol = 1000;\n for i in n..m {\n sol = std::cmp::min(sol, a[i] - a[i - n]);\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "f9375843a9342dbcca00f1a3c234ca26", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input_split() -> Vec {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let (n, m) = {\n let temp = input_split();\n (temp[0], temp[1])\n };\n let mut puzzles = input_split();\n puzzles.sort_unstable();\n\n let mut min_delta = 1001;\n for i in 0..=m - n {\n let mi = puzzles[i..i + n][0];\n let ma = puzzles[i..i + n][n - 1];\n min_delta = min_delta.min(ma - mi);\n }\n\n println!(\"{}\", min_delta);\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "e4fbb24a1d048abdc60111dcf7f028f7", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let mut iterator = stdin.lock().lines();\n let mut mins = Vec::new();\n\n let first = iterator.next().unwrap().unwrap();\n let second = iterator.next().unwrap().unwrap();\n\n let nm: Vec = first\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n \n let mut sizes: Vec = second\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n \n sizes.sort();\n\n for i in 0..(nm[1] - nm[0] + 1) {\n mins.push(sizes[i+nm[0]-1] - sizes[i])\n }\n\n let min = mins.iter().min();\n\n match min {\n Some(value) => println!(\"{}\", value),\n None => println!(\"Vector is empty.\"),\n }\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "ed0abf7ae3c5a81a2140a8e0b0bbbf99", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{ self, Write };\nuse std::str::FromStr;\nuse std::cmp::{ min, max };\nuse std::collections::{ BinaryHeap, VecDeque };\n\n#[allow(unused_macros)]\nmacro_rules! trace {\n ($var:expr) => {\n let _ = writeln!(&mut std::io::stderr(), \">>> {} = {:?}\", stringify!($var), $var);\n };\n ($($args:expr),*) => { trace!(($($args),*)) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! put {\n ($var:expr) => {\n let _ = writeln!(&mut std::io::stdout(), \"{}\", $var);\n };\n ($var:expr, $($args:expr),*) => {\n let _ = write!(&mut std::io::stdout(), \"{} \", $var);\n put!($($args),*);\n };\n}\n\nfn manhattan(p:(i64,i64), q:(i64,i64)) -> i64 {\n (p.0 - q.0).abs() + (p.1 - q.1).abs()\n}\n\nfn center(rect: &Vec<(i64, i64)>) -> (i64, i64) {\n let mut x = 0;\n let mut y = 0;\n for p in rect.iter() {\n x += p.0;\n y += p.1;\n }\n let m = rect.len() as i64;\n (x/m, y/m)\n}\n\nfn radius(rect: &Vec<(i64, i64)>) -> i64 {\n let mut mnx = rect[0].0;\n let mut mxx = rect[0].0;\n for p in rect.iter() {\n mnx = min(mnx, p.0);\n mxx = max(mxx, p.0);\n }\n (mxx - mnx) / 2\n}\n\nfn minx(rect: &Vec<(i64, i64)>) -> i64 {\n let mut ac = rect[0].0;\n for p in rect.iter() { ac = min(ac, p.0); }\n ac\n}\nfn maxx(rect: &Vec<(i64, i64)>) -> i64 {\n let mut ac = rect[0].0;\n for p in rect.iter() { ac = max(ac, p.0); }\n ac\n}\nfn miny(rect: &Vec<(i64, i64)>) -> i64 {\n let mut ac = rect[0].1;\n for p in rect.iter() { ac = min(ac, p.1); }\n ac\n}\nfn maxy(rect: &Vec<(i64, i64)>) -> i64 {\n let mut ac = rect[0].1;\n for p in rect.iter() { ac = max(ac, p.1); }\n ac\n}\n\nfn main() {\n let mut sc = Scanner::new();\n\n let red;\n let blue;\n {\n let x0: i64 = sc.cin();\n let y0: i64 = sc.cin();\n let x1: i64 = sc.cin();\n let y1: i64 = sc.cin();\n let x2: i64 = sc.cin();\n let y2: i64 = sc.cin();\n let x3: i64 = sc.cin();\n let y3: i64 = sc.cin();\n red = vec![(x0, y0), (x1, y1), (x2, y2), (x3, y3)];\n }\n {\n let x0: i64 = sc.cin();\n let y0: i64 = sc.cin();\n let x1: i64 = sc.cin();\n let y1: i64 = sc.cin();\n let x2: i64 = sc.cin();\n let y2: i64 = sc.cin();\n let x3: i64 = sc.cin();\n let y3: i64 = sc.cin();\n blue = vec![(x0, y0), (x1, y1), (x2, y2), (x3, y3)];\n }\n let c = center(&blue);\n let r = radius(&blue);\n for i in minx(&red)..(maxx(&red)+1) {\n for j in miny(&red)..(maxy(&red)+1) {\n if manhattan((i, j), c) <= r {\n // trace!((i, j), c, manhattan((i, j), c));\n println!(\"YES\");\n return\n }\n }\n }\n println!(\"NO\");\n\n}\n\n#[allow(dead_code)]\nstruct Scanner { stdin: io::Stdin, buffer: VecDeque, }\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }\n fn reserve(&mut self) {\n while self.buffer.len() == 0 {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n }\n fn cin(&mut self) -> T {\n self.reserve();\n match self.buffer.pop_front().unwrap().parse::() {\n Ok(a) => a,\n Err(_) => panic!(\"parse err\")\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "c0484c9a530d7078a203ec3f45918171", "src_uid": "f6a3dd8b3bab58ff66055c61ddfdf06a", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\ntype Point = (i32, i32);\ntype Seg = (Point, Point);\n\nfn cm(base: &Point, a: &Point, b: &Point) -> i32 {\n return (a.0 - base.0)*(b.1 - base.1) - (a.1 - base.1)*(b.0 - base.0);\n}\n\nfn inx(a: i32, b: i32, x: i32) -> bool {\n return (b >= a && x >= a && x <= b) || (b <= a && x <= a && x >= b);\n}\n\nfn ins(pa: &Point, pb: &Point, px: &Point) -> bool {\n return inx(pa.0, pb.0, px.0) && inx(pa.1, pb.1, px.1);\n}\n\nfn intersect(a: &Seg, b: &Seg) -> bool {\n let b0 = cm(&a.0, &a.1, &b.0);\n if b0 == 0 && ins(&a.0, &a.1, &b.0) { return true; }\n let b1 = cm(&a.0, &a.1, &b.1);\n if b1 == 0 && ins(&a.0, &a.1, &b.1) { return true; }\n let a0 = cm(&b.0, &b.1, &a.0);\n if a0 == 0 && ins(&b.0, &b.1, &a.0) { return true; }\n let a1 = cm(&b.0, &b.1, &a.1);\n if a1 == 0 && ins(&b.0, &b.1, &a.1) { return true; }\n return ((a0 > 0 && a1 < 0) || (a0 < 0 && a1 > 0))\n && ((b0 > 0 && b1 < 0) || (b0 < 0 && b1 > 0));\n}\n\nfn main() {\n let stdin: io::Stdin = io::stdin();\n let mut lines: io::Lines = stdin.lock().lines();\n\n let line_1 = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n let line_2 = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let square_a: Vec<_> = line_1.trim().split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n\n let square_b: Vec<_> = line_2.trim().split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n \n // any a inside b\n for a_i in 0..4 {\n let a = (square_a[2*a_i], square_a[2*a_i+1]);\n let mut left = false;\n let mut right = false;\n for i in 0..4 {\n let base = (square_b[2*i], square_b[2*i+1]);\n let j = (i+1) % 4;\n let b = (square_b[2*j], square_b[2*j+1]);\n let cmv = cm(&base, &b, &a);\n if cmv > 0 { left = true; }\n if cmv < 0 { right = true; }\n }\n if !left || !right {\n println!(\"YES\");\n return;\n }\n }\n\n // any b inside a\n for b_i in 0..4 {\n let b = (square_b[2*b_i], square_b[2*b_i+1]);\n let mut left = false;\n let mut right = false;\n for i in 0..4 {\n let base = (square_a[2*i], square_a[2*i+1]);\n let j = (i+1) % 4;\n let a = (square_a[2*j], square_a[2*j+1]);\n let cmv = cm(&base, &a, &b);\n if cmv > 0 { left = true; }\n if cmv < 0 { right = true; }\n }\n if !left || !right {\n println!(\"YES\");\n return;\n }\n }\n\n // check intersect\n for a_i in 0..4 {\n let a_a = (square_a[2*a_i], square_a[2*a_i+1]);\n let a_j = (a_i + 1) % 4;\n let a_b = (square_a[2*a_j], square_a[2*a_j+1]);\n let seg_a = (a_a, a_b);\n\n for i in 0..4 {\n let b_a = (square_b[2*i], square_b[2*i+1]);\n let j = (i+1) % 4;\n let b_b = (square_b[2*j], square_b[2*j+1]);\n let seg_b = (b_a, b_b);\n if intersect(&seg_a, &seg_b) {\n println!(\"YES\");\n return;\n }\n }\n }\n\n println!(\"NO\");\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "93cf512dee5f00a6ed6e16a035b4e8d9", "src_uid": "f6a3dd8b3bab58ff66055c61ddfdf06a", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\ntype Point = (i32, i32);\ntype Seg = (Point, Point);\n\n\n\n\nfn cross_product(base: &Point, a: &Point, b: &Point) -> i32 {\n return (a.0 - base.0)*(b.1 - base.1) - (a.1 - base.1)*(b.0 - base.0);\n}\n\nfn is_inside(p: Point, square: &Vec) -> bool {\n let mut left = false;\n let mut right = false;\n\n // loop through all sides of square\n for i in 0..4 {\n let j = (i+1) % 4;\n let side_p1 = (square[2*i], square[2*i+1]);\n let side_p2 = (square[2*j], square[2*j+1]);\n\n let cp = cross_product(&side_p1, &side_p2, &p);\n if cp > 0 { left = true; }\n if cp < 0 { right = true; }\n }\n \n return !left || !right;\n}\n\nfn inx(a: i32, b: i32, x: i32) -> bool {\n return (b >= a && x >= a && x <= b) || (b <= a && x <= a && x >= b);\n}\n\nfn ins(pa: &Point, pb: &Point, px: &Point) -> bool {\n return inx(pa.0, pb.0, px.0) && inx(pa.1, pb.1, px.1);\n}\n\nfn intersect(a: &Seg, b: &Seg) -> bool {\n let b0 = cross_product(&a.0, &a.1, &b.0);\n if b0 == 0 && ins(&a.0, &a.1, &b.0) { return true; }\n let b1 = cross_product(&a.0, &a.1, &b.1);\n if b1 == 0 && ins(&a.0, &a.1, &b.1) { return true; }\n let a0 = cross_product(&b.0, &b.1, &a.0);\n if a0 == 0 && ins(&b.0, &b.1, &a.0) { return true; }\n let a1 = cross_product(&b.0, &b.1, &a.1);\n if a1 == 0 && ins(&b.0, &b.1, &a.1) { return true; }\n return ((a0 > 0 && a1 < 0) || (a0 < 0 && a1 > 0))\n && ((b0 > 0 && b1 < 0) || (b0 < 0 && b1 > 0));\n}\n\nfn main() {\n let stdin: io::Stdin = io::stdin();\n let mut lines: io::Lines = stdin.lock().lines();\n\n let line_1 = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n let line_2 = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let square_a: Vec<_> = line_1.trim().split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n\n let square_b: Vec<_> = line_2.trim().split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n \n // any a inside b\n for a_i in 0..4 {\n let a = (square_a[2*a_i], square_a[2*a_i+1]);\n if is_inside(a, &square_b) {\n println!(\"YES\");\n return;\n }\n }\n\n // any b inside a\n for b_i in 0..4 {\n let b = (square_b[2*b_i], square_b[2*b_i+1]);\n let mut left = false;\n let mut right = false;\n for i in 0..4 {\n let base = (square_a[2*i], square_a[2*i+1]);\n let j = (i+1) % 4;\n let a = (square_a[2*j], square_a[2*j+1]);\n let cmv = cross_product(&base, &a, &b);\n if cmv > 0 { left = true; }\n if cmv < 0 { right = true; }\n }\n if !left || !right {\n println!(\"YES\");\n return;\n }\n }\n\n // check intersect\n for a_i in 0..4 {\n let a_j = (a_i + 1) % 4;\n let a_point_1 = (square_a[2*a_i], square_a[2*a_i+1]);\n let a_point_2 = (square_a[2*a_j], square_a[2*a_j+1]);\n let seg_a = (a_point_1, a_point_2);\n\n for b_i in 0..4 {\n let b_j = (b_i+1) % 4;\n let b_point_1 = (square_b[2*b_i], square_b[2*b_i+1]);\n let b_point_2 = (square_b[2*b_j], square_b[2*b_j+1]);\n let seg_b = (b_point_1, b_point_2);\n\n if intersect(&seg_a, &seg_b) {\n println!(\"YES\");\n return;\n }\n }\n }\n\n println!(\"NO\");\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "2f5567a5f5c58d6de5bf8e7b8dfa27b6", "src_uid": "f6a3dd8b3bab58ff66055c61ddfdf06a", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\ntype Point = (i32, i32);\ntype Seg = (Point, Point);\n\nfn cm(base: &Point, a: &Point, b: &Point) -> i32 {\n let debug = false;\n if debug { println!(\"base {:?}, a {:?}, b {:?}\", base, a, b) }\n return (a.0 - base.0)*(b.1 - base.1) - (a.1 - base.1)*(b.0 - base.0);\n}\n\nfn inx(a: i32, b: i32, x: i32) -> bool {\n return (b >= a && x >= a && x <= b) || (b <= a && x <= a && x >= b);\n}\n\nfn ins(pa: &Point, pb: &Point, px: &Point) -> bool {\n return inx(pa.0, pb.0, px.0) && inx(pa.1, pb.1, px.1);\n}\n\nfn intersect(a: &Seg, b: &Seg) -> bool {\n let b0 = cm(&a.0, &a.1, &b.0);\n if b0 == 0 && ins(&a.0, &a.1, &b.0) { return true; }\n let b1 = cm(&a.0, &a.1, &b.1);\n if b1 == 0 && ins(&a.0, &a.1, &b.1) { return true; }\n let a0 = cm(&b.0, &b.1, &a.0);\n if a0 == 0 && ins(&b.0, &b.1, &a.0) { return true; }\n let a1 = cm(&b.0, &b.1, &a.1);\n if a1 == 0 && ins(&b.0, &b.1, &a.1) { return true; }\n return ((a0 > 0 && a1 < 0) || (a0 < 0 && a1 > 0))\n && ((b0 > 0 && b1 < 0) || (b0 < 0 && b1 > 0));\n}\n\nfn main() {\n let debug = false;\n let stdin: io::Stdin = io::stdin();\n let mut lines: io::Lines = stdin.lock().lines();\n\n let next_line = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let square_a: Vec<_> = next_line\n .trim()\n .split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n\n let next_line = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let square_b: Vec<_> = next_line\n .trim()\n .split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n \n // any a inside b\n if debug { println!(\"\\n\\n a inside b ?? \\n\\n\") }\n for a_i in 0..4 {\n let a = (square_a[2*a_i], square_a[2*a_i+1]);\n let mut left = false;\n let mut right = false;\n if debug { println!(\"POINT a choosen\") }\n for i in 0..4 {\n let base = (square_b[2*i], square_b[2*i+1]);\n let j = (i+1) % 4;\n let b = (square_b[2*j], square_b[2*j+1]);\n if debug { println!(\"-------------------\") }\n let cmv = cm(&base, &b, &a);\n if debug { println!(\"cmv {}\", cmv) }\n if cmv > 0 { left = true; }\n if cmv < 0 { right = true; }\n }\n if !left || !right {\n println!(\"YES\");\n return;\n }\n }\n\n // any b inside a\n if debug { println!(\"\\n\\n b inside a ?? \\n\\n\") }\n for b_i in 0..4 {\n let b = (square_b[2*b_i], square_b[2*b_i+1]);\n let mut left = false;\n let mut right = false;\n if debug { println!(\"POINT b choosen\") }\n for i in 0..4 {\n let base = (square_a[2*i], square_a[2*i+1]);\n let j = (i+1) % 4;\n let a = (square_a[2*j], square_a[2*j+1]);\n if debug { println!(\"-------------------\") }\n let cmv = cm(&base, &a, &b);\n if debug { println!(\"cmv {}\", cmv) }\n if cmv > 0 { left = true; }\n if cmv < 0 { right = true; }\n }\n if !left || !right {\n println!(\"YES\");\n return;\n }\n }\n\n // check intersect\n for a_i in 0..4 {\n let a_a = (square_a[2*a_i], square_a[2*a_i+1]);\n let a_j = (a_i + 1) % 4;\n let a_b = (square_a[2*a_j], square_a[2*a_j+1]);\n let seg_a = (a_a, a_b);\n\n for i in 0..4 {\n let b_a = (square_b[2*i], square_b[2*i+1]);\n let j = (i+1) % 4;\n let b_b = (square_b[2*j], square_b[2*j+1]);\n let seg_b = (b_a, b_b);\n if intersect(&seg_a, &seg_b) {\n println!(\"YES\");\n return;\n }\n }\n }\n\n println!(\"NO\");\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "41a0b0276a99e3a77b865ebf95231202", "src_uid": "f6a3dd8b3bab58ff66055c61ddfdf06a", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_pair() -> (i32, i32) {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n let v = input\n .trim()\n .split_whitespace()\n .map(|s| i32::from_str(s).unwrap())\n .collect::>();\n\n (v[0], v[1])\n}\n\nfn main() {\n let (n, m) = get_pair();\n\n let mut c = 0;\n for a in 0..=1000 {\n for b in 0..=100 {\n if a * a + b == n && a + b * b == m {\n c += 1;\n }\n }\n }\n\n println!(\"{}\", c);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "46716dbf01880e5012ebf570cdb3a9d5", "src_uid": "03caf4ddf07c1783e42e9f9085cc6efd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n let m = input.i();\n let sol: usize = (0..1001).map(|a| (0..1001).filter(|b| a*a+b == n && a+b*b == m).count()).sum();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "54e67197736000da6f8be9f9b82f02e4", "src_uid": "03caf4ddf07c1783e42e9f9085cc6efd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Pair = (u16, u16);\nfn input_pair() -> Pair {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let buf: Vec = buf\n .trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect();\n (buf[0], buf[1])\n}\n\nfn main() {\n let (n, m) = input_pair();\n let mut count = 0;\n let border = f32::from(n).sqrt() as u16;\n for a in 0u16..=border {\n let b_sqr = (n - a.pow(2)).pow(2);\n if a + b_sqr == m {\n count += 1;\n }\n }\n\n print!(\"{}\", count);\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "c09ea668e170031729411bd39a0ca577", "src_uid": "03caf4ddf07c1783e42e9f9085cc6efd", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*};\n\n\n#[allow(unused_must_use)]\n#[allow(unused_assignments)]\n#[allow(unused_variables)]\nfn solve(mut scan: Scanner, mut w: W) {\n let mut input: Vec = scan.get_vector(4);\n\n input.sort();\n input.dedup();\n let ans: usize = 4 -input.len();\n\n writeln!(w, \"{}\", ans);\n}\n \nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n solve(reader, writer);\n}\n#[allow(dead_code)]\nfn vector_to_str(vector: &Vec, separator: &str) -> String { \n use std::fmt::Write;\n let mut ans = String::new();\n for line in vector.iter() {\n write!(&mut ans, \"{}{}\", line.to_string(), separator).unwrap();\n }\n ans\n}\n#[allow(dead_code)]\nfn matrix_to_str(matrix: &Vec>, separator: &str) -> String { \n use std::fmt::Write;\n let mut ans = String::new();\n for line in matrix.iter() {\n for elem in line.iter() {\n write!(&mut ans, \"{}{}\", elem.to_string(), separator).unwrap();\n }\n write!(&mut ans, \"\\n\").unwrap();\n }\n ans\n}\npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace()\n }\n }\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace()) }\n }\n }\n pub fn get_matrix(&mut self, m: usize, n: usize) -> Vec> {\n // m rows and n columns\n let mut ans: Vec> = Vec::with_capacity(m);\n for i in 0..m {\n ans.push(Vec::with_capacity(n));\n for _ in 0..n {\n ans[i].push(self.token::());\n }\n }\n ans\n }\n pub fn get_vector(&mut self, n: usize) -> Vec {\n let mut ans: Vec = Vec::with_capacity(n);\n for _ in 0..n {\n ans.push(self.token::());\n }\n ans\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4559fddfad3b9302c3316be0ce1d6030", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\nuse std::io::*;\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n let input: Vec = reads(sin);\n\n let mut set = HashSet::new();\n\n for c in input {\n set.insert(c);\n }\n\n println!(\"{}\", 4 - set.len());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b819db1fc38b67ba40f239c200c98220", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\nuse std::io::stdin;\n\nfn main() {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n\n let line: Vec = line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let mut lista_sin_repetidos = HashSet::new();\n\n for i in line {\n lista_sin_repetidos.insert(i);\n }\n\n println!(\"{}\", 4 - lista_sin_repetidos.len());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f3fbb2b6306f1a3933cc238c5894ee29", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/228/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let mut ns: Vec = buf.split(\" \")\n .map(|str| str.trim().parse::().unwrap())\n .collect();\n ns.sort();\n let mut last = 0;\n let mut shoes = 0;\n for n in ns {\n if n != last { shoes += 1; last = n; }\n }\n println!(\"{}\", 4 - shoes);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "71119f8826126c166c80462ea414072f", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn main() {\n let mut scan = Scan::new();\n let a: usize = scan.next();\n let b: usize = scan.next();\n let c: usize = scan.next();\n let d: usize = scan.next();\n let eq: [bool;3] = [a==b || a==c || a==d, b==c || b==d, c==d];\n let result: usize = eq.iter().map(|&x| (x as usize))\n .fold(0,|sum, x| sum+x);\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b43e7b0ee36938a0676a51f4ab17db13", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\n\nfn read_str() -> String {\n let mut buffer: String = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Error\");\n buffer.trim().to_string()\n}\n\nfn read_hash() -> std::collections::HashSet {\n read_str()\n .split_whitespace()\n .map(|value| value.parse::().ok().expect(\"Error\"))\n .collect()\n}\n\nfn main() {\n let shoes: std::collections::HashSet = read_hash();\n print!(\"{}\", 4 - shoes.len());\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "51e1d39033cdb4371eb284bbaaa67901", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cell::RefCell;\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Formatter, Write as FmtWrite};\nuse std::io::{stderr, stdin, BufRead, Write};\nuse std::mem::{replace, swap};\nuse std::ops::*;\nuse std::rc::Rc;\n\n// -----------------------------------------------\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($t:ty) =>\n (rl().parse::<$t>().unwrap());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($arg:expr),*) => {\n #[cfg(debug_assertions)]\n $(writeln!(stderr(), \"{} = {:?}\", stringify!($arg), $arg).unwrap());*\n };\n}\n\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_owned()\n}\n\ntrait IteratorExt: Iterator + Sized {\n fn vec(self) -> Vec {\n self.collect()\n }\n}\n\nimpl IteratorExt for T {}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\nfn main() {\n let input = rl();\n\n let mut s = HashSet::new();\n\n input\n .split(\" \")\n .for_each(|t| {\n s.insert(t);\n });\n\n println!(\"{}\", 4-s.len());\n\n\treturn;\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f565494410264227955d4660b2b5e37d", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/228/A\nuse std::io;\nuse std::collections::HashSet;\n\nfn main() {\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let words: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let mut horseshoes = HashSet::new();\n\n for item in words {\n horseshoes.insert(item);\n }\n\n println!(\"{}\", 4-horseshoes.len());\n\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a215bbdf9ff7f2888a925f778f6a2298", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\nuse std::collections::VecDeque;\n\nstruct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> VecDeque {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn get_state(card1: &VecDeque, card2: &VecDeque) -> (u64, u64) {\n let mut r1 = 0u64;\n let mut r2 = 0u64;\n for item in card1.iter() {\n r1 <<= 4;\n r1 |= 1 << *item as u64;\n }\n for item in card2.iter() {\n r2 <<= 4;\n r2 |= 1 << *item as u64;\n }\n return (r1, r2);\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut visited = HashSet::new();\n let _n: usize = scan.next();\n let k1: usize = scan.next();\n let mut card1: VecDeque = scan.next_n(k1);\n let k2: usize = scan.next();\n let mut card2: VecDeque = scan.next_n(k2);\n let mut wars = 0usize;\n while !card1.is_empty() && !card2.is_empty() {\n let first = card1.pop_front().unwrap();\n let second = card2.pop_front().unwrap();\n if first > second {\n card1.push_back(second);\n card1.push_back(first);\n } else {\n card2.push_back(first);\n card2.push_back(second);\n }\n wars += 1;\n let state = get_state(&card1, &card2);\n if visited.contains(&state) {\n break;\n }\n visited.insert(state);\n }\n if !card1.is_empty() && !card2.is_empty() {\n println!(\"-1\");\n } else {\n println!(\"{} {}\", wars, if card1.is_empty() { 2 } else { 1 });\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "brute force", "games"], "code_uid": "2f8b284f3a43ad492d6bd93f96e27682", "src_uid": "f587b1867754e6958c3d7e0fe368ec6e", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Vicfred\n// https://codeforces.com/problemset/problem/546/C\n\nuse std::io;\nuse std::collections::HashSet;\nuse std::collections::VecDeque;\n\n#[derive(Debug,PartialEq,Eq,PartialOrd,Ord,Hash)]\nstruct Pair(i64, i64);\n\nfn main() {\n let mut n = String::new();\n\n io::stdin()\n .read_line(&mut n)\n .unwrap();\n\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let mut a: VecDeque =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n a.pop_front();\n\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let mut b: VecDeque =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n b.pop_front();\n\n let mut ans = 0;\n\n let mut states = HashSet::new();\n\n states.insert(Pair(1,2));\n\n while !a.is_empty() && !b.is_empty() {\n ans += 1;\n\n let x = a.pop_front().unwrap();\n let y = b.pop_front().unwrap();\n\n if x > y {\n a.push_back(y);\n a.push_back(x);\n } else {\n b.push_back(x);\n b.push_back(y);\n }\n\n if ans > 200 {\n println!(\"-1\");\n return;\n }\n }\n\n let winner = if a.is_empty() {2} else {1};\n\n println!(\"{} {}\", ans, winner);\n}\n\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "brute force", "games"], "code_uid": "96bb0c2c168ded2cc2bbafb8f12c79cb", "src_uid": "f587b1867754e6958c3d7e0fe368ec6e", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n type D = VecDeque;\n let _n = input.u();\n let mut a = (0..2).map(|_| {\n let k = input.u();\n input.ii(k).collect::()\n });\n let s0 = (a.next().unwrap(), a.next().unwrap());\n let mut s1 = s0.clone();\n let mut s2 = s0;\n\n let advance = |(a,b):(D,D)| -> (D,D) {\n if a.is_empty() || b.is_empty() {\n (a,b)\n } else {\n let mut a = a;\n let mut b = b;\n let x = a.pop_front().unwrap();\n let y = b.pop_front().unwrap();\n if x > y {\n a.push_back(y);\n a.push_back(x);\n } else {\n b.push_back(x);\n b.push_back(y);\n }\n (a,b)\n }\n };\n\n for sol in 1.. {\n s1 = advance(s1);\n s2 = advance(s2);\n s2 = advance(s2);\n\n if s1.1.is_empty() {\n println!(\"{} 1\", sol);\n break;\n }\n if s1.0.is_empty() {\n println!(\"{} 2\", sol);\n break;\n }\n if s1 == s2 {\n println!(\"-1\");\n break;\n }\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "brute force", "games"], "code_uid": "65f59de2add2bff47b217a2f80ffd0d1", "src_uid": "f587b1867754e6958c3d7e0fe368ec6e", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Vicfred\n// https://codeforces.com/problemset/problem/546/C\n\nuse std::io;\nuse std::collections::HashSet;\nuse std::collections::VecDeque;\n\n#[derive(Debug,PartialEq,Eq,PartialOrd,Ord,Hash)]\nstruct Pair(i64, i64);\n\nfn main() {\n let mut n = String::new();\n\n io::stdin()\n .read_line(&mut n)\n .unwrap();\n\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let mut a: VecDeque =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n a.pop_front();\n\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let mut b: VecDeque =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n b.pop_front();\n\n let mut ans = 0;\n\n while !a.is_empty() && !b.is_empty() {\n ans += 1;\n\n let x = a.pop_front().unwrap();\n let y = b.pop_front().unwrap();\n\n if x > y {\n a.push_back(y);\n a.push_back(x);\n } else {\n b.push_back(x);\n b.push_back(y);\n }\n if ans > 1000 {\n println!(\"-1\");\n return;\n }\n }\n\n let winner = if a.is_empty() {2} else {1};\n\n println!(\"{} {}\", ans, winner);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "brute force", "games"], "code_uid": "4438f859e55408ce0618b84756e094ed", "src_uid": "f587b1867754e6958c3d7e0fe368ec6e", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n\n let mut n: i32 = input.trim().parse().unwrap();\n\n let mut compare = n;\n let mut sum: i32 = 0;\n\n loop {\n while n > 0{\n sum += n % 10;\n n /= 10;\n }\n if sum % 4 == 0 {\n println!(\"{}\", compare);\n break;\n } else {\n sum = 0;\n compare += 1;\n n = compare;\n\n }\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e0b36bf40786b460940e612a1bb157b7", "src_uid": "bb6fb9516b2c55d1ee47a30d423562d7", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input!(a: i32);\n let mut a = a;\n loop {\n let mut v = a;\n let mut sum = 0;\n while v > 0 {\n sum += v % 10;\n v /= 10;\n }\n if sum % 4 == 0 {\n puts!(\"{}\\n\", a);\n return;\n }\n a += 1;\n }\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "47437507089d9315422a7bbfcff78f8e", "src_uid": "bb6fb9516b2c55d1ee47a30d423562d7", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn sum_digts(n: u16) -> u16 {\n n.to_string()\n .split(\"\")\n .filter_map(|a| a.parse::().ok())\n .sum()\n}\n\nfn main() {\n let a: u16 = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n };\n\n println!(\n \"{}\",\n (a..).skip_while(|&n| sum_digts(n) % 4 != 0).next().unwrap()\n );\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9df42d6b6af0afe6a07e37744ea705bc", "src_uid": "bb6fb9516b2c55d1ee47a30d423562d7", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nuse std::hash::Hash;\nfn inc(map:&mut BTreeMap, key:T) {\n let count = map.entry(key).or_insert(0);\n *count += 1;\n}\n\nfn digit(ch: char) -> i64 {\n return (ch as u8 - b'0') as i64\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nfn func(n:i64) -> i64 {\n if n==0 { return 0; }\n n%10 + func(n/10)\n}\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let a:i64 = read();\n for n in a..1000000 {\n if func(n)%4 == 0 {\n println!(\"{}\", n);\n return;\n }\n }\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "55125155697e9a9063f46365a8baa845", "src_uid": "bb6fb9516b2c55d1ee47a30d423562d7", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn sum_digits(n : u16) -> u16 {\n let mut num = n;\n let mut sum = 0;\n while num != 0 {\n sum += num % 10;\n num /= 10;\n }\n sum\n}\n\nfn to_div_four(n : u16) -> u16 {\n let m = n % 4;\n if m == 0 {\n 0\n } else {\n 4 - m\n }\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"failed to read input\");\n\n let mut n: u16 = input.trim().parse().expect(\"invalid input\");\n let mut s = to_div_four(sum_digits(n));\n if n % 10 + s >= 10 {\n n = n + 10 - (n % 10);\n s = to_div_four(sum_digits(n));\n }\n println!(\"{}\", n + s);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f28621eadf72fb25df811e0442890fcf", "src_uid": "bb6fb9516b2c55d1ee47a30d423562d7", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\n\nfn exec() {\n let mut sc = Scanner::new();\n let n: usize = sc.ne();\n let a: Vec = (0..n).map(|_| sc.ne()).collect();\n let b: Vec = (0..n).map(|_| sc.ne()).collect();\n let mut cnt = vec![0i32; 6];\n for &x in &a {\n cnt[x] += 1;\n }\n for &x in &b {\n cnt[x] += 1;\n }\n let mut ok = true;\n for i in 1..6 {\n if cnt[i] & 1 == 1 {\n ok = false;\n }\n }\n if ok {\n let mut cnt2 = vec![0; 6];\n for &x in &a {\n cnt2[x] += 1;\n }\n let mut ans = 0;\n for i in 1..6 {\n let a = cnt[i] / 2;\n ans += (a - cnt2[i]).abs();\n }\n println!(\"{}\", ans / 2);\n } else {\n println!(\"-1\");\n }\n}\n\nfn main() {\n const STACK: usize = 16 * 1024 * 1024;\n let _ = std::thread::Builder::new()\n .stack_size(STACK)\n .spawn(|| { exec(); })\n .unwrap()\n .join()\n .unwrap();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => {\n panic!(\"parse error, {:?}\",\n String::from_utf8(self.buf[l..r].to_owned()))\n }\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "475a153f1dc99ddeed9b6fd02faab8a1", "src_uid": "47da1dd95cd015acb8c7fd6ae5ec22a3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let n: usize = get_line().trim().parse().unwrap();\n\n let a: Vec = get_vec();\n\n let b: Vec = get_vec();\n\n let a_cnts = a.into_iter().fold(vec![0i32; 5], |mut acc, x| {\n acc[(x - 1) as usize] += 1;\n acc\n });\n\n let b_cnts = b.into_iter().fold(vec![0i32; 5], |mut acc, x| {\n acc[(x - 1) as usize] += 1;\n acc\n });\n\n let ans = if (0..5).all(|i| (a_cnts[i] + b_cnts[i]) % 2 == 0) {\n (0..5).map(|i| ((b_cnts[i] - a_cnts[i]) / 2).abs()).sum::() / 2\n } else {\n -1\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "75c3b9e07d9c232aac0ad8211f07f416", "src_uid": "47da1dd95cd015acb8c7fd6ae5ec22a3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(dead_code)]\nuse std::cmp::*;\nuse std::collections::*;\n\nfn main() {\n let n = readln();\n let xs: Vec = readln();\n let ys: Vec = readln();\n let mut fx: Vec = vec![0;6];\n let mut fy: Vec = vec![0;6];\n let mut freq: Vec = vec![0;6];\n for i in 0..n {\n fx[xs[i]] += 1;\n fy[ys[i]] += 1;\n freq[xs[i]] += 1;\n freq[ys[i]] += 1;\n }\n\n for i in 1..6 {\n if freq[i] % 2 != 0 {\n println!(\"-1\");\n return;\n }\n }\n\n let mut res = 0;\n for i in 1..6 {\n let k = freq[i] / 2;\n if fx[i] > k {\n res += fx[i] - k;\n }\n }\n\n\n println!(\"{}\", res);\n\n}\n\n\nfn get_line() -> String {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_string()\n}\n\nfn get_chars() -> Vec {\n get_line().chars().collect()\n}\n\nfn readln() -> T {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n T::read(buf.trim_right())\n}\n\ntrait Read {\n fn read(s: &str) -> Self;\n}\n\nmacro_rules! read_impl{\n ($($t:ty)*) => ($(\n impl Read for $t {\n fn read(s: &str) -> $t{\n s.parse().unwrap()\n }\n }\n )*)\n}\nread_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.split_whitespace().map(T::read).collect()\n }\n}\n\nimpl Read for (A, B) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]))\n }\n}\n\nimpl Read for (A, B, C) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "4e97e4d06c65485ae153323d6590c064", "src_uid": "47da1dd95cd015acb8c7fd6ae5ec22a3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! ----------------------------------------------\n//! Framework \n//!\n//! See the bottom of file for solution.\n//! ----------------------------------------------\n\n#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cell::RefCell;\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Display, Formatter, Write as FmtWrite};\nuse std::io::{stderr, stdin, BufRead, Write};\nuse std::mem::{replace, swap};\nuse std::ops::*;\nuse std::rc::Rc;\n\n/// Print values to standard error if debug mode.\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($e:expr),*) => {\n #[cfg(debug_assertions)]\n $({\n let (e, mut err) = (stringify!($e), stderr());\n writeln!(err, \"\\x1B[33m{}\\x1B[0m = {:?}\", e, $e).unwrap()\n })*\n };\n}\n\n/// Read from standard input and parse each word.\n/// - `read!(T, U, ..)` parses a line as a tuple of words.\n/// - `read![[T]]` parses a line as an array of words.\n/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n/// Read a line from standard input.\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n\n #[allow(deprecated)]\n buf.trim_right().to_owned()\n}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\nstruct Solver {\n N: usize,\n dp: Vec>,\n}\n\nimpl Solver {\n fn dfs(&mut self, x: usize, y: usize) -> i64 {\n if self.dp[x][y] == 0 {\n self.dp[x][y] = self.do_dfs(x, y);\n }\n self.dp[x][y]\n }\n\n fn do_dfs(&mut self, x: usize, y: usize) -> i64 {\n assert!(x < y);\n if y - x == 1 {\n return 0;\n }\n\n let mut min_w = std::i64::MAX;\n for z in x + 1..y {\n min_w = min(min_w, self.dfs(x, z) + self.dfs(z, y) + (x * y * z) as i64)\n }\n min_w\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(200 * 1024 * 1024)\n .spawn(|| {\n let N = read!(usize);\n let w = Solver {\n N: N,\n dp: vec![vec![0; N + 2]; N + 2],\n }\n .dfs(1, N);\n println!(\"{}\", w)\n })\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp"], "code_uid": "9f1d42abd85255b456ff2eb8cd9da1d5", "src_uid": "1bd29d7a8793c22e81a1f6fd3991307a", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n\nuse std::cmp::*;\nuse std::collections::*;\n\nfn main() {\n let n = read_ints()[0];\n let mut r: i64 = 0;\n for i in 2..n {\n r += 1*(n - i + 2)*(n - i + 1);\n }\n println!(\"{}\", r);\n}\n\nfn read_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n return s;\n}\n\nfn read_ints() -> Vec {\n return read_line()\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp"], "code_uid": "7e23071eb2b887e4b046684b8f29daa6", "src_uid": "1bd29d7a8793c22e81a1f6fd3991307a", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let x_2: usize = input.trim().parse().unwrap();\n\n // Le troisi\u00e8me exemple est assez surprenant. 8192 = 2^13,\n // Il faut que le nombre premier choisi par Bob divise le r\u00e9sultat, ce qui\n // explique d\u00e9j\u00e0 le troisi\u00e8me exemple. X_2 est composite par hypoth\u00e8se. On\n // envisage de prendre son plus petit diviseur premier comme choix de Bob.\n // X_2 = p * k. On a p * (k - 1) < X_1 <= X_2\n\n let n = 1_000_001;\n\n let mut fl = vec![0; n];\n\n for i in 2..= 1_000 {\n if fl[i] != 0 {\n continue;\n }\n let mut x = 2 * i;\n while x < n {\n if fl[x] == 0 {\n fl[x] = i;\n }\n x += i;\n }\n }\n\n let gpd = |mut i| {\n while i != fl[i] && fl[i] != 0 {\n i /= fl[i];\n }\n i\n };\n\n let mut ans = None;\n\n let gpd_2 = gpd(x_2);\n let k_2 = x_2 / gpd_2;\n\n for x_1 in gpd_2 * (k_2 - 1) + 1..=x_2 {\n let gpd_1 = gpd(x_1);\n let cand = if fl[x_1] == 0 { x_1 } else {\n (x_1 / gpd_1 - 1) * gpd_1 + 1\n };\n match ans {\n Some(a) if a <= cand => (),\n _ => ans = Some(cand),\n }\n }\n\n println!(\"{}\", ans.unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "d8ff2441320fda9a235ab74a790f77a7", "src_uid": "43ff6a223c68551eff793ba170110438", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin chmin, chmax ----------\ntrait ChangeMinMax {\n fn chmin(&mut self, x: Self) -> bool;\n fn chmax(&mut self, x: Self) -> bool;\n}\n\nimpl ChangeMinMax for T {\n fn chmin(&mut self, x: Self) -> bool {\n *self > x && {\n *self = x;\n true\n }\n }\n fn chmax(&mut self, x: Self) -> bool {\n *self < x && {\n *self = x;\n true\n }\n }\n}\n// ---------- end chmin, chmax ----------\n// ---------- begin enumerate prime ----------\nfn enumerate_prime(n: usize) -> Vec {\n assert!(n <= 10usize.pow(8));\n if n <= 1 {\n return vec![];\n }\n let batch = (n as f64).sqrt() as usize + 1;\n let mut is_prime = vec![true; batch + 1];\n for i in (2..).take_while(|p| p * p <= batch) {\n if is_prime[i] {\n let mut j = i * i;\n while let Some(p) = is_prime.get_mut(j) {\n *p = false;\n j += i;\n }\n }\n }\n let mut prime = vec![];\n let mut small_prime = vec![];\n for (i, p) in is_prime.iter().enumerate().skip(2) {\n if *p && i <= n {\n prime.push(i);\n small_prime.push(i);\n }\n }\n let mut l = batch;\n while l <= n {\n let r = std::cmp::min(l + batch, n + 1);\n is_prime.clear();\n is_prime.resize(r - l, true);\n for &p in small_prime.iter() {\n let mut j = (l + p - 1) / p * p - l;\n while let Some(is_prime) = is_prime.get_mut(j) {\n *is_prime = false;\n j += p;\n }\n }\n for (i, p) in is_prime.iter().enumerate().filter(|p| *p.1) {\n if *p {\n prime.push(i + l);\n }\n }\n l += batch;\n }\n prime\n}\n// ---------- end enumerate prime ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n }\n let p = enumerate_prime(n);\n let mut dp = (0..=n).collect::>();\n for &p in p.iter() {\n for i in 2..=(n / p) {\n dp[i * p].chmin((i - 1) * p + 1);\n }\n }\n let mut ans = n;\n for &p in p.iter() {\n if n % p == 0 {\n let d = n / p;\n for i in ((d - 1) * p + 1)..=n {\n ans.chmin(dp[i]);\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "87d650adbdde3035d3b991b772e9eb71", "src_uid": "43ff6a223c68551eff793ba170110438", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\nuse std::cmp;\n\nfn largest_prime_factor(mut n: u32) -> u32 {\n let mut k = 2;\n let mut last_factor = 1;\n while k*k <= n {\n while n % k == 0 {\n n = n / k;\n last_factor = k;\n }\n k += 1;\n }\n if n > 1 { n } else { last_factor }\n}\n\nfn candidate(n: u32) -> u32 {\n let p = largest_prime_factor(n);\n if p == n {\n n\n } else {\n n - p + 1\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let line = stdin.lock().lines().next().unwrap().unwrap();\n let n: u32 = line.parse().unwrap();\n let low = candidate(n);\n let mut ans = low;\n for i in low..n+1 {\n ans = cmp::min(ans, candidate(i));\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "15c91655607b845bfaf21bcc9beba413", "src_uid": "43ff6a223c68551eff793ba170110438", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nuse std::cmp::*;\n\nfn run() {\n input! {\n seed: (i64, i64),\n a: (i64, i64),\n b: (i64, i64),\n s: (i64, i64),\n t: i64,\n }\n let mut p = vec![];\n let mut state = seed;\n while state.0 <= s.0 + t && state.1 <= s.1 + t {\n p.push(state);\n state = (a.0 * state.0 + b.0, a.1 * state.1 + b.1);\n }\n let n = p.len();\n let dis = |a: (i64, i64), b: (i64, i64)| -> i64 {\n (a.0 - b.0).abs() + (a.1 - b.1).abs()\n };\n let mut ans = 0;\n for i in 0..n {\n let mut cnt = 0;\n let mut now = s;\n let mut next = i;\n let mut rem = t;\n while next < n && dis(now, p[next]) <= rem {\n rem -= dis(now, p[next]);\n now = p[next];\n next += 1;\n cnt += 1;\n }\n ans = max(ans, cnt);\n }\n for i in (0..n).rev() {\n let mut cnt = 0;\n let mut now = s;\n let mut next = i;\n let mut rem = t;\n while next < n && dis(now, p[next]) <= rem {\n rem -= dis(now, p[next]);\n now = p[next];\n next -= 1;\n cnt += 1;\n }\n ans = max(ans, cnt);\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "implementation", "greedy", "geometry"], "code_uid": "c3b859490091bed32b2c06074763741e", "src_uid": "d8a7ae2959b3781a8a4566a2f75a4e28", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1293/problem/D\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::io::Write;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n// Input macros.\n// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_line {\n ($t:tt) => {\n {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim_right().parse::<$t>().unwrap()\n }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\n// ===\n\nconst MAX_CORD: i128 = 1e18 as i128;\n\nfn solve(mut limit: i128, start: usize, p1: usize, p2: usize, p3: usize, cost: &Vec>) -> i32 {\n if limit < 0 {\n return -10000;\n }\n let mut count = 1;\n let mut now = start;\n while now != p1 {\n let t = ifv!(now < p1, now+1, now-1);\n if limit < cost[now][t] {\n return count;\n }\n count += 1;\n limit -= cost[now][t];\n now = t;\n }\n assert_eq!(now, p1);\n assert_ne!(now, p2);\n if limit < cost[now][p2] {\n return count;\n }\n limit -= cost[now][p2];\n count += 1;\n now = p2;\n\n while now != p3 {\n let t = ifv!(now < p3, now+1, now-1);\n if limit < cost[now][t] {\n return count;\n }\n count += 1;\n limit -= cost[now][t];\n now = t;\n }\n count\n}\n\nfn main() {\n input! {\n x0: i128, y0: i128, ax: i128, ay: i128, bx: i128, by: i128,\n sx: i128, sy: i128, limit: i128\n };\n\n let mut points = vec![(x0, y0)];\n loop {\n let (lx, ly) = *points.last().unwrap();\n if lx > MAX_CORD || ly > MAX_CORD {\n break;\n }\n points.push((lx*ax+bx, ly*ay+by));\n }\n let n = points.len();\n\n let mut first_cost = vec![];\n for i in 0..n {\n first_cost.push((sx-points[i].0).abs() + (sy-points[i].1).abs());\n }\n let mut pp_cost = dvec!(0; n, n);\n for i in 0..n {\n for j in 0..n {\n pp_cost[i][j] = (points[i].0-points[j].0).abs() + (points[i].1-points[j].1).abs();\n }\n }\n\n // debug!(points);\n // debug!(first_cost);\n\n assert!(n >= 2);\n\n let mut best = 0;\n for s in 0..n {\n if s < n-1 {\n for l in 0..=s {\n best = max(best, solve(limit - first_cost[s], s, l, s+1, n-1, &pp_cost));\n }\n }\n if s >= 1 {\n for l in s..n {\n best = max(best, solve(limit - first_cost[s], s, l, s-1, 0, &pp_cost));\n }\n }\n }\n\n println!(\"{}\", best);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "implementation"], "code_uid": "6e408abd2ad9ff2c3e76f30806c97de1", "src_uid": "d8a7ae2959b3781a8a4566a2f75a4e28", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unknown_lints)]\n#![allow(unused_imports, unused_macros, non_snake_case, bare_trait_objects)]\n#![allow(renamed_and_removed_lints, redundant_field_names)]\nuse std::cmp::Ordering::{self, Greater, Less};\nuse std::cmp::{max, min};\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\nuse std::error::Error;\nuse std::io::{self, BufReader, BufWriter, Read, Write};\nuse text_scanner::{scan, scan_iter, scanln, scanln_iter};\nuse utils::adj4_iter;\n\nfn cost((x0, y0): (i64, i64), (x1, y1): (i64, i64)) -> i64 {\n (x0 - x1).abs() + (y0 - y1).abs()\n}\n\nfn run() {\n // WARNING: usize is 32bit!\n let x0: i64 = scan();\n let y0: i64 = scan();\n let ax: i64 = scan();\n let ay: i64 = scan();\n let bx: i64 = scan();\n let by: i64 = scan();\n let xs: i64 = scan();\n let ys: i64 = scan();\n let t: i64 = scan();\n\n let limit = 2_000_000_000_000_000_0;\n assert!(limit * 100 > 0);\n let mut cur_x = x0;\n let mut cur_y = y0;\n let mut vertexes = Vec::new();\n loop {\n vertexes.push((cur_x, cur_y));\n cur_x = cur_x * ax + bx;\n cur_y = cur_y * ay + by;\n if cur_x > limit || cur_y > limit {\n break;\n }\n }\n\n let n = vertexes.len();\n let mut ans = 0;\n for _ in 0..2 {\n for c in 0..n {\n let mut cost_a = 0;\n let mut get_a = 0;\n for a in (0..c + 1).rev() {\n let from = if a == c { (xs, ys) } else { vertexes[a + 1] };\n let to = vertexes[a];\n cost_a += cost(from, to);\n if cost_a > t {\n break;\n }\n get_a += 1;\n\n ans.set_max(get_a);\n\n let mut cost_b = 0;\n let mut get_b = 0;\n for b in c + 1..n {\n let from = if b == c + 1 {\n vertexes[a]\n } else {\n vertexes[b - 1]\n };\n let to = vertexes[b];\n cost_b += cost(from, to);\n if cost_b + cost_a > t {\n break;\n }\n get_b += 1;\n ans.set_max(get_a + get_b);\n }\n }\n }\n vertexes.reverse();\n }\n\n println!(\"{}\", ans);\n}\n\nfn main() {\n std::thread::Builder::new()\n .name(\"run\".to_string())\n .stack_size(256 * 1024 * 1024)\n .spawn(run)\n .unwrap()\n .join()\n .unwrap()\n}\n\n//{{{ utils\npub mod utils {\n static DY: [isize; 8] = [0, 1, 0, -1, 1, -1, 1, -1];\n static DX: [isize; 8] = [1, 0, -1, 0, 1, 1, -1, -1];\n\n fn try_adj(\n y: usize,\n x: usize,\n dy: isize,\n dx: isize,\n h: usize,\n w: usize,\n ) -> Option<(usize, usize)> {\n let ny = y as isize + dy;\n let nx = x as isize + dx;\n if ny >= 0 && nx >= 0 {\n let ny = ny as usize;\n let nx = nx as usize;\n if ny < h && nx < w {\n Some((ny, nx))\n } else {\n None\n }\n } else {\n None\n }\n }\n\n pub struct Adj4 {\n y: usize,\n x: usize,\n h: usize,\n w: usize,\n r: usize,\n }\n\n impl Iterator for Adj4 {\n type Item = (usize, usize);\n\n fn next(&mut self) -> Option {\n loop {\n if self.r >= 4 {\n return None;\n }\n\n let dy = DY[self.r];\n let dx = DX[self.r];\n self.r += 1;\n\n if let Some((ny, nx)) = try_adj(self.y, self.x, dy, dx, self.h, self.w) {\n return Some((ny, nx));\n }\n }\n }\n }\n\n pub fn adj4_iter(y: usize, x: usize, h: usize, w: usize) -> Adj4 {\n Adj4 {\n y: y,\n x: x,\n h: h,\n w: w,\n r: 0,\n }\n }\n}\npub mod text_scanner {\n use std;\n #[derive(Debug)]\n pub enum Error {\n IoError(std::io::Error),\n EncodingError(std::string::FromUtf8Error),\n ParseError(String),\n Eof,\n }\n\n impl std::fmt::Display for Error {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n match *self {\n Error::IoError(ref e) => writeln!(f, \"IO Error: {}\", e),\n Error::EncodingError(ref e) => writeln!(f, \"Encoding Error: {}\", e),\n Error::ParseError(ref e) => writeln!(f, \"Parse Error: {}\", e),\n Error::Eof => writeln!(f, \"EOF\"),\n }\n }\n }\n\n impl std::error::Error for Error {\n // dummy implementation for 1.15.1\n fn description(&self) -> &str {\n \"description() is deprecated; use Display\"\n }\n }\n\n pub fn read_line() -> Option {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n fread_line(&mut stdin).expect(\"IO error\")\n }\n\n pub fn scan() -> T {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n fscan(&mut stdin).expect(\"IO error\")\n }\n\n pub fn scanln() -> T {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n fscanln(&mut stdin).expect(\"IO error\")\n }\n\n pub fn scan_iter() -> ScanIter {\n ScanIter {\n item_type: std::marker::PhantomData,\n }\n }\n\n pub fn scanln_iter() -> ScanlnIter {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n let s = fread_line(&mut stdin)\n .expect(\"IO error\")\n .unwrap_or_else(String::new);\n ScanlnIter {\n cursor: std::io::Cursor::new(s),\n item_type: std::marker::PhantomData,\n }\n }\n\n pub fn fread_line(r: &mut R) -> Result, std::io::Error> {\n let mut buf = String::new();\n let length = r.read_line(&mut buf)?;\n if let Some('\\n') = buf.chars().last() {\n buf.pop();\n }\n if let Some('\\r') = buf.chars().last() {\n buf.pop();\n }\n if length == 0 {\n Ok(None)\n } else {\n Ok(Some(buf))\n }\n }\n\n pub fn fscan(reader: &mut R) -> Result {\n let mut tokenizer = Tokenizer::new(reader);\n FromTokens::from_tokens(&mut tokenizer)\n }\n\n pub fn fscanln(reader: &mut R) -> Result {\n let s = match fread_line(reader) {\n Ok(Some(s)) => s,\n Ok(None) => return Err(Error::Eof),\n Err(e) => return Err(Error::IoError(e)),\n };\n let mut bytes = s.as_bytes();\n let mut tokenizer = Tokenizer::new(&mut bytes);\n FromTokens::from_tokens(&mut tokenizer)\n }\n\n pub fn fscan_iter(reader: &mut R) -> FscanIter {\n FscanIter {\n tokenizer: Tokenizer::new(reader),\n item_type: std::marker::PhantomData,\n }\n }\n\n pub fn fscanln_iter(\n reader: &mut R,\n ) -> Result, Error> {\n let s = match fread_line(reader) {\n Ok(Some(s)) => s,\n Ok(None) => \"\".to_string(),\n Err(e) => return Err(Error::IoError(e)),\n };\n Ok(ScanlnIter {\n cursor: std::io::Cursor::new(s),\n item_type: std::marker::PhantomData,\n })\n }\n\n pub struct ScanIter\n where\n T: FromTokens,\n {\n item_type: std::marker::PhantomData,\n }\n\n impl Iterator for ScanIter {\n type Item = T;\n\n fn next(&mut self) -> Option {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n let mut tokenizer = Tokenizer::new(&mut stdin);\n match FromTokens::from_tokens(&mut tokenizer) {\n Err(Error::Eof) => None,\n r => Some(r.expect(\"IO error\")),\n }\n }\n }\n\n pub struct FscanIter<'a, R, T>\n where\n R: std::io::Read + 'a,\n T: FromTokens,\n {\n tokenizer: Tokenizer<'a, R>,\n item_type: std::marker::PhantomData,\n }\n\n impl<'a, R: std::io::Read, T: FromTokens> Iterator for FscanIter<'a, R, T> {\n type Item = Result;\n\n fn next(&mut self) -> Option {\n match FromTokens::from_tokens(&mut self.tokenizer) {\n Err(Error::Eof) => None,\n r => Some(r),\n }\n }\n }\n\n pub struct ScanlnIter\n where\n T: FromTokens,\n {\n cursor: std::io::Cursor,\n item_type: std::marker::PhantomData,\n }\n\n impl<'a, T: FromTokens> Iterator for ScanlnIter {\n type Item = T;\n\n fn next(&mut self) -> Option {\n let mut tokenizer = Tokenizer::new(&mut self.cursor);\n match FromTokens::from_tokens(&mut tokenizer) {\n Err(Error::Eof) => None,\n r => Some(r.expect(\"IO error\")),\n }\n }\n }\n\n pub trait FromTokens\n where\n Self: Sized,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result;\n }\n\n macro_rules! from_tokens_primitives {\n ($($t:ty),*) => { $(\n impl FromTokens for $t {\n fn from_tokens(tokenizer: &mut Iterator>) -> Result {\n let token = tokenizer.next();\n match token {\n Some(s) => s?\n .parse::<$t>()\n .map_err(|e| Error::ParseError(format!(\"{}\", e))),\n None => Err(Error::Eof),\n }\n }\n }\n )* }\n}\n\n from_tokens_primitives! {\n String,\n bool,\n f32,\n f64,\n isize,\n i8,\n i16,\n i32,\n i64,\n usize,\n u8,\n u16,\n u32,\n u64\n }\n\n impl FromTokens for Vec {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok(String::from_tokens(tokenizer)?.chars().collect())\n }\n }\n\n impl FromTokens for (T1, T2)\n where\n T1: FromTokens,\n T2: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((T1::from_tokens(tokenizer)?, T2::from_tokens(tokenizer)?))\n }\n }\n\n impl FromTokens for (T1, T2, T3)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n ))\n }\n }\n\n impl FromTokens for (T1, T2, T3, T4)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n T4: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n T4::from_tokens(tokenizer)?,\n ))\n }\n }\n\n impl FromTokens for (T1, T2, T3, T4, T5)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n T4: FromTokens,\n T5: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n T4::from_tokens(tokenizer)?,\n T5::from_tokens(tokenizer)?,\n ))\n }\n }\n\n impl FromTokens for (T1, T2, T3, T4, T5, T6)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n T4: FromTokens,\n T5: FromTokens,\n T6: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n T4::from_tokens(tokenizer)?,\n T5::from_tokens(tokenizer)?,\n T6::from_tokens(tokenizer)?,\n ))\n }\n }\n\n struct Tokenizer<'a, R: std::io::Read + 'a> {\n reader: &'a mut R,\n }\n\n impl<'a, R: std::io::Read> Tokenizer<'a, R> {\n pub fn new(reader: &'a mut R) -> Self {\n Tokenizer { reader: reader }\n }\n\n pub fn next_token(&mut self) -> Result, Error> {\n use std::io::Read;\n let mut token = Vec::new();\n for b in self.reader.by_ref().bytes() {\n let b = b.map_err(Error::IoError)?;\n match (is_ascii_whitespace(b), token.is_empty()) {\n (false, _) => token.push(b),\n (true, false) => break,\n (true, true) => {}\n }\n }\n if token.is_empty() {\n return Ok(None);\n }\n String::from_utf8(token)\n .map(Some)\n .map_err(Error::EncodingError)\n }\n }\n\n impl<'a, R: std::io::Read> Iterator for Tokenizer<'a, R> {\n type Item = Result;\n fn next(&mut self) -> Option {\n match self.next_token() {\n Ok(Some(s)) => Some(Ok(s)),\n Ok(None) => None,\n Err(e) => Some(Err(e)),\n }\n }\n }\n\n fn is_ascii_whitespace(b: u8) -> bool {\n // Can use u8::is_ascii_whitespace once removing support of 1.15.1\n match b {\n b'\\t' | b'\\n' | b'\\x0C' | b'\\r' | b' ' => true,\n _ => false,\n }\n }\n}\n\npub trait SetMinMax {\n fn set_min(&mut self, v: Self) -> bool;\n fn set_max(&mut self, v: Self) -> bool;\n}\n\nimpl SetMinMax for T\nwhere\n T: PartialOrd,\n{\n fn set_min(&mut self, v: T) -> bool {\n *self > v && {\n *self = v;\n true\n }\n }\n fn set_max(&mut self, v: T) -> bool {\n *self < v && {\n *self = v;\n true\n }\n }\n}\n\n#[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]\npub struct Reverse(pub T);\n\nimpl PartialOrd for Reverse {\n #[inline]\n fn partial_cmp(&self, other: &Reverse) -> Option {\n other.0.partial_cmp(&self.0)\n }\n\n #[inline]\n fn lt(&self, other: &Self) -> bool {\n other.0 < self.0\n }\n #[inline]\n fn le(&self, other: &Self) -> bool {\n other.0 <= self.0\n }\n #[inline]\n fn ge(&self, other: &Self) -> bool {\n other.0 >= self.0\n }\n #[inline]\n fn gt(&self, other: &Self) -> bool {\n other.0 > self.0\n }\n}\n\nimpl Ord for Reverse {\n #[inline]\n fn cmp(&self, other: &Reverse) -> Ordering {\n other.0.cmp(&self.0)\n }\n}\n\n#[derive(PartialEq, PartialOrd, Debug, Copy, Clone, Default)]\npub struct Num(pub f64);\n\nimpl Eq for Num {}\n\nimpl Ord for Num {\n fn cmp(&self, other: &Num) -> Ordering {\n self.0\n .partial_cmp(&other.0)\n .expect(\"unexpected NaN when compare\")\n }\n}\n\n// See https://docs.rs/superslice/1.0.0/superslice/trait.Ext.html\npub trait SliceExt {\n type Item;\n\n fn lower_bound(&self, x: &Self::Item) -> usize\n where\n Self::Item: Ord;\n\n fn lower_bound_by<'a, F>(&'a self, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering;\n\n fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord;\n\n fn upper_bound(&self, x: &Self::Item) -> usize\n where\n Self::Item: Ord;\n\n fn upper_bound_by<'a, F>(&'a self, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering;\n\n fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord;\n}\n\nimpl SliceExt for [T] {\n type Item = T;\n\n fn lower_bound(&self, x: &Self::Item) -> usize\n where\n T: Ord,\n {\n self.lower_bound_by(|y| y.cmp(x))\n }\n\n fn lower_bound_by<'a, F>(&'a self, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering,\n {\n let s = self;\n let mut size = s.len();\n if size == 0 {\n return 0;\n }\n let mut base = 0usize;\n while size > 1 {\n let half = size / 2;\n let mid = base + half;\n let cmp = f(unsafe { s.get_unchecked(mid) });\n base = if cmp == Less { mid } else { base };\n size -= half;\n }\n let cmp = f(unsafe { s.get_unchecked(base) });\n base + (cmp == Less) as usize\n }\n\n fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord,\n {\n self.lower_bound_by(|e| f(e).cmp(k))\n }\n\n fn upper_bound(&self, x: &Self::Item) -> usize\n where\n T: Ord,\n {\n self.upper_bound_by(|y| y.cmp(x))\n }\n\n fn upper_bound_by<'a, F>(&'a self, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering,\n {\n let s = self;\n let mut size = s.len();\n if size == 0 {\n return 0;\n }\n let mut base = 0usize;\n while size > 1 {\n let half = size / 2;\n let mid = base + half;\n let cmp = f(unsafe { s.get_unchecked(mid) });\n base = if cmp == Greater { base } else { mid };\n size -= half;\n }\n let cmp = f(unsafe { s.get_unchecked(base) });\n base + (cmp != Greater) as usize\n }\n\n fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord,\n {\n self.upper_bound_by(|e| f(e).cmp(k))\n }\n}\n\n//}}}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "implementation", "greedy", "geometry"], "code_uid": "b995cfbc52b9dd2bea306073d11642ed", "src_uid": "d8a7ae2959b3781a8a4566a2f75a4e28", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let mut table = String::new();\n let mut hand = String::new();\n\n stdin.lock().read_line(&mut table).unwrap();\n stdin.lock().read_line(&mut hand).unwrap();\n\n let table = table.as_bytes();\n let hand = hand.trim().split(\" \");\n for card in hand {\n let card = card.as_bytes();\n if card[0] == table[0] || card[1] == table[1] {\n println!(\"YES\");\n return;\n }\n }\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "b3a9bac2a207bb960777239505800615", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead, BufWriter, StdinLock, Write};\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = stdin.lock();\n let mut out = BufWriter::new(stdout.lock());\n\n let table = scan.next();\n let hand = scan.next();\n\n writeln!(\n out,\n \"{}\",\n if {\n let bytes = table.as_bytes();\n hand.contains(bytes[0] as char) || hand.contains(bytes[1] as char)\n } {\n \"YES\"\n } else {\n \"NO\"\n }\n )\n .ok();\n}\n\ntrait Scan {\n fn next(&mut self) -> String;\n}\n\nimpl<'a> Scan for StdinLock<'a> {\n fn next(&mut self) -> String {\n let mut buf = String::with_capacity(15);\n self.read_line(&mut buf).unwrap();\n return buf;\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "80e1a8d081a4b57a71b7f8f2ef8b8c83", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut ti = String::new();\n io::stdin().read_line(&mut ti).unwrap();\n let mut hi = String::new();\n io::stdin().read_line(&mut hi).unwrap();\n\n\n let t = ti.as_bytes();\n let h: Vec<&str> = hi.split_terminator(\" \").collect();\n for i in 0..5 {\n let h = h[i].as_bytes();\n if (h[1] == t[1]) || (h[0] == t[0]) {\n println!(\"YES\");\n return;\n } \n }\n println!(\"NO\");\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "7ef9b8167effd0a96c05475dbcd0f496", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn can_play(table: &str, hand: Vec<&str>) -> &'static str {\n for card in hand.iter() {\n let mut table_chars = table.chars();\n let mut card_chars = card.chars();\n\n if table_chars.nth(0).unwrap() == card_chars.nth(0).unwrap()\n || table_chars.nth(0).unwrap() == card_chars.nth(0).unwrap()\n {\n return \"YES\";\n }\n }\n\n \"NO\"\n}\n\npub fn solution() -> io::Result<()> {\n let mut table = String::new();\n let mut hand = String::new();\n\n io::stdin().read_line(&mut table)?;\n io::stdin().read_line(&mut hand)?;\n let hand: Vec<&str> = hand.trim().split(\" \").collect();\n\n println!(\"{}\", can_play(&table, hand));\n Ok(())\n}\n\nfn main() {\n solution();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "be024e23aadc1b6036c53f651f76de1d", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut card_on_table = String::new();\n std::io::stdin().read_line(&mut card_on_table).expect(\"CARD_ON_TABLE::Read line failed!\");\n\n let mut cards_in_hand = String::new();\n std::io::stdin().read_line(&mut cards_in_hand).expect(\"CARDS_IN_HAND::Read line failed!\");\n\n let mut card = card_on_table.trim().chars();\n let suit = card.next().expect(\"SUIT::Not exist next char!\");\n let rank = card.next().expect(\"RANK::Not exist next char!\");\n\n let can_play = cards_in_hand.contains(suit) || cards_in_hand.contains(rank);\n\n match can_play {\n true => println!(\"YES\"),\n false => println!(\"NO\"),\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "7b664f44caba71f9f0a1b4764d8a92f3", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap,BTreeSet};\n#[allow(unused_imports)]\nuse std::ops::*;\n#[allow(unused_imports)]\nuse std::collections::BinaryHeap;\n\n#[allow(unused_macros)]\nmacro_rules! ite {\n ($c:expr, $t:expr, $f:expr) => {{\n if $c { $t } else { $f }\n }};\n}\n\n// ref: tanakh \n// diff: using Parser\n#[macro_export]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut parser = Parser::from_str($s);\n input_inner!{parser, $($r)*}\n };\n (parser = $parser:ident, $($r:tt)*) => {\n input_inner!{$parser, $($r)*}\n };\n (new_stdin_parser = $parser:ident, $($r:tt)*) => {\n let stdin = std::io::stdin();\n let reader = std::io::BufReader::new(stdin.lock());\n let mut $parser = Parser::new(reader);\n input_inner!{$parser, $($r)*}\n };\n ($($r:tt)*) => {\n input!{new_stdin_parser = parser, $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! input_inner {\n ($parser:ident) => {};\n ($parser:ident, ) => {};\n ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($parser, $t);\n input_inner!{$parser $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($parser:ident, ( $($t:tt),* )) => {\n ( $(read_value!($parser, $t)),* )\n };\n ($parser:ident, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($parser, $t)).collect::>()\n };\n ($parser:ident, chars) => {\n read_value!($parser, String).chars().collect::>()\n };\n ($parser:ident, usize1) => {\n read_value!($parser, usize) - 1\n };\n ($parser:ident, $t:ty) => {\n $parser.next::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n s: chars,\n ts: [chars; 5],\n }\n let mut res = false;\n for i in 0..5 {\n if s[0] == ts[i][0] || s[1] == ts[i][1] {\n res = true;\n }\n }\n println!(\"{}\", ite!(res, \"YES\", \"NO\"));\n}\n\nuse std::io::BufRead;\nuse std::io;\nuse std::str;\n\n// ref: tatsuya6502 \n// ref: wariuni \n// diff: using std::io::BufRead::fill_buf()\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\n\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\n\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len,complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n (len, buf2[len-1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n }\n else {\n self.update_buf();\n }\n }\n }\n}\n\nuse std::fmt::Display;\n#[allow(dead_code)]\nfn write_vec(xs: &Vec) {\n if xs.len() == 0 {\n println!();\n return;\n }\n print!(\"{}\", xs[0]);\n for i in 1..xs.len() {\n print!(\" {}\", xs[i]);\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "c0c4c3ddbd6352c5da9e9f9e3a533293", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn get_line() -> io::Result {\n\tlet mut buffer = String::new();\n\tio::stdin().read_line(&mut buffer)?;\n\tOk(buffer)\n}\n\nfn main() {\n\tlet input = get_line().unwrap();\n\tlet card = input.trim().as_bytes();\n\tlet input = get_line().unwrap();\n\tlet hand: Vec<&[u8]> = input.split_whitespace().map(|s| s.as_bytes()).collect();\n\tlet mut play = \"NO\";\n\tfor i in 0..hand.len() {\n\t\tif card[0] == hand[i][0] || card[1] == hand[i][1] {\n\t\t\tplay = \"YES\";\n\t\t\tbreak;\n\t\t}\n\t}\n\tprint!(\"{}\", play);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "7943c47221f9f1f759e2c6bc9090c409", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut card = String::new();\n std::io::stdin().read_line(&mut card)\n .expect(\"Error input\");\n let card_chars: Vec = card.chars().collect();\n let mut hand = String::new();\n std::io::stdin().read_line(&mut hand)\n .expect(\"Error input\");\n let hand_chars: Vec> = hand.split(' ').map(|s| s.chars().collect()).collect();\n\n for c in hand_chars {\n if c[0] == card_chars[0] || c[1] == card_chars[1] {\n println!(\"YES\");\n std::process::exit(0);\n }\n }\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "be372629f9aa2839892d08371baeee6f", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn cost_to_one(n : u64, k : u64, a : u64, b : u64) -> u64 {\n let mut c = 0;\n let mut x = n;\n if k == 1 {\n c = (x - 1) * a; \n } else {\n loop {\n if x < 1 {\n panic!(\"x is less than 1!\");\n } else if x == 1 {\n break;\n } else if x < k {\n c = c + (a * (x - 1));\n x = 1;\n } else {\n let q = x / k;\n let r = x % k;\n let cost_div = b;\n let cost_sub = a * ((q * k) - q);\n if r == 0 {\n if cost_div <= cost_sub {\n c = c + cost_div;\n } else {\n c = c + cost_sub;\n }\n x = q;\n } else {\n c = c + (r * a);\n x = x - r;\n }\n }\n }\n }\n c\n}\n\nfn main() {\n let stdin = io::stdin();\n let n = read_t(&stdin);\n let k = read_t(&stdin);\n let a = read_t(&stdin);\n let b = read_t(&stdin);\n println!(\"{}\", cost_to_one(n, k, a, b));\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "aa490733c8ac1a7e6b08512a67a5fd88", "src_uid": "f838fae7c98bf51cfa0b9bd158650b10", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let n = getint();\n let k = getint();\n let a = getint();\n let b = getint();\n\n println!(\"{}\",find_min_cost(n,k,a,b,0));\n}\n\nfn getint() -> i64 {\n let mut inpstr = String::new();\n io::stdin().read_line(&mut inpstr).expect(\"Could not read integer\");\n let number = inpstr.trim().parse::();\n\n number.unwrap()\n\n}\n\n//Implements greedy algorithm, acc is the accumulator\nfn find_min_cost(n : i64, k: i64, a : i64, b : i64, acc: i64) -> i64 {\n let rem = n%k;\n\n if rem != 0 && n > k {\n return find_min_cost(n - rem, k, a, b, acc+ a*rem);\n }\n\n let quo = n/k;\n\n if quo > 0 && quo*a + b < n*a {\n return find_min_cost(quo, k, a, b, acc+ b);\n }\n\n (n-1)*a + acc\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "c2c34d0d517c66af6d34ce9f3b17397d", "src_uid": "f838fae7c98bf51cfa0b9bd158650b10", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros, dead_code)]\nuse std::f64::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! dump{\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nconst INF: i64 = 0x3f3f3f3f3f3f3f3f;\nconst MOD: i64 = 1000000007;\nconst NOTHING: usize = std::usize::MAX;\nconst DX: [usize; 4] = [1, 0, std::usize::MAX, 0];\nconst DY: [usize; 4] = [0, 1, 0, std::usize::MAX];\n\nfn main() {\n let mut n: i64 = readln();\n let k: i64 = readln();\n let a: i64 = readln();\n let b: i64 = readln();\n\n if k == 1 {\n println!(\"{}\", a * (n - 1));\n return;\n }\n\n let mut res: i64 = 0;\n while n >= k {\n let r = n % k;\n if r > 0 {\n res += a * r;\n n -= r;\n } else {\n res += min(a * (n - n / k), b);\n n /= k;\n }\n }\n res += a * (n - 1);\n\n println!(\"{}\", res);\n\n}\n\ntrait Read {\n fn read(s: &str) -> Self;\n}\n\nfn readln() -> T {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n T::read(buf.trim_right())\n}\n\nmacro_rules! read_impl{\n ($($t:ty)*) => ($(\n impl Read for $t {\n fn read(s: &str) -> $t{\n s.parse().unwrap()\n }\n }\n )*)\n}\nread_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }\n\nimpl Read for String {\n fn read(s: &str) -> Self {\n s.to_string()\n }\n}\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.chars().collect()\n }\n}\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.split_whitespace().map(T::read).collect()\n }\n}\n\nimpl Read for (A, B) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]))\n }\n}\n\nimpl Read for (A, B, C) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))\n }\n}\n\nimpl Read for (A, B, C, D) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]), D::read(tokens[3]))\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "11de65cf3fdd9daa9bf1c9ce11308b1c", "src_uid": "f838fae7c98bf51cfa0b9bd158650b10", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n#![allow(non_camel_case_types)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{max, min, Ordering};\nuse std::f64::consts::*;\nuse std::mem::{swap, size_of_val, size_of};\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\nuse std::num::*;\nuse std::process::*;\n//use std::ptr::*;\nuse std::iter::{once, repeat};\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\nstruct Input {\n\tbuffer: Buf,\n}\n\nimpl Input {\n\tfn read_char(&mut self) -> char {\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\tx[0] as char\n\t}\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n}\n\nmacro_rules! read {\n () => {};\n\t($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect(\"Parsing error\"));\n\t($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect(\"Parsing error\")),*));\n}\nfn gcd(mut a: T, mut b: T) -> T\n\twhere T: ShrAssign + BitAnd + Ord + From + Clone + SubAssign + ShlAssign + Copy\n{\n\tlet one = T::from(1);\n\tlet zero = T::from(0);\n\tlet mut ans = 0;\n\tif a < b {\n\t\tswap(&mut a, &mut b);\n\t}\n\twhile b > zero {\n\t\tif (a & one > zero) && (b & one > zero) {\n\t\t\ta -= b;\n\t\t} else if a & one > zero {\n\t\t\tb >>= one;\n\t\t} else if b & one > zero {\n\t\t\ta >>= one;\n\t\t} else {\n\t\t\tans += 1;\n\t\t\ta >>= one;\n\t\t\tb >>= one;\n\t\t}\n\t\tif a < b {\n\t\t\tswap(&mut a, &mut b);\n\t\t}\n\t}\n\ta <<= ans;\n\ta\n}\n\nfn powmod(mut base: X, mut exp: Y, mm: X) -> X\n\twhere X: Copy + Clone + Mul + Rem + From,\n\t Y: ShrAssign + Copy + Clone + BitAnd + From + Ord\n{\n\tlet mut res = X::from(1);\n\twhile exp > Y::from(0) {\n\t\tif exp & Y::from(1) > Y::from(0) {\n\t\t\tres = res * base % mm;\n\t\t}\n\t\tbase = base * base % mm;\n\t\texp >>= Y::from(1);\n\t}\n\tres\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\")) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet stdin = stdin();\n\t\t\tlet istr = stdin.lock();\n\t\t\tlet mut inf = Input { buffer: BufReader::new(istr) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output) {\n\tlet (mut n, k, a, b) = read!(inf,i64,i64,i64,i64);\n\tif k == 1 {\n\t\twriteln!(ouf, \"{}\", (n - 1) * a);\n\t\treturn;\n\t}\n\tlet mut ans = 0i64;\n\twhile n > 1 {\n\t\tif n < k {\n\t\t\tans += (n - 1) * a;\n\t\t\tbreak;\n\t\t}\n\t\tans += (n % k) * a;\n\t\tn -= n % k;\n\n\t\tans += min(b, (n - n / k) * a);\n\t\tn /= k;\n\t}\n\twriteln!(ouf, \"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "1c196f8b993e3e7986e0dac74d411812", "src_uid": "f838fae7c98bf51cfa0b9bd158650b10", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::prelude::*;\n use std::io;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let n: u64 = it.next().unwrap().parse().unwrap();\n let k: u64 = it.next().unwrap().parse().unwrap();\n let a: u64 = it.next().unwrap().parse().unwrap();\n let b: u64 = it.next().unwrap().parse().unwrap();\n\n if k == 1 {\n let ans = (n - 1) * a;\n println!(\"{}\", ans);\n return;\n }\n\n let mut x = n;\n\n let mut ans = 0;\n\n loop {\n let rem = x % k;\n if rem > 0 {\n x -= rem;\n ans += rem * a;\n } else {\n let q = x / k;\n let y = std::cmp::min((k - 1) * q * a, b);\n\n ans += y;\n x = q;\n }\n if x == 1 {\n println!(\"{}\", ans);\n break;\n } else if x == 0 {\n println!(\"{}\", ans - a);\n break;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "5d61c4b4c68215d60c1fa3468d3f88ae", "src_uid": "f838fae7c98bf51cfa0b9bd158650b10", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Formatter};\nuse std::io::*;\nuse std::ops::*;\nuse std::*;\n\n// -----------------------------------------------\n// Framework\n// -----------------------------------------------\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($t:ty) =>\n (rl().parse::<$t>().unwrap());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($arg:expr),*) => {\n #[cfg(debug_assertions)]\n {\n let entries = [$(&stringify!([$arg]:), &$arg as &Debug),*];\n stderr().write_fmt(format_args!(\"{:#?}\\n\", entries)).unwrap();\n }\n };\n}\n\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_owned()\n}\n\ntrait IteratorExt: Iterator + Sized {\n fn vec(self) -> Vec {\n self.collect()\n }\n}\n\nimpl IteratorExt for T {}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\npub fn main() {\n let n = read!(i64);\n let k = read!(i64);\n let A = read!(i64);\n let B = read!(i64);\n\n let mut x = n;\n let mut s = 0;\n if k == 1 {\n s = (x - 1) * A;\n } else {\n while x > 1 {\n if x < k {\n s += (x - 1) * A;\n break;\n }\n\n let r = x % k;\n if r != 0 {\n x -= r;\n s += r * A;\n continue;\n }\n\n let q = x / k;\n s += min((x - q) * A, B);\n x = q;\n }\n }\n\n println!(\"{}\", s);\n return;\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "47d5ad5b8d4308f24da9f451e2fe65b4", "src_uid": "f838fae7c98bf51cfa0b9bd158650b10", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const N: usize = 19;\n\nfn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let n: u64 = input.trim().parse().unwrap();\n\n let fact: Vec = std::iter::once(1).chain((1..N).scan(1, |state, x| {\n *state *= x as u64;\n Some(*state)\n })).collect();\n\n let mut dl = Vec::with_capacity(N);\n\n let mut t = n;\n while t > 0 {\n let r = t % 10;\n dl.push(r);\n t /= 10;\n }\n\n let mut ms = [0; 10];\n for d in dl {\n ms[d as usize] += 1;\n }\n\n let binc = |k: usize, n: usize| -> u64 {\n fact[n] / fact[k] / fact[n - k]\n };\n\n let cnt = |ms: &[usize; 10], c: usize, zc: usize| -> u64 {\n if c == 0 {\n 0\n } else {\n let mut ret_val = fact[c];\n for &c in &ms[1..] {\n ret_val /= fact[c];\n }\n ret_val *= binc(ms[0], c + zc - 1);\n ret_val\n }\n };\n\n let mut curc = 0;\n let mut curzc = 0;\n\n let first = {\n let mut t = [0; 10];\n if ms[0] > 0 {\n t[0] = 1;\n curzc += 1;\n }\n for (&c, t) in ms.iter().zip(t.iter_mut()).skip(1) {\n if c > 0 {\n *t = 1;\n curc += 1;\n }\n }\n t\n };\n\n let mut ans = 0;\n let mut cur = first;\n 'outer: loop {\n let c = cnt(&cur, curc, curzc);\n ans += c;\n for di in 0..10 {\n if cur[di] == ms[di] {\n if di == 9 {\n break 'outer;\n }\n if di == 0 {\n curzc -= cur[di] - first[di];\n } else {\n curc -= cur[di] - first[di];\n }\n cur[di] = first[di];\n } else {\n cur[di] += 1;\n if di == 0 {\n curzc += 1;\n } else {\n curc += 1;\n }\n break;\n }\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "combinatorics"], "code_uid": "76650f28715cdab6c699d697a4675d45", "src_uid": "7f4e533f49b73cc2b96b4c56847295f2", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 991E\nuse std::io;\n\nfn main() {\n let mut a = String::new();\n io::stdin().read_line(&mut a).unwrap();\n let a = a.trim();\n\n let mut counts = [0u64; 10];\n\n for c in a.chars() {\n counts[c.to_digit(10).unwrap() as usize] += 1;\n }\n\n let mut fa = [0u64; 30];\n\n let with_zero = count(&mut counts, 0, &mut fa);\n let mut correct = with_zero;\n if counts[0] > 0 {\n counts[0] -= 1;\n correct -= count(&mut counts, 0, &mut fa);\n if counts[0] > 0 {\n counts[0] = 0;\n correct -= count(&mut counts, 0, &mut fa);\n }\n }\n println!(\"{}\", correct);\n}\n\nfn factorial(n: u64, fa: &mut [u64]) -> u64 {\n if n == 0 {\n fa[n as usize] = 1;\n } else if fa[n as usize] == 0 {\n fa[n as usize] = factorial(n - 1, fa) * n;\n }\n return fa[n as usize];\n}\n\nfn count(counts: &mut [u64], change_here: usize, fa: &mut [u64]) -> u64 {\n if change_here == 10 {\n // All numbers are fixed now\n let numerator = factorial(counts.iter().sum(), fa);\n let mut denominator = 1;\n for c in counts {\n denominator *= factorial(*c, fa);\n }\n return numerator / denominator;\n }\n\n if counts[change_here] == 0 {\n return count(counts, change_here + 1, fa);\n }\n\n let mut add = 0;\n for i in 1..(counts[change_here] + 1) {\n counts[change_here] = i;\n add += count(counts, change_here + 1, fa);\n }\n return add;\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "combinatorics"], "code_uid": "83cb93d797197000432edca993e1e1fc", "src_uid": "7f4e533f49b73cc2b96b4c56847295f2", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::stdin;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nuse std::collections::HashMap;\nuse std::cmp::min;\n\nfn main() {\n let mut scan = Scanner::default();\n let n: usize = scan.next();\n let k: usize = scan.next();\n let a: Vec = (0..n).map(|_| scan.next::()).collect();\n let mut to_reach: HashMap> = HashMap::new();\n for x in &a {\n let mut y = x.clone();\n let mut div = 0;\n while y > 0 {\n if !to_reach.contains_key(&y) {\n to_reach.insert(y.clone(), vec![]);\n }\n let v: &mut Vec = to_reach.get_mut(&y).unwrap();\n v.push(div);\n y /= 2;\n div += 1;\n }\n }\n let mut ans = std::u64::MAX;\n for v in to_reach.values_mut() {\n if v.len() < k {\n continue;\n }\n v.sort();\n ans = min(ans, v[0..k].iter().sum::());\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "261f265668626c3f9f61bcf26c64c10f", "src_uid": "ed1a2ae733121af6486568e528fe2d84", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nuse std::hash::Hash;\nfn inc(map:&mut BTreeMap, key:T) {\n let count = map.entry(key).or_insert(0);\n *count += 1;\n}\n\nfn digit(ch: char) -> i64 {\n return (ch as u8 - b'0') as i64\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nfn gcd(x:i64, y:i64) -> i64 {\n if y==0 { return x; }\n gcd(y, x%y)\n}\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let k:usize = read();\n let a:Vec = (0..n).map(|_| read()).collect();\n\n let mut map = HashMap::new();\n for i in 0..n {\n let mut b = a[i];\n let mut j = 0;\n while b != 0 {\n let v = map.entry(b).or_insert(vec![]);\n v.push(j);\n j += 1;\n b /= 2;\n }\n }\n //debug!(map);\n\n let mut ans = INF;\n\n for (_,v) in &mut map {\n v.sort();\n if v.len() < k { continue; }\n let mut cnt = 0;\n for i in 0..k {\n cnt += v[i];\n }\n ans = min(ans,cnt);\n }\n\n println!(\"{}\", ans);\n\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "0cbf14b3e5892dc83b0f3fb349907224", "src_uid": "ed1a2ae733121af6486568e528fe2d84", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n k: usize,\n a: [usize; n],\n }\n let m = 200_000;\n let mut cnt = vec![0; m + 1];\n for &a in a.iter() {\n cnt[a] += 1;\n }\n let mut ans = 20 * n;\n let mut s = vec![vec![]; m + 1];\n let mut sum = vec![0; m + 1];\n for i in (0..=m).rev() {\n for _ in 0..cnt[i] {\n s[i].push(0);\n }\n s[i].sort();\n while s[i].len() > k {\n if let Some(v) = s[i].pop() {\n sum[i] -= v;\n }\n }\n if s[i].len() >= k {\n ans = std::cmp::min(ans, sum[i]);\n }\n if i > 0 {\n while let Some(v) = s[i].pop() {\n s[i / 2].push(v + 1);\n sum[i / 2] += v + 1;\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "55f8fc865d26b7be500d5d030c90af5b", "src_uid": "ed1a2ae733121af6486568e528fe2d84", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n#[allow(unused_imports)]\nuse std::io::{stdout, stdin, BufWriter, Write};\n\nfn main() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n\n input!{\n n: usize,\n k: usize,\n mut aa: [u64; n],\n }\n aa.sort();\n let mut m: u64 = *aa.iter().max().unwrap();\n let mut ans: u64 = 1 << 60;\n for t in 0..m+1 {\n let mut temp = 0;\n let mut ok = 0;\n\n for i in 0..n {\n let mut a = aa[i];\n let mut cnt = 0;\n if a < t {\n continue;\n }\n\n while a > t {\n a/=2;\n cnt += 1;\n }\n if t == a {\n temp += cnt;\n ok += 1;\n if ok == k {\n break;\n }\n }\n }\n\n if ok == k {\n ans = min(ans, temp);\n }\n }\n puts!(\"{}\\n\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "c34dd3aefe4ae7aad73a356c0281086a", "src_uid": "ed1a2ae733121af6486568e528fe2d84", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io;\n\nfn lvl(mut x: i32) -> i8 {\n let mut res: i8 = 0;\n\n while x > 1 {\n res += 1;\n x >>= 1;\n }\n\n res\n}\n\nfn main() {\n let mut inp = String::new();\n io::stdin().read_line(&mut inp).unwrap();\n let line: Vec = inp\n .split_whitespace()\n .map(|x| x.trim().parse().unwrap())\n .collect();\n let (_n, k) = (line[0], line[1]);\n\n inp.clear();\n io::stdin().read_line(&mut inp).unwrap();\n\n let mut input: Vec<(i32, i8, i8)> = inp\n .split_whitespace()\n .map(|x| {\n let xx = x.trim().parse::().unwrap();\n (xx, lvl(xx), 0)\n })\n .collect();\n\n let mut min_steps: i32 = std::i32::MAX;\n loop {\n input.sort_unstable_by(|a, b| b.1.partial_cmp(&a.1).unwrap());\n\n //\n let mut eq_map: HashMap = HashMap::new();\n\n // count equal\n input\n .iter()\n .for_each(|x| *eq_map.entry(x.0).or_insert(0) += 1);\n\n eq_map.keys().for_each(|key| {\n if *eq_map.get(key).unwrap() >= k {\n // push equal to separate vector\n let mut eq_vec: Vec = input\n .iter()\n .filter(|x| &x.0 == key)\n .map(|x| x.2 as i32)\n .collect();\n\n // sort vector\n eq_vec.sort_unstable();\n // take(k).sum()\n min_steps = std::cmp::min(min_steps, eq_vec.iter().take(k as usize).sum());\n }\n });\n\n // all on first level\n if input.iter().all(|x| x.1 == 0) {\n break;\n }\n\n //println!(\"steps: {}; lvls: {:?}\", min_steps, input);\n\n let mut f: &mut (i32, i8, i8) = &mut input[0];\n\n f.0 >>= 1;\n f.1 -= 1;\n f.2 += 1;\n }\n\n //println!(\"lvls: {:?}\", input);\n print!(\"{}\", min_steps);\n //println!(\"steps: {}\", min_steps);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "5094652c7f602bf2ca161c9437c22f9c", "src_uid": "ed1a2ae733121af6486568e528fe2d84", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\nuse std::ops::*;\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]\nstruct Clock {\n time: i32,\n}\n\nimpl Clock {\n pub fn new (hh: i32, mm: i32) -> Self {\n Self {\n time: Clock::hhmm_to_time(hh, mm)\n }\n }\n pub fn hh(&self) -> i32 {\n self.time / 60\n }\n pub fn mm(&self) -> i32 {\n self.time % 60\n }\n fn hhmm_to_time(hh: i32, mm: i32) -> i32 {\n hh * 60 + mm\n }\n fn time_to_hhmm(t: i32) -> (i32, i32) {\n (t / 60, t % 60)\n }\n}\n\nimpl Sub for Clock {\n type Output = Clock;\n fn sub(mut self, m: i32) -> Clock {\n let day = 24 * 60;\n let m = m % day;\n self.time = (self.time + day - m) % day;\n self\n }\n}\n\nfn find_lucky(c: &Clock) -> bool {\n if c.hh() / 10 == 7 || c.hh() % 10 == 7 || c.mm() / 10 == 7 || c.mm() % 10 == 7 {\n true\n } else {\n false\n }\n}\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Can't read input\");\n let x: i32 = input.trim().parse().expect(\"Can't parse input\");\n input.clear();\n stdin().read_line(&mut input).expect(\"Cant' read input\");\n let mut hm = input.split_whitespace().map(|s| s.parse().expect(\"Can't parse intput\"));\n let hh: i32 = hm.next().unwrap();\n let mm = hm.next().unwrap();\n let mut c = Clock::new(hh, mm);\n let mut n = 0;\n loop {\n if find_lucky(&c) {\n println!(\"{}\", n);\n break;\n }\n c = c - x;\n n += 1;\n }\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "7e329c16a9b1f9be06b7099f4fa57afb", "src_uid": "5ecd569e02e0164a5da9ff549fca3ceb", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n\nfn luckey(h: usize, m: usize) -> bool {\n m % 10 == 7 || h % 10 == 7\n}\n\nfn main() {\n let x = get!(usize);\n let (mut h, mut m) = get!(usize, usize);\n\n let mut ans = 0;\n while !luckey(h, m) {\n let mut subh = false;\n if x > m {\n subh = true;\n m = m + 60 - x;\n } else {\n m -= x;\n }\n\n if subh {\n if h == 0 {\n h = 23;\n } else {\n h -= 1;\n }\n }\n\n ans += 1;\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "6ea8781c699ce2a84c4c028e6bf5bc5a", "src_uid": "5ecd569e02e0164a5da9ff549fca3ceb", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n#![allow(unused_imports)]\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::str::FromStr;\nuse std::collections::{VecDeque, HashMap};\nuse std::ops::Sub;\n\nfn main() {\n let stdin = io::stdin();\n let mut input = stdin.lock();\n let mut line = String::new();\n input.read_line(&mut line).unwrap();\n let x = get_numbers(&line)[0];\n line.clear(); input.read_line(&mut line).unwrap();\n let nums = get_numbers(&line);\n\n let get_up = Time::new(nums[0], nums[1]);\n\n let mut snoozed = 0;\n let mut cur_time = get_up;\n while cur_time.lucky() == false {\n cur_time = cur_time - x;\n snoozed += 1;\n //println!(\"{} -> {}:{}\", snoozed, cur_time.hh, cur_time.mm);\n }\n\n println!(\"{}\", snoozed);\n}\n\n#[derive(Debug, Clone, Copy)]\nstruct Time {\n hh: u8,\n mm: u8,\n}\n\nimpl Time {\n fn new(hour: u8, min: u8) -> Time {\n Time {\n hh: hour,\n mm: min,\n }\n }\n\n fn lucky(&self) -> bool {\n // 7 cannot be appear in the 10s spot so we only have to check ones\n self.mm % 10 == 7 || self.hh % 10 == 7\n }\n}\n\nimpl Sub for Time {\n type Output = Time;\n\n fn sub(self, mins: u8) -> Time {\n if mins <= self.mm {\n Time { hh: self.hh, mm: self.mm - mins }\n } else if self.hh >= 1 {\n Time { hh: self.hh - 1, mm: self.mm + 60 - mins }\n } else {\n // going back a day\n Time { hh: 23, mm: self.mm + 60 - mins }\n }\n }\n}\n\n/*\n * Utility Functions\n */\n\n// get numbers from line seperated by spaces\nfn get_numbers(line: &str) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n line.split_whitespace()\n .map(|chunk| chunk.parse::().expect(\"failed to parse\"))\n .collect()\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "3fa5aaba0fd5386bcd6a7dba36df2f3e", "src_uid": "5ecd569e02e0164a5da9ff549fca3ceb", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufReader, stdin};\n\nfn main() {\n let mut reader = stdin();\n let mut s = String::new();\n reader.read_line(&mut s).unwrap();\n let N = s.trim_right().parse::().unwrap();\n s.clear();\n reader.read_line(&mut s).unwrap();\n let A = s.trim_right().parse::().unwrap();\n s.clear();\n reader.read_line(&mut s).unwrap();\n let B = s.trim_right().parse::().unwrap();\n s.clear();\n reader.read_line(&mut s).unwrap();\n let C = s.trim_right().parse::().unwrap();\n\n let mut ans = 0;\n let mut loc = 0;\n for x in 1..N {\n if loc == 0 { // rabbit\n if A > B {\n ans = ans + B;\n loc = 2;\n } else {\n ans = ans + A;\n loc = 1;\n }\n } else if loc == 1 { // owl\n if A > C {\n ans = ans + C;\n loc = 2;\n } else {\n ans = ans + A;\n loc = 0;\n }\n } else { // eeyore\n if B > C {\n ans = ans + C;\n loc = 1;\n } else {\n ans = ans + B;\n loc = 0;\n }\n }\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "9450ee7cc3d4e30f696946a5f63d0ed1", "src_uid": "6058529f0144c853e9e17ed7c661fc50", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::io::prelude::*;\nuse std::iter::*;\nuse std::str::SplitWhitespace;\nuse std::cmp::min;\n\nfn main() {\n let mut input = InRead::new();\n let n = input.int();\n let a = input.int();\n let b = input.int();\n let c = input.int();\n let x = min(a, b);\n let res = if n == 1 { 0 } else { x + min(x, c) * (n - 2) };\n println!(\"{}\", res);\n}\n\nstruct InRead(String);\n\nimpl InRead {\n fn new() -> InRead {\n InRead(String::new())\n }\n fn get_line(self: &mut Self) {\n self.0.clear();\n stdin().read_line(&mut self.0);\n }\n fn parse_int(s: &str) -> i32 { s.parse().unwrap() }\n fn ints(self: &mut Self) -> Map i32> {\n self.get_line();\n self.0.split_whitespace().map(InRead::parse_int)\n }\n fn int_vec(self: &mut Self) -> Vec { self.ints().collect() }\n fn int(self: &mut Self) -> i32 { self.ints().next().unwrap() }\n}\n\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "4a181347971978f6c5455763f89a258a", "src_uid": "6058529f0144c853e9e17ed7c661fc50", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nconst N: i64 = 998_244_353;\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let n: usize = get_line().trim().parse().unwrap();\n let a: usize = get_line().trim().parse().unwrap();\n let b: usize = get_line().trim().parse().unwrap();\n let c: usize = get_line().trim().parse().unwrap();\n\n let min_d = min(min(a,b), c);\n\n let ans = match n {\n 1 => 0,\n _ => min(a, b) + (n - 2) * min_d,\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "40dd804580503b127bc7adcd364047d7", "src_uid": "6058529f0144c853e9e17ed7c661fc50", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_int() -> u64 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n let x = input.trim().parse::().unwrap();\n x\n}\n\nfn main(){\n let n = read_int();\n let a = read_int();\n let b = read_int();\n let c = read_int();\n\n let mut location = \"R\";\n let mut dist = 0;\n let mut meals = 1;\n while meals < n{\n let trip = match location {\n \"R\" => {\n if a < b{\n location = \"O\";\n a\n }else{\n location = \"E\";\n b\n }\n },\n \"E\" => {\n if c < b{\n location = \"O\";\n c\n }else{\n location = \"R\";\n b\n }\n },\n \"O\" => {\n if a < c{\n location = \"R\";\n a\n }else{\n location = \"E\";\n c\n }\n },\n _ => {break},\n };\n meals = meals + 1;\n dist = dist + trip;\n }\n println!(\"{}\", dist);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "e09578e46c736c4861badadc082963c4", "src_uid": "6058529f0144c853e9e17ed7c661fc50", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_int() -> u64 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n let x = input.trim().parse::().unwrap();\n input.clear();\n x\n}\n\nfn main(){\n let n = read_int();\n let a = read_int();\n let b = read_int();\n let c = read_int();\n\n let mut location = 0;\n let mut dist = 0;\n let mut meals = 1;\n while meals < n{\n let trip = match location {\n 0 => { // rabbit\n if a < b{\n location = 2;\n a\n }else{\n location = 1;\n b\n }\n },\n 1 => { // eeyore\n if c < b{\n location = 2;\n c\n }else{\n location = 0;\n b\n }\n },\n 2 => { // owl\n if a < c{\n location = 0;\n a\n }else{\n location = 1;\n c\n }\n },\n _ => {break},\n };\n meals = meals + 1;\n dist = dist + trip;\n }\n println!(\"{}\", dist);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "24754d020cf255acb81eeeed2602bae0", "src_uid": "6058529f0144c853e9e17ed7c661fc50", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n x: i64,\n y: i64,\n z: i64,\n }\n let mut ans = 2 * z;\n let v = std::cmp::min(x, y);\n ans += 2 * v;\n if x > v {\n ans += 1;\n }\n if y > v {\n ans += 1;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "2ca44ed6816f30284d6f817cdc1156ae", "src_uid": "609f131325c13213aedcf8d55fc3ed77", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"input: read line failed\");\n let vec = input.trim().split_whitespace().map(|item| {\n item.parse::().expect(\"item: parse to usize failed\")\n }).collect::>();\n\n let (a_amount, b_amount, ab_amount) = (vec[0], vec[1], vec[2]);\n\n let length = 2 * ab_amount\n + 2 * min(a_amount, b_amount)\n + if max(a_amount, b_amount) - min(a_amount, b_amount) > 0 { 1 } else { 0 };\n println!(\"{}\", length);\n\n}\n\nfn min(one: usize, another: usize) -> usize {\n if one < another { one } else { another }\n}\n\nfn max(one: usize, another: usize) -> usize {\n if one > another { one } else { another }\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "231cfa9f232fce7757ec0996a579e0e5", "src_uid": "609f131325c13213aedcf8d55fc3ed77", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\nuse std::fs::File;\nuse std::io::Read;\n\n// fn pow_speedt_with_mod(mut p: i64, mut q: i64, m: i64) -> i64 {\n// p %= m;\n// let mut r = p;\n// let mut ret: i64 = 1;\n// while q > 0 {\n// ret *= if q % 2 == 1 {r} else {1};\n// r *= r;\n// r %= m;\n// q /= 2;\n// ret %= m;\n// }\n// return ret;\n// }\n\nfn main() {\n let inputstatus = 1;\n\n let mut buf = String::new();\n let filename = \"inputrust.txt\";\n\n if inputstatus == 0 {\n let mut f = File::open(filename).expect(\"file not found\");\n f.read_to_string(&mut buf)\n .expect(\"something went wrong reading the file\");\n } else {\n std::io::stdin().read_to_string(&mut buf).unwrap();\n }\n\n let mut iter = buf.split_whitespace();\n let a: i64 = iter.next().unwrap().parse().unwrap();\n let b: i64 = iter.next().unwrap().parse().unwrap();\n let c: i64 = iter.next().unwrap().parse().unwrap();\n\n let ans = if a == b {\n a + b + 2 * c\n } else {\n 2 * cmp::min(a, b) + 1 + 2 * c\n };\n\n println!(\"{}\", ans);\n\n\n // if p + 1 >= m\n\n // println!(\"{}\", n);\n // println!(\"{}\", k);\n // println!(\"{:?}\", num);\n // println!(\"{:?}\", cum_num);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "8af0d4618d886805b7dbdc5357a4969a", "src_uid": "609f131325c13213aedcf8d55fc3ed77", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n return (a, 1, 0);\n }\n let (g, x1, y1) = egcd(b, a % b);\n (g, y1, x1 - (a / b) * y1)\n}\n\nfn ceil_div(num: i64, denom: i64) -> i64 {\n (num + denom - 1).div_euclid(denom)\n}\n\n// Check if the diophantine equation a * x + b * y = c has non-negative solutions.\nfn solve(scan: &mut Scanner, out: &mut W) {\n let a: i64 = scan.token();\n let b: i64 = scan.token();\n let c: i64 = scan.token();\n let (g, xg, yg) = egcd(a, b);\n if c % g == 0 {\n let x0 = xg * c / g;\n let y0 = yg * c / g;\n // xk = x0 + k * b / g\n // yk = y0 - k * a / g\n // xk >= 0 and yk >= 0\n // After solving for k:\n let ans = (y0 * g).div_euclid(a) - ceil_div(-x0 * g, b) + 1;\n if ans > 0 {\n writeln!(out, \"Yes\").ok();\n } else {\n writeln!(out, \"No\").ok();\n }\n } else {\n writeln!(out, \"No\").ok();\n }\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "b03a95647ebbd8754b0d0a00e64f2630", "src_uid": "e66ecb0021a34042885442b336f3d911", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! https://codeforces.com/contest/633/problem/A\n\nuse std::io;\n\n#[derive(Clone, Copy)]\nstruct Solution(i32, i32);\n\nfn main() {\n let mut inp = String::new();\n io::stdin().read_line(&mut inp).unwrap();\n let mut iter = inp.trim().split_whitespace();\n let a: i32 = iter.next().unwrap().parse().unwrap();\n let b: i32 = iter.next().unwrap().parse().unwrap();\n let c: i32 = iter.next().unwrap().parse().unwrap();\n\n println!(\"{}\", match find_if_poss(a, b, c) {\n true => \"Yes\",\n false => \"No\"\n })\n}\n\nfn gcd(a: i32, b: i32) -> (Solution, i32) {\n if a == 0 {\n (Solution(0, 1), b)\n } else {\n let (Solution(x1, y1), g) = gcd(b % a, a);\n (Solution(y1 - (b / a) * x1, x1), g)\n }\n}\n\nfn find_one(a: i32, b: i32, c: i32) -> Option<(Solution, i32)> {\n let (Solution(x, y), g) = gcd(a.abs(), b.abs());\n if c % g != 0 {\n None\n } else {\n let mult = c / g;\n\n let x = get_sign(a) * mult * x;\n let y = get_sign(b) * mult * y;\n\n Some((Solution(x, y), g))\n }\n}\n\nfn get_sign(i: i32) -> i32 {\n if i < 0 { -1 } else { 1 }\n}\n\nfn shift_solution(sol: Solution, ag: i32, bg: i32, offset: i32) -> Solution {\n Solution(sol.0 + bg * offset, sol.1 - ag * offset)\n}\n\nfn find_if_poss(a: i32, b: i32, c: i32) -> bool {\n match find_one(a, b, c) {\n Some((mut sol, g)) => {\n let sign_a = get_sign(a);\n let sign_b = get_sign(b);\n\n let maxx = c/a;\n let maxy = c/b;\n\n let a = a / g;\n let b = b / g;\n\n let minx_offset = -sol.0/b;\n sol = shift_solution(sol, a, b, minx_offset);\n if sol.0 < 0 {\n sol = shift_solution(sol, a, b, sign_b);\n }\n if sol.0 > maxx {\n return false;\n }\n let lx1 = sol.0;\n\n let maxx_offset = (maxx - sol.0)/b;\n sol = shift_solution(sol, a, b, maxx_offset);\n if sol.0 > maxx {\n sol = shift_solution(sol, a, b, -sign_b);\n }\n let rx1 = sol.0;\n\n let miny_offset = sol.1/a;\n sol = shift_solution(sol, a, b, miny_offset);\n if sol.1 < 0 {\n sol = shift_solution(sol, a, b, -sign_a);\n }\n if sol.1 > maxy {\n return false;\n }\n let mut lx2 = sol.0;\n\n let maxy_offset = (sol.1 - maxy) / a;\n sol = shift_solution(sol, a, b, maxy_offset);\n if sol.1 > maxy {\n sol = shift_solution(sol, a, b, sign_a);\n }\n let mut rx2 = sol.0;\n\n if lx2 > rx2 {\n let temp = lx2;\n lx2 = rx2;\n rx2 = temp;\n }\n\n let lx = if lx1 > lx2 { lx1 } else { lx2 };\n let rx = if rx1 < rx2 { rx1 } else { rx2 };\n\n if lx > rx {\n return false;\n }\n\n let count = (rx - lx)/b.abs() + 1;\n\n count > 0\n },\n None => false\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "768766f7184fb9ad86e7659ee03765b0", "src_uid": "e66ecb0021a34042885442b336f3d911", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = input.i();\n let b = input.i();\n let c = input.i();\n println!(\"{}\", 3 * b.min(a + 1).min(c - 1));\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "3bfdfd4d34fc6e60b7d14f75fa91ba81", "src_uid": "03ac8efe10de17590e1ae151a7bae1a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, StdoutLock, Write};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_macros)]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n#[allow(dead_code)]\npub fn with_bufwriter) -> ()>(f: F) {\n let out = stdout();\n let writer = BufWriter::new(out.lock());\n f(writer)\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) } ; }\n#[allow(dead_code)]\nfn main() {\n input!{\n y: u64,\n b: u64,\n r: u64,\n }\n let mut mr = r;\n let mut mb = r - 1;\n let mut my = r - 2;\n if b < mb {\n my = b - 1;\n mb = b;\n mr = b + 1;\n }\n if y < my {\n my = y;\n mb = y + 1;\n mr = y + 2;\n }\n println!(\"{}\", my + mb + mr);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "811194fdd184c0403828e12c60edcf5b", "src_uid": "03ac8efe10de17590e1ae151a7bae1a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn main() {\n let (y, b, r) = readln!(i32, i32, i32);\n\n let (y1, b1, r1) = (y, y + 1, y + 2);\n let (y2, b2, r2) = (b - 1, b, b + 1);\n let (y3, b3, r3) = (r - 2, r - 1, r);\n\n if y1 <= y && b1 <= b && r1 <= r {\n println!(\"{}\", y1 + b1 + r1);\n } else if y2 <= y && b2 <= b && r2 <= r {\n println!(\"{}\", y2 + b2 + r2);\n } else {\n println!(\"{}\", y3 + b3 + r3);\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "284a1d3c9c015995d65ce199e9013fb0", "src_uid": "03ac8efe10de17590e1ae151a7bae1a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut nums: Vec = scan.next_n(3);\n nums[0] = nums[0].min(nums[1] - 1);\n nums[1] = nums[1].min(nums[2] - 1).min(nums[0] + 1);\n nums[2] = nums[2].min(nums[1] + 1);\n nums[0] = nums[0].min(nums[1] - 1);\n println!(\"{}\", nums[0] + nums[1] + nums[2]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "ad7a05727c3b03700424af1e68267855", "src_uid": "03ac8efe10de17590e1ae151a7bae1a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap,BTreeSet};\n#[allow(unused_imports)]\nuse std::ops::*;\n#[allow(unused_imports)]\nuse std::collections::BinaryHeap;\n\n#[allow(unused_macros)]\nmacro_rules! ite {\n ($c:expr, $t:expr, $f:expr) => {{\n if $c { $t } else { $f }\n }};\n}\n\n// ref: tanakh \n// diff: using Parser\n#[macro_export]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut parser = Parser::from_str($s);\n input_inner!{parser, $($r)*}\n };\n (parser = $parser:ident, $($r:tt)*) => {\n input_inner!{$parser, $($r)*}\n };\n (new_stdin_parser = $parser:ident, $($r:tt)*) => {\n let stdin = std::io::stdin();\n let reader = std::io::BufReader::new(stdin.lock());\n let mut $parser = Parser::new(reader);\n input_inner!{$parser, $($r)*}\n };\n ($($r:tt)*) => {\n input!{new_stdin_parser = parser, $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! input_inner {\n ($parser:ident) => {};\n ($parser:ident, ) => {};\n ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($parser, $t);\n input_inner!{$parser $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($parser:ident, ( $($t:tt),* )) => {\n ( $(read_value!($parser, $t)),* )\n };\n ($parser:ident, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($parser, $t)).collect::>()\n };\n ($parser:ident, chars) => {\n read_value!($parser, String).chars().collect::>()\n };\n ($parser:ident, usize1) => {\n read_value!($parser, usize) - 1\n };\n ($parser:ident, $t:ty) => {\n $parser.next::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n x: i64,\n y: i64,\n z: i64,\n }\n let res = min(min(x+1,y),z-1) * 3;\n println!(\"{}\", res);\n}\n\nuse std::io::BufRead;\nuse std::io;\nuse std::str;\n\n// ref: tatsuya6502 \n// ref: wariuni \n// diff: using std::io::BufRead::fill_buf()\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\n\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\n\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len,complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n (len, buf2[len-1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n }\n else {\n self.update_buf();\n }\n }\n }\n}\n\nuse std::fmt::Display;\n#[allow(dead_code)]\nfn write_vec(xs: &Vec) {\n if xs.len() == 0 {\n println!();\n return;\n }\n print!(\"{}\", xs[0]);\n for i in 1..xs.len() {\n print!(\" {}\", xs[i]);\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "f0cd0d8f6ea86454b4dbed96f495e7b5", "src_uid": "03ac8efe10de17590e1ae151a7bae1a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_nums() -> (usize, usize, usize, usize) {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n let v = input\n .trim()\n .split_whitespace()\n .map(|s| usize::from_str(s).unwrap())\n .collect::>();\n\n (v[0], v[1], v[2], v[3])\n}\n\nfn main() {\n let (a, b, c, d) = get_nums();\n\n let misha = std::cmp::max(3 * a / 10, a - a / 250 * c);\n let vasya = std::cmp::max(3 * b / 10, b - b / 250 * d);\n\n if misha > vasya {\n println!(\"Misha\");\n } else if misha < vasya {\n println!(\"Vasya\");\n } else {\n println!(\"Tie\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "48d0128b3d0b1fc98cbd9677e28f67a1", "src_uid": "95b19d7569d6b70bd97d46a8541060d0", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::Ordering;\nuse std::io::{self, BufRead};\n\nfn score(p: i32, t: i32) -> i32 {\n std::cmp::max(3 * p / 10, p - p / 250 * t)\n}\n\nfn main() {\n let stdin = io::stdin();\n let line = stdin.lock().lines().next().unwrap().unwrap();\n let v: Vec<_> = line.split(\" \").map(|x| x.parse::().unwrap()).collect();\n let (a, b, c, d) = (v[0], v[1], v[2], v[3]);\n let misha = score(a,c);\n let vasya = score(b,d);\n match vasya.cmp(&misha) {\n Ordering::Greater => println!(\"Vasya\"),\n Ordering::Equal => println!(\"Tie\"),\n Ordering::Less => println!(\"Misha\"),\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b2ff41f025eaa81f7579db3ac937bbdb", "src_uid": "95b19d7569d6b70bd97d46a8541060d0", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = input.i();\n let b = input.i();\n let c = input.i();\n let d = input.i();\n println!(\"{}\", match ((a * 3 / 10).max(a - a/250 * c)).cmp(&(b * 3 / 10).max(b - b/250 * d)) {\n Greater => \"Misha\",\n Less => \"Vasya\",\n Equal => \"Tie\",\n });\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "53104a89d3b53983328bad6f21215273", "src_uid": "95b19d7569d6b70bd97d46a8541060d0", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min,Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn solve(a: i64, t: i64) -> i64 {\n return max((a*3)/10,a-(a/250)*t);\n}\n\nfn main() {\n let (a,b,c,d) = readln!(i64,i64,i64,i64);\n let p1 = solve(a,c);\n let p2 = solve(b,d);\n println!(\"{}\",if p1 < p2 { \"Vasya\" } else if p1 > p2 { \"Misha\" } else { \"Tie\" });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9569743084e9933c7b49be1267a95eda", "src_uid": "95b19d7569d6b70bd97d46a8541060d0", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/515/C\nuse std::io;\nuse std::collections::HashMap;\n\nfn main() {\n let mut n = String::new();\n\n io::stdin()\n .read_line(&mut n)\n .unwrap();\n\n let _n: i64 = n.trim().parse().unwrap();\n\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let line = line.trim();\n\n let mut a: Vec = line.chars().collect();\n\n a.sort();\n a.reverse();\n\n let mut translate = HashMap::new();\n\n translate.insert('0',\"\");\n translate.insert('1',\"\");\n translate.insert('2',\"2\");\n translate.insert('3',\"3\");\n translate.insert('4',\"322\");\n translate.insert('5',\"5\");\n translate.insert('6',\"53\");\n translate.insert('7',\"7\");\n translate.insert('8',\"7222\");\n translate.insert('9',\"7332\");\n\n let mut ans = String::from(\"\");\n\n for ch in a {\n //print!(\"{}\", translate.get(&ch).unwrap());\n ans.push_str(translate.get(&ch).unwrap());\n } \n let mut fin: Vec = ans.chars().collect();\n fin.sort();\n fin.reverse();\n println!(\"{}\", fin.into_iter().collect::());\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "greedy"], "code_uid": "7eff9b8662b37cad9ba79081bc41a510", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nfn run() {\n input! {\n _n: usize,\n s: bytes,\n }\n let mut cnt = vec![0; 4];\n let p = [2, 3, 5, 7];\n for c in s {\n let k = (c - b'0') as usize;\n match k {\n 2 => cnt[0] += 1,\n 3 => cnt[1] += 1,\n 4 => {\n cnt[0] += 2;\n cnt[1] += 1;\n },\n 5 => cnt[2] += 1,\n 6 => {\n cnt[2] += 1;\n cnt[1] += 1;\n },\n 7 => cnt[3] += 1,\n 8 => {\n cnt[3] += 1;\n cnt[0] += 3;\n },\n 9 => {\n cnt[3] += 1;\n cnt[1] += 2;\n cnt[0] += 1;\n },\n _ => (),\n }\n }\n for (p, c) in p.iter().zip(cnt.iter()).rev() {\n for _ in 0..*c {\n print!(\"{}\", *p)\n }\n }\n println!();\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp", "implementation"], "code_uid": "f0a7c6b9a90e2f2b8fb7e9add4c2a5b6", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n readln!();\n let mut s = readln!();\n let mut v = s.into_bytes();\n v.sort();\n v = v.iter().map(|c|c-('0' as u8)).collect();\n let mut f = vec![0;10];\n v.iter().map(|x|for i in (2..(x+1)) {\n f[i as usize] += 1;\n }).count();\n f[2] += 2*f[4];\n f[4] = 0;\n f[2] += f[6];\n f[3] += f[6];\n f[6] = 0;\n f[2] += 3*f[8];\n f[8] = 0;\n f[3] += 2*f[9];\n f[9] = 0;\n let mut res = String::new();\n while f[7] > 0 {\n res.push('7');\n f[7] -= 1;\n f[2] -= 1; f[3] -= 1;\n f[5] -= 1;\n f[2] -= 2;\n f[3] -= 1;\n f[2] -= 1;\n }\n while f[5] > 0 {\n res.push('5');\n f[5] -= 1;\n f[2] -= 2;\n f[3] -= 1;\n f[2] -= 1;\n }\n while f[3] > 0 {\n res.push('3');\n f[3] -= 1;\n f[2] -= 1;\n }\n while f[2] > 0 {\n res.push('2');\n f[2] -= 1;\n }\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "greedy"], "code_uid": "249779a5addf7e24ca0ffb27380256b7", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let _ = input.i();\n let x = vec![7,5,3,2];\n let mut a = vec![0; 4];\n for c in input.bs() {\n for mut z in 2..(c - b'0' + 1) as i32 {\n for j in 0..4 {\n while z % x[j] == 0 {\n z /= x[j];\n a[j] += 1;\n }\n }\n }\n }\n for i in 0..4 {\n let n = a[i];\n for _ in 0..n { print!(\"{}\", x[i]); }\n for mut z in 2..x[i] + 1 {\n for j in 0..4 {\n while z % x[j] == 0 {\n z /= x[j];\n a[j] -= n;\n }\n }\n }\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "greedy"], "code_uid": "b819fac93fe2da41baacc9b15373e18c", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let _n : usize = s.trim().parse().unwrap();\n s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut v = [0,0,0,0];\n let d = [7,5,3,2];\n let mut x = s.trim().chars().map(|a| a.to_digit(10).unwrap()).peekable(); \n while x.peek().is_some() {\n match x.next().unwrap() {\n 9 => { v[0]+=1; v[2]+=2; v[3]+=1},\n 8 => { v[0]+=1; v[3]+=3; },\n 7 => { v[0]+=1;},\n 6 => { v[1]+=1; v[2]+=1;},\n 5 => { v[1]+=1; },\n 4 => { v[2]+=1; v[3]+=2; },\n 3 => { v[2]+=1; },\n 2 => { v[3]+=1; }\n _ => {}\n }\n\n }\n for i in 0..4 {\n for j in 0..v[i] {\n print!(\"{}\", d[i]);\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "greedy"], "code_uid": "ca2ee3228f15e21ad592a234a588053d", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn run(s: String){\n let mut arr: [usize;10] = [0;10];\n\n for c in s.chars(){\n let mut x=(c.to_string()).parse::().unwrap();\n if x==4 || x==8 || x==6 ||x==9{\n if x==4{\n arr[2]+=2;\n }\n else if x==8{\n arr[2]+=3;\n }\n else if x==6{\n arr[3]+=1;\n }\n else{\n arr[2]+=1;\n arr[3]+=2;\n x-=1;\n }\n x-=1;\n }\n arr[x]+=1;\n }\n for i in (2..10).rev(){\n for _j in 0..arr[i]{\n print!(\"{}\",i);\n }\n }\n}\nfn main()\n{\n let mut s1=String::new();\n let mut s2=String::new();\n io::stdin().read_line(&mut s1).expect(\"read error\");\n io::stdin().read_line(&mut s2).expect(\"read error\");\n\n run(s2.trim().to_string());\n}", "lang_cluster": "Rust", "tags": ["math", "sortings", "greedy"], "code_uid": "3ab52792ef051578e4dcb9a783b2a5a0", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn input(read_file: bool) -> String {\n if read_file {\n let mut file = std::fs::File::open(\"sample.txt\").unwrap();\n let mut buf = String::new();\n file.read_to_string(&mut buf).unwrap();\n buf\n } else {\n let mut buf = String::new();\n std::io::stdin().read_to_string(&mut buf).unwrap();\n buf.trim_end().to_owned()\n }\n}\n\nfn solve(ws: &mut std::str::SplitWhitespace) {\n let _: usize = ws.next().unwrap().parse().unwrap();\n let s: Vec = ws.next().unwrap().to_string().chars().collect();\n\n let mut m = std::collections::HashMap::new();\n m.insert(2, \"2\");\n m.insert(3, \"3\");\n m.insert(4, \"223\");\n m.insert(5, \"5\");\n m.insert(6, \"35\");\n m.insert(7, \"7\");\n m.insert(8, \"2227\");\n m.insert(9, \"2337\");\n\n let mut ans: Vec = Vec::new();\n for c in s {\n let d = c as i32 - '0' as i32;\n let mut x: Vec = m.entry(d).or_default().chars().collect();\n ans.append(&mut x);\n }\n\n ans.sort();\n ans.reverse();\n let s: String = ans.iter().collect();\n println!(\"{}\", s);\n}\n\nfn main() {\n const READ_FROM_FILE: bool = false;\n\n let s = input(READ_FROM_FILE);\n let mut ws = s.split_whitespace();\n\n solve(&mut ws);\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "greedy"], "code_uid": "d94e3f1c63e8b1838c1bc6b5a0e0ba29", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n stdin().read_line(&mut String::new());\n\n let mut a = String::new();\n stdin().read_line(&mut a).unwrap();\n let a = a.trim();\n\n let a: Vec = a\n .chars()\n .filter(|x| x != &'0' && x != &'1')\n .collect();\n\n let mut c = String::new();\n\n for i in a {\n let b = i.to_string();\n let b = b.as_str();\n c.push_str( match i {\n '4' => \"223\",\n '6' => \"53\",\n '8' => \"7222\",\n '9' => \"2337\",\n _ => b\n });\n }\n\n let mut c: Vec = c.chars().map(|x| x.to_digit(10 as u32).unwrap()).collect();\n\n c.sort();\n c.reverse();\n\n for i in c {\n print!(\"{}\", i);\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "greedy"], "code_uid": "79530e64ae3b4072b37a8b677417f168", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::prelude::*;\nuse std::io;\nuse std::str::FromStr;\n#[cfg(local)]\nuse std::fs::File;\n#[cfg(local)]\nuse std::io::BufReader;\n\nuse std::cmp;\n\n#[cfg(local)]\nfn buf_read() -> io::Result<(Vec)> {\n let f = try!(File::open(\"input.txt\"));\n let input_lines: Vec<_> = BufReader::new(f).lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\n#[cfg(not(local))]\nfn buf_read() -> io::Result<(Vec)> {\n let stdin = io::stdin();\n let input_lines: Vec<_> = stdin.lock().lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\nfn main() {\n type Element = i64;\n let input = buf_read().unwrap();\n let mut input_vectors: Vec> = vec![];\n for input_line in input {\n let input_str: Vec = input_line.split(' ').map(String::from).collect();\n let mut input_vector: Vec = vec![];\n for input_elem_str in input_str {\n let elem: Element = Element::from_str(input_elem_str.as_str()).unwrap();\n input_vector.push(elem);\n }\n input_vectors.push(input_vector);\n }\n let k = input_vectors[0][0];\n let a = input_vectors[0][1];\n let b = input_vectors[0][2];\n let c = input_vectors[0][3];\n let required_copies = match k % 4 {\n 0 => 0,\n n => 4 - n,\n };\n let cost = match required_copies {\n 1 => cmp::min(a * 1, cmp::min(b * 1 + c * 1, c * 3)),\n 2 => cmp::min(cmp::min(a * 2, b * 1), cmp::min(a * 1 + c * 1, c * 2)),\n 3 => cmp::min(a * 3, cmp::min(a * 1 + b * 1, c * 1)),\n _ => 0,\n };\n println!(\"{}\", cost);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "2aa32110627a85144fbfc33397baa296", "src_uid": "c74537b7e2032c1d928717dfe15ccfb8", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\nuse std::thread;\nuse std::cmp::*;\nfn exec() {\n let mut sc = Scanner::new();\n let n: usize = sc.ne();\n let a: usize = sc.ne();\n let b: usize = sc.ne();\n let c: usize = sc.ne();\n let ans = match n % 4 {\n 0 => 0,\n 1 => min(a * 3, min(a + b, c)),\n 2 => min(a * 2, min(c * 2, b)),\n _ => min(a, min(b + c, c * 3)),\n };\n println!(\"{}\", ans);\n}\n\nfn main() {\n const DEFAULT_STACK: usize = 16 * 1024 * 1024;\n let builder = thread::Builder::new();\n let th = builder.stack_size(DEFAULT_STACK);\n let handle = th.spawn(|| { exec(); }).unwrap();\n let _ = handle.join();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => return None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => panic!(\"parse error\"),\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "9034b296a742ed33cc3f6ac7edb1cfcf", "src_uid": "c74537b7e2032c1d928717dfe15ccfb8", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::min;\n\nfn main() {\n let mut input_line = String::new();\n stdin().read_line(&mut input_line);\n\n let input_iter = input_line.\n split_whitespace().\n map(|x| x.parse::().unwrap());\n\n let input: Vec<_> = input_iter.collect();\n\n let owned = input[0];\n if owned % 4 == 0 {\n // Already meet criteria\n println!(\"0\");\n return;\n }\n\n let purchase = (4 - owned % 4) as usize;\n\n let mut dp = vec![u64::max_value(); 12];\n dp[0] = 0;\n\n for i in 0..12 {\n for j in 1..4 {\n if i >= j {\n dp[i] = min(dp[i - j] + input[j], dp[i]);\n }\n }\n }\n\n println!(\"{}\", min(min(dp[purchase], dp[purchase + 4]), dp[purchase + 8]));\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "24bd1d99c287edcb6a952969f47a6c53", "src_uid": "c74537b7e2032c1d928717dfe15ccfb8", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::min;\n\nfn main() {\n let mut input_line = String::new();\n stdin().read_line(&mut input_line);\n\n let mut input_iter = input_line.\n split_whitespace().\n map(|x| x.parse::().unwrap());\n\n let owned = input_iter.next().unwrap();\n let price1 = input_iter.next().unwrap();\n let price2 = input_iter.next().unwrap();\n let price3 = input_iter.next().unwrap();\n\n if owned % 4 == 0 {\n // Already meet criteria\n println!(\"0\");\n return;\n }\n\n let purchase = 4 - owned % 4;\n let result = match purchase {\n 1 => min(price1, min(price3 * 3, price2 + price3)),\n 2 => min(price2, min(price1 * 2, price3 * 2)),\n 3 => min(price3, min(price1 * 3, price2 + price1)),\n _ => u64::max_value()\n };\n\n println!(\"{}\", result);\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "ab3253466909a987a24d21539b4609cd", "src_uid": "c74537b7e2032c1d928717dfe15ccfb8", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n\tlet inp = std::io::stdin();\n\tlet mut inp = my_ios::InputReader::new(inp.lock());\n\tlet m:i64 = 1000000007;\n\tlet n:i64 = inp.read();\n\tlet _l:i64 = inp.read();\n\tlet l = _l - 1;\n\tlet r:i64 = inp.read();\n\tlet mut cnt = vec![0 as i64; 3];\n\tfor i in 0..3 {\n\t\tcnt[i] += r / 3 + m - l / 3;\n\t\tif i as i64 <= r % 3 {\n\t\t\tcnt[i] += 1;\n\t\t}\n\t\tif i as i64 <= l % 3 {\n\t\t\tcnt[i] += m - 1;\n\t\t}\n\t\tcnt[i] %= m;\n\t}\n\tlet mut dp = vec![0 as i64; 3];\n\tlet mut tp = vec![0 as i64; 3];\n\tdp[0] = 1;\n\tfor _ in 0..n {\n\t\tfor i in 0..3 {\n\t\t\tfor j in 0..3 {\n\t\t\t\ttp[(i + j) % 3] += dp[i] * cnt[j];\n\t\t\t}\n\t\t}\n\t\tfor i in 0..3 {\n\t\t\ttp[i] %= m;\n\t\t\tdp[i] = tp[i];\n\t\t\ttp[i] = 0;\n\t\t}\n\t}\n\tprintln!(\"{}\", dp[0]);\n}\n\nmod my_ios {\n\tuse std::io::{BufRead, ErrorKind, Result};\n\tuse std::str::{FromStr, from_utf8};\n\tuse std::fmt::Debug;\n\t\n\tpub fn read_token(r:&mut R, buf:&mut Vec) -> Result {\n\t\tlet mut read = 0;\n\t\tloop {\n\t\t\tlet (done, used) = {\n\t\t\t\tlet avail = match r.fill_buf() {\n\t\t\t\t\tOk(n) => n,\n\t\t\t\t\tErr(ref e) if e.kind() == ErrorKind::Interrupted => continue,\n\t\t\t\t\tErr(e) => return Err(e)\n\t\t\t\t};\n\t\t\t\tmatch avail.iter().position(|&x| x == b'\\n' || x== b' ') {\n\t\t\t\t\tSome(i) => {\n\t\t\t\t\t\tbuf.extend_from_slice(&avail[..i]);\n\t\t\t\t\t\t(true, i + 1)\n\t\t\t\t\t}\n\t\t\t\t\tNone => {\n\t\t\t\t\t\tbuf.extend_from_slice(avail);\n\t\t\t\t\t\t(false, avail.len())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tr.consume(used);\n\t\t\tread += used;\n\t\t\tif done || used == 0 {\n\t\t\t\treturn Ok(read);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpub struct InputReader {\n\t\treader:R,\n\t\tbuf:Vec,\n\t}\n\t\t\n\timpl InputReader {\n\t\tpub fn new(reader: R) -> InputReader {\n\t\t\tInputReader {\n\t\t\t\treader:reader,\n\t\t\t\tbuf:Vec::::new(),\n\t\t\t}\n\t\t}\n\t\tpub fn read_token(&mut self) {\n\t\t\tread_token(&mut self.reader, &mut self.buf);\n\t\t}\n\t\tpub fn read(&mut self) -> T where T:FromStr, T::Err:Debug {\n\t\t\tself.buf.clear();\n\t\t\tself.read_token();\n\t\t\tfrom_utf8(&self.buf).unwrap().trim().parse().unwrap()\n\t\t}\n\t}\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "3e9741739a1ccae1ad0237fab6fee8d7", "src_uid": "4c4852df62fccb0a19ad8bc41145de61", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let n: usize = scan.token();\n let (l, r) = scan.pair::();\n\n const M: i64 = 1_000_000_007;\n\n let m0 = r/3 - (l-1)/3;\n let m1 = m0\n - if r%3 == 0 { 1 } else { 0 }\n + if (l-1)%3 == 0 { 1 } else { 0 };\n let m2 = m0\n - if r%3 <= 1 { 1 } else { 0 }\n + if (l-1)%3 <= 1 { 1 } else { 0 };\n\n dbg!(m0);\n dbg!(m1);\n dbg!(m2);\n\n let mut ans = [1_i64, 0, 0];\n for _ in 0..n {\n let mut nxt = [0_i64; 3];\n nxt[0] = m0 * ans[0] % M + m1 * ans[2] % M + m2 * ans[1];\n nxt[1] = m0 * ans[1] % M + m1 * ans[0] % M + m2 * ans[2];\n nxt[2] = m0 * ans[2] % M + m1 * ans[1] % M + m2 * ans[0];\n\n for i in 0..3 {\n ans[i] = nxt[i] % M;\n }\n }\n\n writeln!(out, \"{}\", ans[0])?;\n\n Ok(())\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "43ca571edf137b0d3713d6d723890b7e", "src_uid": "4c4852df62fccb0a19ad8bc41145de61", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"ERROR: Empty input.\");\n let mut words = input.split_whitespace();\n let k:u64 = words.next().expect(\"k not given.\").parse().unwrap();\n let p:u64 = words.next().expect(\"p not given.\").parse().unwrap();\n\n let mut sum:u64 = 0;\n for i in 1..k+1 {\n sum+=zcy(i);\n //println!(\"zcy({}) = {}\",i,zcy(i));\n }\n\n //println!(\"{} % {}\",sum,p);\n println!(\"{}\",sum % p);\n}\n\nfn rev(n:u64) -> u64 {\n let mut rev:u64 = 0;\n let mut n = n;\n while n>0 {\n rev*=10;\n rev+=n%10;\n n/=10;\n }\n return rev;\n}\n\nfn num_digits(n:u64) -> u32 {\n let mut d:u32 = 0;\n let mut n = n;\n while n>0 {\n n/=10;\n d+=1;\n }\n return d;\n}\n\nfn zcy(n:u64) -> u64{\n n*(10u64.pow(num_digits(n)))+rev(n)\n}\n\n\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "50a04568516eb32fc99d56b5a195d588", "src_uid": "00e90909a77ce9e22bb7cbf1285b0609", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(&mut std::io::stdin(), &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get { () => (get().parse().unwrap()) }\n \n let k: u64 = get!();\n let p: u64 = get!();\n let mut ans: u64 = 0;\n for i in 1..k+1 {\n let mut x = i;\n let mut y = i;\n let mut r = 0;\n while x > 0 {\n r = r * 10 + x % 10;\n x /= 10;\n y *= 10;\n }\n ans = (y + r + ans) % p;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "93fddd02552778b11431141bf6191303", "src_uid": "00e90909a77ce9e22bb7cbf1285b0609", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap, VecDeque, BTreeSet, BTreeMap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let (k, p) = get!(usize, u64);\n\n let mut sum = 0;\n for i in 1..k + 1 {\n let mut v = Vec::new();\n let mut x = i as u64;\n while x > 0 {\n v.push(x % 10);\n x /= 10;\n }\n\n let l = v.len() * 2;\n for (i, &x) in v.iter().rev().enumerate() {\n sum += 10u64.pow(i as u32) * x;\n sum %= p;\n sum += 10u64.pow((l - i - 1) as u32) * x;\n sum %= p;\n }\n\n }\n\n println!(\"{}\", sum);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "088deccd445580dd091078ee5b8829d6", "src_uid": "00e90909a77ce9e22bb7cbf1285b0609", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports, deprecated, dead_code)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{VecDeque,HashSet,HashMap,BinaryHeap};\n// Module for v1.15.1\nuse std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead\n\n// Functions\n\n// Main\nfn main() {\n\n input! {\n N: chars,\n }\n \n let mut ans = \"YES\";\n let mut cnt_4 = 0; \n\n // \u6700\u4e0a\u4f4d\u306f 1 \u5fc5\u9808\n if N[0] != '1' {\n ans = \"NO\";\n } else {\n for i in 1..N.len() {\n if N[i] == '1' {\n cnt_4 = 0;\n continue;\n // 4 \u306f\u9023\u7d9a2\u56de\u307e\u3067\n } else if N[i] == '4' {\n cnt_4 += 1;\n if cnt_4 > 2 {\n ans = \"NO\";\n break;\n }\n } else {\n ans = \"NO\";\n break;\n }\n }\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "b77822097be23ba5e9fe3f5d06133c0b", "src_uid": "3153cfddae27fbd817caaf2cb7a6a4b5", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut input: usize = scan.next();\n let mut result = true;\n let mut count4 = 0usize;\n let mut digit = 0usize;\n while input > 0 {\n digit = input % 10;\n input /= 10;\n if digit == 4 {\n count4 += 1;\n if count4 > 2 {\n result = false;\n break;\n }\n } else if digit == 1 {\n count4 = 0;\n } else {\n result = false;\n break;\n }\n }\n println!(\"{}\", if result && digit != 4 { \"YES\" } else { \"NO\" });\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "b0a9b2774ef330b2edb44f1ecac20f30", "src_uid": "3153cfddae27fbd817caaf2cb7a6a4b5", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::collections::{*};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n \nfn main() {\n let mut scanner = Scanner::default();\n let dx: [i32;3] = [1, 0, -1];\n let mut arr: [[u64;3];3] = [[0;3];3];\n for i in 0..3 {\n \tfor j in 0..3{\n \t\tlet times: u64 = scanner.next();\n \t\tfor x in &dx {\n \t\t\tfor y in &dx {\n \t\t\t\tif i + *x < 3 && j + *y < 3 && i + *x > -1 && j + *y > -1 && (*x).abs() + (*y).abs() <= 1{\n \t\t\t\t\tarr[(i + *x) as usize][(j + *y) as usize] += times;\n \t\t\t\t} \n \t\t\t}\n \t\t}\n \t}\n }\n for i in 0usize..3{\n \tfor j in 0usize..3{\n \t\tif arr[i][j]%2 == 1 {\n \t\t\tprint![\"0\"];\n \t\t} else {\n \t\t\tprint![\"1\"];\n \t\t}\n \t}\n \tprintln![\"\"];\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a7cbb5b3eaf3d0402871783080df189b", "src_uid": "b045abf40c75bb66a80fd6148ecc5bd6", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::BufRead;\n\ntype Grid = Vec>;\n\nfn valid_index(index: isize) -> bool {\n index >= 0 && index <= 2\n}\n\nfn get_position(grid: &Grid, x: isize, y: isize) -> usize {\n if !valid_index(x) || !valid_index(y) {\n 0\n } else {\n *grid.get(y as usize).and_then(|n| n.get(x as usize).or(Some(&0))).unwrap_or(&0)\n }\n}\n\nfn main() {\n let numbers: Grid = io::stdin()\n .lock()\n .lines()\n .take(3)\n .map(|line| line.expect(\"failed to read line\")\n .trim()\n .split(\" \")\n .map(|number| number.parse::().expect(\"failed to parse number\"))\n .collect()\n )\n .collect();\n\n for y in 0 as isize..3 {\n for x in 0 as isize..3 {\n let mut n = get_position(&numbers, x, y);\n n += get_position(&numbers, x, y - 1);\n n += get_position(&numbers, x, y + 1);\n n += get_position(&numbers, x - 1, y);\n n += get_position(&numbers, x + 1, y);\n print!(\"{}\", match n % 2 {\n 0 => 1,\n 1 => 0,\n _ => unreachable!()\n });\n }\n println!(\"\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "60ed91c697e5eda1168341ba1b70d2ee", "src_uid": "b045abf40c75bb66a80fd6148ecc5bd6", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufReader, BufRead};\n\nfn main() -> Result<(), Box> {\n let mut distance = BufReader::new(std::io::stdin())\n .lines()\n .map(Result::unwrap)\n .next()\n .unwrap()\n .parse::()?;\n\n let mut steps = 0;\n for step in &[5, 4, 3, 2, 1] {\n if distance == 0 { break }\n steps += distance / step;\n distance %= step;\n }\n\n println!(\"{}\", steps);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "8b20ed423d3220f255dc3b60555d2183", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (n, ) = R!(usize);\n println!(\"{}\", n/5 + (if n % 5 != 0 { 1 } else { 0 }));\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "6f8fa832988b5729ae7246b547f9b312", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut buf = String::new();\n let _ = stdin().read_line(&mut buf);\n let mut x = buf.trim_end().parse::().unwrap();\n let mut ans = 0;\n let mut iter = 5;\n while iter > 0 && x >= 0 {\n ans += x / iter;\n x -= iter * (x / iter);\n iter -= 1;\n }\n println!(\"{}\\n\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "567e8e117906dceaf8cdc69e13125692", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"Failed to read line\");\n\n let input: u32 = input.trim().parse().expect(\"Please Type a number!\");\n\n if input%5 == 0{\n println!(\"{}\",input/5);\n }\n else{\n println!(\"{}\",input/5+1)\n }\n }", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1fc967c69df10b5c0448335bec77bfbd", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut text = String::new();\n std::io::stdin().read_line(&mut text).expect(\"\");\n println!(\"{}\", resolver(text.trim().parse().expect(\"msg: &str\"), 0));\n}\n\nfn resolver(value: usize, step: usize) -> usize {\n if value > 5 {\n resolver(value % 5, value / 5)\n } else {\n if value == 1 {\n step + 1\n } else if value % 5 == 0 {\n (value / 5) + step\n } else if value % 4 == 0 {\n (value / 4) + step\n } else if value % 3 == 0 {\n (value / 3) + step\n } else {\n (value / 2) + step\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "84d0d7aad7db1bcf61fbc837fd9cdf86", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut val = String::new();\n\n io::stdin().read_line(&mut val)\n .expect(\"\u041d\u0435 \u0443\u0434\u0430\u043b\u043e\u0441\u044c \u043f\u0440\u043e\u0447\u0438\u0442\u0430\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0443\");\n\n let val: i32 = val.trim().parse()\n .expect(\"\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e!\");\n\n let ans = val / 5;\n println!(\"{}\", ans + (val % 5 > 0) as i32);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "3ce64ee551926d1fc5bbfbdc0218fa49", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn get_input() -> String {\n\tlet mut buffer = String::new();\n\tstd::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n\tbuffer\n}\n\nfn main() {\n\tlet x = get_input().trim().parse::().unwrap();\n\t\n\tlet mut cnt = x / 5;\n\tlet dv = x % 5;\n\t\n\tif dv != 0 {\n\t\tcnt += 1;\n\t}\n\t\n\tprint!(\"{}\", cnt); \n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "eff3842ea33d66297600c0b1b6265f57", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! debug(\n ($($arg:tt)*) => { {\n let r = writeln!(&mut ::std::io::stderr(), $($arg)*);\n r.expect(\"failed printing to stderr\");\n } }\n);\n\nstruct Scanner {\n buffer : std::collections::VecDeque\n}\n\nimpl Scanner {\n\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn process(&mut self) -> String {\n if self.buffer.len() == 0 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n for word in input.split_whitespace() {\n self.buffer.push_back(word.to_string())\n }\n }\n\n self.buffer.pop_front().unwrap()\n }\n\n #[allow(dead_code)]\n fn next(&mut self) -> T {\n self.process().parse::().ok().unwrap()\n }\n\n #[allow(dead_code)]\n fn next_char(&mut self) -> char {\n self.process().into_bytes()[0] as char\n }\n}\n\nfn main() {\n let mut sin = Scanner::new();\n let n = sin.next::();\n\n let result = n / 5 + (0 != n % 5) as i32;\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "e47e97c79bd3edb2546ec581737476eb", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let ss = readln!();\n let s = ss.as_bytes();\n let n = s.len();\n let mut need = 0;\n for i in 0..(n/2) {\n if s[i] != s[n-1-i] {\n need += 1;\n }\n }\n if need == 1 || (need == 0 && (n%2) == 1) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "constructive algorithms"], "code_uid": "ee1c5d88da0d7648c771d3924ddd9242", "src_uid": "fe74313abcf381f6c5b7b2057adaaa52", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::{Error, ErrorKind};\nuse std::str::FromStr;\n\nstruct IO {\n buffer: Vec\n}\n\nimpl IO {\n fn new() -> IO {\n IO { buffer: Vec::new() }\n }\n /*\n pub fn reset(&mut self) {\n self.buffer = Vec::new();\n }\n */\n\n fn try_parse(s: String) -> Result \n where T: FromStr {\n let res = (&s).parse::()?;\n Ok(res)\n }\n\n fn receive(&mut self) -> Result \n where T: FromStr {\n let ref mut stdio = &mut io::stdin();\n if let Some(s) = self.buffer.pop() {\n return match IO::try_parse::(s) {\n Ok(value) => Ok(value),\n _ => Err(Error::new(ErrorKind::Other, \"cannot parse to desired type\"))\n }\n }\n\n let mut input = String::new();\n if let Err(error) = stdio.read_line(&mut input) {\n return Err(error)\n }\n\n input = input.trim().to_string();\n\n self.buffer.extend:: >(input.split(' ').map(|s| s.to_string()).collect());\n\n return self.receive::()\n }\n}\n\nfn main() {\n let mut sio = IO::new();\n let s = sio.receive::().unwrap();\n let q = s.bytes().collect:: >();\n let mut diff = 0;\n for i in 0..s.len() {\n if q[i] != q[s.len() - 1 - i] {\n diff += 1;\n }\n }\n if diff == 2 || (diff == 0 && s.len() % 2 == 1){\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings", "constructive algorithms"], "code_uid": "f0098da4bfbff1ebce1e4075e046dc58", "src_uid": "fe74313abcf381f6c5b7b2057adaaa52", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let s = input.bs();\n let n = s.len();\n let x = (0..n).zip((0..n).rev()).filter(|(a,b)| a < b && s[*a] != s[*b]).count();\n if (n % 2 == 1 && x <= 1) || (n % 2 == 0 && x == 1) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "constructive algorithms"], "code_uid": "6e7cc0c670546efd708d7d19ec65acec", "src_uid": "fe74313abcf381f6c5b7b2057adaaa52", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::cell::RefCell;\nuse std::cmp::Ordering;\nuse std::collections::*;\nuse std::error::Error;\nuse std::fmt::write;\nuse std::hash::Hash;\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::StdinLock;\nuse std::io::StdoutLock;\nuse std::io::Write;\nuse std::io::{stdin, stdout, BufRead, BufWriter};\nuse std::ops::Add;\nuse std::thread::panicking;\n\nmacro_rules! fprintvec {\n ($dst:expr, $arg:expr) => {{\n writeln!(\n $dst,\n \"{}\",\n $arg.iter()\n .map(|x| format!(\"{} \", x))\n .collect::>()\n .join(\"\")\n )\n .ok();\n }};\n}\n\npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace(),\n }\n }\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace())\n }\n }\n }\n\n pub fn next_split(&mut self) -> Vec {\n loop {\n let mut v = Vec::new();\n while let Some(token) = self.buf_iter.next() {\n v.push(token.parse().ok().expect(\"Failed parse\"));\n }\n if v.len() > 0 {\n return v;\n }\n\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace())\n }\n }\n }\n}\n\nfn lcm(first: usize, second: usize) -> usize {\n first * second / gcd(first, second)\n}\n\nfn gcd(first: usize, second: usize) -> usize {\n let mut max = first;\n let mut min = second;\n if min > max {\n let val = max;\n max = min;\n min = val;\n }\n\n loop {\n let res = max % min;\n if res == 0 {\n return min;\n }\n\n max = min;\n min = res;\n }\n}\n#[derive(Clone, Default, Debug)]\nstruct FactModCache {\n fact: Vec,\n inv: Vec,\n n: i64,\n}\n\nimpl FactModCache {\n fn new(n: usize) -> FactModCache {\n let mut fmc = FactModCache {\n ..Default::default()\n };\n fmc.fact.resize(n, 0);\n fmc.inv.resize(n, 0);\n fmc.fact[0] = 1;\n fmc.inv[0] = 1;\n fmc.n = n as i64; //set this after so the calculation doesn't return cached value\n for i in 1..n {\n fmc.fact[i] = fmc.mult_mod(fmc.fact[i - 1], i as i64);\n fmc.inv[i] = fmc.inv_mod(fmc.fact[i]);\n }\n fmc\n }\n\n fn factorial_mod(&self, n: i64) -> i64 {\n if n < self.n {\n return self.fact[n as usize];\n }\n let mut t = self.fact[self.n as usize - 1];\n for x in self.n..=n {\n t = (t * x) % MODVAL;\n }\n t\n }\n\n fn permutations_mod(&self, n: i64, r: i64) -> i64 {\n let a = self.factorial_mod(n);\n let b = self.inv_fact_mod(n - r);\n return self.mult_mod(a, b);\n }\n\n fn inv_fact_mod(&self, n: i64) -> i64 {\n if n < self.n {\n return self.inv[n as usize];\n }\n self.pow_mod(self.factorial_mod(n), MODVAL - 2)\n }\n\n fn inv_mod(&self, n: i64) -> i64 {\n self.pow_mod(n, MODVAL - 2)\n }\n\n fn combinations_mod(&self, n: i64, r: i64) -> i64 {\n let a = self.factorial_mod(n);\n let b = self.inv_fact_mod(r);\n let c = self.inv_fact_mod(n - r);\n return self.mult_mod(self.mult_mod(a, b), c);\n }\n\n fn pow_mod(&self, mut base: i64, mut pow: i64) -> i64 {\n if pow == 0 {\n return 1;\n }\n let mut result = 1;\n while pow > 0 {\n if pow & 1 == 1 {\n result = (result * base) % MODVAL;\n }\n pow /= 2;\n base = (base * base) % MODVAL;\n }\n result\n }\n\n fn mult_mod(&self, a: i64, b: i64) -> i64 {\n let a = a as i128;\n let b = b as i128;\n ((a * b) % MODVAL as i128) as i64\n }\n\n fn add_mod(&self, a: i64, b: i64) -> i64 {\n ((a % MODVAL) + (b % MODVAL)) % MODVAL\n }\n}\n\nfn main() -> Result<(), Box> {\n let stdout = io::stdout();\n let lock = stdout.lock();\n let stdin = io::stdin();\n let mut ow = io::BufWriter::new(lock);\n let mut scan = Scanner::new(stdin.lock());\n\n // let n_tests = scan.next::();\n let n_tests = 1;\n let fmc = FactModCache::<1000000007>::new(1000005);\n for t_num in 1..=n_tests {\n let n = scan.next::();\n let k = scan.next::();\n\n let mut start = 1;\n\n for i in 1..=(std::cmp::min(n, k)) {\n start = fmc.add_mod(start, fmc.combinations_mod(n as i64, i as i64));\n }\n\n writeln!(ow, \"{}\", start);\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "90d7fc25a1829a642c3a931ac6fa516e", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// start of input macros\r\n\r\nmacro_rules! input {\r\n\t(source = $s:expr, $($r:tt)*) => {\r\n\t\tlet mut iter = $s.split_whitespace();\r\n\t\tinput_inner!{iter, $($r)*}\r\n\t};\r\n\t($($r:tt)*) => {\r\n\t\tlet s = {\r\n\t\t\tuse std::io::Read;\r\n\t\t\tlet mut s = String::new();\r\n\t\t\tstd::io::stdin().read_to_string(&mut s).unwrap();\r\n\t\t\ts\r\n\t\t};\r\n\t\tlet mut iter = s.split_whitespace();\r\n\t\tinput_inner!{iter, $($r)*}\r\n\t};\r\n}\r\n\r\nmacro_rules! input_inner {\r\n\t($iter:expr) => {};\r\n\t($iter:expr, ) => {};\r\n\r\n\t($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n\t\tlet $var = read_value!($iter, $t);\r\n\t\tinput_inner!{$iter $($r)*}\r\n\t};\r\n}\r\n\r\nmacro_rules! read_value {\r\n\t($iter:expr, ( $($t:tt),* )) => {\r\n\t\t( $(read_value!($iter, $t)),* )\r\n\t};\r\n\r\n\t($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n\t\t(0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n\t};\r\n\r\n\t($iter:expr, chars) => {\r\n\t\tread_value!($iter, String).chars().collect::>()\r\n\t};\r\n\r\n\t($iter:expr, usize1) => {\r\n\t\tread_value!($iter, usize) - 1\r\n\t};\r\n\r\n\t($iter:expr, $t:ty) => {\r\n\t\t$iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n\t};\r\n}\r\n\r\n// end of input macros\r\n\r\nstruct Factorial {\r\n\tn: usize,\r\n\tm: i64,\r\n\tfactorial: Vec,\r\n\tinverse: Vec,\r\n\tinverse_factorial: Vec,\r\n}\r\n\r\nimpl Factorial {\r\n\tfn new(n: usize, m: i64) -> Factorial {\r\n\t\tlet mut factorial = vec![1; n + 1];\r\n\t\tlet mut inverse = vec![1; n + 1];\r\n\t\tlet mut inverse_factorial = vec![1; n + 1];\r\n\t\tfor i in 2..=n {\r\n\t\t\tfactorial[i] = (i as i64) * factorial[i - 1] % m;\r\n\t\t\tinverse[i] = ((m / (i as i64)) * -inverse[(m % (i as i64)) as usize] % m + m) % m;\r\n\t\t\tinverse_factorial[i] = inverse[i] * inverse_factorial[i - 1] % m;\r\n\t\t}\r\n\t\tFactorial {\r\n\t\t\tn,\r\n\t\t\tm,\r\n\t\t\tfactorial,\r\n\t\t\tinverse,\r\n\t\t\tinverse_factorial,\r\n\t\t}\r\n\t}\r\n\r\n\tfn c(&self, n: usize, k: usize) -> i64 {\r\n\t\tif n < k {\r\n\t\t\t0\r\n\t\t} else {\r\n\t\t\tassert!(k <= n && n <= self.n);\r\n\t\t\tself.factorial[n] * self.inverse_factorial[k] % self.m * self.inverse_factorial[n - k]\r\n\t\t\t\t% self.m\r\n\t\t}\r\n\t}\r\n\r\n\tfn catalan(&self, n: usize) -> i64 {\r\n\t\tassert!(2 * n <= self.n);\r\n\t\tself.c(2 * n, n) * self.inverse[n + 1] % self.m\r\n\t}\r\n}\r\n\r\n// start of solution\r\n\r\nconst MOD: i64 = 1_000_000_007;\r\n\r\nfn main() {\r\n\tinput! {\r\n\t n: usize, k: usize\r\n\t}\r\n\tlet data = Factorial::new(200_005, MOD);\r\n\tlet mut answer = 0;\r\n\tfor i in 0..=n.min(k) {\r\n\t answer = (answer + data.c(n, i)) % MOD;\r\n\t}\r\n\tprintln!(\"{}\", answer);\r\n}\r\n\r\n// end of solution", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "403f2eb47a2ebcb78fb773833b274693", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::{io::{BufRead, BufWriter, Write}, hash::Hash};\r\n#[allow(unused)]\r\nuse std::{{collections::*, mem::swap},cmp::Reverse};\r\n\r\nuse std::convert::TryInto;\r\n\r\npub struct Combi {\r\n fact: Vec,\r\n ifact: Vec,\r\n}\r\nimpl Combi {\r\n pub fn new(n:usize) -> Self{\r\n let mut fact = vec![0;n+1];\r\n fact[0]=1;\r\n for i in 0..n {\r\n fact[i+1] = fact[i]*(i+1)%MOD;\r\n }\r\n let mut ifact = vec![0;n+1];\r\n ifact[n] = Self::inv(fact[n]);\r\n for i in (0..n).rev() {\r\n ifact[i] = ifact[i+1]*(i+1)%MOD;\r\n }\r\n return Self { fact, ifact};\r\n }\r\n\r\n pub fn kperm>(&self,n:U,k:U) -> usize {\r\n let n = n.try_into().ok().expect(\"Unable to cast n to usize\");\r\n let k = k.try_into().ok().expect(\"Unable to cast k to usize\");\r\n if n < k {\r\n return 0;\r\n }\r\n return self.fact[n]*self.ifact[n-k]%MOD;\r\n }\r\n\r\n pub fn kcombi>(&self,n:U,k:U) -> usize {\r\n let n = n.try_into().ok().expect(\"Unable to cast n to usize\");\r\n let k = k.try_into().ok().expect(\"Unable to cast k to usize\");\r\n if n < k {\r\n return 0;\r\n }\r\n return self.fact[n]*self.ifact[k]%MOD*self.ifact[n-k]%MOD;\r\n }\r\n\r\n pub fn fact(&self) -> &Vec { &self.fact }\r\n pub fn ifact(&self) -> &Vec { &self.ifact }\r\n\r\n fn pow(val:usize, mut power: usize) -> usize {\r\n let mut square = val;\r\n let mut ret = 1;\r\n while 0 < power {\r\n if (power & 1) == 1{\r\n ret *= square;\r\n ret %= MOD;\r\n }\r\n square *= square;\r\n square %= MOD;\r\n power >>= 1;\r\n }\r\n return ret;\r\n }\r\n fn inv(val: usize) -> usize {\r\n return Self::pow(val, MOD - 2);\r\n }\r\n}\r\n\r\nimpl Default for Combi{\r\n fn default() -> Self {\r\n return Self::new(1_000_000);\r\n }\r\n}\r\n\r\n\r\nfn main() {\r\n let sin = std::io::stdin();\r\n let scan = &mut Scanner::new(sin.lock());\r\n let sout = std::io::stdout();\r\n let out = &mut BufWriter::new(sout.lock());\r\n solve_wrapper(scan, out, solve);\r\n}\r\n\r\n#[allow(unused)]\r\n#[macro_export]\r\nmacro_rules! logln {\r\n ($($arg:tt)*) => ({\r\n #[cfg(debug_assertions)]\r\n println!($($arg)*);\r\n })\r\n}\r\n\r\ntrait MapX {\r\n fn update_with V>(&mut self, key:K, get_new_value:F);\r\n}\r\nmacro_rules! update_with { () => {\r\n fn update_with V>(&mut self, key:K, get_new_value:F) {\r\n let v = self.entry(key).or_default();\r\n let nv = get_new_value(v);\r\n *v = nv;\r\n }\r\n} }\r\nimpl MapX for BTreeMap {\r\n update_with!();\r\n}\r\nimpl MapX for HashMap {\r\n update_with!();\r\n}\r\n\r\ntrait UsizeX {\r\n fn i64(self) -> i64;\r\n fn ssb(self,rhs:usize) -> usize;\r\n}\r\nimpl UsizeX for usize {\r\n fn i64(self) -> i64 { self as i64 }\r\n fn ssb(self,rhs:usize) -> usize { self.saturating_sub(rhs) }\r\n}\r\n\r\ntrait I64X {\r\n fn usize(self) -> usize; }\r\nimpl I64X for i64 {\r\n fn usize(self) -> usize { self as usize }\r\n}\r\n\r\npub struct Scanner {\r\n reader: R,\r\n buffer: Vec,\r\n}\r\nimpl Scanner {\r\n pub fn new(reader: R) -> Self {\r\n Self { reader, buffer: vec![] }\r\n }\r\n pub fn token(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n let mut input = String::new();\r\n self.reader.read_line(&mut input).expect(\"Failed read\");\r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n }\r\n }\r\n pub fn line(&mut self) -> Vec {\r\n if !self.buffer.is_empty() {\r\n panic!(\"Consume token buffer before read a line.\");\r\n }\r\n let mut input = String::new();\r\n self.reader.read_line(&mut input).expect(\"Failed read\");\r\n input.split_whitespace().map(|v| v.parse().ok().expect(\"Failed parse\")).collect()\r\n }\r\n pub fn line_withT>(&mut self, f: F) -> Vec {\r\n return self.line().iter().map(f).collect::>();\r\n }\r\n}\r\n\r\n#[cfg(test)]\r\nmod abc999x {\r\n use super::*;\r\n use std::io::Read;\r\n\r\n macro_rules! test_macro {\r\n ($name:ident,) => {\r\n #[test]\r\n fn $name() {\r\n let fn_name = stringify!($name);\r\n let test_no = fn_name.as_bytes().last().copied().unwrap() as char;\r\n let bname = env!(\"CARGO_BIN_NAME\");\r\n let fname = format!(\"src/contest/{}/in{}\",bname,test_no);\r\n let f = std::fs::File::open(fname);\r\n if f.is_err() {\r\n panic!(\"No input file\");\r\n }\r\n let mut f = f.unwrap();\r\n let mut inp = Vec::new();\r\n f.read_to_end(&mut inp).unwrap();\r\n let fname = format!(\"src/contest/{}/out{}\",bname,test_no);\r\n let f = std::fs::File::open(fname);\r\n let mut exp = Vec::new();\r\n if let Ok(mut f) = f {\r\n f.read_to_end(&mut exp).unwrap();\r\n }\r\n let exp = String::from_utf8_lossy(&exp);\r\n let out = &mut Vec::new();\r\n let scan = &mut Scanner::new(&*inp);\r\n solve_wrapper(scan, out, solve);\r\n let out = String::from_utf8_lossy(&out);\r\n assert_eq!(exp, out);\r\n }\r\n };\r\n ($name:ident, $($n:ident),*,) => {\r\n test_macro!($name,);\r\n test_macro!($($n),*,);\r\n };\r\n }\r\n\r\n test_macro!(\r\ntest1,\r\ntest2,\r\ntest3,\r\n);\r\n\r\n}\r\n\r\nfn solve_wrapper(scan: &mut Scanner, out: &mut W, mut solve: F)\r\n where B: BufRead, W: Write, F:FnMut(&mut Scanner, &mut W)\r\n {\r\n let t = 1;\r\n //let t = scan.token::();\r\n for _ in 0..t {\r\n solve(scan,out);\r\n }\r\n}\r\n\r\nconst MOD:usize = 1e9 as usize + 7;\r\n\r\nfn solve(scan: &mut Scanner, out: &mut impl Write) {\r\n let n = scan.token::();\r\n let k = scan.token::();\r\n let cmb = Combi::::new(n);\r\n cmb.kcombi(n,k);\r\n let mut ans = 0;\r\n for i in 0..(k.min(n)+1) {\r\n ans+=cmb.kcombi(n,i);\r\n ans%=MOD;\r\n }\r\n writeln!(out, \"{}\", ans).ok();\r\n}\r\n\r\n\r\n\r\n\r\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "1f6c4ebf14f434192ca566ddd8a02bbf", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "pub mod solution {\n\nuse std::cmp::min;\nuse crate::io::input::Input;\nuse crate::io::output::output;\nuse crate::{out, out_line};\n\nfn solve(input: &mut Input, _test_case: usize) {\n let (n, k) = input.read();\n let mut ans = 0;\n let mut fact = vec![0; n + 1];\n let mut inv = vec![0; n + 1];\n let mut invfact = vec![0; n + 1];\n inv[1] = 1;\n for i in 2..=n {\n inv[i] = mul(inv[(MOD % i as i32) as usize], MOD - MOD / i as i32);\n }\n fact[0] = 1;\n invfact[0] = 1;\n for i in 1..=n {\n fact[i] = mul(fact[i - 1], i as i32);\n invfact[i] = mul(invfact[i - 1], inv[i]);\n }\n for i in 0..=min(k, n) {\n add(&mut ans, c(n, i, &fact, &invfact));\n }\n out_line!(ans);\n}\n\nfn c(n: usize, k: usize, fact: &Vec, invfact: &Vec) -> i32 {\n mul(fact[n], mul(invfact[k], invfact[n - k]))\n}\n\nfn add(a: &mut i32, b: i32) {\n *a += b;\n if *a >= MOD {\n *a -= MOD;\n }\n}\n\nconst MOD: i32 = 1000000007;\n\nfn mul(a: i32, b: i32) -> i32 {\n (a as i64 * b as i64 % MOD as i64) as i32\n}\n\n\npub(crate) fn run(mut input: Input) -> bool {\n solve(&mut input, 1);\n output().flush();\n input.skip_whitespace();\n !input.peek().is_some()\n}\n\n\n}\npub mod io {\npub mod input {\nuse std::fmt::Debug;\nuse std::io::Read;\nuse std::marker::PhantomData;\nuse std::str::FromStr;\n\npub struct Input<'s> {\n input: &'s mut dyn Read,\n buf: Vec,\n at: usize,\n buf_read: usize,\n}\n\nimpl<'s> Input<'s> {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(input: &'s mut dyn Read) -> Self {\n Self {\n input,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn new_with_size(input: &'s mut dyn Read, buf_size: usize) -> Self {\n Self {\n input,\n buf: vec![0; buf_size],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn get(&mut self) -> Option {\n if self.refill_buffer() {\n let res = self.buf[self.at];\n self.at += 1;\n Some(res)\n } else {\n None\n }\n }\n\n pub fn peek(&mut self) -> Option {\n if self.refill_buffer() {\n Some(self.buf[self.at])\n } else {\n None\n }\n }\n\n pub fn skip_whitespace(&mut self) {\n while let Some(b) = self.peek() {\n if !char::from(b).is_whitespace() {\n return;\n }\n self.get();\n }\n }\n\n pub fn next_token(&mut self) -> Option> {\n self.skip_whitespace();\n let mut res = Vec::new();\n while let Some(c) = self.get() {\n if char::from(c).is_whitespace() {\n break;\n }\n res.push(c);\n }\n if res.is_empty() {\n None\n } else {\n Some(res)\n }\n }\n\n //noinspection RsSelfConvention\n pub fn is_exhausted(&mut self) -> bool {\n self.peek().is_none()\n }\n\n pub fn read(&mut self) -> T {\n T::read(self)\n }\n\n pub fn read_vec(&mut self, size: usize) -> Vec {\n let mut res = Vec::with_capacity(size);\n for _ in 0usize..size {\n res.push(self.read());\n }\n res\n }\n\n pub fn read_line(&mut self) -> String {\n let mut res = String::new();\n while let Some(c) = self.get() {\n if c == b'\\n' {\n break;\n }\n if c == b'\\r' {\n if self.peek() == Some(b'\\n') {\n self.get();\n }\n break;\n }\n res.push(c.into());\n }\n res\n }\n\n #[allow(clippy::should_implement_trait)]\n pub fn into_iter(self) -> InputIterator<'s, T> {\n InputIterator {\n input: self,\n phantom: Default::default(),\n }\n }\n\n fn read_integer(&mut self) -> T\n where\n ::Err: Debug,\n {\n let res = self.read_string();\n res.parse::().unwrap()\n }\n\n fn read_string(&mut self) -> String {\n match self.next_token() {\n None => {\n panic!(\"Input exhausted\");\n }\n Some(res) => unsafe { String::from_utf8_unchecked(res) },\n }\n }\n\n fn read_char(&mut self) -> char {\n self.skip_whitespace();\n self.get().unwrap().into()\n }\n\n fn read_float(&mut self) -> f64 {\n self.read_string().parse().unwrap()\n }\n\n fn refill_buffer(&mut self) -> bool {\n if self.at == self.buf_read {\n self.at = 0;\n self.buf_read = self.input.read(&mut self.buf).unwrap();\n self.buf_read != 0\n } else {\n true\n }\n }\n}\n\npub trait Readable {\n fn read(input: &mut Input) -> Self;\n}\n\nimpl Readable for String {\n fn read(input: &mut Input) -> Self {\n input.read_string()\n }\n}\n\nimpl Readable for char {\n fn read(input: &mut Input) -> Self {\n input.read_char()\n }\n}\n\nimpl Readable for f64 {\n fn read(input: &mut Input) -> Self {\n input.read_float()\n }\n}\n\nimpl Readable for Vec {\n fn read(input: &mut Input) -> Self {\n let size = input.read();\n input.read_vec(size)\n }\n}\n\npub struct InputIterator<'s, T: Readable> {\n input: Input<'s>,\n phantom: PhantomData,\n}\n\nimpl<'s, T: Readable> Iterator for InputIterator<'s, T> {\n type Item = T;\n\n fn next(&mut self) -> Option {\n self.input.skip_whitespace();\n self.input.peek().map(|_| self.input.read())\n }\n}\n\nmacro_rules! read_integer {\n ($t:ident) => {\n impl Readable for $t {\n fn read(input: &mut Input) -> Self {\n input.read_integer()\n }\n }\n };\n}\n\nread_integer!(i8);\nread_integer!(i16);\nread_integer!(i32);\nread_integer!(i64);\nread_integer!(i128);\nread_integer!(isize);\nread_integer!(u8);\nread_integer!(u16);\nread_integer!(u32);\nread_integer!(u64);\nread_integer!(u128);\nread_integer!(usize);\n\nmacro_rules! tuple_readable {\n ( $( $name:ident )+ ) => {\n impl<$($name: Readable), +> Readable for ($($name,)+) {\n fn read(input: &mut Input) -> Self {\n ($($name::read(input),)+)\n }\n }\n }\n}\n\ntuple_readable! {T}\ntuple_readable! {T U}\ntuple_readable! {T U V}\ntuple_readable! {T U V X}\ntuple_readable! {T U V X Y}\ntuple_readable! {T U V X Y Z}\ntuple_readable! {T U V X Y Z A}\ntuple_readable! {T U V X Y Z A B}\ntuple_readable! {T U V X Y Z A B C}\ntuple_readable! {T U V X Y Z A B C D}\ntuple_readable! {T U V X Y Z A B C D E}\ntuple_readable! {T U V X Y Z A B C D E F}\n}\npub mod output {\nuse std::io::Write;\n\npub struct Output {\n output: Box,\n buf: Vec,\n at: usize,\n auto_flush: bool,\n}\n\nimpl Output {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: false,\n }\n }\n\n pub fn new_with_auto_flush(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: true,\n }\n }\n\n pub fn flush(&mut self) {\n if self.at != 0 {\n self.output.write_all(&self.buf[..self.at]).unwrap();\n self.at = 0;\n self.output.flush().expect(\"Couldn't flush output\");\n }\n }\n\n pub fn print(&mut self, s: &T) {\n s.write(self);\n }\n\n pub fn put(&mut self, b: u8) {\n self.buf[self.at] = b;\n self.at += 1;\n if self.at == self.buf.len() {\n self.flush();\n }\n }\n\n pub fn maybe_flush(&mut self) {\n if self.auto_flush {\n self.flush();\n }\n }\n\n pub fn print_per_line(&mut self, arg: &[T]) {\n for i in arg {\n i.write(self);\n self.put(b'\\n');\n }\n }\n\n pub fn print_iter>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n\n pub fn print_iter_ref<'a, T: 'a + Writable, I: Iterator>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n}\n\nimpl Write for Output {\n fn write(&mut self, buf: &[u8]) -> std::io::Result {\n let mut start = 0usize;\n let mut rem = buf.len();\n while rem > 0 {\n let len = (self.buf.len() - self.at).min(rem);\n self.buf[self.at..self.at + len].copy_from_slice(&buf[start..start + len]);\n self.at += len;\n if self.at == self.buf.len() {\n self.flush();\n }\n start += len;\n rem -= len;\n }\n if self.auto_flush {\n self.flush();\n }\n Ok(buf.len())\n }\n\n fn flush(&mut self) -> std::io::Result<()> {\n self.flush();\n Ok(())\n }\n}\n\npub trait Writable {\n fn write(&self, output: &mut Output);\n}\n\nimpl Writable for &str {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for String {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for char {\n fn write(&self, output: &mut Output) {\n output.put(*self as u8);\n }\n}\n\nimpl Writable for [T] {\n fn write(&self, output: &mut Output) {\n output.print_iter_ref(self.iter());\n }\n}\n\nimpl Writable for Vec {\n fn write(&self, output: &mut Output) {\n self[..].write(output);\n }\n}\n\nmacro_rules! write_to_string {\n ($t:ident) => {\n impl Writable for $t {\n fn write(&self, output: &mut Output) {\n self.to_string().write(output);\n }\n }\n };\n}\n\nwrite_to_string!(u8);\nwrite_to_string!(u16);\nwrite_to_string!(u32);\nwrite_to_string!(u64);\nwrite_to_string!(u128);\nwrite_to_string!(usize);\nwrite_to_string!(i8);\nwrite_to_string!(i16);\nwrite_to_string!(i32);\nwrite_to_string!(i64);\nwrite_to_string!(i128);\nwrite_to_string!(isize);\nwrite_to_string!(f32);\nwrite_to_string!(f64);\n\nimpl Writable for (T, U) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n }\n}\n\nimpl Writable for (T, U, V) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n output.put(b' ');\n self.2.write(output);\n }\n}\n\npub static mut OUTPUT: Option = None;\n\npub fn output() -> &'static mut Output {\n unsafe {\n match &mut OUTPUT {\n None => {\n panic!(\"Panic\");\n }\n Some(output) => output,\n }\n }\n}\n\n#[macro_export]\nmacro_rules! out {\n ($first: expr $(,$args:expr )*) => {\n output().print(&$first);\n $(output().put(b' ');\n output().print(&$args);\n )*\n }\n}\n\n#[macro_export]\nmacro_rules! out_line {\n ($first: expr $(, $args:expr )* ) => {\n out!($first $(,$args)*);\n output().put(b'\\n');\n };\n () => {\n output().put(b'\\n');\n };\n}\n}\n}\nfn main() {\n let mut sin = std::io::stdin();\n let input = crate::io::input::Input::new(&mut sin);\n unsafe {\n crate::io::output::OUTPUT = Some(crate::io::output::Output::new(Box::new(std::io::stdout())));\n }\n crate::solution::run(input);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "4b4298903f5e78738d62d57841e0f621", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#[allow(unused_imports)]\nuse std::{\n cmp,\n collections::{BinaryHeap, HashMap, HashSet, VecDeque},\n hash::Hash,\n io::{self, BufWriter, Read, StdoutLock, Write},\n str::Lines,\n};\n\nconst MODVAL: u64 = 1e9 as u64 + 7;\n\n#[allow(unused_mut, unused_variables)]\nfn main() -> io::Result<()> {\n let mut input = String::new();\n io::stdin().lock().read_to_string(&mut input).unwrap();\n let mut input = input.lines();\n\n let out = io::stdout();\n let mut out = BufWriter::new(out.lock());\n\n let line = next_line_as_u64_vec(&mut input);\n let n = line[0];\n let k = line[1];\n\n let mut m = 1;\n let fact = FactorialsMod::new(n as usize, MODVAL);\n for k in 1..=cmp::min(n, k) {\n m += bi_coefficient_mod(n, k, &fact, MODVAL);\n }\n writeln!(out, \"{}\", m % MODVAL)?;\n\n Ok(())\n}\n\n#[allow(dead_code)]\nfn bi_coefficient_mod(n: u64, k: u64, fact: &FactorialsMod, modval: u64) -> u64 {\n if n == k {\n return 1;\n }\n let mut res = fact.get(n as usize).unwrap();\n res *= mod_inverse(fact.get(k as usize).unwrap(), modval);\n res %= modval;\n res *= mod_inverse(fact.get((n - k) as usize).unwrap(), modval);\n res %= modval;\n res\n}\n\n#[allow(dead_code)]\nfn pow_mod(a: u64, b: u64, modval: u64) -> u64 {\n let mut a = a % modval;\n if a == 0 {\n return 0;\n }\n let mut b = b;\n let mut res = 1u64;\n while b > 0 {\n if b & 1 != 0 {\n res *= a;\n res %= modval;\n b -= 1;\n }\n a *= a;\n a %= modval;\n b >>= 1;\n }\n res\n}\n\n#[allow(dead_code)]\nfn mod_inverse(a: u64, modval: u64) -> u64 {\n pow_mod(a, modval - 2, modval)\n}\n\n#[derive(Debug, Clone)]\nstruct FactorialsMod {\n numbers: Vec,\n}\n\n#[allow(dead_code)]\nimpl FactorialsMod {\n fn new(n: usize, modval: u64) -> Self {\n let mut numbers = vec![0; n + 1];\n let mut fac = 1u64;\n for i in 1..=n {\n fac *= i as u64;\n fac %= modval;\n numbers[i] = fac;\n }\n FactorialsMod { numbers }\n }\n\n fn get(&self, n: usize) -> Option {\n self.numbers.get(n).map(|&x| x)\n }\n}\n\n#[allow(dead_code)]\nfn next_line(input: &mut Lines) -> String {\n input.next().unwrap().to_string()\n}\n\n#[allow(dead_code)]\nfn next_line_as_u64(input: &mut Lines) -> u64 {\n let s = input.next().unwrap();\n let n: u64 = s.parse().unwrap();\n n\n}\n\n#[allow(dead_code)]\nfn next_line_as_i64(input: &mut Lines) -> i64 {\n let s = input.next().unwrap();\n let n: i64 = s.parse().unwrap();\n n\n}\n\n#[allow(dead_code)]\nfn next_line_as_string_vec(input: &mut Lines) -> Vec {\n let s = input.next().unwrap();\n let a = s.split(\" \").collect::>();\n a.iter().map(|&s| s.to_string()).collect()\n}\n\n#[allow(dead_code)]\nfn next_line_as_char_vec(input: &mut Lines) -> Vec {\n let s = input.next().unwrap();\n let a: Vec = s.chars().collect();\n a\n}\n\n#[allow(dead_code)]\nfn next_line_as_u64_vec(input: &mut Lines) -> Vec {\n let s = input.next().unwrap();\n let a: Vec = s.split(\" \").map(|s| s.parse().unwrap()).collect();\n a\n}\n\n#[allow(dead_code)]\nfn next_line_as_i64_vec(input: &mut Lines) -> Vec {\n let s = input.next().unwrap();\n let a: Vec = s.split(\" \").map(|s| s.parse().unwrap()).collect();\n a\n}\n\n#[allow(dead_code)]\nfn write_bool_answer(answer: bool, out: &mut BufWriter) {\n if answer {\n writeln!(out, \"yes\").unwrap();\n } else {\n writeln!(out, \"no\").unwrap();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "e518240eabf16d49e06013ce58b8f3ca", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin scanner -----------\n#[allow(unused_imports)]\nuse std::io::{BufWriter, stdin, stdout, Read, Write, Stdout};\nuse std::str::FromStr;\n\npub struct Scanner<'a> {\n it: std::str::SplitWhitespace<'a>,\n}\n#[allow(dead_code)]\nimpl<'a> Scanner<'a> {\n pub fn new(s: &'a String) -> Scanner<'a> {\n Scanner {\n it: s.split_whitespace(),\n }\n }\n pub fn next(&mut self) -> T {\n self.it.next().expect(\"read EOF\").parse::().ok().expect(\"parse failed\")\n }\n pub fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n pub fn next_n_index1(&mut self, n: usize) -> Vec {\n std::iter::once(T::default()).chain((0..n).map(|_| self.next())).collect()\n }\n pub fn next_chars(&mut self) -> Vec { self.it.next().unwrap().chars().collect() }\n pub fn next_bytes(&mut self) -> Vec { self.it.next().unwrap().bytes().collect() }\n pub fn next_digits(&mut self) -> Vec {\n self.it.next().unwrap().bytes().map(|c|c-C0).collect()\n }\n}\n// ---------- end scanner -------------\n\n\n// ---------- begin utils -------------\n#[allow(dead_code)]\nconst C0: u8 = '0' as u8;\n\n// ---------- end utils ---------------\n\n\n// ---------- begin debugger ----------\n#[cfg(feature = \"my_debug\")]\n#[macro_export]\nmacro_rules! debug {\n () => {\n eprintln!(\"[{}:{}]\", file!(), line!())\n };\n ($val:expr $(,)?) => {\n eprintln!(\"[{}:{}] {} = {:?}\", file!(), line!(), stringify!($val), &($val))\n };\n ($($val:expr),+ $(,)?) => {\n ($(debug!($val)),+,)\n };\n}\n\n#[cfg(not(feature = \"my_debug\"))]\n#[macro_export]\nmacro_rules! debug {\n ($( $args:expr ),*) => {}\n}\n// ---------- end debugger ------------\n\n\nfn main() {\n debug!(\"Ish: good luck and high rating!\");\n\n #[cfg(not(feature = \"my_debug\"))]\n let s = {\n let mut s = String::new();\n stdin().read_to_string(&mut s).unwrap();\n s\n };\n #[cfg(feature = \"my_debug\")]\n let s = std::fs::read_to_string(\"in.txt\").unwrap();\n\n let mut sc = Scanner::new(&s);\n let out = &mut BufWriter::new(stdout());\n\n // let cases: u32 = sc.next();\n let cases: u32 = 1;\n debug!(cases);\n for _case in 1..=cases { debug!(_case);\n run(&mut sc, out);\n }\n}\n\n\n/** Write your mind here.\n1234 -\n\u4e0d\u59a8\u5047\u8bbe\u90fd\u662f\u5de6\u8d62\n1\n1 3\n12 34\n3142\n\n1\n1 5\n1 3 5 7\n12 34 56 78\n\n\n1\n1 2\n1 3 2 4\n153\n\n1 \u4e00\u5b9a\u4e0d\u80fd\u548c\n\n\u4e8c\u5206\uff1f\n1\n1 3\n1 2 3 4\n15 26 37 48\n\n\n1\n1 2\n1 3 2 5\n14 36 27 58\n\n\u7b80\u5355\u7684\u8bf4\uff0c1 \u6709\u88ab\u6bcf\u4e2a\u5bf9\u624b\u66ff\u6362\u7684\u98ce\u9669\u3002\n\u5982\u679c k=1\uff0c\u7b54\u6848\u5c31\u662f n+1\uff0c\u56e0\u4e3a 1 \u53ef\u80fd\u88ab\u4e09\u4e2a\u5bf9\u624b\u66ff\u6362\uff0c\u4ece\u4e2d\u9009\u62e9\u6700\u83dc\u7684\u3002\n\n\u5982\u679c k=2 \u5462\uff0c \u53ef\u4ee5\u66ff\u6362\u4e24\u6b21\u3002\n\n1~16, k=1, ans=5\nk=2, \u53ef\u4ee5\u6362\u7684\u5c31\u662f\n\n1\n1 9\n1 5 9 d\n1 3 5 7 9 b d f\n1_ _+ _+ +8 _+ +c +e f0\n\n*\u53ef\u4ee5\u6362\u591a\u5c11\u4e2a\nk=0, 1\nk=1, n\u4e2a, 4\nk=2\uff0c1+2+..+n-1, 7\nk=3, 1\n\n\u5c42\n0: n\n1: 1, 2, 3, 4, .., n-1\n2:\n\nn^2 \u505a\u6cd5\u6709\u4e86\uff0c\u5c42\u6570\u8f6c\u79fb\u3002\n\n\u539f\u6570\u7ec4\n0 0 0 0 1 k=0, ans=1\n1 1 1 1 0 k=1, ans=4\n3 2 1 0 0 k=2, ans=7\n3 1 0 0 0 k=3, ans=8\n1 0 0 0 0 k=4, ans=8\n\nn=3\n\nans(n, k) = for i in 0..=k {\n C(n, i)\n}\n\n */\n\nstruct MathSolver {\n fac: Vec,\n}\nimpl MathSolver {\n const MOD: i64 = 1000000007;\n\n fn new(mx: usize) -> Self {\n let mut fac = vec![1i64; mx];\n for i in 1..mx {\n fac[i] = (fac[i-1] * i as i64) % Self::MOD;\n }\n Self { fac }\n }\n\n // solve ax+by=gcd(a,b)\n fn exgcd(a: i64, b: i64) -> (i64, i64) {\n if b == 0 {\n return (1, 0);\n }\n let (x, y) = Self::exgcd(b, a % b);\n (y, x - a / b * y)\n }\n\n fn normalize(a: i64) -> i64 {\n (a % Self::MOD + Self::MOD) % Self::MOD\n }\n\n // solve ax===1 (mod b)\n fn inv(&self, a: i64) -> i64{\n Self::normalize(Self::exgcd(a, Self::MOD).0)\n }\n\n fn c(&self, a: usize, b: usize) -> i64 {\n self.fac[a] * self.inv(self.fac[b] * self.fac[a-b] % Self::MOD) % Self::MOD\n }\n}\n\nfn run(sc: &mut Scanner, out: &mut BufWriter) {\n let n = sc.next::();\n let k = sc.next::();\n\n let solver = MathSolver::new(n+1);\n let mut ans = 0;\n for i in 0..=k.min(n) {\n ans += solver.c(n, i);\n ans %= 1_000_000_007;\n }\n\n\n // let ans = if arr == brr {\"YES\"} else {\"NO\"};\n\n // let ans = 1;\n // let mut ok = true;\n // let ans = if ok {\"Yes\"} else {\"No\"};\n writeln!(out, \"{ans}\").ok();\n // for ans in ans {\n // for num in ans { write!(out, \"{num}\").ok(); }\n // writeln!(out).ok();\n // }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "1cd83bdd415a0ba24f88c620130a7675", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_imports)]\n#[rustfmt::skip] mod writer {use std::fmt::Display;use std::io::{stdout, BufWriter, Error as IoError, Stdout, Write};#[derive(Debug)] pub struct Writer { writer: BufWriter, } #[derive(Debug, Clone)] pub struct Format<'a> { separator: &'a str, ending: &'a str, } impl<'a> Format<'a> { pub fn separator(self, separator: &'a str) -> Self { Self { separator, ..self } } pub fn ending(self, ending: &'a str) -> Self { Self { ending, ..self } } } impl Default for Format<'_> { fn default() -> Self { Format { separator: \" \", ending: \"\\n\", } } } impl Writer { pub fn stdout() -> Self { Self::new(stdout()) } } impl Writer { pub fn new(writer: W) -> Self { Self { writer: BufWriter::new(writer), } } pub fn write>(&mut self, val: T) -> Result<(), IoError> { self.write_with(val, &Format::default()) } pub fn write_with>(&mut self, val: T, fmt: &Format) -> Result<(), IoError> { val.write_to(&mut self.writer, fmt) } pub fn flush(&mut self) -> Result<(), IoError> { self.writer.flush() } } pub trait Writable { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError>;} #[non_exhaustive] pub struct Single;impl Writable for T { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError> { write!(w, \"{}{}\", self, fmt.ending) } } #[non_exhaustive] pub struct Many;impl Writable for I where I: Iterator, I::Item: Display, { fn write_to(mut self, w: &mut W, fmt: &Format) -> Result<(), IoError> { if let Some(x) = self.next() { write!(w, \"{}\", x)?;} else { return Ok(());} for x in self { write!(w, \"{}{}\", fmt.separator, x)?;} write!(w, \"{}\", fmt.ending) } } #[non_exhaustive] pub struct Slice;impl Writable for &[T] { fn write_to(self, w: &mut W, fmt: &Format) -> Result<(), IoError> { self.iter().write_to(w, fmt) } } #[macro_export] macro_rules! out { ($writer:expr, $val:expr) => { $writer.write($val).expect(\"failed to write token\");};($writer:expr, $val:expr, $($builder_name:ident = $value:expr),+) => { let mut fmt = Format::default();$( fmt = fmt.$builder_name($value);)+ $writer.write_with($val, &fmt).expect(\"failed to write token\");};} }\n#[rustfmt::skip] mod scanner {use std::fmt::Debug;use std::io::{stdin, BufReader, Bytes, Error as IoError, Read, Stdin};use std::str::{self, FromStr, Utf8Error};#[derive(Debug)] pub struct Scanner { bytes: Bytes>, buf: Vec, } pub trait Instructions { type Target;type Error;fn read_from(scanner: &mut Scanner) -> Result;} impl Instructions for T { type Target = T;type Error = ScanError;fn read_from(scanner: &mut Scanner) -> Result { scanner.read_token() } } #[derive(Debug)] pub enum ScanError { Io(IoError), Parse(T::Err, String), NonUtf8(Utf8Error, Vec), } impl Scanner { pub fn stdin() -> Self { Self::new(stdin()) } } impl Scanner { pub fn new(reader: R) -> Self { Self { bytes: BufReader::new(reader).bytes(), buf: Vec::new(), } } pub fn read_token(&mut self) -> Result> { debug_assert!(self.buf.is_empty());for b in &mut self.bytes { let b = b.map_err(ScanError::Io)?;if b.is_ascii_whitespace() { if self.buf.is_empty() { continue;} else { break;} } else { self.buf.push(b);} } match str::from_utf8(&self.buf) { Err(err) => Err(ScanError::NonUtf8(err, std::mem::take(&mut self.buf))), Ok(s) => { let ret = s.parse().map_err(|err| ScanError::Parse(err, s.to_owned()));self.buf.clear();ret } } } pub fn read(&mut self) -> Result { T::read_from(self) } } #[macro_use] pub mod macros { use super::*;use std::fmt::{self, Debug};use std::io::Read;use std::marker::PhantomData;use std::num::NonZeroUsize;use std::str::FromStr;pub struct UsizeM1(());impl Instructions for UsizeM1 { type Target = usize;type Error = ScanError;fn read_from(scanner: &mut Scanner) -> Result { Ok(scanner.read_token::()?.get() - 1) } } pub struct LenArray(PhantomData);impl Instructions for LenArray { type Target = Vec;type Error = LenArrayScanError;fn read_from(scanner: &mut Scanner) -> Result { let len = scanner .read_token::() .map_err(LenArrayScanError::Len)?;let mut arr = Vec::with_capacity(len);for i in 0..len { let elem = scanner .read_token::() .map_err(|e| LenArrayScanError::Data(i, e))?;arr.push(elem);} Ok(arr) } } pub enum LenArrayScanError { Len(ScanError), Data(usize, ScanError), } impl Debug for LenArrayScanError where T: Debug + FromStr, T::Err: Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::LenArrayScanError::*;match self { Len(e) => f.debug_tuple(\"Len\").field(e).finish(), Data(i, e) => f.debug_tuple(\"Data\").field(i).field(e).finish(), } } } #[macro_export] macro_rules! scan { (@scan 1 $scan:expr, $type:ty) => { $scan .read::<$type>() .expect(concat!(\"failed to read token of type \", stringify!($type))) };(@scan 2 $scan:expr, $type:ty, $n:expr) => { (0..$n) .map(|_| scan!(@scan 1 $scan, $type)) .collect::>() };(@accum ($scan:expr) () -> ($($body:tt)*)) => { ($($body)*) };(@accum ($scan:expr) ($type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 1 $scan, $type))) };(@accum ($scan:expr) ($type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 1 $scan, $type),)) };(@accum ($scan:expr) ($n:tt * $type:ty) -> ($($body:tt)*)) => { scan!(@accum ($scan) () -> ($($body)* scan!(@scan 2 $scan, $type, $n))) };(@accum ($scan:expr) ($n:tt * $type:ty, $($next:tt)*) -> ($($body:tt)*)) => { scan!(@accum ($scan) ($($next)*) -> ($($body)* scan!(@scan 2 $scan, $type, $n),)) };($scan:expr, $($arg:tt)+) => { scan!(@accum ($scan) ($($arg)+) -> ()) };} } }\n#[rustfmt::skip] mod util { use std::cmp::Reverse; pub trait IntoVec { fn into_vec(self) -> Vec;} #[non_exhaustive] pub struct Owned;impl IntoVec for I where I: Iterator, { fn into_vec(self) -> Vec { self.collect() } } #[non_exhaustive] pub struct Reference;impl<'a, I, T> IntoVec for I where I: Iterator, T: Clone + 'a, { fn into_vec(self) -> Vec { self.cloned().collect() } } pub trait Argmax { fn argmax(self) -> Option;fn argmin(self) -> Option;} impl Argmax for I where I: Iterator, I::Item: Ord, { fn argmax(self) -> Option { self.fold((0, None), |(i, mx), next| { if let Some((mx_i, mx_v)) = mx { if next.gt(&mx_v) { (i + 1, Some((i, next))) } else { (i + 1, Some((mx_i, mx_v))) } } else { (i + 1, Some((i, next))) } }) .1 .map(|x| x.0) } fn argmin(self) -> Option { self.map(Reverse).argmax() } } pub trait Sorted { fn sorted(self) -> Self;} impl Sorted for Vec where T: Ord, { fn sorted(mut self) -> Self { self.sort();self } } pub trait SortedBy { fn sorted_by(self, f: F) -> Self where F: FnMut(&T) -> K, K: Ord;} impl SortedBy for Vec { fn sorted_by(mut self, f: F) -> Self where F: FnMut(&T) -> K, K: Ord, { self.sort_by_key(f);self } } pub trait Choose { fn choose(self, a: T, b: T) -> T;fn choose_by(self, a: impl FnOnce() -> T, b: impl FnOnce() -> T) -> T;} impl Choose for bool { fn choose(self, a: T, b: T) -> T { if self { a } else { b } } fn choose_by(self, a: impl FnOnce() -> T, b: impl FnOnce() -> T) -> T { if self { a() } else { b() } } } #[macro_export] macro_rules! p { ( $( $x:expr ),* ) => { #[cfg(any(debug_assertions, debug_print))] { dbg!( $( & $x, )* );} };} pub fn fix(f: &dyn Fn(&dyn Fn(A) -> R, A) -> R) -> impl Fn(A) -> R + '_ { move |arg| f(&fix(&f), arg) } pub trait Assign { fn assign(&mut self, val: T);} impl Assign for Option { fn assign(&mut self, val: T) { assert!(self.is_none(), \".assign() called on Some variant\");*self = Some(val);} } }\n#[rustfmt::skip] mod prefix_sum {use std::{ fmt::{self, Debug, Formatter}, marker::PhantomData, ops::{Add, Bound, Range, RangeBounds, Sub}, };#[derive(Clone)] pub struct PrefixOp { fwd: F, inv: Option, marker: PhantomData T>, } impl PrefixOp where F: Fn(&T, &T) -> T, { pub fn new(op: F) -> Self { PrefixOp { fwd: op, inv: None, marker: PhantomData, } } } impl PrefixOp where F: Fn(&T, &T) -> T, I: Fn(&T, &T) -> T, { pub fn new_invertible(op: F, inverse: I) -> Self { PrefixOp { fwd: op, inv: Some(inverse), marker: PhantomData, } } } impl PrefixOp where F: Fn(&T, &T) -> T, I: Clone, { pub fn build(&self, mut arr: Vec) -> PrefixArray { for i in 1..arr.len() { arr[i] = (self.fwd)(&arr[i - 1], &arr[i]);} PrefixArray { pref: arr, fwd: PhantomData, inv: self.inv.clone(), } } } #[derive(Clone)] pub struct PrefixArray { pref: Vec, fwd: PhantomData, inv: Option, } impl PrefixArray { pub fn len(&self) -> usize { self.pref.len() } pub fn is_empty(&self) -> bool { self.pref.is_empty() } #[track_caller] fn verify_range_bounds(&self, range: impl RangeBounds) -> Range { let start = match range.start_bound() { Bound::Unbounded => 0, Bound::Included(&x) => x, Bound::Excluded(&x) => x + 1, };let end = match range.end_bound() { Bound::Unbounded => self.len(), Bound::Included(&x) => x + 1, Bound::Excluded(&x) => x, };assert!( start < end, \"range inverted: start >= end ({} >= {})\", start, end );assert!( end <= self.len(), \"range out of bounds: end > len ({} > {})\", end, self.len() );Range { start, end } } #[track_caller] pub fn query_prefix(&self, range: impl RangeBounds) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);assert!(start == 0, \"query start bound is non-zero: {} > 0\", start);self.pref[end - 1].clone() } } impl PrefixArray where I: Fn(&T, &T) -> T, { #[track_caller] pub fn query(&self, range: impl RangeBounds) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);if start == 0 { self.pref[end - 1].clone() } else { (self .inv .as_ref() .expect(\"range query is not supported on non-invertible operation\"))( &self.pref[end - 1], &self.pref[start - 1], ) } } } impl Debug for PrefixOp where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct(\"PrefixOp\").finish_non_exhaustive() } } impl Debug for PrefixArray where T: Debug, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct(\"PrefixArray\") .field(\"pref\", &self.pref) .finish_non_exhaustive() } } type NextFn = fn(&T, &T) -> T;pub struct PrefixSum(PhantomData);impl PrefixSum where T: Add + Sub + Clone, { pub fn op() -> PrefixOp, NextFn> { PrefixOp::new_invertible(|a, b| a.clone() + b.clone(), |b, a| b.clone() - a.clone()) } pub fn build(arr: Vec) -> PrefixArray, NextFn> { Self::op().build(arr) } } }\n#[rustfmt::skip] mod combinatorics {use crate::{num::Integer, number_theory::mod_mulinv};pub fn next_permutation(perm: &mut [T]) -> bool where T: Ord, { if perm.is_empty() { return false;} let i = match Iterator::zip(perm.iter(), perm[1..].iter()).rposition(|(x, y)| x < y) { None => { perm.reverse();return false;} Some(x) => x, };let j = perm .iter() .rposition(|x| &perm[i] < x) .expect(\"inconsistent Ord implementation\");perm.swap(i, j);perm[i + 1..].reverse();true } #[derive(Debug, Clone)] pub struct Factorials { m: N, fact: Vec, fact_inv: Vec, } impl Factorials where N: Integer + Clone, { #[inline] fn as_n(x: usize) -> N { N::from_usize(x).expect(\"inconsistent Integer implementation\") } #[inline] fn as_usize(x: &N) -> usize { N::as_usize(x).expect(\"inconsistent Integer implementation\") } #[track_caller] pub fn new(n: N, m: N) -> Self { let cap = n .as_usize() .and_then(|x| x.checked_add(1)) .expect(\"required capacity overflowed usize\");assert!(cap > 0, \"n must be non-negative\");let mut fact = Vec::with_capacity(cap);fact.push(N::one());let mut cur = N::one();for i in 1..cap { cur = (cur * Self::as_n(i)).imod(&m);fact.push(cur.clone());} let mut fact_inv = Vec::with_capacity(cap);let mut cur = mod_mulinv(fact[cap - 1].clone(), m.clone());for i in (0..cap).rev() { fact_inv.push(cur.clone());cur = (cur * Self::as_n(i)).imod(&m);} fact_inv.reverse();debug_assert_eq!(fact.len(), cap);debug_assert_eq!(fact_inv.len(), cap);Factorials { m, fact, fact_inv } } pub fn len(&self) -> usize { self.fact.len() } pub fn is_empty(&self) -> bool { false } pub fn n(&self) -> N { Self::as_n(self.fact.len() - 1) } #[track_caller] fn verify_n<'a>(&self, n: &'a N) -> &'a N { assert!( N::zero() <= *n && *n <= self.n(), \"n is outside precomputed range\" );n } #[track_caller] pub fn factorial(&self, n: &N) -> N { let n = self.verify_n(n);self.fact[Self::as_usize(n)].clone() } #[track_caller] pub fn factorial_inverse(&self, n: &N) -> N { let n = self.verify_n(n);self.fact_inv[Self::as_usize(n)].clone() } #[track_caller] pub fn choose(&self, n: N, k: N) -> N { self.verify_n(&n);assert!(k >= N::zero(), \"k is negative\");if k <= n { ((self.fact[Self::as_usize(&n)].clone() * self.fact_inv[Self::as_usize(&k)].clone()) .imod(&self.m) * self.fact_inv[Self::as_usize(&(n - k))].clone()) .imod(&self.m) } else { N::zero() } } } }\n#[rustfmt::skip] mod number_theory {use crate::num::Integer;use std::mem;pub fn gcd(mut a: N, mut b: N) -> N { while b != N::zero() { mem::swap(&mut a, &mut b);b = b.imod(&a);} a.iabs() } #[allow(clippy::many_single_char_names)] pub fn egcd(a: N, b: N) -> (N, N, N) { if b == N::zero() { ( a.iabs(), if a >= N::zero() { N::one() } else { N::zero() - N::one() }, N::zero(), ) } else { let (g, s, t) = egcd(b.clone(), a.imod(&b));(g, t.clone(), s - a.idiv(&b) * t) } } #[track_caller] pub fn mod_exp(a: N, mut b: N, m: N) -> N { let zero = N::zero();let one = N::one();let two = N::one() + N::one();assert!(m > zero, \"modulus must be positive\");if b < zero { return mod_exp(mod_mulinv(a, m.clone()), zero - b, m);} let mut x = N::one();let mut pwr = a;while b > N::zero() { if b.imod(&two) == one { x = (x * pwr.clone()).imod(&m);} pwr = (pwr.clone() * pwr).imod(&m);b = b.idiv(&two);} x } #[track_caller] pub fn mod_mulinv(a: N, m: N) -> N { let zero = N::zero();let one = N::one();assert!(m > zero, \"modulus must be positive\");let (g, s, _) = egcd(a, m.clone());assert!(g == one, \"multiplicative inverse does not exist\");s.imod(&m) } #[derive(Debug, Clone)] pub struct PrimeSieve { lowest_factor: Vec, primes: Vec, } impl PrimeSieve where N: Integer + Clone, { #[inline] fn as_n(x: usize) -> N { N::from_usize(x).expect(\"inconsistent Integer implementation\") } #[inline] fn as_usize(x: &N) -> usize { N::as_usize(x).expect(\"inconsistent Integer implementation\") } #[track_caller] pub fn new(n: N) -> Self { let cap = n .as_usize() .and_then(|x| x.checked_add(1)) .expect(\"capacity overflowed usize\");assert!(cap > 0, \"n must be non-negative\");let mut lowest_factor = vec![N::zero(); cap];let mut primes = vec![];for i in 2..cap { if lowest_factor[i] == N::zero() { lowest_factor[i] = Self::as_n(i);primes.push(Self::as_n(i));} let lowest_factor_i = lowest_factor[i].clone();for (p, p_usize) in primes .iter() .map(|p| (p, Self::as_usize(p))) .take_while(|(p, p_usize)| i * p_usize < cap && p <= &&lowest_factor_i) { lowest_factor[i * p_usize] = p.clone();} } PrimeSieve { lowest_factor, primes, } } pub fn len(&self) -> usize { self.lowest_factor.len() } pub fn is_empty(&self) -> bool { false } pub fn n(&self) -> N { Self::as_n(self.lowest_factor.len() - 1) } #[track_caller] pub fn is_prime(&self, x: &N) -> bool { assert!(*x >= N::zero(), \"x must be non-negative\");let n = self.n();if *x <= n { *x > N::zero() && self.lowest_factor[Self::as_usize(x)] == *x } else if *x <= n.clone() * n { for p in self.primes.iter() { if x.imod(p) == N::zero() { return false;} } true } else { panic!(\"unable to determine primality: x > n^2\");} } #[track_caller] pub fn lowest_factor(&self, x: &N) -> N { assert!(*x >= N::zero(), \"x must be non-negative\");let n = self.n();if *x <= n { self.lowest_factor[Self::as_usize(x)].clone() } else if *x <= n.clone() * n { for p in self .primes .iter() .take_while(|&p| p.clone() * p.clone() <= *x) { if x.imod(p) == N::zero() { return p.clone();} } x.clone() } else { panic!(\"unable to determine lowest factor: x > n^2\",) } } #[track_caller] pub fn factorize(&self, mut x: N) -> Vec { let n = self.n();assert!(x > N::zero(), \"cannot factorize non-positive numbers\");assert!(x <= n.clone() * n.clone(), \"unable to factorize: x > n^2\",);let mut factors = Vec::new();let x2 = x.clone();let mut primes = self .primes .iter() .take_while(|&p| p.clone() * p.clone() <= x2);while x > N::one() { if x <= n { let f = &self.lowest_factor[Self::as_usize(&x)];factors.push(f.clone());x = x.idiv(f);} else if let Some(p) = primes.next() { while x.imod(p) == N::zero() { factors.push(p.clone());x = x.idiv(p);} } else { factors.push(x);break;} } factors } } }\n#[rustfmt::skip] mod num {use std::convert::{TryFrom, TryInto};use std::ops::{Add, Div, Mul, Rem, Sub};pub trait Num: Ord + Add + Sub + Mul + Div + Rem + FromPrimitive + IntoPrimitive + Sized { fn zero() -> Self;fn one() -> Self;} pub trait FromPrimitive: Sized { fn from_u64(x: u64) -> Option;fn from_i64(x: i64) -> Option;fn from_usize(x: usize) -> Option { Self::from_u64(x as u64) } fn from_isize(x: isize) -> Option { Self::from_i64(x as i64) } } pub trait IntoPrimitive { fn as_u64(&self) -> Option;fn as_i64(&self) -> Option;fn as_usize(&self) -> Option { self.as_u64().and_then(|x| x.try_into().ok()) } fn as_isize(&self) -> Option { self.as_i64().and_then(|x| x.try_into().ok()) } } pub trait Integer: Num { fn idiv(&self, x: &Self) -> Self;fn imod(&self, x: &Self) -> Self;fn iabs(&self) -> Self;} macro_rules! generate_integer_impl_for_primitive { ($( ($ty:ty, $unsigned:tt) ),+) => { $( impl FromPrimitive for $ty { #[inline(always)] fn from_u64(x: u64) -> Option { <$ty>::try_from(x).ok() } #[inline(always)] fn from_i64(x: i64) -> Option { <$ty>::try_from(x).ok() } } impl IntoPrimitive for $ty { #[inline(always)] fn as_u64(&self) -> Option { u64::try_from(*self).ok() } #[inline(always)] fn as_i64(&self) -> Option { i64::try_from(*self).ok() } } impl Num for $ty { #[inline(always)] fn zero() -> Self { 0 } #[inline(always)] fn one() -> Self { 1 } } impl Integer for $ty { #[inline(always)] fn idiv(&self, x: &Self) -> Self { self.div_euclid(*x) } #[inline(always)] fn imod(&self, x: &Self) -> Self { self.rem_euclid(*x) } generate_iabs_impl!($unsigned);} )+ };} macro_rules! generate_iabs_impl { (true) => { #[inline(always)] fn iabs(&self) -> Self { *self } };(false) => { #[inline(always)] fn iabs(&self) -> Self { self.abs() } };} generate_integer_impl_for_primitive!( (u8, true), (u16, true), (u32, true), (u64, true), (u128, true), (usize, true), (i8, false), (i16, false), (i32, false), (i64, false), (i128, false), (isize, false) );}\n\nuse combinatorics::{next_permutation, Factorials};\nuse number_theory::{egcd, gcd, mod_exp, mod_mulinv, PrimeSieve};\nuse prefix_sum::{PrefixOp, PrefixSum};\nuse scanner::{\n macros::{LenArray, UsizeM1},\n Scanner,\n};\nuse util::{fix, Argmax, Assign, Choose, IntoVec, Sorted};\nuse writer::{Format, Writer};\n\nfn main() {\n let mut sc = Scanner::stdin();\n let mut wr = Writer::stdout();\n\n let (n, k) = scan!(sc, i64, i64);\n const MOD: i64 = 1_000_000_007;\n let fact = Factorials::new(n, MOD);\n let mut ans = 0;\n for i in 0..=i64::min(n, k) {\n ans = (ans + fact.choose(n, i)) % MOD;\n }\n out!(wr, ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "e57a10083968c95727d496737978d96d", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\r\n#![allow(unused_must_use)]\r\n#![allow(unused_macros)]\r\n#![allow(non_snake_case)]\r\n#![allow(clippy::too_many_arguments)]\r\n#![allow(clippy::many_single_char_names)]\r\n#![allow(clippy::needless_range_loop)]\r\n#![allow(clippy::comparison_chain)]\r\n\r\nuse std::cmp::{max, min, Reverse};\r\nuse std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};\r\nuse std::io::{self, prelude::*};\r\nuse std::str;\r\n\r\nfn solve(sc: &mut Scanner, wr: &mut W) {\r\n const MOD: i64 = 1_000_000_007;\r\n let n: i64 = sc.tok();\r\n let k: i64 = sc.tok();\r\n let mut cur = 1;\r\n let mut res = 1;\r\n for a in 1..=min(n, k) {\r\n cur = (cur * mod_inv(a, MOD)) % MOD;\r\n cur = (cur * (n - a + 1)) % MOD;\r\n res += cur;\r\n if res >= MOD {\r\n res -= MOD;\r\n }\r\n }\r\n writeln!(wr, \"{}\", res);\r\n}\r\n\r\n/// Returns x, y such that ax + by = gcd(a, b);\r\n/// Assumes a, b are >= 0\r\npub fn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\r\n let (mut x1, mut y1, mut z1) = (1i64, 0i64, a);\r\n let (mut x2, mut y2, mut z2) = (0i64, 1i64, b);\r\n while z2 > 0 {\r\n let k = z1 / z2;\r\n let (x3, y3, z3) = (x1 - k * x2, y1 - k * y2, z1 - k * z2);\r\n (x1, y1, z1) = (x2, y2, z2);\r\n (x2, y2, z2) = (x3, y3, z3);\r\n }\r\n (x1, y1, z1)\r\n}\r\n\r\n/// Finds the inverse of a mod m.\r\n/// Assumes they are relatively prime and m > 0\r\npub fn mod_inv(mut a: i64, m: i64) -> i64 {\r\n a %= m;\r\n if a < 0 {\r\n a += m;\r\n }\r\n let res = extended_euclid(a, m).0 % m;\r\n if res < 0 {\r\n res + m\r\n } else {\r\n res\r\n }\r\n}\r\n\r\nuse std::marker::PhantomData;\r\nmacro_rules! recursive_function {\r\n ($name: ident, $trait: ident, ($($type: ident $arg: ident,)*)) => {\r\n pub trait $trait<$($type, )*Output> {\r\n fn call(&mut self, $($arg: $type,)*) -> Output;\r\n }\r\n\r\n pub struct $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n f: F,\r\n $($arg: PhantomData<$type>,\r\n )*\r\n phantom_output: PhantomData,\r\n }\r\n\r\n impl $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n pub fn new(f: F) -> Self {\r\n Self {\r\n f,\r\n $($arg: Default::default(),\r\n )*\r\n phantom_output: Default::default(),\r\n }\r\n }\r\n }\r\n\r\n impl $trait<$($type, )*Output> for $name\r\n where\r\n F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output,\r\n {\r\n fn call(&mut self, $($arg: $type,)*) -> Output {\r\n let const_ptr = &self.f as *const F;\r\n let mut_ptr = const_ptr as *mut F;\r\n unsafe { (&mut *mut_ptr)(self, $($arg, )*) }\r\n }\r\n }\r\n }\r\n}\r\n\r\nrecursive_function!(RecursiveFunction0, Callable0, ());\r\nrecursive_function!(RecursiveFunction, Callable, (Arg arg,));\r\nrecursive_function!(RecursiveFunction2, Callable2, (Arg1 arg1, Arg2 arg2,));\r\nrecursive_function!(RecursiveFunction3, Callable3, (Arg1 arg1, Arg2 arg2, Arg3 arg3,));\r\nrecursive_function!(RecursiveFunction4, Callable4, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4,));\r\nrecursive_function!(RecursiveFunction5, Callable5, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5,));\r\nrecursive_function!(RecursiveFunction6, Callable6, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6,));\r\nrecursive_function!(RecursiveFunction7, Callable7, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7,));\r\nrecursive_function!(RecursiveFunction8, Callable8, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8,));\r\nrecursive_function!(RecursiveFunction9, Callable9, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9,));\r\n\r\n#[macro_export]\r\nmacro_rules! dbg{\r\n ($($a:expr),*) => {\r\n #[cfg(debug_assertions)]\r\n eprintln!(\r\n concat!(\"{}:{}:{}: \",$(stringify!($a), \" = {:?}, \"),*),\r\n file!(), line!(), column!(), $($a),*\r\n );\r\n #[cfg(not(debug_assertions))]\r\n {};\r\n }\r\n}\r\nstruct Scanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitWhitespace<'static>,\r\n}\r\nimpl Scanner {\r\n fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: vec![],\r\n buf_iter: \"\".split_whitespace(),\r\n }\r\n }\r\n fn tok(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_whitespace())\r\n }\r\n }\r\n }\r\n}\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let mut scan = Scanner::new(stdin.lock());\r\n let mut out = io::BufWriter::new(stdout.lock());\r\n solve(&mut scan, &mut out);\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "885a60823d3dabe4a1e4aa8305bc794e", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let friend_count = get_input_usize();\n let finger_count: usize = get_input().split_ascii_whitespace().map(|v| v.parse::().unwrap()).sum();\n\n let total_people = friend_count + 1;\n let position = finger_count % total_people;\n\n let res = vec![1,2,3,4,5].iter().fold(0, |res, next| {\n if (next + position) % total_people == 1 {\n res\n } else {\n res + 1\n }\n });\n\n println!(\"{}\", res);\n\n}\n\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer.trim().to_owned()\n}\n\nfn get_input_usize() -> usize {\n get_input().parse().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e8faed8e4452925b6e37037435b65086", "src_uid": "ff6b3fd358c758324c19a26283ab96a4", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_int() -> u16 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n let x = input.trim().parse::().unwrap();\n x\n}\n\nfn read_int_vec() -> Vec{\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"rFailed\");\n let vec = input.split_whitespace()\n .map(|i| i.parse::().expect(\"parse error\"))\n .collect::>();\n vec\n}\n\nfn main() {\n \n let x = read_int() + 1;\n let vec = read_int_vec();\n let sum: u16 = vec.iter().sum();\n\n let mut total = 0;\n let mut range = 1..6;\n loop {\n match range.next() {\n Some(i) => {\n // println!(\"also: ({}+{}) % {} = {}\", sum, i, x, (((sum+i) % x) + x)% x);\n if !((((sum+i) % x) + x) % x == 1){\n // println!(\"====\");\n total = total + 1;\n }\n },\n None => { break }\n }\n }\n println!(\"{}\", total);\n\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "f4cb2aa833cc626e9cf1c9732db61768", "src_uid": "ff6b3fd358c758324c19a26283ab96a4", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_num() -> i32 {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n i32::from_str(input.trim()).unwrap()\n}\n\nfn get_nums() -> Vec {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n input.trim()\n .split_whitespace()\n .map(|s| i32::from_str(s).unwrap())\n .collect::>()\n}\n\nfn main() {\n let n = get_num();\n let s = get_nums().iter().sum::();\n \n let mut c = 0;\n for i in 1..=5 {\n if (s + i - n - 2) % (n + 1) != 0 {\n c += 1;\n }\n }\n\n println!(\"{}\", c);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "7c3a9f3c1d9fd7b6eb4c468db1710dcc", "src_uid": "ff6b3fd358c758324c19a26283ab96a4", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::collections::{*};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\n \nfn main() {\n let mut scanner = Scanner::default();\n let n: u128 = scanner.next();\n let sum = (1..=n).fold(0u128, |acc, x| acc + scanner.next::());\n println![\"{:?}\", (1..=5).map(|x| sum + x).filter(|x| x % (n+1) != 1).count()];\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "05dc351621d5b799474267708542d082", "src_uid": "ff6b3fd358c758324c19a26283ab96a4", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io;\n use std::io::prelude::*;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let n: u64 = input.trim().parse().unwrap();\n\n let ans = n / 2 + 1;\n\n println!(\"{}\", ans)\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "b68d0d45bd4f6aef9ea82e89467ab25a", "src_uid": "5551742f6ab39fdac3930d866f439e3e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn main() {\n let stdin = io::stdin();\n let n : u64 = read_t(&stdin);\n let s = (n / 2) + 1;\n println!(\"{}\", s);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "0649a088fdab74db97deacc9e83e06e1", "src_uid": "5551742f6ab39fdac3930d866f439e3e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Read;\nuse std::collections::HashMap;\n\nfn main() {\n let mut stdin = String::new();\n io::stdin().read_to_string(&mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n }\n \n let n = get!(usize);\n let need = get!(u64);\n \n let mut costs = vec![0; n];\n \n for i in 0..n {\n costs[i] = get!(u64);\n }\n \n fn search(costs: &Vec, need: u64, memo: &mut HashMap) -> u64 {\n if let Some(p) = memo.get(&need) {\n return *p;\n }\n let mut best_payment = 0;\n for i in 0..costs.len() {\n let liters = 1 << i;\n if liters < need {\n let bottles = need / liters;\n let remains = need-bottles*liters;\n let payment = bottles*costs[i]; \n let payment = if remains > 0 {\n payment+search(costs, remains, memo)\n } else {\n payment\n };\n if payment < best_payment || best_payment == 0 {\n best_payment = payment;\n }\n } else {\n let payment = costs[i];\n if payment < best_payment || best_payment == 0 {\n best_payment = payment;\n }\n }\n }\n memo.insert(need, best_payment);\n best_payment\n }\n let best_payment = search(&costs, need, &mut HashMap::new());\n println!(\"{}\", best_payment);\n}", "lang_cluster": "Rust", "tags": ["greedy", "dp", "bitmasks"], "code_uid": "490da0e1deb47473fcea1796a6605770", "src_uid": "04ca137d0383c03944e3ce1c502c635b", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::mem;\nuse std::io;\nuse std::string;\nuse std::cmp::*;\nuse std::collections::*;\n\nfn load() -> Vec {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let vec: Vec<&str> = line.split(\" \").collect();\n let mut data : Vec = Vec::new();\n for i in vec {\n let el : i64 = i.trim().parse().unwrap();\n data.push(el);\n }\n data\n}\n\nfn main() {\n let s = load();\n let (a,b)=(s[0],s[1]);\n println!(\"{}\", (if min(a,b)%2==0 {\"Malvika\"}else{\"Akshat\"}));\n}\n// min, max\n// HashSet, insert, contains\n// Vec, len, sort\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c5471a7de70c4793dd0c107495e0b5d5", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_pair() -> (i32, i32) {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n let v = input.trim()\n .split_whitespace()\n .map(|s| i32::from_str(s).unwrap())\n .collect::>();\n\n (v[0], v[1])\n}\n\nfn main() {\n let (mut n, mut m) = get_pair();\n\n let mut curr = \"Malvika\";\n while n * m != 0 {\n n -= 1;\n m -=1 ;\n\n if curr == \"Akshat\" {\n curr = \"Malvika\";\n } else {\n curr = \"Akshat\";\n }\n }\n\n println!(\"{}\", curr);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3f67fba700dd69a26742d44d3d36f4e6", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! rt {\n ( $( $t: ty ),+ ) => ({\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut iter = s.split_whitespace();\n (\n $(\n iter.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n })\n}\n\nfn main() {\n let (n, m) = rt!(i32, i32);\n\n let x = std::cmp::min(n, m);\n\n if x % 2 == 0 {\n println!(\"Malvika\");\n } else {\n println!(\"Akshat\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "50ac72ab8299a445c542f403ca2946f8", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input_split() -> (usize, usize) {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let buf: Vec = buf\n .trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect();\n (buf[0], buf[1])\n}\n\nfn main() {\n let players = [\"Malvika\", \"Akshat\"];\n let (n, m) = input_split();\n println!(\"{}\", players[n.min(m) % 2]);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "60b207f5bda5804f7c4735578db017bb", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/451/A\nuse std::io;\n\nfn main() {\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let words: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let n = words[0];\n let m = words[1];\n\n let minima = std::cmp::min(n,m);\n \n if minima%2 == 0 {\n println!(\"Malvika\");\n } else {\n println!(\"Akshat\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "cd28b10dc81eb6be6235dccf1c712968", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let inputs: Vec = reads(sin);\n let m = inputs[0];\n let n = inputs[1];\n\n let x = std::cmp::min(m, n);\n\n let winner = if x % 2 == 0 { \"Malvika\" } else { \"Akshat\" };\n\n println!(\"{}\", winner);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3aff08ddb5245bb8ed67b8fbcdef8938", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::cmp;\n\nfn main() {\n let (n, m) = R!(u32, u32);\n println!(\"{}\", if cmp::min(n, m) % 2 == 0 { \"Malvika\" } else { \"Akshat\" });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1f8844d54d51a0c3bb5274c54aa7b955", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut line = String::new();\n stdin().read_line(&mut line).unwrap();\n\n let line: Vec = line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let ejemaximo = std::cmp::min(line[0], line[1]);\n\n println!(\n \"{}\",\n if ejemaximo % 2 == 0 {\n \"Malvika\"\n } else {\n \"Akshat\"\n }\n );\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f99cc7d5db51bd4dabca17541eae7868", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let mut sum = 1usize;\n let mut lastsum = 1usize;\n let mut level = 1usize;\n while sum <= n {\n level += 1;\n lastsum += level;\n sum += lastsum;\n }\n println!(\"{}\", level - 1);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9eb08c255d87f8fe360bd9feacddd562", "src_uid": "873a12edffc57a127fdfb1c65d43bdb0", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*input\n3\n*/\nfn main() {\n let mut input = format!(\"\");\n std::io::stdin().read_line(&mut input).expect(\"\");\n let mut input_num: i16 = input.trim().parse::().unwrap();\n let mut substractor: i16 = 0;\n let mut iter: i16 = 0;\n while input_num > 0 {\n iter = iter + 1;\n substractor = substractor + iter;\n input_num = input_num - substractor;\n if input_num < 0 {\n iter = iter - 1;\n }\n }\n println!(\"{}\", iter);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "84bed5affc092f64410a3473b2f27f47", "src_uid": "873a12edffc57a127fdfb1c65d43bdb0", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut n: u16 = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n };\n let (mut level, mut level_blocks) = (1, 1);\n while level_blocks <= n {\n n -= level_blocks;\n level += 1;\n level_blocks = level * (level + 1) / 2;\n }\n println!(\"{}\", level - 1);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7eff03293962ce35cbcaa156eb45fa48", "src_uid": "873a12edffc57a127fdfb1c65d43bdb0", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::mem;\nuse std::io;\nuse std::string;\nuse std::cmp::*;\nuse std::collections::*;\n\nfn load() -> Vec {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let vec: Vec<&str> = line.split(\" \").collect();\n let mut data : Vec = Vec::new();\n for i in vec {\n let el : i64 = i.trim().parse().unwrap();\n data.push(el);\n }\n data\n}\nfn maxv(v : &Vec) -> i64{\n let mut s=v[0];\n for i in v {s=max(s,*i);}\n return s;\n}\nfn minv(v : &Vec) -> i64{\n let mut s=v[0];\n for i in v {s=min(s,*i);}\n return s;\n}\n\nfn main() {\n let s = load()[0];\n let mut num = 0;\n let mut sum = 0;\n let mut last = 0;\n for i in 1..s+1 {\n num+=i;\n sum+=num;\n if sum > s {break;}\n last = i;\n }\n println!(\"{}\", last);\n}\n// min, max\n// HashSet, insert, contains\n// Vec, len, sort\n// primitive retype: i as f64\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "01747fb736c62220a3c3c33f065e5e61", "src_uid": "873a12edffc57a127fdfb1c65d43bdb0", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n\n let (n, ) = R!(usize);\n let mut c = 0;\n let mut v = 0;\n\n for i in 1.. {\n c += i;\n if c + v <= n {\n v += c;\n } else {\n println!(\"{}\", i - 1);\n break;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "61bf4b06b79c7fc3699fddec71a0a3ca", "src_uid": "873a12edffc57a127fdfb1c65d43bdb0", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn good(mut a: u32) -> bool {\n let mut sum = 0;\n while a != 0 {\n sum += a % 10;\n a /= 10;\n }\n return sum == 10;\n}\n\nfn solve(writer: &mut std::io::BufWriter) {\n let mut k = parse_line!(usize);\n let mut result = 0;\n while k > 0 {\n result += 1;\n if good(result) {\n k -= 1;\n }\n }\n writeln!(writer, \"{}\", result).unwrap();\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "binary search", "implementation", "number theory"], "code_uid": "e5c5d42ff5af14606294b0ca333a11a8", "src_uid": "0a98a6a15e553ce11cb468d3330fc86a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, Read, StdinLock};\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::collections::{HashSet, HashMap, BinaryHeap, VecDeque};\n#[allow(unused_imports)]\nuse std::vec::Vec;\n\n#[allow(dead_code)]\nconst INF: i32 = 1000_000_000;\n#[allow(dead_code)]\nconst INFLL: i64 = 1000_000_000_000_000_000;\n#[allow(dead_code)]\nconst EPS: f64 = 1.0e-10;\n#[allow(dead_code)]\nconst MOD: i32 = 1000_000_007;\n#[allow(dead_code)]\nconst MODLL: i64 = 1000_000_007;\n\nstruct Scanner<'a> {\n cin: StdinLock<'a>,\n}\n\n#[allow(dead_code)]\nimpl<'a> Scanner<'a> {\n fn new(cin: StdinLock<'a>) -> Scanner<'a> {\n Scanner {cin: cin}\n }\n fn read1(&mut self) -> Option {\n let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect::();\n token.parse::().ok()\n }\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\n\n\nfn main() {\n let cin = stdin();\n let cin = cin.lock();\n let mut sc = Scanner::new(cin);\n\n let k: usize = sc.read();\n let mut cnt = 0;\n for i in 0..1000_000_00 {\n let mut sum = 0;\n let mut x = i;\n while x > 0 {\n sum += x % 10;\n x /= 10;\n }\n if sum == 10 {\n cnt += 1;\n }\n\n if cnt == k {\n println!(\"{}\", i);\n break;\n }\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "dp", "binary search", "implementation", "number theory"], "code_uid": "923f88f6cc81cfddf4478c0a636aa76b", "src_uid": "0a98a6a15e553ce11cb468d3330fc86a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> Option {\n let stdin = std::io::stdin();\n let mut line = String::new();\n if stdin.read_line(&mut line).unwrap_or(0) > 0 {\n Some(line.trim().into())\n } else {\n None\n }\n}\n\nfn main() {\n let n: i32 = read_line().unwrap().parse().unwrap();\n fn sum_digits(mut n: i64) -> i32 {\n let mut sum = 0;\n while n > 0 {\n sum += (n % 10) as i32;\n n /= 10;\n }\n sum\n }\n let mut a = 19;\n let mut m = 0;\n loop {\n let sum = sum_digits(a);\n if sum == 10 {\n m += 1;\n if m == n {\n println!(\"{}\", a);\n break;\n }\n }\n if sum >= 10 {\n a += 10 - a % 10;\n } else {\n a += 1;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "binary search", "implementation", "number theory"], "code_uid": "938169207ce81b76acf1c5d2b0f0a698", "src_uid": "0a98a6a15e553ce11cb468d3330fc86a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let k = input.u();\n let sol = (1..).filter(|&a| {\n let mut b = a;\n let mut s = 0;\n while b > 0 {\n s += b % 10;\n b /= 10;\n }\n s == 10\n }).nth(k - 1).unwrap();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "binary search", "implementation", "number theory"], "code_uid": "03481eaabfc5c384d1e129ae375f9540", "src_uid": "0a98a6a15e553ce11cb468d3330fc86a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros, dead_code)]\nuse std::f64::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! dump{\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nconst INF: i64 = 0x3f3f3f3f3f3f3f3f;\nconst MOD: i64 = 1000000007;\nconst NOTHING: usize = std::usize::MAX;\nconst DX: [usize; 4] = [1, 0, std::usize::MAX, 0];\nconst DY: [usize; 4] = [0, 1, 0, std::usize::MAX];\n\nfn main() {\n let mut k: u64 = readln();\n let mut i = 0;\n while k > 0 {\n i += 1;\n let mut x = i;\n let mut s = 0;\n while x > 0 {\n s += x % 10;\n x /= 10;\n }\n if s == 10 {\n k -= 1;\n }\n }\n println!(\"{}\", i);\n}\n\ntrait Read {\n fn read(s: &str) -> Self;\n}\n\nfn readln() -> T {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n T::read(buf.trim_right())\n}\n\nmacro_rules! read_impl{\n ($($t:ty)*) => ($(\n impl Read for $t {\n fn read(s: &str) -> $t{\n s.parse().unwrap()\n }\n }\n )*)\n}\nread_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }\n\nimpl Read for String {\n fn read(s: &str) -> Self {\n s.to_string()\n }\n}\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.chars().collect()\n }\n}\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.split_whitespace().map(T::read).collect()\n }\n}\n\nimpl Read for (A, B) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]))\n }\n}\n\nimpl Read for (A, B, C) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))\n }\n}\n\nimpl Read for (A, B, C, D) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]), D::read(tokens[3]))\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "binary search", "implementation", "number theory"], "code_uid": "4c546ff093b92d22c9243821ce25f463", "src_uid": "0a98a6a15e553ce11cb468d3330fc86a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n\n let arr: Vec = input\n .split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect();\n\n if arr[1..].iter().min().unwrap() >= &arr[0] {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "68703425b07d875389d3985b85c1260a", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n\nuse std::io;\n\nmacro_rules! parse_line \n{\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nfn main() \n{\n let (n, m, k) = parse_line!(i32, i32, i32);\n\n if n <= m && n <= k\n {\n println!(\"Yes\");\n }\n else\n {\n println!(\"No\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a8c21a5f5d0e811020992e4488759bf5", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn main() {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).expect(\"input error\");\n let parsed = input_line.split_whitespace().map(|x| x.parse::().expect(\"parse error\"));\n let inputs: Vec = parsed.collect();\n let (n, m, k) = (inputs[0], inputs[1], inputs[2]);\n if n <= cmp::min(m, k) {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7c8d4897fad9d352d600251a04493bb2", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nmacro_rules! parse {\n () => {{\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap(); // don't do this\n s.trim().parse().unwrap() // don't do this\n }};\n}\n\nfn main() {\n let s: String = parse!();\n let input: Vec = s.split_whitespace().map(|f| f.trim()).map(|s| s.parse().unwrap()).collect();\n let participants = input[0];\n let pens = input[1];\n let notebooks = input[2];\n if participants > pens || participants > notebooks{\n println!(\"No\");\n }else {\n println!(\"Yes\");\n }\n}\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "161333ffaf7ed52a7ae534460655333a", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_string() -> String {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string)\n .ok()\n .expect(\"\u041e\u0448\u0438\u0431\u043a\u0430 \u0447\u0442\u0435\u043d\u0438\u044f \u0432\u0432\u043e\u0434\u0430\");\n return string;\n}\n\nfn main() {\n let data = read_string();\n let mut iter = data.split_whitespace();\n let n = iter.next().unwrap().parse::().expect(\"\u041e\u0448\u0438\u0431\u043a\u0430\");\n let m = iter.next().unwrap().parse::().expect(\"\u041e\u0448\u0438\u0431\u043a\u0430\");\n let k = iter.next().unwrap().parse::().expect(\"\u041e\u0448\u0438\u0431\u043a\u0430\");\n if n <= m && n <= k{\n println!(\"{}\", \"YES\");\n }else {\n println!(\"{}\", \"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d514ae8cc1e56301a5e3b3ca2bd236e1", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let m: usize = scan.next();\n let k: usize = scan.next();\n println!(\"{}\", if m >= n && k >= n { \"Yes\" } else { \"No\" });\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "bbba5a5236143a9e16592e962be07c26", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut no = String::new();\n std::io::stdin().read_line(&mut no)\n .expect(\"Error input\");\n let input = no.trim().split(' ').collect::>();\n let n: usize = input[0].parse().unwrap();\n let m: usize = input[1].parse().unwrap();\n let k: usize = input[2].parse().unwrap();\n\n let out = match n <= m && n <= k { true => \"YES\", _ => \"No\"};\n\n print!(\"{}\", out);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c3a12c406ee853568932519e0998a30c", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(a,b,c = input.i());\n if a <= b.min(c) {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d7cb4ff2e163f6de840c248687fee8fa", "src_uid": "6cd07298b23cc6ce994bb1811b9629c4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let p1: i32 = scan.token();\n let p2: i32 = scan.token();\n let p3: i32 = scan.token();\n let p4: i32 = scan.token();\n let a: i32 = scan.token();\n let b: i32 = scan.token();\n let ans = 0.max(b.min(p1.min(p2).min(p3).min(p4) - 1) - a.max(0) + 1);\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "6bbee09b619bdf6dd0f031445133509b", "src_uid": "63b9dc70e6ad83d89a487ffebe007b0a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 998_244_353;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n assert!(self.0 > 0);\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ----------\n// ---------- begin Matrix ----------\n#[allow(dead_code)]\nmod matrix {\n use std::ops::{Add, Mul};\n pub trait SemiRing: Add + Mul + Copy {\n fn zero() -> Self;\n fn one() -> Self;\n }\n pub const SIZE: usize = 2;\n #[derive(Clone)]\n pub struct SquareMatrix {\n buf: [[T; SIZE]; SIZE],\n }\n impl SquareMatrix {\n pub fn zero() -> Self {\n let z = T::zero();\n SquareMatrix {\n buf: [[z; SIZE]; SIZE],\n }\n }\n pub fn identity() -> Self {\n let mut m = Self::zero();\n for i in 0..SIZE {\n m.buf[i][i] = T::one();\n }\n m\n }\n pub fn set_at(&mut self, i: usize, j: usize, v: T) {\n self.buf[i][j] = v;\n }\n pub fn get_at(&self, i: usize, j: usize) -> T {\n self.buf[i][j]\n }\n pub fn matmul(&self, rhs: &Self) -> Self {\n let mut res = Self::zero();\n for (x, a) in res.buf.iter_mut().zip(self.buf.iter()) {\n for (a, b) in a.iter().zip(rhs.buf.iter()) {\n for (x, b) in x.iter_mut().zip(b.iter()) {\n *x = *x + *a * *b;\n }\n }\n }\n res\n }\n pub fn matadd(&self, rhs: &Self) -> Self {\n let mut c = Self::zero();\n for (c, (a, b)) in c.buf.iter_mut().zip(self.buf.iter().zip(rhs.buf.iter())) {\n for (c, (a, b)) in c.iter_mut().zip(a.iter().zip(b.iter())) {\n *c = *a + *b;\n }\n }\n c\n }\n pub fn matpow(&self, mut n: usize) -> Self {\n let mut t = Self::identity();\n let mut s = self.clone();\n while n > 0 {\n if n & 1 == 1 {\n t = t.matmul(&s);\n }\n s = s.matmul(&s);\n n >>= 1;\n }\n t\n }\n }\n}\n// ---------- end Matrix ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nuse matrix::*;\nuse std::io::Write;\n\nimpl SemiRing for ModInt {\n fn zero() -> Self {\n ModInt::zero()\n }\n fn one() -> Self {\n ModInt::one()\n }\n}\n\nfn run() {\n input! {\n h: usize,\n w: usize,\n l: u32,\n r: u32,\n }\n let d = r - l + 1;\n let x = ModInt(d / 2);\n let y = ModInt(d) - x;\n let mut mat = SquareMatrix::::zero();\n mat.set_at(0, 0, y);\n mat.set_at(1, 1, y);\n mat.set_at(0, 1, x);\n mat.set_at(1, 0, x);\n let p = mat.matpow(h);\n let q = p.matpow(w);\n let a = q.get_at(0, 0);\n let b = q.get_at(1, 0);\n let mut ans = a;\n if h % 2 == 1 && w % 2 == 1 {\n ans += b;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "constructive algorithms", "combinatorics"], "code_uid": "486b893dbfa18a1b4abbab15913199c5", "src_uid": "ded299fa1cd010822c60f2389a3ba1a3", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn vvb(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n\tfn graph(&mut self, n: usize, m: usize) -> Vec> {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e\n\t}\n\tfn graph_w(&mut self, n: usize, m: usize) -> Vec> where T::Err: Debug {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e\n\t}\n}\n//------------------- End rusT }}}\n\n// Field (mod prime) {{{\nmod field {\n\tuse std::ops::*;\n\t#[allow(dead_code)] pub const Z0: Field = Field(0);\n\t#[allow(dead_code)] pub const Z1: Field = Field(1);\n\tconst P5: i32 = 998244353;\n\tconst P6: i64 = P5 as i64;\n\t#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(i32);\n\t#[allow(dead_code)] impl Field {\n\t\tpub fn new>(a: T) -> Self { Self(Self::cv(a)) }\n\t\tpub fn new_unchecked(a: i32) -> Self { Self(a) }\n\t\tfn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n\t\tfn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n\t\tfn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n\t\tpub fn inv(self) -> Self { self.pow(P5-2) }\n\t\tpub fn pow>(self, b: T) -> Self {\n\t\t\tlet b = b.into(); if b == 0 { Self(1) } else {\n\t\t\t\tlet mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res\n\t\t\t}\n\t\t}\n\t}\n\timpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\n\timpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\n\timpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\n\timpl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}\n\timpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\n\timpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\n\timpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\n\timpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\n\timpl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }\n\tuse std::fmt::{Display, Formatter, Result};\n\timpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n}\n#[allow(unused_imports)] use field::{Field, Field as Z, Z0, Z1};\n//}}}\n// Square Matrix (Field) {{{\ntype MatT = Field;\nconst MAT_T_0: MatT = Z0;\nconst MAT_T_1: MatT = Z1;\n#[derive(Debug,Clone)] struct Mat { n: usize, a: Vec }\n#[allow(dead_code)] impl Mat {\n\tfn new(n:usize)->Self{Self{n,a:vec![MAT_T_0;n*n]}}\n\tfn diag(n:usize,v:MatT)->Self{let mut m=Self::new(n);let mut p=0;for _ in 0..n{m.a[p]=v;p+=n+1;}m}\n\tfn pow(&self,n:u64)->Self{if n==0{Self::diag(self.n,MAT_T_1)}else{let mut t=self.pow(n/2);t*=t.clone();if n%2==1{t*=self.clone();}t}}\n\tfn range(&self,r:Range,c:Range)->Vec>{if r.startMatT{self.a[r*self.n+c]}\n\tfn at_mut<'a>(&'a mut self,r:usize,c:usize)->&'a mut MatT{&mut self.a[r*self.n+c]}//'\n}\nimpl Mul for Mat{type Output=Self;fn mul(self,o:Self)->Self::Output{assert!(self.n==o.n);let n=self.n;let mut res=Self::new(n);\n\tfor ii in(0..n).map(|i|i*n){for j in 0..n{let mut t=MAT_T_0;let mut kk=j;for k in 0..n{t+=self.a[ii+k]*o.a[kk];kk+=n;}res.a[ii+j]=t;}}res}}\nimpl Add for Mat{type Output=Self;fn add(mut self,o:Self)->Self{self+=o;self}}\nimpl Sub for Mat{type Output=Self;fn sub(mut self,o:Self)->Self{self-=o;self}}\nimpl MulAssign for Mat{fn mul_assign(&mut self,a:Self){*self=self.clone()*a;}}\nimpl AddAssign for Mat{fn add_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x+=y;}} }\nimpl SubAssign for Mat{fn sub_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x-=y;}} }\nimpl PartialEq for Mat{fn eq(&self,o:&Self)->bool{self.n==o.n&&self.a==o.a}}impl Eq for Mat{}\n// }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tl!(n,m,l,r = rin.l());\n\tlet sol = if n*m % 2 == 1 {\n\t\tZ::new(r-l+1).pow(n*m)\n\t} else {\n\t\tlet b = (n*m+1)/2;\n\t\tlet w = n*m/2;\n\t\tlet o = Z::new((r+1)/2 - l/2);\n\t\tlet e = Z::new(r/2 - (l-1)/2);\n\t\tlet mut mat = Mat::new(2);\n\t\t*mat.at_mut(0,0) = e;\n\t\t*mat.at_mut(0,1) = o;\n\t\t*mat.at_mut(1,0) = o;\n\t\t*mat.at_mut(1,1) = e;\n\t\tlet bm = mat.pow(b as u64);\n\t\tlet bw = mat.pow(w as u64);\n\t\tbm.at(0,1) * bw.at(0,1) + bm.at(1,1) * bw.at(1,1)\n\t};\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "constructive algorithms", "combinatorics"], "code_uid": "4e326fa95e905734df64f2eef8402364", "src_uid": "ded299fa1cd010822c60f2389a3ba1a3", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused)]\nmacro_rules! debug {\n ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());\n}\n#[allow(unused)]\nmacro_rules! debugln {\n ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());\n}\n\n/// Verified by https://atcoder.jp/contests/arc093/submissions/3968098\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData }\n impl ModInt {\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n pub fn pow(self, mut e: i64) -> Self {\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl>> Add for ModInt {\n type Output = Self;\n fn add(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Sub for ModInt {\n type Output = Self;\n fn sub(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Mul for ModInt {\n type Output = Self;\n fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }\n }\n impl>> AddAssign for ModInt {\n fn add_assign(&mut self, other: T) { *self = *self + other; }\n }\n impl>> SubAssign for ModInt {\n fn sub_assign(&mut self, other: T) { *self = *self - other; }\n }\n impl>> MulAssign for ModInt {\n fn mul_assign(&mut self, other: T) { *self = *self * other; }\n }\n impl Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self { ModInt::new(0) - self }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n let (mut a, mut b, _) = red(self.x, M::m());\n if b < 0 {\n a = -a;\n b = -b;\n }\n write!(f, \"{}/{}\", a, b)\n }\n }\n impl From for ModInt {\n fn from(x: i64) -> Self { Self::new(x) }\n }\n // Finds the simplest fraction x/y congruent to r mod p.\n // The return value (x, y, z) satisfies x = y * r + z * p.\n fn red(r: i64, p: i64) -> (i64, i64, i64) {\n if r.abs() <= 10000 {\n return (r, 1, 0);\n }\n let mut nxt_r = p % r;\n let mut q = p / r;\n if 2 * nxt_r >= r {\n nxt_r -= r;\n q += 1;\n }\n if 2 * nxt_r <= -r {\n nxt_r += r;\n q -= 1;\n }\n let (x, z, y) = red(nxt_r, r);\n (x, y - q * z, z)\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998_244_353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n input!(n: i64, m: i64, l: i64, r: i64);\n let a = (n * m + 1) / 2;\n let b = n * m - a;\n let d = r / 2 - (l - 1) / 2;\n let c = r - l + 1 - d;\n if a != b {\n puts!(\"{}\\n\", ModInt::new(c + d).pow(n * m));\n return;\n }\n let diff = ModInt::new(d) - ModInt::new(c);\n puts!(\"{}\\n\",\n (ModInt::new(c + d).pow(n * m) + diff.pow(n * m))\n * ModInt::new(2).inv());\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "constructive algorithms", "combinatorics"], "code_uid": "cc560d8a00ff2f1052c5c8e26b7e7fe1", "src_uid": "ded299fa1cd010822c60f2389a3ba1a3", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn div_and_ceil(n1: i32, n2: i32) -> i32 {\n if n1 % n2 == 0 {\n n1 / n2\n } else {\n n1 / n2 + 1\n }\n}\n\nfn main() {\n let count = readln!(i32);\n let width = (count as f64).sqrt() as i32;\n println!(\"{}\", width + div_and_ceil(count, width));\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "binary search"], "code_uid": "95921075f09beae6cf92b15e60306a25", "src_uid": "eb8212aec951f8f69b084446da73eaf7", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n// use proconio::input;\nuse std::cmp::Ordering::*;\nuse std::collections::{BTreeMap, BTreeSet};\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\nmacro_rules! answer {\n ($out:ident, $ans:expr) => {\n writeln!($out, \"{}\", $ans)\n };\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let n: i64 = scan.token();\n\n let sqrt = (1..=n).take_while(|x| x * x <= n).last().unwrap();\n\n answer!(out, sqrt + (n + sqrt - 1) / sqrt)\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Mostly copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse [Scanner]\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\n// aka #![feature(bool_to_option)]\ntrait BoolThen {\n fn then_(self, f: impl FnOnce() -> T) -> Option;\n}\n\nimpl BoolThen for bool {\n fn then_(self, f: impl FnOnce() -> T) -> Option {\n if self {\n Some(f())\n } else {\n None\n }\n }\n}\n\ntrait BoolToYes {\n fn yes(self) -> &'static str;\n}\n\nimpl BoolToYes for bool {\n fn yes(self) -> &'static str {\n if self {\n \"YES\"\n } else {\n \"NO\"\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "binary search"], "code_uid": "f91c263c4785a57025437032912a45ce", "src_uid": "eb8212aec951f8f69b084446da73eaf7", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_i32() -> i32 {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.trim().parse().unwrap()\n}\n\nfn main() {\n let n = read_i32();\n let mut a = 0;\n let mut b = 0;\n while a * b < n {\n if a == b {\n a += 1;\n } else {\n b += 1;\n }\n }\n println!(\"{}\", a + b);\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "binary search"], "code_uid": "9e46de1caa4f4f84f6e7542f25461492", "src_uid": "eb8212aec951f8f69b084446da73eaf7", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, StdoutLock, Write};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_macros)]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n#[allow(dead_code)]\npub fn with_bufwriter) -> ()>(f: F) {\n let out = stdout();\n let writer = BufWriter::new(out.lock());\n f(writer)\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) } ; }\n#[allow(dead_code)]\nfn main() {\n input!{\n n: u64,\n }\n let mut i = 1;\n while i <= 31623 {\n if i * i == n {\n println!(\"{}\", i * 2);\n return;\n }\n if i * i > n {\n if n <= i * (i - 1) {\n println!(\"{}\", i * 2 - 1);\n } else {\n println!(\"{}\", i * 2);\n }\n return;\n }\n i += 1;\n }\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "binary search"], "code_uid": "506edfb1e44fccff32f2b35052f7f21e", "src_uid": "eb8212aec951f8f69b084446da73eaf7", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let s: u32 = buffer.trim().parse().expect(\"invalid input\");\n\n println!(\"{}\", if s == 2 { 2 } else { 1 });\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "f5fc195feed3517832fbec7e5ba6cb82", "src_uid": "c30b372a9cc0df4948dca48ef4c5d80d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cell::RefCell;\nuse std::io::{self, Read};\nuse std::iter::FromIterator;\n\n#[allow(dead_code)]\nstruct Source {\n chars: Box>,\n}\n\n#[allow(dead_code)]\nimpl Source {\n fn next_chr(&mut self) -> char {\n self.chars\n .by_ref()\n .skip_while(|c| char::is_whitespace(*c))\n .next()\n .expect(\"eof\")\n }\n\n fn next_str(&mut self) -> String {\n let it = self\n .chars\n .by_ref()\n .skip_while(|c| char::is_whitespace(*c))\n .take_while(|c| !char::is_whitespace(*c));\n let s = String::from_iter(it);\n if s.is_empty() {\n panic!(\"eof\")\n } else {\n s\n }\n }\n\n fn from_stdin() -> Self {\n let mut data = String::new();\n io::stdin().read_to_string(&mut data).expect(\"Input error\");\n Self::from_str(&data)\n }\n\n fn from_str(s: &str) -> Self {\n let data = String::from(s);\n let chars = data.chars().collect::>().into_iter();\n Source {\n chars: Box::new(chars),\n }\n }\n}\n\nthread_local!(static SRC: RefCell = RefCell::new(Source::from_stdin()));\n\n#[allow(unused_macros)]\nmacro_rules! input {\n ($($elem:tt)*) => {\n input_inner!(SRC, $($elem)*)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($src:expr) => {};\n ($src:expr,) => {};\n ($src:expr, $var:ident : mut $ty:tt $($rest:tt)*) => {\n let mut $var = $src.with(|src| {\n let mut src = src.borrow_mut();\n parse!(src, $ty)\n });\n input_inner!($src $($rest)*)\n };\n ($src:expr, $var:ident : $ty:tt $($rest:tt)*) => {\n let $var = $src.with(|src| {\n let mut src = src.borrow_mut();\n parse!(src, $ty)\n });\n input_inner!($src $($rest)*)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse {\n ($src:expr, ( $($ty:tt),* )) => {\n ( $(parse!($src,$ty)),* )\n };\n ($src:expr, char) => {\n $src.next_chr()\n };\n ($src:expr, [ $ty:tt; $len:expr ]) => {\n (0..$len).map(|_| parse!($src,$ty)).collect::>()\n };\n ($src:expr, $ty:tt) => {\n parse_str!($src,$ty)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_str {\n ($src:expr, chars) => {\n $src.next_str().chars().collect::>()\n };\n ($src:expr, $ty:ty) => {\n $src.next_str().parse::<$ty>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! { n: mut u32 }\n\n if n > 2 {\n println!(\"1\")\n } else {\n println!(\"{}\", n)\n }\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "be6034fe802b68fc079ae963ba45f9f8", "src_uid": "c30b372a9cc0df4948dca48ef4c5d80d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\nuse std::fs;\n\nfn main() {\n let stdin = io::stdin();\n let line = stdin.lock()\n .lines()\n .next()\n .expect(\"there was no next line\")\n .expect(\"the line could not be read\");\n\n let numbers: Vec<_> = line.split(\" \").collect();\n let v: i32 = numbers[0].parse().unwrap();\n// let b: i32 = numbers[1].parse().unwrap();\n\n println!(\"{}\", if v == 2 {2} else {1});\n}\n\n//fn main() {\n// let mut line = String::new();\n// let stdin = io::stdin();\n// stdin.lock().read_line(&mut line).expect(\"Could not read line\");\n// println!(\"{}\", line)\n//}\n\n/*\nfn main() {\n let stdin = io::stdin();\n let lines: Vec = stdin.lock().lines().map(|x| x.unwrap()).collect();\n\n let line = &lines[0];\n\n// let data = fs::read_to_string(\"test\").expect(\"Unable to read file\");\n// println!(\"{}\", data);\n\n\n let numbers: Vec<_> = line.split(\" \").collect();\n let a: i32 = numbers[0].parse().unwrap();\n let b: i32 = numbers[1].parse().unwrap();\n\n println!(\"{}\", a + b);\n}\n\n*/", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "4778bd5f26a50082e362418d6b179271", "src_uid": "c30b372a9cc0df4948dca48ef4c5d80d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\nimpl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt((val % MOD as usize) as u32)\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n assert!(self.0 > 0);\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let n: u32 = it.next().unwrap().parse().unwrap();\n let k: usize = it.next().unwrap().parse().unwrap();\n let mut is_prime = vec![true; k + 1];\n for i in 2.. {\n if i * i > k {\n break;\n }\n if is_prime[i] {\n let mut j = i * i;\n while let Some(p) = is_prime.get_mut(j) {\n *p = false;\n j += i;\n }\n }\n }\n let mut mobius = vec![ModInt::one(); k + 1];\n for (i, p) in is_prime.into_iter().enumerate().skip(2) {\n if !p {\n continue;\n }\n let mut j = i;\n while let Some(x) = mobius.get_mut(j) {\n *x = -*x;\n j += i;\n }\n let k = i.saturating_mul(i);\n let mut j = k;\n while let Some(x) = mobius.get_mut(j) {\n *x = ModInt::zero();\n j += k;\n }\n }\n let pow: Vec = (0..=k).map(|k| ModInt::from(k).pow(n)).collect();\n let mut imos = vec![ModInt::zero(); 2 * k + 1];\n for (i, v) in mobius.into_iter().enumerate().skip(2) {\n if v.0 == 0 {\n continue;\n }\n for (x, &pow) in pow.iter().enumerate().skip(1) {\n if x * i > k {\n break;\n }\n let v = v * pow;\n let l = x * i;\n let r = (x + 1) * i;\n imos[l] += v;\n imos[r] -= v;\n }\n }\n let mut ans = ModInt::zero();\n for i in 1..=k {\n imos[i] = imos[i] + imos[i - 1];\n let way = ModInt::from(i).pow(n) + imos[i];\n ans += ModInt::new(way.0 ^ i as u32);\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "97ff4cab45123375274a597d5d6f7bea", "src_uid": "122c08aa91c9a9d6a151ee6e3d0662fa", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n/// Verified by: https://atcoder.jp/contests/pakencamp-2018-day3/submissions/3878249\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy + Clone { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData<*const M> }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < M::m());\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt::new_internal(self.x * other.x % M::m())\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new_internal(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 { sum += cur; }\n cur += cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self { self.mul_fast(other) }\n }\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Self) { *self = *self + other; }\n }\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Self) { *self = *self - other; }\n }\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, other: Self) { *self = *self * other; }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 1_000_000_007;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\nmod pollard_rho {\n use std::collections::HashMap;\n /// binary gcd\n pub fn gcd(mut x: i64, mut y: i64) -> i64 {\n if y == 0 { return x; }\n if x == 0 { return y; }\n let mut sh = 0;\n while ((x | y) & 1) == 0 {\n x >>= 1; y >>= 1; sh += 1;\n }\n while (x & 1) == 0 { x >>= 1; }\n while y != 0 {\n while (y & 1) == 0 { y >>= 1; }\n if x > y { let t = x; x = y; y = t; }\n y -= x;\n }\n x << sh\n }\n\n fn add_mod(x: i64, y: i64, n: i64) -> i64 {\n let z = x + y;\n if z >= n { z - n } else { z }\n }\n\n fn mul_mod(x: i64, mut y: i64, n: i64) -> i64 {\n assert!(x >= 0);\n assert!(x < n);\n let mut sum = 0;\n let mut cur = x;\n while y > 0 {\n if (y & 1) == 1 {\n sum = add_mod(sum, cur, n);\n }\n cur = add_mod(cur, cur, n);\n y >>= 1;\n }\n sum\n }\n\n fn mod_pow(x: i64, mut e: i64, n: i64) -> i64 {\n let mut prod = if n == 1 { 0 } else { 1 };\n let mut cur = x % n;\n while e > 0 {\n if (e & 1) == 1 {\n prod = mul_mod(prod, cur, n);\n }\n cur = mul_mod(cur, cur, n);\n e >>= 1;\n }\n prod\n }\n\n pub fn is_prime(n: i64) -> bool {\n if n <= 1 { return false; }\n let small = [2, 3, 5, 7, 11, 13];\n if small.iter().any(|&u| u == n) { return true; }\n if small.iter().any(|&u| n % u == 0) { return false; }\n let mut d = n - 1;\n let mut e = 0;\n while (d & 1) == 0 {\n d >>= 1;\n e += 1;\n }\n let a = [2, 325, 9375, 28178, 450775, 9780504, 1795265022];\n a.iter().all(|&a| {\n if a >= n { return true; }\n let mut x = mod_pow(a, d, n);\n if x == 1 { return true; }\n for _ in 0 .. e {\n if x == n - 1 {\n return true;\n }\n x = mul_mod(x, x, n);\n if x == 1 { return false; }\n }\n x == 1\n })\n }\n\n fn pollard_rho(n: i64, c: &mut i64) -> i64 {\n if n % 2 == 0 { return 2; }\n loop {\n let mut x: i64 = 2;\n let mut y = 2;\n let mut d = 1;\n let cc = *c;\n let f = |i| add_mod(mul_mod(i, i, n), cc, n);\n while d == 1 {\n x = f(x);\n y = f(f(y));\n d = gcd((x - y).abs(), n);\n }\n if d == n {\n *c += 1;\n continue;\n }\n return d;\n }\n }\n\n /// Outputs (p, e) in p's ascending order.\n pub fn factorize(x: i64) -> Vec<(i64, usize)> {\n if x <= 1 {\n return Vec::new();\n }\n let mut hm = HashMap::new();\n let mut pool = vec![x];\n let mut c = 1;\n while let Some(u) = pool.pop() {\n if is_prime(u) {\n *hm.entry(u).or_insert(0) += 1;\n continue;\n }\n let p = pollard_rho(u, &mut c);\n pool.push(p);\n pool.push(u / p);\n }\n let mut v: Vec<_> = hm.into_iter().collect();\n v.sort();\n v\n }\n} // mod pollard_rho\n\nuse pollard_rho::*;\n\nfn calc(p: i64, e: usize, k: usize) -> ModInt {\n let mut dp = vec![vec![ModInt::new(0); e + 1]; k + 1];\n dp[0][e] = ModInt::new(1);\n let mut inv = vec![ModInt::new(0); e + 2];\n for i in 1 .. e + 2 {\n inv[i] = ModInt::new(i as i64).inv();\n }\n for i in 0 .. k {\n let mut accum = ModInt::new(0);\n for j in (0 .. e + 1).rev() {\n accum += dp[i][j] * inv[j + 1];\n dp[i + 1][j] = accum;\n }\n }\n let mut tot = ModInt::new(0);\n let mut cur = ModInt::new(1);\n let p = ModInt::new(p);\n for i in 0 .. e + 1 {\n tot += dp[k][i] * cur;\n cur *= p;\n }\n tot\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: i64,\n k: usize,\n }\n let fac = factorize(n);\n let mut prod = ModInt::new(1);\n for (p, e) in fac {\n prod *= calc(p, e, k);\n }\n puts!(\"{}\\n\", prod);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "probabilities", "number theory"], "code_uid": "0dfdb0a2236c3dadbd0fc94dba81f231", "src_uid": "dc466d9c24b7dcb37c0e99337b4124d2", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap,BTreeSet};\n#[allow(unused_imports)]\nuse std::ops::*;\n#[allow(unused_imports)]\nuse std::collections::BinaryHeap;\n\n#[allow(unused_macros)]\nmacro_rules! ite {\n ($c:expr, $t:expr, $f:expr) => {{\n if $c { $t } else { $f }\n }};\n}\n\n// ref: tanakh \n// diff: using Parser\n#[macro_export]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut parser = Parser::from_str($s);\n input_inner!{parser, $($r)*}\n };\n (parser = $parser:ident, $($r:tt)*) => {\n input_inner!{$parser, $($r)*}\n };\n (new_stdin_parser = $parser:ident, $($r:tt)*) => {\n let stdin = std::io::stdin();\n let reader = std::io::BufReader::new(stdin.lock());\n let mut $parser = Parser::new(reader);\n input_inner!{$parser, $($r)*}\n };\n ($($r:tt)*) => {\n input!{new_stdin_parser = parser, $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! input_inner {\n ($parser:ident) => {};\n ($parser:ident, ) => {};\n ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($parser, $t);\n input_inner!{$parser $($r)*}\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($parser:ident, ( $($t:tt),* )) => {\n ( $(read_value!($parser, $t)),* )\n };\n ($parser:ident, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($parser, $t)).collect::>()\n };\n ($parser:ident, chars) => {\n read_value!($parser, String).chars().collect::>()\n };\n ($parser:ident, usize1) => {\n read_value!($parser, usize) - 1\n };\n ($parser:ident, $t:ty) => {\n $parser.next::<$t>().expect(\"Parse error\")\n };\n}\n\nfn prime_factorization(n: i64) -> Vec<(i64,usize)> {\n let mut res = vec![];\n let mut x = n;\n let mut i = 2;\n while i * i <= x {\n let mut count = 0;\n while x % i == 0 {\n count += 1;\n x /= i;\n }\n if count != 0 {\n res.push((i, count));\n }\n i += 1;\n }\n if x != 1 {\n res.push((x,1));\n }\n res\n}\n\nfn dfs(ps: &Vec<(i64,usize)>, table: &Vec>, i: usize, x: i64, prob: Mod) -> Mod {\n if i == ps.len() {\n return prob * Mod::new(x as u64);\n }\n let mut res = Mod::new(0);\n for k in 0..ps[i].1+1 {\n res += dfs(ps, table, i+1, x * ps[i].0.pow(k as u32), prob * table[i][k]);\n }\n res\n}\n\nfn main() {\n input! {\n n: i64,\n m: u64,\n }\n let ps = prime_factorization(n);\n\n let mut inv_table = vec![Mod::new(1), Mod::new(1)];\n for i in 2..1000 {\n inv_table.push(Mod::new(1) / Mod::new(i));\n }\n\n let mut table = vec![];\n for &(p,count) in &ps {\n let mut dp = vec![Mod::new(0); count+1];\n dp[count] = Mod::new(1);\n for _ in 0..m {\n let mut dp2 = vec![Mod::new(0); count+1];\n for j in 0..count+1 {\n for k in 0..j+1 {\n // dp2[k] += dp[j] / Mod((j+1) as u64);\n dp2[k] += dp[j] * inv_table[j+1];\n }\n }\n dp = dp2;\n }\n table.push(dp);\n }\n\n let res = dfs(&ps, &table, 0, 1, Mod::new(1));\n println!(\"{}\", res.0);\n}\n\nuse std::ops::*;\n\nconst MOD : u64 = 1_000_000_007;\n#[derive(Clone,Copy,PartialEq,Debug)]\npub struct Mod (pub u64);\n\nimpl Mod {\n pub fn new(x: u64) -> Mod {\n Mod(x % MOD)\n }\n pub fn pow(self, n: u64) -> Mod {\n if n == 0 {\n return Mod(1);\n }\n let t = self.pow(n/2);\n if n % 2 == 0 {\n t * t\n }\n else {\n t * t * self\n }\n }\n}\n\nimpl Add for Mod {\n type Output = Self;\n fn add(self, rhs: Self) -> Self::Output {\n Mod((self.0 + rhs.0) % MOD)\n }\n}\n\nimpl AddAssign for Mod {\n fn add_assign(&mut self, rhs: Self) {\n *self = *self + rhs;\n }\n}\n\nimpl Sub for Mod {\n type Output = Self;\n fn sub(self, rhs: Self) -> Self::Output {\n Mod((self.0 + MOD - rhs.0 % MOD) % MOD)\n }\n}\n\nimpl SubAssign for Mod {\n fn sub_assign(&mut self, rhs: Self) {\n *self = *self - rhs;\n }\n}\n\nimpl Neg for Mod {\n type Output = Mod;\n fn neg(self) -> Mod {\n Mod(MOD - self.0)\n }\n}\n\nimpl Mul for Mod {\n type Output = Self;\n fn mul(self, rhs: Self) -> Self::Output {\n Mod((self.0 % MOD) * (rhs.0 % MOD) % MOD)\n }\n}\n\nimpl MulAssign for Mod {\n fn mul_assign(&mut self, rhs: Self) {\n *self = *self * rhs;\n }\n}\n\nimpl Div for Mod {\n type Output = Self;\n fn div(self, rhs: Self) -> Self::Output {\n if rhs.0 == 0 {\n loop {}\n }\n assert!(rhs.0 != 0);\n self * rhs.pow(MOD-2)\n }\n}\n\nuse std::io::BufRead;\nuse std::io;\nuse std::str;\n\n// ref: tatsuya6502 \n// ref: wariuni \n// diff: using std::io::BufRead::fill_buf()\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\n\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\n\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len,complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n (len, buf2[len-1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n }\n else {\n self.update_buf();\n }\n }\n }\n}\n\nuse std::fmt::Display;\n#[allow(dead_code)]\nfn write_vec(xs: &Vec) {\n if xs.len() == 0 {\n println!();\n return;\n }\n print!(\"{}\", xs[0]);\n for i in 1..xs.len() {\n print!(\" {}\", xs[i]);\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "probabilities", "number theory"], "code_uid": "4840fdd97afd46a93d5b034158297b9e", "src_uid": "dc466d9c24b7dcb37c0e99337b4124d2", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\nuse std::io::stdin;\n\nconst MOD: u128 = 1000000007;\n\nfn get_vals(count: usize) -> Vec where\n T: FromStr,\n ::Err: std::fmt::Debug {\n let mut val = String::new();\n stdin().read_line(&mut val).expect(\"Failed to read line\");\n val.split_whitespace()\n .map(|x|\n x.parse::().expect(\"Failed to parse value\"))\n .take(count).collect()\n}\n\npub fn main() {\n let mut ins = get_vals::(2);\n let (n, k) = (ins.remove(0), ins.remove(0));\n let mut dp = vec![vec![0 as u128; k]; n];\n for x in dp[0].iter_mut() {\n *x = 1;\n }\n for i in dp.iter_mut() {\n i[0] = 1;\n }\n for i in 1..dp.len() {\n let facs = factor((i as u64) + 1);\n for j in 1..dp[i].len() {\n dp[i][j] = (&facs).into_iter()\n .map(|x| dp[(*x as usize) - 1][j - 1])\n .sum::() % MOD;\n }\n }\n // for i in &dp {\n // for j in i {\n // print!(\"{0: <10}\", *j)\n // }\n // println!()\n // }\n let ans: u128 = dp.iter().map(|x| x[k - 1]).sum();\n println!(\"{}\", ans % MOD)\n}\n\npub fn factor(input: u64) -> Vec {\n let mut vector = vec![];\n\n let mut i = 1;\n while i * i <= input {\n if input % i == 0 {\n vector.push(i);\n if i != input / i {\n vector.push(input / i);\n }\n }\n i += 1;\n }\n\n vector\n}", "lang_cluster": "Rust", "tags": ["dp", "combinatorics", "number theory"], "code_uid": "de19fb9fdc974a6f68ba92ceba2cff60", "src_uid": "c8cbd155d9f20563d37537ef68dde5aa", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// CodeForces 414b Rust Solution\n// (from CF 414b Solution with ruby)\n\nuse std::io;\n\nfn main() {\n let stdin = io::stdin();\n let mut line = String::new();\n let modulo = 1_000_000_000 + 7;\n if let Ok(_) = stdin.read_line(&mut line) {\n let words = line.split_whitespace();\n let parsed: Vec = words.map( |s| s.parse::().unwrap() ).collect();\n let n = parsed[0];\n let k = parsed[1];\n let mut dp:Vec> = vec![vec![0; n + 1usize]; k + 1usize];\n \n for j in 1..=n {\n dp[1][j] = 1;\n }\n \n for i in 2..=k {\n for j in 1..=n {\n let mut l = j;\n while l <= n {\n dp[i][l] = (dp[i][l] + dp[i-1][j])%modulo;\n l += j;\n }\n }\n }\n\n //println!(\"{:?}\", dp);\n let mut sum: i64 = 0i64;\n for value in &dp[k] {\n sum = (sum + value)%modulo;\n }\n\n println!(\"{}\", sum);\n }\n}\n\n// # coding: utf-8\n// # Good sequence\uc758 \uae38\uc774\ub294 k, \uc22b\uc790 \uc81c\ud55c\uc740 n\uae4c\uc9c0\n// # 1\ubd80\ud130 n\uae4c\uc9c0 \uac10\uc18c \uc5c6\ub294 \ubc29\ud5a5\uc73c\ub85c (\uc99d\uac00 or \uac19\uc74c)\uc73c\ub85c \ub9cc\ub4e4\uc5b4\uc9c0\ub294 Good seq\uc758 \uc218\n// # Good seq\uc5d0\uc11c\ub294 \uc774\uc804 \uc22b\uc790\uac00 \ub2e4\uc74c\uc22b\uc790\ub97c \ub098\ub220\ub3c4 \uc798 \ub5a8\uc5b4\uc9c4\ub2e4\n// # \ubb38\uc81c \uc774\ud574\ub97c \uc81c\ub300\ub85c \ud558\uace0 \uc2dc\uc791\ud569\uc2dc\ub2e4.\n// # \uc5ec\uae30\ub294 1\ub85c \ub05d\ub098\ub3c4 \ub418\uace0 2\ub85c \ub05d\ub098\ub3c4 \ub418\uace0 n\uc73c\ub85c \ub05d\ub098\ub3c4 \ub428\n// # \uc989 \ubc14\ub2e5\ubd80\ud130 \ubaa8\ub4e0 \uacbd\uc6b0\uac00 \ub098\uc640\uc57c\ud55c\ub2e4.\n// # n = 3, k = 3 \uc5d0\uc11c \ud55c\ubc88 \ud2b8\ub9ac \ubd84\uae30\ub97c \ubd10\ubcf4\uba74\n// # R\n// # 1 2 3\n// # 1 2 3 2 3\n// # \uaf34\ub85c \ubc18\ubcf5 \ub41c\ub2e4. \uc774 \ud574\ubc95\uc740 CF 414b\uc758 \uae30\uc874 \uc815\ub2f5\uacfc\ub3c4 \ub3d9\uc77c\ud568\n// # (1,1) (1,2), (1,3) (2,2), (3,3) total 5 tuples.\n// # \uc774 \uac1c\uc218\ub294 tree\uc758 k depth\uc5d0\uc11c\uc758 child \uc218\ub97c \uad6c\ud558\ub294 \uac83\uacfc \ub3d9\uc77c\ud558\ub2e4.\n// # child\uc5d0\uc11c 1 2 3 \uc774 \uac01\uac01 \uba87\ud68c \ub098\uc624\ub294\uc9c0 \uce74\uc6b4\ud2b8 \ud55c\ub2e4\uba74 \ucda9\ubd84\ud560 \uac83 \uac19\uc74c\n// #\n// # \uc544 \uadfc\ub370 \uc790\uafb8 \ud0c0\uc784\uc544\uc6c3\ub098\uc11c \ub488\uc9c8 \uac83 \uac19\ub124\uc5ec\n\n// # << \uc774 \ubb38\uc81c\ub294 Ruby\uc758 \ud37c\ud3ec\uba3c\uc2a4 \ubb38\uc81c\ub85c \uc77c\ub2e8 \uc81c\ucd9c \uc911\ub2e8\ud569\ub2c8\ub2e4. >>\n\n// n, k = gets.split.map(&:to_i)\n// MODULO_BASE = 10 ** 9 + 7\n// dpcounters = []\n// init = Array.new(n + 1) { 1 } # k = 1\uc5d0\uc11c\ub294 \uac01 \ud558\ub098\uc529\n// init[0] = 0 # \ub2f9\uc5f0\ud788 0\uc774\uc8e0\n// dpcounters << init\n\n// for a in 2..k\n// sub_dpcounter = Array.new(n + 1) { 0 }\n// for b in 1..n\n// c = b\n// while c <= n\n// sub_dpcounter[c] = (sub_dpcounter[c] + dpcounters.last[b]) % MODULO_BASE\n// c += b\n// end\n// end\n// dpcounters << sub_dpcounter\n// end\n\n// puts dpcounters.last.inject { |sum, n| (sum + n) % MODULO_BASE }\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics", "number theory"], "code_uid": "bc9c49e89c637e1d6aa5896f7a4ef91d", "src_uid": "c8cbd155d9f20563d37537ef68dde5aa", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const MOD: usize = 1000000007;\n\n\nfn count_good_sequences(n: usize, k: usize) -> usize {\n let mut d: Vec> = vec![vec![0; n + 1]; k + 1];\n d[1] = vec![1; n + 1];\n d[1][0] = 0;\n\n for length in 2..=k {\n for x in 1..=n {\n for t in (x..=n).step_by(x) {\n d[length][t] += d[length - 1][x];\n d[length][t] %= MOD;\n }\n }\n }\n // dbg!(&d);\n let mut sum: usize = 0;\n for x in d.last().unwrap() {\n sum += x;\n sum %= MOD;\n }\n sum\n}\n\n\nfn main() {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let mut n_k = buf.trim().split_whitespace().map(|x| x.parse::().unwrap());\n let n = n_k.next().unwrap();\n let k = n_k.next().unwrap();\n\n println!(\"{}\", count_good_sequences(n, k));\n}\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics", "number theory"], "code_uid": "f5b0e61b993a76dd83a353f1315bfba7", "src_uid": "c8cbd155d9f20563d37537ef68dde5aa", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn get_divs(x: usize) -> Vec {\n let mut result = vec![1usize];\n for i in 2..=x {\n if x % i == 0 {\n result.push(i);\n }\n }\n result\n}\n\nfn _main() -> std::io::Result<()> {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let k: usize = scan.next();\n let mut divs: Vec> = vec![Vec::new(); 2048];\n for i in 1..=n {\n divs[i] = get_divs(i);\n }\n let mut dp = [[0usize; 2048]; 2048];\n for i in 1..=n {\n dp[1][i] = 1;\n }\n for i in 2..=k {\n for j in 1..=n {\n for d in &divs[j] {\n dp[i][j] = (dp[i][j] + dp[i - 1][*d]) % 1000000007;\n }\n }\n }\n let mut result = 0usize;\n for i in 1..=n {\n result = (result + dp[k][i]) % 1000000007;\n }\n println!(\"{}\", result);\n Ok(())\n}\n\nfn main() -> std::io::Result<()> {\n std::thread::Builder::new()\n .stack_size(1 << 26)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap()?;\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics", "number theory"], "code_uid": "b660ccd5296bd4425b03e0ceec040660", "src_uid": "c8cbd155d9f20563d37537ef68dde5aa", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*};\n\n\n#[allow(unused_must_use)]\nfn solve(mut scan: Scanner, mut w: W) {\n let n = scan.token::();\n let m = scan.token::();\n\n let mut primes = [true; 51];\n\n primes[0] = false;\n primes[1] = false;\n\n for i in 2usize..=50 {\n for j in ((2*i)..=50).step_by(i) {\n primes[j] = false;\n }\n }\n\n let mut i = n;\n assert!(primes[i]);\n\n let mut ans = \"NO\";\n while i < 50 {\n i += 1;\n if primes[i] == true {\n if i == m {\n ans = \"YES\"\n }\n break;\n }\n }\n\n writeln!(w, \"{}\", ans);\n}\n \nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n solve(reader, writer);\n}\n\n#[allow(dead_code)]\nfn matrix_to_str(matrix: &Vec>, separator: &str) -> String { \n use std::fmt::Write;\n let mut ans = String::new();\n for line in matrix.iter() {\n for elem in line.iter() {\n write!(&mut ans, \"{}{}\", elem.to_string(), separator).unwrap();\n }\n write!(&mut ans, \"\\n\").unwrap();\n }\n ans\n}\npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace()\n }\n }\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace()) }\n }\n }\n pub fn get_matrix(&mut self, m: usize, n: usize) -> Vec> {\n // m rows and n columns\n let mut ans: Vec> = Vec::with_capacity(m);\n for i in 0..m {\n ans.push(Vec::with_capacity(n));\n for _ in 0..n {\n ans[i].push(self.token::());\n }\n }\n ans\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "fc0b953b144217fe5ec92a5f3902bc0a", "src_uid": "9d52ff51d747bb59aa463b6358258865", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/80/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n let mut sieve = vec![true; 51];\n for i in 2..50 {\n let mut j = 2 * i;\n while j < 51 {\n sieve[j] = false;\n j += i;\n }\n }\n scanln!(n: usize, m: usize);\n let mut next_prime = n;\n for i in n+1..51 {\n if sieve[i] { next_prime = i; break; }\n }\n if next_prime == m {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "a77840ddc55215f759a73dc20fa71eb0", "src_uid": "9d52ff51d747bb59aa463b6358258865", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn f(a: i32) -> i32 {\n let p = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];\n for i in 0..p.len() {\n if a == p[i] {\n return i as i32;\n }\n }\n -1\n}\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = f(input.i());\n let b = f(input.i());\n if a + 1 == b {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "b66e1b027a687787b67b913222204496", "src_uid": "9d52ff51d747bb59aa463b6358258865", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{HashSet,HashMap,VecDeque,BinaryHeap};\n\n// Functions\n\n// Main\nfn main(){\n input!{\n N: u64,\n M: u64,\n }\n let mut next_prime = 0;\n for i in N+1..M+1{\n let mut cnt = 0;\n for j in 2..i{\n if i%j==0{\n cnt += 1;\n }\n }\n if cnt == 0{\n next_prime = i;\n break;\n }\n }\n println!(\"{}\", if next_prime==M{\"YES\"}else{\"NO\"});\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "81e2210e9d5bf4a0d2e97933282d9583", "src_uid": "9d52ff51d747bb59aa463b6358258865", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_pair() -> (i32, i32) {\n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input)\n\t\t.expect(\"\");\n\n\tlet v = input.trim()\n\t\t\t.split_whitespace()\n\t\t\t.map(|d| i32::from_str(d).unwrap())\n\t\t\t.collect::>();\n\n\t(v[0], v[1])\n}\n\nfn main() {\n\tlet (n, m) = get_pair();\n\n\tlet mut v = false;\n\tfor x in n+1..m+1 {\n\t\tif is_prime(x) {\n\t\t\tif x == m {\n\t\t\t\tv = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif v {\n\t\tprintln!(\"YES\");\n\t} else {\n\t\tprintln!(\"NO\");\n\t}\n\n\tfn is_prime(n: i32) -> bool {\n\t\tlet m = (n as f32).sqrt().round() as i32;\n\t\tfor i in 2..m+1 {\n\t\t\tif n%i == 0 {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\ttrue\n\t}\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "aed577cde99d471617e8a2d2ee4d1aad", "src_uid": "9d52ff51d747bb59aa463b6358258865", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_pair() -> (i32, i32) {\n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input)\n\t\t.expect(\"\");\n\n\tlet v = input.trim()\n\t\t\t.split_whitespace()\n\t\t\t.map(|d| i32::from_str(d).unwrap())\n\t\t\t.collect::>();\n\n\t(v[0], v[1])\n}\n\nfn main() {\n\tlet (n, m) = get_pair();\n\n\tlet mut v = false;\n\tfor x in n+1..m+1 {\n\t\tif is_prime(x) {\n\t\t\tif x == m {\n\t\t\t\tv = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif v {\n\t\tprintln!(\"YES\");\n\t} else {\n\t\tprintln!(\"NO\");\n\t}\n\n\tfn is_prime(n: i32) -> bool {\n\t\tlet m = (n as f32).sqrt().round() as i32;\n\t\tfor i in 2..m+1 {\n\t\t\tif n%i == 0 {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\ttrue\n\t}\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "1bacd452ad4df4c3375ce65a00fb504a", "src_uid": "9d52ff51d747bb59aa463b6358258865", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\nfn main() {\n let s = get!(String).chars().toVec();\n let s2 = get!(String).chars().toVec();\n mydbg!(s, s2);\n let mut a = true;\n let mut b = true;\n\n let mut h = vec![0; 26];\n let mut h2 = vec![0; 26];\n\n let mut cur = 0;\n for &c in &s2 {\n a = false;\n while cur < s.len() {\n if s[cur] == c {\n a = true;\n cur += 1;\n break;\n }\n cur += 1;\n }\n }\n\n if a {\n echo!(\"automaton\");\n return;\n }\n a = true;\n if s.len() <= s2.len() {\n a = false;\n }\n\n for &c in &s {\n let c = c as usize - 'a' as usize;\n h[c] += 1;\n }\n for &c in &s2 {\n let c = c as usize - 'a' as usize;\n h2[c] += 1;\n }\n\n for i in 0..26 {\n if h[i] != h2[i] {\n b = false;\n }\n }\n\n if b {\n echo!(\"array\");\n return;\n }\n b = true;\n for i in 0..26 {\n if h[i] < h2[i] {\n b = false;\n }\n }\n if a && b {\n echo!(\"both\");\n return;\n }\n echo!(\"need tree\");\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "a50c5b1033a192c115864df3408d031e", "src_uid": "edb9d51e009a59a340d7d589bb335c14", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut n: usize = s.trim().parse().unwrap();\n let mut ans = String::new();\n for k in 2..1000 {\n while n % k == 0 {\n ans.push_str(&format!(\"{}\", k));\n n /= k;\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "28f38110a618499c88ccf3ff0b4ef309", "src_uid": "7220f2da5081547a12118595bbeda4f6", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main()\n{\n let mut n = String::new();\n io::stdin().read_line(&mut n).unwrap();\n let n : i32 = n.trim().parse().unwrap();\n for i in 2..(n as f64).sqrt() as i32 + 1\n {\n if n % i == 0\n {\n println!(\"{}{}\", i, n / i);\n }\n }\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "a14a686b9d2af1b12ce45837ee4247a4", "src_uid": "7220f2da5081547a12118595bbeda4f6", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main()\n{\n let mut n = String::new();\n io::stdin().read_line(&mut n).unwrap();\n let n : i32 = n.trim().parse().unwrap();\n for i in 2..(n as f64).sqrt() as i32 + 1\n {\n if n % i == 0\n {\n println!(\"{}{}\", i, n / i);\n return;\n }\n }\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "ff430ca18359330b0d91abcf70be1e64", "src_uid": "7220f2da5081547a12118595bbeda4f6", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn solution(arg: String) -> bool {\n let mut sf = 0;\n let mut fs = 0;\n let mut prev_char;\n let mut c;\n let mut iter = arg.chars().peekable();\n prev_char = iter.next().unwrap(); \n while iter.peek().is_some() {\n c = iter.next().unwrap();\n if prev_char == 'S' && c == 'F' {\n sf+=1;\n } else if prev_char == 'F' && c == 'S' {\n fs+=1;\n }\n prev_char = c;\n }\n sf>fs\n}\n\nfn main() {\n assert_eq!(false,solution(String::from(\"FSSF\")));\n assert_eq!(true,solution(String::from(\"SF\")));\n assert_eq!(false,solution(String::from(\"FFFFFFFFFF\")));\n assert_eq!(true,solution(String::from(\"SSFFSFFSFF\")));\n\n\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n println!(\"{}\", if solution(s) {\"YES\"} else {\"NO\"}); \n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9d6f27b36a557f59dbce41bc7afb2b7c", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut ni = String::new();\n io::stdin().read_line(&mut ni).unwrap();\n let mut si = String::new();\n io::stdin().read_line(&mut si).unwrap();\n let sf = si.trim().matches(\"SF\").collect::>().len(); \n let fs = si.trim().matches(\"FS\").collect::>().len(); \n if sf > fs {\n println!(\"YES\")\n } else {\n println!(\"NO\")\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e79500df9a585093b2e8ee455789ba47", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let mut number = buf.trim().parse::().unwrap();\n //println!(\"{}\", number);\n //println!(\"Hello, world!\");\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let mut string = buffer.trim().as_bytes();\n //println!(\"{:?}\", string);\n let mut counter = 0;\n let mut S_to_F = 0;\n let mut F_to_S = 0;\n loop {\n if (counter == (number-1)) {\n break;\n }\n //F < S\n if string[counter as usize] < string[(counter+1) as usize] {\n F_to_S = F_to_S + 1;\n //println!(\"F to s + 1\");\n }\n else if string[counter as usize] > string[(counter+1) as usize]{\n S_to_F = S_to_F + 1;\n //println!(\"S to f + 1\");\n }\n counter = counter + 1;\n }\n if (S_to_F > F_to_S) {\n println!(\"YES\");\n }\n else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e3d783d134fb41a5ee762f995b1ca148", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let s = input.bs();\n if s[0] == b'S' && s[n - 1] == b'F' {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "23cab2de938a6208707c2b163e69a224", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io;\n\nfn get_lines() -> io::Result {\n\tlet mut buffer = String::new();\n\tio::stdin().read_line(&mut buffer)?;\n\tOk(buffer)\n}\n\nfn main() -> Result<(), Box> {\n\tlet _ = get_lines()?;\n\tlet input = get_lines()?;\n\tlet mut iter = input.chars();\n\n\tlet mut s_to_sf = 0;\n\tlet mut sf_to_s = 0;\n\tlet mut last = iter.next().unwrap();\n\tfor c in iter {\n\t\tmatch (last, c) {\n\t\t\t('S', 'F') => {\n\t\t\t\ts_to_sf += 1;\n\t\t\t}\n\t\t\t('F', 'S') => {\n\t\t\t\tsf_to_s += 1;\n\t\t\t}\n\t\t\t_ => {}\n\t\t}\n\t\tlast = c;\n\t}\n\tprint!(\"{}\", if s_to_sf > sf_to_s { \"YES\" } else { \"NO\" });\n\tOk(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "003e0cbbb662741800cb16718c9d0cd1", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n input.clear();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::Read line failed\");\n\n let sf_amount = input.trim().matches(\"SF\").collect::>().len();\n let fs_amount = input.trim().matches(\"FS\").collect::>().len();\n\n if sf_amount > fs_amount {\n println!(\"YES\");\n }else {\n println!(\"NO\");\n }\n\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9dd59dce5c9fda2bd29eb1669ab61067", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let n: usize = get_line().trim().parse().unwrap();\n\n let days: Vec = get_line().trim().bytes().map(|b| b == b'S').collect();\n\n let mut prev = None;\n\n let mut cnt = 0;\n\n let first = days[0];\n\n for day in days {\n match prev {\n Some(b) if b != day => {\n prev = Some(day);\n cnt += 1;\n },\n _ => {\n prev = Some(day);\n }\n }\n }\n\n if first && cnt % 2 == 1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0971781a2f151df932a942824ce1e3f1", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn foo(a: u64, b:u64) -> (u64, u64) {\n if a == 0 || b == 0 {\n (a, b)\n } else if a >= 2*b {\n foo(a % (2*b), b)\n } else if b >= 2*a {\n foo(a, b % (2*a))\n } else {\n (a, b)\n }\n}\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let data = buffer.split_whitespace()\n .map(|x| x.trim().parse::().unwrap())\n .collect::>();\n let (a,b) = foo(data[0], data[1]);\n println!(\"{} {}\", a, b);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "2f7367b4ead87b7e78f52c6947dc72fc", "src_uid": "1f505e430eb930ea2b495ab531274114", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n#![allow(non_camel_case_types)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{max, min, Ordering};\nuse std::f64::consts::*;\nuse std::mem::{swap, size_of_val, size_of};\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\nuse std::num::*;\nuse std::process::*;\n//use std::ptr::*;\nuse std::iter::{once, repeat};\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\nstruct Input {\n\tbuffer: Buf,\n}\n\nimpl Input {\n\tfn read_char(&mut self) -> char {\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\tx[0] as char\n\t}\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n}\n\nmacro_rules! read {\n () => {};\n\t($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect(\"Parsing error\"));\n\t($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect(\"Parsing error\")),*));\n}\nfn gcd(mut a: T, mut b: T) -> T\n\twhere T: ShrAssign + BitAnd + Ord + From + Clone + SubAssign + ShlAssign + Copy\n{\n\tlet one = T::from(1);\n\tlet zero = T::from(0);\n\tlet mut ans = 0;\n\tif a < b {\n\t\tswap(&mut a, &mut b);\n\t}\n\twhile b > zero {\n\t\tif (a & one > zero) && (b & one > zero) {\n\t\t\ta -= b;\n\t\t} else if a & one > zero {\n\t\t\tb >>= one;\n\t\t} else if b & one > zero {\n\t\t\ta >>= one;\n\t\t} else {\n\t\t\tans += 1;\n\t\t\ta >>= one;\n\t\t\tb >>= one;\n\t\t}\n\t\tif a < b {\n\t\t\tswap(&mut a, &mut b);\n\t\t}\n\t}\n\ta <<= ans;\n\ta\n}\n\nfn powmod(mut base: X, mut exp: Y, mm: X) -> X\n\twhere X: Copy + Clone + Mul + Rem + From,\n\t Y: ShrAssign + Copy + Clone + BitAnd + From + Ord\n{\n\tlet mut res = X::from(1);\n\twhile exp > Y::from(0) {\n\t\tif exp & Y::from(1) > Y::from(0) {\n\t\t\tres = res * base % mm;\n\t\t}\n\t\tbase = base * base % mm;\n\t\texp >>= Y::from(1);\n\t}\n\tres\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\")) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet stdin = stdin();\n\t\t\tlet istr = stdin.lock();\n\t\t\tlet mut inf = Input { buffer: BufReader::new(istr) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output) {\n\tlet (mut a, mut b) = read!(inf,i64,i64);\n\twhile b > 0 && a > 0 {\n\t\tif a >= 2 * b {\n\t\t\ta %= 2 * b;\n\t\t} else if b >= 2 * a {\n\t\t\tb %= 2 * a;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\twriteln!(ouf, \"{} {}\", a, b);\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "950f0182e2566d1790b18bdc762af0b2", "src_uid": "1f505e430eb930ea2b495ab531274114", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n a: u64,\n b: u64,\n }\n let mut a = a;\n let mut b = b;\n loop {\n if a == 0 || b == 0 {\n println!(\"{} {}\", a, b);\n return;\n } else if a >= 2 * b {\n a %= 2 * b;\n } else if b >= 2 * a {\n b %= 2 * a;\n } else {\n println!(\"{} {}\", a, b);\n return;\n }\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "194022a70b6805f45c5e228519c8bcc2", "src_uid": "1f505e430eb930ea2b495ab531274114", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn process(a : u64, b : u64) -> (u64, u64) {\n let mut m_a = a;\n let mut m_b = b;\n loop {\n if (m_a == 0) || (m_b == 0) {\n break;\n } else {\n let two_m_a = 2 * m_a;\n let two_m_b = 2 * m_b;\n if m_a >= two_m_b {\n m_a = m_a % two_m_b;\n } else if m_b >= two_m_a {\n m_b = m_b % two_m_a;\n } else {\n break;\n }\n }\n }\n (m_a, m_b)\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut a_b = vec![];\n read_ts(&stdin, &mut a_b);\n let (c, d) = process(a_b[0], a_b[1]);\n println!(\"{} {}\", c, d);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "d865ea9cf8ee89c6297adb4a2ea98099", "src_uid": "1f505e430eb930ea2b495ab531274114", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get { \n () => (get().parse::().unwrap());\n }\n let mut a = get!();\n let mut b = get!();\n while a > 0 && b > 0 {\n if a >= 2 * b {\n let x = a / (2 * b);\n a -= 2 * b * x;\n } else if b >= 2 * a {\n let x = b / (2 * a);\n b -= 2 * a * x;\n } else {\n break;\n }\n }\n println!(\"{} {}\", a, b);\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "f9d99c1f2786e1dfc06d723d2857f23c", "src_uid": "1f505e430eb930ea2b495ab531274114", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_variables, dead_code, non_snake_case, unused_macros)]\nuse std::io::{stdin, Read, StdinLock};\nuse std::str::FromStr;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nfn getline() -> String{\n let mut res = String::new();\n std::io::stdin().read_line(&mut res).ok();\n res\n}\n\nmacro_rules! readl {\n ($t: ty) => {\n {\n let s = getline();\n s.trim().parse::<$t>().unwrap()\n }\n };\n ($( $t: ty),+ ) => {\n {\n let s = getline();\n let mut iter = s.trim().split(' ');\n ($(iter.next().unwrap().parse::<$t>().unwrap(),)*) \n }\n };\n}\n\nmacro_rules! readlvec {\n ($t: ty) => {\n {\n let s = getline();\n let iter = s.trim().split(' ');\n iter.map(|x| x.parse().unwrap()).collect::>()\n }\n }\n}\n\nmacro_rules! mvec {\n ($v: expr, $s: expr) => {\n vec![$v; $s]\n };\n ($v: expr, $s: expr, $($t: expr),*) => {\n vec![mvec!($v, $($t),*); $s]\n };\n}\n\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn printiter<'a, T>(v: &'a T)\nwhere\n &'a T: std::iter::IntoIterator, \n <&'a T as std::iter::IntoIterator>::Item: std::fmt::Display {\n for (i,e) in v.into_iter().enumerate() {\n if i != 0 {\n print!(\" \");\n }\n print!(\"{}\", e);\n }\n println!(\"\");\n}\n\nstruct ContestPrinter {\n s: String,\n}\n\nimpl ContestPrinter {\n fn new() -> ContestPrinter {\n ContestPrinter {\n s: String::new(),\n }\n }\n\n fn print(&mut self, x: T)\n where T: std::fmt::Display {\n self.s.push_str(format!(\"{}\", x).as_str());\n }\n\n fn println(&mut self, x: T)\n where T: std::fmt::Display {\n self.s.push_str(format!(\"{}\\n\", x).as_str());\n }\n}\n\nimpl std::ops::Drop for ContestPrinter {\n fn drop(&mut self) {\n print!(\"{}\", self.s);\n }\n}\n\n\n\nfn main() {\n let mut printer = ContestPrinter::new();\n \n let (A, B) = readl!(i64, i64);\n let (mut a, mut b) = (A, B);\n loop {\n if (a == 0) | (b == 0) { break; }\n else if a >= (2*b) {\n let num = a / (2*b);\n a -= num * (2*b);\n } else if b >= (2*a) {\n let num = b / (2*a);\n b -= num * (2*a);\n } else {\n break;\n }\n }\n println!(\"{} {}\", a, b);\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "3243db45935e489a729e59d7e373bc11", "src_uid": "1f505e430eb930ea2b495ab531274114", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"EOF\");\n line.pop();\n return line;\n}\n\nmacro_rules! read_line {\n (Vec<$t: ty>) => {{\n read_line().split_whitespace().map(|token| {\n <$t as std::str::FromStr>::from_str(token).expect(\"Invalid token\")\n }).collect>()\n }};\n ($($t: ty),*) => {{\n let line = read_line();\n let mut iter = line.split_whitespace();\n ($({\n let token = iter.next().expect(\"Too few tokens\");\n <$t as std::str::FromStr>::from_str(token).expect(\"Invalid token\")\n }), *)\n }};\n}\n\nuse std::cmp;\n\nfn main() {\n let (n, k) = read_line!(i32, i32);\n let x = cmp::min(k * 2, n - k);\n let y = if k == 0 { 0 } else { cmp::min(1, n - k) };\n println!(\"{} {}\", y, x);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "ac203e5c4e5ee7a6969f16b869b9ee6b", "src_uid": "bdccf34b5a5ae13238c89a60814b9f86", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n use std::io;\n use std::str::FromStr;\n use std::cmp::min;\n use std::cmp::max;\n \n let stdin = io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).ok();\n let s_line : Vec<&str> = line.split(' ').collect();\n let n : i64 = i64::from_str(s_line[0].trim()).unwrap();\n let k : i64 = i64::from_str(s_line[1].trim()).unwrap();\n let mut ans_min = min(1, n-k);\n if k == 0 {\n ans_min = 0;\n }\n let mut ans_max = 2*min(n/3, k) - max((k-min(n/3, k)) - n%3, 0);\n if (k-min(n/3, k))==1 && n%3==2{\n ans_max += 1;\n }\n println!(\"{0} {1}\", ans_min, ans_max);\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "19b3644a1104665e9cb1dc35d9ef8fa8", "src_uid": "bdccf34b5a5ae13238c89a60814b9f86", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec(s: String) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n s.split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn gcd(a: u32, b: u32) -> u32 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn main() {\n let (n, k): (u32, u32) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse().unwrap());\n (it.next().unwrap(),\n it.next().unwrap())\n };\n\n let min_val = if k == 0 || k == n {\n 0\n } else {\n 1\n };\n\n let q = n / 3;\n let r = n % 3;\n\n let max_val = if k <= q {\n 2 * k\n } else if k <= q + r {\n 2 * q + if r == 2 && k == q + 1 {1} else {0}\n } else {\n n - k\n };\n\n println!(\"{} {}\", min_val, max_val);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "4743f149bce4a67e26e0ab5f5133f4e1", "src_uid": "bdccf34b5a5ae13238c89a60814b9f86", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 998_244_353;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ----------\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let p: usize = it.next().unwrap().parse().unwrap();\n let s: usize = it.next().unwrap().parse().unwrap();\n let r: usize = it.next().unwrap().parse().unwrap();\n let pc = Precalc::new(s + p);\n let mut ans = ModInt::zero();\n for v in r..=s {\n if p * v == s {\n ans += pc.inv(p);\n }\n for k in 1..p {\n if k * v > s {\n break;\n }\n let rem = s - k * v;\n let q = p - k;\n let mut way = ModInt::zero();\n let mut sign = ModInt::one();\n for x in 0..=q {\n if x * v > rem {\n break;\n }\n way += sign * pc.comb(rem - x * v + q - 1, q - 1) * pc.comb(q, x);\n sign = -sign;\n }\n ans += pc.comb(p - 1, k - 1) * way * pc.inv(k);\n }\n }\n ans *= pc.comb(s - r + p - 1, p - 1).inv();\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["probabilities", "math", "dp", "combinatorics"], "code_uid": "686703a8325a261fa96e8021d30a0b3b", "src_uid": "609195ef4a970c62a8210dafe118580e", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u32 = scan.token();\n let ans = 3 * n / 2;\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "a6abca6ccc0aaedaed33dff689bb6603", "src_uid": "031e53952e76cff8fdc0988bb0d3239c", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: u64,\n }\n let mut ans = 100;\n for k in 1.. {\n if k * k > n {\n break;\n }\n let a: Vec<_> = (k * k).to_string().chars().collect();\n let b: Vec<_> = n.to_string().chars().collect();\n let mut x = 0;\n let mut y = 0;\n let mut c = 0;\n while x < a.len() && y < b.len() {\n if a[x] == b[y] {\n x += 1;\n y += 1;\n } else {\n y += 1;\n c += 1;\n }\n }\n if x >= a.len() {\n c += b.len() - y;\n ans = std::cmp::min(ans, c);\n }\n }\n if ans >= 100 {\n println!(\"-1\");\n } else {\n println!(\"{}\", ans);\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "8d96158e47f6ba0d6685f31c10cf06fe", "src_uid": "fa4b1de79708329bb85437e1413e13df", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\nuse std::iter;\nuse std::io;\nuse std::io::BufRead;\n\nmod lib {\npub fn bam() {\n println!(\"Hi!\")\n}\n}\n\nfn is_square(n: u32) -> bool {\n let mut l: u64 = 1;\n let mut r: u64 = 60000;\n while r - l > 1 {\n let m = (r + l) / 2;\n if m * m <= n as u64 {\n l = m\n } else {\n r = m\n }\n }\n return l * l == (n as u64);\n}\n\nfn recurse(n: u32, mut f: F) {\n if n < 10 {\n return; \n }\n\n let mut pow10: u64 = 1;\n while (n as u64) >= pow10 {\n if pow10 * 10 <= (n as u64) || ((n as u64) % pow10 >= pow10 / 10) {\n f(((n as u64 / (pow10 * 10) * pow10) + (n as u64 % pow10)) as u32);\n }\n\n pow10 *= 10;\n }\n}\n\nfn get(n: u32, xs: &mut Vec>>) -> Option {\n if n as usize >= xs.len() || xs[n as usize].is_none() {\n let res = if is_square(n) {\n Some(0)\n } else {\n let mut result: Option = None;\n recurse(n, |n_rm| {\n if let Some(k_rm) = get(n_rm, xs) {\n result = result.map_or(\n Some(k_rm + 1), |k| Some(cmp::min(k, k_rm + 1))\n );\n }\n });\n result\n };\n\n if (n as usize) < xs.len() {\n xs[n as usize] = Some(res);\n }\n return res;\n }\n return xs[n as usize].unwrap();\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut input = stdin.lock().lines().flat_map(\n |x| x.unwrap().split_whitespace().map(|x| x.to_string()).collect::>()\n );\n let n: u32 = input.next().unwrap().parse().unwrap();\n\n let mut array: Vec<_> = iter::repeat(None).take(100000).collect();\n if let Some(k) = get(n, &mut array) {\n println!(\"{}\", k);\n } else {\n println!(\"-1\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "23432fbcc2fd10d8e461602a3c41932f", "src_uid": "fa4b1de79708329bb85437e1413e13df", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn contains(n: &String, sub: &String) -> bool {\n let mut chars = sub.chars();\n let mut now = chars.next();\n for c in n.chars() {\n if let Some(nowc) = now {\n if nowc == c {\n now = chars.next();\n }\n } else {\n break;\n }\n }\n return now == None;\n}\n\nfn main() {\n let mut n = String::new();\n io::stdin().read_line(&mut n);\n n = n.trim().to_string();\n let n_len = n.chars().count();\n for k in (1..44722).rev() {\n let sub = (k * k).to_string();\n let sub_len = sub.chars().count();\n if n_len >= sub_len && contains(&n, &sub) {\n println!(\"{}\", n_len - sub_len);\n return;\n }\n }\n println!(\"-1\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "8d4fbffc3294ca47ff59a02d30fc046e", "src_uid": "fa4b1de79708329bb85437e1413e13df", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Read, Write, BufWriter};\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn is_square(s: Vec) -> bool {\n if s.len() == 0 { return false; }\n if s[0] == 0 { return false; }\n let mut val = 0;\n for u in s {\n val *= 10;\n val += u as i64;\n }\n let mut pass = 0;\n let mut fail = 1 << 16;\n while fail - pass > 1 {\n let mid = (fail + pass) / 2;\n if mid * mid <= val { pass = mid; }\n else { fail = mid; }\n }\n pass * pass == val\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($format:expr) => (write!(out,$format).unwrap());\n ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())\n }\n let n: Vec<_> = get_word().chars().map(|c| c as u8 as i32 - b'0' as i32).collect();\n let len = n.len();\n let mut ans = 1 << 20;\n for bits in 0 .. 1usize << len {\n let mut t = Vec::new();\n for i in 0 .. len {\n if (bits & 1 << i) == 0 {\n t.push(n[i]);\n }\n }\n if is_square(t) {\n ans = min(ans, bits.count_ones() as i32);\n }\n }\n puts!(\"{}\\n\", if ans == 1 << 20 { -1 } else { ans });\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "75e05708af5c746b53d9c9cb0bee2aa2", "src_uid": "fa4b1de79708329bb85437e1413e13df", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n#![allow(unused_imports)]\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::str::FromStr;\nuse std::collections::{VecDeque, HashMap};\n\nfn main() {\n let stdin = io::stdin();\n let mut input = stdin.lock();\n let mut line = String::new();\n input.read_line(&mut line).unwrap();\n let nums = get_numbers(&line);\n let shovel_price: i32 = nums[0];\n let change = nums[1];\n\n for i in 1..11 {\n let total = i * shovel_price;\n if total < 10 && total < change {\n continue;\n }\n\n if total % 10 == 0 || (total - change) % 10 == 0 {\n println!(\"{}\", i);\n return;\n }\n }\n\n println!(\"-1\");\n}\n\n/*\n * Utility Functions\n */\n\n// get numbers from line seperated by spaces\nfn get_numbers(line: &str) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n line.split_whitespace()\n .map(|chunk| chunk.parse::().expect(\"failed to parse\"))\n .collect()\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "df5e5651a9efad689757064811d014dc", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Scanner {\n Scanner {\n reader: reader,\n buffer: Vec::new(),\n }\n }\n\n /// Use \"turbofish\" syntax next::() to select data type of next token.\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n}\n\nfn main1() {\n let stdin = io::stdin();\n let mut input = Scanner::new(stdin.lock());\n let k = input.next::();\n let r = input.next::();\n for i in 1..10 {\n if (i * k % 10) == r || (i * k % 10) == 0 {\n println!{\"{}\", i};\n return;\n }\n }\n println![\"10\"];\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "10e457d1cd7f6a257e9f065e887108a2", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n,r) = readln!(i32,i32);\n for i in 1..20 {\n if (n*i)%10 == r || (n*i)%10 == 0 {\n println!(\"{}\",i);\n return;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "1a6353b8be3774ff06e8c0b281f631c8", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (k, r): (u32, u32) = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let mut ws = buf.split_whitespace();\n let k = ws.next().unwrap().parse().unwrap();\n let r = ws.next().unwrap().parse().unwrap();\n (k, r)\n };\n\n let c = std::char::from_digit(r, 10).unwrap();\n for i in 1..=10 {\n let s = format!(\"{}\", i * k);\n let d = s.chars().last().unwrap();\n if d == c || d == '0' {\n println!(\"{}\", i);\n break;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "8df63aa99a842cd442f2c3bc6be2cb75", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let kr: Vec;\n let line: String;\n let mut iterator = stdin.lock().lines();\n let mut min: i32;\n\n line = iterator.next().unwrap().unwrap();\n kr = line\n .split_whitespace()\n .map(|n| n.parse().unwrap())\n .collect();\n \n min = 1;\n while (kr[0]*min)%10 != 0 && (kr[0]*min)%10 != kr[1] {\n min += 1;\n }\n\n println!(\"{}\", min);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "953146f7d7c921a148404ee07df9bc66", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).expect(\"failed\");\n let mut iter = s.split_whitespace();\n let k = iter.next().unwrap().parse::().unwrap();\n let r = iter.next().unwrap().parse::().unwrap();\n for i in 1..10 {\n if k * i % 10 == 0 || k * i % 10 == r {\n println!(\"{}\", i);\n break;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "64ed5890bc9fe15aa2c6fc5e462b4428", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (k, r) = R!(usize, usize);\n for i in 1.. {\n if k*i % 10 == 0 || k*i % 10 == r {\n println!(\"{}\", i);\n break;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "94cfe0986abb292e5a86ff66b4f9fbd3", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! debug(\n ($($arg:tt)*) => { {\n let r = writeln!(&mut ::std::io::stderr(), $($arg)*);\n r.expect(\"failed printing to stderr\");\n } }\n);\n\nstruct Scanner {\n buffer : std::collections::VecDeque\n}\n\nimpl Scanner {\n\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn process(&mut self) -> String {\n if self.buffer.len() == 0 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n for word in input.split_whitespace() {\n self.buffer.push_back(word.to_string())\n }\n }\n\n self.buffer.pop_front().unwrap()\n }\n\n fn next(&mut self) -> T {\n self.process().parse::().ok().unwrap()\n }\n\n fn next_char(&mut self) -> char {\n self.process().into_bytes()[0] as char\n }\n}\n\nfn main() {\n let mut sin = Scanner::new();\n\n let k : usize = sin.next();\n let r = sin.next();\n\n for i in 1..10001 {\n let test = ((i*k) + 10) % 10;\n if test == r || test == 0 {\n println!(\"{}\", i);\n break;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "ab4672bc0fcea8df0d417d9baf86a89b", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\nuse std::thread;\n\nfn exec() {\n let mut sc = Scanner::new();\n let s: String = sc.ne();\n let t: String = sc.ne();\n fn f(s: &str) -> i32 {\n match s {\n \"monday\" => 0,\n \"tuesday\" => 1,\n \"wednesday\" => 2,\n \"thursday\" => 3,\n \"friday\" => 4,\n \"saturday\" => 5,\n \"sunday\" => 6,\n _ => panic!(\">_<\"),\n }\n }\n let s = f(&s);\n let t = f(&t);\n let mut ok = false;\n for &x in &[28, 30, 31] {\n if (s + x) % 7 == t {\n ok = true;\n break;\n }\n }\n println!(\"{}\", if ok { \"YES\" } else { \"NO\" });\n}\n\nfn main() {\n const DEFAULT_STACK: usize = 16 * 1024 * 1024;\n let builder = thread::Builder::new();\n let th = builder.stack_size(DEFAULT_STACK);\n let handle = th.spawn(|| { exec(); }).unwrap();\n let _ = handle.join();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => return None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => {\n panic!(\"parse error, {:?}\",\n String::from_utf8(self.buf[l..r].to_owned()))\n }\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "19607c5935b838a2cfaab0f241c7c49f", "src_uid": "2a75f68a7374b90b80bb362c6ead9a35", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn zeros_fac(n : u32) -> u32 {\n let mut i = 5;\n let mut count = 0;\n while i <= n {\n count += n / i;\n i *= 5;\n }\n count\n}\n\nfn bsearch(mut pi : u32, mut pf : u32, n : u32) -> Option {\n while pf >= pi {\n let pm = (pf + pi) / 2;\n let zeros_pm = zeros_fac(5 * pm);\n if zeros_pm < n {\n pi = pm + 1;\n } else if zeros_pm == n {\n return Some(5 * pm);\n } else {\n pf = pm - 1;\n }\n }\n return None;\n}\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let n: u32 = buffer.trim().parse().expect(\"invalid input\");\n\n match bsearch(4 * n / 5, n, n) {\n Some(x) => {\n println!(\"5\");\n println!(\"{} {} {} {} {}\", x, x + 1, x + 2, x + 3, x + 4);\n },\n None => println!(\"0\"),\n };\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "number theory"], "code_uid": "d535cf4d3ea195a3cabd8b6f6b2ce854", "src_uid": "c27ecc6e4755b21f95a6b1b657ef0744", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Time {\n hour: u8,\n min: u8\n}\n\nimpl Time {\n fn add_minute(&mut self) {\n self.min += 1;\n if self.min == 60 {\n self.min = 0;\n self.hour += 1;\n if self.hour == 24 {\n self.hour = 0;\n }\n }\n }\n\n fn is_palindrome(&self) -> bool {\n let (h1, h2) = (self.hour / 10, self.hour % 10);\n let (m1, m2) = (self.min / 10, self.min % 10);\n\n h1 == m2 && h2 == m1\n }\n}\n\nfn main() {\n use std::io::{self, Read};\n\n let mut buf = [0; 5];\n io::stdin().read(&mut buf).unwrap();\n\n let mut time = Time {\n hour: {\n let h1 = buf[0] - b'0';\n let h2 = buf[1] - b'0';\n (h1 * 10) + h2\n },\n min: {\n let m1 = buf[3] - b'0';\n let m2 = buf[4] - b'0';\n (m1 * 10) + m2\n }\n };\n\n let mut mins = 0;\n while !time.is_palindrome() {\n time.add_minute();\n mins += 1;\n }\n\n println!(\"{}\", mins);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "0c168788bb16a89eabc9a1987df2c2f4", "src_uid": "3ad3b8b700f6f34b3a53fdb63af351a5", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self};\n\nfn is_paly(x: i32) -> bool {\n let h = (x / 60) % 24;\n let m = x % 60;\n h % 10 * 10 + h / 10 == m\n}\n\nfn find_paly(x: i32) -> i32 {\n for i in x..3000{\n if is_paly(i) {return i - x}\n }\n -1\n}\n\nfn read_time() -> Result {\n let mut str = String::new();\n try!(io::stdin().read_line(&mut str).map_err(|e| e.to_string()));\n let parts: Vec<&str> = str.split(':').collect();\n if parts.len() != 2 { return Err(String::from(\"wrong format, should have single : delimiter\")) };\n let x = try!(parts[0].trim().parse::().map_err(|e|e.to_string()));\n let y = try!(parts[1].trim().parse::().map_err(|e|e.to_string()));\n Ok(x * 60 + y)\n}\n\nfn main() {\n let tt = read_time().unwrap();\n print!(\"{}\", find_paly(tt));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "9c16d67d67628fe6a184b8404b534f28", "src_uid": "3ad3b8b700f6f34b3a53fdb63af351a5", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn solve(nums: &Vec) -> &str {\n let mut res = false;\n if nums[0] + nums[1] > nums[2] {\n return \"TRIANGLE\";\n } else if nums[0] + nums[1] == nums[2] {\n res = true;\n }\n if nums[1] + nums[2] > nums[3] {\n \"TRIANGLE\"\n } else if nums[1] + nums[2] == nums[3] || res {\n \"SEGMENT\"\n } else {\n \"IMPOSSIBLE\"\n }\n}\n\nfn main() {\n let mut input = String::with_capacity(7);\n io::stdin().read_line(&mut input).unwrap();\n let mut nums: Vec = input\n .trim()\n .split_whitespace()\n .map(|a| a.parse().unwrap())\n .collect();\n\n nums.sort_unstable();\n print!(\"{}\", solve(&nums));\n}", "lang_cluster": "Rust", "tags": ["brute force", "geometry"], "code_uid": "e49de46a46dfe654f173d29418d72803", "src_uid": "8f5df9a41e6e100aa65b9fc1d26e447a", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn is_triangle(a: usize, b: usize, c: usize) -> bool {\n // parameters are passed sorted in increasing order\n return a + b > c;\n}\n\nfn is_collinear(a: usize, b: usize, c: usize) -> bool {\n // parameters are passed sorted in increasing order\n return a + b == c;\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut arr: Vec = scan.next_n(4);\n arr.sort();\n if is_triangle(arr[0], arr[1], arr[2])\n || is_triangle(arr[0], arr[1], arr[3])\n || is_triangle(arr[0], arr[2], arr[3])\n || is_triangle(arr[1], arr[2], arr[3])\n {\n println!(\"TRIANGLE\");\n } else if is_collinear(arr[0], arr[1], arr[2])\n || is_collinear(arr[0], arr[1], arr[3])\n || is_collinear(arr[0], arr[2], arr[3])\n || is_collinear(arr[1], arr[2], arr[3])\n {\n println!(\"SEGMENT\");\n } else {\n println!(\"IMPOSSIBLE\");\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "geometry"], "code_uid": "c7cb29affa95156a7785a724021c04a2", "src_uid": "8f5df9a41e6e100aa65b9fc1d26e447a", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn triangle(a: i32, b: i32, c: i32) -> bool {\n return a < b + c && b < c + a && c < a + b;\n}\nfn segment(a: i32, b: i32, c: i32) -> bool {\n return a == b + c || b == c + a || c == a + b;\n}\n\nfn main() {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let mut tokens = buf.split_whitespace();\n let a:i32 = tokens.next().unwrap().parse().unwrap();\n let b:i32 = tokens.next().unwrap().parse().unwrap();\n let c:i32 = tokens.next().unwrap().parse().unwrap();\n let d:i32 = tokens.next().unwrap().parse().unwrap();\n if triangle(a,b,c) || triangle(a,b,d) || triangle(a,c,d) || triangle(b,c,d) {\n println!(\"TRIANGLE\");\n } else if segment(a,b,c) || segment(a,b,d) || segment(a,c,d) || segment(b,c,d) {\n println!(\"SEGMENT\");\n } else {\n println!(\"IMPOSSIBLE\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "geometry"], "code_uid": "f8ea1893e9a553bc01ca1396ec15bc29", "src_uid": "8f5df9a41e6e100aa65b9fc1d26e447a", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read as _};\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_to_string(&mut input).unwrap();\n let mut input = input.split_whitespace();\n macro_rules! read(\n ([$tt:tt; $n:expr]) => ((0..$n).map(|_| read!($tt)).collect::>());\n ($ty:ty) => (input.next().unwrap().parse::<$ty>().unwrap());\n );\n\n let mut xs = read!([u64; 4]);\n xs.sort();\n if xs[0] + xs[1] > xs[2] || xs[1] + xs[2] > xs[3] {\n println!(\"TRIANGLE\");\n } else if xs[0] + xs[1] == xs[2] || xs[1] + xs[2] == xs[3] {\n println!(\"SEGMENT\");\n } else {\n println!(\"IMPOSSIBLE\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "geometry"], "code_uid": "3674191624e33a6014de2100a22387f3", "src_uid": "8f5df9a41e6e100aa65b9fc1d26e447a", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut result = String::new();\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let mut buf = buf\n .trim()\n .split_whitespace()\n .map(|num| num.parse::().unwrap())\n .take(3);\n let (n, p, k) = (\n buf.next().unwrap(),\n buf.next().unwrap(),\n buf.next().unwrap(),\n );\n\n // Add begining (before 'p')\n if (1..=(k + 1)).contains(&p) {\n for i in 1..p {\n result.push_str(&format!(\"{} \", i));\n }\n } else {\n result.push_str(\"<< \");\n for i in (p - k)..p {\n result.push_str(&format!(\"{} \", i));\n }\n }\n\n result.push_str(&format!(\"({})\", p));\n\n // Add ending (after 'p')\n if ((n - k)..=n).contains(&p) {\n for i in (p + 1)..=n {\n result.push_str(&format!(\" {}\", i));\n }\n } else {\n for i in (p + 1)..=(p + k) {\n result.push_str(&format!(\" {}\", i));\n }\n result.push_str(\" >>\");\n }\n\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6f22e6ff5e300ea9b2276aaf03783cf5", "src_uid": "526e2cce272e42a3220e33149b1c9c84", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::{max, min};\nuse std::io::stdin;\nfn main() {\n let (n, p, k) = {\n let mut buf = String::new();\n stdin().read_line(&mut buf).expect(\"Failed to read line\");\n let nums: Vec = buf\n .trim()\n .split_ascii_whitespace()\n .map(|c| c.parse::().unwrap())\n .collect();\n (nums[0], nums[1], nums[2])\n };\n if p - k > 1 {\n print!(\"<< \");\n }\n for i in max(1, p - k)..(p) {\n print!(\"{} \", i);\n }\n print!(\"({}) \", p);\n for i in (p + 1)..min(p + k + 1, n + 1) {\n print!(\"{} \", i);\n }\n if p + k < n {\n println!(\">>\");\n } else {\n println!(\"\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "387575bf027a83a83917b1c06f2cf7a7", "src_uid": "526e2cce272e42a3220e33149b1c9c84", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Write;\n\n// Outline\n// read in numberse first and parse\n\nfn main() {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"Couldn't read line.\");\n\n let input: Vec = input\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n\n let number_of_pages: i32 = input[0];\n let current_page: i32 = input[1];\n let range_of_pages: i32 = input[2];\n\n let lower_bound = {\n if current_page - range_of_pages <= 0 {\n 1\n } else {\n current_page - range_of_pages\n }\n };\n\n let higher_bound = {\n if current_page + range_of_pages > number_of_pages {\n number_of_pages\n } else {\n current_page + range_of_pages\n }\n };\n\n if higher_bound != number_of_pages && lower_bound != 1 {\n print!(\"<< \");\n io::stdout().flush().unwrap();\n for page in lower_bound..higher_bound+1 {\n if page == current_page {\n print!(\"({}) \", page);\n io::stdout().flush().unwrap();\n } else {\n print!(\"{} \", page);\n io::stdout().flush().unwrap();\n }\n }\n print!(\">>\");\n io::stdout().flush().unwrap();\n } else if higher_bound == number_of_pages && lower_bound != 1 {\n print!(\"<< \");\n io::stdout().flush().unwrap();\n for page in lower_bound..higher_bound+1 {\n if page == current_page {\n print!(\"({}) \", page);\n io::stdout().flush().unwrap();\n } else {\n print!(\"{} \", page);\n io::stdout().flush().unwrap();\n }\n }\n } else if higher_bound == number_of_pages && lower_bound == 1 {\n for page in lower_bound..higher_bound+1 {\n if page == current_page {\n print!(\"({}) \", page);\n io::stdout().flush().unwrap();\n } else {\n print!(\"{} \", page);\n io::stdout().flush().unwrap();\n }\n }\n } else if higher_bound != number_of_pages && lower_bound == 1 {\n for page in lower_bound..higher_bound+1 {\n if page == current_page {\n print!(\"({}) \", page);\n io::stdout().flush().unwrap();\n } else {\n print!(\"{} \", page);\n io::stdout().flush().unwrap();\n }\n }\n print!(\">>\");\n io::stdout().flush().unwrap();\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a0bfa7c9085b107d07b20e0eaa5825a9", "src_uid": "526e2cce272e42a3220e33149b1c9c84", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\r\nuse std::io::Write;\r\nuse std::cmp::min;\r\n\r\n/**************************************************\r\n\r\n START OF TEMPLATE CODE\r\n\r\n *************************************************/\r\n#[allow(unused_macros)]\r\nmacro_rules! dbg {\r\n ($first_val:expr, $($val:expr),+ $(,)?) => {\r\n eprint!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n ($(eprint!(\", {} = {:?}\", stringify!($val), &$val)),+,);\r\n eprintln!();\r\n };\r\n ($first_val:expr) => {\r\n eprintln!(\"[{}:{}] {} = {:?}\",\r\n file!(), line!(), stringify!($first_val), &$first_val);\r\n };\r\n}\r\n\r\nenum InputSource {\r\n Stdin,\r\n FromFile(Vec),\r\n}\r\n\r\nstruct Scanner {\r\n buffer: Vec,\r\n input_source: InputSource,\r\n}\r\n\r\n\r\nimpl Scanner {\r\n #[allow(dead_code)]\r\n fn new() -> Self {\r\n Self { buffer: vec![], input_source: InputSource::Stdin }\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn new_file(filename: &str) -> Self {\r\n let file = std::fs::read_to_string(filename).unwrap();\r\n let mut lines: Vec = file.lines().map(|line| String::from(line)).collect();\r\n lines.reverse();\r\n Self { buffer: vec![], input_source: InputSource::FromFile(lines) }\r\n }\r\n\r\n\r\n #[allow(dead_code)]\r\n fn i64(&mut self) -> i64 {\r\n self.next::()\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn i32(&mut self) -> i32 {\r\n self.next::()\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn usize(&mut self) -> usize {\r\n self.next::()\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.next::()).collect()\r\n }\r\n\r\n fn parse_next_line(&mut self) -> bool {\r\n let mut input = String::new();\r\n match &mut self.input_source {\r\n | InputSource::Stdin => {\r\n if std::io::stdin().read_line(&mut input).expect(\"Failed read\") == 0 {\r\n return false;\r\n }\r\n }\r\n | InputSource::FromFile(lines) => {\r\n match lines.pop() {\r\n Some(line) => input = line,\r\n None => return false,\r\n }\r\n }\r\n }\r\n\r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n return true;\r\n }\r\n\r\n fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n\r\n self.parse_next_line();\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n fn has_more_elements(&mut self) -> bool {\r\n loop {\r\n if !self.buffer.is_empty() {\r\n return true;\r\n }\r\n if !self.parse_next_line() {\r\n return false;\r\n }\r\n }\r\n }\r\n\r\n\r\n #[allow(dead_code)]\r\n fn string(&mut self) -> Vec {\r\n self.next::().into_bytes()\r\n }\r\n}\r\n\r\n/**************************************************\r\n\r\n END OF TEMPLATE CODE\r\n\r\n *************************************************/\r\n\r\n\r\npub fn main() {\r\n let stdout = io::stdout();\r\n let mut out = std::io::BufWriter::new(stdout.lock());\r\n let mut sc = Scanner::new();\r\n\r\n let n = sc.usize();\r\n let req_prob = sc.next::();\r\n for learn in 0..=n {\r\n let mut res = 0.0;\r\n let mut tot_prob = 0.0;\r\n for know1 in 0..=1 {\r\n for know2 in 0..=1 {\r\n for know3 in 0..=1 {\r\n let mut prob_here = 1.0;\r\n let mut more_know = learn;\r\n let mut more_not_know = n - learn;\r\n for &cur_know in [know1, know2, know3].iter() {\r\n let tot_left = (more_know + more_not_know) as f64;\r\n if cur_know == 0 {\r\n prob_here *= more_not_know as f64;\r\n if prob_here == 0.0 {\r\n break;\r\n }\r\n more_not_know -= 1;\r\n } else {\r\n prob_here *= more_know as f64;\r\n if prob_here == 0.0 {\r\n break;\r\n }\r\n more_know -= 1;\r\n }\r\n prob_here /= tot_left as f64;\r\n\r\n }\r\n let know_cnt = min(2, know1 + know2 + know3);\r\n let prob_know = (know_cnt as f64) / 2.0;\r\n res += prob_here * prob_know;\r\n tot_prob += prob_here;\r\n }\r\n }\r\n }\r\n if res >= req_prob {\r\n writeln!(out, \"{}\", learn).unwrap();\r\n return;\r\n }\r\n }\r\n unreachable!();\r\n}\r\n\r\n", "lang_cluster": "Rust", "tags": ["math", "probabilities", "combinatorics"], "code_uid": "e236c9a1a561b0166d5bf64ce35be04b", "src_uid": "788ed59a964264bd0e755e155a37e14d", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read(); };\n ($t: ty) => { read::<$t>(); };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n); };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }); };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }); }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }); }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }); }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen); }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE.rotate_right(1) >> self.leading_zeros() } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn set_max(&mut self, v: T) -> bool;\n fn set_min(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for T {\n fn set_max(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn set_min(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\npub trait BinarySearchExt {\n fn binary_search_by Ordering>(&self, f: F) -> Result;\n\n fn partition_point bool>(&self, mut f: F) -> T {\n self.binary_search_by(|x| if f(x) { Ordering::Less } else { Ordering::Greater }).err().unwrap()\n }\n}\nmacro_rules! impl_binary_search_ext_integer {\n ($($ty:tt),*) => {\n $(\n impl BinarySearchExt<$ty> for std::ops::Range<$ty> {\n fn binary_search_by Ordering>(&self, mut f: F) -> Result<$ty, $ty> {\n let mut low = self.start;\n let mut high = self.end;\n \n while low < high {\n let mid = (low & high) + ((low ^ high) >> 1);\n let cmp = f(mid);\n if cmp == Ordering::Less {\n low = mid + 1;\n } else if cmp == Ordering::Greater {\n high = mid;\n } else {\n return Ok(mid);\n }\n }\n Err(low)\n }\n }\n )*\n }\n}\nimpl_binary_search_ext_integer!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n \n for _case_num in 1..=num_cases {\n const SCALE: i64 = 10_000;\n\n let n = read!(i64);\n let p = (read!(f64) * SCALE as f64).round() as i64;\n\n let den = n * (n-1) * (n-2) * 2;\n\n let ans = (0..n).partition_point(|x| {\n let mut num = 0i64;\n\n for ng in 0..=3 {\n let mut chance = 1i64;\n for i in 0..ng {\n chance *= x-i;\n }\n for i in 0..3-ng {\n chance *= n-x-i;\n }\n\n if ng == 1 || ng == 2 { chance *= 3; }\n\n chance *= min(ng, 2);\n num += chance;\n }\n\n //dbg!(x, num * SCALE / den);\n num * SCALE / den < p\n });\n\n println!(ans);\n }\n \n out_flush();\n}\n", "lang_cluster": "Rust", "tags": ["math", "probabilities", "binary search"], "code_uid": "96e1f40e061dac6cffd93e70a1a93a8f", "src_uid": "788ed59a964264bd0e755e155a37e14d", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\r\nuse std::io;\r\n\r\nfn read_line() -> Vec\r\n where\r\n T::Err: std::fmt::Debug\r\n{\r\n let mut input = String::new();\r\n io::stdin().read_line(&mut input).unwrap();\r\n input.trim()\r\n .split(' ')\r\n .map(|x| x.parse::().unwrap())\r\n .collect()\r\n}\r\n\r\nfn c(n: i64, k: i64) -> i64 {\r\n if k > n {\r\n return 0;\r\n }\r\n let mut result = 1;\r\n if k > n - k {\r\n for i in k + 1..n + 1 {\r\n result *= i;\r\n }\r\n for i in 1..n - k + 1 {\r\n result /= i;\r\n }\r\n }\r\n if k <= n - k {\r\n for i in n - k + 1..n + 1 {\r\n result *= i;\r\n }\r\n for i in 1..k + 1 {\r\n result /= i;\r\n }\r\n }\r\n return result;\r\n}\r\n\r\nfn main() {\r\n let input = read_line::();\r\n let n = input[0].parse::().unwrap();\r\n let p = input[1].parse::().unwrap();\r\n let p_int = (p * 10000.0).round() as i64;\r\n for k in 0..n + 1 {\r\n let numerator = 2 * (c(k, 3) + c(k, 2) * c(n - k, 1)) + c(k, 1) * c(n - k, 2);\r\n if numerator * 10000 >= p_int * 2 * c(n, 3) {\r\n println!(\"{}\", k);\r\n return\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "probabilities", "combinatorics"], "code_uid": "9b7a9e2917dbf0efc4fcd4674f329bfa", "src_uid": "788ed59a964264bd0e755e155a37e14d", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{ self, Write };\nuse std::str::FromStr;\nuse std::cmp::{ min, max };\nuse std::collections::{ BinaryHeap, VecDeque };\n\nmacro_rules! trace {\n ($var:expr) => ({\n let _ = writeln!(&mut std::io::stderr(), \">>> {} = {:?}\", stringify!($var), $var);\n })\n}\nmacro_rules! swap { ($a:expr, $b:expr) => ({ let t = $b; $b = $a; $a = t; }) }\n\n\nfn main() {\n let mut sc = Scanner::new();\n let mut cost = vec![vec![0; 3]; 3];\n let mut memo = vec![vec![vec![0; 3]; 3]; 42];\n\n for i in 0..3 {\n for j in 0..3 {\n cost[i][j] = sc.cin::();\n }\n }\n\n for i in 0..3 {\n for j in 0..3 {\n if i == j { continue }\n let k = 3 - i - j;\n memo[1][i][j] = min(cost[i][k] + cost[k][j], cost[i][j]);\n }\n }\n\n let n: usize = sc.cin();\n\n for m in 2..(n+1) {\n for i in 0..3 {\n for j in 0..3 {\n if i == j { continue }\n let k = 3 - i - j;\n memo[m][i][j] =\n min(\n memo[m-1][i][k] + memo[m-1][k][j] + cost[i][j],\n memo[m-1][i][j] + cost[i][k] + memo[m-1][j][i] + cost[k][j] + memo[m-1][i][j]);\n }\n }\n // trace!(m);\n // for i in 0..3 {\n // for j in 0..3 {\n // print!(\"{} \", memo[m][i][j]);\n // }\n // println!(\"\");\n // }\n }\n\n println!(\"{}\", memo[n][0][2]);\n\n}\n\n#[allow(dead_code)]\nstruct Scanner { stdin: io::Stdin, buffer: VecDeque, }\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }\n fn reserve(&mut self) {\n while self.buffer.len() == 0 {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n }\n fn cin(&mut self) -> T {\n self.reserve();\n match self.buffer.pop_front().unwrap().parse::() {\n Ok(a) => a,\n Err(_) => panic!(\"parse err\")\n }\n }\n fn get_char(&mut self) -> char {\n self.reserve();\n let head = self.buffer[0].chars().nth(0).unwrap();\n let tail = String::from( &self.buffer[0][1..] );\n if tail.len()>0 { self.buffer[0]=tail } else { self.buffer.pop_front(); }\n head\n }\n}\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "b0d84979702bd0e11524135a76d4a68e", "src_uid": "c4c20228624365e39299d0a6e8fe7095", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, Read, StdinLock};\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::collections::{HashSet, HashMap, BinaryHeap};\n#[allow(unused_imports)]\nuse std::vec::Vec;\n\n#[allow(dead_code)]\nconst INF: i32 = 1000_000_000;\n#[allow(dead_code)]\nconst INFLL: i64 = 1000_000_000_000_000_000;\n#[allow(dead_code)]\nconst EPS: f64 = 1.0e-10;\n#[allow(dead_code)]\nconst MOD: i32 = 1000_000_007;\n\nstruct Scanner<'a> {\n cin: StdinLock<'a>,\n}\n\nimpl<'a> Scanner<'a> {\n #[allow(dead_code)]\n fn new(cin: StdinLock<'a>) -> Scanner<'a> {\n Scanner {cin: cin}\n }\n\n #[allow(dead_code)]\n fn read1(&mut self) -> Option {\n let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect::();\n token.parse::().ok()\n }\n\n #[allow(dead_code)]\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\nfn main() {\n let cin = stdin();\n let cin = cin.lock();\n let mut sc = Scanner::new(cin);\n\n let n: i32 = sc.read();\n let m: i32 = sc.read();\n let h = min(n, m);\n let w = max(n, m);\n if h == 1 {\n println!(\"{}\", w);\n } else if h == 2 {\n let ans = w / 4 * 4 + min(w % 4, 2) * 2;\n println!(\"{}\", ans);\n } else {\n println!(\"{}\", (n * m + 1) / 2);\n }\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "graph matchings"], "code_uid": "07f69abb97bfa20c89468f751d161033", "src_uid": "e858e7f22d91aaadd7a48a174d7b2dc9", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\nuse std::io::prelude::*;\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let n: u64 = get_line().trim().parse().unwrap();\n\n let get_beautiful = |i: u64| -> u64 {\n ((1 << i) - 1) << (i - 1)\n };\n\n let ans = (1..).map(|i| get_beautiful(i)).take_while(|&i| i <= n)\n .filter(|&i| n % i == 0).max().unwrap();\n\n println!(\"{}\", ans);\n}\n\nstruct Solver {\n\n}\n\nimpl Solver {\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "9a2e61533dc0d17767ac5cb0d9441c0d", "src_uid": "339246a1be81aefe19290de0d1aead84", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn ok(x: u64) -> bool {\n let test = x | (x - 1);\n test & (test + 1) == 0\n}\n\nfn solve() {\n let n = parse_line!(u64);\n let mut result = 1;\n for i in 1..16 {\n let cur = ((1 << (i + 1)) - 1) << i;\n if n % cur == 0 {\n result = cur;\n }\n }\n println!(\"{}\", result)\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "815c6c0e054ac5edd230f2743d282a33", "src_uid": "339246a1be81aefe19290de0d1aead84", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap, VecDeque, BTreeSet, BTreeMap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let n = get!(u64);\n\n let ans = (1..)\n .map(|k| (2u64.pow(k as u32) - 1) * (2u64.pow(k as u32 - 1)))\n .take_while(|&x| x <= n)\n .filter(|&x| n % x == 0)\n .last()\n .unwrap();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "e83a81cb355dfe7c0f1e863141f38454", "src_uid": "339246a1be81aefe19290de0d1aead84", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: u64,\n }\n let mut ans = 1;\n for k in 1u64.. {\n let d = 2u64.pow(k as u32 - 1) * (2u64.pow(k as u32) - 1);\n if d > n {\n break;\n }\n if n % d == 0 {\n ans = d;\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "7baf78ca3840592d31c2219d34b868b9", "src_uid": "339246a1be81aefe19290de0d1aead84", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! input {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, bytes) => {\n read_value!($next, String).into_bytes()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nconst MOD: i64 = 1000000007;\n\n// assume a, b positive\nfn gcd(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (1, 0, a)\n }\n else {\n let (x, y, d) = gcd(b, a%b); // xb + y(a-qb) = d where q = a/b\n (y, x-y*(a/b), d)\n }\n}\n\nfn factorial_mod(a: i64) -> i64 {\n if a == 0 {\n 1\n }\n else {\n a * factorial_mod(a-1) % MOD\n }\n}\n\nfn binomial_mod(n: i64, k: i64) -> i64 {\n let a = factorial_mod(k);\n let b = factorial_mod(n-k);\n let (inv_a, _, _) = gcd(a, MOD);\n let (inv_b, _, _) = gcd(b, MOD);\n let result = factorial_mod(n) * inv_a % MOD * inv_b % MOD;\n if result < 0 { result + MOD } else { result }\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input! {next,\n n: i64,\n m: i64,\n k: i64,\n }\n if 2*k > n-1 || 2*k > m-1 {\n println!(\"0\");\n }\n else {\n println!(\"{}\", binomial_mod(n-1,2*k)*binomial_mod(m-1,2*k) % MOD);\n }\n}\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics"], "code_uid": "d6ae2ab3dfe3c1a063cf95e541a8b28d", "src_uid": "309d2d46086d526d160292717dfef308", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1271/problem/A\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n input! {\n a: i64, b: i64, c: i64, d: i64,\n t1: i64, t2: i64\n };\n\n let mut best = 0;\n for i in 0..d+1 {\n best = max(best, t1*min(a, i)+t2*(min(min(b,c),d-i)));\n }\n\n println!(\"{}\", best);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "brute force"], "code_uid": "902d2778fd624c1c3b05291e78b113b8", "src_uid": "84d9e7e9c9541d997e6573edb421ae0a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nuse std::cmp::*;\n\nfn run() {\n input! {\n a: i32,\n b: i32,\n c: i32,\n d: i32,\n e: i32,\n f: i32,\n }\n let mut ans = 0;\n for x in 0..=min(a, d) {\n let mut val = 0;\n val += e * x;\n val += f * min(b, min(c, d - x));\n ans = max(ans, val);\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "brute force"], "code_uid": "94423dededc443ba0ea5b5949d780613", "src_uid": "84d9e7e9c9541d997e6573edb421ae0a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn read_u32() -> u32 {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n}\n\nfn convert_a(a: &mut u32, d: &mut u32, cost: u32) -> u32 {\n\n let a_amount = *a.min(d);\n *a -= a_amount;\n *d -= a_amount;\n\n a_amount * cost\n}\n\nfn convert_b(b: &mut u32, c: &mut u32, d: &mut u32, cost: u32) -> u32 {\n\n let b_amount = *b.min(c).min(d);\n *b -= b_amount;\n *c -= b_amount;\n *d -= b_amount;\n\n b_amount * cost\n}\n\nfn main() {\n let mut a = read_u32();\n let mut b = read_u32();\n let mut c = read_u32();\n let mut d = read_u32();\n\n let cost_a = read_u32();\n let cost_b = read_u32();\n\n let mut rev = 0;\n\n if cost_a > cost_b {\n\n rev += convert_a(&mut a, &mut d, cost_a);\n rev += convert_b(&mut b, &mut c, &mut d, cost_b);\n\n } else {\n\n rev += convert_b(&mut b, &mut c, &mut d, cost_b);\n rev += convert_a(&mut a, &mut d, cost_a);\n\n }\n\n println!(\"{}\", rev);\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "brute force"], "code_uid": "7e8b321539c2cdd6ae345327fb2cd53f", "src_uid": "84d9e7e9c9541d997e6573edb421ae0a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::max;\nuse std::cmp::min;\n\nfn main() {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut a: i64 = str.trim().parse().unwrap();\n str.clear();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut b: i64 = str.trim().parse().unwrap();\n str.clear();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut c: i64 = str.trim().parse().unwrap();\n str.clear();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut d: i64 = str.trim().parse().unwrap();\n str.clear();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut e: i64 = str.trim().parse().unwrap();\n str.clear();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut f: i64 = str.trim().parse().unwrap();\n str.clear();\n b = min (b, c);\n if e > f {\n println!(\"{}\", min(d, a) * e + min(d - min(d,a) ,b) * f);\n }\n else {\n println!(\"{}\", min(d, b) * f + min(d - min(d,b) ,a) * e);\n }\n \n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "brute force"], "code_uid": "9471ece1048e6f99b7cdae5bcb4a3213", "src_uid": "84d9e7e9c9541d997e6573edb421ae0a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::Write;\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($e:expr),*) => {\n #[cfg(debug_assertions)]\n $({\n let (e, mut err) = (stringify!($e), std::io::stderr());\n writeln!(err, \"{} = {:?}\", e, $e).unwrap()\n })*\n };\n}\n\nfn main() {\n let a = read::();\n let b = read::();\n let c = read::();\n let b = min(b, c);\n let mut d = read::();\n let e = read::();\n let f = read::();\n if e > f {\n let eset = min(a, d);\n d -= eset;\n let fset = min(b, d);\n println!(\"{}\", e * eset + f * fset);\n } else {\n let fset = min(b, d);\n d -= fset;\n let eset = min(a, d);\n println!(\"{}\", e * eset + f * fset);\n }\n}\n\nfn read() -> T {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn read_vec() -> Vec {\n read::()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "brute force"], "code_uid": "dbe651a9283334758456342298a1cc92", "src_uid": "84d9e7e9c9541d997e6573edb421ae0a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n\nuse std::cmp::Reverse;\n\nfn main() {\n let mut aa: Vec = util::line().chars().collect();\n let bb: Vec = util::line().chars().collect();\n\n let mut amap = HashMap::new();\n let mut bmap = HashMap::new();\n\n for &a in &aa {\n *amap.entry(a).or_insert(0) += 1;\n }\n\n for &b in &bb {\n *bmap.entry(b).or_insert(0) += 1;\n }\n\n if amap == bmap {\n println!(\n \"{}\",\n bb.iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(\"\")\n );\n return;\n }\n\n if aa.len() < bb.len() {\n aa.sort_by_key(|&x| Reverse(x));\n println!(\n \"{}\",\n aa.iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(\"\")\n );\n return;\n }\n\n let ans = (0..aa.len())\n .filter_map(|i| {\n let mut res = Vec::new();\n let mut amap = amap.clone();\n\n for &b in &bb[..i] {\n let c = amap.entry(b).or_insert(0);\n if *c > 0 {\n *c -= 1;\n res.push(b);\n } else {\n return None;\n }\n }\n\n if let Some((&x, _)) = amap.iter().filter(|&(&k, &v)| v > 0 && k < bb[i]).max() {\n res.push(x);\n *amap.entry(x).or_insert(0) -= 1;\n } else {\n return None;\n }\n\n let mut rest = Vec::new();\n for (&k, &v) in amap.iter() {\n for _ in 0..v {\n rest.push(k);\n }\n }\n\n rest.sort_by_key(|&x| Reverse(x));\n\n res.append(&mut rest);\n\n Some(res)\n })\n .max()\n .unwrap();\n\n println!(\n \"{}\",\n ans.iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(\"\")\n );\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "2736234a94795f2b7678b853b056fe99", "src_uid": "bc31a1d4a02a0011eb9f5c754501cd44", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn factorial(x: i32) -> i32 {\n if x < 2 {\n return 1;\n } else {\n return x * factorial(x - 1);\n }\n}\n\nfn main() {\n let reader = io::stdin();\n let numbers: Vec =\n reader.lock() // (0)\n .lines().next().unwrap().unwrap() // (1)\n .split(' ').map(|s| s.trim()) // (2)\n .filter(|s| !s.is_empty()) // (3)\n .map(|s| s.parse().unwrap()) // (4)\n .collect(); // (5)\n\n let mut min= numbers[0];\n if numbers[1] < min {\n min = numbers[1];\n }\n\n println!(\"{}\", factorial(min));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "dfb3c98f9f2d305a32504cd1addd0269", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::cmp::{min, max};\nuse std::mem;\nuse std::str::FromStr;\nuse std::cmp::Ordering;\nuse std::collections::BinaryHeap;\n\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Scanner {\n Scanner {\n reader: reader,\n buffer: Vec::new(),\n }\n }\n\n /// Use \"turbofish\" syntax next::() to select data type of next token.\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n\n pub fn next_vec(&mut self, len: usize) -> Vec\n where\n T::Err: ::std::fmt::Debug,\n {\n (0..len).map(|_| self.next::()).collect::>()\n }\n}\n\nfn main1() {\n let stdin = io::stdin();\n let mut input = Scanner::new(stdin.lock());\n let a: i64 = input.next();\n let b: i64 = input.next();\n let n = min(a, b);\n let answer = (1..(n + 1)).fold(1i64, |mul, x| mul * x);\n println!(\"{}\", answer);\n\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "3ae436bf274fdcbb4ef4cf7f95ade022", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::{FromStr, SplitWhitespace};\nuse std::fmt::Debug;\nuse std::iter::Map;\nuse std::cmp::min;\n\nfn main() {\n let (a,b) = Input::line().pair();\n let res = (1..min::(a,b) + 1).fold(1, |ref x, i| x * i) ;\n println!(\"{}\", res);\n\n}\n\npub trait UParse: FromStr {\n fn uparse(&str) -> Self;\n}\nimpl UParse for T\nwhere\n T: FromStr,\n T::Err: Debug,\n{\n fn uparse(str: &str) -> Self {\n str.trim().parse().unwrap()\n }\n}\n\npub struct Input(String);\nimpl Input {\n pub fn line() -> Input {\n let mut str = String::new();\n io::stdin().read_line(&mut str).unwrap();\n Input(str)\n }\n\n fn trim_parse(s: &str) -> T {\n UParse::uparse(s)\n }\n\n pub fn iter(&self) -> Map T> {\n self.0.split_whitespace().map(Input::trim_parse)\n }\n\n pub fn single(&self) -> T {\n Input::trim_parse(self.0.as_ref())\n }\n\n pub fn pair(&self) -> (A, B) {\n let mut it = self.0.split_whitespace();\n let a = Input::trim_parse(it.next().unwrap());\n let b = Input::trim_parse(it.next().unwrap());\n (a, b)\n }\n\n pub fn triple(&self) -> (A, B, C) {\n let mut it = self.0.split_whitespace();\n let a = Input::trim_parse(it.next().unwrap());\n let b = Input::trim_parse(it.next().unwrap());\n let c = Input::trim_parse(it.next().unwrap());\n (a, b, c)\n }\n\n pub fn quadruple(&self) -> (A, B, C, D) {\n let mut it = self.0.split_whitespace();\n let a = Input::trim_parse(it.next().unwrap());\n let b = Input::trim_parse(it.next().unwrap());\n let c = Input::trim_parse(it.next().unwrap());\n let d = Input::trim_parse(it.next().unwrap());\n (a, b, c, d)\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "3cef498bfb64aa49a385b4bca6b08fc1", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn read_n() -> (u32, u32) {\n let mut buffer = String::new();\n stdin().read_line(&mut buffer).unwrap();\n let snums: Vec<&str> = buffer.trim().split(\" \").collect();\n (snums[0].parse::().unwrap(), snums[1].parse::().unwrap())\n}\n\nfn factorial(x: u32) -> u32 {\n let mut n: u32 = 1;\n for i in 2..x+1 {\n n *= i;\n }\n n\n}\n\n\nfn main() {\n let (a, b) = read_n();\n if a < b {\n println!(\"{}\", factorial(a));\n } else {\n println!(\"{}\", factorial(b));\n }\n}", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "9b3bba14e200dd451842a4f704cabb6a", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::{FromStr, SplitWhitespace};\nuse std::fmt::Debug;\nuse std::iter::Map;\nuse std::cmp::min;\n\nfn main() {\n let (a,b) = Input::line().pair();\n let res = (1..min::(a,b) + 1).fold(1, |ref x, i| x * i) ;\n println!(\"{}\", res);\n\n}\n\npub trait UParse: FromStr {\n fn uparse(&str) -> Self;\n}\nimpl UParse for T\nwhere\n T: FromStr,\n T::Err: Debug,\n{\n fn uparse(str: &str) -> Self {\n str.trim().parse().unwrap()\n }\n}\n\npub struct Input(String);\nimpl Input {\n pub fn line() -> Input {\n let mut str = String::new();\n io::stdin().read_line(&mut str).unwrap();\n Input(str)\n }\n\n fn trim_parse(s: &str) -> T {\n UParse::uparse(s)\n }\n\n pub fn iter(&self) -> Map T> {\n self.0.split_whitespace().map(Input::trim_parse)\n }\n\n pub fn single(&self) -> T {\n Input::trim_parse(self.0.as_ref())\n }\n\n pub fn pair(&self) -> (A, B) {\n let mut it = self.0.split_whitespace();\n let a = Input::trim_parse(it.next().unwrap());\n let b = Input::trim_parse(it.next().unwrap());\n (a, b)\n }\n\n pub fn triple(&self) -> (A, B, C) {\n let mut it = self.0.split_whitespace();\n let a = Input::trim_parse(it.next().unwrap());\n let b = Input::trim_parse(it.next().unwrap());\n let c = Input::trim_parse(it.next().unwrap());\n (a, b, c)\n }\n\n pub fn quadruple(&self) -> (A, B, C, D) {\n let mut it = self.0.split_whitespace();\n let a = Input::trim_parse(it.next().unwrap());\n let b = Input::trim_parse(it.next().unwrap());\n let c = Input::trim_parse(it.next().unwrap());\n let d = Input::trim_parse(it.next().unwrap());\n (a, b, c, d)\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "6add889b79c15f72d8cff33a4038d43f", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn factorial(n: i32) -> i32 {\n if n == 0 {\n 1\n } else {\n n * factorial(n - 1)\n }\n}\n\nuse std::cmp;\nuse std::io;\n\nfn main() {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).unwrap();\n\n let mut iter = input.split_whitespace().map(|p| p.parse::().unwrap());\n\n let a = iter.next().unwrap();\n let b = iter.next().unwrap();\n\n let c = cmp::min(a, b);\n println!(\"{}\", factorial(c));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "e23d6bfd04e48a86393b6b42aae99cc0", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn fact(n: u32) -> u32 {\n if n == 1 {\n 1\n } else {\n n * fact(n - 1)\n }\n}\n\nfn main() {\n let (a, b) = {\n let mut buf = String::with_capacity(3);\n std::io::stdin().read_line(&mut buf).unwrap();\n let nums: Vec = buf\n .trim()\n .split_whitespace()\n .map(|a| a.parse().unwrap())\n .collect();\n (nums[0], nums[1])\n };\n\n print!(\"{}\", fact(a.min(b)));\n}", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "2fe9d7d67017b717b8fb76408cbd28a1", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn factorial(x: usize) -> usize {\n let mut result: usize = 1;\n for i in 1..=x {\n result *= i;\n }\n result\n}\n\nstruct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: usize = scan.next();\n let b: usize = scan.next();\n println!(\"{}\", factorial(a.min(b)));\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "4a1419be55e64f1361f95cec87e596d2", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\n\nfn prime_factorization(mut n: u64) -> Vec<(u64, u64)> {\n let mut i = 2;\n let mut ans = vec![];\n while i*i <= n {\n let mut cnt = 0;\n while n%i == 0 {\n n /= i;\n cnt += 1;\n }\n if cnt > 0 {\n ans.push((i, cnt));\n }\n i += 1;\n }\n if n > 1 {\n ans.push((n, 1));\n }\n ans\n}\n\nfn fact_num(n: u64, v: u64) -> u64 {\n if n < v {\n return 0;\n }\n let div = n/v;\n div + fact_num(div, v)\n}\n\n\nfn main() {\n input!{\n n: u64,\n b: u64,\n }\n let facts = prime_factorization(b);\n let mut ans: i64 = -1;\n for i in 0..facts.len() {\n let (v, pow) = facts[i];\n let fnum = fact_num(n, v);\n if ans == -1 {\n ans = (fnum/pow) as i64;\n } else {\n ans = min(ans, (fnum/pow) as i64);\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "86d95870f7feafdb0a6bb4e321f0d032", "src_uid": "491748694c1a53771be69c212a5e0e25", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(n,b: i64 = input.p());\n let mut sol = n;\n let mut b = b;\n let mut i = 2;\n while b > 1 {\n if i * i > b {\n i = b;\n }\n if b % i == 0 {\n let mut c = 0;\n while b % i == 0 {\n b /= i;\n c += 1;\n }\n let mut a = n;\n let mut b = 0;\n while a > 0 {\n a /= i;\n b += a;\n }\n m!(<, sol, b/c);\n }\n i += 1;\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "d791242dd5b762c1f2231cea0d520a53", "src_uid": "491748694c1a53771be69c212a5e0e25", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nmod pollard_rho {\n use std::collections::HashMap;\n /// binary gcd\n pub fn gcd(mut x: i64, mut y: i64) -> i64 {\n if y == 0 { return x; }\n if x == 0 { return y; }\n let mut sh = 0;\n while ((x | y) & 1) == 0 {\n x >>= 1; y >>= 1; sh += 1;\n }\n while (x & 1) == 0 { x >>= 1; }\n while y != 0 {\n while (y & 1) == 0 { y >>= 1; }\n if x > y { let t = x; x = y; y = t; }\n y -= x;\n }\n x << sh\n }\n\n fn add_mod(x: i64, y: i64, n: i64) -> i64 {\n let z = x + y;\n if z >= n { z - n } else { z }\n }\n\n fn mul_mod(x: i64, mut y: i64, n: i64) -> i64 {\n assert!(x >= 0);\n assert!(x < n);\n let mut sum = 0;\n let mut cur = x;\n while y > 0 {\n if (y & 1) == 1 {\n sum = add_mod(sum, cur, n);\n }\n cur = add_mod(cur, cur, n);\n y >>= 1;\n }\n sum\n }\n\n fn mod_pow(x: i64, mut e: i64, n: i64) -> i64 {\n let mut prod = if n == 1 { 0 } else { 1 };\n let mut cur = x % n;\n while e > 0 {\n if (e & 1) == 1 {\n prod = mul_mod(prod, cur, n);\n }\n cur = mul_mod(cur, cur, n);\n e >>= 1;\n }\n prod\n }\n\n pub fn is_prime(n: i64) -> bool {\n if n <= 1 { return false; }\n let small = [2, 3, 5, 7, 11, 13];\n if small.iter().any(|&u| u == n) { return true; }\n if small.iter().any(|&u| n % u == 0) { return false; }\n let mut d = n - 1;\n let mut e = 0;\n while (d & 1) == 0 {\n d >>= 1;\n e += 1;\n }\n let a = [2, 325, 9375, 28178, 450775, 9780504, 1795265022];\n a.iter().all(|&a| {\n if a >= n { return true; }\n let mut x = mod_pow(a, d, n);\n if x == 1 { return true; }\n for _ in 0 .. e {\n if x == n - 1 {\n return true;\n }\n x = mul_mod(x, x, n);\n if x == 1 { return false; }\n }\n x == 1\n })\n }\n\n fn pollard_rho(n: i64, c: &mut i64) -> i64 {\n if n % 2 == 0 { return 2; }\n loop {\n let mut x: i64 = 2;\n let mut y = 2;\n let mut d = 1;\n let cc = *c;\n let f = |i| add_mod(mul_mod(i, i, n), cc, n);\n while d == 1 {\n x = f(x);\n y = f(f(y));\n d = gcd((x - y).abs(), n);\n }\n if d == n {\n *c += 1;\n continue;\n }\n return d;\n }\n }\n\n /// Outputs (p, e) in p's ascending order.\n pub fn factorize(x: i64) -> Vec<(i64, usize)> {\n if x <= 1 {\n return Vec::new();\n }\n let mut hm = HashMap::new();\n let mut pool = vec![x];\n let mut c = 1;\n while let Some(u) = pool.pop() {\n if is_prime(u) {\n *hm.entry(u).or_insert(0) += 1;\n continue;\n }\n let p = pollard_rho(u, &mut c);\n pool.push(p);\n pool.push(u / p);\n }\n let mut v: Vec<_> = hm.into_iter().collect();\n v.sort();\n v\n }\n} // mod pollard_rho\n\nuse pollard_rho::*;\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: i64,\n b: i64,\n }\n let fac = factorize(b);\n let mut mi: i64 = 1 << 62;\n for (p, e) in fac {\n let mut tot = 0;\n let mut v = n;\n while v > 0 {\n v /= p;\n tot += v;\n }\n mi = min(mi, tot / e as i64);\n }\n puts!(\"{}\\n\", mi);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "c6466c1c95e97d58ca43701430e68acd", "src_uid": "491748694c1a53771be69c212a5e0e25", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::min;\n\nfn main() {\n let tmp = readline_ints();\n let n = tmp[0];\n let b = tmp[1];\n\n let fs = factor(b);\n let mut ans = std::i64::MAX;\n\n // println!(\"{:?}\", fs);\n\n for &(p, cnt) in fs.iter() {\n //println!(\"{}\", count(n, p) / cnt);\n ans = min(count(n, p) / cnt, ans);\n }\n \n println!(\"{}\", ans);\n}\n\nfn factor(mut n: i64) -> Vec<(i64, i64)> {\n let mut fs: Vec<(i64, i64)> = Vec::new();\n for i in 2..((n as f64).sqrt().ceil() as i64 + 1) {\n let mut cnt = 0i64;\n while n % i == 0 {\n n /= i;\n cnt += 1;\n }\n if cnt > 0 {\n fs.push((i as i64, cnt));\n }\n }\n if n > 1 {\n fs.push((n, 1));\n }\n fs\n}\n\nfn count(n: i64, p: i64) -> i64 {\n let mut c = 0i64;\n let mut b = p;\n while n >= b {\n c += n / b; \n //println!(\"n = {}, b = {}, n/b = {}\", n, b, n/b);\n\n if n/b >= p {\n b *= p;\n } else {\n break;\n }\n }\n c\n}\n\nfn readline_ints() -> Vec {\n let mut strs = String::new();\n let _ = io::stdin().read_line(&mut strs);\n strs.split_whitespace().map(|s| s.parse::().unwrap()).collect()\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "f7837bf60fd9023d8759d46ab87aa387", "src_uid": "491748694c1a53771be69c212a5e0e25", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet};\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n\n #[allow(dead_code)]\n pub fn get3() -> (S, T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn main() {\n let n: i64 = util::get();\n let n_digits = (1..).find(|&d| 10i64.pow(d as u32) > n).unwrap();\n\n let ans: Vec = (max(0, n - n_digits * 9)..n + 1)\n .filter(|&x| {\n let mut a = x;\n let mut y = x;\n\n while y > 0 {\n a += y % 10;\n y /= 10;\n }\n\n a == n\n })\n .collect();\n\n if ans.is_empty() {\n println!(\"0\");\n } else {\n println!(\"{}\", ans.len());\n for &x in &ans {\n println!(\"{}\", x);\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "d0e10003278481e04de316bdb37847a7", "src_uid": "ae20ae2a16273a0d379932d6e973f878", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, BufRead, BufReader};\nuse std::vec::Vec;\nuse std::process;\n\nconst MAX_DIFF: i32 = 90;\n\nfn digit_sum(n: i32) -> i32 {\n let mut result = 0;\n let mut t = n;\n while t > 0 {\n result = result + (t % 10);\n t = t / 10;\n }\n result\n}\n\nfn solve(n: i32) -> Vec {\n let mut result: Vec = Vec::new();\n for x in 1..MAX_DIFF {\n let t = n - x;\n if digit_sum(t) == x {\n result.push(t);\n }\n }\n result\n}\n\n#[allow(non_snake_case)]\n#[allow(unused_variables)]\nfn main() {\n let mut reader = BufReader::new(stdin());\n let mut s = String::new();\n reader.read_line(&mut s).unwrap();\n let N = s.trim_right().parse::().unwrap();\n let mut solved = solve(N);\n let mut result = solved.as_mut_slice();\n result.sort();\n println!(\"{}\", result.len());\n if result.len() == 0 {\n process::exit(0);\n }\n s.clear();\n for i in 0..result.len() {\n s.push_str(result[i].to_string().as_str());\n if i != result.len() - 1 {\n s.push(' ');\n }\n }\n println!(\"{}\", s);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "c9c1f260694773c28d1d3a326cd73264", "src_uid": "ae20ae2a16273a0d379932d6e973f878", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nconst N: i64 = 998_244_353;\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let n: u32 = get_line().trim().parse().unwrap();\n\n // La somme est inf\u00e9rieure \u00e0 81.\n // n <= x + 81\n // n - 81 <= x <= n\n\n let min_ind = if n > 81 {\n n - 81\n } else {\n 0\n };\n\n let digit_sum = |x| {\n let s = format!(\"{}\", x);\n s.bytes().map(|b| (b - b'0') as u32).sum::()\n };\n\n let answers: Vec<_> = (min_ind..n + 1).filter(|&i| i + digit_sum(i) == n).collect();\n\n println!(\"{}\", answers.len());\n for ans in answers {\n println!(\"{}\", ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "af91df3fd0aab2a805c0aed968a671be", "src_uid": "ae20ae2a16273a0d379932d6e973f878", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::io::prelude::*;\nuse std::iter::*;\nuse std::str::SplitWhitespace;\nuse std::cmp::max;\n\nfn main() {\n let mut input = InRead::new();\n let n = input.int();\n let mut sols = Vec::new();\n for i in max(n - 90, 1)..n {\n if i + sumdigits(i) == n { sols.push(i.to_string()) };\n }\n println!(\"{}\\n{}\", sols.len(), sols.join(\" \"));\n}\n\nfn sumdigits(x: i32) -> i32 {\n if x == 0 { 0 } else { (x % 10) + sumdigits(x / 10) }\n}\n\nstruct InRead(String);\n\nimpl InRead {\n fn new() -> InRead {\n InRead(String::new())\n }\n fn get_line(self: &mut Self) {\n self.0.clear();\n stdin().read_line(&mut self.0);\n }\n fn parse_int(s: &str) -> i32 { s.parse().unwrap() }\n fn ints(self: &mut Self) -> Map i32> {\n self.get_line();\n self.0.split_whitespace().map(InRead::parse_int)\n }\n fn int_vec(self: &mut Self) -> Vec { self.ints().collect() }\n fn int(self: &mut Self) -> i32 { self.ints().next().unwrap() }\n fn int2(self: &mut Self) -> (i32, i32) {\n let mut is = self.ints();\n (is.next().unwrap(), is.next().unwrap())\n }\n fn int3(self: &mut Self) -> (i32, i32, i32) {\n let mut is = self.ints();\n (is.next().unwrap(), is.next().unwrap(), is.next().unwrap())\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "dc74399e91e4c982658b67e919e9a843", "src_uid": "ae20ae2a16273a0d379932d6e973f878", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let n = parse_line!(usize);\n let ok = n % 2 == 1;\n writeln!(writer, \"{}\", if ok {\"Ehab\"} else {\"Mahmoud\"}).unwrap();\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "fb9983ca3683a35b039e83409d18397d", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\n\npub fn main() {\n let input = get_input();\n match input % 2 {\n 0 => println!(\"Mahmoud\"),\n _ => println!(\"Ehab\"),\n };\n}\n\nfn get_input() -> u64 {\n let mut input = String::new();\n io::stdin().read_line(&mut input);\n input.trim().parse::().unwrap()\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "f53449229b0f7dafbaa63aa22863b694", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n\n let num: i32 = input.trim().parse().unwrap();\n\n if num % 2 == 0 {\n println!(\"Mahmoud\");\n } else {\n println!(\"Ehab\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "2efda59108ef89a65d5197db3d89a2b0", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use procon::*;\nuse std::io;\nfn main() {\n try_main().unwrap();\n}\n\nfn try_main() -> Result<(), Box> {\n let stdin = io::stdin();\n let mut sc = Scanner::new(stdin.lock());\n let n = sc.next::();\n if n % 2 == 0 {\n println!(\"Mahmoud\");\n } else {\n println!(\"Ehab\");\n }\n Ok(())\n}\n\nmod procon {\n use std::io;\n use std::cmp::Ordering;\n /// Scanner is taken from https://github.com/EbTech/rust-algorithms\n pub struct Scanner {\n reader: B,\n buffer: Vec,\n }\n\n impl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n }\n\n pub fn merge<'a, T>(this: &'a [T], that: &'a [T], out: &'a mut [T])\n where T: Ord + Copy {\n let mut i = 0;\n let mut j = 0;\n let mut oind = 0;\n while i < this.len() && j < that.len() {\n if this[i] <= that[j] {\n out[oind] = this[i];\n i += 1;\n } else {\n out[oind] = that[j];\n j += 1;\n }\n oind += 1;\n }\n while i < this.len() {\n out[oind] = this[i];\n i += 1;\n oind += 1;\n }\n while j < that.len() {\n out[oind] = that[j];\n j += 1;\n oind += 1;\n }\n }\n\n\n /// trait for implementing functions to get lower/upper bounds (implementation is based on the rust std library)\n /// the functions return OK(indx) if self[indx] is the element we queried.\n /// e.g., in lower_bound_by, f(self[indx]) returns Ordering::Equal if the function returned Ok(indx).\n /// Further, if all the elements are less than the queried value, lower_bound/upper_bound must return Err(self.len()).\n /// Similarly, all the elements are greater than the queried value, they must return Err(0).\n pub trait CmpSearch {\n type Item;\n\n fn find_bound_by<'a, F>(&'a self, f: F, is_lower: bool) -> Result\n where F: FnMut(&'a Self::Item) -> Ordering;\n\n fn find_bound_by_key<'a, B, F>(&'a self, b: &B, f: F, is_lower: bool) -> Result\n where F: FnMut(&'a Self::Item) -> B,\n B: Ord;\n\n /// returns Result which contains the lowest index indx that satisfies the following condition,\n /// assuming that self is already sorted:\n /// 1. self[i] < x if i < indx\n /// 2. self[i] >= x if i >= indx\n /// 3. self.insert(indx, x) keeps the sorted order.\n /// The return value is Ok(indx) if there is an index that satisfies x.cmp(self[indx]) == Ordering::Equal.\n /// Otherwise the return value is Err(indx).\n ///\n fn lower_bound(&self, x: &Self::Item) -> Result\n where Self::Item: Ord {\n self.find_bound_by(|elem| { elem.cmp(x) }, true)\n }\n\n\n /// returns Result which contains the highest index indx that satisfies the following condition,\n /// assuming that self is already sorted:\n /// 1. self[i] <= x if i <= indx\n /// 2. self[i] > x if i > indx\n /// 3. self.insert(indx, x) keeps the sorted order.\n /// The return value is Ok(indx) if there is an index that satisfies x.cmp(self[indx]) == Ordering::Equal.\n /// Otherwise the return value is Err(indx).\n ///\n fn upper_bound(&self, x: &Self::Item) -> Result\n where Self::Item: Ord {\n self.find_bound_by(|elem| { elem.cmp(x) }, false)\n }\n }\n\n impl CmpSearch for [T] {\n type Item = T;\n\n /// loop invariants (if is_lower = true):\n /// 1. f(self[lb]) == Less, assuming that lb >= 0\n /// 2. f(self[ub]) == Greater or Equal, assuming that gb < self.len()\n /// 3. lb < ub; in particular, lb != ub\n ///\n /// after the loop:\n /// 1. if ub < self.len(), ub is a valid index in the slice\n /// 2. if lb == -1, ub == 0 and:\n /// 2-1. f(self[0]) == Equal then the return value is Ok(0)\n /// 2-2. f(self[0]) == Greater then the return value is Err(0)\n /// 3. if ub == self.len(), lb == self.len() - 1 and the return value is Err(self.len())\n ///\n /// a similar set of conditions holds if is_lower = false.\n ///\n fn find_bound_by<'a, F>(&'a self, mut f: F, is_lower: bool) -> Result\n where F: FnMut(&'a Self::Item) -> Ordering {\n let mut lb: isize = -1;\n let mut ub: isize = self.len() as isize;\n let mut step = (ub - lb) / 2;\n while step > 0 {\n let m = (lb + step) as usize;\n match f(&self[m]) {\n Ordering::Less => {\n lb = m as isize;\n },\n Ordering::Greater => {\n ub = m as isize;\n },\n Ordering::Equal => {\n if is_lower {\n ub = m as isize;\n } else {\n lb = m as isize;\n }\n }\n }\n step = (ub - lb) / 2\n }\n\n if is_lower {\n if ub as usize == self.len() {\n Err(self.len())\n } else {\n let ub = ub as usize;\n match f(&self[ub]) {\n Ordering::Equal => {\n Ok(ub)\n },\n _ => {\n Err(ub)\n }\n }\n }\n } else {\n if lb == -1 {\n Err(0)\n } else {\n let lb = lb as usize;\n match f(&self[lb]) {\n Ordering::Equal => {\n Ok(lb)\n },\n _ => {\n Err(lb+1)\n }\n }\n }\n }\n }\n\n fn find_bound_by_key<'a, B, F>(&'a self, b: &B, mut f: F, is_lower: bool) -> Result\n where F: FnMut(&'a Self::Item) -> B,\n B: Ord {\n self.find_bound_by(|elem|{ f(elem).cmp(b) }, is_lower)\n }\n\n\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::procon::*;\n\n #[test]\n fn test_find_bound_by() {\n let s = [0, 2, 2, 2, 4];\n // lower bound\n let seek = 2;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), true), Ok(1));\n let seek = 1;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), true), Err(1));\n let seek = -1;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), true), Err(0));\n let seek = 5;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), true), Err(5));\n // upper bound\n let seek = 2;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), false), Ok(3));\n let seek = 1;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), false), Err(1));\n let seek = 5;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), false), Err(5));\n let seek = -1;\n assert_eq!(s.find_bound_by(|probe| probe.cmp(&seek), false), Err(0));\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "9d11aa0d091dc55c9d18fd85c1c48b4d", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)?;\n\n let n = input.trim().parse::().unwrap();\n\n match n % 2 {\n 0 => println!(\"Mahmoud\"),\n 1 => println!(\"Ehab\"),\n _ => println!(\"Invalid number\"),\n }\n\n Ok(())\n}", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "13d1772fc171c9343a7dae0d72088547", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let n = line.trim().parse::().unwrap();\n \n if n % 2 == 0 {\n println!(\"Mahmoud\")\n } else {\n println!(\"Ehab\")\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "c66cd0f485b65f9849cdfb0b943efe61", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn get_line() -> io::Result {\n\tlet mut buffer = String::new();\n\n\tio::stdin().read_line(&mut buffer)?;\n\tOk(buffer)\n}\n\nfn main() {\n\tlet input = get_line().unwrap();\n\tlet n: u32 = input.trim().parse().unwrap();\n\n\tprint!(\"{}\", if n % 2 == 0 { \"Mahmoud\" } else { \"Ehab\" });\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "c92c48fe1a42da1cf778488c14423131", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut val = String::new();\n\n io::stdin().read_line(&mut val)\n .expect(\"\u041d\u0435 \u0443\u0434\u0430\u043b\u043e\u0441\u044c \u043f\u0440\u043e\u0447\u0438\u0442\u0430\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0443\");\n\n let val: u32 = val.trim().parse()\n .expect(\"\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e!\");\n\n if val % 2 == 0 {\n println!(\"Mahmoud\");\n } else {\n println!(\"Ehab\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "f54aa3c15682b7ffa4b3e459850d3b0c", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::iter::*;\n\nfn main() {\n let mut inp = ReadIn::new();\n let n = inp.int() as usize;\n let dices: Vec> = repeat(()).take(n).map(|_| inp.intvec()).collect();\n let mut res = nums(&dices);\n res.sort();\n let cnt = res.iter().scan(0, |p, &el| {\n if *p + 1 >= el {\n *p = el;\n Some(el)\n } else { None }\n }\n ).last().unwrap();\n println!(\"{:?}\", cnt);\n}\n\nfn nums(digs: &Vec>) -> Vec {\n if digs.is_empty() { vec![0] } else {\n digs.iter()\n .enumerate()\n .flat_map(|(i, v)| {\n let mut v1 = digs.clone();\n v1.remove(i);\n nums(&v1)\n .into_iter()\n .flat_map(move |n| v\n .iter()\n .map(move |d| n * 10 + d)\n .chain(once(n)))\n })\n .collect()\n }\n}\n\n\nuse std::str::SplitWhitespace;\nuse std::io::stdin;\nuse std::mem::forget;\n\npub struct ReadIn(pub String);\n\nimpl ReadIn {\n pub fn new() -> ReadIn { ReadIn(String::new()) }\n fn read_i32(s: &str) -> i32 { s.parse().unwrap() }\n pub fn read_line(&mut self) {\n self.0.clear();\n forget(stdin().read_line(&mut self.0));\n }\n pub fn ints(&mut self) -> Map i32> {\n self.read_line();\n self.0.split_whitespace().map(ReadIn::read_i32)\n }\n pub fn intvec(&mut self) -> Vec { self.ints().collect() }\n pub fn int(&mut self) -> i32 { self.ints().next().unwrap() }\n pub fn int2(&mut self) -> (i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap())\n }\n\n pub fn int3(&mut self) -> (i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n pub fn int4(&mut self) -> (i32, i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "1bc1cb324c3ad32d788caca46e144493", "src_uid": "20aa53bffdfd47b4e853091ee6b11a4b", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let n: usize = get_line().trim().parse().unwrap();\n\n let cubes: Vec<_> = BufReader::new(io::stdin()).lines()\n .map(|s| {\n let s = s.unwrap();\n let mut cube = [false; 10];\n for s in s.split_whitespace() {\n let d = s.bytes().last().unwrap();\n let d = (d - b'0') as usize;\n cube[d] = true;\n }\n cube\n }).collect();\n\n let perms = match n {\n 3 => vec![\n vec![0, 1, 2],\n vec![0, 2, 1],\n vec![1, 0, 2],\n vec![1, 2, 0],\n vec![2, 0, 1],\n vec![2, 1, 0],\n ],\n 2 => vec![\n vec![0, 1],\n vec![1, 0],\n ],\n 1 => vec![vec![0]],\n _ => panic!(\"\"),\n };\n\n\n let fact = |n| {\n let mut ret_val = 1;\n for i in 0..n {\n ret_val *= i + 1;\n }\n ret_val\n };\n\n let check = |x| {\n let x = format!(\"{}\", x);\n for perm in perms.iter().take(fact(n)) {\n let p = x.bytes().map(|b| (b - b'0') as usize)\n .zip(perm.iter()).all(|(d, &i)| cubes[i][d]);\n if p {\n return true;\n }\n }\n false\n };\n\n for i in 1.. {\n if !check(i) {\n println!(\"{}\", i - 1);\n return;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "fe1b74ff03a673fecf11e4f9242440dc", "src_uid": "20aa53bffdfd47b4e853091ee6b11a4b", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n\n #[allow(dead_code)]\n pub fn get3() -> (S, T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn main() {\n let n: usize = util::get();\n let ss: Vec> = (0..n)\n .map(|_| {\n let mut v: Vec = util::gets();\n v.sort();\n v\n })\n .collect();\n\n let ans = (1..)\n .take_while(|&x| if x < 10 {\n ss.iter().any(|v| v.binary_search(&x).is_ok())\n } else if x < 100 {\n let a1 = x % 10;\n let a2 = x / 10;\n\n let h1 = (0..ss.len())\n .filter(|&i| ss[i].binary_search(&a1).is_ok())\n .collect::>();\n let h2 = (0..ss.len())\n .filter(|&i| ss[i].binary_search(&a2).is_ok())\n .collect::>();\n\n (h1.len() > 1 && h2.len() > 1) ||\n (h1.len() > 0 && h2.len() > 0 &&\n (h1.difference(&h2).count() != 0 || h2.difference(&h1).count() != 0))\n\n } else {\n let perm = vec![\n vec![0, 1, 2],\n vec![0, 2, 1],\n vec![1, 0, 2],\n vec![1, 2, 0],\n vec![2, 0, 1],\n vec![2, 1, 0],\n ];\n\n let a1 = x % 10;\n let a2 = x / 10 % 10;\n let a3 = x / 100;\n let a = vec![a1, a2, a3];\n\n if n < 3 {\n false\n } else {\n perm.iter().any(|p| {\n p.iter().zip(a.iter()).all(|(&i, &k)| {\n ss[i].binary_search(&k).is_ok()\n })\n })\n }\n\n })\n .last();\n\n if let Some(a) = ans {\n println!(\"{}\", a);\n } else {\n println!(\"0\");\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "4f3e08ccb1349e797104e7ce651fef4b", "src_uid": "20aa53bffdfd47b4e853091ee6b11a4b", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::iter::*;\n\nfn main() {\n let mut inp = ReadIn::new();\n let n = inp.int() as usize;\n let dices: Vec> = repeat(()).take(n).map(|_| inp.intvec()).collect();\n let mut res: Vec = nums(dices).collect();\n res.sort();\n let cnt = res.iter().scan(0, |p, &el| {\n if *p + 1 >= el {\n *p = el;\n Some(el)\n } else { None }\n }\n ).last().unwrap();\n println!(\"{:?}\", cnt);\n}\n\nfn nums<'a>(digs: Vec>) -> Box + 'a> {\n if digs.is_empty() { Box::new(once(0)) } else {\n let d1 = digs.clone();\n Box::new(d1.into_iter()\n .enumerate()\n .flat_map(move |(i, v)| {\n let mut v1 = digs.clone();\n v1.remove(i);\n nums(v1)\n .into_iter()\n .flat_map(move |n|\n v.clone()\n .into_iter()\n .map(move |d| n * 10 + d)\n .chain(once(n)))\n }))\n }\n}\n\n\nuse std::str::SplitWhitespace;\nuse std::io::stdin;\nuse std::mem::forget;\n\npub struct ReadIn(pub String);\n\nimpl ReadIn {\n pub fn new() -> ReadIn { ReadIn(String::new()) }\n fn read_i32(s: &str) -> i32 { s.parse().unwrap() }\n pub fn read_line(&mut self) {\n self.0.clear();\n forget(stdin().read_line(&mut self.0));\n }\n pub fn ints(&mut self) -> Map i32> {\n self.read_line();\n self.0.split_whitespace().map(ReadIn::read_i32)\n }\n pub fn intvec(&mut self) -> Vec { self.ints().collect() }\n pub fn int(&mut self) -> i32 { self.ints().next().unwrap() }\n pub fn int2(&mut self) -> (i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap())\n }\n\n pub fn int3(&mut self) -> (i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n pub fn int4(&mut self) -> (i32, i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "3478979b236d45c2903668d59dc0dd03", "src_uid": "20aa53bffdfd47b4e853091ee6b11a4b", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let stdin = std::io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n String::from(line.trim())\n}\n\nmacro_rules! scan_line {\n ($($ty: ty),*) => {{\n let line = read_line();\n let mut tok = line.split_whitespace();\n ($(tok.next().unwrap().parse::<$ty>().unwrap()),*)\n }}\n}\n\nfn check(dice: &[[i32; 6]], digits: &[i32]) -> bool {\n if dice.len() < digits.len() {\n println!(\"a\");\n false\n } else if digits.len() == 0 {\n true\n } else {\n let mut leftover_dice: Vec<[i32; 6]> = dice[1..].iter().cloned().collect();\n let mut has_solution = false;\n for (i, &die) in dice.iter().enumerate() {\n if die.iter().any(|&a| a == digits[0]) && check(&leftover_dice, &digits[1..]) {\n has_solution = true;\n break;\n }\n if i < leftover_dice.len() {\n leftover_dice[i] = die;\n }\n }\n has_solution\n }\n}\n\nfn main() {\n let n = scan_line!(i32);\n let mut dice = Vec::new();\n for _ in 0..n {\n let (a, b, c, d, e, f) = scan_line!(i32, i32, i32, i32, i32, i32);\n dice.push([a, b, c, d, e, f]);\n }\n let mut max_valid = 0;\n for i in 1.. {\n let mut digits = Vec::new();\n let mut j = i;\n while j > 0 {\n digits.push(j % 10);\n j /= 10;\n }\n let is_valid = check(&dice, &digits);\n if is_valid {\n max_valid = i;\n } else {\n break;\n }\n }\n println!(\"{}\", max_valid);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "ca2cb1bfc4d3cb72aec892fa201124c1", "src_uid": "20aa53bffdfd47b4e853091ee6b11a4b", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let mut text = String::new();\n stdin().read_line(&mut text).unwrap();\n let text: Vec = text\n .trim()\n .split_whitespace()\n .collect::>()\n .iter()\n .map(|e| e.parse().unwrap())\n .collect();\n let (a, b) = (text[0], text[1]);\n let mut values = vec![];\n if a == truc(b, a, &mut values) {\n println!(\"YES\");\n println!(\"{}\", values.len());\n let mut text = String::new();\n text.push_str(a.to_string().as_str());\n for i in (0..(values.len() - 1)).rev() {\n text = format!(\"{} {}\", text, values[i]);\n }\n println!(\"{}\", text)\n } else {\n println!(\"NO\")\n }\n}\n\nfn truc(i: usize, b: usize, v: &mut Vec) -> usize {\n v.push(i);\n if i == b {\n i\n } else if i % 10 == 1 && i > 1 {\n truc((i - 1) / 10, b, v)\n } else if i % 2 == 0 {\n truc(i / 2, b, v)\n } else {\n i\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "brute force"], "code_uid": "7e54cecb57cbac89bf2394786057c618", "src_uid": "fc3adb1a9a7f1122b567b4d8afd7b3f3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> io::Result {\n let mut input_str = String::new();\n\n try!(io::stdin().read_line(&mut input_str));\n\n Ok(input_str)\n}\n\nfn a_to_b(a: u32, b: u32) -> Vec {\n let mut result = Vec::new();\n let mut current_state = b;\n\n loop {\n match current_state {\n x if (x < a) || (x > a && x % 2 != 0 && x % 10 != 1) => {\n result.clear();\n break;\n }\n x => {\n result.push(x); \n match x {\n x if x == a => break, \n x if x % 2 == 0 => current_state /= 2,\n _ => current_state /= 10, \n }\n } \n }\n }\n\n result.reverse();\n result\n}\n\nfn main() { \n let input_line = read_line().expect(\"Failed to read line.\");\n let mut input_line_iter = input_line.split_whitespace();\n\n let given_number = input_line_iter.next()\n .expect(\"First number is not given.\")\n .parse::()\n .expect(\"First number is invalid.\");\n let result_number = input_line_iter.next()\n .expect(\"Second number is not given.\")\n .parse::()\n .expect(\"Second number is invalid\");\n\n let answer_sequence = a_to_b(given_number, result_number);\n\n match answer_sequence.len() {\n 0 => println!(\"NO\"),\n len => {\n println!(\"YES\\n{}\", len);\n for number in answer_sequence {\n print!(\"{} \", number);\n }\n } \n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "brute force"], "code_uid": "361a7336594e23e9485729106e0118f4", "src_uid": "fc3adb1a9a7f1122b567b4d8afd7b3f3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n\nstruct Reader {}\n\nimpl Reader {\n #[allow(unused)]\n fn read_string() -> String {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.trim().to_string()\n }\n\n #[allow(unused)]\n fn read_tokens() -> Vec:: {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n v\n }\n}\n\n//mod math;\n//mod binary_search;\n//mod graph;\n\nfn generate(value: i64, limit: i64, list: Vec, res: &mut Vec) {\n if value == limit {\n *res = list.clone();\n }\n\n let next_value = value * 2;\n if next_value <= limit {\n let mut v = list.clone();\n v.push(next_value);\n generate(next_value, limit, v, res);\n }\n let next_value = value * 10 + 1;\n if next_value <= limit {\n let mut v = list.clone();\n v.push(next_value);\n generate(next_value, limit, v, res);\n }\n}\n\nfn main() {\n let tokens = Reader::read_tokens();\n let a = tokens[0].parse::().unwrap();\n let b = tokens[1].parse::().unwrap();\n\n let mut res = Vec::::new();\n\n generate(a, b, vec![a], &mut res);\n\n match res.len() > 1 {\n true => {\n println!(\"YES\");\n println!(\"{}\", res.len());\n for value in res {\n print!(\"{} \", value);\n }\n\n },\n _ => {\n println!(\"NO\");\n }\n }\n}", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "brute force"], "code_uid": "d5cd44b5a4a5b4966f5f1ab33171d937", "src_uid": "fc3adb1a9a7f1122b567b4d8afd7b3f3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn read_numbers() -> (i64, i64) {\n let stdin = io::stdin();\n let mut input = String::new();\n stdin.read_line(&mut input);\n let data: Vec = input\n .split_whitespace()\n .map(|x| i64::from_str(x).unwrap())\n .collect();\n (data[0], data[1])\n}\n\nfn rec(a: i64, b: i64, result: &mut Vec) -> bool {\n if a > b {\n return false;\n }\n\n if a == b || rec(10 * a + 1, b, result) == true || rec(2 * a, b, result) == true {\n result.push(a);\n return true;\n }\n\n false\n}\n\nfn main() {\n let (a, b) = read_numbers();\n let mut vec: Vec = vec![];\n let yes = rec(a, b, &mut vec);\n\n if yes == true {\n println!(\"YES\");\n println!(\"{}\", vec.len());\n\n for i in vec.iter().rev() {\n print!(\"{} \", i);\n }\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "brute force"], "code_uid": "c6b9fc08917deec4e5f06c08e7b849a2", "src_uid": "fc3adb1a9a7f1122b567b4d8afd7b3f3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> io::Result {\n let mut input_str = String::new();\n\n try!(io::stdin().read_line(&mut input_str));\n\n Ok(input_str)\n}\n\nfn a_to_b(a: u32, b: u32) -> Vec {\n let mut result = Vec::new();\n let mut current_state = b;\n\n loop {\n match current_state {\n x if (x < a) || (x > a && x % 2 != 0 && x % 10 != 1) => {\n result.clear();\n break;\n }\n x => {\n result.push(x); \n match x {\n x if x == a => break, \n x if x % 2 == 0 => current_state /= 2,\n _ => current_state /= 10, \n }\n } \n }\n }\n\n result.reverse();\n result\n}\n\nfn main() { \n let input_line = read_line().expect(\"Failed to read line.\");\n let mut input_line_iter = input_line.split_whitespace();\n\n let given_number = input_line_iter.next()\n .expect(\"First number is not given.\")\n .parse::()\n .expect(\"First number is invalid.\");\n let result_number = input_line_iter.next()\n .expect(\"Second number is not given.\")\n .parse::()\n .expect(\"Second number is invalid\");\n\n let answer_sequence = a_to_b(given_number, result_number);\n\n match answer_sequence.len() {\n 0 => println!(\"NO\"),\n len => {\n println!(\"YES\\n{}\", len);\n for number in answer_sequence {\n print!(\"{} \", number);\n }\n } \n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "brute force"], "code_uid": "913ecd21279ddc40f2fa29bebc288e95", "src_uid": "fc3adb1a9a7f1122b567b4d8afd7b3f3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!(usize);\n let mut xs = vec![];\n for _ in 0..n {\n let x = get!();\n xs.push(x);\n }\n xs.sort();\n let mut ans = 0;\n for i in 0..n/2 {\n ans += xs[i*2+1]-xs[i*2];\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "ec710b6e9840e133ebb6ac857a8a0eba", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin};\n\nfn main() {\n let mut students_count = String::new();\n stdin().read_line(&mut students_count).expect(\"expected count input\");\n let _count : u32 = students_count.trim().parse().unwrap();\n let mut students_score = String::with_capacity(500);\n stdin().read_line(&mut students_score).expect(\"expected students score\");\n let mut scores_arr : Vec = students_score.trim().split(\" \")\n .map(|score| score.parse::().unwrap())\n .collect();\n scores_arr.sort();\n let mut problems_to_solve : u32 = 0;\n for i in (0..(scores_arr.len() - 1)).step_by(2) {\n let diff : u32 = scores_arr[i + 1] - scores_arr[i];\n problems_to_solve = problems_to_solve + diff;\n }\n println!(\"{}\", problems_to_solve);\n}", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "1d02d75c189a201df95b3da6347dd764", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\n\nfn partition(array: &mut [i32], mut left_index: usize, mut right_index: usize) -> usize {\n let pivot_element = array[(left_index + right_index) >> 1];\n loop {\n while array[left_index] < pivot_element {\n left_index += 1;\n }\n while array[right_index] > pivot_element {\n right_index -= 1;\n }\n if left_index >= right_index {\n break;\n }\n array.swap(left_index, right_index);\n left_index += 1;\n right_index -= 1;\n }\n return right_index;\n}\n\n\nfn qsort(array: &mut [i32], left: usize, right: usize) {\n if left < right {\n let p = partition(array, left, right);\n qsort(array, left, p);\n qsort(array, p + 1, right);\n }\n}\n\n\nfn main() {\n let reader = io::stdin();\n\n let mut val = String::new();\n io::stdin().read_line(&mut val)\n .expect(\"\u041d\u0435 \u0443\u0434\u0430\u043b\u043e\u0441\u044c \u043f\u0440\u043e\u0447\u0438\u0442\u0430\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0443\");\n\n let mut numbers: Vec =\n reader.lock() // (0)\n .lines().next().unwrap().unwrap() // (1)\n .split(' ').map(|s| s.trim()) // (2)\n .filter(|s| !s.is_empty()) // (3)\n .map(|s| s.parse().unwrap()) // (4)\n .collect(); // (5)\n\n let length = numbers.len();\n qsort(numbers.as_mut_slice(), 0, length - 1);\n let mut total = 0;\n let mut i = 0;\n while i < length - 1 {\n total += numbers[i + 1] - numbers[i];\n i += 2;\n }\n println!(\"{}\", total);\n}\n", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "9d0312659cbe92c31dc7548e5b905cdc", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_to_string(&mut buffer).expect(\"read stdin\");\n\n let mut skill_levels: Vec = buffer\n .lines()\n .nth(1)\n .expect(\"all lines but first\")\n .split(' ')\n .map(|s| s.parse::().expect(\"skill level\")).collect(); \n skill_levels.sort();\n let num_problems: i32 = (0..(skill_levels.len() / 2))\n .map(|idx| skill_levels[idx * 2 + 1] - skill_levels[idx * 2])\n .sum();\n\n println!(\"{}\", num_problems);\n}\n", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "990550f1a949b0fb9a1d574e0dc81257", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\n#[derive(Debug)]\nstruct Info {\n n: i64,\n k: i64,\n m: i64,\n ans: Vec,\n}\n\nimpl Info {\n fn rec(&mut self, crt: i64) {\n //debug!(crt, self);\n if self.m == self.k || crt == 1 {\n self.ans.push(crt);\n return;\n }\n\n self.m += 1;\n self.rec(crt/2);\n self.rec(crt/2);\n }\n}\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let mut a:Vec = (0..n).map(|_| read()).collect();\n a.sort();\n let mut ans = 0;\n for i in (0..n).step_by(2) {\n ans += a[i+1]-a[i];\n }\n println!(\"{}\", ans);\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "c8f144565751540b2eab76f149b681f6", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::io::*;\nuse std::vec;\nuse std::vec::*;\nfn main(){\n\n let mut N = String::new();\n io::stdin().read_line(&mut N);\n let mut N = N.trim().parse::().unwrap();\n\n let mut nums_line = String::new();\n io::stdin().read_line(&mut nums_line);\n\n let mut nums : Vec = nums_line.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n nums.sort(); \n\n let mut sum = 0;\n let mut i = 0;\n while i < N-1{\n sum = sum + nums[i as usize +1] - nums[i as usize];\n i = i + 2;\n }\n println!(\"{}\", sum);\n}\n\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "80466f16739038ffb8a47a715cfc338c", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{io, process};\n\nfn main() {\n\tlet n: u8 = {\n\t\tlet mut line = String::new();\n\t\tio::stdin().read_line(&mut line).unwrap();\n\t\tline.trim().parse().unwrap()\n\t};\n\n\tlet mut a: Vec = {\n\t\tlet mut line = String::new();\n\t\tio::stdin().read_line(&mut line).unwrap();\n\t\tline.trim().split(' ').map(|a| a.parse().unwrap()).collect()\n\t};\n\n\ta.sort();\n\n\t// remove duplicates\n\tlet mut i = a.len() - 1;\n\tloop {\n\t\tfor j in (0..a.len()).rev() {\n\t\t\tif i == j {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif a[i] == a[j] {\n\t\t\t\tif i > j {\n\t\t\t\t\ta.remove(i);\n\t\t\t\t\ta.remove(j);\n\t\t\t\t} else {\n\t\t\t\t\ta.remove(j);\n\t\t\t\t\ta.remove(i);\n\t\t\t\t}\n\t\t\t\ti -= 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif i == 0 {\n\t\t\tbreak;\n\t\t}\n\t\ti -= 1;\n\t}\n\n\tassert!(a.len() % 2 == 0);\n\n\tlet mut pb0 = 0u32;\n\tfor s in a\n\t\t.iter()\n\t\t.enumerate()\n\t\t.filter(|s| s.0 % 2 == 0)\n\t\t.map(|s| *s.1)\n\t\t.zip(a.iter().enumerate().filter(|s| s.0 % 2 == 1).map(|s| *s.1))\n\t{\n\t\tpb0 += s.1 as u32 - s.0 as u32;\n\t}\n\n\tif a.len() < 3 {\n\t\tprintln!(\"{}\", pb0);\n\t\tprocess::exit(0);\n\t}\n\n\tlet mut pb1 = 0u32;\n\tlet mut b: Vec = a\n\t\t.iter()\n\t\t.enumerate()\n\t\t.filter(|s| s.0 % 2 == 0)\n\t\t.map(|s| *s.1)\n\t\t.collect();\n\tb.remove(0);\n\tlet lasti = b.len() - 1;\n\tb.remove(lasti);\n\tfor s in a\n\t\t.iter()\n\t\t.enumerate()\n\t\t.filter(|s| s.0 % 2 == 1)\n\t\t.map(|s| *s.1)\n\t\t.zip(b)\n\t{\n\t\tpb1 += s.1 as u32 - s.0 as u32;\n\t}\n\tpb1 += a[a.len() - 1] as u32 - a[0] as u32;\n\n\tprintln!(\"{}\", pb0.min(pb1));\n}\n", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "8ba71624156902acadbf87b152b3692c", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::*;\nuse std::vec;\nuse std::vec::*;\nmacro_rules! in_seq{\n ($x:ident) => {\n let mut nums_line = String::new();\n io::stdin().read_line(&mut nums_line);\n let mut $x : Vec = nums_line.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n }\n}\n\nfn main(){\n in_seq!(N);\n let N = N[0];\n\n in_seq!(nums);\n\n nums.sort(); \n\n let mut sum = 0;\n let mut i = 0;\n while i < N-1{\n sum = sum + nums[i as usize +1] - nums[i as usize];\n i = i + 2;\n }\n println!(\"{}\", sum);\n}", "lang_cluster": "Rust", "tags": ["sortings"], "code_uid": "5be7efa582f1c49bdad20b81ff7249d1", "src_uid": "55485fe203a114374f0aae93006278d3", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn gcd(a: i64, b: i64) -> i64 {\n if a > b {\n return gcd(b,a);\n }\n if a == 0 {\n return 0;\n } else {\n return (b/a) + gcd(b%a,a);\n }\n}\n\nfn main() {\n let (a,b) = readln!(i64,i64);\n let res = gcd(a,b);\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "7e2e3bb404d69ef3f9beff6757131620", "src_uid": "ce698a0eb3f5b82de58feb177ce43b83", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let mut a: i64 = input.p();\n let mut b: i64 = input.p();\n let mut sol = 0;\n while b > 0 {\n sol += a / b;\n let t = a % b;\n a = b;\n b = t;\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e2ef6950edc4b4917144a65dd9b2986a", "src_uid": "ce698a0eb3f5b82de58feb177ce43b83", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let size = s.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n let mut c = -1;\n if size.iter().fold(true, |acc, &x| acc && (x==0)) == true {\n c=-1;\n } else {\n for i in 0..=100 {\n if size.iter().map(|x| x-i).sum::() == 0 {\n c = i;\n break;\n }\n }\n }\n println!(\"{}\",c );\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ecb6b08616cd1b43421c8f5ad1e81764", "src_uid": "af1ec6a6fc1f2360506fc8a34e3dcd20", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let a = readvec!(i32);\n let b = a.iter().fold(0,|x,y| x+y);\n println!(\"{}\",if b > 0 && b%a.len() as i32 == 0 { b/a.len() as i32 } else { -1 });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "92c71e714738ac94f68f7bdf18492465", "src_uid": "af1ec6a6fc1f2360506fc8a34e3dcd20", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let bets: Vec = scan.next_n(5);\n let total: usize = bets.iter().sum();\n let (valid, result) = (total%5==0 && total!=0, total/5);\n if valid {\n println!(\"{}\", result);\n } else {\n println!(\"-1\");\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "83988831b31326bdb97b8b07baf2c29a", "src_uid": "af1ec6a6fc1f2360506fc8a34e3dcd20", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let s: i32 = R!(i32, ...).into_iter().sum();\n println!(\"{}\", if s % 5 == 0 && s > 0 { s / 5 } else { -1 });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "00808560f9eae36ac36deef41fca0f9a", "src_uid": "af1ec6a6fc1f2360506fc8a34e3dcd20", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, std::io::stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut buffer = String::new();\n let mut input = WordReader::from_stdin(&mut buffer);\n\n let sum = (0..5).map(|_| input.i()).sum::();\n let sol = if sum % 5 == 0 && sum > 0 {\n sum / 5\n } else {\n -1\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "53bb6a8910d64ad991e1d2188c91703f", "src_uid": "af1ec6a6fc1f2360506fc8a34e3dcd20", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdout, BufWriter, Write};\n\ntype Mint = ModInt1000000007;\n\nfn main() {\n inputv! {\n n:usize,x:usize,pos:usize\n }\n let mut f = vec![Mint::new(1)];\n for i in 1..1000 {\n let l = *f.last().unwrap();\n f.push(l * Mint::new(i));\n }\n let mut r_count = 0;\n let mut l_count = 0;\n let mut left = 0;\n let mut right = n;\n while left < right {\n let mid = (left + right) / 2;\n if mid > pos {\n r_count += 1;\n right = mid;\n } else {\n l_count += 1;\n left = mid + 1;\n }\n }\n if left > 0 && left - 1 == pos {\n l_count -= 1;\n } else {\n println!(\"0\");\n return;\n }\n //dbg!(l_count, r_count);\n if n - x < r_count || x - 1 < l_count {\n println!(\"0\");\n return;\n }\n let mut ans = f[n - x] / f[n - x - r_count] * f[x - 1] / f[x - 1 - l_count]\n * f[n - l_count - r_count - 1];\n println!(\"{}\", ans);\n}\n\n//https://github.com/rust-lang-ja/ac-library-rs\n//https://github.com/manta1130/competitive-template-rs\n\nuse input::*;\nuse modint::*;\n\npub mod input {\n use std::cell::RefCell;\n use std::io;\n pub const SPLIT_DELIMITER: char = ' ';\n pub use std::io::prelude::*;\n\n #[macro_export]\n thread_local! {\n pub static INPUT_BUFFER:RefCell>=RefCell::new(std::collections::VecDeque::new());\n }\n\n #[macro_export]\n macro_rules! input_internal {\n ($x:ident : $t:ty) => {\n INPUT_BUFFER.with(|p| {\n if p.borrow().len() == 0 {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str\n .split(SPLIT_DELIMITER)\n .map(|q| q.to_string())\n .collect::>();\n p.borrow_mut().append(&mut split_result_iter)\n }\n });\n let mut buf_split_result = String::new();\n INPUT_BUFFER.with(|p| buf_split_result = p.borrow_mut().pop_front().unwrap());\n let $x: $t = buf_split_result.parse().unwrap();\n };\n (mut $x:ident : $t:ty) => {\n INPUT_BUFFER.with(|p| {\n if p.borrow().len() == 0 {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str\n .split(SPLIT_DELIMITER)\n .map(|q| q.to_string())\n .collect::>();\n p.borrow_mut().append(&mut split_result_iter)\n }\n });\n let mut buf_split_result = String::new();\n INPUT_BUFFER.with(|p| buf_split_result = p.borrow_mut().pop_front().unwrap());\n let mut $x: $t = buf_split_result.parse().unwrap();\n };\n }\n\n #[macro_export]\n macro_rules! inputv {\n ($i:ident : $t:ty) => {\n input_internal!{$i : $t}\n };\n (mut $i:ident : $t:ty) => {\n input_internal!{mut $i : $t}\n };\n ($i:ident : $t:ty $(,)*) => {\n input_internal!{$i : $t}\n };\n (mut $i:ident : $t:ty $(,)*) => {\n input_internal!{mut $i : $t}\n };\n (mut $i:ident : $t:ty,$($q:tt)*) => {\n input_internal!{mut $i : $t}\n inputv!{$($q)*}\n };\n ($i:ident : $t:ty,$($q:tt)*) => {\n input_internal!{$i : $t}\n inputv!{$($q)*}\n };\n}\n\n pub fn input_all() {\n INPUT_BUFFER.with(|p| {\n if p.borrow().len() == 0 {\n let mut temp_str = String::new();\n std::io::stdin().read_to_string(&mut temp_str).unwrap();\n let mut split_result_iter = temp_str\n .split_whitespace()\n .map(|q| q.to_string())\n .collect::>();\n p.borrow_mut().append(&mut split_result_iter)\n }\n });\n }\n\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\npub mod internal_math {\n #![allow(dead_code)]\n use std::mem::swap;\n\n /* const */\n pub(crate) fn safe_mod(mut x: i64, m: i64) -> i64 {\n x %= m;\n if x < 0 {\n x += m;\n }\n x\n }\n\n pub(crate) struct Barrett {\n pub(crate) _m: u32,\n pub(crate) im: u64,\n }\n\n impl Barrett {\n pub(crate) fn new(m: u32) -> Barrett {\n Barrett {\n _m: m,\n im: (-1i64 as u64 / m as u64).wrapping_add(1),\n }\n }\n\n pub(crate) fn umod(&self) -> u32 {\n self._m\n }\n\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn mul(&self, a: u32, b: u32) -> u32 {\n mul_mod(a, b, self._m, self.im)\n }\n }\n\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn mul_mod(a: u32, b: u32, m: u32, im: u64) -> u32 {\n let mut z = a as u64;\n z *= b as u64;\n let x = (((z as u128) * (im as u128)) >> 64) as u64;\n let mut v = z.wrapping_sub(x.wrapping_mul(m as u64)) as u32;\n if m <= v {\n v = v.wrapping_add(m);\n }\n v\n }\n\n /* const */\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn pow_mod(x: i64, mut n: i64, m: i32) -> i64 {\n if m == 1 {\n return 0;\n }\n let _m = m as u32;\n let mut r: u64 = 1;\n let mut y: u64 = safe_mod(x, m as i64) as u64;\n while n != 0 {\n if (n & 1) > 0 {\n r = (r * y) % (_m as u64);\n }\n y = (y * y) % (_m as u64);\n n >>= 1;\n }\n r as i64\n }\n\n /* const */\n pub(crate) fn is_prime(n: i32) -> bool {\n let n = n as i64;\n match n {\n _ if n <= 1 => return false,\n 2 | 7 | 61 => return true,\n _ if n % 2 == 0 => return false,\n _ => {}\n }\n let mut d = n - 1;\n while d % 2 == 0 {\n d /= 2;\n }\n for &a in &[2, 7, 61] {\n let mut t = d;\n let mut y = pow_mod(a, t, n as i32);\n while t != n - 1 && y != 1 && y != n - 1 {\n y = y * y % n;\n t <<= 1;\n }\n if y != n - 1 && t % 2 == 0 {\n return false;\n }\n }\n true\n }\n\n /* const */\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = safe_mod(a, b);\n if a == 0 {\n return (b, 0);\n }\n\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\n\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n if m0 < 0 {\n m0 += b / s;\n }\n (s, m0)\n }\n\n /* const */\n pub(crate) fn primitive_root(m: i32) -> i32 {\n match m {\n 2 => return 1,\n 167_772_161 => return 3,\n 469_762_049 => return 3,\n 754_974_721 => return 11,\n 998_244_353 => return 3,\n _ => {}\n }\n\n let mut divs = [0; 20];\n divs[0] = 2;\n let mut cnt = 1;\n let mut x = (m - 1) / 2;\n while x % 2 == 0 {\n x /= 2;\n }\n for i in (3..std::i32::MAX).step_by(2) {\n if i as i64 * i as i64 > x as i64 {\n break;\n }\n if x % i == 0 {\n divs[cnt] = i;\n cnt += 1;\n while x % i == 0 {\n x /= i;\n }\n }\n }\n if x > 1 {\n divs[cnt] = x;\n cnt += 1;\n }\n let mut g = 2;\n loop {\n if (0..cnt).all(|i| pow_mod(g, ((m - 1) / divs[i]) as i64, m) != 1) {\n break g as i32;\n }\n g += 1;\n }\n }\n}\npub mod modint {\n\n use crate::internal_math;\n use std::{\n cell::RefCell,\n convert::{Infallible, TryInto as _},\n fmt,\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n sync::atomic::{self, AtomicU32, AtomicU64},\n thread::LocalKey,\n };\n\n pub type ModInt1000000007 = StaticModInt;\n pub type ModInt998244353 = StaticModInt;\n pub type ModInt = DynamicModInt;\n\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct StaticModInt {\n val: u32,\n phantom: PhantomData M>,\n }\n\n impl StaticModInt {\n #[inline(always)]\n pub fn modulus() -> u32 {\n M::VALUE\n }\n\n #[inline]\n pub fn new(val: T) -> Self {\n Self::raw(val.rem_euclid_u32(M::VALUE))\n }\n\n #[inline]\n pub fn raw(val: u32) -> Self {\n Self {\n val,\n phantom: PhantomData,\n }\n }\n\n #[inline]\n pub fn val(self) -> u32 {\n self.val\n }\n\n #[inline]\n pub fn pow(self, n: u64) -> Self {\n ::pow(self, n)\n }\n\n #[inline]\n pub fn inv(self) -> Self {\n if M::HINT_VALUE_IS_PRIME {\n if self.val() == 0 {\n panic!(\"attempt to divide by zero\");\n }\n debug_assert!(\n internal_math::is_prime(M::VALUE.try_into().unwrap()),\n \"{} is not a prime number\",\n M::VALUE,\n );\n self.pow((M::VALUE - 2).into())\n } else {\n Self::inv_for_non_prime_modulus(self)\n }\n }\n }\n\n impl ModIntBase for StaticModInt {\n #[inline(always)]\n fn modulus() -> u32 {\n Self::modulus()\n }\n\n #[inline]\n fn raw(val: u32) -> Self {\n Self::raw(val)\n }\n\n #[inline]\n fn val(self) -> u32 {\n self.val()\n }\n\n #[inline]\n fn inv(self) -> Self {\n self.inv()\n }\n }\n\n pub trait Modulus: 'static + Copy + Eq {\n const VALUE: u32;\n const HINT_VALUE_IS_PRIME: bool;\n\n fn butterfly_cache() -> &'static LocalKey>>>;\n }\n\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum Mod1000000007 {}\n\n impl Modulus for Mod1000000007 {\n const VALUE: u32 = 1_000_000_007;\n const HINT_VALUE_IS_PRIME: bool = true;\n\n fn butterfly_cache() -> &'static LocalKey>>> {\n thread_local! {\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\n }\n &BUTTERFLY_CACHE\n }\n }\n\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum Mod998244353 {}\n\n impl Modulus for Mod998244353 {\n const VALUE: u32 = 998_244_353;\n const HINT_VALUE_IS_PRIME: bool = true;\n\n fn butterfly_cache() -> &'static LocalKey>>> {\n thread_local! {\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\n }\n &BUTTERFLY_CACHE\n }\n }\n\n pub struct ButterflyCache {\n pub(crate) sum_e: Vec>,\n pub(crate) sum_ie: Vec>,\n }\n\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct DynamicModInt {\n val: u32,\n phantom: PhantomData I>,\n }\n\n impl DynamicModInt {\n #[inline]\n pub fn modulus() -> u32 {\n I::companion_barrett().umod()\n }\n\n #[inline]\n pub fn set_modulus(modulus: u32) {\n if modulus == 0 {\n panic!(\"the modulus must not be 0\");\n }\n I::companion_barrett().update(modulus);\n }\n\n #[inline]\n pub fn new(val: T) -> Self {\n ::new(val)\n }\n\n #[inline]\n pub fn raw(val: u32) -> Self {\n Self {\n val,\n phantom: PhantomData,\n }\n }\n\n #[inline]\n pub fn val(self) -> u32 {\n self.val\n }\n\n #[inline]\n pub fn pow(self, n: u64) -> Self {\n ::pow(self, n)\n }\n\n #[inline]\n pub fn inv(self) -> Self {\n Self::inv_for_non_prime_modulus(self)\n }\n }\n\n impl ModIntBase for DynamicModInt {\n #[inline]\n fn modulus() -> u32 {\n Self::modulus()\n }\n\n #[inline]\n fn raw(val: u32) -> Self {\n Self::raw(val)\n }\n\n #[inline]\n fn val(self) -> u32 {\n self.val()\n }\n\n #[inline]\n fn inv(self) -> Self {\n self.inv()\n }\n }\n\n pub trait Id: 'static + Copy + Eq {\n fn companion_barrett() -> &'static Barrett;\n }\n\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum DefaultId {}\n\n impl Id for DefaultId {\n fn companion_barrett() -> &'static Barrett {\n static BARRETT: Barrett = Barrett::default();\n &BARRETT\n }\n }\n\n pub struct Barrett {\n m: AtomicU32,\n im: AtomicU64,\n }\n\n impl Barrett {\n #[inline]\n pub const fn new(m: u32) -> Self {\n Self {\n m: AtomicU32::new(m),\n im: AtomicU64::new((-1i64 as u64 / m as u64).wrapping_add(1)),\n }\n }\n\n #[inline]\n const fn default() -> Self {\n Self::new(998_244_353)\n }\n\n #[inline]\n fn update(&self, m: u32) {\n let im = (-1i64 as u64 / m as u64).wrapping_add(1);\n self.m.store(m, atomic::Ordering::SeqCst);\n self.im.store(im, atomic::Ordering::SeqCst);\n }\n\n #[inline]\n fn umod(&self) -> u32 {\n self.m.load(atomic::Ordering::SeqCst)\n }\n\n #[inline]\n fn mul(&self, a: u32, b: u32) -> u32 {\n let m = self.m.load(atomic::Ordering::SeqCst);\n let im = self.im.load(atomic::Ordering::SeqCst);\n internal_math::mul_mod(a, b, m, im)\n }\n }\n\n impl Default for Barrett {\n #[inline]\n fn default() -> Self {\n Self::default()\n }\n }\n\n pub trait ModIntBase:\n Default\n + FromStr\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + Copy\n + Eq\n + Hash\n + fmt::Display\n + fmt::Debug\n + Neg\n + Add\n + Sub\n + Mul\n + Div\n + AddAssign\n + SubAssign\n + MulAssign\n + DivAssign\n {\n fn modulus() -> u32;\n\n fn raw(val: u32) -> Self;\n\n fn val(self) -> u32;\n\n fn inv(self) -> Self;\n\n #[inline]\n fn new(val: T) -> Self {\n Self::raw(val.rem_euclid_u32(Self::modulus()))\n }\n\n #[inline]\n fn pow(self, mut n: u64) -> Self {\n let mut x = self;\n let mut r = Self::raw(1);\n while n > 0 {\n if n & 1 == 1 {\n r *= x;\n }\n x *= x;\n n >>= 1;\n }\n r\n }\n }\n\n pub trait RemEuclidU32 {\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n\n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n}\n\n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n\n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n\n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n}\n\n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n}\n\n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n\n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n\n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n\n trait InternalImplementations: ModIntBase {\n #[inline]\n fn inv_for_non_prime_modulus(this: Self) -> Self {\n let (gcd, x) = internal_math::inv_gcd(this.val().into(), Self::modulus().into());\n if gcd != 1 {\n panic!(\"the multiplicative inverse does not exist\");\n }\n Self::new(x)\n }\n\n #[inline]\n fn default_impl() -> Self {\n Self::raw(0)\n }\n\n #[inline]\n fn from_str_impl(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n\n #[inline]\n fn hash_impl(this: &Self, state: &mut impl Hasher) {\n this.val().hash(state)\n }\n\n #[inline]\n fn display_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\n fmt::Display::fmt(&this.val(), f)\n }\n\n #[inline]\n fn debug_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\n fmt::Debug::fmt(&this.val(), f)\n }\n\n #[inline]\n fn neg_impl(this: Self) -> Self {\n Self::sub_impl(Self::raw(0), this)\n }\n\n #[inline]\n fn add_impl(lhs: Self, rhs: Self) -> Self {\n let modulus = Self::modulus();\n let mut val = lhs.val() + rhs.val();\n if val >= modulus {\n val -= modulus;\n }\n Self::raw(val)\n }\n\n #[inline]\n fn sub_impl(lhs: Self, rhs: Self) -> Self {\n let modulus = Self::modulus();\n let mut val = lhs.val().wrapping_sub(rhs.val());\n if val >= modulus {\n val = val.wrapping_add(modulus)\n }\n Self::raw(val)\n }\n\n fn mul_impl(lhs: Self, rhs: Self) -> Self;\n\n #[inline]\n fn div_impl(lhs: Self, rhs: Self) -> Self {\n Self::mul_impl(lhs, rhs.inv())\n }\n }\n\n impl InternalImplementations for StaticModInt {\n #[inline]\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\n Self::raw((u64::from(lhs.val()) * u64::from(rhs.val()) % u64::from(M::VALUE)) as u32)\n }\n }\n\n impl InternalImplementations for DynamicModInt {\n #[inline]\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\n Self::raw(I::companion_barrett().mul(lhs.val, rhs.val))\n }\n }\n\n macro_rules! impl_basic_traits {\n () => {};\n (impl <$generic_param:ident : $generic_param_bound:tt> _ for $self:ty; $($rest:tt)*) => {\n impl <$generic_param: $generic_param_bound> Default for $self {\n #[inline]\n fn default() -> Self {\n Self::default_impl()\n }\n }\n\n impl <$generic_param: $generic_param_bound> FromStr for $self {\n type Err = Infallible;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::from_str_impl(s)\n }\n }\n\n impl<$generic_param: $generic_param_bound, V: RemEuclidU32> From for $self {\n #[inline]\n fn from(from: V) -> Self {\n Self::new(from)\n }\n }\n\n #[allow(clippy::derive_hash_xor_eq)]\n impl<$generic_param: $generic_param_bound> Hash for $self {\n #[inline]\n fn hash(&self, state: &mut H) {\n Self::hash_impl(self, state)\n }\n }\n\n impl<$generic_param: $generic_param_bound> fmt::Display for $self {\n #[inline]\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Self::display_impl(self, f)\n }\n }\n\n impl<$generic_param: $generic_param_bound> fmt::Debug for $self {\n #[inline]\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Self::debug_impl(self, f)\n }\n }\n\n impl<$generic_param: $generic_param_bound> Neg for $self {\n type Output = $self;\n\n #[inline]\n fn neg(self) -> $self {\n Self::neg_impl(self)\n }\n }\n\n impl<$generic_param: $generic_param_bound> Neg for &'_ $self {\n type Output = $self;\n\n #[inline]\n fn neg(self) -> $self {\n <$self>::neg_impl(*self)\n }\n }\n\n impl_basic_traits!($($rest)*);\n };\n}\n\n impl_basic_traits! {\n impl _ for StaticModInt ;\n impl _ for DynamicModInt;\n }\n\n macro_rules! impl_bin_ops {\n () => {};\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~ <$rhs_ty:ty> -> $output:ty { { $lhs_body:expr } ~ { $rhs_body:expr } } $($rest:tt)*) => {\n impl <$($generic_param: $generic_param_bound),*> Add<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn add(self, rhs: $rhs_ty) -> $output {\n <$output>::add_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Sub<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn sub(self, rhs: $rhs_ty) -> $output {\n <$output>::sub_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Mul<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn mul(self, rhs: $rhs_ty) -> $output {\n <$output>::mul_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Div<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn div(self, rhs: $rhs_ty) -> $output {\n <$output>::div_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl_bin_ops!($($rest)*);\n };\n}\n\n macro_rules! impl_assign_ops {\n () => {};\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~= <$rhs_ty:ty> { _ ~= { $rhs_body:expr } } $($rest:tt)*) => {\n impl <$($generic_param: $generic_param_bound),*> AddAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn add_assign(&mut self, rhs: $rhs_ty) {\n *self = *self + apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> SubAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn sub_assign(&mut self, rhs: $rhs_ty) {\n *self = *self - apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> MulAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn mul_assign(&mut self, rhs: $rhs_ty) {\n *self = *self * apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> DivAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn div_assign(&mut self, rhs: $rhs_ty) {\n *self = *self / apply($rhs_body, rhs);\n }\n }\n\n impl_assign_ops!($($rest)*);\n };\n}\n\n #[inline]\n fn apply O, X, O>(f: F, x: X) -> O {\n f(x)\n }\n\n impl_bin_ops! {\n for > ~ > -> StaticModInt { { |x| x } ~ { |x| x } }\n for > ~ <&'_ StaticModInt > -> StaticModInt { { |x| x } ~ { |&x| x } }\n for <&'_ StaticModInt > ~ > -> StaticModInt { { |&x| x } ~ { |x| x } }\n for <&'_ StaticModInt > ~ <&'_ StaticModInt > -> StaticModInt { { |&x| x } ~ { |&x| x } }\n for > ~ > -> DynamicModInt { { |x| x } ~ { |x| x } }\n for > ~ <&'_ DynamicModInt> -> DynamicModInt { { |x| x } ~ { |&x| x } }\n for <&'_ DynamicModInt> ~ > -> DynamicModInt { { |&x| x } ~ { |x| x } }\n for <&'_ DynamicModInt> ~ <&'_ DynamicModInt> -> DynamicModInt { { |&x| x } ~ { |&x| x } }\n\n for > ~ -> StaticModInt { { |x| x } ~ { StaticModInt::::new } }\n for > ~ -> DynamicModInt { { |x| x } ~ { DynamicModInt::::new } }\n }\n\n impl_assign_ops! {\n for > ~= > { _ ~= { |x| x } }\n for > ~= <&'_ StaticModInt > { _ ~= { |&x| x } }\n for > ~= > { _ ~= { |x| x } }\n for > ~= <&'_ DynamicModInt> { _ ~= { |&x| x } }\n\n for > ~= { _ ~= { StaticModInt::::new } }\n for > ~= { _ ~= { DynamicModInt::::new } }\n }\n\n macro_rules! impl_folding {\n () => {};\n (impl<$generic_param:ident : $generic_param_bound:tt> $trait:ident<_> for $self:ty { fn $method:ident(_) -> _ { _($unit:expr, $op:expr) } } $($rest:tt)*) => {\n impl<$generic_param: $generic_param_bound> $trait for $self {\n #[inline]\n fn $method(iter: S) -> Self\n where\n S: Iterator,\n {\n iter.fold($unit, $op)\n }\n }\n\n impl<'a, $generic_param: $generic_param_bound> $trait<&'a Self> for $self {\n #[inline]\n fn $method(iter: S) -> Self\n where\n S: Iterator,\n {\n iter.fold($unit, $op)\n }\n }\n\n impl_folding!($($rest)*);\n };\n}\n\n impl_folding! {\n impl Sum<_> for StaticModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\n impl Product<_> for StaticModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\n impl Sum<_> for DynamicModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\n impl Product<_> for DynamicModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\n }\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "2506821d1f5601c0e0db21a636239740", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n date : 2020 / 5 / 5\n author : quickn (quickn.ga)\n email : quickwshell@gmail.com\n*/\n\nuse std::io::{self, BufWriter, Write};\n\nmod scanner {\n use std::{io, str};\n pub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n }\n\n impl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n }\n}\n\nconst MOD: i64 = 1_000_000_007;\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let (mut scan, mut sout) = (\n scanner::UnsafeScanner::new(stdin.lock()),\n BufWriter::new(stdout.lock()),\n );\n let (n, x, pos): (usize, usize, usize) = (scan.token(), scan.token(), scan.token());\n let (mut l, mut r) = (0, n);\n let (mut c_l, mut c_r) = (0, 0);\n while l < r {\n let mid = (l + r) >> 1;\n //dbg!(l, r, mid);\n if mid <= pos {\n l = mid + 1;\n if mid != pos {\n c_l += 1;\n }\n } else {\n r = mid;\n //if l < r {\n c_r += 1;\n //}\n }\n }\n let mut comb: Vec> = vec![vec![0;n+1];n+1];\n comb[0][0] = 1;\n for i in 1..=n {\n comb[i][0] = 1;\n comb[i][n] = 1;\n for j in 1..n {\n comb[i][j] = (comb[i-1][j] + comb[i-1][j-1])%MOD;\n }\n }\n let mut fact: Vec = vec![0;n+1];\n fact[0] = 1;\n for i in 1..=n {\n fact[i] = (fact[i-1] * (i as i64)) % MOD;\n }\n //dbg!(c_l, c_r);\n //dbg!(comb[n-x][c_r], comb[x-1][c_l]);\n writeln!(sout, \"{}\", (((if c_r == 0 { 1 } else { (comb[n-x][c_r]*fact[c_r])%MOD }*if c_l == 0 { 1 } else { (comb[x-1][c_l]*fact[c_l])%MOD })%MOD)*fact[n-(c_r+c_l+1)])%MOD).ok();\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "3b13c3076e084ee006fb4aff5c10776d", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\n#[derive(Clone)]\nstruct Graph {\n nodes: usize,\n edges: Vec>,\n}\n\nimpl Graph {\n fn new(n: usize) -> Self {\n Self {\n nodes: n,\n edges: vec![Vec::new(); n + 1],\n }\n }\n\n fn add_edge(&mut self, x: usize, y: usize, cost: u64) {\n self.edges[x].push((y, cost));\n self.edges[y].push((x, cost));\n }\n\n fn dijkstra(&mut self, start: usize, end: usize) -> u64 {\n let mut dist = vec![None; self.nodes + 1];\n let mut prev = vec![None; self.nodes + 1];\n dist[start] = Some(0);\n let mut queue = (1..=self.nodes).collect::>();\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n while let Some(next_node) = queue.pop() {\n if next_node == end {\n return dist[next_node].unwrap();\n }\n for (neighbour, cost) in self.edges[next_node].iter() {\n let alt = dist[next_node].unwrap() + cost;\n if dist[*neighbour].is_none() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n } else {\n if alt < dist[*neighbour].unwrap() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n }\n }\n }\n //println!(\"{:?} {:?}\", dist, prev);\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n }\n 0\n }\n\n fn set_cost(&mut self, x: usize, y: usize, cost: u64) {\n for i in 0..self.edges[x].len() {\n if self.edges[x][i].0 == y {\n self.edges[x][i].1 = cost\n }\n }\n for i in 0..self.edges[y].len() {\n if self.edges[y][i].0 == x {\n self.edges[y][i].1 = cost\n }\n }\n }\n}\n\nconst MODULO: u64 = 1_000_000_007;\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\nstruct BigPrimeRing {\n inner: u64,\n}\n\nimpl From for BigPrimeRing\nwhere\n T: Into,\n{\n fn from(n: T) -> Self {\n Self {\n inner: n.into() % MODULO,\n }\n }\n}\n\nimpl std::ops::Add for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn add(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::AddAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn add_assign(&mut self, rhs: T) {\n self.inner += rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Sub for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn sub(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + MODULO - rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::SubAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn sub_assign(&mut self, rhs: T) {\n self.inner += MODULO;\n self.inner -= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Mul for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn mul(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner * rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::MulAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn mul_assign(&mut self, rhs: T) {\n self.inner *= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl BigPrimeRing {\n fn inverse(self) -> Self {\n if self.inner == 0 {\n return self;\n }\n let (_g, mut x, _y) = egcd(self.inner as i64, MODULO as i64);\n if x < 0 {\n x += MODULO as i64;\n }\n Self { inner: x as u64 }\n }\n}\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn dp(graph: &Vec>, weights: &Vec, node: usize) -> (u64, u64, usize) {\n if graph[node].is_empty() {\n return (weights[node], 0, 1);\n }\n let weight = weights[node];\n let ans_vec = graph[node]\n .iter()\n .map(|neighbour| dp(graph, weights, *neighbour))\n .collect::>();\n let max_ans = ans_vec\n .iter()\n .map(|(a, _residue, _leaves)| *a)\n .max()\n .unwrap();\n let sum_residue = ans_vec\n .iter()\n .map(|(a, res, leaves)| res + (max_ans - a) * (*leaves) as u64)\n .sum::();\n let total_leaves = ans_vec.into_iter().map(|(_a, _r, l)| l).sum::();\n if sum_residue >= weight {\n (max_ans, sum_residue - weight, total_leaves)\n } else {\n let residue = weight - sum_residue;\n (\n max_ans + ((residue + total_leaves as u64 - 1) / total_leaves as u64),\n residue % total_leaves as u64,\n total_leaves,\n )\n }\n}\n\nfn main() -> Result<(), Box> {\n let (n, x, pos) = read_3::();\n let mut left = 0;\n let mut right = n;\n //let mut checks = Vec::new();\n let mut prefix = 0;\n let mut postfix = 0;\n while left < right {\n let middle = (left + right) / 2;\n //checks.push(middle);\n if middle <= pos {\n left = middle + 1;\n prefix += 1;\n } else {\n right = middle;\n postfix += 1;\n }\n }\n //checks.sort_unstable();\n // let prefix = checks.iter().take_while(|v| **v <= pos).count();\n //let postfix = checks.iter().skip_while(|v| **v <= pos).count();\n //println!(\"{:?}\", checks);\n //println!(\"{:?}\", prefix);\n //println!(\"{:?}\", postfix);\n let remain = n - prefix - postfix;\n let mut res = BigPrimeRing::from(1u8);\n for i in 1..=remain {\n res *= i as u64\n }\n //println!(\"{}\", res.inner);\n if (prefix - 1) > (x - 1) {\n res = BigPrimeRing::from(0u8);\n }\n for i in (x - prefix + 1)..=(x - 1) {\n res *= i as u64\n }\n if postfix > n - x {\n res = BigPrimeRing::from(0u8);\n }\n //println!(\"{}\", res.inner);\n for i in ((n - x) - postfix + 1)..=(n - x) {\n res *= i as u64\n }\n println!(\"{}\", res.inner);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "9a96596e92578f75f10e82ecaf3788cd", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\nuse std::{fmt, ops, str};\n\nmacro_rules! read {\n ( $t:ty ) => {{\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.trim_end().parse::<$t>().ok().unwrap()\n }};\n ( $( $t:ty ),* ) => {{\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let mut iter = input.split_whitespace();\n ( $( iter.next().unwrap().parse::<$t>().unwrap() ),* )\n }};\n}\n\nstruct Ios(Vec);\n\nimpl str::FromStr for Ios {\n type Err = ();\n\n fn from_str(s: &str) -> Result {\n Ok(Ios(s.chars().collect()))\n }\n}\n\nimpl fmt::Display for Ios {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\", self.0.iter().collect::())\n }\n}\n\n#[derive(Clone)]\nstruct Iov(Vec);\n\nimpl str::FromStr for Iov {\n type Err = T::Err;\n\n fn from_str(s: &str) -> Result {\n let iter = s.split_whitespace();\n Ok(Iov(iter.map(|x| x.parse()).collect::>()?))\n }\n}\n\nimpl fmt::Display for Iov {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}\",\n self.0.iter().map(|x| x.to_string())\n .collect::>().join(\" \")\n )\n }\n}\n\nimpl ops::Index for Iov {\n type Output = T;\n\n fn index(&self, i: usize) -> &Self::Output {\n self.0.get(i - 1).unwrap()\n }\n}\n\nimpl ops::IndexMut for Iov {\n fn index_mut(&mut self, i: usize) -> &mut Self::Output {\n self.0.get_mut(i - 1).unwrap()\n }\n}\n\nconst MOD: i64 = 1_000_000_007;\n\nfn solve(writer: &mut io::BufWriter) {\n let (n, x, pos) = read!(i64, i64, i64);\n\n let mut ans = 1;\n let mut small = x - 1;\n let mut large = n - x;\n\n let mut left = 0;\n let mut right = n;\n while left < right {\n let middle = (left + right) / 2;\n if middle <= pos {\n left = middle + 1;\n } else {\n right = middle;\n }\n\n if middle < pos {\n ans = ans * small % MOD;\n small = small.saturating_sub(1);\n }\n if pos < middle {\n ans = ans * large % MOD;\n large = large.saturating_sub(1);\n }\n }\n\n let k = small + large;\n ans = ans * (1..=k).fold(1, |acc, x| acc * x % MOD) % MOD;\n writeln!(writer, \"{}\", ans).ok();\n}\n\nfn main() {\n let stdout = io::stdout();\n let mut writer = io::BufWriter::new(stdout.lock());\n solve(&mut writer);\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "a2b16e86c97585e1fe4fa5a526d31b30", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin};\nuse std::str::FromStr;\nuse std::iter::from_fn;\nuse std::sync::Once;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n #[allow(dead_code)]\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n #[allow(dead_code)]\n fn next_vec (&mut self, n:isize) -> Vec {\n let mut count = 0;\n let res = from_fn(| | {\n if count < n {\n count += 1;\n Some(self.next::())\n } else {\n None\n }\n });\n res.collect()\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n solve(&mut scan)\n}\n\nconst MOD:u64 = 1000000007;\n\nstatic INIT: Once = Once::new();\nstatic mut FACTS:Vec = Vec::new();\n\nfn fact(n:u64) -> u64 {\n\tunsafe {\n\t\tINIT.call_once(|| {\n\t\t\tFACTS.push(1);\n\t\t\tfor i in 1..=1000 {\n\t\t\t\tFACTS.push((FACTS[i-1]*i as u64)%MOD);\n\t\t\t}\n\t\t});\n\t\tFACTS[n as usize]\n\t}\n}\n\n\n\nfn mod_pow(mut base: u64, mut exp: u64, modulus: u64) -> u64 {\n if modulus == 1 { return 0 }\n let mut result = 1;\n base = base % modulus;\n while exp > 0 {\n if exp % 2 == 1 {\n result = result * base % modulus;\n }\n exp = exp >> 1;\n base = base * base % modulus\n }\n result\n}\n\nfn inverse(base: u64) -> u64 {\n\tmod_pow(base, MOD-2, MOD)\n}\n\nfn perms(n:u64, x:u64) -> u64 {\n\t(fact(n) * inverse(fact(n-x)))%MOD\n}\n\t\nfn solve(scan:&mut Scanner) {\n\tlet n:u64 = scan.next();\n\tlet x:u64 = scan.next();\n\tlet p:u64 = scan.next();\n\tlet mut ltx = Vec::new();\n\tlet mut gtx = Vec::new();\n\tlet mut l = 0;\n\tlet mut r = n;\n\tlet mut m;\n\twhile l < r {\n\t\tm = (l + r)/2;\n\t\tif m < p {\n\t\t\tltx.push(m);\n\t\t\tl = m+1;\n\t\t} else if m > p {\n\t\t\tgtx.push(m);\n\t\t\tr = m\n\t\t} else {\n\t\t\tl = m+1;\n\t\t}\n\t}\n\tif x <= ltx.len() as u64 || n - x < gtx.len() as u64 {\n\t\tprintln!(\"0\");\n\t\treturn;\n\t}\n\tlet free = n - ltx.len() as u64 - gtx.len() as u64 - 1;\n\tprintln!(\"{}\",\n\t\t((perms(free, free) * \n\t\tperms(x-1, ltx.len() as u64))%MOD * \n\t\tperms(n-x, gtx.len() as u64))%MOD);\n}\n\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "4863498de873ef8f78d0928247ba315a", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// vim: foldmethod=marker\n// vim: foldmarker={{{,}}}\n\nuse std::collections::HashSet;\nuse std::io;\nuse std::io::Write;\n\n// {{{\n#[allow(unused_macros)]\nmacro_rules! read_non_empty_line {\n () => {{\n let mut inner = String::new();\n while true {\n io::stdin().read_line(&mut inner).unwrap();\n if inner.trim() != \"\" {\n break;\n }\n inner.clear();\n }\n inner\n .trim_end_matches(|c| c == '\\r' || c == '\\n')\n .to_string()\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_multi {\n ($($t: ty),+) => ({\n let line = read_non_empty_line!();\n let mut i = line.trim().split_whitespace();\n (\n $(\n i.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! read {\n () => {\n read_non_empty_line!().trim().parse::<_>().unwrap()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_vec {\n () => {\n read_non_empty_line!()\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<_>().unwrap())\n .collect::>();\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! fmt_vec {\n ($v:ident) => {\n $v.iter()\n .map(|v| format!(\"{}\", v))\n .collect::>()\n .join(\" \")\n };\n}\n\n// }}}\n\nfn md(a: i64) -> i64 {\n a % 1000000007\n}\n\nfn mul(a: i64, b: i64) -> i64 {\n md(md(a) * md(b))\n}\n\nfn solve(writer: &mut io::BufWriter) {\n let (n, x, pos) = read_multi!(i64, i64, i64);\n\n let checks: Vec = {\n let mut path: Vec<(i64, bool)> = vec![];\n let mut left: i64 = 0;\n let mut right: i64 = n;\n while left < right {\n let middle = (left + right) / 2;\n let check = middle <= pos;\n if middle != pos {\n path.push((middle, check));\n }\n if check {\n left = middle + 1;\n } else {\n right = middle;\n }\n }\n path.into_iter()\n .collect::>()\n .into_iter()\n .map(|(_, y)| y)\n .collect()\n };\n\n let mut n_tf: Vec = vec![0, 0];\n for &check in checks.iter() {\n n_tf[check as usize] += 1;\n }\n\n let h_tf = vec![n - x, x - 1];\n\n let mut r: i64 = 1;\n for i in 0..n_tf[1] {\n r = mul(r, h_tf[1] - i);\n }\n for i in 0..n_tf[0] {\n r = mul(r, h_tf[0] - i);\n }\n\n for i in 1..h_tf[1] - n_tf[1] + h_tf[0] - n_tf[0] + 1 {\n r = mul(r, i);\n }\n\n writeln!(writer, \"{}\", r).unwrap();\n}\n\nfn main() {\n let mut writer = io::BufWriter::new(io::stdout());\n solve(&mut writer);\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "aa8a6b3371f4e1246a461c7447a9b938", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\nuse std::io::Write;\n\npub struct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n let (n, x, pos) = (scan.token::(), scan.token::(), scan.token::());\n const MOD: i64 = 1e9 as i64 + 7;\n\n let mut permutation_ordering = vec![0; n];\n let mut factorial = vec![0i64; n + 1];\n factorial[0] = 1;\n for i in 1..=n {\n factorial[i] = (factorial[i - 1] * i as i64) % MOD;\n }\n let mut left = 0;\n let mut right = n;\n while left < right {\n let mid = (left + right) >> 1;\n // println!(\"{}, {}, {}\", left, right, mid);\n if mid < pos {\n permutation_ordering[mid] = -1;\n left = mid + 1;\n } else if mid == pos {\n left = mid + 1;\n } else {\n permutation_ordering[mid] = 1;\n right = mid;\n }\n }\n let lesser_elements_count = permutation_ordering.iter().filter(|x| **x == -1).count();\n let greater_elements_count = permutation_ordering.iter().filter(|x| **x == 1).count();\n // println!(\"{:?}, {}, {}\", elements, lesser_elements_count, greater_elements_count);\n\n let mut ans = 0i64;\n if n - x >= greater_elements_count && x - 1 >= lesser_elements_count {\n ans = 1;\n for i in 0..greater_elements_count {\n ans *= (n - x - i) as i64;\n ans %= MOD;\n }\n for i in 0..lesser_elements_count {\n ans *= (x - 1 - i) as i64;\n ans %= MOD;\n }\n ans *= factorial[n - 1 - greater_elements_count - lesser_elements_count];\n ans %= MOD;\n }\n writeln!(out, \"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "36b28dd593e966de927f3ab501a1fb62", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\n#[derive(Debug, Copy, Clone)]\npub struct ModInt {\n x: i64,\n global_mod: i64,\n}\nimpl ModInt {\n pub fn new(p: i64) -> Self {\n let gm = 1000000007;\n let a = (p % gm + gm) % gm;\n return ModInt {\n x: a,\n global_mod: gm,\n };\n }\n pub fn inv(self) -> Self {\n return self.pow(self.global_mod - 2);\n }\n pub fn pow(self, t: i64) -> Self {\n if (t == 0) {\n return ModInt::new(1);\n };\n let mut a = self.pow(t >> 1);\n a = a * a;\n if (t & 1 != 0) {\n a = a * self\n };\n return a;\n }\n}\nimpl Add for ModInt {\n type Output = ModInt;\n fn add(self, other: ModInt) -> ModInt {\n let ret = self.x + other.x;\n return ModInt::new(ret);\n }\n}\nimpl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, other: ModInt) -> ModInt {\n let ret = self.x - other.x;\n return ModInt::new(ret);\n }\n}\nimpl Mul for ModInt {\n type Output = ModInt;\n fn mul(self, other: ModInt) -> ModInt {\n let ret = self.x * other.x;\n return ModInt::new(ret);\n }\n}\nimpl Div for ModInt {\n type Output = ModInt;\n fn div(self, other: ModInt) -> ModInt {\n let ret = self.x * other.inv().x;\n return ModInt::new(ret);\n }\n}\nimpl std::string::ToString for ModInt {\n fn to_string(&self) -> String {\n return self.x.to_string();\n }\n}\npub struct Combination {\n fact: Vec,\n ifact: Vec,\n}\nimpl Combination {\n pub fn new(n: i32) -> Self {\n if n > 3000000 {\n panic!(\"error\");\n }\n let mut fact = vec![ModInt::new(0); (n + 1) as usize];\n let mut ifact = vec![ModInt::new(0); (n + 1) as usize];\n fact[0] = ModInt::new(1);\n for i in 1..n + 1 {\n fact[i as usize] = fact[(i - 1) as usize] * ModInt::new(i as i64)\n }\n ifact[n as usize] = fact[n as usize].inv();\n for i in (1..n + 1).rev() {\n ifact[(i - 1) as usize] = ifact[i as usize] * ModInt::new(i as i64)\n }\n let a = Combination {\n fact: fact,\n ifact: ifact,\n };\n return a;\n }\n #[macro_use]\n pub fn gen(&mut self, n: i32, k: i32) -> ModInt {\n if (k < 0 || k > n) {\n return ModInt::new(0 as i64);\n };\n return self.fact[n as usize] * self.ifact[k as usize] * self.ifact[(n - k) as usize];\n }\n pub fn P(&mut self, n: i32, k: i32) -> ModInt {\n self.fact[n as usize] * self.ifact[(n - k) as usize]\n }\n}\n\nfn main() {\n let (N, X, POS) = get!(usize, i32, i32);\n let mut a = vec![0; N];\n for i in 0..N {\n a[i] = i as i32;\n }\n let mut l = 0;\n let mut r = N;\n let mut pos = vec![];\n let mut p = vec![];\n while l < r {\n let m = (l + r) / 2;\n pos.push(m);\n if a[m] <= POS {\n l = m + 1;\n p.push(0);\n } else {\n r = m;\n p.push(1);\n }\n }\n mydbg!(p);\n let e = (p.iter().filter(|&x| *x == 0).count() - 1) as i32;\n let e2 = (p.iter().filter(|&x| *x == 1).count()) as i32;\n mydbg!(e, e2);\n let mut ans = ModInt::new(1);\n let mut cmb = Combination::new(N as i32 + 100);\n let b = N as i32 - X;\n if e2 != 0 {\n ans = ans * cmb.gen(b, e2);\n ans = ans * cmb.P(e2, e2);\n }\n if e != 0 {\n ans = ans * cmb.gen(X - 1, e);\n ans = ans * cmb.P(e, e);\n }\n ans = ans * cmb.P(N as i32 - 1 - e - e2, N as i32 - 1 - e - e2);\n echo!(ans.to_string());\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "e1be01b6ef92b93b2f1bcfe5530840d3", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::iter;\nuse std::cmp;\n\nfn main() {\n let mut peds = [false; 4];\n let mut cars = [false; 4];\n\n for i in 0..4 {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let it = input.split_whitespace().map(|c| if c == \"0\" {false} else {true});\n for (j, b) in it.enumerate() {\n match j {\n 0 => {\n cars[i] = b || cars[i];\n cars[(i + 3) % 4] = b || cars[(i + 3) % 4];\n },\n 1 => {\n cars[i] = b || cars[i];\n cars[(i + 2) % 4] = b || cars[(i + 2) % 4];\n },\n 2 => {\n cars[i] = b || cars[i];\n cars[(i + 1) % 4] = b || cars[(i + 1) % 4];\n },\n 3 => {\n peds[i] = b;\n },\n _ => (),\n }\n }\n }\n\n for i in 0..4 {\n if peds[i] && cars[i] {\n println!(\"YES\");\n std::process::exit(0);\n }\n }\n\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4aadcd1aee015bf715609a1bed61a456", "src_uid": "44fdf71d56bef949ec83f00d17c29127", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n\n #[allow(dead_code)]\n pub fn get3() -> (S, T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn check(s: &[usize]) -> bool {\n (0..6).all(|i| {\n s[4 * i] == s[4 * i + 1] && s[4 * i] == s[4 * i + 2] && s[4 * i] == s[4 * i + 3]\n })\n}\n\nfn main() {\n let seq: Vec = util::gets();\n\n let mut ss = seq.clone();\n let mut s1 = seq.clone();\n for i in 0..3 {\n s1[20] = ss[3];\n s1[22] = ss[1];\n\n s1[9] = ss[22];\n s1[11] = ss[20];\n\n s1[5] = ss[9];\n s1[7] = ss[11];\n\n s1[1] = ss[5];\n s1[3] = ss[7];\n\n ss = s1.clone();\n\n if check(&s1) && i != 1 {\n println!(\"YES\");\n return;\n }\n }\n\n let mut ss = seq.clone();\n let mut s1 = seq.clone();\n for i in 0..3 {\n s1[21] = ss[17];\n s1[20] = ss[16];\n\n s1[17] = ss[5];\n s1[16] = ss[4];\n\n s1[5] = ss[13];\n s1[4] = ss[12];\n\n s1[13] = ss[20];\n s1[12] = ss[21];\n\n ss = s1.clone();\n\n if check(&s1) && i != 1 {\n println!(\"YES\");\n return;\n }\n }\n\n let mut ss = seq.clone();\n let mut s1 = seq.clone();\n for i in 0..3 {\n s1[16] = ss[9];\n s1[18] = ss[8];\n\n s1[2] = ss[16];\n s1[3] = ss[18];\n\n s1[13] = ss[3];\n s1[15] = ss[2];\n\n s1[9] = ss[15];\n s1[8] = ss[13];\n\n ss = s1.clone();\n\n if check(&s1) && i != 1 {\n println!(\"YES\");\n return;\n }\n }\n\n println!(\"NO\");\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "dbf58bb6e0c53dfdc9f0b57930341300", "src_uid": "881a820aa8184d9553278a0002a3b7c4", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "static PERMS: [[usize; 8]; 3] = [\n [2, 4, 6, 8, 10, 12, 23, 21],\n [13, 14, 5, 6, 17, 18, 21, 22],\n [3, 4, 17, 19, 10, 9, 16, 14]\n];\n\n\nfn shiftmod(i: usize, dir: i32) -> usize {\n let res = i as i32 + 2 * dir;\n (if res < 0 { 8 + res } else if res > 8 { res - 8 } else { res }) as usize\n}\n\n\nstruct State(Vec);\n\nimpl State {\n fn shift(&mut self, perm: &[usize; 8], dir: i32) {\n for i in 0..6 {\n self.0.swap(perm[i] - 1, perm[shiftmod(i, dir)] - 1)\n }\n }\n\n fn is_correct(&self) -> bool {\n (0..6).all(|i|\n ((i * 4)..(i * 4 + 3))\n .all(|k| self.0[k] == self.0[k + 1]))\n }\n\n fn try_move(&mut self, perm: &[usize; 8], dir: i32) -> bool {\n self.shift(perm, dir);\n let res = self.is_correct();\n self.shift(perm, -dir);\n res\n }\n\n fn single_move(&mut self) -> bool {\n PERMS.iter().any(|perm| {\n self.try_move(perm, 1) || self.try_move(perm, -1)\n })\n }\n}\n\nfn main() {\n let mut sin = ReadIn::new();\n let mut colors = State(sin.intvec());\n println!(\"{}\", if colors.single_move() { \"YES\" } else { \"NO\" });\n}\n\n\nuse std::iter::*;\nuse std::str::SplitWhitespace;\nuse std::io::stdin;\nuse std::mem::forget;\n\npub struct ReadIn(pub String);\n\nimpl ReadIn {\n pub fn new() -> ReadIn { ReadIn(String::new()) }\n fn read_i32(s: &str) -> i32 { s.parse().unwrap() }\n pub fn read_line(&mut self) {\n self.0.clear();\n forget(stdin().read_line(&mut self.0));\n }\n pub fn ints(&mut self) -> Map i32> {\n self.read_line();\n self.0.split_whitespace().map(ReadIn::read_i32)\n }\n pub fn intvec(&mut self) -> Vec { self.ints().collect() }\n pub fn int(&mut self) -> i32 { self.ints().next().unwrap() }\n pub fn int2(&mut self) -> (i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap())\n }\n\n pub fn int3(&mut self) -> (i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n pub fn int4(&mut self) -> (i32, i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "d1b2e1cde0052061de14302f35fc65e4", "src_uid": "881a820aa8184d9553278a0002a3b7c4", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let colors: Vec = get_vec();\n\n let rotated = |face| {\n let mut ret_val = colors.clone();\n\n match face {\n 0 => {\n rotate(&mut ret_val, 0, 1, 3, 2);\n rotate(&mut ret_val, 21, 17, 5, 13);\n rotate(&mut ret_val, 20, 16, 4, 12);\n },\n 1 => {\n rotate(&mut ret_val, 4, 5, 7, 6);\n rotate(&mut ret_val, 2, 16, 9, 15);\n rotate(&mut ret_val, 3, 18, 8, 13);\n },\n 2 => {\n rotate_rev(&mut ret_val, 8, 9, 11, 10);\n rotate_rev(&mut ret_val, 6, 18, 22, 14);\n rotate_rev(&mut ret_val, 7, 19, 23, 15);\n },\n 3 => {\n rotate(&mut ret_val, 12, 13, 15, 14);\n rotate(&mut ret_val, 0, 4, 8, 23);\n rotate(&mut ret_val, 2, 6, 10, 21);\n },\n 4 => {\n rotate_rev(&mut ret_val, 16, 17, 19, 18);\n rotate_rev(&mut ret_val, 3, 20, 11, 7);\n rotate_rev(&mut ret_val, 1, 22, 9, 5);\n },\n 5 => {\n rotate_rev(&mut ret_val, 20, 21, 23, 22);\n rotate_rev(&mut ret_val, 1, 12, 10, 19);\n rotate_rev(&mut ret_val, 0, 14, 11, 17);\n },\n _ => panic!(\"Something happened.\"),\n }\n ret_val\n };\n\n for face in 0..6 {\n let r = rotated(face);\n if check(&r) {\n println!(\"YES\");\n return;\n }\n }\n\n println!(\"NO\");\n}\n\nfn rotate(v: &mut Vec, i: usize, j: usize, k: usize, l: usize) {\n let t = v[i];\n v[i] = v[j];\n v[j] = v[k];\n v[k] = v[l];\n v[l] = t;\n}\n\nfn rotate_rev(v: &mut Vec, i: usize, j: usize, k: usize, l: usize) {\n let t = v[l];\n v[l] = v[k];\n v[k] = v[j];\n v[j] = v[i];\n v[i] = t;\n}\n\nfn check(v: &Vec) -> bool {\n for face in 0..6 {\n for sq in 1..4 {\n if v[4 * face + sq] != v[4 * face] {\n return false;\n }\n }\n }\n true\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "1da5aff55f9e241597f92111e6beaf99", "src_uid": "881a820aa8184d9553278a0002a3b7c4", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::{TryInto, TryFrom}, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self;\n if a == 0 || b == 0 { return a | b; }\n let shift = (a | b).trailing_zeros();\n a >>= a.trailing_zeros();\n b >>= b.trailing_zeros();\n while a != b {\n if a > b { a -= b; a >>= a.trailing_zeros(); }\n else { b -= a; b >>= b.trailing_zeros(); }\n }\n a << shift\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, b: Self) -> Self {\n fn w_abs(x: $ix) -> $ux { (if x.is_negative() { x.wrapping_neg() } else { x }) as _ }\n w_abs(self).gcd(w_abs(b)) as _\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\npub trait BinarySearchExt {\n fn binary_search_by Ordering>(&self, f: F) -> Result;\n\n fn partition_point bool>(&self, mut f: F) -> T {\n self.binary_search_by(|x| if f(x) { Ordering::Less } else { Ordering::Greater }).err().unwrap()\n }\n}\nmacro_rules! impl_binary_search_ext_integer {\n ($($ty:tt),*) => {\n $(\n impl BinarySearchExt<$ty> for std::ops::Range<$ty> {\n fn binary_search_by Ordering>(&self, mut f: F) -> Result<$ty, $ty> {\n let mut low = self.start;\n let mut high = self.end;\n \n while low < high {\n let mid = (low & high) + ((low ^ high) >> 1);\n let cmp = f(mid);\n if cmp == Ordering::Less {\n low = mid + 1;\n } else if cmp == Ordering::Greater {\n high = mid;\n } else {\n return Ok(mid);\n }\n }\n Err(low)\n }\n }\n )*\n }\n}\nimpl_binary_search_ext_integer!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n\n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\t\n for _case_num in 1..=num_cases {\n\t\tlet n = read!(u32);\n\t\t\n\t\tlet ans = (n..2*n+2).partition_point(|x| x.saturating_sub(1) / 2 + x.saturating_sub(4) / 4 < n);\n\t\tprintln!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "geometry", "binary search"], "code_uid": "023d2684c80bf366520a08f691a136e9", "src_uid": "d0a8604b78ba19ab769fd1ec90a72e4e", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::{TryInto, TryFrom}, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self;\n if a == 0 || b == 0 { return a | b; }\n let shift = (a | b).trailing_zeros();\n a >>= a.trailing_zeros();\n b >>= b.trailing_zeros();\n while a != b {\n if a > b { a -= b; a >>= a.trailing_zeros(); }\n else { b -= a; b >>= b.trailing_zeros(); }\n }\n a << shift\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, b: Self) -> Self {\n fn w_abs(x: $ix) -> $ux { (if x.is_negative() { x.wrapping_neg() } else { x }) as _ }\n w_abs(self).gcd(w_abs(b)) as _\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\npub trait BinarySearchExt {\n fn binary_search_by Ordering>(&self, f: F) -> Result;\n\n fn partition_point bool>(&self, mut f: F) -> T {\n self.binary_search_by(|x| if f(x) { Ordering::Less } else { Ordering::Greater }).err().unwrap()\n }\n}\nmacro_rules! impl_binary_search_ext_integer {\n ($($ty:tt),*) => {\n $(\n impl BinarySearchExt<$ty> for std::ops::Range<$ty> {\n fn binary_search_by Ordering>(&self, mut f: F) -> Result<$ty, $ty> {\n let mut low = self.start;\n let mut high = self.end;\n \n while low < high {\n let mid = (low & high) + ((low ^ high) >> 1);\n let cmp = f(mid);\n if cmp == Ordering::Less {\n low = mid + 1;\n } else if cmp == Ordering::Greater {\n high = mid;\n } else {\n return Ok(mid);\n }\n }\n Err(low)\n }\n }\n )*\n }\n}\nimpl_binary_search_ext_integer!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n\n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\t\n for _case_num in 1..=num_cases {\n\t\tlet n = read!(i64);\n\t\t\n\t\tlet ans = if n == 1 {3} else {n*4/3 + 3};\n\t\tprintln!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "geometry", "binary search"], "code_uid": "222209a1bb9a63a716f2675bfc2fe4b0", "src_uid": "d0a8604b78ba19ab769fd1ec90a72e4e", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_variables)]\n#![allow(unused_must_use)]\nuse collections::*;\nuse std::io::Write;\nuse std::*;\n\nfn test_case(sc: &mut input::In, out: &mut std::io::BufWriter) {\n let n: usize = sc.read();\n if n == 1 {\n writeln!(out, \"3\");\n } else {\n writeln!(out, \"{}\", (4 * n + 9) / 3);\n }\n}\n\nfn main() {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut sc = input::In::new(&s);\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n let t = 1;\n // let t: usize = sc.read();\n for _ in 0..t {\n test_case(&mut sc, &mut out);\n }\n}\n\nmod input {\n use std::str::FromStr;\n use std::str::SplitWhitespace;\n pub struct In<'a> {\n iter: SplitWhitespace<'a>,\n }\n impl<'a> In<'a> {\n pub fn new(s: &'a String) -> Self {\n Self {\n iter: s.split_whitespace(),\n }\n }\n pub fn read(&mut self) -> T {\n self.iter.next().unwrap().parse::().ok().unwrap()\n }\n\n pub fn read_bytes(&mut self) -> Vec {\n self.iter.next().unwrap().bytes().collect()\n }\n pub fn read_chars(&mut self) -> Vec {\n self.iter.next().unwrap().chars().collect()\n }\n pub fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "geometry", "binary search"], "code_uid": "5319e78d2208472df8804bf239a3611a", "src_uid": "d0a8604b78ba19ab769fd1ec90a72e4e", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::{TryInto, TryFrom}, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self;\n if a == 0 || b == 0 { return a | b; }\n let shift = (a | b).trailing_zeros();\n a >>= a.trailing_zeros();\n b >>= b.trailing_zeros();\n while a != b {\n if a > b { a -= b; a >>= a.trailing_zeros(); }\n else { b -= a; b >>= b.trailing_zeros(); }\n }\n a << shift\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, b: Self) -> Self {\n fn w_abs(x: $ix) -> $ux { (if x.is_negative() { x.wrapping_neg() } else { x }) as _ }\n w_abs(self).gcd(w_abs(b)) as _\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\npub trait BinarySearchExt {\n fn binary_search_by Ordering>(&self, f: F) -> Result;\n\n fn partition_point bool>(&self, mut f: F) -> T {\n self.binary_search_by(|x| if f(x) { Ordering::Less } else { Ordering::Greater }).err().unwrap()\n }\n}\nmacro_rules! impl_binary_search_ext_integer {\n ($($ty:tt),*) => {\n $(\n impl BinarySearchExt<$ty> for std::ops::Range<$ty> {\n fn binary_search_by Ordering>(&self, mut f: F) -> Result<$ty, $ty> {\n let mut low = self.start;\n let mut high = self.end;\n \n while low < high {\n let mid = (low & high) + ((low ^ high) >> 1);\n let cmp = f(mid);\n if cmp == Ordering::Less {\n low = mid + 1;\n } else if cmp == Ordering::Greater {\n high = mid;\n } else {\n return Ok(mid);\n }\n }\n Err(low)\n }\n }\n )*\n }\n}\nimpl_binary_search_ext_integer!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n\n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\t\n for _case_num in 1..=num_cases {\n\t\tlet n = read!(u32);\n\t\t\n\t\tlet ans = (3..2*n+2).partition_point(|x| x.saturating_sub(1) / 2 + x.saturating_sub(4) / 4 < n);\n\t\tprintln!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "geometry", "binary search"], "code_uid": "37ab55470425d8cce0f4b6db5063967b", "src_uid": "d0a8604b78ba19ab769fd1ec90a72e4e", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::cmp::min;\n\nfn read_line() -> Vec {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n return buf.trim().split(\" \")\n .map(|x| {x.parse::().unwrap() })\n .collect();\n}\n\nfn get_ans (a : i32, b : i32, c : i32, d : i32) -> i32{\n let ans = -1;\n \n for i in 0..101{\n for j in 0..101{\n if (a*i + b == c*j + d){\n return a*i + b;\n }\n }\n }\n \n return 0x3f3f3f3f;\n}\n\n\nfn main(){\n let mut line = read_line();\n let (a, b) = (line[0], line[1]);\n line = read_line();\n let (c, d) = (line[0], line[1]);\n \n let mut ans = 0x3f3f3f3f;\n\n ans = min (get_ans(c, d, a, b), get_ans(a, b, c, d));\n if (ans == 0x3f3f3f3f){\n println! (\"-1\");\n }\n else{\n println! (\"{}\", ans);\n }\n \n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "abc2567ec50b14b3ee4ad459f54a64d0", "src_uid": "158cb12d45f4ee3368b94b2b622693e7", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec(s: String) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n s.split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn extended_euclid(a: i32, b: i32) -> (i32, i32, i32) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d, x, y) = extended_euclid(b, modulo(a, b));\n (d, y, x - a / b * y)\n }\n}\n\nfn modulo(a: i32, b: i32) -> i32 {\n let ret_val = a % b;\n if ret_val < 0 {\n ret_val + b\n } else {\n ret_val\n }\n}\n\nfn main() {\n let (a, b): (i32, i32) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n \n let (c, d): (i32, i32) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let e = d - b;\n\n let (g, x, y) = extended_euclid(a, c);\n\n let ans = if e % g != 0 {\n -1\n } else {\n let x1 = x * e / g;\n let x2 = modulo(x1, c / g);\n\n let y1 = y * e / g;\n let y2 = modulo(-y1, a / g);\n\n max(b + x2 * a, d + y2 * c)\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "ea1ec94c1d51f12c977bd2cb02db3f25", "src_uid": "158cb12d45f4ee3368b94b2b622693e7", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn gcd(mut x: usize, mut y: usize) -> usize {\n while y != 0 {\n let z = x%y;\n x = y;\n y = z;\n }\n x\n}\n\nfn lcm(x: usize, y: usize) -> usize {\n x * y / gcd(x, y)\n}\n\nfn main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut line = line.split_whitespace();\n let a = line.next().unwrap().parse::().unwrap();\n let b = line.next().unwrap().parse::().unwrap();\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut line = line.split_whitespace();\n let c = line.next().unwrap().parse::().unwrap();\n let d = line.next().unwrap().parse::().unwrap();\n\n let mut counter_one = 0;\n let mut counter_two = 0;\n let limit = lcm(a, c);\n loop {\n let (x, y) = (counter_one + b, counter_two + d);\n if x == y {\n println!(\"{}\", x);\n return;\n } else if x < y {\n counter_one += a;\n } else {\n counter_two += c;\n }\n if counter_one > limit && counter_two > limit {\n println!(\"-1\");\n return;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "a940d71e345019b29e6310e20b69ac07", "src_uid": "158cb12d45f4ee3368b94b2b622693e7", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read, stdin};\n\nfn main() {\n let mut buf = String::new();\n stdin().read_to_string(&mut buf).unwrap();\n let mut tok = buf.split_whitespace();\n let mut get = || tok.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(usize));\n }\n \n let n = get!();\n let m = get!();\n let mut fs = vec![0; 101];\n for _ in 0..m {\n fs[get!()] += 1;\n }\n let fs: Vec<_> = fs\n .into_iter()\n .filter(|v| *v > 0)\n .collect();\n \n let mut ans = 0;\n for i in 1..101 {\n let mut c = 0;\n for &f in fs.iter() {\n c += f / i;\n }\n if c >= n {\n ans = i;\n }\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "53e93218d1042b7a7f7641c4d54a0598", "src_uid": "b7ef696a11ff96f2e9c31becc2ff50fe", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! except {\n ($result: expr) => {\n match $result {\n Err(e) => panic!(\"{}\", e),\n Ok(m) => m,\n }\n };\n ($result: expr, $msg: expr) => {\n match $result {\n Err(e) => panic!(\"{}: {}\", $msg, e),\n Ok(m) => m,\n }\n };\n}\n\nfn parse_line() -> Vec {\n let mut input = String::new();\n except!(io::stdin().read_line(&mut input));\n input.trim().split_whitespace()\n .map(|x| except!(x.parse::()))\n .collect()\n}\n\nconst MAXN: u8 = 100;\n\nfn main() {\n let n = parse_line()[0];\n let a = parse_line();\n let counts = a.iter().fold([0u8; 101], |mut v, &x| {v[x as usize] += 1; v});\n for i in 1..MAXN + 1 {\n if n > counts.iter().fold(0, |v, x| v + x / i) {\n println!(\"{}\", i - 1);\n return\n }\n }\n println!(\"{}\", MAXN);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "001717ee2121b92494e502788bda8714", "src_uid": "b7ef696a11ff96f2e9c31becc2ff50fe", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! unwrap {\n ($result: expr) => {\n match $result {\n Err(e) => panic!(\"{}\", e),\n Ok(m) => m,\n }\n };\n}\n\nfn parse_line() -> Vec {\n let mut input = String::new();\n unwrap!(io::stdin().read_line(&mut input));\n input.trim().split_whitespace()\n .map(|x| unwrap!(x.parse::()))\n .collect()\n}\n\nconst MAXN: u8 = 100;\n\nfn main() {\n let n = parse_line()[0];\n let a = parse_line();\n let counts = a.iter().fold([0u8; MAXN as usize + 1], |mut v, &x| {v[x as usize] += 1; v});\n for i in 1..counts.len() as u8 / n + 2 {\n if n > counts.iter().fold(0, |v, x| v + x / i) {\n println!(\"{}\", i - 1);\n return\n }\n }\n println!(\"{}\", MAXN);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "8bc7dde678ce64376ac31072d8497dfb", "src_uid": "b7ef696a11ff96f2e9c31becc2ff50fe", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! except {\n ($result: expr) => {\n match $result {\n Err(e) => panic!(\"{}\", e),\n Ok(m) => m,\n }\n };\n ($result: expr, $msg: expr) => {\n match $result {\n Err(e) => panic!(\"{}: {}\", $msg, e),\n Ok(m) => m,\n }\n };\n}\n\nfn parse_line() -> Vec {\n let mut input = String::new();\n except!(io::stdin().read_line(&mut input));\n input.trim().split_whitespace()\n .map(|x| except!(x.parse::()))\n .collect()\n}\n\n\nfn main() {\n let n = parse_line()[0] as usize;\n let a = parse_line();\n if n > a.len() {\n println!(\"0\");\n return\n }\n let mut counts = a.iter().fold([0u8; 101], |mut v, &x| {v[x as usize] += 1; v});\n counts.sort_unstable_by(|x, y| y.cmp(x));\n let mut nums = vec![0u8; n];\n for _ in 0..n {\n let (index, _) = nums.iter().enumerate()\n .max_by_key(|&(i, v)| counts[i] / (v + 1)).unwrap();\n nums[index] += 1;\n }\n let (index, _) = nums.iter().enumerate().filter(|&(_, v)| *v != 0)\n .min_by_key(|&(i, v)| counts[i] / v).unwrap();\n println!(\"{}\", counts[index] / nums[index]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "bc07be3dc9f4fd702812c94803e0db58", "src_uid": "b7ef696a11ff96f2e9c31becc2ff50fe", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn gcd(mut u: u64, mut v: u64) -> u64 {\n if u == 0 {\n return v;\n }\n if v == 0 {\n return u;\n }\n\n let mut shift = 0;\n let mut aux : [u64; 2] = [(u | v), 1];\n while aux[0] & aux[1] == 0 {\n shift += 1;\n aux[1] <<= 1;\n }\n u >>= shift;\n v >>= shift;\n\n while u & 1 == 0 {\n u >>= 1;\n }\n\n loop {\n while v & 1 == 0 {\n v >>= 1;\n }\n \n if u > v {\n aux[0] = v;\n v = u;\n u = aux[0];\n }\n v -= u;\n\n if v == 0 {\n break;\n }\n }\n u << shift\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"failed to read input\");\n let mut input_iter = input.split_whitespace();\n let a = input_iter.next().unwrap().parse::().unwrap();\n let b = input_iter.next().unwrap().parse::().unwrap();\n\n let md = if a > b { a - b } else { b - a };\n let sqrt_md = (md as f64).sqrt() as u64 + 1;\n let mut lcm_min = 4 * a * b;\n let mut min_k = 0;\n let mut vec = Vec::new();\n for i in (1..=sqrt_md).filter(|x| md % x == 0) {\n vec.push(md / i);\n\n let mut k = a % i;\n if k != 0 {\n k = i - k;\n }\n\n let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));\n if lcm < lcm_min {\n lcm_min = lcm;\n min_k = k;\n }\n }\n if md != 0 {\n for i in vec {\n let mut k = a % i;\n if k != 0 {\n k = i - k;\n }\n\n let lcm = (a + k) * (b + k) / (i * gcd((a + k) / i, (b + k) / i));\n if lcm < lcm_min {\n lcm_min = lcm;\n min_k = k;\n }\n }\n }\n\n println!(\"{}\", min_k);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "88ec19129b2b454da8587d3a9a13c19a", "src_uid": "414149fadebe25ab6097fc67663177c3", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn is_sufficient(v: u64, n: u64, k: u64) -> bool {\n let summand_count = ((v as f64).log(k as f64).trunc() + 1_f64) as usize;\n // dbg!(summand_count);\n let sum: u64 = (0..summand_count).map(|x| v / k.checked_pow(x as u32).unwrap()).sum();\n // dbg!(sum);\n sum >= n\n}\n\nfn solve(n: u64, k: u64) -> u64 {\n let mut l: u64 = 1;\n let mut r: u64 = n + 1;\n while r - l > 2 {\n let m = l + (r - l) / 2;\n // dbg!(l, m, r);\n if is_sufficient(m, n, k) {\n // dbg!(\"YES\");\n r = m + 1;\n } else {\n // dbg!(\"NO\");\n l = m;\n }\n }\n // dbg!(is_sufficient(4, n, k));\n if is_sufficient(l, n, k) {l} else {l + 1}\n}\n\nfn main() {\n let (n, k) = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let mut n_k = buf.trim().split_whitespace().map(|x| x.parse::().unwrap());\n let n = n_k.next().unwrap();\n let k = n_k.next().unwrap();\n (n, k)\n };\n\n println!(\"{}\", solve(n, k));\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "binary search"], "code_uid": "eb31d0cf63f61a7bd13865364fc8cdbe", "src_uid": "41dfc86d341082dd96e089ac5433dc04", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn bs(f: F, mut mi: i64, mut ma: i64) -> i64\nwhere\n F: Fn(i64) -> bool,\n{\n let mut mm = 0;\n while mi < ma {\n mm = (mi + ma) / 2;\n if f(mm) {\n mi = mm + 1;\n } else {\n ma = mm;\n }\n }\n if f(mm) {\n mm + 1\n } else {\n mm\n }\n}\n\n#[allow(dead_code)]\nfn solve() -> Vec {\n let mut input = \"\".split_ascii_whitespace();\n let mut read = || loop {\n if let Some(word) = input.next() {\n break word;\n }\n input = {\n let mut input = \"\".to_owned();\n io::stdin().read_line(&mut input).unwrap();\n if input.is_empty() {\n panic!(\"reached EOF\");\n }\n Box::leak(input.into_boxed_str()).split_ascii_whitespace()\n };\n };\n macro_rules! read(($ty:ty) => (read().parse::<$ty>().unwrap()));\n\n let mut rr = vec![\"\".to_string(); 0];\n\n let t = 1;\n for _ in 0..t {\n let n = read!(i64);\n let k = read!(i64);\n\n let f = |i| {\n let mut u: i64 = 0;\n let mut kk = 1;\n while kk <= i {\n u += i / kk;\n kk *= k;\n }\n u < n\n };\n\n let r = bs(f, 0, n);\n rr.push(format!(\"{}\", r));\n }\n\n rr\n}\n\n#[allow(dead_code)]\nfn main() {\n let output = solve();\n println!(\"{}\", output.join(\"\\n\"));\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "binary search"], "code_uid": "f9f0ea3dd9fd37fcd296cdaee9e3faa7", "src_uid": "41dfc86d341082dd96e089ac5433dc04", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer\n}\n\nfn main() {\n let input = get_input()\n .trim()\n .split(\" \")\n .map(|s| s.parse::().unwrap())\n .collect::>();\n\n let rows = input[0];\n let columns = input[1];\n\n if rows == 1 {\n println!(\"{}\", columns - 1);\n return;\n }\n\n if columns == 1 {\n println!(\"{}\", rows - 1);\n return;\n }\n\n println!(\"{}\", rows * (columns - 1));\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "cd346c3c1df17b235cce9a382b1a0f50", "src_uid": "a91aab4c0618d036c81022232814ef44", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn main() {\n let stdin = std::io::stdin();\n let mut input = std::io::BufReader::new(stdin);\n let a = read_vec_i64(&mut input);\n let solution = solve(a[0], a[1]);\n println!(\"{solution}\");\n\n}\n\nfn solve(n: i64, m: i64,) -> i64 {\n if m == 1 {\n n - 1\n }\n else {\n n * (m - 1)\n }\n}\n\n#[allow(dead_code)]\nfn read_i32(reader: &mut impl std::io::BufRead) -> i32 {\n let mut line = String::new();\n reader.read_line(&mut line).unwrap();\n line.trim().parse::().unwrap()\n}\n\n#[allow(dead_code)]\nfn read_vec_i32(reader: &mut impl std::io::BufRead) -> Vec {\n let mut line = String::new();\n reader.read_line(&mut line).unwrap();\n line = line.trim().into();\n line.split(\" \").map(|s| s.parse::().unwrap()).collect()\n}\n\n#[allow(dead_code)]\nfn read_i64(reader: &mut impl std::io::BufRead) -> i64 {\n let mut line = String::new();\n reader.read_line(&mut line).unwrap();\n line.trim().parse::().unwrap()\n}\n\n#[allow(dead_code)]\nfn read_vec_i64(reader: &mut impl std::io::BufRead) -> Vec {\n let mut line = String::new();\n reader.read_line(&mut line).unwrap();\n line = line.trim().into();\n line.split(\" \").map(|s| s.parse::().unwrap()).collect()\n}\n\n#[allow(dead_code)]\nfn read_string(reader: &mut impl std::io::BufRead) -> String {\n let mut line = String::new();\n reader.read_line(&mut line).unwrap();\n line.trim().into()\n}\n\n#[allow(dead_code)]\nfn read_chars(reader: &mut impl std::io::BufRead) -> Vec {\n let mut line = String::new();\n reader.read_line(&mut line).unwrap();\n line.trim().chars().collect()\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "741f7089ed1ccd33d5da35af36cf402c", "src_uid": "a91aab4c0618d036c81022232814ef44", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn main() {\r\n let mut input_line = String::new();\r\n std::io::stdin()\r\n .read_line(&mut input_line)\r\n .expect(\"Failed to read line\");\r\n\r\n let mut parts = input_line.split_whitespace();\r\n let n: usize = parts.next().expect(\"Not enough input numbers\")\r\n .parse().expect(\"Input is not a number\");\r\n let m: usize = parts.next().expect(\"Not enough input numbers\")\r\n .parse().expect(\"Input is not a number\");\r\n\r\n if m == 1 {\r\n println!(\"{}\", n - 1)\r\n } else {\r\n println!(\"{}\", n * (m - 1));\r\n }\r\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "b2939aa51be4394e54e8cfbd8cb332d9", "src_uid": "a91aab4c0618d036c81022232814ef44", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! debug(\n ($($arg:tt)*) => { {\n let r = writeln!(&mut ::std::io::stderr(), $($arg)*);\n r.expect(\"failed printing to stderr\");\n } }\n);\n\nstruct Scanner {\n buffer : std::collections::VecDeque\n}\n\nimpl Scanner {\n\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn next(&mut self) -> T {\n\n if self.buffer.len() == 0 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n for word in input.split_whitespace() {\n self.buffer.push_back(word.to_string())\n }\n }\n\n let front = self.buffer.pop_front().unwrap();\n front.parse::().ok().unwrap()\n }\n}\n\nfn main() {\n let mut s = Scanner::new();\n let input = s.next::();\n let mut iter = input.chars();\n let column = iter.next().unwrap();\n let row = iter.next().unwrap();\n\n if column == 'a' || column == 'h' {\n if row == '1' || row == '8' {\n println!(\"3\");\n } else {\n println!(\"5\");\n }\n } else if row == '1' || row == '8' {\n if column == 'a' || column == 'h' {\n println!(\"3\");\n } else {\n println!(\"5\");\n }\n } else {\n println!(\"8\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "60ff2e3dfdeac9963de2b4ec8af7e5b2", "src_uid": "6994331ca6282669cbb7138eb7e55e01", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Error\");\n let letter = line.chars().nth(0).expect(\"Error\");\n let number = line.chars().nth(1).expect(\"Error\");\n let array = [letter, number];\n\n fn boundary(a: char) -> bool {\n match a {\n 'a' | 'h' | '1' | '8' => true,\n _ => false,\n }\n }\n let cnt = array.iter().map(|x| boundary(*x)).filter(|x| *x).count();\n\n let res = match cnt {\n 0 => 8,\n 1 => 5,\n 2 => 3,\n _ => unreachable!(),\n };\n println!(\"{}\", res);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e35e0dbe532a35413c4e3479f30e2fdd", "src_uid": "6994331ca6282669cbb7138eb7e55e01", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut guess = String::new();\n\n io::stdin().read_line(&mut guess)\n .expect(\"Failed to read whatever you enter\");\n \n \n let first = guess.chars().nth(0).unwrap();\n let second = guess.chars().nth(1).unwrap();\n let mut allow = 8;\n let mut left_or_rigt_most = false;\n\n if first == 'a' || first == 'h' {\n left_or_rigt_most = true;\n allow -= 3;\n }\n\n if second == '1' || second == '8' {\n if left_or_rigt_most {\n allow -= 2;\n } else {\n allow -= 3;\n }\n }\n\n println!(\"{}\", allow);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6738d73364ff6c9e4312f18efa887d12", "src_uid": "6994331ca6282669cbb7138eb7e55e01", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get().parse::().unwrap());\n ($t:ty) => (get().parse::<$t>().unwrap());\n }\n \n let n = get!();\n let k = get!();\n \n fn solve(n: i64, k: i64) -> bool {\n if k == 1 {\n return true;\n }\n if k >= n {\n return n == 1 && (k <= 2);\n }\n let mut k = k;\n while k > 0 {\n if n % k != k - 1 {\n return false;\n }\n k -= 1\n }\n true\n }\n \n if solve(n, k) {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n \n for a in 1..31 {\n for b in 1..31 {\n let mut ok = true;\n let mut f = vec![false; b+1];\n for i in 1..b+1 {\n let p = a % i;\n if f[p] {\n ok = false;\n break;\n }\n f[p] = true;\n }\n if ok != solve(a as i64, b as i64) {\n println!(\"{} {} {}\", a, b, ok);\n }\n }\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "a429434213b8c9763c1ca702a9d668ce", "src_uid": "5271c707c9c72ef021a0baf762bf3eb2", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n *\n * Author : fcbruce \n *\n * Time : Sat 10 Feb 2018 20:02:28\n *\n */\n\nfn main() {\n\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).unwrap();\n let mut numbers = buffer.split_whitespace();\n let n: u64 = numbers.next().unwrap().parse::().unwrap();\n let k: u64 = numbers.next().unwrap().parse::().unwrap();\n\n let max: usize = 100000;\n\n let mut remainders = vec![false; max];\n\n let mut min = k + 1;\n\n for i in 1..std::cmp::min::(max as u64, k + 1) {\n let r: usize = (n % i) as usize;\n if remainders[r] {\n min = i;\n break;\n }\n remainders[r] = true;\n }\n\n if k == 1 || k < min {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "eca6aa444a73ce576bbad5a4af8efd84", "src_uid": "5271c707c9c72ef021a0baf762bf3eb2", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"input: read line failed\");\n let number = input.trim().parse::().expect(\"number: parse to usize failed\");\n\n let vec = vec![\n hp_judge(0, number),\n hp_judge(1, number),\n hp_judge(2, number),\n ];\n \n let outcome = great_hp(vec);\n\n println!(\"{} {}\", outcome.0, outcome.1);\n\n\n\n}\n\nfn great_hp(hp_vec: Vec<(i32, i32)>) -> (i32, String) {\n let mut best_hp = (i32::default(), i32::default());\n\n for item in hp_vec.iter() {\n if item.1 > best_hp.1 {\n best_hp = *item;\n }\n }\n\n\n\n convert(best_hp)\n}\n\nfn hp_judge(offset: i32, number: i32) -> (i32, i32) {\n ( offset, grade_estimation(number + offset) )\n}\n\nfn grade_estimation(hp: i32) -> i32 {\n let reminder = hp % 4;\n\n match reminder {\n 0 => { 0 },\n 1 => { 3 },\n 2 => { 1 },\n 3 => { 2 },\n _ => { -1 },\n\n }\n}\n\nfn convert(hp: (i32, i32)) -> (i32 ,String) {\n match hp.1 {\n 0 => { (hp.0, String::from(\"D\")) },\n 3 => { (hp.0, String::from(\"A\")) },\n 1 => { (hp.0, String::from(\"C\")) },\n 2 => { (hp.0, String::from(\"B\")) },\n _ => { (hp.0, String::from(\"Err\")) },\n }\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "4d0badbf89562194a0fdc68beb020616", "src_uid": "488e809bd0c55531b0b47f577996627e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn get_class(x: usize) -> usize {\n let classes = [0usize, 2, 3, 1];\n return classes.iter().position(|&v| v == (x % 4)).unwrap();\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let x: usize = scan.next();\n let mut maxclass = get_class(x);\n let mut maxb = 0;\n for &step in [1usize, 2].iter() {\n let current_class = get_class(x + step);\n if current_class > maxclass {\n maxclass = current_class;\n maxb = step;\n }\n }\n println!(\"{} {}\", maxb, ['D', 'C', 'B', 'A'][maxclass]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "737d1b7b451b659615b552c8fd448d6c", "src_uid": "488e809bd0c55531b0b47f577996627e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\nuse utils::*;\n\npub fn main() {\n let i = stdin();\n let mut o = Vec::new();\n run(i.lock(), &mut o);\n stdout().write_all(&o).unwrap();\n}\n\npub fn run(i: R, o: &mut W) {\n let mut i = CpReader::new(i);\n let x = i.read::();\n\n let (a, b) = solve(x);\n writeln!(o, \"{} {}\", a, b).unwrap();\n}\nfn solve(x: u32) -> (u32, char) {\n fn to_category(x: u32) -> char {\n match x % 4 {\n 1 => 'A',\n 3 => 'B',\n 2 => 'C',\n 0 => 'D',\n _ => unreachable!(),\n }\n }\n [0, 1, 2]\n .iter()\n .map(|&a| (a, to_category(x + a)))\n .min_by_key(|&(_a, c)| c)\n .unwrap()\n}\n\npub mod utils {\n use super::*;\n\n pub struct CpReader {\n r: R,\n b: Vec,\n }\n impl CpReader {\n pub fn new(r: R) -> Self {\n CpReader {\n r: r,\n b: Vec::new(),\n }\n }\n pub fn read_word(&mut self) -> &[u8] {\n self.b.clear();\n let mut consume = 0;\n loop {\n self.r.consume(consume);\n let b = self.r.fill_buf().unwrap();\n assert!(b.len() != 0);\n if let Some(p) = b.iter().position(|&x| x.is_ascii_whitespace()) {\n self.b.extend_from_slice(&b[..p]);\n consume = p + 1;\n break;\n }\n self.b.extend_from_slice(b);\n consume = b.len();\n }\n self.r.consume(consume);\n consume_ws(&mut self.r);\n &self.b\n }\n pub fn read_word_str(&mut self) -> &str {\n unsafe { std::str::from_utf8_unchecked(self.read_word()) }\n }\n\n pub fn read_line(&mut self) -> &[u8] {\n self.b.clear();\n self.r.read_until(b'\\n', &mut self.b).unwrap();\n let end = self\n .b\n .iter()\n .rposition(|x| !x.is_ascii_whitespace())\n .map(|idx| idx + 1)\n .unwrap_or(0);\n &self.b[..end]\n }\n pub fn read_line_str(&mut self) -> &str {\n unsafe { std::str::from_utf8_unchecked(self.read_line()) }\n }\n\n pub fn read(&mut self) -> T {\n T::read_from(self)\n }\n\n pub fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {\n CpIter {\n r: self,\n n: n,\n _pd: Default::default(),\n }\n }\n }\n pub struct CpIter<'a, R: BufRead + 'a, T> {\n r: &'a mut CpReader,\n n: usize,\n _pd: std::marker::PhantomData T>,\n }\n impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {\n type Item = T;\n fn next(&mut self) -> Option {\n if self.n == 0 {\n None\n } else {\n self.n -= 1;\n Some(self.r.read())\n }\n }\n }\n\n pub trait CpIn {\n fn read_from(r: &mut CpReader) -> Self;\n }\n\n impl CpIn for u64 {\n fn read_from(r: &mut CpReader) -> Self {\n read_u64_fast(&mut r.r)\n }\n }\n impl CpIn for i64 {\n fn read_from(r: &mut CpReader) -> Self {\n read_i64_fast(&mut r.r)\n }\n }\n impl CpIn for char {\n fn read_from(r: &mut CpReader) -> Self {\n let b = r.r.fill_buf().unwrap()[0] as char;\n r.r.consume(1);\n let s = r.r.fill_buf().unwrap()[0];\n assert!(s == b' ' || s == b'\\n');\n r.r.consume(1);\n b\n }\n }\n\n macro_rules! cpin_tuple {\n ($($t:ident),*) => {\n impl<$($t: CpIn),*> CpIn for ($($t),*) {\n fn read_from(r: &mut CpReader) -> Self {\n ($($t::read_from(r)),*)\n }\n }\n };\n }\n\n macro_rules! cpin_cast {\n ($t_self:ty, $t_read:ty) => {\n impl CpIn for $t_self {\n fn read_from(r: &mut CpReader) -> Self {\n <$t_read>::read_from(r) as $t_self\n }\n }\n };\n }\n macro_rules! cpin_parse {\n ($t:ty) => {\n impl CpIn for $t {\n fn read_from(r: &mut CpReader) -> Self {\n r.read_word_str().parse().unwrap()\n }\n }\n };\n }\n cpin_cast!(usize, u64);\n cpin_cast!(u32, u64);\n cpin_cast!(u16, u64);\n cpin_cast!(i32, i64);\n cpin_cast!(i16, i64);\n cpin_cast!(i8, i64);\n\n cpin_parse!(f64);\n\n cpin_tuple!(T1, T2);\n cpin_tuple!(T1, T2, T3);\n cpin_tuple!(T1, T2, T3, T4);\n cpin_tuple!(T1, T2, T3, T4, T5);\n\n fn read_u64_fast(r: &mut R) -> u64 {\n let mut value = 0;\n loop {\n let mut idx = 0;\n let buf_len;\n {\n let buf = r.fill_buf().unwrap();\n buf_len = buf.len();\n assert!(buf_len != 0);\n while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {\n value = value * 10 + (buf[idx] - b'0') as u64;\n idx += 1;\n }\n }\n if idx < buf_len {\n r.consume(idx);\n consume_ws(r);\n return value;\n }\n r.consume(idx);\n }\n }\n fn read_i64_fast(r: &mut R) -> i64 {\n let (consume, sign) = match r.fill_buf().unwrap()[0] {\n b'+' => (true, 1),\n b'-' => (true, -1),\n _ => (false, 1),\n };\n if consume {\n r.consume(1);\n }\n read_u64_fast(r) as i64 * sign\n }\n fn consume_ws(r: &mut R) {\n let mut c = 0;\n loop {\n r.consume(c);\n let b = r.fill_buf().unwrap();\n if b.len() == 0 {\n return;\n }\n if let Some(p) = b.iter().position(|&x| !x.is_ascii_whitespace()) {\n c = p;\n break;\n }\n c = b.len();\n }\n r.consume(c);\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "46bc2f733c13b73e6eeb98ce7871c1cc", "src_uid": "488e809bd0c55531b0b47f577996627e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Template adapted from submissions by https://codeforces.com/profile/EbTech\n\n#[allow(unused_imports)]\nuse std::io::*;\n\n#[derive(Default)]\nstruct Scanner(Vec);\nimpl Scanner {\n fn read(&mut self) -> T {\n loop {\n if let Some(token) = self.0.pop() {\n return token.parse().ok().unwrap();\n }\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n self.0 = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut cin = Scanner::default();\n let cout = &mut BufWriter::new(stdout());\n\n let x: u8 = cin.read();\n let (a, b) = match x % 4 {\n 1 => (0, 'A'),\n 3 => (2, 'A'),\n 2 => (1, 'B'),\n 0 => (1, 'A'),\n _ => unreachable!(),\n };\n\n writeln!(cout, \"{} {}\", a, b).unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "d308c3bf688aec9b8e7d0dc7bd0b592b", "src_uid": "488e809bd0c55531b0b47f577996627e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\n\nfn read_string() -> String {\n let mut string: String = String::new();\n\n std::io::stdin().read_line(&mut string)\n .ok()\n .expect(\"Error read line!\");\n return string;\n}\n\n\nfn main() {\n\n let hp : i32 = read_string().trim().parse().ok().expect(\"not int\");\n\n let mut category : HashMap = HashMap::new();\n category.insert(1, \"0 A\");\n category.insert(3, \"2 A\");\n category.insert(2, \"1 B\");\n category.insert(0, \"1 A\");\n println!(\"{}\", category[&(hp % 4)]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "851106be45aeb2bf33e5d367bc45c674", "src_uid": "488e809bd0c55531b0b47f577996627e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]\nstruct Score{\n grade: String,\n score: i32\n}\n\nfn calculate_grade(grade: i32) -> String{\n let mut words : String;\n match grade {\n 1 => words = String::from(\"A\"),\n 2 => words = String::from(\"C\"),\n 3 => words = String::from(\"B\"),\n _ => words = String::from(\"D\")\n }\n words\n}\n\nfn main() {\n let mut t: String = String::new();\n std::io::stdin().read_line(&mut t).expect(\"input\");\n let counter:Vec = t.trim()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"Not an Integer!\"))\n .collect();\n\n let mut list_of_score : Vec = Vec::new();\n for i in 0..3{\n list_of_score.push( Score {\n score: i ,\n grade: calculate_grade((counter[0] + i) % 4)\n })\n }\n list_of_score.sort();\n println!(\"{} {}\", list_of_score[0].score, list_of_score[0].grade);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "460a2cf03380b68227a5259ddae2575a", "src_uid": "488e809bd0c55531b0b47f577996627e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let mut a = vec![0; 3];\n for i in 0..n {\n a[i % 3] += input.i();\n }\n let max = a.iter().max().unwrap();\n for (x,y) in vec![\"chest\",\"biceps\",\"back\"].into_iter().zip(a.iter()) {\n if max == y {\n println!(\"{}\", x);\n }\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "294a07b7d78a27812882b1f5e0dbb8a5", "src_uid": "579021de624c072f5e0393aae762117e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input_count() -> [u8; 3] {\n let mut buf = String::new();\n let mut body = [0; 3];\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse::().unwrap())\n .zip(0..)\n .for_each(|(a_i, i)| body[i % 3] += a_i);\n body\n}\n\nfn main() {\n {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n }\n println!(\n \"{}\",\n input_count()\n .iter()\n .zip([\"chest\", \"biceps\", \"back\"].iter())\n .max()\n .unwrap()\n .1\n );\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d256e15f9fb3250079747e58ca2a85fa", "src_uid": "579021de624c072f5e0393aae762117e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let mut cnt = [0usize; 3];\n let ex_msg = [\"chest\", \"biceps\", \"back\"];\n let mut maxa = 0usize;\n let mut maxi = 0usize;\n for i in 0..n {\n let a: usize = scan.next();\n let exi = i % 3;\n cnt[exi] += a;\n if cnt[exi] > maxa {\n maxa = cnt[exi];\n maxi = exi;\n }\n }\n println!(\"{}\", ex_msg[maxi]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "edeeb4a9e9f5ff6256d906282f8eaac4", "src_uid": "579021de624c072f5e0393aae762117e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let mut field: Vec> = (0..11).map(|_| util::line().chars().collect()).collect();\n let (mut y, mut x) = get!(usize, usize);\n\n y -= 1;\n x -= 1;\n\n let ry = y - 3 * (y / 3);\n let rx = x - 3 * (x / 3);\n\n let sy = 4 * ry;\n let sx = 4 * rx;\n\n if (sy..sy + 3).all(|y1| (sx..sx + 3).all(|x1| field[y1][x1] != '.')) {\n for v in field.iter_mut() {\n for c in v.iter_mut() {\n if *c == '.' {\n *c = '!';\n }\n }\n }\n } else {\n for y1 in sy..sy + 3 {\n for x1 in sx..sx + 3 {\n if field[y1][x1] == '.' {\n field[y1][x1] = '!';\n }\n }\n }\n }\n\n for line in &field {\n println!(\n \"{}\",\n line.iter()\n .map(|c| c.to_string())\n .collect::>()\n .join(\"\")\n );\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d25a88293e875a61e0f0a0f9ed5271bd", "src_uid": "8f0fad22f629332868c39969492264d3", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(&mut std::io::stdin(), &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get().parse::().unwrap());\n ($t:ty) => (get().parse::<$t>().unwrap()); }\n \n let mut field = vec![vec![]; 9];\n for i in 0..9 {\n for _ in 0..3 {\n field[i].push(get().as_bytes());\n }\n }\n let y = (get!(usize) - 1) % 3;\n let x = (get!(usize) - 1) % 3;\n \n let mut c = 0;\n for i in 0..3 {\n for &ch in &field[y*3+i][x][..] {\n if ch == b'.' {\n c += 1;\n }\n }\n }\n if c == 0 {\n for i in 0..9 {\n for j in 0..3 {\n if j > 0 { print!(\" \"); }\n for k in 0..3 {\n let ch = field[i][j][k];\n if ch == b'.' {\n print!(\"!\");\n } else {\n print!(\"{}\", ch as char);\n }\n }\n }\n println!();\n if i % 3 == 2 { println!(); }\n }\n return;\n }\n for i in 0..9 {\n for j in 0..3 {\n if j > 0 { print!(\" \"); }\n for k in 0..3 {\n let ch = field[i][j][k];\n if ch == b'.' && j == x && i / 3 == y {\n print!(\"!\");\n } else {\n print!(\"{}\", ch as char);\n }\n }\n }\n println!();\n if i % 3 == 2 { println!(); }\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d5a7099228bf615769de3116ae60c30d", "src_uid": "8f0fad22f629332868c39969492264d3", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::prelude::*;\n std::io::stdin().read_to_string(&mut input).unwrap();\n\n let p = input.bytes().position(|b| b'0' <= b && b <= b'9').unwrap();\n\n let grid: Vec<_> = input.as_bytes()[0..p].iter().filter_map(|&b| match b {\n b'.' => Some(Cell::Empty),\n b'x' => Some(Cell::Chip1),\n b'o' => Some(Cell::Chip2),\n _ => None,\n }).collect();\n\n let check = |x: usize, y: usize, grid: &Vec| {\n let x_off = 27 * x;\n let y_off = 3 * y;\n let mut it = grid[x_off + y_off..].iter().take(3)\n .chain(grid[x_off + y_off + 9..].iter().take(3))\n .chain(grid[x_off + y_off + 18..].iter().take(3));\n\n !it.all(|cell| match *cell {\n Cell::Empty => false,\n _ => true,\n })\n };\n\n let mut it = input[p..].split_whitespace();\n let x: usize = it.next().unwrap().parse::().unwrap() - 1;\n let y: usize = it.next().unwrap().parse::().unwrap() - 1;\n\n let bx = x % 3;\n let by = y % 3;\n\n let ans: Vec<_> = if !check(bx, by, &grid) {\n grid.into_iter().map(|cell| match cell {\n Cell::Empty => Cell::Possible,\n _ => cell,\n }).collect()\n } else {\n grid.into_iter().enumerate().map(|(i, cell)| {\n let x = i / 9;\n let y = i % 9;\n match cell {\n Cell::Empty if x / 3 == bx && y / 3 == by => Cell::Possible,\n _ => cell,\n }\n }).collect()\n };\n\n let mut ans_str = Vec::with_capacity(2 * p);\n\n for (i, cell) in ans.into_iter().enumerate() {\n let next = match cell {\n Cell::Empty => b'.',\n Cell::Chip1 => b'x',\n Cell::Chip2 => b'o',\n Cell::Possible => b'!',\n };\n\n ans_str.push(next);\n\n if i % 27 == 26 {\n ans_str.push(b'\\n');\n }\n if i % 9 == 8 {\n ans_str.push(b'\\n');\n } else if i % 3 == 2 {\n ans_str.push(b' ');\n }\n }\n\n let ans = String::from_utf8(ans_str).unwrap();\n\n print!(\"{}\", ans);\n}\n\n#[derive(Debug)]\nenum Cell {\n Empty,\n Chip1,\n Chip2,\n Possible,\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a48eb8daee8dd8042323a1bd479dd93c", "src_uid": "8f0fad22f629332868c39969492264d3", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "mod util {\n use std;\n pub fn read_line() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).unwrap();\n String::from(buffer.trim_right())\n }\n #[allow(dead_code)]\n pub fn read_ascii() -> Vec {\n let line = read_line();\n debug_assert!(line.is_ascii());\n line.bytes().collect()\n }\n #[allow(dead_code)]\n pub fn read1() -> i64 {\n read_line().parse::().unwrap()\n }\n #[allow(dead_code)]\n fn read_nums() -> Vec\n where ::Err : std::fmt::Debug {\n read_line().split(' ').map(|x| x.parse::().unwrap()).collect()\n }\n #[allow(dead_code)]\n pub fn read_ints() -> Vec {\n read_nums::()\n }\n #[allow(dead_code)]\n pub fn read_floats() -> Vec {\n read_nums::()\n }\n #[allow(dead_code)]\n pub fn read2() -> (i64, i64) {\n let nums = read_ints();\n (nums[0], nums[1])\n }\n #[allow(dead_code)]\n pub fn read3() -> (i64, i64, i64) {\n let nums = read_ints();\n (nums[0], nums[1], nums[2])\n }\n #[allow(dead_code)]\n pub fn read4() -> (i64, i64, i64, i64) {\n let nums = read_ints();\n (nums[0], nums[1], nums[2], nums[3])\n }\n} // mod util\nuse util::*;\n\ntype Prime = i64;\ntype Power = usize;\ntype PrimePower = (Prime, Power);\ntype Factorization = Vec;\n\nfn primes_below(maxn: usize) -> Vec {\n if maxn <= 2 {\n return vec![];\n }\n let mut is_prime: Vec = vec![true; maxn];\n is_prime[0] = false;\n is_prime[1] = false;\n let mut iterator: i64 = 2;\n while iterator * iterator < maxn as i64 {\n if is_prime[iterator as usize] {\n let mut destroyer: i64 = iterator * iterator;\n while destroyer < maxn as i64 {\n is_prime[destroyer as usize] = false;\n destroyer += iterator;\n }\n }\n iterator += 1;\n }\n is_prime.iter().enumerate().filter(|pair| *pair.1)\n .map(|pair| pair.0 as Prime).collect()\n}\n\nfn naive_factorization(mut number: i64, primes_till_sqrt: &Vec) -> Factorization {\n let mut prime_iter: usize = 0;\n let mut prime: Prime;\n let mut answer: Factorization = vec![];\n while number != 1 {\n if prime_iter >= primes_till_sqrt.len() {\n answer.push((number, 1));\n return answer;\n }\n prime = primes_till_sqrt[prime_iter];\n if number % prime == 0 {\n let mut power: Power = 0;\n while number % prime == 0 {\n power += 1;\n number /= prime;\n }\n answer.push((prime, power));\n }\n prime_iter += 1;\n }\n answer\n}\n\nfn main() {\n let b = read1();\n let v = primes_below(100000);\n let mut ans = 1;\n for (_p, val) in naive_factorization(b, &v) {\n ans *= (val + 1);\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "3aa40435bfb26fa5a51419b2e35cb227", "src_uid": "7fc9e7d7e25ab97d8ebc10ed8ae38fd1", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let mut text = String::new();\n stdin().read_line(&mut text).unwrap();\n let text: Vec<&str> = text.trim().split_whitespace().collect();\n let mut value = 0;\n\n let mut val: Vec = vec![];\n let a = text[0].chars().collect::>();\n let b = text[1].chars().collect::>();\n let mut text1 = String::new();\n for x in &a {\n text1.push(*x);\n let mut text2 = String::new();\n\n for y in &b {\n text2.push(*y);\n val.push(text1.clone() + &text2[..]);\n }\n }\n val.sort();\n println!(\"{}\", val[0]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "9de771fbae7e423b51ec20843662f32e", "src_uid": "aed892f2bda10b6aee10dcb834a63709", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).unwrap();\n\n let parts: Vec<&str> = input.trim().split(' ').collect();\n let mut logins: Vec = vec![];\n\n for i in 1..(parts[0].len()+1) {\n for j in 1..(parts[1].len()+1) {\n let mut login = String::new();\n login.push_str(&parts[0][0..i]);\n login.push_str(&parts[1][0..j]);\n logins.push(login);\n }\n }\n\n logins.sort();\n\n println!(\"{}\", logins[0]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "55536e32b94c0e58bcb428beae217240", "src_uid": "aed892f2bda10b6aee10dcb834a63709", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let mut text = String::new();\n stdin().read_line(&mut text).unwrap();\n let text: Vec<&str> = text.trim().split_whitespace().collect();\n\n let mut val: Vec = vec![];\n let a = text[0].chars().collect::>();\n let b = text[1].chars().collect::>();\n let mut text1 = String::new();\n if a.len() > 1 {\n for x in &a[1..] {\n if x < &b[0] {\n text1.push(*x);\n } else {\n break;\n }\n }\n }\n val.sort();\n println!(\"{}{}{}\", a[0], text1, b[0]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "efc1b631a45f2ce7525bfe0ca866d2a2", "src_uid": "aed892f2bda10b6aee10dcb834a63709", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "pub use __cargo_equip::prelude::*;\r\n\r\nfn main() {\r\n cf_utils::cf_prelude!();\r\n\r\n const MODULUS: u64 = 1_000_000_007;\r\n\r\n for _ in 0..read!() {\r\n let n = read!(u64);\r\n let k = read!(u64);\r\n\r\n let upper = modexp(2, n - 1, MODULUS) - 1;\r\n\r\n let mut result = 1;\r\n\r\n for bit in 0..k {\r\n if n % 2 == 1 {\r\n result *= upper + 2;\r\n result %= MODULUS;\r\n } else {\r\n result *= upper;\r\n result %= MODULUS;\r\n result += modexp(2, n * bit, MODULUS);\r\n result %= MODULUS;\r\n }\r\n }\r\n\r\n outln!(\"{}\", result % MODULUS);\r\n }\r\n}\r\n\r\nfn modexp(mut base: u64, mut exp: u64, modulus: u64) -> u64 {\r\n let mut result = 1;\r\n\r\n while exp > 0 {\r\n if exp & 1 != 0 {\r\n result *= base;\r\n result %= modulus;\r\n }\r\n\r\n exp >>= 1;\r\n base *= base;\r\n base %= modulus;\r\n }\r\n\r\n result\r\n}\r\n\r\n// The following code was expanded by `cargo-equip`.\r\n\r\n/// # Bundled libraries\r\n///\r\n/// - `cf_utils 0.1.0 (git+https://github.com/jakobrs/cf_utils#efb13574168dc8cf0a033c3cc262f744480ed4b2)` licensed under `MIT` as `crate::__cargo_equip::crates::cf_utils`\r\n///\r\n/// # License and Copyright Notices\r\n///\r\n/// - `cf_utils 0.1.0 (git+https://github.com/jakobrs/cf_utils#efb13574168dc8cf0a033c3cc262f744480ed4b2)`\r\n///\r\n/// ```text\r\n/// MIT License\r\n///\r\n/// Copyright (c) 2022 jakobrs\r\n///\r\n/// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n/// of this software and associated documentation files (the \"Software\"), to deal\r\n/// in the Software without restriction, including without limitation the rights\r\n/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n/// copies of the Software, and to permit persons to whom the Software is\r\n/// furnished to do so, subject to the following conditions:\r\n///\r\n/// The above copyright notice and this permission notice shall be included in all\r\n/// copies or substantial portions of the Software.\r\n///\r\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n/// SOFTWARE.\r\n/// ```\r\n#[allow(unused)]\r\nmod __cargo_equip {\r\n pub(crate) mod crates {\r\n pub mod cf_utils {\r\n pub use crate::__cargo_equip::macros::cf_utils::*;\r\n #[macro_export]\r\n macro_rules! /*_build_rest*/__cargo_equip_macro_def_cf_utils__build_rest {\r\n ($n:expr; $words:ident; $($accum:tt)*) => {\r\n $words\r\n .by_ref()\r\n .take($n)\r\n $($accum)*\r\n .collect::>()\r\n }\r\n }\r\n macro_rules!_build_rest{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__build_rest!{$($tt)*})}\r\n\r\n #[macro_export]\r\n macro_rules! /*_parse_rest*/__cargo_equip_macro_def_cf_utils__parse_rest {\r\n (decr; $($rest:tt)*) => {\r\n $crate::__cargo_equip::crates::cf_utils::_build_rest!($($rest)* .map(|x| x - 1))\r\n };\r\n (decr, $($rest:tt)*) => {\r\n $crate::__cargo_equip::crates::cf_utils::_parse_rest!($($rest)* .map(|x| x - 1))\r\n };\r\n ($filter:expr; $($rest:tt)*) => {\r\n $crate::__cargo_equip::crates::cf_utils::_build_rest!($($rest)* .map($filter))\r\n };\r\n ($filter:expr, $($rest:tt)*) => {\r\n $crate::__cargo_equip::crates::cf_utils::_parse_rest!($($rest)* .map($filter))\r\n }\r\n }\r\n macro_rules!_parse_rest{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__parse_rest!{$($tt)*})}\r\n\r\n #[macro_export]\r\n macro_rules! /*_define_read*/__cargo_equip_macro_def_cf_utils__define_read {\r\n ($words:ident, $dollar:tt) => {\r\n #[allow(unused_macros)]\r\n macro_rules! read {\r\n () => {\r\n $words.next().unwrap().parse().unwrap()\r\n };\r\n (raw) => {\r\n $words.next().unwrap()\r\n };\r\n ($t:ty) => {\r\n $words.next().unwrap().parse::<$t>().unwrap()\r\n };\r\n ($t:ty; $n:expr) => {\r\n $crate::__cargo_equip::crates::cf_utils::_build_rest!($n; $words; .map(|s| s.parse::<$t>().unwrap()))\r\n };\r\n ($t:ty, $dollar ($dollar rest:tt)*) => {\r\n $crate::__cargo_equip::crates::cf_utils::_parse_rest!($dollar ($dollar rest)*; $words; .map(|s| s.parse::<$t>().unwrap()))\r\n }\r\n }\r\n };\r\n }\r\n macro_rules!_define_read{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__define_read!{$($tt)*})}\r\n\r\n #[macro_export]\r\n macro_rules! /*_define_out*/__cargo_equip_macro_def_cf_utils__define_out {\r\n ($stdout:ident, $dollar:tt) => {\r\n #[allow(unused_macros)]\r\n macro_rules! out {\r\n ($dollar ($dollar arg:tt)*) => {{\r\n ::std::io::Write::write_fmt(&mut $stdout, format_args!($dollar ($dollar arg)*)).unwrap();\r\n }};\r\n }\r\n\r\n #[allow(unused_macros)]\r\n macro_rules! outln {\r\n () => {{\r\n ::std::io::Write::write_all(&mut $stdout, b\"\\n\").unwrap();\r\n }};\r\n ($dollar ($dollar arg:tt)*) => {{\r\n ::std::io::Write::write_fmt(&mut $stdout, format_args!($dollar ($dollar arg)*)).unwrap();\r\n outln!();\r\n }};\r\n }\r\n }\r\n }\r\n macro_rules!_define_out{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__define_out!{$($tt)*})}\r\n\r\n #[macro_export]\r\n macro_rules! /*_cf_prelude*/__cargo_equip_macro_def_cf_utils__cf_prelude {\r\n () => {\r\n let mut input = String::new();\r\n std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).unwrap();\r\n let mut words = input.split_whitespace();\r\n\r\n let out = ::std::io::stdout();\r\n let mut out = ::std::io::BufWriter::new(out.lock());\r\n\r\n $crate::__cargo_equip::crates::cf_utils::define_read!(words, $);\r\n\r\n $crate::__cargo_equip::crates::cf_utils::define_out!(out, $);\r\n };\r\n }\r\n macro_rules!_cf_prelude{($($tt:tt)*)=>(crate::__cargo_equip_macro_def_cf_utils__cf_prelude!{$($tt)*})}\r\n\r\n pub use crate::__cargo_equip::crates::cf_utils::{\r\n _cf_prelude as cf_prelude, _define_out as define_out, _define_read as define_read,\r\n };\r\n }\r\n }\r\n\r\n pub(crate) mod macros {\r\n pub mod cf_utils {\r\n pub use crate::{\r\n __cargo_equip_macro_def_cf_utils__build_rest as _build_rest,\r\n __cargo_equip_macro_def_cf_utils__cf_prelude as _cf_prelude,\r\n __cargo_equip_macro_def_cf_utils__define_out as _define_out,\r\n __cargo_equip_macro_def_cf_utils__define_read as _define_read,\r\n __cargo_equip_macro_def_cf_utils__parse_rest as _parse_rest,\r\n };\r\n }\r\n }\r\n\r\n pub(crate) mod prelude {\r\n pub use crate::__cargo_equip::crates::*;\r\n }\r\n\r\n mod preludes {\r\n pub mod cf_utils {}\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "0c26cf3ddf470ba681b1177e1b6ab4a2", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub mod pr {\n #[inline(always)]\n #[allow(dead_code)]\n pub fn ln(x: T) {\n print!(\"{}\\n\", x)\n }\n #[inline(always)]\n #[allow(dead_code)]\n pub fn e(x: T) {\n print!(\"{} \", x)\n }\n #[inline(always)]\n #[allow(dead_code)]\n pub fn pb() {\n print!(\" \")\n }\n #[inline(always)]\n #[allow(dead_code)]\n pub fn endl() {\n print!(\"\\n\")\n }\n #[inline(always)]\n #[allow(dead_code)]\n pub fn slice(v: &[T]) {\n for x in v {\n print!(\"{} \", &x);\n }\n print!(\"\\n\")\n }\n}\npub mod algo {\n pub fn calculate_array_inversions(arr: &[T]) -> i64 {\n let (answer, _) = _calculate_array_inversions(arr);\n return answer;\n }\n fn _calculate_array_inversions(\n arr: &[T],\n ) -> (i64, Vec) {\n let n = arr.len();\n match n {\n 0 | 1 => return (0, arr.to_vec()),\n 3..=10 => return _calculate_array_inversions_brute_force(arr),\n _ => (),\n }\n let mid = n / 2;\n let left = &arr[0..mid];\n let right = &arr[mid..];\n let (left_val, left_sorted) = _calculate_array_inversions(left);\n let (right_val, right_sorted) = _calculate_array_inversions(right);\n let (swap_count, vec_sorted) = _merge_sorted_vecs(left_sorted, right_sorted);\n let answer = left_val + right_val + swap_count;\n return (answer, vec_sorted);\n }\n fn _merge_sorted_vecs(\n left: Vec,\n right: Vec,\n ) -> (i64, Vec) {\n assert!(!left.is_empty());\n assert!(!right.is_empty());\n let mut sorted = Vec::with_capacity(left.len() + right.len());\n let mut swap_count = 0;\n let mut lp: usize = 0;\n let mut rp: usize = 0;\n while lp < left.len() && rp < right.len() {\n match left[lp] <= right[rp] {\n true => {\n sorted.push(left[lp]);\n lp += 1;\n }\n false => {\n sorted.push(right[rp]);\n rp += 1;\n let left_remained = left.len() - lp;\n swap_count += left_remained as i64;\n }\n }\n }\n while lp < left.len() {\n sorted.push(left[lp]);\n lp += 1;\n }\n while rp < right.len() {\n sorted.push(right[rp]);\n rp += 1;\n }\n assert_eq!(sorted.len(), left.len() + right.len());\n assert_eq!(left.len(), lp);\n assert_eq!(right.len(), rp);\n return (swap_count, sorted);\n }\n fn _calculate_array_inversions_brute_force(\n arr: &[T],\n ) -> (i64, Vec) {\n let n = arr.len();\n let mut answer = 0;\n for i in 0..n {\n for j in i + 1..n {\n if arr[i] > arr[j] {\n answer += 1;\n }\n }\n }\n let mut v = arr.to_vec();\n v.sort_unstable();\n return (answer, v);\n }\n #[allow(dead_code)]\n pub fn find_max_min_pos(slice: &[T]) -> (T, T, usize, usize) {\n std::assert!(slice.len() > 0);\n let mut max = &slice[0];\n let mut min = &slice[0];\n let mut max_pos: usize = 0;\n let mut min_pos: usize = 0;\n for index in 1..slice.len() {\n if slice[index] < *min {\n min = &slice[index];\n min_pos = index;\n }\n if slice[index] > *max {\n max = &slice[index];\n max_pos = index;\n }\n }\n (*max, *min, max_pos, min_pos)\n }\n}\npub mod nd {\n pub struct Arr {\n _max_n: usize,\n _max_m: usize,\n _data: Vec,\n }\n impl Arr {\n pub fn new(size: (usize, usize), default: T) -> Self {\n let dimensions = 2;\n let container_size = (size.0 + 1) * (size.1 + 1) + 1;\n let mut v = Vec::with_capacity(container_size);\n for _ in 0..container_size {\n v.push(default);\n }\n Arr {\n _max_n: size.0,\n _max_m: size.1,\n _data: v,\n }\n }\n fn _get_pos(&self, n: usize, m: usize) -> usize {\n assert!(n <= self._max_n);\n assert!(m <= self._max_m);\n n * self._max_m + m\n }\n pub fn get(&self, n: usize, m: usize) -> T {\n let p = self._get_pos(n, m);\n self._data[p]\n }\n pub fn set(&mut self, n: usize, m: usize, ans: T) -> T {\n let p = self._get_pos(n, m);\n self._data[p] = ans;\n ans\n }\n }\n impl std::fmt::Debug for Arr {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"Dim={}, ({},{})\\n\", 2, self._max_n, self._max_m);\n for i in 0..self._max_n {\n write!(f, \" [\");\n for j in 0..self._max_m {\n write!(f, \"{}\", self.get(i, j));\n if j + 1 < self._max_m {\n write!(f, \",\");\n }\n }\n write!(f, \"]\\n\");\n }\n write!(f, \"\")\n }\n }\n}\npub mod multi_queue {\n use std::collections::HashMap;\n use std::collections::VecDeque;\n pub struct MultiQueue\n where\n KeyT: Eq + std::hash::Hash,\n {\n _data: HashMap>,\n }\n impl MultiQueue {\n pub fn new() -> Self {\n MultiQueue {\n _data: HashMap::new(),\n }\n }\n pub fn push(&mut self, key: KeyT, value: ValT) {\n let mut entry = self._data.entry(key).or_insert(VecDeque::new());\n entry.push_back(value);\n }\n #[doc = \" Return None if 1. key not found 2. queue consumed\"]\n pub fn pop(&mut self, key: KeyT) -> Option {\n let mut queue = self._data.get_mut(&key);\n if queue.is_none() {\n return None;\n }\n let mut queue = queue.expect(\"Get Queue\");\n queue.pop_front()\n }\n }\n}\npub mod nums {\n #[doc = \" Returns a vector representing the bits.\"]\n #[doc = \" i=63 is the highest bit, i=0 is the lowest bit\"]\n #[doc = \" x = sigma v[i]*(2^i)\"]\n #[doc = \" # Arguments\"]\n #[doc = \"\"]\n #[doc = \" * `x`: A 64-bit number to be represented in bits\"]\n #[doc = \"\"]\n #[doc = \" returns: Vec\"]\n #[doc = \"\"]\n #[allow(dead_code)]\n pub fn represent_into_bits(x: u64) -> Vec {\n let mut result = Vec::with_capacity(64);\n let mut x = x;\n for _ in 0..64 {\n let bit = x & 1;\n let bit = bit as u8;\n result.push(bit);\n x >>= 1;\n }\n assert_eq!(result.len(), 64);\n result\n }\n pub fn represent_from_bits(a: &Vec) -> u64 {\n assert_eq!(a.len(), 64);\n let mut result: u64 = 0;\n for i in 0..64 {\n result += a[i] as u64 * (1u64 << i);\n }\n result\n }\n #[inline(always)]\n #[allow(dead_code)]\n pub fn multi_mod(x: i32, y: i32, modulo: i32) -> i32 {\n let mid: i64 = (x as i64) * (y as i64);\n let mid = mid % (modulo as i64);\n return mid as i32;\n }\n #[allow(dead_code)]\n pub fn pow_mod(base: i32, exp: u32, modulo: i32) -> i32 {\n let mut answer: i64 = 1;\n if exp > 10 {\n let sub_exp = exp / 2;\n let mut p: i64 = pow_mod(base, sub_exp, modulo) as i64;\n p = p as i64 * p as i64 % modulo as i64;\n if exp % 2 == 1 {\n p = p * base as i64 % modulo as i64;\n }\n return p as i32;\n }\n for _ in 0..exp {\n answer *= base as i64;\n answer %= modulo as i64;\n }\n answer as i32\n }\n #[inline(always)]\n #[allow(dead_code)]\n pub fn in_closed_range(left: i32, right: i32, x: i32) -> bool {\n left <= x && x <= right\n }\n #[inline(always)]\n #[allow(dead_code)]\n pub fn in_closed_range_reversible(left: i32, right: i32, x: i32) -> bool {\n match left.cmp(&right) {\n std::cmp::Ordering::Less => in_closed_range(left, right, x),\n std::cmp::Ordering::Equal => x == left,\n std::cmp::Ordering::Greater => in_closed_range(right, left, x),\n }\n }\n pub fn select_lowest_kth_bit(x: u32, b: u32) -> u32 {\n let result = (x >> b) & 1;\n assert!(result == 0 || result == 1);\n result\n }\n #[allow(dead_code)]\n pub fn calc_combination_with_mod(a: i32, b: i32, modulo: i32) -> i32 {\n let mut num: i64 = 1;\n let mut den: i64 = 1;\n for i in 0..b {\n num = num * (a - i) as i64 % modulo as i64;\n den = den * (i + 1) as i64 % modulo as i64;\n }\n let answer = num * pow_mod(den as i32, modulo as u32 - 2, modulo) as i64;\n let answer = answer % modulo as i64;\n answer as i32\n }\n}\npub mod iters {\n pub fn permutation_chars(s: &str) -> Vec> {\n return permutation(s.as_bytes());\n }\n pub fn permutation(s: &[T]) -> Vec> {\n assert!(s.len() > 0);\n let mut possibilities = 1;\n for i in 1..=s.len() {\n possibilities *= i;\n }\n permutation_dfs(s, &vec![false; s.len()])\n }\n fn permutation_dfs(s: &[T], used: &Vec) -> Vec> {\n assert_eq!(s.len(), used.len());\n let mut result_list = Vec::new();\n for pos in 0..s.len() {\n if used[pos] {\n continue;\n }\n let mut new_used = used.clone();\n new_used[pos] = true;\n let select = s[pos];\n let recursive_results = permutation_dfs(s, &new_used);\n if recursive_results.is_empty() {\n let mut r = Vec::with_capacity(s.len());\n r.push(select);\n result_list.push(r);\n } else {\n for v in recursive_results {\n let mut r = v;\n r.push(select);\n result_list.push(r);\n }\n }\n }\n result_list\n }\n}\nuse std::error;\nuse std::fmt;\nuse std::str::FromStr;\n#[non_exhaustive]\n#[derive(Debug, PartialEq)]\npub enum Error {\n MissingMatch,\n MissingClosingBrace,\n UnexpectedValue(u8, Option),\n InvalidUtf8(Vec),\n PartialUtf8(usize, Vec),\n Parse(String, &'static str),\n}\nimpl error::Error for Error {}\nimpl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n use crate::Error::*;\n use std::str::from_utf8;\n match *self {\n InvalidUtf8(ref raw) => write!(f, \"input was not valid utf8: {:?}\", raw),\n Parse(ref s, arg) => write!(f, \"could not parse {} as target type of {}\", s, arg),\n UnexpectedValue(exp, act) => write!(\n f,\n \"found value {:?} not matching the pattern value {}\",\n act.map(|b| b as char),\n exp as char\n ),\n PartialUtf8(n, ref raw) => write!(\n f,\n \"input was only partially valid utf8: \\\"{}\\\" followed by {:?}\",\n from_utf8(&raw[..n]).unwrap(),\n &raw[n..]\n ),\n MissingMatch => write!(f, \"Bad read! format string: did not contain {{}}\"),\n MissingClosingBrace => write!(\n f,\n \"found single open curly brace at the end of the format string\"\n ),\n }\n }\n}\npub fn match_next(expected: u8, iter: &mut dyn Iterator) -> Result<(), Error> {\n let next = iter.next();\n if next != Some(expected) {\n return Err(Error::UnexpectedValue(expected, next));\n }\n Ok(())\n}\npub fn parse_capture(\n name: &'static str,\n next: Option,\n iter: &mut dyn Iterator,\n) -> Result\nwhere\n T: FromStr,\n ::Err: ::std::fmt::Debug,\n{\n static WHITESPACES: &[u8] = b\"\\t\\r\\n \";\n let raw: Vec = match next {\n Some(c) => iter.take_while(|&ch| ch != c).collect(),\n None => iter\n .skip_while(|ch| WHITESPACES.contains(ch))\n .take_while(|ch| !WHITESPACES.contains(ch))\n .collect(),\n };\n match String::from_utf8(raw) {\n Ok(s) => FromStr::from_str(&s).map_err(|_| Error::Parse(s, name)),\n Err(e) => {\n let n = e.utf8_error().valid_up_to();\n let raw = e.into_bytes();\n if n == 0 {\n Err(Error::InvalidUtf8(raw))\n } else {\n Err(Error::PartialUtf8(n, raw))\n }\n }\n }\n}\n#[macro_export]\nmacro_rules ! try_read (() => { $ crate :: try_read ! (\"{}\") } ; ($ text : expr) => { { (|| -> std :: result :: Result < _ , $ crate :: Error > { let __try_read_var__ ; $ crate :: try_scan ! ($ text , __try_read_var__) ; Ok (__try_read_var__) }) () } } ; ($ text : expr , $ input : expr) => { { (|| -> std :: result :: Result < _ , $ crate :: Error > { let __try_read_var__ ; $ crate :: try_scan ! ($ input => $ text , __try_read_var__) ; Ok (__try_read_var__) }) () } } ;) ;\n#[macro_export]\nmacro_rules ! try_scan (($ pattern : expr , $ ($ arg : expr) ,*) => { use :: std :: io :: Read ; $ crate :: try_scan ! (:: std :: io :: stdin () . bytes () . map (std :: result :: Result :: unwrap) => $ pattern , $ ($ arg) ,*) ; } ; ($ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { $ crate :: try_scan ! (@ impl question_mark ; $ input => $ pattern , $ ($ arg) ,*) } } ; (@ question_mark : $ ($ e : tt) +) => { { ($ ($ e) +) ? } } ; (@ unwrap : $ ($ e : tt) +) => { { ($ ($ e) +) . unwrap () } } ; (@ impl $ action : tt ; $ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { #! [allow (clippy :: try_err)] use $ crate :: { Error , match_next , parse_capture } ; let pattern : &'static str = $ pattern ; let stdin : & mut Iterator < Item = u8 > = & mut ($ input) ; let mut pattern = pattern . bytes () ; $ ($ arg = loop { match $ crate :: try_scan ! (@$ action : pattern . next () . ok_or (Error :: MissingMatch)) { b'{' => match $ crate :: try_scan ! (@$ action : pattern . next () . ok_or (Error :: MissingClosingBrace)) { b'{' => $ crate :: try_scan ! (@$ action : match_next (b'{' , stdin)) , b'}' => break $ crate :: try_scan ! (@$ action : parse_capture (stringify ! ($ arg) , pattern . next () , stdin)) , _ => return $ crate :: try_scan ! (@$ action : Err (Error :: MissingClosingBrace)) , } , c => $ crate :: try_scan ! (@$ action : match_next (c , stdin)) , } } ;) * for c in pattern { $ crate :: try_scan ! (@$ action : match_next (c , stdin)) } format_args ! ($ pattern , $ ($ arg) ,*) ; } } ;) ;\n#[doc = \" All text input is handled through this macro\"]\n#[macro_export]\nmacro_rules ! read (($ ($ arg : tt) *) => { $ crate :: try_read ! ($ ($ arg) *) . unwrap () } ;) ;\n#[doc = \" This macro allows to pass several variables so multiple values can be read\"]\n#[macro_export]\nmacro_rules ! scan (($ text : expr , $ ($ arg : expr) ,*) => { use :: std :: io :: Read ; $ crate :: scan ! (:: std :: io :: stdin () . bytes () . map (std :: result :: Result :: unwrap) => $ text , $ ($ arg) ,*) ; } ; ($ input : expr => $ pattern : expr , $ ($ arg : expr) ,*) => { { $ crate :: try_scan ! (@ impl unwrap ; $ input => $ pattern , $ ($ arg) ,*) } } ;) ;\n#[inline(always)]\n#[allow(dead_code)]\npub fn read_ivec(n: usize) -> Vec {\n let mut vec = Vec::with_capacity(n);\n for _ in 0..n {\n let x: i32 = read!();\n vec.push(x);\n }\n return vec;\n}\n#[inline]\n#[allow(dead_code)]\npub fn read_ived_1(n: usize) -> Vec {\n let mut vec = Vec::with_capacity(n + 1);\n vec.push(0);\n for _ in 0..n {\n let x: i32 = read!();\n vec.push(x);\n }\n return vec;\n}\n#[inline(always)]\n#[allow(dead_code)]\npub fn read_uvec(n: usize) -> Vec {\n let mut vec = Vec::with_capacity(n);\n for _ in 0..n {\n let x: u32 = read!();\n vec.push(x);\n }\n return vec;\n}\nconst MODULO: i32 = 1_000_000_007;\nfn solve() -> Option {\n let n = read!();\n let k = read!();\n if k == 0 {\n return Some(1);\n }\n if n == 1 {\n let ans = nums::pow_mod(2, k, MODULO);\n return Some(ans as i64);\n }\n let free_select_01 = nums::pow_mod(2, n, MODULO);\n let mut factorial = vec![1i64; n as usize + 1];\n for i in 1usize..=(n as usize) {\n factorial[i] = factorial[i - 1] * i as i64;\n factorial[i] %= MODULO as i64;\n }\n let mut greater_or_equal_select_01: i64 = 0;\n for selected_1 in (0..=n as usize).step_by(2) {\n let a = factorial[n as usize];\n let b = factorial[n as usize - selected_1];\n let b = nums::pow_mod(b as i32, MODULO as u32 - 2, MODULO);\n let b2 = factorial[selected_1];\n let b2 = nums::pow_mod(b2 as i32, MODULO as u32 - 2, MODULO);\n let c = a * b as i64 % MODULO as i64 * b2 as i64 % MODULO as i64;\n greater_or_equal_select_01 += c as i64;\n greater_or_equal_select_01 %= MODULO as i64;\n }\n if n % 2 != 0 {\n greater_or_equal_select_01 += 1;\n greater_or_equal_select_01 %= MODULO as i64;\n }\n let mut answer: i64 = greater_or_equal_select_01 as i64;\n let mut prev: i64 = 0;\n let mut pow_bit = 1 as i64;\n for bit in 1..k {\n prev = answer;\n answer = 0;\n let x = greater_or_equal_select_01 as i64 * prev % MODULO as i64;\n answer += x as i64;\n answer %= MODULO as i64;\n if n % 2 == 0 {\n pow_bit *= free_select_01 as i64;\n pow_bit %= MODULO as i64;\n answer += pow_bit;\n answer %= MODULO as i64;\n answer += MODULO as i64;\n answer -= prev;\n answer %= MODULO as i64;\n }\n }\n Some(answer)\n}\nfn calc(\n n: u32,\n bit: u32,\n free_select_01: i32,\n greater_or_equal_select_01: i32,\n modulo: i32,\n) -> i64 {\n let mut answer: i64 = 0;\n if bit == 0 {\n return greater_or_equal_select_01 as i64;\n }\n if n % 2 == 0 {\n answer += nums::pow_mod(free_select_01, bit, modulo) as i64;\n }\n let x = greater_or_equal_select_01 as i64\n * calc(\n n,\n bit - 1,\n free_select_01,\n greater_or_equal_select_01,\n modulo,\n )\n % MODULO as i64;\n answer += x as i64;\n answer %= MODULO as i64;\n answer\n}\nfn main() {\n let testcases: i32 = read!();\n for _ in 0..testcases {\n solve_and_print();\n }\n}\n#[inline]\nfn solve_and_print() {\n let answer = solve();\n match answer {\n None => (),\n _ => pr::ln(answer.unwrap()),\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "f84fb2cfdcbbddf0a0a82da00f2307f0", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\n#[allow(unused_imports)]use std::{io::*,collections::*,fmt::Debug,str::{self,*},cmp::*,ops::{self,*},iter::{self,*}};\nmacro_rules!rp{{[$c:expr]$($s:tt)+}=>(for _ in 0..$c{$($s)+})}\nmacro_rules!l{\n\t($($v:ident),+:$t:ty=$e:expr)=>{$(let$v:$t=$e;)+};(mut $($v:ident),+ =$e:expr)=>{$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr)=>{$(let mut$v:$t=$e;)+};($($v:ident),+ =$e:expr)=>{$(let$v=$e;)+};}\nmacro_rules!v{\n\t($(:$t:ty)?=$e:expr)=>{$e$(as$t)?};([$d:expr]$(:$t:ty)?)=>{Vec::$(<$t>::)?with_capacity($d)};\n\t([]$(:$t:ty)?)=>{Vec::$(<$t>::)?new()};([$d:expr]$($s:tt)+)=>{vec![v!($($s)+);$d]};}\nfn rio()->(Reader,BufWriter){(Reader::new(),BufWriter::new(stdout()))}\nstruct Reader{buf:Vec,pos:usize,x:*mut Stdin,q:StdinLock<'static>}//'\n#[allow(dead_code)]impl Reader{\n\tfn new()->Self{let x=Box::into_raw(Box::new(stdin()));let q=unsafe{&*x}.lock();Self{x,q,buf:v!([]),pos:0}}\n\tfn next_line(&mut self)->bool{self.buf.clear();self.pos=0;self.q.read_until(b'\\n',&mut self.buf).unwrap_or(0)>0}\n\tfn byte(&mut self)->Option{\n\t\tif self.pos==self.buf.len(){if!self.next_line(){return None;}}self.pos+=1;Some(self.buf[self.pos-1])}\n\tfn vb(&mut self)->Vec{let mut s=v!([10]);let mut f=false;while let Some(c)=self.byte(){\n\t\tif!c.is_ascii_whitespace(){s.push(c);f=true;}else if f{break;}}s}\n\tfn p(&mut self)->T where T::Err:Debug{let w=self.vb();str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()}\n\tfn u(&mut self) -> usize { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n}impl Drop for Reader{fn drop(&mut self){unsafe{Box::from_raw(self.x)};}}\n//----------}}}\n\n// Field (mod prime) {{{\nmod field {\n\tuse std::ops::*;\n\t#[allow(dead_code)] pub const Z0: Field = Field(0);\n\t#[allow(dead_code)] pub const Z1: Field = Field(1);\n\tconst P5: i32 = 1_000_000_007;\n\tconst P6: i64 = P5 as i64;\n\t#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(i32);\n\t#[allow(dead_code)] impl Field {\n\t\tpub fn new>(a: T) -> Self { Self(Self::cv(a)) }\n\t\tpub unsafe fn new_unchecked(a: i32) -> Self { Self(a) }\n\t\tfn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n\t\tfn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n\t\tfn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n\t\tpub fn inv(self) -> Self { self.pow(P5-2) }\n\t\tpub fn pow>(self, b: T) -> Self {\n\t\t\tlet b = b.into(); if b == 0 { Self(1) } else {\n\t\t\t\tlet mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res\n\t\t\t}\n\t\t}\n\t}\n\timpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\n\timpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\n\timpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\n\timpl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}\n\timpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\n\timpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\n\timpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\n\timpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\n\timpl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }\n\tuse std::fmt::{Display, Formatter, Result};\n\timpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n}\n#[allow(unused_imports)] use field::{Field, Field as Z, Z0, Z1};\n//}}}\n\nfn main() {\n\tlet (mut rin,mut rout) = rio();\n\tlet z2 = Z::new(2);\n\n\trp!{[rin.u()]\n\t\tlet n = rin.l();\n\t\tlet k = rin.u();\n\t\tlet (c10,c) = if n % 2 == 0 {\n\t\t\t(Z1, z2.pow(n-1) - Z1)\n\t\t} else {\n\t\t\t(Z0, z2.pow(n-1) + Z1)\n\t\t};\n\t\tl!(mut x,p = Z1);\n\t\tlet p2 = z2.pow(n);\n\t\trp!{[k]\n\t\t\tx = c10 * p + c * x;\n\t\t\tp *= p2;\n\t\t}\n\t\twriteln!(rout, \"{}\", x).unwrap();\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "08c9d9b91b761bebee7f76bfc9ad781d", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code,unused_imports)]\n#[rustfmt::skip] mod prefix_sum {use std::fmt::{self, Debug, Formatter};use std::ops::Add;#[derive(Clone)] pub struct PrefixOp where I: Iterator, F: Fn(T, T) -> T, { iter: I, acc: Option, f: F, } impl Iterator for PrefixOp where I: Iterator, F: Fn(T, T) -> T, T: Clone, { type Item = T;fn next(&mut self) -> Option { let next = self.iter.next();if let Some(next) = next { if let Some(acc) = self.acc.take() { self.acc = Some((self.f)(acc, next));} else { self.acc = Some(next);} Some(self.acc.clone().unwrap()) } else { None } } } impl Debug for PrefixOp where I: Iterator + Debug, F: Fn(T, T) -> T, T: Debug, { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct(\"PrefixOp\") .field(\"acc\", &self.acc) .field(\"iter\", &self.iter) .finish() } } pub trait CreatePrefixOps: Iterator + Sized where F: Fn(T, T) -> T, { fn prefix_ops(self, op: F) -> PrefixOp;} impl CreatePrefixOps for I where I: Iterator, F: Fn(T, T) -> T, { fn prefix_ops(self, op: F) -> PrefixOp { PrefixOp { iter: self, acc: None, f: op, } } } macro_rules! prefix_op_specialisation { ($trait_name:ident, $fn_name:ident, $fn:expr, $($bound_token:tt)+) => { pub trait $trait_name: Iterator + Sized where $($bound_token)+ { fn $fn_name(self) -> PrefixOp T>;} impl $trait_name for I where I: Iterator, $($bound_token)+ { fn $fn_name(self) -> PrefixOp T> { PrefixOp { iter: self, acc: None, f: $fn, } } } };} prefix_op_specialisation!(CreatePrefixSums, prefix_sums, T::add, T: Add);prefix_op_specialisation!(CreatePrefixMax, prefix_max, T::max, T: Ord);prefix_op_specialisation!(CreatePrefixMin, prefix_min, T::min, T: Ord);}\n#[rustfmt::skip] mod scanner {use std::io::{stdin, BufReader, Bytes, Error as IoError, Read, Stdin};use std::str::{self, FromStr, Utf8Error};#[derive(Debug)] pub struct Scanner { bytes: Bytes>, buf: Vec, } #[derive(Debug)] pub enum ScanError { Io(IoError), Parse(T::Err, String), NonUtf8(Utf8Error, Vec), } impl Scanner { pub fn stdin() -> Self { Self::new(stdin()) } } impl Scanner { pub fn new(reader: R) -> Self { Self { bytes: BufReader::new(reader).bytes(), buf: Vec::new(), } } #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Result> { assert!(self.buf.is_empty());for b in &mut self.bytes { let b = b.map_err(ScanError::Io)?;if b.is_ascii_whitespace() { if self.buf.is_empty() { continue;} else { break;} } else { self.buf.push(b);} } match str::from_utf8(&self.buf) { Err(err) => Err(ScanError::NonUtf8(err, std::mem::take(&mut self.buf))), Ok(s) => { let ret = s.parse().map_err(|err| ScanError::Parse(err, s.to_owned()));self.buf.clear();ret } } } } #[macro_export] macro_rules! scan { ($scanner:expr) => { $scanner.next().expect(\"failed to read token\") };($scanner:expr, $type:ty) => { $scanner .next::<$type>() .expect(concat!(\"failed to read token of type \", stringify!($type))) };($scanner:expr, $type:ty; $n:expr) => { (0..$n).map(|_| scan!($scanner)).collect::>() };($scanner:expr, $($type:ty),+) => { ($( scan!($scanner, $type), )+) };} }\n#[rustfmt::skip] mod writer {use std::fmt::Display;use std::io::{stdout, BufWriter, Error as IoError, Stdout, Write};#[derive(Debug)] pub struct Writer { writer: BufWriter, } impl Writer { pub fn stdout() -> Self { Self::new(stdout()) } } impl Writer { pub fn new(writer: W) -> Self { Self { writer: BufWriter::new(writer), } } pub fn write>(&mut self, val: T) -> Result<(), IoError> { val.write_to(&mut self.writer) } pub fn flush(&mut self) -> Result<(), IoError> { self.writer.flush() } } pub trait Writable { fn write_to(self, w: &mut W) -> Result<(), IoError>;} #[non_exhaustive] pub struct Single;impl Writable for T { fn write_to(self, w: &mut W) -> Result<(), IoError> { writeln!(w, \"{}\", self) } } #[non_exhaustive] pub struct Many;impl Writable for I where I: Iterator, I::Item: Display, { fn write_to(mut self, w: &mut W) -> Result<(), IoError> { if let Some(x) = self.next() { write!(w, \"{}\", x)?;} else { return Ok(());} for x in self { write!(w, \" {}\", x)?;} writeln!(w) } } #[non_exhaustive] pub struct Array;impl Writable for &[T] { fn write_to(self, w: &mut W) -> Result<(), IoError> { self.iter().write_to(w) } } }\n#[rustfmt::skip] mod util { pub trait IntoVec { fn into_vec(self) -> Vec;} #[non_exhaustive] pub struct Owned;impl IntoVec for I where I: Iterator, { fn into_vec(self) -> Vec { self.collect() } } #[non_exhaustive] pub struct Reference;impl<'a, I, T> IntoVec for I where I: Iterator, T: Clone + 'a, { fn into_vec(self) -> Vec { self.cloned().collect() } } pub trait Argmax { fn argmax(self) -> Option;} impl Argmax for I where I: Iterator, I::Item: Ord, { fn argmax(self) -> Option { self.fold((0, None), |(i, mx), next| { if let Some((mx_i, mx_v)) = mx { if next.gt(&mx_v) { (i + 1, Some((i, next))) } else { (i + 1, Some((mx_i, mx_v))) } } else { (i + 1, Some((i, next))) } }) .1 .map(|x| x.0) } } pub trait Sorted { fn sorted(self) -> Self;} impl Sorted for Vec where T: Ord, { fn sorted(mut self) -> Self { self.sort();self } } pub trait Choose { fn choose(self, a: T, b: T) -> T;} impl Choose for bool { fn choose(self, a: T, b: T) -> T { if self { a } else { b } } } }\n\nuse prefix_sum::{CreatePrefixOps, CreatePrefixSums, CreatePrefixMax, CreatePrefixMin};\nuse scanner::Scanner;\nuse writer::Writer;\nuse util::{IntoVec, Argmax, Sorted, Choose};\n\nconst MOD: i64 = 1_000_000_007;\nfn main() {\n let mut sc = Scanner::stdin();\n let mut wr = Writer::stdout();\n for _ in 0..scan!(sc, usize) {\n let (n, k) = scan!(sc, i64, i64);\n\n if n % 2 == 0 {\n let mut total = 0;\n let a = modexp(2, n - 1) - 1;\n let b = modexp(2, n);\n for i in 0..k {\n total = (total + modexp(a, i) * modexp(b, k - i - 1)) % MOD;\n }\n total = (total + modexp(a, k)) % MOD;\n wr.write(total).unwrap();\n } else {\n let c = (modexp(2, n - 1) - 1 + 2 * (n % 2)) % MOD;\n let total = modexp(c, k);\n wr.write(total).unwrap();\n }\n }\n}\n\nconst fn modexp(a: i64, b: i64) -> i64 {\n if b == 0 { 1 }\n else if b % 2 == 0 { modexp((a * a) % MOD, b / 2) }\n else { (modexp((a * a) % MOD, b / 2) * a) % MOD}\n}\n\nconst fn modinv(a: i64) -> i64 {\n modexp(a, MOD - 2)\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "35f62be8833f0d3f5851a2d62e595040", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\r\n date : 2021 / 4 / 7\r\n author : quickn (quickn.tech)\r\n email : quickwshell@gmail.com\r\n*/\r\n\r\nuse std::io::{self, BufWriter, Write};\r\n\r\nmod scanner {\r\n use std::{io, str};\r\n /* https://github.com/EbTech/rust-algorithms */\r\n\r\n /// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\r\n /// **REQUIRES** Rust 1.34 or higher\r\n pub struct UnsafeScanner {\r\n reader: R,\r\n buf_str: Vec,\r\n buf_iter: str::SplitAsciiWhitespace<'static>,\r\n }\r\n\r\n impl UnsafeScanner {\r\n pub fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buf_str: Vec::new(),\r\n buf_iter: \"\".split_ascii_whitespace(),\r\n }\r\n }\r\n\r\n /// This function should be marked unsafe, but noone has time for that in a\r\n /// programming contest. Use at your own risk!\r\n pub fn token(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buf_iter.next() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n self.buf_str.clear();\r\n self.reader\r\n .read_until(b'\\n', &mut self.buf_str)\r\n .expect(\"Failed read\");\r\n self.buf_iter = unsafe {\r\n let slice = str::from_utf8_unchecked(&self.buf_str);\r\n std::mem::transmute(slice.split_ascii_whitespace())\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nuse std::cmp::{min, max};\r\n\r\nfn s2vec(s: String) -> Vec {\r\n s.chars().collect()\r\n}\r\n\r\nconst MOD: i64 = 1000000007;\r\n\r\nfn pow_mod(a: i64, x: i64) -> i64 {\r\n let (mut a_t, mut x_t, mut r) = (a, x, 1);\r\n while x_t > 0 {\r\n if x_t % 2 == 1 {\r\n r *= a_t;\r\n r %= MOD;\r\n }\r\n a_t *= a_t;\r\n a_t %= MOD;\r\n x_t /= 2;\r\n }\r\n r\r\n}\r\n\r\nfn main() {\r\n let (stdin, stdout) = (io::stdin(), io::stdout());\r\n let (mut scan, mut sout) = (\r\n scanner::UnsafeScanner::new(stdin.lock()),\r\n BufWriter::new(stdout.lock()),\r\n );\r\n let t: usize = scan.token();\r\n for _case in 0..t {\r\n let (n, k): (usize, usize) = (scan.token(), scan.token());\r\n if k > 0 {\r\n let mut dp: Vec> = vec![vec![0;2];k+1];\r\n dp[1][0] = pow_mod(2, (n-1) as i64) - if n % 2 == 0 { 1 } else { 0 };\r\n dp[1][1] = 1;\r\n for i in 2..=k {\r\n dp[i][0] = (((dp[i-1][0] + dp[i-1][1])%MOD)*(pow_mod(2, (n-1) as i64) - if n % 2 == 0 { 1 } else { 0 }))%MOD;\r\n if n % 2 == 0 {\r\n dp[i][1] = pow_mod(2, (n as i64)*((i-1) as i64));\r\n } else {\r\n dp[i][1] = (dp[i-1][1] + dp[i-1][0])%MOD;\r\n }\r\n }\r\n writeln!(sout, \"{}\", (dp[k][0] + dp[k][1])%MOD).ok();\r\n } else {\r\n writeln!(sout, \"1\").ok();\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "e6fb5e784cd41b649183c1bc94fa1a71", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case)]\n\nuse std::io::{self, prelude::*};\n\nfn solve(scn: &mut Scanner, wrt: &mut W) {\n let MOD: u64 = 1000000000+7;\n\n let N = scn.token::();\n let K = scn.token();\n\n let pw = |b: u64, mut a: u64| {\n let mut res = 1;\n let mut p = b;\n while a > 0 {\n if a & 1 == 1 {\n res = (res * p) % MOD;\n }\n p = (p*p) % MOD;\n a >>= 1;\n }\n res\n };\n\n let mut ans = 0;\n let mut dw = 1;\n\n for i in 0..K {\n if N & 1 == 0 {\n //auto win here and n even\n ans = (ans + ((dw * pw(2,(K-i-1)*N)) % MOD)) % MOD;\n dw = (dw * (pw(2, N-1) - 1)) % MOD;\n } else {\n //n odd\n dw = (dw * (pw(2, N-1) + 1) % MOD) % MOD;\n }\n }\n\n ans = (ans + dw) % MOD;\n\n writeln!(wrt, \"{}\", ans).unwrap();\n}\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let mut reader = Scanner::new(stdin.lock());\n let mut writer = io::BufWriter::new(stdout.lock());\n\n let T = reader.token::();\n //let T = 1;\n for _ in 0..T {\n solve(&mut reader, &mut writer);\n }\n}\n\npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace(),\n }\n }\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace())\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "2e5bed45967613b72d96b33b6a525698", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{io, io::prelude::*, str};\n\nstruct Scanner {\n reader: R,\n buffer: Vec,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n fn t(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nuse std::ops;\n\n#[derive(Copy, Clone)]\nstruct ModGroup {\n val: usize,\n}\nimpl ModGroup {\n const MOD: usize = 1000000007;\n const MOD64: i64 = Self::MOD as i64;\n\n fn new(v: usize) -> Self {\n Self { val: v }\n }\n\n fn from_usize(v: usize) -> Self {\n Self { val: v % Self::MOD }\n }\n\n fn from_i64(v: i64) -> Self {\n Self {\n val: (v % Self::MOD64) as usize,\n }\n }\n\n fn pow(self, mut p: usize) -> Self {\n let mut base = self;\n let mut res = Self::new(1);\n while p > 0 {\n if p % 2 > 0 {\n res = res * base;\n }\n base = base * base;\n p /= 2;\n }\n\n res\n }\n\n fn inv(self) -> Self {\n self.pow(Self::MOD - 2)\n }\n}\n\nimpl ops::Add for ModGroup {\n type Output = Self;\n\n fn add(self, other: usize) -> Self {\n Self::from_usize(self.val + other)\n }\n}\nimpl ops::Add for ModGroup {\n type Output = Self;\n\n fn add(self, other: Self) -> Self {\n self + other.val\n }\n}\nimpl ops::Sub for ModGroup {\n type Output = Self;\n\n fn sub(self, other: usize) -> Self {\n Self::new(if self.val > other {\n self.val - other\n } else {\n self.val + Self::MOD - other\n })\n }\n}\nimpl ops::Sub for ModGroup {\n type Output = Self;\n\n fn sub(self, other: Self) -> Self {\n self - other.val\n }\n}\nimpl ops::Mul for ModGroup {\n type Output = Self;\n\n fn mul(self, other: usize) -> Self {\n Self::from_i64(self.val as i64 * other as i64)\n }\n}\nimpl ops::Mul for ModGroup {\n type Output = Self;\n\n fn mul(self, other: Self) -> Self {\n self * other.val\n }\n}\nimpl ops::Div for ModGroup {\n type Output = Self;\n\n fn div(self, other: usize) -> Self {\n self * Self::new(other).inv()\n }\n}\nimpl ops::Div for ModGroup {\n type Output = Self;\n\n fn div(self, other: Self) -> Self {\n self * other.inv()\n }\n}\n\nfn main() -> io::Result<()> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout);\n\n const N: usize = 200002;\n\n let pow2_mod = {\n let mut p = vec![ModGroup::new(1); N];\n for i in 1..N {\n p[i] = p[i - 1] * 2;\n }\n p\n };\n let fact_mod = {\n let mut f = vec![ModGroup::new(1); N];\n for i in 1..N {\n f[i] = f[i - 1] * i;\n }\n f\n };\n\n let bin_coef = |n: usize, k: usize| fact_mod[n] / (fact_mod[k] * fact_mod[n - k]);\n\n let tn: usize = scan.t();\n for _ in 0..tn {\n let (n, k): (usize, usize) = (scan.t(), scan.t());\n\n let pow2n_mod = {\n let mut p = vec![ModGroup::new(1); k];\n for i in 1..k {\n p[i] = pow2_mod[i].pow(n);\n }\n p\n };\n\n let gt_cnt = if n % 2 > 0 {\n ModGroup::new(0)\n } else {\n ModGroup::new(1)\n };\n let eq_cnt = {\n let mut res = ModGroup::new(1);\n if n % 2 > 0 {\n res = res + 1;\n }\n\n let mut m = 2;\n while m < n {\n res = res + bin_coef(n, m);\n m += 2;\n }\n\n res\n };\n let mut sum_eq_cnt = ModGroup::new(1);\n let mut res = ModGroup::new(0);\n for i in 0..k {\n res = res + gt_cnt * sum_eq_cnt * pow2n_mod[k - i - 1];\n sum_eq_cnt = sum_eq_cnt * eq_cnt;\n }\n\n res = res + sum_eq_cnt;\n writeln!(out, \"{}\", res.val)?;\n }\n\n io::Result::Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "4aba9b5815321f9e2254a6ed15540ff2", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\r\n#![allow(unused_imports)]\r\n#![allow(non_upper_case_globals)]\r\n#![allow(non_snake_case)]\r\n#![allow(unused_mut)]\r\n#![allow(unused_variables)]\r\n#![allow(dead_code)]\r\n\r\ntype Vec2 = Vec>;\r\ntype Vec3 = Vec>>;\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! invec {\r\n ( $ t : ty ) => {{\r\n let mut s = String::new();\r\n match std::io::stdin().read_line(&mut s) {\r\n Ok(0) => Vec::<$t>::new(),\r\n Ok(n) => s\r\n .trim()\r\n .split_whitespace()\r\n .map(|s| s.parse::<$t>().unwrap())\r\n .collect::>(),\r\n Err(_) => Vec::<$t>::new(),\r\n }\r\n }};\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! get {\r\n ($t:ty) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.trim().parse::<$t>().unwrap()\r\n }\r\n };\r\n ($($t:ty),*) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n let mut iter = line.split_whitespace();\r\n (\r\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\r\n )\r\n }\r\n };\r\n ($t:ty; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($t)\r\n ).collect::>()\r\n };\r\n ($($t:ty),*; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($($t),*)\r\n ).collect::>()\r\n };\r\n ($t:ty ;;) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.split_whitespace()\r\n .map(|t| t.parse::<$t>().unwrap())\r\n .collect::>()\r\n }\r\n };\r\n ($t:ty ;; $n:expr) => {\r\n (0..$n).map(|_| get!($t ;;)).collect::>()\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let mut s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\r\n let mut $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n\r\n ($next:expr, [$t:tt]) => {\r\n {\r\n let len = read_value!($next, usize);\r\n (0..len).map(|_| read_value!($next, $t)).collect::>()\r\n }\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\n#[cfg(debug_assertions)]\r\nmacro_rules! mydbg {\r\n //($arg:expr) => (dbg!($arg))\r\n //($arg:expr) => (println!(\"{:?}\",$arg));\r\n ($($a:expr),*) => {\r\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\r\n }\r\n}\r\n#[cfg(not(debug_assertions))]\r\nmacro_rules! mydbg {\r\n ($($arg:expr),*) => {};\r\n}\r\n\r\nmacro_rules! echo {\r\n ($($a:expr),*) => {\r\n $(println!(\"{}\",$a))*\r\n }\r\n}\r\n\r\nuse std::cmp::*;\r\nuse std::collections::*;\r\nuse std::ops::{Add, Div, Mul, Rem, Sub};\r\n\r\ntrait SafeRangeContain {\r\n fn safe_contains(&self, x: i64) -> bool;\r\n}\r\n\r\nimpl SafeRangeContain for std::ops::Range {\r\n fn safe_contains(&self, x: i64) -> bool {\r\n if x < 0 {\r\n return false;\r\n }\r\n return self.contains(&(x as usize));\r\n }\r\n}\r\n\r\n#[allow(dead_code)]\r\nstatic INF_I64: i64 = i64::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_I32: i32 = i32::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_USIZE: usize = usize::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic M_O_D: usize = 1000000007;\r\n#[allow(dead_code)]\r\nstatic PAI: f64 = 3.1415926535897932;\r\n\r\ntrait IteratorExt: Iterator {\r\n fn toVec(self) -> Vec;\r\n}\r\n\r\nimpl IteratorExt for T {\r\n fn toVec(self) -> Vec {\r\n self.collect()\r\n }\r\n}\r\n\r\ntrait CharExt {\r\n fn toNum(&self) -> usize;\r\n fn toAlphabetIndex(&self) -> usize;\r\n fn toNumIndex(&self) -> usize;\r\n}\r\nimpl CharExt for char {\r\n fn toNum(&self) -> usize {\r\n return *self as usize;\r\n }\r\n fn toAlphabetIndex(&self) -> usize {\r\n return self.toNum() - 'a' as usize;\r\n }\r\n fn toNumIndex(&self) -> usize {\r\n return self.toNum() - '0' as usize;\r\n }\r\n}\r\n\r\ntrait VectorExt {\r\n fn joinToString(&self, s: &str) -> String;\r\n}\r\nimpl VectorExt for Vec {\r\n fn joinToString(&self, s: &str) -> String {\r\n return self\r\n .iter()\r\n .map(|x| x.to_string())\r\n .collect::>()\r\n .join(s);\r\n }\r\n}\r\n\r\ntrait StringExt {\r\n fn get_reverse(&self) -> String;\r\n}\r\nimpl StringExt for String {\r\n fn get_reverse(&self) -> String {\r\n self.chars().rev().collect::()\r\n }\r\n}\r\n\r\ntrait UsizeExt {\r\n fn pow(&self, n: usize) -> usize;\r\n}\r\nimpl UsizeExt for usize {\r\n fn pow(&self, n: usize) -> usize {\r\n return ((*self as u64).pow(n as u32)) as usize;\r\n }\r\n}\r\n\r\n//https://github.com/rust-lang-ja/ac-library-rs\r\n\r\npub mod internal_math {\r\n // remove this after dependencies has been added\r\n #![allow(dead_code)]\r\n use std::mem::swap;\r\n\r\n /// # Arguments\r\n /// * `m` `1 <= m`\r\n ///\r\n /// # Returns\r\n /// x mod m\r\n /* const */\r\n pub(crate) fn safe_mod(mut x: i64, m: i64) -> i64 {\r\n x %= m;\r\n if x < 0 {\r\n x += m;\r\n }\r\n x\r\n }\r\n\r\n /// Fast modular by barrett reduction\r\n /// Reference: https://en.wikipedia.org/wiki/Barrett_reduction\r\n /// NOTE: reconsider after Ice Lake\r\n pub(crate) struct Barrett {\r\n pub(crate) _m: u32,\r\n pub(crate) im: u64,\r\n }\r\n\r\n impl Barrett {\r\n /// # Arguments\r\n /// * `m` `1 <= m`\r\n /// (Note: `m <= 2^31` should also hold, which is undocumented in the original library.\r\n /// See the [pull reqeust commment](https://github.com/rust-lang-ja/ac-library-rs/pull/3#discussion_r484661007)\r\n /// for more details.)\r\n pub(crate) fn new(m: u32) -> Barrett {\r\n Barrett {\r\n _m: m,\r\n im: (-1i64 as u64 / m as u64).wrapping_add(1),\r\n }\r\n }\r\n\r\n /// # Returns\r\n /// `m`\r\n pub(crate) fn umod(&self) -> u32 {\r\n self._m\r\n }\r\n\r\n /// # Parameters\r\n /// * `a` `0 <= a < m`\r\n /// * `b` `0 <= b < m`\r\n ///\r\n /// # Returns\r\n /// a * b % m\r\n #[allow(clippy::many_single_char_names)]\r\n pub(crate) fn mul(&self, a: u32, b: u32) -> u32 {\r\n mul_mod(a, b, self._m, self.im)\r\n }\r\n }\r\n\r\n /// Calculates `a * b % m`.\r\n ///\r\n /// * `a` `0 <= a < m`\r\n /// * `b` `0 <= b < m`\r\n /// * `m` `1 <= m <= 2^31`\r\n /// * `im` = ceil(2^64 / `m`)\r\n #[allow(clippy::many_single_char_names)]\r\n pub(crate) fn mul_mod(a: u32, b: u32, m: u32, im: u64) -> u32 {\r\n // [1] m = 1\r\n // a = b = im = 0, so okay\r\n\r\n // [2] m >= 2\r\n // im = ceil(2^64 / m)\r\n // -> im * m = 2^64 + r (0 <= r < m)\r\n // let z = a*b = c*m + d (0 <= c, d < m)\r\n // a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im\r\n // c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2\r\n // ((ab * im) >> 64) == c or c + 1\r\n let mut z = a as u64;\r\n z *= b as u64;\r\n let x = (((z as u128) * (im as u128)) >> 64) as u64;\r\n let mut v = z.wrapping_sub(x.wrapping_mul(m as u64)) as u32;\r\n if m <= v {\r\n v = v.wrapping_add(m);\r\n }\r\n v\r\n }\r\n\r\n /// # Parameters\r\n /// * `n` `0 <= n`\r\n /// * `m` `1 <= m`\r\n ///\r\n /// # Returns\r\n /// `(x ** n) % m`\r\n /* const */\r\n #[allow(clippy::many_single_char_names)]\r\n pub(crate) fn pow_mod(x: i64, mut n: i64, m: i32) -> i64 {\r\n if m == 1 {\r\n return 0;\r\n }\r\n let _m = m as u32;\r\n let mut r: u64 = 1;\r\n let mut y: u64 = safe_mod(x, m as i64) as u64;\r\n while n != 0 {\r\n if (n & 1) > 0 {\r\n r = (r * y) % (_m as u64);\r\n }\r\n y = (y * y) % (_m as u64);\r\n n >>= 1;\r\n }\r\n r as i64\r\n }\r\n\r\n /// Reference:\r\n /// M. Forisek and J. Jancina,\r\n /// Fast Primality Testing for Integers That Fit into a Machine Word\r\n ///\r\n /// # Parameters\r\n /// * `n` `0 <= n`\r\n /* const */\r\n pub(crate) fn is_prime(n: i32) -> bool {\r\n let n = n as i64;\r\n match n {\r\n _ if n <= 1 => return false,\r\n 2 | 7 | 61 => return true,\r\n _ if n % 2 == 0 => return false,\r\n _ => {}\r\n }\r\n let mut d = n - 1;\r\n while d % 2 == 0 {\r\n d /= 2;\r\n }\r\n for &a in &[2, 7, 61] {\r\n let mut t = d;\r\n let mut y = pow_mod(a, t, n as i32);\r\n while t != n - 1 && y != 1 && y != n - 1 {\r\n y = y * y % n;\r\n t <<= 1;\r\n }\r\n if y != n - 1 && t % 2 == 0 {\r\n return false;\r\n }\r\n }\r\n true\r\n }\r\n\r\n // omitted\r\n // template constexpr bool is_prime = is_prime_constexpr(n);\r\n\r\n /// # Parameters\r\n /// * `b` `1 <= b`\r\n ///\r\n /// # Returns\r\n /// (g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\r\n /* const */\r\n #[allow(clippy::many_single_char_names)]\r\n pub(crate) fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\r\n let a = safe_mod(a, b);\r\n if a == 0 {\r\n return (b, 0);\r\n }\r\n\r\n // Contracts:\r\n // [1] s - m0 * a = 0 (mod b)\r\n // [2] t - m1 * a = 0 (mod b)\r\n // [3] s * |m1| + t * |m0| <= b\r\n let mut s = b;\r\n let mut t = a;\r\n let mut m0 = 0;\r\n let mut m1 = 1;\r\n\r\n while t != 0 {\r\n let u = s / t;\r\n s -= t * u;\r\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\r\n\r\n // [3]:\r\n // (s - t * u) * |m1| + t * |m0 - m1 * u|\r\n // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)\r\n // = s * |m1| + t * |m0| <= b\r\n\r\n swap(&mut s, &mut t);\r\n swap(&mut m0, &mut m1);\r\n }\r\n // by [3]: |m0| <= b/g\r\n // by g != b: |m0| < b/g\r\n if m0 < 0 {\r\n m0 += b / s;\r\n }\r\n (s, m0)\r\n }\r\n\r\n /// Compile time (currently not) primitive root\r\n /// @param m must be prime\r\n /// @return primitive root (and minimum in now)\r\n /* const */\r\n pub(crate) fn primitive_root(m: i32) -> i32 {\r\n match m {\r\n 2 => return 1,\r\n 167_772_161 => return 3,\r\n 469_762_049 => return 3,\r\n 754_974_721 => return 11,\r\n 998_244_353 => return 3,\r\n _ => {}\r\n }\r\n\r\n let mut divs = [0; 20];\r\n divs[0] = 2;\r\n let mut cnt = 1;\r\n let mut x = (m - 1) / 2;\r\n while x % 2 == 0 {\r\n x /= 2;\r\n }\r\n for i in (3..std::i32::MAX).step_by(2) {\r\n if i as i64 * i as i64 > x as i64 {\r\n break;\r\n }\r\n if x % i == 0 {\r\n divs[cnt] = i;\r\n cnt += 1;\r\n while x % i == 0 {\r\n x /= i;\r\n }\r\n }\r\n }\r\n if x > 1 {\r\n divs[cnt] = x;\r\n cnt += 1;\r\n }\r\n let mut g = 2;\r\n loop {\r\n if (0..cnt).all(|i| pow_mod(g, ((m - 1) / divs[i]) as i64, m) != 1) {\r\n break g as i32;\r\n }\r\n g += 1;\r\n }\r\n }\r\n // omitted\r\n // template constexpr int primitive_root = primitive_root_constexpr(m);\r\n\r\n #[cfg(test)]\r\n mod tests {\r\n #![allow(clippy::unreadable_literal)]\r\n #![allow(clippy::cognitive_complexity)]\r\n use crate::internal_math::{inv_gcd, is_prime, pow_mod, primitive_root, safe_mod, Barrett};\r\n use std::collections::HashSet;\r\n\r\n #[test]\r\n fn test_safe_mod() {\r\n assert_eq!(safe_mod(0, 3), 0);\r\n assert_eq!(safe_mod(1, 3), 1);\r\n assert_eq!(safe_mod(2, 3), 2);\r\n assert_eq!(safe_mod(3, 3), 0);\r\n assert_eq!(safe_mod(4, 3), 1);\r\n assert_eq!(safe_mod(5, 3), 2);\r\n assert_eq!(safe_mod(73, 11), 7);\r\n assert_eq!(safe_mod(2306249155046129918, 6620319213327), 1374210749525);\r\n\r\n assert_eq!(safe_mod(-1, 3), 2);\r\n assert_eq!(safe_mod(-2, 3), 1);\r\n assert_eq!(safe_mod(-3, 3), 0);\r\n assert_eq!(safe_mod(-4, 3), 2);\r\n assert_eq!(safe_mod(-5, 3), 1);\r\n assert_eq!(safe_mod(-7170500492396019511, 777567337), 333221848);\r\n }\r\n\r\n #[test]\r\n fn test_barrett() {\r\n let b = Barrett::new(7);\r\n assert_eq!(b.umod(), 7);\r\n assert_eq!(b.mul(2, 3), 6);\r\n assert_eq!(b.mul(4, 6), 3);\r\n assert_eq!(b.mul(5, 0), 0);\r\n\r\n let b = Barrett::new(998244353);\r\n assert_eq!(b.umod(), 998244353);\r\n assert_eq!(b.mul(2, 3), 6);\r\n assert_eq!(b.mul(3141592, 653589), 919583920);\r\n assert_eq!(b.mul(323846264, 338327950), 568012980);\r\n\r\n // make `z - x * self._m as u64` overflow.\r\n // Thanks @koba-e964 (at https://github.com/rust-lang-ja/ac-library-rs/pull/3#discussion_r484932161)\r\n let b = Barrett::new(2147483647);\r\n assert_eq!(b.umod(), 2147483647);\r\n assert_eq!(b.mul(1073741824, 2147483645), 2147483646);\r\n }\r\n\r\n #[test]\r\n fn test_pow_mod() {\r\n assert_eq!(pow_mod(0, 0, 1), 0);\r\n assert_eq!(pow_mod(0, 0, 3), 1);\r\n assert_eq!(pow_mod(0, 0, 723), 1);\r\n assert_eq!(pow_mod(0, 0, 998244353), 1);\r\n assert_eq!(pow_mod(0, 0, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(0, 1, 1), 0);\r\n assert_eq!(pow_mod(0, 1, 3), 0);\r\n assert_eq!(pow_mod(0, 1, 723), 0);\r\n assert_eq!(pow_mod(0, 1, 998244353), 0);\r\n assert_eq!(pow_mod(0, 1, i32::max_value()), 0);\r\n\r\n assert_eq!(pow_mod(0, i64::max_value(), 1), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), 3), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), 723), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), 998244353), 0);\r\n assert_eq!(pow_mod(0, i64::max_value(), i32::max_value()), 0);\r\n\r\n assert_eq!(pow_mod(1, 0, 1), 0);\r\n assert_eq!(pow_mod(1, 0, 3), 1);\r\n assert_eq!(pow_mod(1, 0, 723), 1);\r\n assert_eq!(pow_mod(1, 0, 998244353), 1);\r\n assert_eq!(pow_mod(1, 0, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(1, 1, 1), 0);\r\n assert_eq!(pow_mod(1, 1, 3), 1);\r\n assert_eq!(pow_mod(1, 1, 723), 1);\r\n assert_eq!(pow_mod(1, 1, 998244353), 1);\r\n assert_eq!(pow_mod(1, 1, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(1, i64::max_value(), 1), 0);\r\n assert_eq!(pow_mod(1, i64::max_value(), 3), 1);\r\n assert_eq!(pow_mod(1, i64::max_value(), 723), 1);\r\n assert_eq!(pow_mod(1, i64::max_value(), 998244353), 1);\r\n assert_eq!(pow_mod(1, i64::max_value(), i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(i64::max_value(), 0, 1), 0);\r\n assert_eq!(pow_mod(i64::max_value(), 0, 3), 1);\r\n assert_eq!(pow_mod(i64::max_value(), 0, 723), 1);\r\n assert_eq!(pow_mod(i64::max_value(), 0, 998244353), 1);\r\n assert_eq!(pow_mod(i64::max_value(), 0, i32::max_value()), 1);\r\n\r\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 1), 0);\r\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 3), 1);\r\n assert_eq!(pow_mod(i64::max_value(), i64::max_value(), 723), 640);\r\n assert_eq!(\r\n pow_mod(i64::max_value(), i64::max_value(), 998244353),\r\n 683296792\r\n );\r\n assert_eq!(\r\n pow_mod(i64::max_value(), i64::max_value(), i32::max_value()),\r\n 1\r\n );\r\n\r\n assert_eq!(pow_mod(2, 3, 1_000_000_007), 8);\r\n assert_eq!(pow_mod(5, 7, 1_000_000_007), 78125);\r\n assert_eq!(pow_mod(123, 456, 1_000_000_007), 565291922);\r\n }\r\n\r\n #[test]\r\n fn test_is_prime() {\r\n assert!(!is_prime(0));\r\n assert!(!is_prime(1));\r\n assert!(is_prime(2));\r\n assert!(is_prime(3));\r\n assert!(!is_prime(4));\r\n assert!(is_prime(5));\r\n assert!(!is_prime(6));\r\n assert!(is_prime(7));\r\n assert!(!is_prime(8));\r\n assert!(!is_prime(9));\r\n\r\n // assert!(is_prime(57));\r\n assert!(!is_prime(57));\r\n assert!(!is_prime(58));\r\n assert!(is_prime(59));\r\n assert!(!is_prime(60));\r\n assert!(is_prime(61));\r\n assert!(!is_prime(62));\r\n\r\n assert!(!is_prime(701928443));\r\n assert!(is_prime(998244353));\r\n assert!(!is_prime(1_000_000_000));\r\n assert!(is_prime(1_000_000_007));\r\n\r\n assert!(is_prime(i32::max_value()));\r\n }\r\n\r\n #[test]\r\n fn test_is_prime_sieve() {\r\n let n = 1_000_000;\r\n let mut prime = vec![true; n];\r\n prime[0] = false;\r\n prime[1] = false;\r\n for i in 0..n {\r\n assert_eq!(prime[i], is_prime(i as i32));\r\n if prime[i] {\r\n for j in (2 * i..n).step_by(i) {\r\n prime[j] = false;\r\n }\r\n }\r\n }\r\n }\r\n\r\n #[test]\r\n fn test_inv_gcd() {\r\n for &(a, b, g) in &[\r\n (0, 1, 1),\r\n (0, 4, 4),\r\n (0, 7, 7),\r\n (2, 3, 1),\r\n (-2, 3, 1),\r\n (4, 6, 2),\r\n (-4, 6, 2),\r\n (13, 23, 1),\r\n (57, 81, 3),\r\n (12345, 67890, 15),\r\n (-3141592 * 6535, 3141592 * 8979, 3141592),\r\n (i64::max_value(), i64::max_value(), i64::max_value()),\r\n (i64::min_value(), i64::max_value(), 1),\r\n ] {\r\n let (g_, x) = inv_gcd(a, b);\r\n assert_eq!(g, g_);\r\n let b_ = b as i128;\r\n assert_eq!(((x as i128 * a as i128) % b_ + b_) % b_, g as i128 % b_);\r\n }\r\n }\r\n\r\n #[test]\r\n fn test_primitive_root() {\r\n for &p in &[\r\n 2,\r\n 3,\r\n 5,\r\n 7,\r\n 233,\r\n 200003,\r\n 998244353,\r\n 1_000_000_007,\r\n i32::max_value(),\r\n ] {\r\n assert!(is_prime(p));\r\n let g = primitive_root(p);\r\n if p != 2 {\r\n assert_ne!(g, 1);\r\n }\r\n\r\n let q = p - 1;\r\n for i in (2..i32::max_value()).take_while(|i| i * i <= q) {\r\n if q % i != 0 {\r\n break;\r\n }\r\n for &r in &[i, q / i] {\r\n assert_ne!(pow_mod(g as i64, r as i64, p), 1);\r\n }\r\n }\r\n assert_eq!(pow_mod(g as i64, q as i64, p), 1);\r\n\r\n if p < 1_000_000 {\r\n assert_eq!(\r\n (0..p - 1)\r\n .scan(1, |i, _| {\r\n *i = *i * g % p;\r\n Some(*i)\r\n })\r\n .collect::>()\r\n .len() as i32,\r\n p - 1\r\n );\r\n }\r\n }\r\n }\r\n }\r\n}\r\npub mod modint {\r\n //! Structs that treat the modular arithmetic.\r\n //!\r\n //! For most of the problems, It is sufficient to use [`ModInt1000000007`] or [`ModInt998244353`], which can be used as follows.\r\n //!\r\n //! ```\r\n //! use ac_library_rs::ModInt1000000007 as Mint; // rename to whatever you want\r\n //! use proconio::{input, source::once::OnceSource};\r\n //!\r\n //! input! {\r\n //! from OnceSource::from(\"1000000006 2\\n\"),\r\n //! a: Mint,\r\n //! b: Mint,\r\n //! }\r\n //!\r\n //! println!(\"{}\", a + b); // `1`\r\n //! ```\r\n //!\r\n //! If the modulus is not fixed, you can use [`ModInt`] as follows.\r\n //!\r\n //! ```\r\n //! use ac_library_rs::ModInt as Mint; // rename to whatever you want\r\n //! use proconio::{input, source::once::OnceSource};\r\n //!\r\n //! input! {\r\n //! from OnceSource::from(\"3 3 7\\n\"),\r\n //! a: u32,\r\n //! b: u32,\r\n //! m: u32,\r\n //! }\r\n //!\r\n //! Mint::set_modulus(m);\r\n //! let a = Mint::new(a);\r\n //! let b = Mint::new(b);\r\n //!\r\n //! println!(\"{}\", a * b); // `2`\r\n //! ```\r\n //!\r\n //! # Major changes from the original ACL\r\n //!\r\n //! - Converted the struct names to PascalCase.\r\n //! - Renamed `mod` `modulus`.\r\n //! - Moduli are `u32`, not `i32`.\r\n //! - Each `Id` does not have a identifier number. Instead, they explicitly own `&'static LocalKey>`.\r\n //! - The type of the argument of `pow` is `u64`, not `i64`.\r\n //! - Modints implement `FromStr` and `Display`. Modints in the original ACL don't have `operator<<` or `operator>>`.\r\n //!\r\n //! [`ModInt1000000007`]: ./type.ModInt1000000007.html\r\n //! [`ModInt998244353`]: ./type.ModInt998244353.html\r\n //! [`ModInt`]: ./type.ModInt.html\r\n\r\n use crate::internal_math;\r\n use std::{\r\n cell::RefCell,\r\n convert::{Infallible, TryInto as _},\r\n fmt,\r\n hash::{Hash, Hasher},\r\n iter::{Product, Sum},\r\n marker::PhantomData,\r\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\r\n str::FromStr,\r\n sync::atomic::{self, AtomicU32, AtomicU64},\r\n thread::LocalKey,\r\n };\r\n\r\n pub type ModInt1000000007 = StaticModInt;\r\n pub type ModInt998244353 = StaticModInt;\r\n pub type ModInt = DynamicModInt;\r\n\r\n /// Represents where _m_ is a constant value.\r\n ///\r\n /// Corresponds to `atcoder::static_modint` in the original ACL.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::ModInt1000000007 as Mint;\r\n /// use proconio::{input, source::once::OnceSource};\r\n ///\r\n /// input! {\r\n /// from OnceSource::from(\"1000000006 2\\n\"),\r\n /// a: Mint,\r\n /// b: Mint,\r\n /// }\r\n ///\r\n /// println!(\"{}\", a + b); // `1`\r\n /// ```\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n #[repr(transparent)]\r\n pub struct StaticModInt {\r\n val: u32,\r\n phantom: PhantomData M>,\r\n }\r\n\r\n impl StaticModInt {\r\n /// Returns the modulus, which is [`::VALUE`].\r\n ///\r\n /// Corresponds to `atcoder::static_modint::mod` in the original ACL.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::ModInt1000000007 as Mint;\r\n ///\r\n /// assert_eq!(1_000_000_007, Mint::modulus());\r\n /// ```\r\n ///\r\n /// [`::VALUE`]: ../trait.Modulus.html#associatedconstant.VALUE\r\n #[inline(always)]\r\n pub fn modulus() -> u32 {\r\n M::VALUE\r\n }\r\n\r\n /// Creates a new `StaticModInt`.\r\n ///\r\n /// Takes [any primitive integer].\r\n ///\r\n /// Corresponds to the constructor of `atcoder::static_modint` in the original ACL.\r\n ///\r\n /// [any primitive integer]: ../trait.RemEuclidU32.html\r\n #[inline]\r\n pub fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(M::VALUE))\r\n }\r\n\r\n /// Constructs a `StaticModInt` from a `val < Self::modulus()` without checking it.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::raw` in the original ACL.\r\n ///\r\n /// # Constraints\r\n ///\r\n /// - `val` is less than `Self::modulus()`\r\n ///\r\n /// See [`ModIntBase::raw`] for more more details.\r\n ///\r\n /// [`ModIntBase::raw`]: ./trait.ModIntBase.html#tymethod.raw\r\n #[inline]\r\n pub fn raw(val: u32) -> Self {\r\n Self {\r\n val,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n /// Retruns the representative.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::val` in the original ACL.\r\n #[inline]\r\n pub fn val(self) -> u32 {\r\n self.val\r\n }\r\n\r\n /// Returns `self` to the power of `n`.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::pow` in the original ACL.\r\n #[inline]\r\n pub fn pow(self, n: u64) -> Self {\r\n ::pow(self, n)\r\n }\r\n\r\n /// Retruns the multiplicative inverse of `self`.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::inv` in the original ACL.\r\n ///\r\n /// # Panics\r\n ///\r\n /// Panics if the multiplicative inverse does not exist.\r\n #[inline]\r\n pub fn inv(self) -> Self {\r\n if M::HINT_VALUE_IS_PRIME {\r\n if self.val() == 0 {\r\n panic!(\"attempt to divide by zero\");\r\n }\r\n debug_assert!(\r\n internal_math::is_prime(M::VALUE.try_into().unwrap()),\r\n \"{} is not a prime number\",\r\n M::VALUE,\r\n );\r\n self.pow((M::VALUE - 2).into())\r\n } else {\r\n Self::inv_for_non_prime_modulus(self)\r\n }\r\n }\r\n }\r\n\r\n /// These methods are implemented for the struct.\r\n /// You don't need to `use` `ModIntBase` to call methods of `StaticModInt`.\r\n impl ModIntBase for StaticModInt {\r\n #[inline(always)]\r\n fn modulus() -> u32 {\r\n Self::modulus()\r\n }\r\n\r\n #[inline]\r\n fn raw(val: u32) -> Self {\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn val(self) -> u32 {\r\n self.val()\r\n }\r\n\r\n #[inline]\r\n fn inv(self) -> Self {\r\n self.inv()\r\n }\r\n }\r\n\r\n /// Represents a modulus.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// macro_rules! modulus {\r\n /// ($($name:ident($value:expr, $is_prime:expr)),*) => {\r\n /// $(\r\n /// #[derive(Copy, Clone, Eq, PartialEq)]\r\n /// enum $name {}\r\n ///\r\n /// impl ac_library_rs::modint::Modulus for $name {\r\n /// const VALUE: u32 = $value;\r\n /// const HINT_VALUE_IS_PRIME: bool = $is_prime;\r\n ///\r\n /// fn butterfly_cache() -> &'static ::std::thread::LocalKey<::std::cell::RefCell<::std::option::Option>>> {\r\n /// thread_local! {\r\n /// static BUTTERFLY_CACHE: ::std::cell::RefCell<::std::option::Option>> = ::std::default::Default::default();\r\n /// }\r\n /// &BUTTERFLY_CACHE\r\n /// }\r\n /// }\r\n /// )*\r\n /// };\r\n /// }\r\n ///\r\n /// use ac_library_rs::StaticModInt;\r\n ///\r\n /// modulus!(Mod101(101, true), Mod103(103, true));\r\n ///\r\n /// type Z101 = StaticModInt;\r\n /// type Z103 = StaticModInt;\r\n ///\r\n /// assert_eq!(Z101::new(101), Z101::new(0));\r\n /// assert_eq!(Z103::new(103), Z103::new(0));\r\n /// ```\r\n pub trait Modulus: 'static + Copy + Eq {\r\n const VALUE: u32;\r\n const HINT_VALUE_IS_PRIME: bool;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>>;\r\n }\r\n\r\n /// Represents _1000000007_.\r\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\n pub enum Mod1000000007 {}\r\n\r\n impl Modulus for Mod1000000007 {\r\n const VALUE: u32 = 1_000_000_007;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n }\r\n\r\n /// Represents _998244353_.\r\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\n pub enum Mod998244353 {}\r\n\r\n impl Modulus for Mod998244353 {\r\n const VALUE: u32 = 998_244_353;\r\n const HINT_VALUE_IS_PRIME: bool = true;\r\n\r\n fn butterfly_cache() -> &'static LocalKey>>> {\r\n thread_local! {\r\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\r\n }\r\n &BUTTERFLY_CACHE\r\n }\r\n }\r\n\r\n /// Cache for butterfly operations.\r\n pub struct ButterflyCache {\r\n pub(crate) sum_e: Vec>,\r\n pub(crate) sum_ie: Vec>,\r\n }\r\n\r\n /// Represents where _m_ is a dynamic value.\r\n ///\r\n /// Corresponds to `atcoder::dynamic_modint` in the original ACL.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::ModInt as Mint;\r\n /// use proconio::{input, source::once::OnceSource};\r\n ///\r\n /// input! {\r\n /// from OnceSource::from(\"3 3 7\\n\"),\r\n /// a: u32,\r\n /// b: u32,\r\n /// m: u32,\r\n /// }\r\n ///\r\n /// Mint::set_modulus(m);\r\n /// let a = Mint::new(a);\r\n /// let b = Mint::new(b);\r\n ///\r\n /// println!(\"{}\", a * b); // `2`\r\n /// ```\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n #[repr(transparent)]\r\n pub struct DynamicModInt {\r\n val: u32,\r\n phantom: PhantomData I>,\r\n }\r\n\r\n impl DynamicModInt {\r\n /// Returns the modulus.\r\n ///\r\n /// Corresponds to `atcoder::dynamic_modint::mod` in the original ACL.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::ModInt as Mint;\r\n ///\r\n /// assert_eq!(998_244_353, Mint::modulus()); // default modulus\r\n /// ```\r\n #[inline]\r\n pub fn modulus() -> u32 {\r\n I::companion_barrett().umod()\r\n }\r\n\r\n /// Sets a modulus.\r\n ///\r\n /// Corresponds to `atcoder::dynamic_modint::set_mod` in the original ACL.\r\n ///\r\n /// # Constraints\r\n ///\r\n /// - This function must be called earlier than any other operation of `Self`.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::ModInt as Mint;\r\n ///\r\n /// Mint::set_modulus(7);\r\n /// assert_eq!(7, Mint::modulus());\r\n /// ```\r\n #[inline]\r\n pub fn set_modulus(modulus: u32) {\r\n if modulus == 0 {\r\n panic!(\"the modulus must not be 0\");\r\n }\r\n I::companion_barrett().update(modulus);\r\n }\r\n\r\n /// Creates a new `DynamicModInt`.\r\n ///\r\n /// Takes [any primitive integer].\r\n ///\r\n /// Corresponds to the constructor of `atcoder::dynamic_modint` in the original ACL.\r\n ///\r\n /// [any primitive integer]: ../trait.RemEuclidU32.html\r\n #[inline]\r\n pub fn new(val: T) -> Self {\r\n ::new(val)\r\n }\r\n\r\n /// Constructs a `DynamicModInt` from a `val < Self::modulus()` without checking it.\r\n ///\r\n /// Corresponds to `atcoder::dynamic_modint::raw` in the original ACL.\r\n ///\r\n /// # Constraints\r\n ///\r\n /// - `val` is less than `Self::modulus()`\r\n ///\r\n /// See [`ModIntBase::raw`] for more more details.\r\n ///\r\n /// [`ModIntBase::raw`]: ./trait.ModIntBase.html#tymethod.raw\r\n #[inline]\r\n pub fn raw(val: u32) -> Self {\r\n Self {\r\n val,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n /// Retruns the representative.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::val` in the original ACL.\r\n #[inline]\r\n pub fn val(self) -> u32 {\r\n self.val\r\n }\r\n\r\n /// Returns `self` to the power of `n`.\r\n ///\r\n /// Corresponds to `atcoder::dynamic_modint::pow` in the original ACL.\r\n #[inline]\r\n pub fn pow(self, n: u64) -> Self {\r\n ::pow(self, n)\r\n }\r\n\r\n /// Retruns the multiplicative inverse of `self`.\r\n ///\r\n /// Corresponds to `atcoder::dynamic_modint::inv` in the original ACL.\r\n ///\r\n /// # Panics\r\n ///\r\n /// Panics if the multiplicative inverse does not exist.\r\n #[inline]\r\n pub fn inv(self) -> Self {\r\n Self::inv_for_non_prime_modulus(self)\r\n }\r\n }\r\n\r\n /// These methods are implemented for the struct.\r\n /// You don't need to `use` `ModIntBase` to call methods of `DynamicModInt`.\r\n impl ModIntBase for DynamicModInt {\r\n #[inline]\r\n fn modulus() -> u32 {\r\n Self::modulus()\r\n }\r\n\r\n #[inline]\r\n fn raw(val: u32) -> Self {\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn val(self) -> u32 {\r\n self.val()\r\n }\r\n\r\n #[inline]\r\n fn inv(self) -> Self {\r\n self.inv()\r\n }\r\n }\r\n\r\n pub trait Id: 'static + Copy + Eq {\r\n fn companion_barrett() -> &'static Barrett;\r\n }\r\n\r\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\r\n pub enum DefaultId {}\r\n\r\n impl Id for DefaultId {\r\n fn companion_barrett() -> &'static Barrett {\r\n static BARRETT: Barrett = Barrett::default();\r\n &BARRETT\r\n }\r\n }\r\n\r\n /// Pair of _m_ and _ceil(2\u7ac5\uff76\u7ac5\uff74/m)_.\r\n pub struct Barrett {\r\n m: AtomicU32,\r\n im: AtomicU64,\r\n }\r\n\r\n impl Barrett {\r\n /// Creates a new `Barrett`.\r\n #[inline]\r\n pub const fn new(m: u32) -> Self {\r\n Self {\r\n m: AtomicU32::new(m),\r\n im: AtomicU64::new((-1i64 as u64 / m as u64).wrapping_add(1)),\r\n }\r\n }\r\n\r\n #[inline]\r\n const fn default() -> Self {\r\n Self::new(998_244_353)\r\n }\r\n\r\n #[inline]\r\n fn update(&self, m: u32) {\r\n let im = (-1i64 as u64 / m as u64).wrapping_add(1);\r\n self.m.store(m, atomic::Ordering::SeqCst);\r\n self.im.store(im, atomic::Ordering::SeqCst);\r\n }\r\n\r\n #[inline]\r\n fn umod(&self) -> u32 {\r\n self.m.load(atomic::Ordering::SeqCst)\r\n }\r\n\r\n #[inline]\r\n fn mul(&self, a: u32, b: u32) -> u32 {\r\n let m = self.m.load(atomic::Ordering::SeqCst);\r\n let im = self.im.load(atomic::Ordering::SeqCst);\r\n internal_math::mul_mod(a, b, m, im)\r\n }\r\n }\r\n\r\n impl Default for Barrett {\r\n #[inline]\r\n fn default() -> Self {\r\n Self::default()\r\n }\r\n }\r\n\r\n /// A trait for [`StaticModInt`] and [`DynamicModInt`].\r\n ///\r\n /// Corresponds to `atcoder::internal::modint_base` in the original ACL.\r\n ///\r\n /// [`StaticModInt`]: ../struct.StaticModInt.html\r\n /// [`DynamicModInt`]: ../struct.DynamicModInt.html\r\n pub trait ModIntBase:\r\n Default\r\n + FromStr\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + From\r\n + Copy\r\n + Eq\r\n + Hash\r\n + fmt::Display\r\n + fmt::Debug\r\n + Neg\r\n + Add\r\n + Sub\r\n + Mul\r\n + Div\r\n + AddAssign\r\n + SubAssign\r\n + MulAssign\r\n + DivAssign\r\n {\r\n /// Returns the modulus.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::mod` and `atcoder::dynamic_modint::mod` in the original ACL.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::modint::ModIntBase;\r\n ///\r\n /// fn f() {\r\n /// let _: u32 = Z::modulus();\r\n /// }\r\n /// ```\r\n fn modulus() -> u32;\r\n\r\n /// Constructs a `Self` from a `val < Self::modulus()` without checking it.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::raw` and `atcoder::dynamic_modint::raw` in the original ACL.\r\n ///\r\n /// # Constraints\r\n ///\r\n /// - `val` is less than `Self::modulus()`\r\n ///\r\n /// **Note that all operations assume that inner values are smaller than the modulus.**\r\n /// If `val` is greater than or equal to `Self::modulus()`, the behaviors are not defined.\r\n ///\r\n /// ```should_panic\r\n /// use ac_library_rs::ModInt1000000007 as Mint;\r\n ///\r\n /// let x = Mint::raw(1_000_000_007);\r\n /// let y = x + x;\r\n /// assert_eq!(0, y.val());\r\n /// ```\r\n ///\r\n /// ```text\r\n /// thread 'main' panicked at 'assertion failed: `(left == right)`\r\n /// left: `0`,\r\n /// right: `1000000007`', src/modint.rs:8:1\r\n /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\r\n /// ```\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::modint::ModIntBase;\r\n ///\r\n /// fn f() -> Z {\r\n /// debug_assert!(Z::modulus() >= 100);\r\n ///\r\n /// let mut acc = Z::new(0);\r\n /// for i in 0..100 {\r\n /// if i % 3 == 0 {\r\n /// // I know `i` is smaller than the modulus!\r\n /// acc += Z::raw(i);\r\n /// }\r\n /// }\r\n /// acc\r\n /// }\r\n /// ```\r\n fn raw(val: u32) -> Self;\r\n\r\n /// Retruns the representative.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::val` and `atcoder::dynamic_modint::val` in the original ACL.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::modint::ModIntBase;\r\n ///\r\n /// fn f(x: Z) {\r\n /// let _: u32 = x.val();\r\n /// }\r\n /// ```\r\n fn val(self) -> u32;\r\n\r\n /// Retruns the multiplicative inverse of `self`.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::inv` and `atcoder::dynamic_modint::inv` in the original ACL.\r\n ///\r\n /// # Panics\r\n ///\r\n /// Panics if the multiplicative inverse does not exist.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::modint::ModIntBase;\r\n ///\r\n /// fn f(x: Z) {\r\n /// let _: Z = x.inv();\r\n /// }\r\n /// ```\r\n fn inv(self) -> Self;\r\n\r\n /// Creates a new `Self`.\r\n ///\r\n /// Takes [any primitive integer].\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::modint::ModIntBase;\r\n ///\r\n /// fn f() {\r\n /// let _ = Z::new(1u32);\r\n /// let _ = Z::new(1usize);\r\n /// let _ = Z::new(-1i64);\r\n /// }\r\n /// ```\r\n ///\r\n /// [any primitive integer]: ../trait.RemEuclidU32.html\r\n #[inline]\r\n fn new(val: T) -> Self {\r\n Self::raw(val.rem_euclid_u32(Self::modulus()))\r\n }\r\n\r\n /// Returns `self` to the power of `n`.\r\n ///\r\n /// Corresponds to `atcoder::static_modint::pow` and `atcoder::dynamic_modint::pow` in the original ACL.\r\n ///\r\n /// # Example\r\n ///\r\n /// ```\r\n /// use ac_library_rs::modint::ModIntBase;\r\n ///\r\n /// fn f() {\r\n /// let _: Z = Z::new(2).pow(3);\r\n /// }\r\n /// ```\r\n #[inline]\r\n fn pow(self, mut n: u64) -> Self {\r\n let mut x = self;\r\n let mut r = Self::raw(1);\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n r *= x;\r\n }\r\n x *= x;\r\n n >>= 1;\r\n }\r\n r\r\n }\r\n }\r\n\r\n /// A trait for `{StaticModInt, DynamicModInt, ModIntBase}::new`.\r\n pub trait RemEuclidU32 {\r\n /// Calculates `self` _mod_ `modulus` losslessly.\r\n fn rem_euclid_u32(self, modulus: u32) -> u32;\r\n }\r\n\r\n macro_rules! impl_rem_euclid_u32_for_small_signed {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self as i64).rem_euclid(i64::from(modulus)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\r\n\r\n impl RemEuclidU32 for i128 {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self.rem_euclid(i128::from(modulus)) as _\r\n }\r\n }\r\n\r\n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self as u32 % modulus\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self % (modulus as $ty)) as _\r\n }\r\n }\r\n )*\r\n }\r\n}\r\n\r\n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\r\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\r\n\r\n #[cfg(target_pointer_width = \"32\")]\r\n impl_rem_euclid_u32_for_small_unsigned!(usize);\r\n\r\n #[cfg(target_pointer_width = \"64\")]\r\n impl_rem_euclid_u32_for_large_unsigned!(usize);\r\n\r\n trait InternalImplementations: ModIntBase {\r\n #[inline]\r\n fn inv_for_non_prime_modulus(this: Self) -> Self {\r\n let (gcd, x) = internal_math::inv_gcd(this.val().into(), Self::modulus().into());\r\n if gcd != 1 {\r\n panic!(\"the multiplicative inverse does not exist\");\r\n }\r\n Self::new(x)\r\n }\r\n\r\n #[inline]\r\n fn default_impl() -> Self {\r\n Self::raw(0)\r\n }\r\n\r\n #[inline]\r\n fn from_str_impl(s: &str) -> Result {\r\n Ok(s.parse::()\r\n .map(Self::new)\r\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\r\n }\r\n\r\n #[inline]\r\n fn hash_impl(this: &Self, state: &mut impl Hasher) {\r\n this.val().hash(state)\r\n }\r\n\r\n #[inline]\r\n fn display_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Display::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn debug_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\r\n fmt::Debug::fmt(&this.val(), f)\r\n }\r\n\r\n #[inline]\r\n fn neg_impl(this: Self) -> Self {\r\n Self::sub_impl(Self::raw(0), this)\r\n }\r\n\r\n #[inline]\r\n fn add_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val() + rhs.val();\r\n if val >= modulus {\r\n val -= modulus;\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n #[inline]\r\n fn sub_impl(lhs: Self, rhs: Self) -> Self {\r\n let modulus = Self::modulus();\r\n let mut val = lhs.val().wrapping_sub(rhs.val());\r\n if val >= modulus {\r\n val = val.wrapping_add(modulus)\r\n }\r\n Self::raw(val)\r\n }\r\n\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self;\r\n\r\n #[inline]\r\n fn div_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::mul_impl(lhs, rhs.inv())\r\n }\r\n }\r\n\r\n impl InternalImplementations for StaticModInt {\r\n #[inline]\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::raw((u64::from(lhs.val()) * u64::from(rhs.val()) % u64::from(M::VALUE)) as u32)\r\n }\r\n }\r\n\r\n impl InternalImplementations for DynamicModInt {\r\n #[inline]\r\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\r\n Self::raw(I::companion_barrett().mul(lhs.val, rhs.val))\r\n }\r\n }\r\n\r\n macro_rules! impl_basic_traits {\r\n () => {};\r\n (impl <$generic_param:ident : $generic_param_bound:tt> _ for $self:ty; $($rest:tt)*) => {\r\n impl <$generic_param: $generic_param_bound> Default for $self {\r\n #[inline]\r\n fn default() -> Self {\r\n Self::default_impl()\r\n }\r\n }\r\n\r\n impl <$generic_param: $generic_param_bound> FromStr for $self {\r\n type Err = Infallible;\r\n\r\n #[inline]\r\n fn from_str(s: &str) -> Result {\r\n Self::from_str_impl(s)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound, V: RemEuclidU32> From for $self {\r\n #[inline]\r\n fn from(from: V) -> Self {\r\n Self::new(from)\r\n }\r\n }\r\n\r\n #[allow(clippy::derive_hash_xor_eq)]\r\n impl<$generic_param: $generic_param_bound> Hash for $self {\r\n #[inline]\r\n fn hash(&self, state: &mut H) {\r\n Self::hash_impl(self, state)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Display for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::display_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> fmt::Debug for $self {\r\n #[inline]\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Self::debug_impl(self, f)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n Self::neg_impl(self)\r\n }\r\n }\r\n\r\n impl<$generic_param: $generic_param_bound> Neg for &'_ $self {\r\n type Output = $self;\r\n\r\n #[inline]\r\n fn neg(self) -> $self {\r\n <$self>::neg_impl(*self)\r\n }\r\n }\r\n\r\n impl_basic_traits!($($rest)*);\r\n };\r\n}\r\n\r\n impl_basic_traits! {\r\n impl _ for StaticModInt ;\r\n impl _ for DynamicModInt;\r\n }\r\n\r\n macro_rules! impl_bin_ops {\r\n () => {};\r\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~ <$rhs_ty:ty> -> $output:ty { { $lhs_body:expr } ~ { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$($generic_param: $generic_param_bound),*> Add<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn add(self, rhs: $rhs_ty) -> $output {\r\n <$output>::add_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Sub<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn sub(self, rhs: $rhs_ty) -> $output {\r\n <$output>::sub_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Mul<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn mul(self, rhs: $rhs_ty) -> $output {\r\n <$output>::mul_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> Div<$rhs_ty> for $lhs_ty {\r\n type Output = $output;\r\n\r\n #[inline]\r\n fn div(self, rhs: $rhs_ty) -> $output {\r\n <$output>::div_impl(apply($lhs_body, self), apply($rhs_body, rhs))\r\n }\r\n }\r\n\r\n impl_bin_ops!($($rest)*);\r\n };\r\n}\r\n\r\n macro_rules! impl_assign_ops {\r\n () => {};\r\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~= <$rhs_ty:ty> { _ ~= { $rhs_body:expr } } $($rest:tt)*) => {\r\n impl <$($generic_param: $generic_param_bound),*> AddAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn add_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self + apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> SubAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn sub_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self - apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> MulAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn mul_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self * apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl <$($generic_param: $generic_param_bound),*> DivAssign<$rhs_ty> for $lhs_ty {\r\n #[inline]\r\n fn div_assign(&mut self, rhs: $rhs_ty) {\r\n *self = *self / apply($rhs_body, rhs);\r\n }\r\n }\r\n\r\n impl_assign_ops!($($rest)*);\r\n };\r\n}\r\n\r\n #[inline]\r\n fn apply O, X, O>(f: F, x: X) -> O {\r\n f(x)\r\n }\r\n\r\n impl_bin_ops! {\r\n for > ~ > -> StaticModInt { { |x| x } ~ { |x| x } }\r\n for > ~ <&'_ StaticModInt > -> StaticModInt { { |x| x } ~ { |&x| x } }\r\n for <&'_ StaticModInt > ~ > -> StaticModInt { { |&x| x } ~ { |x| x } }\r\n for <&'_ StaticModInt > ~ <&'_ StaticModInt > -> StaticModInt { { |&x| x } ~ { |&x| x } }\r\n for > ~ > -> DynamicModInt { { |x| x } ~ { |x| x } }\r\n for > ~ <&'_ DynamicModInt> -> DynamicModInt { { |x| x } ~ { |&x| x } }\r\n for <&'_ DynamicModInt> ~ > -> DynamicModInt { { |&x| x } ~ { |x| x } }\r\n for <&'_ DynamicModInt> ~ <&'_ DynamicModInt> -> DynamicModInt { { |&x| x } ~ { |&x| x } }\r\n\r\n for > ~ -> StaticModInt { { |x| x } ~ { StaticModInt::::new } }\r\n for > ~ -> DynamicModInt { { |x| x } ~ { DynamicModInt::::new } }\r\n }\r\n\r\n impl_assign_ops! {\r\n for > ~= > { _ ~= { |x| x } }\r\n for > ~= <&'_ StaticModInt > { _ ~= { |&x| x } }\r\n for > ~= > { _ ~= { |x| x } }\r\n for > ~= <&'_ DynamicModInt> { _ ~= { |&x| x } }\r\n\r\n for > ~= { _ ~= { StaticModInt::::new } }\r\n for > ~= { _ ~= { DynamicModInt::::new } }\r\n }\r\n\r\n macro_rules! impl_folding {\r\n () => {};\r\n (impl<$generic_param:ident : $generic_param_bound:tt> $trait:ident<_> for $self:ty { fn $method:ident(_) -> _ { _($unit:expr, $op:expr) } } $($rest:tt)*) => {\r\n impl<$generic_param: $generic_param_bound> $trait for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl<'a, $generic_param: $generic_param_bound> $trait<&'a Self> for $self {\r\n #[inline]\r\n fn $method(iter: S) -> Self\r\n where\r\n S: Iterator,\r\n {\r\n iter.fold($unit, $op)\r\n }\r\n }\r\n\r\n impl_folding!($($rest)*);\r\n };\r\n}\r\n\r\n impl_folding! {\r\n impl Sum<_> for StaticModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\r\n impl Product<_> for StaticModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\r\n impl Sum<_> for DynamicModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\r\n impl Product<_> for DynamicModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\r\n }\r\n\r\n #[cfg(test)]\r\n mod tests {\r\n use crate::modint::ModInt1000000007;\r\n\r\n #[test]\r\n fn static_modint_new() {\r\n assert_eq!(0, ModInt1000000007::new(0u32).val);\r\n assert_eq!(1, ModInt1000000007::new(1u32).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008u32).val);\r\n\r\n assert_eq!(0, ModInt1000000007::new(0u64).val);\r\n assert_eq!(1, ModInt1000000007::new(1u64).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008u64).val);\r\n\r\n assert_eq!(0, ModInt1000000007::new(0usize).val);\r\n assert_eq!(1, ModInt1000000007::new(1usize).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008usize).val);\r\n\r\n assert_eq!(0, ModInt1000000007::new(0i64).val);\r\n assert_eq!(1, ModInt1000000007::new(1i64).val);\r\n assert_eq!(1, ModInt1000000007::new(1_000_000_008i64).val);\r\n assert_eq!(1_000_000_006, ModInt1000000007::new(-1i64).val);\r\n }\r\n\r\n #[test]\r\n fn static_modint_add() {\r\n fn add(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) + ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(2, add(1, 1));\r\n assert_eq!(1, add(1_000_000_006, 2));\r\n }\r\n\r\n #[test]\r\n fn static_modint_sub() {\r\n fn sub(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) - ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(1, sub(2, 1));\r\n assert_eq!(1_000_000_006, sub(0, 1));\r\n }\r\n\r\n #[test]\r\n fn static_modint_mul() {\r\n fn mul(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) * ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(1, mul(1, 1));\r\n assert_eq!(4, mul(2, 2));\r\n assert_eq!(999_999_937, mul(100_000, 100_000));\r\n }\r\n\r\n #[test]\r\n fn static_modint_prime_div() {\r\n fn div(lhs: u32, rhs: u32) -> u32 {\r\n (ModInt1000000007::new(lhs) / ModInt1000000007::new(rhs)).val\r\n }\r\n\r\n assert_eq!(0, div(0, 1));\r\n assert_eq!(1, div(1, 1));\r\n assert_eq!(1, div(2, 2));\r\n assert_eq!(23_809_524, div(1, 42));\r\n }\r\n\r\n #[test]\r\n fn static_modint_sum() {\r\n fn sum(values: &[i64]) -> ModInt1000000007 {\r\n values.iter().copied().map(ModInt1000000007::new).sum()\r\n }\r\n\r\n assert_eq!(ModInt1000000007::new(-3), sum(&[-1, 2, -3, 4, -5]));\r\n }\r\n\r\n #[test]\r\n fn static_modint_product() {\r\n fn product(values: &[i64]) -> ModInt1000000007 {\r\n values.iter().copied().map(ModInt1000000007::new).product()\r\n }\r\n\r\n assert_eq!(ModInt1000000007::new(-120), product(&[-1, 2, -3, 4, -5]));\r\n }\r\n\r\n #[test]\r\n fn static_modint_binop_coercion() {\r\n let f = ModInt1000000007::new;\r\n let a = 10_293_812_usize;\r\n let b = 9_083_240_982_usize;\r\n assert_eq!(f(a) + f(b), f(a) + b);\r\n assert_eq!(f(a) - f(b), f(a) - b);\r\n assert_eq!(f(a) * f(b), f(a) * b);\r\n assert_eq!(f(a) / f(b), f(a) / b);\r\n }\r\n\r\n #[test]\r\n fn static_modint_assign_coercion() {\r\n let f = ModInt1000000007::new;\r\n let a = f(10_293_812_usize);\r\n let b = 9_083_240_982_usize;\r\n let expected = (((a + b) * b) - b) / b;\r\n let mut c = a;\r\n c += b;\r\n c *= b;\r\n c -= b;\r\n c /= b;\r\n assert_eq!(expected, c);\r\n }\r\n }\r\n}\r\nuse modint::ModInt1000000007 as mint;\r\nuse modint::*;\r\n\r\npub struct Combination {\r\n fact: Vec,\r\n ifact: Vec,\r\n}\r\nimpl Combination {\r\n pub fn new(n: i32) -> Self {\r\n let mut fact = vec![mint::new(0); (n + 1) as usize];\r\n let mut ifact = vec![mint::new(0); (n + 1) as usize];\r\n fact[0] = mint::new(1);\r\n for i in 1..n + 1 {\r\n fact[i as usize] = fact[(i - 1) as usize] * mint::new(i as i64)\r\n }\r\n ifact[n as usize] = fact[n as usize].inv();\r\n for i in (1..n + 1).rev() {\r\n ifact[(i - 1) as usize] = ifact[i as usize] * mint::new(i as i64)\r\n }\r\n let a = Combination {\r\n fact: fact,\r\n ifact: ifact,\r\n };\r\n return a;\r\n }\r\n #[macro_use]\r\n pub fn gen(&mut self, n: i32, k: i32) -> mint {\r\n if (k < 0 || k > n) {\r\n return mint::new(0 as i64);\r\n };\r\n return self.fact[n as usize] * self.ifact[k as usize] * self.ifact[(n - k) as usize];\r\n }\r\n pub fn P(&mut self, n: i32, k: i32) -> mint {\r\n self.fact[n as usize] * self.ifact[(n - k) as usize]\r\n }\r\n}\r\n\r\nfn main() {\r\n let T = get!(usize);\r\n let mut cmb = Combination::new(2 * 100000 + 10);\r\n\r\n for testcase in 0..T {\r\n mydbg!(testcase);\r\n let mut ans: mint = mint::new(0);\r\n let (N, K) = get!(usize, usize);\r\n\r\n let mut E = mint::new(1);\r\n for i in 1.. {\r\n let k = i * 2;\r\n if k >= N {\r\n break;\r\n }\r\n E += cmb.gen(N as i32, k as i32);\r\n }\r\n\r\n mydbg!(E);\r\n\r\n let mut dp = vec![vec![mint::new(0); 3]; K + 1];\r\n dp[0][0] = mint::new(1);\r\n for i in 0..K {\r\n for j in 0..2 {\r\n if dp[i][j] == mint::new(0) {\r\n continue;\r\n }\r\n if j == 0 {\r\n //1\r\n if N % 2 == 0 {\r\n dp[i + 1][j + 1] = dp[i + 1][j + 1] + dp[i][j];\r\n } else {\r\n dp[i + 1][j] = dp[i + 1][j] + dp[i][j];\r\n }\r\n //0\r\n dp[i + 1][j] = dp[i + 1][j] + dp[i][j] * E;\r\n } else {\r\n dp[i + 1][j] = dp[i + 1][j] + dp[i][j] * mint::new(2).pow(N as u64);\r\n }\r\n }\r\n }\r\n\r\n echo!(dp[K][0] + dp[K][1]);\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "ff1cb8758f3c7f749e9dbccd17732e22", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nuse std::io::Write;\r\nuse std::collections::*;\r\n\r\ntype Map = BTreeMap;\r\ntype Set = BTreeSet;\r\ntype Deque = VecDeque;\r\n\r\nfn run() {\r\n input! {\r\n t: usize,\r\n ask: [(usize, usize, usize); t],\r\n }\r\n let out = std::io::stdout();\r\n let mut out = std::io::BufWriter::new(out.lock());\r\n for (h, w, k) in ask {\r\n let b = k;\r\n let a = h * w / 2 - b;\r\n let ans = match (h % 2, w % 2, a % 2, b % 2) {\r\n (0, 0, 0, 0) => \"YES\",\r\n (0, 0, _, _) => \"NO\",\r\n (0, 1, _, 0) if b <= (w - 1) * h / 2 => \"YES\",\r\n (0, 1, _, _) => \"NO\",\r\n (1, 0, 0, _) if a <= (h - 1) * w / 2 => \"YES\",\r\n _ => \"NO\",\r\n };\r\n writeln!(out, \"{}\", ans).ok();\r\n }\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "0ad2feef65ce521930ac7a6af09c3372", "src_uid": "4d0c0cc8faca62eb6384f8135b30feb8", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{io, io::prelude::*, str};\n\nstruct Scanner {\n reader: R,\n buffer: Vec,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n fn t(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn check(mut n: usize, mut m: usize, mut k: usize) -> bool {\n m /= 2;\n if m == 0 {\n return k == 0;\n }\n\n if n % 2 == 1 {\n if k < m {\n return false;\n }\n k -= m;\n n -= 1;\n }\n if k % 2 == 1 {\n return false;\n }\n\n let mut rows = 0usize;\n while k >= m * 2 {\n k -= m * 2;\n rows += 2;\n }\n if n < rows {\n return false;\n }\n\n n -= rows;\n if k > 0 {\n return n > 0;\n }\n true\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout);\n\n let tn: usize = scan.t();\n for _ in 0..tn {\n let (n, m, k): (usize, usize, usize) = (scan.t(), scan.t(), scan.t());\n\n let ok = check(n, m, k);\n if ok {\n writeln!(out, \"YES\").ok();\n } else {\n writeln!(out, \"NO\").ok();\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "fb556957e50cb58b5812ca8367cb901c", "src_uid": "4d0c0cc8faca62eb6384f8135b30feb8", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\r\n#![allow(unused_imports)]\r\n#![allow(non_upper_case_globals)]\r\n#![allow(non_snake_case)]\r\n#![allow(unused_mut)]\r\n#![allow(unused_variables)]\r\n#![allow(dead_code)]\r\n\r\ntype Vec2 = Vec>;\r\ntype Vec3 = Vec>>;\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! invec {\r\n ( $ t : ty ) => {{\r\n let mut s = String::new();\r\n match std::io::stdin().read_line(&mut s) {\r\n Ok(0) => Vec::<$t>::new(),\r\n Ok(n) => s\r\n .trim()\r\n .split_whitespace()\r\n .map(|s| s.parse::<$t>().unwrap())\r\n .collect::>(),\r\n Err(_) => Vec::<$t>::new(),\r\n }\r\n }};\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! get {\r\n ($t:ty) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.trim().parse::<$t>().unwrap()\r\n }\r\n };\r\n ($($t:ty),*) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n let mut iter = line.split_whitespace();\r\n (\r\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\r\n )\r\n }\r\n };\r\n ($t:ty; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($t)\r\n ).collect::>()\r\n };\r\n ($($t:ty),*; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($($t),*)\r\n ).collect::>()\r\n };\r\n ($t:ty ;;) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.split_whitespace()\r\n .map(|t| t.parse::<$t>().unwrap())\r\n .collect::>()\r\n }\r\n };\r\n ($t:ty ;; $n:expr) => {\r\n (0..$n).map(|_| get!($t ;;)).collect::>()\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let mut s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\r\n let mut $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n\r\n ($next:expr, [$t:tt]) => {\r\n {\r\n let len = read_value!($next, usize);\r\n (0..len).map(|_| read_value!($next, $t)).collect::>()\r\n }\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\n#[cfg(debug_assertions)]\r\nmacro_rules! mydbg {\r\n //($arg:expr) => (dbg!($arg))\r\n //($arg:expr) => (println!(\"{:?}\",$arg));\r\n ($($a:expr),*) => {\r\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\r\n }\r\n}\r\n#[cfg(not(debug_assertions))]\r\nmacro_rules! mydbg {\r\n ($($arg:expr),*) => {};\r\n}\r\n\r\nmacro_rules! echo {\r\n ($($a:expr),*) => {\r\n $(println!(\"{}\",$a))*\r\n }\r\n}\r\n\r\nuse std::cmp::*;\r\nuse std::collections::*;\r\nuse std::ops::{Add, Div, Mul, Rem, Sub};\r\n\r\ntrait SafeRangeContain {\r\n fn safe_contains(&self, x: i64) -> bool;\r\n}\r\n\r\nimpl SafeRangeContain for std::ops::Range {\r\n fn safe_contains(&self, x: i64) -> bool {\r\n if x < 0 {\r\n return false;\r\n }\r\n return self.contains(&(x as usize));\r\n }\r\n}\r\n\r\n#[allow(dead_code)]\r\nstatic INF_I64: i64 = i64::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_I32: i32 = i32::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_USIZE: usize = usize::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic M_O_D: usize = 1000000007;\r\n#[allow(dead_code)]\r\nstatic PAI: f64 = 3.1415926535897932;\r\n\r\ntrait IteratorExt: Iterator {\r\n fn toVec(self) -> Vec;\r\n}\r\n\r\nimpl IteratorExt for T {\r\n fn toVec(self) -> Vec {\r\n self.collect()\r\n }\r\n}\r\n\r\ntrait CharExt {\r\n fn toNum(&self) -> usize;\r\n fn toAlphabetIndex(&self) -> usize;\r\n fn toNumIndex(&self) -> usize;\r\n}\r\nimpl CharExt for char {\r\n fn toNum(&self) -> usize {\r\n return *self as usize;\r\n }\r\n fn toAlphabetIndex(&self) -> usize {\r\n return self.toNum() - 'a' as usize;\r\n }\r\n fn toNumIndex(&self) -> usize {\r\n return self.toNum() - '0' as usize;\r\n }\r\n}\r\n\r\ntrait VectorExt {\r\n fn joinToString(&self, s: &str) -> String;\r\n}\r\nimpl VectorExt for Vec {\r\n fn joinToString(&self, s: &str) -> String {\r\n return self\r\n .iter()\r\n .map(|x| x.to_string())\r\n .collect::>()\r\n .join(s);\r\n }\r\n}\r\n\r\ntrait StringExt {\r\n fn get_reverse(&self) -> String;\r\n}\r\nimpl StringExt for String {\r\n fn get_reverse(&self) -> String {\r\n self.chars().rev().collect::()\r\n }\r\n}\r\n\r\ntrait UsizeExt {\r\n fn pow(&self, n: usize) -> usize;\r\n}\r\nimpl UsizeExt for usize {\r\n fn pow(&self, n: usize) -> usize {\r\n return ((*self as u64).pow(n as u32)) as usize;\r\n }\r\n}\r\nfn solve() {\r\n let (N, M, mut k) = get!(usize, usize, usize);\r\n if N % 2 == 1 && M % 2 == 1 {\r\n echo!(\"NO\");\r\n return;\r\n }\r\n\r\n let mut map = vec![vec!['!'; M]; N];\r\n if N % 2 == 1 {\r\n for i in 0..M {\r\n if i % 2 == 0 && k > 0 {\r\n map[0][i] = '1';\r\n map[0][i + 1] = '1';\r\n k -= 1;\r\n }\r\n }\r\n }\r\n\r\n for i in 0..N {\r\n for j in 0..M {\r\n if i + 1 < N && j + 1 < M && i % 2 == N % 2 && map[i][j] == '!' && k > 0 {\r\n map[i][j] = '1';\r\n map[i][j + 1] = '1';\r\n k -= 1;\r\n if k > 0 {\r\n map[i + 1][j] = '1';\r\n map[i + 1][j + 1] = '1';\r\n k -= 1;\r\n }\r\n }\r\n }\r\n }\r\n for i in 0..N {\r\n for j in 0..M {\r\n if i + 1 < N && i % 2 == N % 2 && map[i][j] == '!' {\r\n map[i][j] = '0';\r\n map[i + 1][j] = '0';\r\n }\r\n }\r\n }\r\n mydbg!(map);\r\n\r\n for i in 0..N {\r\n for j in 0..M {\r\n if map[i][j] == '!' {\r\n echo!(\"NO\");\r\n return;\r\n }\r\n }\r\n }\r\n if k != 0 {\r\n echo!(\"NO\");\r\n } else {\r\n echo!(\"YES\");\r\n }\r\n}\r\n\r\nfn main() {\r\n let T = get!(usize);\r\n for testcase in 0..T {\r\n mydbg!(testcase);\r\n let mut ans: u64 = 0;\r\n solve();\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "5e62b31a804c2be2a08b5341eb5aab59", "src_uid": "4d0c0cc8faca62eb6384f8135b30feb8", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused)]\r\nuse std::fs::write;\r\nuse std::io::{self, stdin, stdout, BufWriter, Write};\r\n\r\nfn run() {\r\n let mut scan = Scanner::default();\r\n let out = &mut BufWriter::new(stdout());\r\n\r\n let t = scan.next::();\r\n for _ in 0..t {\r\n let mut n = scan.next::();\r\n let mut m = scan.next::();\r\n let mut kh = scan.next::();\r\n let mut kv = (m * n) / 2 - kh;\r\n if n & 1 == 1 {\r\n kh -= m / 2;\r\n if kh < 0 {\r\n writeln!(out, \"{}\", \"NO\").unwrap();\r\n continue;\r\n }\r\n }\r\n if m & 1 == 1 {\r\n kv -= n / 2;\r\n if kv < 0 {\r\n writeln!(out, \"{}\", \"NO\").unwrap();\r\n continue;\r\n }\r\n }\r\n if kh & 1 == 1 && kv & 1 == 1 {\r\n writeln!(out, \"{}\", \"NO\").unwrap();\r\n continue;\r\n }\r\n writeln!(out, \"{}\", \"YES\").unwrap();\r\n }\r\n // writeln!(out, \"{}\", \"done\");\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n\r\n#[derive(Default)]\r\nstruct Scanner {\r\n buffer: Vec,\r\n}\r\nimpl Scanner {\r\n fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().expect(\"Failed parse\");\r\n }\r\n let mut input = String::new();\r\n stdin().read_line(&mut input).expect(\"Failed read\");\r\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\r\n }\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "5c7b7252d66033acb22cda352dc12974", "src_uid": "4d0c0cc8faca62eb6384f8135b30feb8", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "struct Scanner {\n reader: R,\n line: Vec,\n ptr: usize\n\n}\n\nimpl Scanner {\n fn new(reader: R) -> Self {\n return Self {reader, line: vec![], ptr: 0};\n }\n\n fn scan(&mut self) -> T {\n loop {\n while self.ptr < self.line.len() && self.line[self.ptr].is_ascii_whitespace() {\n self.ptr += 1;\n }\n if self.ptr != self.line.len() {\n let start = self.ptr;\n while self.ptr < self.line.len() && !self.line[self.ptr].is_ascii_whitespace() {\n self.ptr += 1;\n }\n return std::str::from_utf8(&self.line[start..self.ptr]).unwrap().parse().ok().\n expect(\"parse error\");\n }\n self.line.clear();\n self.reader.read_until(b'\\n', &mut self.line).expect(\"read error\");\n self.ptr = 0;\n }\n }\n\n}\n\nfn solve_even(n: usize, m: usize, mut k: usize) -> Option>> {\n if k % 2 == 1 {\n return None;\n }\n let mut field = vec![vec![0u8; m]; n];\n for i in (0..n).step_by(2) {\n for j in (0..m).step_by(2) {\n if k != 0 {\n field[i][j] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i][j + 1] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i + 1][j] = ((i + 1) % 3 * 3 + j % 3) as u8 + b'a';\n field[i + 1][j + 1] = ((i + 1) % 3 * 3 + j % 3) as u8 + b'a';\n k -= 2;\n } else {\n field[i][j] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i + 1][j] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i][j + 1] = (i % 3 * 3 + (j + 1) % 3) as u8 + b'a';\n field[i + 1][j + 1] = (i % 3 * 3 + (j + 1) % 3) as u8 + b'a';\n }\n }\n }\n return Some(field);\n}\n\nfn solve_odd(n: usize, m: usize, mut k: usize) -> Option>> {\n if k < m / 2 || (k - m / 2) % 2 == 1 {\n return None;\n }\n let mut field = vec![vec![0u8; m]; n];\n for i in (0..m).step_by(2) {\n field[0][i] = (i % 3) as u8 + b'a';\n field[0][i + 1] = (i % 3) as u8 + b'a';\n k -= 1;\n }\n for i in (1..n).step_by(2) {\n for j in (0..m).step_by(2) {\n if k != 0 {\n field[i][j] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i][j + 1] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i + 1][j] = ((i + 1) % 3 * 3 + j % 3) as u8 + b'a';\n field[i + 1][j + 1] = ((i + 1) % 3 * 3 + j % 3) as u8 + b'a';\n k -= 2;\n } else {\n field[i][j] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i + 1][j] = (i % 3 * 3 + j % 3) as u8 + b'a';\n field[i][j + 1] = (i % 3 * 3 + (j + 1) % 3) as u8 + b'a';\n field[i + 1][j + 1] = (i % 3 * 3 + (j + 1) % 3) as u8 + b'a';\n }\n }\n }\n return Some(field);\n}\n\nfn transpose(old: Vec>) -> Vec> {\n let mut field = vec![vec![0u8; old.len()]; old[0].len()];\n for i in 0..old.len() {\n for j in 0..old[i].len() {\n field[j][i] = old[i][j];\n }\n }\n return field;\n}\n\nfn solve(scanner: &mut Scanner, writer: &mut W) {\n let n: usize = scanner.scan();\n let m: usize = scanner.scan();\n let k: usize = scanner.scan();\n if n % 2 == 0 && m % 2 == 0 {\n if let Some(field) = solve_even(n, m, k) {\n writeln!(writer, \"YES\").unwrap();\n } else {\n writeln!(writer, \"NO\").unwrap();\n }\n return;\n }\n let field = if n % 2 == 1 {\n solve_odd(n, m, k)\n } else {\n let cur = solve_odd(m, n, n * m / 2 - k);\n if let Some(cur) = cur {\n Some(transpose(cur))\n } else {\n None\n }\n };\n if let Some(field) = field {\n writeln!(writer, \"YES\").unwrap();\n } else {\n writeln!(writer, \"NO\").unwrap();\n }\n}\n\nfn main() {\n let (stdin, stdout) = (std::io::stdin(), std::io::stdout());\n let mut writer = std::io::BufWriter::new(stdout.lock());\n let mut scanner = Scanner::new(stdin.lock());\n let tests: usize = scanner.scan();\n for _ in 0..tests {\n solve(&mut scanner, &mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "d65cd3dc3dd2c7b0949961555871870b", "src_uid": "4d0c0cc8faca62eb6384f8135b30feb8", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n\n let mut input = input.trim().split(' ');\n let mut shoes = [i32::default();2];\n shoes[0] = input.next().unwrap().parse::().unwrap();\n shoes[1] = input.next().unwrap().parse::().unwrap();\n\n if shoes[0] > shoes[1] {\n shoes.swap(0, 1);\n }\n\n let fashion = shoes[0];\n let normal = (shoes[1] - fashion) / 2;\n\n println!(\"{} {}\", fashion, normal);\n\n\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "91a5475d15a5e633db7aad851ea330ad", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n red_socks: u32,\n blue_socks: u32,\n }\n\n let x = std::cmp::min(red_socks, blue_socks);\n let y = ((red_socks - x) + (blue_socks - x)) / 2;\n\n println!(\"{} {}\", x, y)\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "66caecb1c42a4ce7d8b31d5aef723e7e", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (i64, i64) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\nfn main() {\n \n let (a, b) = read_line_pair();\n\n let p1 = std::cmp::min(a, b);\n let p2 = ((a + b) - p1 - p1) / 2;\n\n println!(\"{} {}\", p1, p2);\n\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "6b0f8c95df0fe5b232acca4c4e0a1efb", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (a,b) = readln!(i32,i32);\n println!(\"{} {}\",std::cmp::min(a,b),(a+b-std::cmp::min(a,b)*2)/2);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "339284737bd67113ce465a189a5c804c", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s)\n .expect(\"failed to read l2\");\n\n let values = s\n .split_whitespace()\n .map(|x| x.parse::())\n .collect::, _>>()\n .unwrap();\n\n assert!(values.len() == 2);\n let a = values[0];\n let b = values[1];\n\n let min = cmp::min(a,b);\n let rest_same_color_pairs = (cmp::max(a,b) - min) / 2;\n\n println!(\"{} {}\", min, rest_same_color_pairs);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "08e5d4eda37bd9e9f234a6f84c4783bf", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::cmp;\n\nfn main() {\n\n let (a, b) = R!(usize, usize);\n\n println!(\"{} {}\", cmp::min(a, b), (cmp::max(a, b) - cmp::min(a, b)) / 2);\n\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "5249357b097fded43c4967b7881b4087", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io;\n\nfn get_line() -> io::Result {\n\tlet mut buffer = String::new();\n\tio::stdin().read_line(&mut buffer)?;\n\tOk(buffer)\n}\n\nfn main() -> Result<(), Box> {\n\tlet input = get_line()?\n\t\t.split_whitespace()\n\t\t.map(|s| s.parse::())\n\t\t.collect::, _>>()?;\n\tlet diff = input[0].min(input[1]);\n\tlet same = (input[0].max(input[1]) - diff) / 2;\n\tprint!(\"{} {}\", diff, same);\n\tOk(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "32265f827ac101a46db9cbb54843814b", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::BufRead;\nuse std::cmp;\n\nfn main() {\n let reader = io::stdin();\n\n let parts:Vec = \n reader.lock()\n .lines().next().unwrap().unwrap()\n .split_whitespace()\n .filter(|s| !s.is_empty())\n .map(|s| s.parse::().unwrap())\n .collect();\n \n let a:i8 = parts[0];\n let b:i8 = parts[1];\n\n println!(\"{} {}\", cmp::min(a, b), (a-b).abs() / 2 );\n\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "fd4ff731f65fa390a42fe94001509282", "src_uid": "775766790e91e539c1cfaa5030e5b955", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let n: i32 = input.trim().parse().unwrap();\n let mut segs: Vec<(i32, i32, i32)> = vec![];\n\n for i in 0..(n+1) {\n for j in (i+1)..(n+1) {\n segs.push((j-i,i,j));\n }\n }\n segs.sort();\n let mut result: i32 = 0;\n let mut flags: Vec = vec![false; segs.len()];\n for i in (0..segs.len()).rev() {\n if flags[i] { continue; }\n let (size, mut a, mut b) = segs[i];\n flags[i] = true;\n let mut cur: i32 = size;\n while cur < n {\n let mut did_something = false;\n for j in (0..segs.len()).rev() {\n if flags[j] { continue; }\n let (s, c, d) = segs[j];\n if a == d || b == c {\n if cur + s <= n {\n a = cmp::min(a, c);\n b = cmp::max(b, d);\n cur += s;\n flags[j] = true;\n did_something = true;\n }\n }\n }\n if !did_something { break; }\n }\n result += 1;\n }\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "bfd6589c89902a5c46caaf4dea1ff14f", "src_uid": "f8af5dfcf841a7f105ac4c144eb51319", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let n: i32 = input.trim().parse().unwrap();\n let mut segs: Vec<(i32, i32, i32)> = vec![];\n for i in 0..(n+1) {\n for j in (i+1)..(n+1) {\n segs.push((j-i,i,j));\n }\n }\n segs.sort();\n let mut result: i32 = 0;\n let mut flags: Vec = vec![false; segs.len()];\n for i in (0..segs.len()).rev() {\n if flags[i] { continue; }\n let (size, mut a, mut b) = segs[i];\n flags[i] = true;\n let mut cur: i32 = size;\n while cur < n {\n let mut did_something = false;\n for j in (0..segs.len()).rev() {\n if flags[j] { continue; }\n let (s, c, d) = segs[j];\n if a == d || b == c {\n if cur + s <= n {\n a = cmp::min(a, c);\n b = cmp::max(b, d);\n cur += s;\n flags[j] = true;\n did_something = true;\n }\n }\n }\n if !did_something { break; }\n }\n result += 1;\n }\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "f967809babe6b359ed1b22df12083be8", "src_uid": "f8af5dfcf841a7f105ac4c144eb51319", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let zandaka: String = read(sin);\n\n if Some('-') != zandaka.as_str().chars().nth(0) {\n println!(\"{}\", zandaka);\n return;\n }\n\n let remove_last: String = zandaka\n .as_str()\n .chars()\n .enumerate()\n .filter(|(idx, _c)| *idx != (zandaka.len() - 1))\n .map(|(_idx, c)| c)\n .collect();\n\n let rl_num: i64 = remove_last.parse().unwrap();\n let moto: i64 = zandaka.parse().unwrap();\n\n let mut cmax = std::cmp::max(moto, rl_num);\n\n if 2 < zandaka.len() {\n let remove_before_last: String = zandaka\n .as_str()\n .chars()\n .enumerate()\n .filter(|(idx, _c)| *idx != (zandaka.len() - 2))\n .map(|(_idx, c)| c)\n .collect();\n\n let rbl_num: i64 = remove_before_last.parse().unwrap();\n\n cmax = std::cmp::max(cmax, rbl_num);\n }\n\n println!(\"{}\", cmax)\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "a3db8037da806a7058248fcf0aa0a2a2", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let n = s.trim().parse::().unwrap();\n\n if n >= 0 {\n println!(\"{}\", n);\n return;\n }\n\n if n > -10 {\n println!(\"0\");\n return;\n }\n\n let last_digit = (n % 10).abs();\n let second_last_digit = ((n % 100) / 10).abs();\n\n println!(\"{}\", (n/100)*10 -\n std::cmp::min(last_digit, second_last_digit));\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "62c612d4040cfcdddb735472e91b1adf", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::{Write};\nuse std::str;\n\n/// Reads white-space separated tokens one at a time.\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n /// Use \"turbofish\" syntax token::() to select data type of next token.\n ///\n /// # Panics\n ///\n /// Panics if there's an I/O error or if the token cannot be parsed as T.\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\npub fn scanner_from_file(filename: &str) -> Scanner> {\n let file = std::fs::File::open(filename).expect(\"Input file not found\");\n Scanner::new(io::BufReader::new(file))\n}\n\npub fn writer_to_file(filename: &str) -> io::BufWriter {\n let file = std::fs::File::create(filename).expect(\"Output file not found\");\n io::BufWriter::new(file)\n}\n\n#[allow(dead_code)]\nfn max(a: T, b: T) -> T {\n if a > b { a } else { b }\n}\n\n#[allow(dead_code)]\nfn min(a: T, b: T) -> T {\n if a < b { a } else { b }\n}\n\nfn solve() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n let n = scan.token::();\n if n > 0 {\n out.write(format!(\"{}\", n).as_bytes()).unwrap();\n } else {\n out.write(format!(\"{}\", max(n/10, (n/100)*10 + n%10)).as_bytes()).unwrap();\n }\n // let k = scan.token::();\n // let mut arr = scan.token::().chars().collect::>();\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(64 * 1024 * 1024)\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n}", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "ba769065df8bfe008744bdb70f297d64", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: isize = scan.next();\n if n >= 0 {\n println!(\"{}\", n);\n } else {\n let x: String = n.to_string();\n if x.len() == 2 {\n println!(\"0\");\n } else {\n let mut x1: String = x.clone();\n let x1len = x1.len();\n x1.remove(x1len - 1);\n let x1: isize = x1.parse().unwrap();\n let mut x2: String = x.clone();\n let x2len = x2.len();\n x2.remove(x2len - 2);\n let x2: isize = x2.parse().unwrap();\n println!(\"{}\", x1.max(x2));\n }\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "642b3a47fb9b96df18de39c39f34cd3e", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn fix(balance: i64) -> i64 {\n if balance >= 0 {\n return balance;\n }\n\n let temp = -balance;\n let last_dig = temp % 10;\n let seclast_dig = (temp / 10) % 10;\n\n if last_dig > seclast_dig {\n balance / 10\n } else {\n balance / 100 * 10 - last_dig\n }\n}\n\nfn main() {\n let balance: i64 = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n };\n\n let balance = fix(balance);\n println!(\"{}\", balance);\n}", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "9ada76de770b54bd099b5ec09c9040ef", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_num() -> isize {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n isize::from_str(input.trim()).unwrap()\n}\n\nfn main() {\n let n = get_num();\n\n let m = n / 10;\n let o = n % 10 + n / 100 * 10;\n println!(\"{}\", std::cmp::max(n, std::cmp::max(m, o)));\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "1c5403d9d76b671831e5fb26dcdb943c", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::cmp;\n\nfn main() {\n let (n, ) = R!(i32);\n println!(\"{}\", cmp::max(n, cmp::max(n/10, n/100*10+n%10)));\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "9a617a2eb43fb071ebc9b6eb2e71bb4a", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let arr: Vec = scan.next_n(n);\n if arr.len() == 1 {\n if arr[0] == 0 {\n println!(\"UP\");\n } else if arr[0] == 15 {\n println!(\"DOWN\");\n } else {\n println!(\"-1\");\n }\n return;\n }\n let last = arr[arr.len() - 1];\n let last2 = arr[arr.len() - 2];\n if last2 != 14 && last != 15 && (last > last2 || last == 0 && last2 == 1) {\n println!(\"UP\");\n } else {\n println!(\"DOWN\");\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "dc4fe35e674fbcee30ea7885424e1d34", "src_uid": "8330d9fea8d50a79741507b878da0a75", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let a = input.vi(n);\n let sol = if n == 1 && a[0] % 15 > 0 {\n \"-1\"\n } else if a[n-1] == 0 || (a[n-1] != 15 && a[n-2] < a[n-1]) {\n \"UP\"\n } else {\n \"DOWN\"\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "218ae4e86ed13a1d9a50fbcf740bb517", "src_uid": "8330d9fea8d50a79741507b878da0a75", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::cmp::{min, max};\nuse std::mem;\nuse std::str::FromStr;\nuse std::cmp::Ordering;\nuse std::collections::BinaryHeap;\n\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Scanner {\n Scanner {\n reader: reader,\n buffer: Vec::new(),\n }\n }\n\n /// Use \"turbofish\" syntax next::() to select data type of next token.\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n\n pub fn next_vec(&mut self, len: usize) -> Vec\n where\n T::Err: ::std::fmt::Debug,\n {\n (0..len).map(|_| self.next::()).collect::>()\n }\n}\n\nfn main1() {\n let stdin = io::stdin();\n let mut input = Scanner::new(stdin.lock());\n let n = input.next::();\n let a = input.next_vec::(n);\n if a[n - 1] == 15 {\n println!(\"DOWN\");\n } else if a[n - 1] == 0 {\n println!(\"UP\");\n } else {\n if n == 1 {\n println!(\"-1\");\n } else if a[n - 2] < a[n - 1] {\n println!(\"UP\");\n } else {\n println!(\"DOWN\");\n }\n }\n\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b23f78353f6d3bc3f1fd05ae62239225", "src_uid": "8330d9fea8d50a79741507b878da0a75", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n \tlet mut input = String::new(); \n let stdin = io::stdin();\n \tstdin.read_line(&mut input).unwrap();\n \tlet n = input.trim().parse::().unwrap();\n\tlet mut v: Vec = Vec::new();\ninput.clear();\n \tstdin.read_line(&mut input)\n .expect(\"correct input\");\n\tfor u in input.trim().split(' ') {\n let cur_txt = u.trim();\n if cur_txt.len() > 0 {\n let cur_num: i32 = cur_txt.parse().unwrap();\n v.push(cur_num);\n }\n }\n if n == 1 {\n \tif v[0] == 15 {\n\t\t\tprintln!(\"DOWN\");\n\t\t} else if v[0] == 0 {\n\t\t\tprintln!(\"UP\");\n\t\t} else {\n\t\t\tprintln!(\"-1\");\n\t\t}\n } else {\n \tif v[n-1] == 15 {\n\t\t\tprintln!(\"DOWN\");\n\t\t} else if v[n-1] == 0 {\n\t\t\tprintln!(\"UP\");\n\t\t} else if v[n-2] > v[n-1] {\n\t\t\tprintln!(\"DOWN\");\n\t\t} else {\n\t\t\tprintln!(\"UP\");\n\t\t}\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8dea8bdc996a6ca3273e5e106b673060", "src_uid": "8330d9fea8d50a79741507b878da0a75", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::collections::{*};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n \nfn main() {\n let mut scanner = Scanner::default();\n let mut n: u128 = scanner.next();\n let mut week: Vec = (1..=7).map(|_| scanner.next()).collect();\n let mut cur: u128 = 0;\n let mut i: usize = 0;\n while cur < n {\n \tcur += week[i];\n \tif cur >= n {\n \t\tprintln![\"{}\", i+1];\n \t}\n \ti += 1;\n \ti %= 7;\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8b27adb6c0bb47ad43abf8a464cc15a3", "src_uid": "007a779d966e2e9219789d6d9da7002c", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn main() {\n let n: u32 = get_input().parse().unwrap();\n let days: Vec = get_input().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect();\n let total: u32 = days.iter().sum();\n //println!(\"total is {}\", total);\n let m = {\n if total > n {\n n\n } else if total == n || n % total == 0 {\n total\n } else {\n n % total\n }\n };\n\n let mut c = 0;\n\n //println!(\"mod is {}\", m);\n for i in 0..days.len() {\n //println!(\"c is {}\", c);\n c += days[i];\n\n if c >= m {\n println!(\"{}\", i+1);\n break;\n }\n }\n}\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer.trim().to_owned()\n}\n\nfn get_input_usize() -> usize {\n get_input().parse().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6dccf5c8eaa9865b8b4c60982bf084bf", "src_uid": "007a779d966e2e9219789d6d9da7002c", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\n// type Matrix = Vec>;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\n\nfn main() {\n let mut n: u32 = read_line().parse().unwrap();\n let week = read_line_vec();\n let s: u32 = week.iter().sum();\n \n n = ((n - 1) % s) + 1;\n \n for i in 0..week.len() {\n if n <= week[i] {\n println!(\"{}\", i + 1);\n break;\n }\n n -= week[i];\n }\n \n \n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1cb2e44bd36d9d6cebcb8cf5c7686b5c", "src_uid": "007a779d966e2e9219789d6d9da7002c", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, Read, StdinLock};\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::collections::{HashSet, HashMap, BinaryHeap};\n#[allow(unused_imports)]\nuse std::vec::Vec;\n\n#[allow(dead_code)]\nconst INF: i32 = 1000_000_000;\n#[allow(dead_code)]\nconst INFLL: i64 = 1000_000_000_000_000_000;\n#[allow(dead_code)]\nconst EPS: f64 = 1.0e-10;\n#[allow(dead_code)]\nconst MOD: i32 = 1000_000_007;\n\nstruct Scanner<'a> {\n cin: StdinLock<'a>,\n}\n\nimpl<'a> Scanner<'a> {\n #[allow(dead_code)]\n fn new(cin: StdinLock<'a>) -> Scanner<'a> {\n Scanner {cin: cin}\n }\n\n #[allow(dead_code)]\n fn read1(&mut self) -> Option {\n let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect::();\n token.parse::().ok()\n }\n\n #[allow(dead_code)]\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\nfn main() {\n let cin = stdin();\n let cin = cin.lock();\n let mut sc = Scanner::new(cin);\n\n let n: i64 = sc.read();\n let max_r = 9 * (n + 1) - n;\n let mut min_r: i64 = i64::max_value();\n for a in 2..n+2 {\n if (a - 1) * (a - 1) > n {\n break;\n }\n if n % (a - 1) != 0 {\n continue;\n }\n let m = n / (a - 1);\n for b in 3..m+3 {\n if (b - 2) * (b - 2) > m {\n break;\n }\n if m % (b - 2) == 0 {\n let c = m / (b - 2) + 2;\n min_r = min(min_r, a * b * c - n);\n }\n }\n }\n \n println!(\"{} {}\", min_r, max_r);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "3bae093e4c3e00a44fbe4027f8c99c88", "src_uid": "2468eead8acc5b8f5ddc51bfa2bd4fb7", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn main() {\n let mut input = String::new();\n std::io::stdin().read_to_string(&mut input).expect(\"Err: read line failed\");\n let vec = input.lines().map(|line| {\n line.trim().split_whitespace().map(|word| {\n word.parse::().expect(\"Err: parse to i32 failed\")\n }).collect::>()\n }).collect::>>();\n\n for number in &vec[1] {\n for digit in &vec[2] {\n if digit == number {\n print!(\"{} \", &digit);\n }\n }\n }\n\n println!(\"\");\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "06211ab95019823a627d3e18ac7c4c40", "src_uid": "f9044a4b4c3a0c2751217d9b31cd0c72", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// A. Fingerprints\n// http://codeforces.com/problemset/problem/994/A\n\n\n\nfn main() {\n let stdin = std::io::stdin();\n let mut buf = String::new();\n\n stdin.read_line(&mut buf).unwrap();\n let mut buf = String::new();\n stdin.read_line(&mut buf).unwrap();\n \n let xs = \n buf.split_whitespace().filter_map(|s| s.parse::().ok());\n let mut buf = String::new();\n stdin.read_line(&mut buf).unwrap();\n let set: std::collections::HashSet = \n buf.split_whitespace().filter_map(|s| s.parse::().ok()).collect();\n\n xs.filter(|x| set.contains(&x)).for_each(|x| print!(\"{} \", x));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9a001dfdb6cf7ecfd9e3007e13e2884e", "src_uid": "f9044a4b4c3a0c2751217d9b31cd0c72", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\nuse std::collections::*; // HashSet, HashMap, BTreeSet, BTreeMap, ...\n\nfn main() {\n let stdin: io::Stdin = io::stdin();\n let mut lines: io::Lines = stdin.lock().lines();\n\n #[allow(unused_assignments)]\n let mut next_line = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n next_line = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let flv: Vec = next_line\n .trim()\n .split(' ')\n .map(|n| {\n n.parse().unwrap()\n })\n .collect();\n\n next_line = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let slh: HashSet = next_line\n .trim()\n .split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n \n let mut ans: String = String::new();\n\n for n in flv.iter() {\n if slh.contains(&n) {\n ans.push_str(\" \");\n ans.push_str(&n.to_string());\n }\n }\n\n println!(\"{}\", ans.trim());\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "83ad988cf3cb836c47a977e7e9e1627c", "src_uid": "f9044a4b4c3a0c2751217d9b31cd0c72", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\n/* \nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n*/\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ----------\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let n: usize = s.trim().parse().unwrap();\n let mut len = 0;\n while (2 << len) <= n {\n len += 1;\n }\n let mut cnt = vec![0; len + 2];\n for i in 0..=len {\n cnt[i] = n / (1 << i);\n }\n let mut dp = vec![ModInt::zero(); len + 2];\n dp[len] = ModInt::one();\n for i in 1..n {\n let mut next = vec![ModInt::zero(); len + 2];\n for j in 0..len {\n if cnt[j] > i {\n next[j] += dp[j] * ModInt((cnt[j] - i) as u32);\n next[j] += dp[j + 1] * ModInt((cnt[j] - cnt[j + 1]) as u32);\n }\n }\n dp = next;\n }\n let mut ans = dp[0];\n if (1 << len) / 2 * 3 <= n {\n let len = len - 1;\n let mut cnt = vec![vec![0; len + 2]; 2];\n for i in 0..=len {\n cnt[0][i] = n / (1 << i);\n cnt[1][i] = n / (1 << i) / 3;\n }\n let mut dp = vec![vec![ModInt::zero(); len + 2]; 2];\n dp[1][len] = ModInt::one();\n for i in 1..n {\n let mut next = vec![vec![ModInt::zero(); len + 2]; 2];\n for j in 0..=len {\n if cnt[0][j] > i {\n next[0][j] += dp[0][j] * ModInt((cnt[0][j] - i) as u32);\n next[0][j] += dp[1][j] * ModInt((cnt[0][j] - cnt[1][j]) as u32);\n next[0][j] += dp[0][j + 1] * ModInt((cnt[0][j] - cnt[0][j + 1]) as u32);\n }\n if cnt[1][j] > i {\n next[1][j] += dp[1][j] * ModInt((cnt[1][j] - i) as u32);\n next[1][j] += dp[1][j + 1] * ModInt((cnt[1][j] - cnt[1][j + 1]) as u32);\n }\n }\n dp = next;\n }\n ans += dp[0][0];\n }\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "b9cc20329ca99ff01ad4b4e188273404", "src_uid": "b2d59b1279d891dba9372a52364bced2", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\n/* \nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n*/\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ---------- \n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let n: usize = s.trim().parse().unwrap();\n let mut len = 0;\n while (2 << len) <= n {\n len += 1;\n }\n let mut cnt = vec![0; len + 2];\n for i in 0..=len {\n cnt[i] = n / (1 << i);\n }\n let mut dp = vec![ModInt::zero(); len + 2];\n dp[len] = ModInt::one();\n for i in 1..n {\n let mut next = vec![ModInt::zero(); len + 2];\n for j in 0..len {\n if cnt[j] > i {\n next[j] += dp[j] * ModInt((cnt[j] - i) as u32);\n next[j] += dp[j + 1] * ModInt((cnt[j] - cnt[j + 1]) as u32);\n }\n }\n dp = next;\n }\n let mut ans = dp[0];\n if (1 << len) / 2 * 3 <= n {\n let len = len - 1;\n let mut cnt = vec![vec![0; len + 2]; 2];\n for i in 0..=len {\n cnt[0][i] = n / (1 << i);\n cnt[1][i] = n / (1 << i) / 3;\n }\n let mut dp = vec![vec![ModInt::zero(); len + 2]; 2];\n dp[1][len] = ModInt::one();\n for i in 1..n {\n let mut next = vec![vec![ModInt::zero(); len + 2]; 2];\n for j in 0..=len {\n if cnt[0][j] > i {\n next[0][j] += dp[0][j] * ModInt((cnt[0][j] - i) as u32);\n next[0][j] += dp[1][j] * ModInt((cnt[0][j] - cnt[1][j]) as u32);\n next[0][j] += dp[0][j + 1] * ModInt((cnt[0][j] - cnt[0][j + 1]) as u32);\n }\n if cnt[1][j] > i {\n next[1][j] += dp[1][j] * ModInt((cnt[1][j] - i) as u32);\n next[1][j] += dp[1][j + 1] * ModInt((cnt[1][j] - cnt[1][j + 1]) as u32);\n }\n }\n dp = next;\n }\n ans += dp[0][0];\n }\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "eacfebe7aa568935a11fd6efac65ecd3", "src_uid": "b2d59b1279d891dba9372a52364bced2", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let mut line = String::new();\n std::io::stdin()\n .read_line(&mut line)\n .expect(\"Could not read line\");\n String::from(&line[..line.len() - 1])\n}\n\nmacro_rules! read_line {\n ([$t: ty]) => {{\n read_line().split_whitespace().map(|token| {\n <$t as std::str::FromStr>::from_str(token).expect(\n &format!(concat!(\"Could not parse {} into \", stringify!($t)), token))\n })\n }};\n ($($t: ty),*) => {{\n let line = read_line();\n let mut iter = line.split_whitespace();\n ($({\n let token = iter.next().expect(\"Not enough tokens\");\n <$t as std::str::FromStr>::from_str(token).expect(\n &format!(concat!(\"Could not parse {} into \", stringify!($t)), token))\n }),*)\n }};\n}\n\nfn main() {\n read_line!(usize);\n enum State {\n Up,\n Hold,\n Down,\n }\n let mut state = State::Up;\n let mut prev = 0;\n let mut ans = true;\n for x in read_line!([u16]) {\n match state {\n State::Hold => {\n if x > prev {\n ans = false;\n break;\n }\n }\n State::Down => {\n if x >= prev {\n ans = false;\n break;\n }\n }\n State::Up => {}\n }\n state = if x < prev {\n State::Down\n } else if x > prev {\n State::Up\n } else {\n State::Hold\n };\n prev = x;\n }\n println!(\"{}\", if ans { \"YES\" } else { \"NO\" });\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5e2cf446755d8292a7f83f9de6254582", "src_uid": "5482ed8ad02ac32d28c3888299bf3658", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io;\nuse std::process;\n\nfn main() {\n if let Err(e) = run() {\n println!(\"{}\", e);\n process::exit(1);\n }\n}\n\nfn run() -> Result<(), Box> {\n let mut n = String::new();\n io::stdin().read_line(&mut n)?;\n let mut n: usize = n.trim().parse()?;\n let mut a = String::new();\n io::stdin().read_line(&mut a)?;\n let mut a: Vec<&str> = a\n .trim()\n .split(\" \")\n .collect();\n let mut cur = 0;\n let mut pre = 0;\n let mut inc = false;\n let mut con = false;\n let mut dec = false;\n for i in 0..n {\n if i == 0 {\n cur = a[i].parse()?;\n continue;\n }\n pre = cur;\n cur = a[i].parse()?;\n if pre < cur {\n if con || dec {\n println!(\"NO\");\n return Ok(());\n }\n inc = true;\n } else if pre == cur {\n if dec {\n println!(\"NO\");\n return Ok(());\n }\n con = true;\n } else {\n dec = true;\n }\n }\n println!(\"YES\");\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7733aa4b8b54167e04e0aedeb00fe01c", "src_uid": "5482ed8ad02ac32d28c3888299bf3658", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n \n use std::io::stdin;\n\n stdin().read_line(&mut input).unwrap();\n let mut input = String::new();\n\n stdin().read_line(&mut input).unwrap();\n\n let a: Vec = input.split_whitespace().map(|c| c.parse().unwrap()).collect();\n\n let cnt = a.iter().skip(1).zip(a.iter()).skip_while(|&(b, a)| b > a).skip_while(|&(b, a)| b == a).skip_while(|&(b, a)| b < a).count();\n\n if cnt > 0 {\n println!(\"NO\");\n } else {\n println!(\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "047b951af00a83b973fb5fb3766b62b3", "src_uid": "5482ed8ad02ac32d28c3888299bf3658", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::VecDeque;\n\nfn main() {\n let m: f32 = get_input().split_ascii_whitespace().last().unwrap().parse().unwrap();\n let children: Vec = get_input().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect();\n\n let mut max = 0f32;\n let candies: Vec = children.iter().enumerate().map(|(index, value)| {\n let candy = Candy::new((value / m).ceil(), index + 1);\n if candy.value > max {\n max = candy.value;\n }\n candy\n }).collect();\n\n let mut iter = candies.iter();\n let mut next_from_back = iter.next_back().unwrap();\n\n while next_from_back.value != max {\n next_from_back = iter.next_back().unwrap();\n }\n\n println!(\"{:?}\", next_from_back.index);\n}\n\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer.trim().to_owned()\n}\n\nfn get_input_usize() -> usize {\n get_input().parse().unwrap()\n}\n\n#[derive(Debug)]\nstruct Candy {\n value: f32, \n index: usize,\n}\n\nimpl Candy {\n pub fn new(value: f32, index: usize) -> Self {\n Candy {\n value, \n index\n }\n } \n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6a1bc86ca9d2b11cb4eb9fc5a9a0ee3d", "src_uid": "c0ef1e4d7df360c5c1e52bc6f16ca87c", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let m = input.i();\n let (a,_) = input.vi(n).into_iter().map(|x| (x + m - 1) / m).\n enumerate().fold((0,0), |(a,x),(b,y)| {\n if x > y { (a,x) } else { (b,y) }\n });\n println!(\"{}\", a + 1);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "58cb6110df198ecb7d76239571c29145", "src_uid": "c0ef1e4d7df360c5c1e52bc6f16ca87c", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::VecDeque;\n\nfn main() {\n let m: i32 = get_input().split_ascii_whitespace().last().unwrap().parse().unwrap();\n let children: Vec = get_input().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect();\n\n let candies: Vec = children.iter().enumerate().map(|(index, value)| {\n let candy = Candy::new(*value, index + 1);\n candy\n }).collect();\n\n let mut stack = VecDeque::new();\n\n for candy in candies {\n stack.push_back(candy);\n };\n\n while stack.len() > 1 {\n let next = stack.pop_front().unwrap();\n let temp = next.value - m;\n\n if temp > 0 {\n stack.push_back(Candy::new(temp, next.index));\n }\n }\n \n\n println!(\"{}\", stack.pop_front().unwrap().index);\n}\n\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer.trim().to_owned()\n}\n\nfn get_input_usize() -> usize {\n get_input().parse().unwrap()\n}\n\n#[derive(Debug)]\nstruct Candy {\n value: i32, \n index: usize,\n}\n\nimpl Candy {\n pub fn new(value: i32, index: usize) -> Self {\n Candy {\n value, \n index\n }\n } \n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "863f529b938e04c38c70d9e008896bb5", "src_uid": "c0ef1e4d7df360c5c1e52bc6f16ca87c", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn reads(i: &mut StdinLock) -> Vec {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\nfn gcd_worker(a: u64, b: u64) -> u64 {\n match b {\n 0 => a,\n _ => gcd_worker(b, a % b),\n }\n}\n\nfn gcd(a: u64, b: u64) -> u64 {\n let greater = std::cmp::max(a, b);\n let smaller = std::cmp::min(a, b);\n gcd_worker(greater, smaller)\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let params: Vec = reads(sin);\n\n let a = params[0];\n let b = params[1];\n let heap = params[2];\n\n let mut remain = heap;\n let mut turn_of_antisimon = false;\n\n loop {\n let have_to_take = gcd(if turn_of_antisimon { b } else { a }, remain);\n if remain < have_to_take {\n break;\n }\n\n remain = remain - have_to_take;\n turn_of_antisimon = !turn_of_antisimon;\n }\n\n println!(\"{}\", if turn_of_antisimon { 0 } else { 1 });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5b37fd997834ee3706c43fb78c11a823", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn readln() -> Vec {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n\n line.split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect()\n}\n\nfn gcd(mut a : i32, mut b : i32) -> i32 {\n while a > 0 && b > 0 {\n if a > b {\n a %= b;\n }\n else {\n b %= a;\n }\n }\n a + b\n}\n\nfn main() {\n let input = readln();\n\n let a = input[0];\n let b = input[1];\n let mut n = input[2];\n\n let mut cnt = 0;\n while n > 0 {\n if cnt % 2 == 0 {\n n -= gcd(a, n);\n }\n else {\n n -= gcd(b, n);\n }\n cnt += 1;\n }\n\n println!(\"{}\", if cnt % 2 == 1 {0} else {1});\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c3f0e682fa2d57fac77ad386f3f771b3", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn gcd(a: i32, b: i32) -> i32 {\n if b > 0 {\n gcd(b, a % b)\n } else {\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let a = input.i();\n let b = input.i();\n let x = [b, a];\n let mut n = input.i();\n let mut t: usize = 1;\n while n > 0 {\n n -= gcd(n, x[t]);\n t = 1 - t;\n }\n println!(\"{}\", t);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1fe57f7b1b592432c176195ed651d724", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn pgcd(mut a:i8,mut b:i8) -> i8 {\n while (a != b){\n if a > b {\n a = a -b;\n\n }else{\n b = b - a;\n }}\n return a;\n}\nfn main() {\n let mut line = String::new();\n io::stdin()\n .read_line(&mut line)\n .expect(\"error\");\n\n let line: String = line.trim().parse().expect(\"no\");\n let inputs: Vec = line.split(\" \")\n .map(|x| x.parse().expect(\"Not an integer!\"))\n .collect();\n let mut pgcd_a;\n let mut pgcd_b;\n\n let (mut a, mut b, mut n) = (inputs[0], inputs[1], inputs[2]);\n loop {\n pgcd_a = pgcd(a, n); // 3,9 => 3\n //println!(\"{}\",pgcd_a);\n n = n -pgcd_a; // 9 - 3 = 6\n if pgcd_a > n {\n println!(\"0\");\n break;\n }\n pgcd_b = pgcd(b,n); // 5,6 => 1\n //println!(\"{}\",pgcd_b);\n\n n = n-pgcd_b;\n if pgcd_b > n {\n println!(\"1\");\n break;\n }\n\n }\n}\n\n\n\n\n\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "48afd91e1e3a36808dcb6b9c802c4f6e", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports, deprecated, dead_code)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{VecDeque,HashMap,HashSet,BTreeMap,BTreeSet,BinaryHeap};\n// Module for v1.15.1\nuse std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead\n\n// Functions\nfn gcd(a: u64, b: u64) -> u64 {\n assert!(a != 0 || b != 0);\n if a == 0 {\n return b;\n }\n else {\n return gcd(b%a, a);\n }\n}\n\n// Main\nfn main() {\n\n input! {\n A: u64,\n B: u64,\n mut N: u64,\n }\n\n let mut turn = 0;\n let stones = vec![A,B];\n loop {\n let d = gcd(stones[turn], N);\n if N > d {\n N -= d;\n turn = 1-turn;\n } else if N==d {\n turn = 1-turn;\n break;\n } else {\n break;\n }\n }\n\n println!(\"{}\", 1-turn);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4424a5b7825328ba0412f28d781c5813", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn gcd(a: i32, b: i32) -> i32 {\n if b > 0 {\n gcd(b, a % b)\n } else {\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let a = input.i();\n let b = input.i();\n let mut n = input.i();\n let mut t = 1;\n while n > 0 {\n if t == 1 {\n n -= gcd(a,n);\n } else {\n n -= gcd(b,n);\n }\n t = 1 - t;\n }\n println!(\"{}\", t);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b0bbe78f84a5261a366d7518dfffdb5d", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn gcd(a: i32, b: i32) -> i32 {\n let (mut a, mut b) = if a > b { (b, a) } else { (a, b) };\n while a != 0 {\n let tmp = a;\n a = b % a;\n b = tmp;\n }\n return b;\n}\n\nfn main() {\n let v: Vec = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect()\n };\n let (a, b, mut n) = (v[0], v[1], v[2]);\n\n loop {\n n -= gcd(a, n);\n if n == 0 {\n println!(\"0\");\n break;\n }\n n -= gcd(b, n);\n if n == 0 {\n println!(\"1\");\n break;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "73c30a46850629394a972da25b67efaa", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_ts(stdin : &Stdin, ts : &mut Vec) {\n let mut line = String::new();\n read_line(stdin, &mut line);\n let word_iter = line.split_whitespace();\n for word in word_iter {\n let x = parse_t(word);\n ts.push(x);\n }\n}\n\nfn gcd(x : usize, y : usize) -> usize {\n if x == 0 {\n y\n } else if x <= y {\n let r = y % x;\n gcd(r, x)\n } else {\n gcd(y, x)\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut a_b_n : Vec = vec![];\n read_ts(&stdin, &mut a_b_n);\n let a = a_b_n[0];\n let b = a_b_n[1];\n let n = a_b_n[2];\n let mut num_stones = n;\n let mut player = 0;\n loop {\n if player == 0 {\n let g = gcd(a, num_stones);\n if num_stones < g {\n println!(\"1\");\n break;\n } else {\n player = 1;\n num_stones = num_stones - g;\n }\n } else {\n let g = gcd(b, num_stones);\n if num_stones < g {\n println!(\"0\");\n break;\n } else {\n player = 0;\n num_stones = num_stones - g;\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "cbfb314de245e8dbefb478f150014944", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{self, BufRead};\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! scan_to_vec {\n ($count:expr, $t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n for _ in 0..$count {\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_to_vec: failed at `handle.read_line`.\");\n result.push(buffer.trim().parse::<$t>()\n .expect(\"scan_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line_to_vec {\n ($t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_line(&mut buffer)\n .expect(\"scan_line_to_vec: failed at `handle.read_line`.\");\n \n for s in chunks.split_whitespace() {\n result.push(s.parse::<$t>()\n .expect(\"scan_line_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line {\n () => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n buffer\n });\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\nfn main() {\n let (n,) = scan_line!(i64);\n\n if n % 2 == 0 {\n let result = n / 2 - 1;\n println!(\"{}\", result);\n } else {\n let result = (n + 1) / 2 - 1;\n println!(\"{}\", result);\n }\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms"], "code_uid": "c64b6a7201ee3820b22de7f2dce4c334", "src_uid": "dfe9446431325c73e88b58ba204d0e47", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n println!(\"{}\", (input.i() - 1) / 2);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms"], "code_uid": "92144d36448a50a6ac8186c815789c54", "src_uid": "dfe9446431325c73e88b58ba204d0e47", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//#[derive(Debug)]\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\nuse input::*;\n\n\nfn main() {\n let mut n:i32;\n let mut ans:i32 = 1;\n\n input!(n);\n while n>=10\n {\n ans+=10-n%10;\n n/=10;n+=1;\n while n%10==0 {n/=10;}\n }\n\n p(ans+8);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "cbb90ef71f1b297a1d85b74a69990796", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n// _ _ _ _____ ___\n// _ __ ___ __ _ _ __ | |_ __ _/ / |___ / / _ \\\n// | '_ ` _ \\ / _` | '_ \\| __/ _` | | | |_ \\| | | |\n// | | | | | | (_| | | | | || (_| | | |___) | |_| |\n// |_| |_| |_|\\__,_|_| |_|\\__\\__,_|_|_|____/ \\___/\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n\nuse input::*;\nuse std::collections::HashSet;\n\nfn main() {\n let mut n: usize;\n let mut set = HashSet::new();\n input!(n);\n set.insert(n);\n while n > 0 {\n n += 1;\n while n % 10 == 0 {\n n /= 10;\n }\n if set.contains(&n) {\n break;\n }\n set.insert(n);\n }\n p(set.len());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e60d6abbd680e61bf87d87a4c97aab09", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\ntype I = usize;\n\nfn f(i: u64) -> u64 {\n let ss = (i+1).to_string();\n let ss: Vec = ss.chars().collect();\n let mut index = ss.len();\n for i in (0..ss.len()).rev() {\n if ss[i] == '0' {\n index = i;\n } else {\n break;\n }\n }\n let ret = &ss[0..index];\n let ret: String = ret.iter().collect();\n return ret.parse().unwrap();\n}\n\nfn main() {\n input!{\n mut n: u64,\n }\n let mut seen = std::collections::HashMap::new();\n\n let mut ans = 0;\n while !seen.contains_key(&n) {\n ans += 1;\n seen.insert(n, true);\n n = f(n);\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f409c1b65e541131ea09b066a0711e53", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::Read line failed\");\n\n let number = input.trim().parse::().expect(\"NUMBER::Parse to i32 failed\");\n\n let mut vec = vec![];\n vec.push(number);\n let mut fx = function(number);\n let mut is_repeats = is_repeat(&vec, fx);\n\n while !is_repeats {\n vec.push(fx);\n fx = function(fx);\n is_repeats = is_repeat(&vec, fx);\n\n\n }\n\n println!(\"{}\",vec.len());\n}\n\nfn function(number : i32) -> i32 {\n let mut number = number + 1;\n\n let mut last_number = number % 10;\n\n while last_number == 0 {\n number /= 10;\n last_number = number % 10;\n }\n\n number\n\n\n}\n\nfn is_repeat(vec : &Vec, fx:i32) -> bool {\n let mut is_repeat = false;\n\n for i in 0..vec.len() {\n if fx == vec[i] {\n is_repeat = true;\n break;\n }\n\n\n }\n is_repeat\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "90a92b63511a0c81015959bb3b0a5bc5", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//#[derive(Debug)]\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\nuse input::*;\nuse std::collections::HashSet;\n\nfn main() {\n let mut n: i32;\n let mut set = HashSet::new();\n\n input!(n);\n set.insert(n);\n while n > 0 {\n n += 1;\n while n % 10 == 0 {\n n /= 10;\n }\n if set.contains(&n) {\n break;\n }\n set.insert(n);\n }\n p(set.len());\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "87c22d5347aef5e67d9c2e4c8e6779c6", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read,stdin};\nuse std::collections::HashSet;\n\nfn main() {\n let mut buf = String::new();\n stdin().read_to_string(&mut buf).unwrap();\n let mut tok = buf.split_whitespace();\n let mut get = || tok.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let mut n = get!(u64);\n let mut hs = HashSet::new();\n loop {\n if !hs.insert(n) {\n break;\n }\n n = f(n);\n }\n println!(\"{:?}\", hs.len());\n}\n\nfn f(n: u64) -> u64 {\n let mut r = n + 1;\n while r % 10 == 0 {\n r /= 10;\n }\n r\n}\n\n ", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "06277b036d07802e490a79349f9c5cfe", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*};\nuse std::str;\nuse std::collections::HashSet;\n\nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: Vec::new(), buf_iter: \"\".split_whitespace() }\n }\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace())\n }\n }\n }\n}\n\nfn main() {\n\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n let mut n = scan.next::();\n let mut set = HashSet::new();\n\n while set.insert(n) {\n n+=1;\n while n%10==0 {\n n/=10;\n }\n }\n println!(\"{}\", set.len());\n}\n\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "54fc07b34e7a949f21780fe1df3c2043", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input)\n .expect(\"error\");\n let mut input = input.trim().parse().expect(\"error not a number \");\n let mut ans = 9 ;\n while input > 9\n {\n ans += 1 ;\n input = f(input)\n }\n\n print!(\"{}\",ans);\n}\n\nfn f(x: u32) -> u32 {\n let mut y = x + 1;\n while y % 10 == 0\n {\n y = y / 10\n }\n return y;\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a2a6154e0b7c1386a9743e9172aa0671", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn resolve(hy: i64, ay: i64, dy: i64, hm: i64, am: i64, dm: i64) -> bool {\n let ay = ay - dm;\n let am = am - dy;\n if ay <= 0 {\n return false;\n }\n if am <= 0 {\n return true;\n }\n let yt = (hy - 1) / am;\n let mt = (hm - 1) / ay;\n yt > mt\n}\n\nfn solve() {\n let (hy, ay, dy) = parse_line!(i64, i64, i64);\n let (hm, am, dm) = parse_line!(i64, i64, i64);\n let (h, a, d) = parse_line!(i64, i64, i64);\n let mut ans = std::i64::MAX;\n for aadd in 0..500 {\n for dadd in 0..500 {\n let ay = ay + aadd;\n let dy = dy + dadd;\n let mut l: i64 = -1;\n let mut r: i64 = 100001;\n while r - l > 1 {\n let m = (l + r) / 2;\n let hy = hy + m;\n if resolve(hy, ay, dy, hm, am, dm) {\n r = m;\n }else{\n l = m;\n }\n }\n let cost = aadd * a + dadd * d + r * h;\n ans = std::cmp::min(ans, cost);\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "2d7197af81639c86556e43f0cbcd891b", "src_uid": "bf8a133154745e64a547de6f31ddc884", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nuse std::cmp::*;\n\nfn run() {\n input! {\n yang: (i64, i64, i64),\n mons: (i64, i64, i64),\n h: i64,\n a: i64,\n d: i64,\n }\n let win = |h: i64, a: i64, b: i64| -> bool {\n let yang = (yang.0 + h, yang.1 + a, yang.2 + b);\n let x = max(yang.1 - mons.2, 0);\n if x <= 0 {\n return false;\n }\n let y = max(mons.1 - yang.2, 0);\n if y <= 0 {\n return true;\n }\n let a = (yang.0 + y - 1) / y;\n let b = (mons.0 + x - 1) / x;\n a > b\n };\n // DEF\u3092100, ATK \u3092100\u8cb7\u3048\u3070\u52dd\u3066\u308b\u3001\u3053\u308c\u4ee5\u4e0b\n let mut ans = 100 * a + 100 * d;\n for i in 0..=21000 {\n if i * h > ans {\n break;\n }\n for j in 0..=200 {\n if j * a > ans - i * h {\n break;\n }\n for k in 0..=200 {\n if win(i, j, k) {\n ans = min(ans, i * h + j * a + k * d);\n }\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "07b5ff75a6d9ffefa3b271f4f312d55e", "src_uid": "bf8a133154745e64a547de6f31ddc884", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n // e.g: 3 -> 3 + (2*(2-1)+1) + 1\n // e.g: 4 -> 4 + 3 + 2 + 1 =\n let n: isize = scan.next();\n if n == 1 {\n println!(\"1\");\n return;\n }\n let mut result: isize = n + 1; \n let mut i = n-1;\n while i >= 2 {\n result += i*(n-i) + 1;\n i -= 1;\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "da6277b8e76a114f1bb9b856fda030a9", "src_uid": "6df251ac8bf27427a24bc23d64cb9884", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n\n let (n, ) = R!(usize);\n let mut ans = 0;\n for i in 1..n {\n ans += (n-i) * i;\n }\n println!(\"{}\", ans + n);\n\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "2ba1a5b89e5dcb550051b1b5336724e2", "src_uid": "6df251ac8bf27427a24bc23d64cb9884", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> Vec\nwhere\n T: std::str::FromStr,\n{\n let mut input = String::new();\n io::stdin()\n .read_line(&mut input)\n .expect(\"Error reading line\");\n\n input\n .trim()\n .split_ascii_whitespace()\n .map(|e| e.parse().ok().expect(\"Parsing error\"))\n .collect()\n}\n\nfn main() {\n let mut n = read_line::()[0];\n\n if n == 1 {\n println!(\"1\");\n } else {\n let mut sum = n;\n let mut button = 2;\n n = n - 1;\n while n > 1 {\n sum += 1 + button * (n - 1);\n n -= 1;\n button += 1;\n }\n sum += 1;\n println!(\"{}\", sum);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "0bc269584be113e808b17d7856a2980f", "src_uid": "6df251ac8bf27427a24bc23d64cb9884", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i();\n let sol = n + (1..n).zip((1..n).rev())\n .fold(0, |c,(a,b)| a * b + c);\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "5deb23232ca3b3ad92142228191067da", "src_uid": "6df251ac8bf27427a24bc23d64cb9884", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn gcd(a: u64, b: u64) -> u64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn lcm(a: u64, b: u64) -> u64 {\n if a == 0 || b == 0 {\n a + b\n } else {\n a / gcd(a, b) * b\n }\n}\n\nfn run() {\n input! {\n w: u64,\n c: [u64; 8],\n }\n let m = (1..=8).fold(0, |s, a| lcm(s, a));\n let mut ans = 0;\n let mut w = w;\n let mut c = c;\n for (i, c) in c.iter_mut().enumerate() {\n let k = (i + 1) as u64;\n let v = m / k;\n let q = *c / v;\n let d = std::cmp::min(w / m * m, q * v * k);\n ans += d;\n w -= d;\n *c -= d / k;\n if *c > v {\n *c = v;\n }\n }\n if w >= 8 * m {\n ans += c.iter().enumerate().fold(0, |s, (i, c)| s + (i + 1) as u64 * c);\n } else {\n let w = w as usize;\n let mut dp = vec![false; w + 1];\n dp[0] = true;\n for (i, &c) in c.iter().enumerate() {\n let k = i + 1;\n for _ in 0..c {\n for j in (k..=w).rev() {\n dp[j] |= dp[j - k];\n }\n }\n println!();\n }\n ans += dp.iter().rposition(|p| *p).unwrap() as u64;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "greedy", "dp"], "code_uid": "1ed2a8284c7dd8cf1bcb4441fbfab1fe", "src_uid": "8097e10157320524c0faed56f2bc4880", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{ self, Write };\nuse std::str::FromStr;\nuse std::cmp::{ min, max };\nuse std::collections::{ BinaryHeap, VecDeque };\n\n#[allow(unused_macros)]\nmacro_rules! trace {\n ($var:expr) => {\n let _ = writeln!(&mut std::io::stderr(), \">>> {} = {:?}\", stringify!($var), $var);\n };\n ($($args:expr),*) => { trace!(($($args),*)) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! put {\n ($var:expr) => {\n let _ = writeln!(&mut std::io::stdout(), \"{}\", $var);\n };\n ($var:expr, $($args:expr),*) => {\n let _ = write!(&mut std::io::stdout(), \"{} \", $var);\n put!($($args),*);\n };\n}\n\nfn gcd(a: u64, b: u64) -> u64 { if b == 0 { a } else { gcd(b, a % b) } }\nfn main() {\n let mut sc = Scanner::new();\n let l: u64 = sc.cin();\n let r: u64 = sc.cin();\n let x: u64 = sc.cin();\n let y: u64 = sc.cin();\n\n let mut divs = vec![];\n for i in 1..y {\n if i * i > y {\n break\n } else if i * i == y {\n divs.push(i);\n } else if y % i == 0 {\n divs.push(i);\n divs.push(y/i);\n }\n }\n // trace!(divs);\n\n let mut ans = 0;\n for k in divs.iter() {\n let a = k * x;\n let b = y / k;\n if l <= a && a <= r && l <= b && b <= r && gcd(a, b) == x {\n ans += 1;\n }\n }\n put!(ans);\n}\n\n#[allow(dead_code)]\nstruct Scanner { stdin: io::Stdin, buffer: VecDeque, }\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }\n fn reserve(&mut self) {\n while self.buffer.len() == 0 {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n }\n fn cin(&mut self) -> T {\n self.reserve();\n match self.buffer.pop_front().unwrap().parse::() {\n Ok(a) => a,\n Err(_) => panic!(\"parse err\")\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "212ccb2e71ce6837f2c0cdef1c1d423f", "src_uid": "d37dde5841116352c9b37538631d0b15", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::prelude::*;\nuse std::io;\nuse std::str::FromStr;\n#[cfg(local)]\nuse std::fs::File;\n#[cfg(local)]\nuse std::io::BufReader;\n\n#[cfg(local)]\nfn buf_read() -> io::Result<(Vec)> {\n let f = try!(File::open(\"input.txt\"));\n let input_lines: Vec<_> = BufReader::new(f).lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\n#[cfg(not(local))]\nfn buf_read() -> io::Result<(Vec)> {\n let stdin = io::stdin();\n let input_lines: Vec<_> = stdin.lock().lines().collect();\n let lines: Vec = input_lines.into_iter().map(|e| e.unwrap()).collect();\n Ok((lines))\n}\n\nfn main() {\n type Element = u32;\n let input = buf_read().unwrap();\n let mut input_vectors: Vec> = vec![];\n for input_line in input {\n let input_str: Vec = input_line.split(' ').map(String::from).collect();\n let mut input_vector: Vec = vec![];\n for input_elem_str in input_str {\n let elem: Element = Element::from_str(input_elem_str.as_str()).unwrap();\n input_vector.push(elem);\n }\n input_vectors.push(input_vector);\n }\n let input = input_vectors[0][0];\n if input == 0 {\n println!(\"1\");\n\n } else {\n match input % 4 {\n 1 => println!(\"8\"),\n 2 => println!(\"4\"),\n 3 => println!(\"2\"),\n _ => println!(\"6\"),\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "fd57be76ff3e981e715204e3b931be12", "src_uid": "4b51b99d1dea367bf37dc5ead08ca48f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::cmp::{min, max};\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Scanner {\n Scanner {\n reader: reader,\n buffer: Vec::new(),\n }\n }\n\n /// Use \"turbofish\" syntax next::() to select data type of next token.\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n\n pub fn next_vec(&mut self, len: usize) -> Vec\n where\n T::Err: ::std::fmt::Debug,\n {\n (0..len).map(|_| self.next::()).collect::>()\n }\n}\n\nfn main1() {\n let stdin = io::stdin();\n let mut input = Scanner::new(stdin.lock());\n let mut n = input.next::();\n if n == 0 {\n println!(\"1\");\n return;\n }\n n %= 4;\n let mut answer = 6;\n for _ in 0..n {\n answer = answer * 8 % 10;\n }\n println!(\"{}\", answer);\n\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "b6f9f46082998397c6d63740724a8c60", "src_uid": "4b51b99d1dea367bf37dc5ead08ca48f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let pattern = [8, 4, 2, 6];\n println!(\"{}\", if n==0 {1} else {pattern[(n-1)%4]});\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "dd7d02cfde7064f28baae8ca54907926", "src_uid": "4b51b99d1dea367bf37dc5ead08ca48f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let n = readln!(i32);\n let aaa = vec![6,8,4,2];\n let ans : i32 = if n == 0 { 1 } else {aaa[(n%4) as usize]};\n println!(\"{}\",ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "479e9d9b81d169cfc2e109b3e14ede68", "src_uid": "4b51b99d1dea367bf37dc5ead08ca48f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n println!(\"{}\", if n == 0 {\n 1\n } else {\n [6,8,4,2][(n % 4) as usize]\n });\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "707dc0a987759675156e4f2bb1d815a0", "src_uid": "4b51b99d1dea367bf37dc5ead08ca48f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u32 = scan.token();\n let ans = if n == 0 {\n 1\n } else if n % 4 == 0 {\n 6\n } else if n % 4 == 1 {\n 8\n } else if n % 4 == 2 {\n 4\n } else if n % 4 == 3 {\n 2\n } else {\n 1\n };\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "acdaed0157b617c4d2dd10921d23963d", "src_uid": "4b51b99d1dea367bf37dc5ead08ca48f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let positions: String = read(sin);\n\n if positions.contains(\"01111111\")\n || positions.contains(\"11111110\")\n || positions.contains(\"10000000\")\n || positions.contains(\"00000001\")\n {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "35133893d6ff3065b60fc851ae864966", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n // The input binary string\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n\n let mut cnt: [i32; 2] = [0, 0];\n let mut ind: usize = 0;\n\n for c in s.trim().chars() {\n if 7 <= cnt[ind] {\n break;\n }\n\n if (c as usize) - ('0' as usize) == ind {\n cnt[ind] += 1;\n } else {\n ind = (c as usize) - ('0' as usize);\n cnt[ind] = 1;\n }\n }\n\n // Display results\n if cnt[ind] >= 7 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d515001f0193a1ea2140bb57494f019e", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\nuse std::string::String;\n\nfn get_input() -> String {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"Failed\");\n return buffer.trim().to_string();\n}\n\nfn main() {\n let input: String = get_input();\n if input.contains(\"1111111\") || input.contains(\"0000000\") {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n io::stdout().flush().unwrap();\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "3ea79f254e0ea576ff8f9fe7ff158c42", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*};\nuse std::str;\nuse std::string::String;\nuse std::vec::Vec;\n\n#[allow(unused_must_use)]\nfn run(mut reader: Scanner, mut writer: W) {\n let input: String = reader.next_line();\n if input.contains(\"0000000\") || input.contains(\"1111111\") {\n writeln!(writer, \"YES\");\n } else {\n writeln!(writer, \"NO\");\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n run(reader, writer);\n io::stdout().flush().unwrap();\n}\n\npub struct Scanner {\n reader: B,\n buffer_string: Vec,\n buffer_iterator: str::SplitWhitespace<'static>,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n return Self {\n reader,\n buffer_string: Vec::new(),\n buffer_iterator: \"\".split_whitespace()\n };\n }\n\n pub fn next(&mut self) -> T {\n loop {\n //if buffer already exists, just use existing buffer\n if let Some(token) = self.buffer_iterator.next() {\n return token.parse().ok().expect(\"Fail to parse token\");\n }\n\n //get new line\n self.buffer_string.clear();\n self.reader.read_until(b'\\n', &mut self.buffer_string).expect(\"Failed to read\");\n\n //split by white space\n self.buffer_iterator = unsafe {\n let slice = str::from_utf8_unchecked(&self.buffer_string);\n std::mem::transmute(slice.split_whitespace())\n };\n }\n }\n\n pub fn next_line(&mut self) -> String {\n //reset buffer\n self.buffer_iterator = \"\".split_whitespace();\n self.buffer_string.clear();\n\n let mut input: String = String::new();\n self.reader.read_line(&mut input).expect(\"Failed to read line\");\n return input.trim().to_string();\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "e84db43e3a562f53842f0b891fae56fe", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)?;\n let mut counter: i8 = 0;\n let mut current: char = '1';\n for player in input.trim().chars(){\n if player != current{\n current = player;\n counter = 1;\n continue;\n } \n counter += 1;\n if counter >= 7 {\n println!(\"YES\");\n return Ok(());\n }\n };\n\n\n println!(\"NO\");\n\n return Ok(());\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "3a26b330e26a4d23410edae7c06bc5ec", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n\n let mut cnt0 = 0;\n let mut cnt1 = 0;\n let mut ans = \"NO\";\n for ch in line.chars() {\n if ch == '0' {\n cnt0 += 1;\n cnt1 = 0;\n }\n else {\n cnt1 += 1;\n cnt0 = 0;\n }\n\n if cnt0 >= 7 || cnt1 >= 7 {\n ans = \"YES\";\n break;\n }\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "4d4b0ff235373783cbd07a8d2e7cdba9", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n let mut line: String = line.trim().to_string();\n line.push('y');\n let mut iter = line.chars();\n\n let (total, _, _) = iter.fold((0, 0, 'x'), |(total, current, prev), p| if prev == 'x' {\n (0, 1, p)\n } else if p == prev {\n (total, current + 1, p)\n } else {\n (std::cmp::max(total, current), 1, p)\n });\n println!(\"{}\", if total >= 7 { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "43cfe6cf4b0110f3bb775e39ba845a2c", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main() {\n let input = read();\n let mut val = 'a';\n let mut count = 1;\n let mut danger = 0;\n for d in input.chars(){\n if d == val{\n count += 1;\n if count == 7 {\n danger = 1;\n break;\n }\n }\n else {\n count = 1;\n val = d;\n }\n }\n if danger == 1{\n println!(\"YES\");\n }\n else{\n println!(\"NO\");\n }\n}\nfn read() -> String{\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.trim().parse::().unwrap()\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "4d1abedffe2169b4f9ebfd4865e7a31c", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, Read, StdinLock};\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::collections::{HashSet, HashMap, BinaryHeap};\n#[allow(unused_imports)]\nuse std::vec::Vec;\n\n#[allow(dead_code)]\nconst INF: i32 = 1000_000_000;\n#[allow(dead_code)]\nconst INFLL: i64 = 1000_000_000_000_000_000;\n#[allow(dead_code)]\nconst EPS: f64 = 1.0e-10;\n#[allow(dead_code)]\nconst MOD: i32 = 1000_000_007;\n\nstruct Scanner<'a> {\n cin: StdinLock<'a>,\n}\n\nimpl<'a> Scanner<'a> {\n #[allow(dead_code)]\n fn new(cin: StdinLock<'a>) -> Scanner<'a> {\n Scanner {cin: cin}\n }\n\n #[allow(dead_code)]\n fn read1(&mut self) -> Option {\n let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect::();\n token.parse::().ok()\n }\n\n #[allow(dead_code)]\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\n\nfn main() {\n let cin = stdin();\n let cin = cin.lock();\n let mut sc = Scanner::new(cin);\n\n let r1: i32 = sc.read();\n let r2: i32 = sc.read();\n let c1: i32 = sc.read();\n let c2: i32 = sc.read();\n let d1: i32 = sc.read();\n let d2: i32 = sc.read();\n let mut ans: Vec> = vec![vec![-1; 4]; 4];\n for a in 1..10 {\n for b in 1..10 {\n for c in 1..10 {\n for d in 1..10 {\n let mut s: Vec = vec![a, b, c, d];\n s.sort(); s.dedup();\n if s.len() != 4 {\n continue;\n }\n if a + b == r1 && c + d == r2 && a + c == c1 && b + d == c2 && a + d == d1 && b + c == d2 {\n ans[0][0] = a;\n ans[0][1] = b;\n ans[1][0] = c;\n ans[1][1] = d;\n }\n }\n }\n }\n }\n if ans[0][0] != -1 {\n for i in 0..2 {\n println!(\"{} {}\", ans[i][0], ans[i][1]);\n }\n } else {\n println!(\"-1\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "79df21612072e8b796a19b4d980b39d1", "src_uid": "6821f502f5b6ec95c505e5dd8f3cd5d3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (r1, r2) = parse();\n let (c1, c2) = parse();\n let (d1, d2) = parse();\n let mut v1 = vec![];\n let mut v2 = vec![];\n\n for a in 1..10 {\n for b in 1..10 {\n if a != b && a + b == d1 {\n v1.push((a, b));\n }\n if a != b && a + b == d2 {\n v2.push((a, b))\n }\n }\n }\n for a in &v1 {\n for b in &v2 {\n if a.0 + b.0 == r1\n && a.1 + b.1 == r2\n && a.0 + b.1 == c1\n && a.1 + b.0 == c2\n && a.0 != b.0\n && a.0 != b.1\n && a.1 != b.0\n && a.1 != b.1\n {\n print_result(*a, *b);\n return;\n }\n }\n }\n println!(\"-1\");\n}\nfn print_result(a: (usize, usize), b: (usize, usize)) {\n println!(\"{} {}\", a.0, b.0);\n println!(\"{} {}\", b.1, a.1)\n}\nfn parse() -> (usize, usize) {\n let mut text = String::new();\n std::io::stdin().read_line(&mut text).unwrap();\n let text: Vec = text\n .trim()\n .split_whitespace()\n .map(|e| e.parse().unwrap())\n .collect();\n (text[0], text[1])\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "4acfa89af4e8ec7a2435a426884f0f5d", "src_uid": "6821f502f5b6ec95c505e5dd8f3cd5d3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/143/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(r1: u32, r2: u32);\n scanln!(c1: u32, c2: u32);\n scanln!(d1: u32, d2: u32);\n for a in 1..10 {\n for b in 1..10 {\n for c in 1..10 {\n for d in 1..10 {\n if a == b || a == c || a == d || b == c || b == d || c == d { continue; }\n let cond =\n a + b == r1 &&\n c + d == r2 &&\n a + c == c1 &&\n b + d == c2 &&\n a + d == d1 &&\n b + c == d2;\n if cond {\n println!(\"{} {}\", a, b);\n println!(\"{} {}\", c, d);\n return;\n }\n }\n }\n }\n }\n println!(\"-1\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "6b01efe77036da3bb85b4c646df78288", "src_uid": "6821f502f5b6ec95c505e5dd8f3cd5d3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn solution(r1:u32, r2:u32, c1:u32, c2:u32, d1:u32, d2: u32) -> [u32;4] {\n let mut r = [0,0,0,0];\n \n 'outer: \n for a in 1..=9 {\n for b in 1..=9 {\n if b==a {continue}; \n for c in 1..=9 {\n if c==b || c==a {continue};\n for d in 1..=9 {\n if d==a || d==b || d==c {continue}; \n if a+b==r1 && c+d==r2 && a+c==c1 && b+d==c2 && a+d==d1 && b+c==d2 {\n r = [a,b,c,d];\n break 'outer;\n }\n } \n }\n }\n }\n r\n}\n\nfn main() {\n assert_eq!([1,2,3,4],solution(3, 7, 4, 6, 5, 5));\n assert_eq!([4, 7, 9, 1],solution(11, 10, 13, 8, 5, 16));\n assert_eq!([0,0,0,0], solution(1, 2, 3, 4, 5, 6));\n assert_eq!([0,0,0,0], solution(10, 10, 10, 10, 10, 10));\n\n\n let mut r = String::new();\n std::io::stdin().read_line(&mut r).unwrap();\n let mut ns1 = r.split_whitespace().map(|x| x.parse::().unwrap());\n let r1=ns1.next().unwrap();\n let r2=ns1.next().unwrap();\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut ns2 = s.split_whitespace().map(|x| x.parse::().unwrap());\n let c1=ns2.next().unwrap();\n let c2=ns2.next().unwrap();\n let mut t = String::new();\n std::io::stdin().read_line(&mut t).unwrap();\n let mut ns3 = t.split_whitespace().map(|x| x.parse::().unwrap());\n let d1=ns3.next().unwrap();\n let d2=ns3.next().unwrap();\n let a=solution(r1,r2,c1,c2,d1,d2);\n if a[0]==0 {\n println!(\"-1\");\n } else {\n println!(\"{} {}\\n{} {}\",a[0], a[1], a[2], a[3]);\n } \n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "650082c4b7adb18af5c90c430626cfd9", "src_uid": "6821f502f5b6ec95c505e5dd8f3cd5d3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::prelude::*;\nuse std::io::stdin;\n\nfn main() {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n println!(\"{}\", if buf.contains('1') && buf.trim_left_matches('0').matches('0').count() >= 6 { \"yes\" } else { \"no\" });\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1d2578b679f4366b0dd64893aecb1038", "src_uid": "88364b8d71f2ce2b90bdfaa729eb92ca", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n#![allow(non_camel_case_types)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{max, min};\nuse std::f64::consts::*;\nuse std::mem::swap;\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\nstruct Input {\n\tbuffer: Buf,\n}\n\nimpl Input {\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\t#[inline]\n\tfn read_int(&mut self) -> i32 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_long(&mut self) -> i64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_usize(&mut self) -> usize {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n\t#[inline]\n\tfn read_double(&mut self) -> f64 {\n\t\tself.read_word().parse::().expect(\"Parsing error\")\n\t}\n}\nmacro_rules! read {\n () => {};\n\t($inf:ident, $($t:ty),+) => ({($({$inf.read_word().parse::<$t>().expect(\"Parsing error\")}),*)});\n}\nfn gcd + Copy + Clone>(mut a: T, mut b: T) -> T {\n\twhile b > T::from(0) {\n\t\ta %= b;\n\t\tswap(&mut a, &mut b);\n\t}\n\ta\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input {\n\t\t\t\tbuffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\"))\n\t\t\t};\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tlet stack_size = 268_435_456 / 4; // 256 MB\n\t\t\tlet thd = std::thread::Builder::new().stack_size(stack_size);\n\t\t\tthd.spawn(move || solve(&mut inf, &mut ouf)).unwrap().join().unwrap();\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(stdin()) };\n\t\t\tlet mut ouf = BufWriter::new(stdout());\n\t\t\tlet stack_size = 268_435_456 / 4; // 256 MB\n\t\t\tlet thd = std::thread::Builder::new().stack_size(stack_size);\n\t\t\tthd.spawn(move || solve(&mut inf, &mut ouf)).unwrap().join().unwrap();\n\t\t}\n\t}\n}\n\nfn dfs<'a>(g: &'a Vec>, u: &'a mut Vec, v: usize) {\n\tif u[v] {\n\t\treturn;\n\t}\n\tu[v] = true;\n\tfor &x in &g[v] {\n\t\tdfs(g, u, x);\n\t}\n}\n\ntype int = i32;\ntype long = i64;\ntype uint = u32;\ntype ulong = u64;\n\nfn solve(inf: &mut Input, ouf: &mut Output) {\n\tlet s = inf.read_word().as_bytes().to_vec();\n\tlet mut pos = 0;\n\twhile pos < s.len() && s[pos] == b'0' {\n\t\tpos += 1;\n\t}\n\tlet mut ans = 0;\n\tfor i in pos + 1..s.len() {\n\t\tif s[i] == b'0' {\n\t\t\tans += 1;\n\t\t}\n\t}\n\tif ans >= 6 {\n\t\twriteln!(ouf, \"yes\");\n\t} else {\n\t\twriteln!(ouf, \"no\");\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3d6e10fd0bdd2da586b64e266e260888", "src_uid": "88364b8d71f2ce2b90bdfaa729eb92ca", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let str :Vec = util::line().chars().collect();\n let mut flag = 0;\n let mut ans =0;\n for c in str {\n if c == '1' {\n flag = 1;\n } else if flag == 1 {\n ans += 1;\n }\n }\n if ans >= 6 {\n println!(\"yes\");\n } else {\n println!(\"no\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3cba73fee33e377055be8c76335bb29a", "src_uid": "88364b8d71f2ce2b90bdfaa729eb92ca", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::prelude::*;\nuse std::io::stdin;\n\nfn main() {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n let mut chrs = buf.chars().skip_while(|&c| c == '0');\n println!(\"{}\", if chrs.next() == Some('1') && chrs.filter(|&c| c == '0').count() >= 6 { \"yes\" } else { \"no\" });\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0c1a5eebf148dd36a29e85b254ca8ce8", "src_uid": "88364b8d71f2ce2b90bdfaa729eb92ca", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n\n #[allow(dead_code)]\n pub fn get3() -> (S, T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn main() {\n let s = util::line();\n\n let mut zeros = 0;\n for c in s.chars().rev() {\n if c == '0' {\n zeros += 1;\n } else {\n if zeros >= 6 {\n println!(\"yes\");\n return;\n }\n }\n }\n\n println!(\"no\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0d0ceb1ec89f6759c3ce067a8d326199", "src_uid": "88364b8d71f2ce2b90bdfaa729eb92ca", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\n\nfn main() {\n let s = read_line();\n \n match s.chars().skip_while(|x| *x == '0').filter(|x| *x == '0').count() >= 6 {\n true => println!(\"yes\"),\n false => println!(\"no\")\n } \n\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "59c7e03dc00ff8deab9b8a92b3b7cab4", "src_uid": "88364b8d71f2ce2b90bdfaa729eb92ca", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nconst INF: u64 = 999999999999;\nfn main() {\n let n: u64;\n inputm!(n);\n let a = input_vector::();\n let b = input_vector::();\n\n let mut f = MfGraph::new(8);\n f.add_edge(0, 1, a[0]);\n f.add_edge(0, 2, a[1]);\n f.add_edge(0, 3, a[2]);\n\n f.add_edge(1, 5, INF);\n f.add_edge(2, 6, INF);\n f.add_edge(3, 4, INF);\n\n f.add_edge(4, 7, b[0]);\n f.add_edge(5, 7, b[1]);\n f.add_edge(6, 7, b[2]);\n let max = f.flow(0, 7);\n\n let mut f = MfGraph::new(8);\n f.add_edge(0, 1, a[0]);\n f.add_edge(0, 2, a[1]);\n f.add_edge(0, 3, a[2]);\n\n f.add_edge(1, 4, INF);\n f.add_edge(2, 5, INF);\n f.add_edge(3, 6, INF);\n f.add_edge(1, 6, INF);\n f.add_edge(2, 4, INF);\n f.add_edge(3, 5, INF);\n\n f.add_edge(4, 7, b[0]);\n f.add_edge(5, 7, b[1]);\n f.add_edge(6, 7, b[2]);\n let min = f.flow(0, 7);\n\n println!(\"{} {}\", n - min, max);\n}\n\n//https://github.com/rust-lang-ja/ac-library-rs\n\npub mod input {\n use std::io;\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! inputm {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\npub mod internal_queue {\n #![allow(dead_code)]\n\n #[derive(Default)]\n pub(crate) struct SimpleQueue {\n payload: Vec,\n pos: usize,\n }\n\n impl SimpleQueue {\n pub(crate) fn reserve(&mut self, n: usize) {\n if n > self.payload.len() {\n self.payload.reserve(n - self.payload.len());\n }\n }\n\n pub(crate) fn size(&self) -> usize {\n self.payload.len() - self.pos\n }\n\n pub(crate) fn empty(&self) -> bool {\n self.pos == self.payload.len()\n }\n\n pub(crate) fn push(&mut self, t: T) {\n self.payload.push(t);\n }\n\n pub(crate) fn front(&self) -> Option<&T> {\n if self.pos < self.payload.len() {\n Some(&self.payload[self.pos])\n } else {\n None\n }\n }\n\n pub(crate) fn clear(&mut self) {\n self.payload.clear();\n self.pos = 0;\n }\n\n pub(crate) fn pop(&mut self) -> Option<&T> {\n if self.pos < self.payload.len() {\n self.pos += 1;\n Some(&self.payload[self.pos - 1])\n } else {\n None\n }\n }\n }\n}\npub mod internal_type_traits {\n use std::{\n fmt,\n iter::{Product, Sum},\n ops::{\n Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div,\n DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub,\n SubAssign,\n },\n };\n\n pub trait Integral:\n 'static\n + Send\n + Sync\n + Copy\n + Ord\n + Not\n + Add\n + Sub\n + Mul\n + Div\n + Rem\n + AddAssign\n + SubAssign\n + MulAssign\n + DivAssign\n + RemAssign\n + Sum\n + Product\n + BitOr\n + BitAnd\n + BitXor\n + BitOrAssign\n + BitAndAssign\n + BitXorAssign\n + Shl\n + Shr\n + ShlAssign\n + ShrAssign\n + fmt::Display\n + fmt::Debug\n + fmt::Binary\n + fmt::Octal\n + Zero\n + One\n + BoundedBelow\n + BoundedAbove\n {\n }\n\n pub trait Zero {\n fn zero() -> Self;\n }\n\n pub trait One {\n fn one() -> Self;\n }\n\n pub trait BoundedBelow {\n fn min_value() -> Self;\n }\n\n pub trait BoundedAbove {\n fn max_value() -> Self;\n }\n\n macro_rules! impl_integral {\n ($($ty:ty),*) => {\n $(\n impl Zero for $ty {\n #[inline]\n fn zero() -> Self {\n 0\n }\n }\n\n impl One for $ty {\n #[inline]\n fn one() -> Self {\n 1\n }\n }\n\n impl BoundedBelow for $ty {\n #[inline]\n fn min_value() -> Self {\n Self::min_value()\n }\n }\n\n impl BoundedAbove for $ty {\n #[inline]\n fn max_value() -> Self {\n Self::max_value()\n }\n }\n\n impl Integral for $ty {}\n )*\n };\n}\n\n impl_integral!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);\n}\npub mod maxflow {\n #![allow(dead_code)]\n use crate::internal_queue::SimpleQueue;\n use crate::internal_type_traits::Integral;\n use std::cmp::min;\n use std::iter;\n\n impl MfGraph\n where\n Cap: Integral,\n {\n pub fn new(n: usize) -> MfGraph {\n MfGraph {\n _n: n,\n pos: Vec::new(),\n g: iter::repeat_with(Vec::new).take(n).collect(),\n }\n }\n\n pub fn add_edge(&mut self, from: usize, to: usize, cap: Cap) -> usize {\n assert!(from < self._n);\n assert!(to < self._n);\n assert!(Cap::zero() <= cap);\n let m = self.pos.len();\n self.pos.push((from, self.g[from].len()));\n let rev = self.g[to].len() + if from == to { 1 } else { 0 };\n self.g[from].push(_Edge { to, rev, cap });\n let rev = self.g[from].len() - 1;\n self.g[to].push(_Edge {\n to: from,\n rev,\n cap: Cap::zero(),\n });\n m\n }\n }\n\n #[derive(Debug, PartialEq, Eq)]\n pub struct Edge {\n pub from: usize,\n pub to: usize,\n pub cap: Cap,\n pub flow: Cap,\n }\n\n impl MfGraph\n where\n Cap: Integral,\n {\n pub fn get_edge(&self, i: usize) -> Edge {\n let m = self.pos.len();\n assert!(i < m);\n let _e = &self.g[self.pos[i].0][self.pos[i].1];\n let _re = &self.g[_e.to][_e.rev];\n Edge {\n from: self.pos[i].0,\n to: _e.to,\n cap: _e.cap + _re.cap,\n flow: _re.cap,\n }\n }\n pub fn edges(&self) -> Vec> {\n let m = self.pos.len();\n (0..m).map(|i| self.get_edge(i)).collect()\n }\n pub fn change_edge(&mut self, i: usize, new_cap: Cap, new_flow: Cap) {\n let m = self.pos.len();\n assert!(i < m);\n assert!(Cap::zero() <= new_flow && new_flow <= new_cap);\n let (to, rev) = {\n let _e = &mut self.g[self.pos[i].0][self.pos[i].1];\n _e.cap = new_cap - new_flow;\n (_e.to, _e.rev)\n };\n let _re = &mut self.g[to][rev];\n _re.cap = new_flow;\n }\n\n pub fn flow(&mut self, s: usize, t: usize) -> Cap {\n self.flow_with_capacity(s, t, Cap::max_value())\n }\n pub fn flow_with_capacity(&mut self, s: usize, t: usize, flow_limit: Cap) -> Cap {\n let n_ = self._n;\n assert!(s < n_);\n assert!(t < n_);\n assert_ne!(s, t);\n assert!(Cap::zero() <= flow_limit);\n\n let mut calc = FlowCalculator {\n graph: self,\n s,\n t,\n flow_limit,\n level: vec![0; n_],\n iter: vec![0; n_],\n que: SimpleQueue::default(),\n };\n\n let mut flow = Cap::zero();\n while flow < flow_limit {\n calc.bfs();\n if calc.level[t] == -1 {\n break;\n }\n calc.iter.iter_mut().for_each(|e| *e = 0);\n while flow < flow_limit {\n let f = calc.dfs(t, flow_limit - flow);\n if f == Cap::zero() {\n break;\n }\n flow += f;\n }\n }\n flow\n }\n\n pub fn min_cut(&self, s: usize) -> Vec {\n let mut visited = vec![false; self._n];\n let mut que = SimpleQueue::default();\n que.push(s);\n while !que.empty() {\n let &p = que.front().unwrap();\n que.pop();\n visited[p] = true;\n for e in &self.g[p] {\n if e.cap != Cap::zero() && !visited[e.to] {\n visited[e.to] = true;\n que.push(e.to);\n }\n }\n }\n visited\n }\n }\n\n struct FlowCalculator<'a, Cap> {\n graph: &'a mut MfGraph,\n s: usize,\n t: usize,\n flow_limit: Cap,\n level: Vec,\n iter: Vec,\n que: SimpleQueue,\n }\n\n impl FlowCalculator<'_, Cap>\n where\n Cap: Integral,\n {\n fn bfs(&mut self) {\n self.level.iter_mut().for_each(|e| *e = -1);\n self.level[self.s] = 0;\n self.que.clear();\n self.que.push(self.s);\n while !self.que.empty() {\n let v = *self.que.front().unwrap();\n self.que.pop();\n for e in &self.graph.g[v] {\n if e.cap == Cap::zero() || self.level[e.to] >= 0 {\n continue;\n }\n self.level[e.to] = self.level[v] + 1;\n if e.to == self.t {\n return;\n }\n self.que.push(e.to);\n }\n }\n }\n fn dfs(&mut self, v: usize, up: Cap) -> Cap {\n if v == self.s {\n return up;\n }\n let mut res = Cap::zero();\n let level_v = self.level[v];\n for i in self.iter[v]..self.graph.g[v].len() {\n self.iter[v] = i;\n let &_Edge {\n to: e_to,\n rev: e_rev,\n ..\n } = &self.graph.g[v][i];\n if level_v <= self.level[e_to] || self.graph.g[e_to][e_rev].cap == Cap::zero() {\n continue;\n }\n let d = self.dfs(e_to, min(up - res, self.graph.g[e_to][e_rev].cap));\n if d <= Cap::zero() {\n continue;\n }\n self.graph.g[v][i].cap += d;\n self.graph.g[e_to][e_rev].cap -= d;\n res += d;\n if res == up {\n break;\n }\n }\n self.iter[v] = self.graph.g[v].len();\n res\n }\n }\n\n #[derive(Default)]\n pub struct MfGraph {\n _n: usize,\n pos: Vec<(usize, usize)>,\n g: Vec>>,\n }\n\n struct _Edge {\n to: usize,\n rev: usize,\n cap: Cap,\n }\n}\nuse input::*;\nuse maxflow::*;\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "565355a209faff21fd4867d1abac6448", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n\nuse std::cmp::{\n max, min, Ordering,\n Ordering::{Equal, Greater, Less},\n Reverse,\n};\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\nuse std::convert::TryInto;\nuse std::fmt;\nuse std::io::{self, Read as _};\nuse std::mem::swap;\nuse std::num::{NonZeroU32, ParseIntError};\nuse std::ops::{\n Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,\n Index, IndexMut, Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub,\n SubAssign,\n};\nuse std::process::exit;\nuse std::{f32, f64, i128, i16, i32, i64, i8, isize, u128, u16, u32, u64, u8, usize};\n\npub use visualize::*;\npub mod visualize {\n pub trait Visualize {\n fn visualize(&self, split: &str);\n fn continuous(&self) {\n self.visualize(\"\");\n }\n fn spaces(&self) {\n self.visualize(\" \");\n }\n fn lines(&self) {\n self.visualize(\"\\n\");\n }\n }\n macro_rules ! impl_vis_for_sized {($ ($ t : ty ) ,+ ) => {$ (impl Visualize for $ t {fn visualize (& self , _split : & str ) {print ! (\"{}\" , self ) ; } } ) + } ; }\n impl_vis_for_sized! {usize , u8 , u16 , u32 , u64 , u128 , isize , i8 , i16 , i32 , i64 , i128 , String , & str , char }\n impl Visualize for [T] {\n fn visualize(&self, split: &str) {\n let n = self.iter().count();\n print!(\"{}\", {\n let mut buf = String::new();\n for i in 0..n {\n buf += self[i].to_string().as_str();\n if i != n - 1 {\n buf += split;\n }\n }\n buf\n })\n }\n }\n #[macro_export]\n macro_rules ! vis {() => {println ! () ; } ; ($ last : expr ; ) => {$ last . lines () ; vis ! () } ; ($ last : expr => ) => {$ last . continuous () ; vis ! () ; } ; ($ last : expr $ (, ) ? ) => {$ last . spaces () ; vis ! () ; } ; ($ first : expr ; $ ($ rest : tt ) * ) => {$ first . lines () ; println ! () ; vis ! ($ ($ rest ) * ) ; } ; ($ first : expr => $ ($ rest : tt ) * ) => {$ first . continuous () ; vis ! ($ ($ rest ) * ) ; } ; ($ first : expr , $ ($ rest : tt ) * ) => {$ first . spaces () ; print ! (\" \" ) ; vis ! ($ ($ rest ) * ) ; } ; }\n}\n\npub use consts::*;\npub mod consts {\n pub const MOD10E9_7: usize = 1000000007; // 10 ^ 9 + 7\n pub const MOD99_: usize = 998244353;\n pub const MAX: u64 = std::u64::MAX; // = 2 ^ 64 - 1 = 18446744073709551615 \u2248 1.8 * 10 ^ 19\n pub const INF: u64 = 2000000000000000000; // MAX / 9 < 2 * 10e18 < MAX / 10\n pub const FNI: i64 = -2000000000000000000; // == -(INF as i64)\n pub const PI: f64 = std::f64::consts::PI; // 3.141592653589793 -- 10 ^ -15\n pub const ASCII_A_LARGE: u8 = 65;\n pub const ASCII_A_SMALL: u8 = 97;\n pub const ASCII_0: u8 = 48;\n pub const ADJ4: &[(isize, isize); 4] = &[(1, 0), (0, 1), (-1, 0), (0, -1)];\n pub const ADJ8: &[(isize, isize); 8] = &[\n (1, 0),\n (1, 1),\n (0, 1),\n (-1, 1),\n (-1, 0),\n (-1, -1),\n (0, -1),\n (1, -1),\n ];\n}\n\nfn main() {\n let mut input = \"\".to_owned();\n io::stdin().read_to_string(&mut input).unwrap();\n let input = input.trim();\n let mut input = input.split_whitespace();\n\n // // generate testcases\n // for t in 0..input.next().unwrap().parse::().unwrap() {\n // solve(&mut input);\n // }\n // not testcase\n solve(&mut input);\n}\n\nfn solve(input: &mut std::str::SplitWhitespace) {\n macro_rules! read {\n () => ();\n ([$tt:tt]) => (read!([$tt; read!(usize)]));\n ([$tt:tt; $n:expr]) => ((0..$n).map(|_| read!($tt)).collect::>());\n (($($tt:tt),+)) => (($(read!($tt)),*));\n (Usize1) => (read!(usize) - 1);\n (Chars) => (read!(String).chars().collect::>());\n (Byte) => (read!(char) as u8);\n (Bytes) => (read!(String).into_bytes());\n ($ty:ty) => (input.next().unwrap().trim().parse::<$ty>().unwrap());\n }\n macro_rules! input {\n ($($id:ident : $ty:tt),*) => {\n $(\n let $id = read!($ty);\n )*\n }\n }\n\n input! {\n n: usize,\n a_r: usize, a_s: usize, a_p: usize,\n b_r: usize, b_s: usize, b_p: usize\n }\n\n let mi = a_r.saturating_sub(b_r + b_p)\n + a_s.saturating_sub(b_s + b_r)\n + a_p.saturating_sub(b_p + b_s);\n let ma = min(a_r, b_s) + min(a_s, b_p) + min(a_p, b_r);\n\n vis!(mi, ma);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "b29029915a92961a2cfed8af8475d395", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\npub struct Perm {\n used: Vec,\n perm: Vec,\n ret: Vec>,\n}\nimpl Perm {\n pub fn new(len: usize) -> Self {\n let mut f = Perm {\n used: vec![false; len],\n perm: vec![0; len],\n ret: vec![],\n };\n f.calc(0, len);\n return f;\n }\n pub fn calc(&mut self, pos: usize, n: usize) {\n if pos == n {\n self.ret.push(self.perm.clone());\n return;\n }\n for i in 0..n {\n if self.used[i] == false {\n self.perm[pos] = i;\n self.used[i] = true;\n self.calc(pos + 1, n);\n self.used[i] = false;\n }\n }\n }\n}\n\nfn main() {\n let N = get!(u64);\n let alice = get!(u64, u64, u64);\n let bob = get!(u64, u64, u64);\n let mut ans1 = 0;\n let mut ans2 = 0;\n {\n let mut ans = 0;\n let mut perm = Perm::new(6);\n mydbg!(perm.ret);\n for item in perm.ret {\n let mut k = 0;\n // let mut a = vec![alice.0,alice.1,alice.2];\n // let mut b = vec![bob.0,bob.1,bob.2];\n let (mut g, mut c, mut p) = alice.clone();\n let (mut g2, mut c2, mut p2) = bob.clone();\n for i in 0..item.len() {\n let d = item[i];\n match d {\n 0 => {\n let e = min(g, p2);\n k += e;\n g -= e;\n p2 -= e;\n }\n 1 => {\n let e = min(c, g2);\n k += e;\n c -= e;\n g2 -= e;\n }\n 2 => {\n let e = min(p, c2);\n k += e;\n p -= e;\n c2 -= e;\n }\n 3 => {\n let e = min(g, g2);\n g -= e;\n g2 -= e;\n k += e;\n }\n 4 => {\n let e = min(c, c2);\n c -= e;\n c2 -= e;\n k += e;\n }\n 5 => {\n let e = min(p, p2);\n p -= e;\n p2 -= e;\n k += e;\n }\n _ => {}\n }\n }\n ans = max(ans, k);\n }\n ans1 = (N - ans);\n }\n {\n let mut ans = 0;\n let mut perm = Perm::new(3);\n mydbg!(perm.ret);\n for item in perm.ret {\n let mut k = 0;\n // let mut a = vec![alice.0,alice.1,alice.2];\n // let mut b = vec![bob.0,bob.1,bob.2];\n let (mut g, mut c, mut p) = alice.clone();\n let (mut g2, mut c2, mut p2) = bob.clone();\n for i in 0..item.len() {\n let d = item[i];\n match d {\n 0 => {\n let e = min(g, c2);\n k += e;\n g -= e;\n c2 -= e;\n }\n 1 => {\n let e = min(c, p2);\n k += e;\n c -= e;\n p2 -= e;\n }\n 2 => {\n let e = min(p, g2);\n k += e;\n p -= e;\n g2 -= e;\n }\n _ => {}\n }\n }\n ans = max(ans, k);\n }\n ans2 = (ans);\n }\n\n echo!(vec![ans1, ans2].joinToString(\" \"));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "e53ee26fd4dec8cd14360e28c18e10a3", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\nfn main() -> Result<(), Box> {\n let _n = read_usize();\n let (a1, a2, a3) = read_3::();\n let (b1, b2, b3) = read_3::();\n let not_wins = [(0, 0), (1, 1), (2, 2), (0, 2), (1, 0), (2, 1)];\n let mut min_wins = None;\n for perm in Permutations::new(not_wins.to_vec()) {\n let mut tmpa = [a1, a2, a3];\n let mut tmpb = [b1, b2, b3];\n for (a, b) in perm {\n let m = min(tmpa[a], tmpb[b]);\n tmpa[a] -= m;\n tmpb[b] -= m;\n }\n if let Some(m) = min_wins {\n min_wins = Some(min(m, tmpa.iter().sum::()))\n } else {\n min_wins = Some(tmpa.iter().sum::())\n }\n }\n let max_wins = min(a1, b2) + min(a2, b3) + min(a3, b1);\n println!(\"{} {}\", min_wins.unwrap(), max_wins);\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "0ae5dfc5af62d518fc1f5e1093f32446", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt,$x:expr,$y:expr) => {{\n\t\tlet b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet _n = rin.i();\n\tlet a = rin.vi(3);\n\tlet b = rin.vi(3);\n\tlet mut x = 0;\n\tlet mut y = 0;\n\tfor i in 0..3 {\n\t\tlet j = (i + 2) % 3;\n\t\tm!(>, x, a[i] - b[i] - b[j]);\n\t\tlet j = (i + 1) % 3;\n\t\ty += a[i].min(b[j]);\n\t}\n\twriteln!(rout, \"{} {}\", x, y).ok();\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "3f0f050ff92fb23a33381e3c8e307299", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! read_line_to_tuple {\n ( $( $t:ty ),* ) => {{\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n let mut iter = input.split_whitespace();\n ( $( iter.next().unwrap().parse::<$t>().unwrap() ),* )\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_line_to_collection {\n ( $t:ty ) => {{\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n let iter = input.split_whitespace();\n iter.map(|x| x.parse().unwrap()).collect::<$t>()\n }};\n}\n\nuse std::cmp;\nuse std::collections::VecDeque;\n\nfn rec(\n deq: &mut VecDeque<(usize, usize)>,\n a: &mut Vec, b: &mut Vec,\n) -> i32 {\n if deq.is_empty() { return a.iter().sum(); }\n let mut res = std::i32::MAX;\n let n = deq.len();\n for _ in 0..n {\n let (i, j) = deq.pop_front().unwrap();\n let tmp = cmp::min(a[i], b[j]);\n a[i] -= tmp;\n b[j] -= tmp;\n res = cmp::min(res, rec(deq, a, b));\n deq.push_back((i, j));\n a[i] += tmp;\n b[j] += tmp;\n }\n res\n}\n\nfn solve() -> String {\n let _n = read_line_to_tuple!(i32);\n let mut a = read_line_to_collection!(Vec);\n let mut b = read_line_to_collection!(Vec);\n\n let mut deq = VecDeque::new();\n deq.push_back((0, 0));\n deq.push_back((1, 1));\n deq.push_back((2, 2));\n deq.push_back((0, 2));\n deq.push_back((1, 0));\n deq.push_back((2, 1));\n let min = rec(&mut deq, &mut a, &mut b);\n\n let mut max = 0;\n for i in 0..3 {\n let tmp = cmp::min(a[i], b[(i + 1) % 3]);\n max += tmp;\n }\n\n format!(\"{} {}\", min, max)\n}\n\nfn main() {\n println!(\"{}\", solve());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "56ab6b0294f4d0a17e21e7b09ab127e6", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead}; // (a)\n// use array2d::Array2D;\nuse std::cmp;\n\nmacro_rules! numsin {\n () => (\n io::stdin().lock() // (0)\n .lines().next().unwrap().unwrap() // (1)\n .split(' ').map(|s| s.trim()) // (2)\n .filter(|s| !s.is_empty()) // (3)\n .map(|s| s.parse().unwrap()) // (4)\n .collect()\n )\n}\n\nfn main() {\n let n: Vec = numsin!();\n let n = n[0];\n let a: Vec = numsin!();\n let b: Vec = numsin!();\n let maxwin = cmp::min(a[0], b[1]) + cmp::min(a[1], b[2]) + cmp::min(a[2], b[0]);\n let minwin = n - (cmp::min(a[0], b[0] + b[2]) + cmp::min(a[1], b[0] + b[1]) + cmp::min(a[2], b[1] + b[2]));\n println!(\"{} {}\", minwin, maxwin);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "cb0dc2ad61e67c7c4c287865371aecda", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nfn main() {\n let (mut w, mut h) = parse_line!(i32, i32);\n let (u1, d1) = parse_line!(i32, i32);\n let (u2, d2) = parse_line!(i32, i32);\n\n while h > 0 {\n w += h;\n if h == d1 {\n w -= u1;\n } else if h == d2 {\n w -= u2;\n }\n if w < 0 {\n w = 0;\n }\n h -= 1;\n }\n println!(\"{}\", w);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5f0d02c4aca85b93dbc2882ceb3ec014", "src_uid": "084a12eb3a708b43b880734f3ee51374", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n// use proconio::input;\nuse std::cmp::Ordering::*;\nuse std::collections::{BTreeMap, BTreeSet};\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\nmacro_rules! answer {\n ($out:ident, $ans:expr) => {\n writeln!($out, \"{}\", $ans)\n };\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let (mut w, h) = scan.pair::();\n\n let mut u = vec![0_i32; h as usize + 1];\n for _ in 0..2 {\n let (ui, di) = scan.pair::();\n u[di as usize] += ui;\n }\n\n for i in (0..=h).rev() {\n w += i;\n w -= u[i as usize];\n w = w.max(0);\n }\n\n answer!(out, w)\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Mostly copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse [Scanner]\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\n// aka #![feature(bool_to_option)]\ntrait BoolThen {\n fn then_(self, f: impl FnOnce() -> T) -> Option;\n}\n\nimpl BoolThen for bool {\n fn then_(self, f: impl FnOnce() -> T) -> Option {\n if self {\n Some(f())\n } else {\n None\n }\n }\n}\n\ntrait BoolToYes {\n fn yes(self) -> &'static str;\n}\n\nimpl BoolToYes for bool {\n fn yes(self) -> &'static str {\n if self {\n \"YES\"\n } else {\n \"NO\"\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e27af38f20706b78493a7dfa892fe1aa", "src_uid": "084a12eb3a708b43b880734f3ee51374", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn main() {\n let days: &[usize] = &[\n 31,\n 28,\n 31,\n 30,\n 31,\n 30,\n 31,\n 31,\n 30,\n 31,\n\n 31,\n 28,\n 31,\n 30,\n 31,\n 30,\n 31,\n 31,\n 30,\n 31,\n\n 30,\n 31,\n 31,\n 28,\n 31,\n 30,\n 31,\n 30,\n 31,\n 31,\n 30,\n 31,\n 30,\n 31,\n\n 31,\n 29,\n 31,\n 30,\n 31,\n 30,\n 31,\n 31,\n 30,\n 31,\n 30,\n 31,\n\n 31,\n 28,\n 31,\n 30,\n 31,\n 30,\n 31,\n 31,\n 30,\n 31,\n 30,\n 31,\n\n 31,\n 28,\n 31,\n 30,\n 31,\n 30,\n 31,\n 31,\n 30,\n 31,\n 30,\n 31,\n ];\n let cin = stdin();\n let n = {\n let mut s = String::new();\n cin.lock().read_line(&mut s).unwrap();\n s.trim().parse::().unwrap()\n };\n\n let d: Vec = {\n let mut s = String::new();\n cin.lock().read_line(&mut s).unwrap();\n s.split_whitespace()\n .map(|s| s.parse::().unwrap())\n .take(n)\n .collect()\n };\n for i in 0..(days.len() - n) {\n if &days[i..i + n] == &d[..] {\n println!(\"Yes\");\n return;\n }\n }\n println!(\"No\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "06ab0e934c1db2c2307a9effbc86cbab", "src_uid": "d60c8895cebcc5d0c6459238edbdb945", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::prelude::*;\n std::io::stdin().read_to_string(&mut input).unwrap();\n let mut it = input.split_whitespace();\n\n let n: usize = it.next().unwrap().parse().unwrap();\n\n let a: Vec = it.take(n).map(|x| x.parse().unwrap()).collect();\n\n let ms = vec![31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n let ans = (0..ms.len() - n).any(|i| a.iter().zip(ms.iter().skip(i)).all(|(&a, &m)| a == m));\n\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c5fd212f84bc99c56fc5a48b40c17388", "src_uid": "d60c8895cebcc5d0c6459238edbdb945", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn main() {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n let nkx : Vec = line.trim().split(\" \").map(|x| x.parse::().unwrap()).collect();\n let (n, k, x) : (usize, usize, usize) = (nkx[0], nkx[1], nkx[2]);\n\n line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n let my_deeds : Vec = line.trim().split(\" \").map(|x| x.parse::().unwrap()).collect();\n\n let mut min_cost = 0;\n for i in 1..(n + 1) {\n if i <= k {\n min_cost += x;\n } else {\n min_cost += my_deeds[((n - i) as usize)];\n }\n }\n\n print!(\"{}\", min_cost);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "eda5dcbb14f8d0f1f076662cbe4612c4", "src_uid": "92a233f8d9c73d9f33e4e6116b7d0a96", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nconst N: i64 = 998_244_353;\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let (n, k, x): (usize, usize, usize) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let a: Vec = get_vec();\n\n let ans = &a[..a.len() - k].iter().cloned().sum::() + k * x;\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7098957547b7590d9260221338f542ff", "src_uid": "92a233f8d9c73d9f33e4e6116b7d0a96", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet};\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n\n #[allow(dead_code)]\n pub fn get3() -> (S, T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn main() {\n let (n, k, x): (usize, usize, usize) = util::get3();\n let a: Vec = util::gets();\n\n println!(\"{}\", a[..n - k].iter().sum::() + k * x);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b2a6ff7529814c3b5b5a38a4b0adde65", "src_uid": "92a233f8d9c73d9f33e4e6116b7d0a96", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\n\nfn main() {\n input!{\n w1: usize,\n h1: usize,\n w2: usize,\n h2: usize,\n }\n let w = max(w1, w2);\n println!(\"{}\", (w + h1 + h2)*2 + 4);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "108c37841eb0ffc4d34f32bf655cb6b8", "src_uid": "b5d44e0041053c996938aadd1b3865f6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn input() -> (u32, u32, u32, u32) {\n\tlet mut input = String::new();\n\tio::stdin().read_line(&mut input).expect(\"\");\n\tlet strs: Vec<&str> = input.split_whitespace().collect();\n\tassert!(strs.len() == 4);\n\tlet nums: Vec = strs.iter().map(|s| u32::from_str(s).expect(\"\")).collect();\n\treturn (nums[0], nums[1], nums[2], nums[3]);\n}\n\nfn main() {\n\tlet (w1, h1, _, h2) = input();\n\tprint!(\"{}\\n\", 2 * (h1 + h2 + w1) + 4);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "18b3008456470c56b8503ffa9564bcb6", "src_uid": "b5d44e0041053c996938aadd1b3865f6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn get_marked_area(w1: u32, h1: u32, _w2: u32, h2: u32) -> u32 {\n // 4 + 2 * (h1 + h2) + (w1 + w2) + (w1 - w2)\n return 4 + 2 * (h1 + h2 + w1);\n}\n\n#[cfg(test)]\nmod test {\n use super::get_marked_area;\n\n #[test]\n fn test1() {\n let (w1, h1, w2, h2): (u32, u32, u32, u32) = (2, 1, 2, 1);\n let result: u32 = get_marked_area(w1, h1, w2, h2);\n assert_eq!(result, 12);\n }\n #[test]\n fn test2() {\n let (w1, h1, w2, h2): (u32, u32, u32, u32) = (2, 2, 1, 2);\n let result: u32 = get_marked_area(w1, h1, w2, h2);\n assert_eq!(result, 16);\n }\n}\n\nfn read_data() -> (u32, u32, u32, u32) {\n let mut data_str: String = String::new();\n stdin().read_line(&mut data_str).unwrap();\n let data_str_tokens: Vec = data_str\n .trim()\n .split(\" \")\n .map(|s| s.parse::().unwrap())\n .collect();\n return (data_str_tokens[0], data_str_tokens[1], data_str_tokens[2], data_str_tokens[3]);\n}\n\nfn main() {\n let (w1, h1, w2, h2): (u32, u32, u32, u32) = read_data();\n\n let result: u32 = get_marked_area(w1, h1, w2, h2);\n\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "4aa5967c83ccdd267fa70f152a622caf", "src_uid": "b5d44e0041053c996938aadd1b3865f6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n// input macro\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input!{\n f: [i32; 2],\n s: [i32; 2],\n }\n println!(\"{}\", f[0] + s[0] + 4 + f[1] * 2 + s[1] * 2 + (f[0] - s[0]).abs());\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "692d1412d31328d29b9ac8f42d2fe5eb", "src_uid": "b5d44e0041053c996938aadd1b3865f6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::Ordering;\n\nfn main() {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let (n, k) = {\n let temp: Vec = buf\n .trim()\n .split_whitespace()\n .map(|a| a.parse().unwrap())\n .collect();\n (temp[0], temp[1])\n };\n\n let (mut index, mut jump) = (n / 2, n / 2);\n loop {\n let sum_n = index * (index + 1) / 2;\n let eaten = n - index;\n\n if eaten > sum_n {\n jump = 1.max(jump / 2);\n index += jump;\n continue;\n }\n\n match k.cmp(&(sum_n - eaten)) {\n Ordering::Equal => break,\n Ordering::Greater => {\n jump = 1.max(jump / 2);\n index += jump;\n }\n Ordering::Less => {\n jump = 1.max(jump / 2);\n index -= jump;\n }\n }\n }\n\n println!(\"{}\", n - index);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search"], "code_uid": "c6c6da80cf6bc1ae9b13f45f1293e1b3", "src_uid": "17b5ec1c6263ef63c668c2b903db1d77", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n#[allow(unused_imports)]\nuse std::io::{stdout, stdin, BufWriter, Write};\n\n#[doc = \" [l, r)\"]\npub fn binary_search_by(mut l: i64, mut r: i64, f: &F) -> i64\nwhere\n F: Fn(i64) -> bool,\n{\n assert!(l <= r);\n while r != l {\n let m = l + (r - l) / 2;\n if f(m) {\n r = m;\n } else {\n l = m + 1;\n }\n }\n r\n}\n\nfn main() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (writeln!(out,$($format)*).unwrap());\n }\n\n input!{\n n: i64,\n k: i64,\n }\n\n let f = |mid| {\n let sum = mid * (mid+1) / 2;\n sum - (n - mid) >= k\n };\n let ans = binary_search_by(1, n+1, &f);\n puts!(\"{}\", n-ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search"], "code_uid": "d50abdea69db37bbd4fd6a2e63acefa6", "src_uid": "17b5ec1c6263ef63c668c2b903db1d77", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: i64, k: i64,\n }\n // Find x s.t. x(x+1)/2 + x - n = k\n let mut hi = 1i64 << 20;\n let mut lo = 0;\n while hi - lo > 1 {\n let mid = (hi + lo) / 2;\n let val = mid * (mid + 3) / 2;\n if val <= n + k {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n puts!(\"{}\\n\", n - lo);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search"], "code_uid": "908ae24b7182f94ecb191e791325052e", "src_uid": "17b5ec1c6263ef63c668c2b903db1d77", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n let k = get!();\n \n let mut lp = 0;\n let mut rp = n + 1;\n\n while lp < rp {\n let hp = (rp - lp) / 2 + lp;\n let m = n - hp;\n let r = m * (m + 1) / 2;\n if r - hp == k {\n println!(\"{}\", hp);\n return;\n }\n if r - hp < k {\n rp = hp;\n } else {\n lp = hp + 1;\n }\n }\n println!(\"{}\", lp);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search"], "code_uid": "821d5c484fc3d68b7aa982956cd675fc", "src_uid": "17b5ec1c6263ef63c668c2b903db1d77", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(n,k: i64 = input.p());\n let mut lo = 0;\n let mut hi = n;\n let f = |x| { x * (x + 1) / 2 };\n loop {\n let mid = (lo + hi) / 2;\n let y = f(mid) - (n - mid);\n if y == k {\n println!(\"{}\", n - mid);\n break;\n } else if y < k {\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search"], "code_uid": "6303660c4c119bc2ecc1ce0bd94795a5", "src_uid": "17b5ec1c6263ef63c668c2b903db1d77", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (a, b) = {\n let res = getvec::();\n (res[0], res[1])\n };\n let sa = a - b;\n let flag = sa.abs() >= 2 || a + b == 0;\n let res = match flag {\n true => \"NO\",\n false => \"YES\",\n };\n println!(\"{}\", res);\n}\n\n#[allow(dead_code)]\nfn next_line() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n input\n}\n\n#[allow(dead_code)]\nfn getnum() -> T {\n let res = next_line();\n res.trim().parse::().ok().unwrap()\n}\n\n#[allow(dead_code)]\nfn getvec() -> Vec {\n let res = next_line();\n res.split_whitespace().map(|x| x.parse::().ok().unwrap()).collect()\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "227c876c275a78c4c309e81d29e10d99", "src_uid": "ec5e3b3f5ee6a13eaf01b9a9a66ff037", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty, $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt, $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\n\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl std::iter::Iterator where T::Err: Debug {\n //(0..n).map(|_| self.p())\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(input.i, a, b);\n if a + b > 0 && (a - b).abs() <= 1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "5f8e59d968cabd33fcee5ee7fd86d385", "src_uid": "ec5e3b3f5ee6a13eaf01b9a9a66ff037", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! read_line {\n ($v:ident) => {\n let mut temp = String::new();\n std::io::stdin().read_line(&mut temp).unwrap();\n let $v = temp;\n };\n (var, $t:ty, $($v:ident), *) => {\n read_line!(input_line);\n let mut iter = parse_token!($t, input_line);\n $(\n let $v = iter.next().unwrap();\n )*\n };\n (vec, $t:ty, $v:ident) => {\n read_line!(input_line);\n let iter = parse_token!($t, input_line);\n let $v: Vec<$t> = iter.collect();\n };\n ($($v:ident; $t:ty), *) => {\n read_line!(input_line);\n let mut iter = input_line.split_whitespace();\n $(\n let $v: $t = iter.next().unwrap().parse().unwrap();\n )*\n };\n}\n\nmacro_rules! parse_token {\n ($t:ty, $e:expr) => {\n $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());\n };\n}\n\nfn main() {\n read_line!(even;i64, odd;i64);\n if odd == 0 && even == 0 {\n println!(\"NO\"); // There must be one staircase\n return\n }\n if (odd - even).abs() <= 1 {\n // Valid count\n println!(\"YES\")\n } else {\n println!(\"NO\")\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "56d26838ac9afc49b27d1a2567c289db", "src_uid": "ec5e3b3f5ee6a13eaf01b9a9a66ff037", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{ self, Write };\nuse std::str::FromStr;\nuse std::cmp::{ min, max };\nuse std::collections::{ BinaryHeap, VecDeque };\n\nmacro_rules! trace {\n ($var:expr) => ({\n let _ = writeln!(&mut std::io::stderr(), \">>> {} = {:?}\", stringify!($var), $var);\n })\n}\nmacro_rules! swap { ($a:expr, $b:expr) => ({ let t = $b; $b = $a; $a = t; }) }\n\nfn main() {\n let mut sc = Scanner::new();\n let a: i32 = sc.cin();\n let b: i32 = sc.cin();\n\n let k = if a == b + 1 || (a == b && a > 0) || a + 1 == b { \"YES\" } else { \"NO\" };\n println!(\"{}\", k);\n\n}\n\n#[allow(dead_code)]\nstruct Scanner { stdin: io::Stdin, buffer: VecDeque, }\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }\n fn reserve(&mut self) {\n while self.buffer.len() == 0 {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n }\n fn cin(&mut self) -> T {\n self.reserve();\n match self.buffer.pop_front().unwrap().parse::() {\n Ok(a) => a,\n Err(_) => panic!(\"parse err\")\n }\n }\n fn get_char(&mut self) -> char {\n self.reserve();\n let head = self.buffer[0].chars().nth(0).unwrap();\n let tail = String::from( &self.buffer[0][1..] );\n if tail.len()>0 { self.buffer[0]=tail } else { self.buffer.pop_front(); }\n head\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "2226704c2d67c77115b37fdba37a443e", "src_uid": "ec5e3b3f5ee6a13eaf01b9a9a66ff037", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let n: usize = {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.trim().parse().unwrap()\n };\n\n let a: Vec = {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.split_whitespace().map(|k| k.parse().unwrap()).collect()\n };\n\n let mut prefix_sums: Vec<_> = a.iter().scan(0, |state, &k| {\n if k == 1 {\n *state += 1;\n }\n Some(*state)\n }).collect();\n\n prefix_sums.insert(0, 0);\n\n let mut b = a.clone();\n\n b.reverse();\n\n let mut suffix_sums: Vec<_> = b.iter().scan(0, |state, &k| {\n if k == 0 {\n *state += 1;\n }\n Some(*state)\n }).collect();\n\n suffix_sums.insert(0, 0);\n\n suffix_sums.reverse();\n\n let ans = (0..n + 1).map(|i| prefix_sums[i] + suffix_sums[i]).min().unwrap();\n\n println!(\"{}\", n - ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "075036784e4d32e7ad1360891aa4fae9", "src_uid": "c7b1f0b40e310f99936d1c33e4816b95", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn solve() {\n let n: usize = get();\n let a: Vec = (0 .. n).map(|_| get()).collect();\n let mut ma = 0;\n for i in 0 .. (n + 1) {\n let mut tmp = 0;\n for j in 0 .. i {\n tmp += 1 - a[j];\n }\n for j in i .. n {\n tmp += a[j];\n }\n ma = max(ma, tmp);\n }\n println!(\"{}\", ma);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "6d8185921cf765cd4e8262730a159e35", "src_uid": "c7b1f0b40e310f99936d1c33e4816b95", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\n#[derive(Clone)]\nstruct Graph {\n nodes: usize,\n edges: Vec>,\n}\n\nimpl Graph {\n fn new(n: usize) -> Self {\n Self {\n nodes: n,\n edges: vec![Vec::new(); n + 1],\n }\n }\n\n fn add_edge(&mut self, x: usize, y: usize, cost: u64) {\n self.edges[x].push((y, cost));\n self.edges[y].push((x, cost));\n }\n\n fn dijkstra(&mut self, start: usize, end: usize) -> u64 {\n let mut dist = vec![None; self.nodes + 1];\n let mut prev = vec![None; self.nodes + 1];\n dist[start] = Some(0);\n let mut queue = (1..=self.nodes).collect::>();\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n while let Some(next_node) = queue.pop() {\n if next_node == end {\n return dist[next_node].unwrap();\n }\n for (neighbour, cost) in self.edges[next_node].iter() {\n let alt = dist[next_node].unwrap() + cost;\n if dist[*neighbour].is_none() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n } else {\n if alt < dist[*neighbour].unwrap() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n }\n }\n }\n //println!(\"{:?} {:?}\", dist, prev);\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n }\n 0\n }\n\n fn set_cost(&mut self, x: usize, y: usize, cost: u64) {\n for i in 0..self.edges[x].len() {\n if self.edges[x][i].0 == y {\n self.edges[x][i].1 = cost\n }\n }\n for i in 0..self.edges[y].len() {\n if self.edges[y][i].0 == x {\n self.edges[y][i].1 = cost\n }\n }\n }\n}\n\nconst MODULO: u64 = 1_000_000_007;\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\nstruct BigPrimeRing {\n inner: u64,\n}\n\nimpl From for BigPrimeRing\nwhere\n T: Into,\n{\n fn from(n: T) -> Self {\n Self {\n inner: n.into() % MODULO,\n }\n }\n}\n\nimpl std::ops::Add for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn add(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::AddAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn add_assign(&mut self, rhs: T) {\n self.inner += rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Sub for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn sub(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + MODULO - rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::SubAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn sub_assign(&mut self, rhs: T) {\n self.inner += MODULO;\n self.inner -= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Mul for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn mul(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner * rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::MulAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn mul_assign(&mut self, rhs: T) {\n self.inner *= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl BigPrimeRing {\n fn inverse(self) -> Self {\n if self.inner == 0 {\n return self;\n }\n let (_g, mut x, _y) = egcd(self.inner as i64, MODULO as i64);\n if x < 0 {\n x += MODULO as i64;\n }\n Self { inner: x as u64 }\n }\n}\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn main() -> Result<(), Box> {\n let _n = read_usize();\n let vec = read_multiple::();\n let mut one_count_vec = Vec::new();\n let mut one_count = 0;\n for v in vec.iter().rev() {\n if *v == 1 {\n one_count += 1\n }\n one_count_vec.push(one_count)\n }\n one_count_vec.reverse();\n let mut m = 0;\n let mut zero_count = 0;\n for (i, v) in vec.into_iter().enumerate() {\n if v == 0 {\n zero_count += 1;\n }\n if zero_count + one_count_vec[i] > m {\n m = zero_count + one_count_vec[i]\n }\n }\n println!(\"{}\", m);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "5c481834ee3d4cf3b8dc07d9c7cac35d", "src_uid": "c7b1f0b40e310f99936d1c33e4816b95", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (u64, u64) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\nfn get_fixed_num(n: u32) -> u32 {\n let str: String = n.to_string().chars().filter(|c| *c != '0').collect();\n return str.parse().unwrap();\n}\n \nfn main() {\n let a: u32 = read_line().parse().unwrap();\n let b: u32 = read_line().parse().unwrap();\n \n let c = a + b;\n \n if get_fixed_num(a) + get_fixed_num(b) == get_fixed_num(c) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n\n // let a_line_fixed: String = a_line.chars().filter(|c| c == '0').collect();\n // let b_line_fixed: String = b_line.chars().filter(|c| c == '0').collect();\n \n // let a_fixed: u32 = a_line_fixed.parse();\n // let b_fixed: u32 = b_line_fixed.parse();\n \n // println!(\"{}\", get_fixed_num(203));\n \n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2543ade78ce834170a385462d972cdad", "src_uid": "ac6971f4feea0662d82da8e0862031ad", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn no_zeros(x: u64) -> u64 {\n let mut result = 0u64;\n let mut current = x;\n let mut current10 = 1;\n while current > 0 {\n let dig = current % 10;\n if dig != 0 {\n result += current10 * dig;\n current10 *= 10;\n }\n current /= 10;\n }\n result\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: u64 = scan.next();\n let b: u64 = scan.next();\n let c = a + b;\n println!(\n \"{}\",\n if no_zeros(a) + no_zeros(b) == no_zeros(c) {\n \"YES\"\n } else {\n \"NO\"\n },\n );\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "15807dbf57bde410235535b946f5c1aa", "src_uid": "ac6971f4feea0662d82da8e0862031ad", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{HashSet,HashMap,VecDeque,BinaryHeap};\n\n// Functions\nfn remove_zero(n: u64) -> u64{\n let mut ret = 0;\n let mut nz:Vec = Vec::new();\n for d in n.to_string().chars(){\n if d!='0'{\n nz.push(d as u64 -48);\n }\n }\n for d in nz{\n ret = ret*10 + d;\n }\n return ret;\n}\n\n// Main\nfn main(){\n input!{\n A: u64,\n B: u64\n }\n let na = remove_zero(A);\n let nb = remove_zero(B);\n let nc = remove_zero(A+B);\n println!(\"{}\", if na+nb==nc{\"YES\"}else{\"NO\"});\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "892ab793ec519e562c2b2e9eea9cd0cf", "src_uid": "ac6971f4feea0662d82da8e0862031ad", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(a,b = input.i());\n let c = a + b;\n let f = |x: i32| -> i32 {\n let mut d = 1_000_000_000;\n let mut res = 0;\n while d > 0 {\n let y = x / d % 10;\n if y > 0 {\n res = res * 10 + y;\n }\n d /= 10;\n }\n res\n };\n if f(a) + f(b) == f(c) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7ecc025ca9d7ac159d1eee8699c29436", "src_uid": "ac6971f4feea0662d82da8e0862031ad", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::mem::size_of_val;\nuse std::cmp::{max, min};\nuse std::rc::Rc;\nuse std::collections::btree_map::BTreeMap;\nuse std::io::{Write, BufRead};\nuse std::collections::{HashMap, BTreeSet};\nuse std::ptr::write_volatile;\nuse std::process::exit;\nuse std::thread;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused)]\nfn read_strings() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n v\n}\n\n#[allow(unused)]\nfn read_array_i32() -> Vec {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.split_whitespace().map(|x| x.parse::().unwrap()).collect()\n}\n\n\n#[allow(unused_macros)]\nmacro_rules! read_array {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap())\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n// mod math;\n// mod binary_search;\n// mod graph;\n// mod structure;\n// mod fibonacci;\n// mod string;\n// mod permutations;\n// mod patterns;\n\n\n#[allow(dead_code)]\nfn memory_properties(value: &T)\n where\n T: std::fmt::Display + ?Sized,\n{\n println!(\n \"Variable address in memory = {:p}, Allocated bytes for type = {}\",\n value,\n size_of_val(value)\n );\n}\n\n#[allow(unused_macros)]\nmacro_rules! sum {\n ($($x:expr), *) => {\n {\n let mut res = 0;\n $(res += $x;)*\n res\n }\n };\n}\n\nstatic mut array: [[u8;51];51] = [[0u8; 51]; 51];\n\nfn main() {\n use std::io::Write;\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n\n let mut res = 0;\n let s = gets();\n let mut seq = BTreeSet::<&str>::new();\n for i in 0..s.len() {\n for j in i + 1 .. s.len() + 1 {\n if seq.contains(&s[i..j]){\n res = max(res, j - i);\n } else {\n seq.insert(&s[i..j]);\n }\n }\n }\n writeln!(out, \"{}\", res);\n // writeln!(out, \"{}\", \"Hello Rust\").unwrap();\n}", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "8b79adde035b387b300a8b7c19717d7b", "src_uid": "13b5cf94f2fabd053375a5ccf3fd44c7", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut sc = new(std::io::stdin());\n let n: usize = sc.next();\n let mut a: Vec = vec![];\n let mut tot = 0;\n for i in 0..n {\n a.push(sc.next());\n tot += a[i];\n }\n let mut dp = vec![vec![0;2]; n+1];\n for i in (0..n).rev() {\n if i == n - 1 {\n dp[i][0] = a[i];\n dp[i][1] = 0;\n } else {\n dp[i][0] = std::cmp::max(dp[i + 1][0], a[i] + dp[i + 1][1]);\n dp[i][1] = std::cmp::min(dp[i + 1][1] + a[i], dp[i + 1][0]);\n }\n }\n println!(\"{} {}\", tot - dp[0][0], dp[0][0]);\n}\n\nuse std::io;\nuse std::io::BufRead;\n\npub struct Scanner {\n br: io::BufReader,\n // Read tokens are stored in reversed order per line.\n buf: Vec,\n}\n\npub fn new(r: R) -> Scanner {\n Scanner::new(r)\n}\n\nimpl Scanner {\n #[inline]\n fn new(r: R) -> Scanner {\n Scanner {\n br: io::BufReader::new(r),\n buf: vec![],\n }\n }\n #[inline]\n pub fn next(&mut self) -> T\n where T: std::str::FromStr,\n T::Err: std::fmt::Debug\n {\n self.next_string().map(|s| s.parse::().expect(\"Parse failed: \")).unwrap()\n }\n fn next_string(&mut self) -> Option {\n self.buf.pop().or_else(|| match self.update() {\n true => self.next_string(),\n false => None,\n })\n }\n #[inline]\n fn update(&mut self) -> bool {\n let mut s = String::new();\n let res = self.br.read_line(&mut s);\n match res.expect(\"I/O error.\") {\n 0 => false,\n _ => {\n self.buf = s.split_whitespace().map(|x| x.to_string()).rev().collect();\n true\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["dp", "games"], "code_uid": "031df6c2b5d5dedaf1d8c6fdf5d874da", "src_uid": "414540223db9d4cfcec6a973179a0216", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\nuse std::io::{StdinLock, stdin, BufRead};\nuse std::collections::*;\nuse std::cmp::*;\n\nfn scan_helper(lock : &mut StdinLock) -> String {\n let mut buffer = String::new();\n lock.read_line(&mut buffer).ok();\n buffer\n}\n\nmacro_rules! scan {\n ($lock:ident, $t:ty) => ({\n scan_helper(&mut $lock).split_whitespace()\n .next().unwrap()\n .parse::<$t>().unwrap()\n });\n ($lock:ident, $($t:ty),+) => ({\n let buffer = scan_helper(&mut $lock);\n let mut iter = buffer.split_whitespace();\n ($(\n {\n iter.next().unwrap()\n .parse::<$t>().unwrap()\n },\n )+)\n })\n}\n\nmacro_rules! scan_iter {\n ($lock:ident, $t:ty) => ({\n scan_helper(&mut $lock).split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect()\n })\n}\n\ntrait Ext {\n fn idx(&self) -> usize;\n fn num(&self) -> i64;\n}\n\nmacro_rules! ext {\n ($t:ty) => (\n impl Ext for $t {\n #[inline]\n fn idx(&self) -> usize {\n *self as usize\n }\n\n #[inline]\n fn num(&self) -> i64 {\n *self as i64\n }\n }\n )\n}\next!(i64);\next!(usize);\n\nmacro_rules! derive_regular {\n ($t:ty) => (\n impl Ord for $t {\n fn cmp(&self, other : &$t) -> Ordering {\n self.partial_cmp(other).unwrap()\n }\n }\n impl PartialEq for $t {\n fn eq(&self, other : &$t) -> bool {\n self.cmp(other) == Ordering::Equal\n }\n }\n impl Eq for $t {}\n )\n}\n\nfn solve(v : &Vec, n : i64, d : bool, memo : &mut HashMap<(i64, bool), (i64, i64)>) -> (i64, i64) {\n if n == v.len().num() {\n if d {\n return (0, 0);\n } else {\n return (0, 0);\n }\n }\n if let Some(&x) = memo.get(&(n, d)) {\n return x;\n }\n\n let mut take = solve(v, n+1, !d, memo);\n if d {\n take.1 += v[n.idx()];\n } else {\n take.0 += v[n.idx()];\n }\n let mut defer = solve(v, n+1, d, memo);\n if d {\n defer.0 += v[n.idx()];\n } else {\n defer.1 += v[n.idx()];\n }\n\n let result = if d {\n if take.1 >= defer.1 {\n take\n } else {\n defer\n }\n } else {\n if take.0 >= defer.0 {\n take\n } else {\n defer\n }\n };\n memo.insert((n, d), result);\n\n result\n}\n\nfn main() {\n let stdin = stdin();\n let mut s = stdin.lock();\n let n = scan!(s, i64);\n let data : Vec<_> = scan_iter!(s, i64);\n\n let mut memo = HashMap::new();\n\n let result = solve(&data, 0, true, &mut memo);\n println!(\"{} {}\", result.0, result.1);\n}", "lang_cluster": "Rust", "tags": ["dp", "games"], "code_uid": "eac50dfbc0ea85358109a74f6538ee10", "src_uid": "414540223db9d4cfcec6a973179a0216", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 992C\nuse std::io;\n\nfn main() {\n let (mut x, k) = read_2::(&io::stdin());\n let modulo = 1000000007;\n if x == 0 {\n println!(\"{}\", x);\n return;\n }\n x = x % modulo;\n let a = (mod_exp(2, k + 1, modulo) * x) % modulo;\n let b = mod_exp(2, k, modulo);\n if a >= b {\n println!(\"{}\", (a - b + 1) % modulo);\n } else {\n println!(\"{}\", ((modulo + a) - b + 1) % modulo);\n }\n}\n\nfn mod_exp(mut a: u64, mut k: u64, n: u64) -> u64 {\n let mut multiplier = 1;\n a = a % n;\n while k != 0 {\n if k % 2 == 1 {\n multiplier = (multiplier * a) % n;\n }\n a = (a * a) % n;\n k = k / 2;\n }\n multiplier\n}\n\nfn read_2(stdin: &io::Stdin) -> (T, T)\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n let mut iter = s.trim().split_whitespace().map(|x| x.parse().unwrap());\n (iter.next().unwrap(), iter.next().unwrap())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "dc954b60dfc172f4829414ab67da5adc", "src_uid": "e0e017e8c8872fc1957242ace739464d", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let mut x: i32 = scan.token();\n let mut m: i32 = scan.token();\n\n while m % 2 == 0 {\n m /= 2;\n }\n while x % 2 == 0 {\n x /= 2;\n }\n\n writeln!(out, \"{}\", if x % m == 0 { \"Yes\" } else { \"No\" })?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "implementation"], "code_uid": "718d8b4914b6dd8bfb35932b93f47177", "src_uid": "f726133018e2149ec57e113860ec498a", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let mut x: i32 = scan.token();\n let m: i32 = scan.token();\n\n x %= m;\n\n let mut seen = vec![false; m as usize];\n\n while x > 0 && !seen[x as usize] {\n seen[x as usize] = true;\n x += x;\n if x >= m {\n x -= m;\n }\n }\n\n writeln!(out, \"{}\", match x {\n 0 => \"Yes\",\n _ => \"No\",\n })?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "implementation"], "code_uid": "92d50aa30ab1070d72437f1d0d3b39bb", "src_uid": "f726133018e2149ec57e113860ec498a", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let mut x: u32 = scan.token();\n let mut m: u32 = scan.token();\n\n x >>= x.trailing_zeros();\n m >>= m.trailing_zeros();\n\n writeln!(out, \"{}\", if x % m == 0 { \"Yes\" } else { \"No\" })?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "implementation"], "code_uid": "c654e9b8d113f6a54e204cb4fbc0618c", "src_uid": "f726133018e2149ec57e113860ec498a", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n\nuse input::*;\n\nfn main() {\n let (n, k): (usize, u64);\n input!(n, k);\n let mut factorial = vec![1];\n for i in 1..n + 1 {\n let prev = *factorial.last().unwrap();\n factorial.push((i as u64 * prev) % k);\n }\n\n let mut ans = 0;\n for l in 1..n + 1 {\n ans += ((factorial[l] * factorial[n - l + 1]) % k * (n as u64 - l as u64 + 1)) % k;\n ans %= k;\n }\n p(ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "d8a02045507decd39a31258be6b9461d", "src_uid": "020d5dae7157d937c3f58554c9b155f9", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1284/problem/C\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::io::Write;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n// Input macros.\n// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_line {\n ($t:tt) => {\n {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim_right().parse::<$t>().unwrap()\n }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\n// ===\n\nfn main() {\n input! {\n n: usize, m: i64\n };\n let mut fact = vec![0i64; n+1];\n fact[0] = 1;\n for i in 1..=n {\n fact[i] = fact[i-1] * (i as i64) % m;\n }\n\n let mut ans = 0;\n for i in 1..=n {\n ans += (n - i + 1) as i64 * fact[i] % m * fact[n-i] % m * ((n - i + 1) as i64) % m;\n ans %= m;\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "5066867b523588e8a924616d15de1d08", "src_uid": "020d5dae7157d937c3f58554c9b155f9", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nuse std::io::Read;\n\nuse std::collections::{HashMap, HashSet};\n\n//generate factorial modulo m\nfn fac_gen(n: i64, m: i64) -> Vec {\n let it = (1..=n).scan(1, |s, x: i64| {*s = *s * x % m; Some(*s)} );\n (1..=1).chain(it).collect()\n}\n\nfn main() {\n let mut buffer = String::new();\n {\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_to_string(&mut buffer).unwrap();\n }\n\n let arr = buffer\n .split_whitespace()\n .map(|x| x.parse::().expect(\"convert to number\"))\n .collect::>();\n\n let n = arr[0];\n let m = arr[1];\n\n let factorials = fac_gen(n, m);\n\n // dbg!(&factorials);\n\n let ans = (1..=n)\n .map(|length| (n-length+1) * factorials[length as usize] % m * factorials[(n-length + 1) as usize] % m )\n // .inspect(|x| {dbg!(x);} )\n .fold(0i64, |acc, x| (x + acc) % m);\n\n println!(\"{}\",ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "b90573ab79df8f743093b6ba31c44522", "src_uid": "020d5dae7157d937c3f58554c9b155f9", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n// _ _ _ _____ ___\n// _ __ ___ __ _ _ __ | |_ __ _/ / |___ / / _ \\\n// | '_ ` _ \\ / _` | '_ \\| __/ _` | | | |_ \\| | | |\n// | | | | | | (_| | | | | || (_| | | |___) | |_| |\n// |_| |_| |_|\\__,_|_| |_|\\__\\__,_|_|_|____/ \\___/\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n\n\nuse input::*;\nuse std::cmp;\nuse std::collections::HashMap;\n\nfn main() {\n let t: usize;\n input!(t);\n for _ in 0..t {\n let (n, k, d): (usize, usize, usize);\n input!(n, k, d);\n let v = input_vector::();\n let mut map = HashMap::new();\n let mut ans;\n for i in 0..d {\n *map.entry(v[i]).or_insert(0) += 1;\n }\n ans = map.len();\n for i in 0..n - d {\n *map.entry(v[i + d]).or_insert(0) += 1;\n let buf = map[&v[i]] - 1;\n map.insert(v[i], buf);\n if map[&v[i]] == 0 {\n map.remove(&v[i]);\n }\n //println!(\"{:?}->{}\",&map,map.len());\n ans = cmp::min(ans, map.len());\n }\n p(ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a0de2c43bed998d44384cc390ad604af", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub trait Readable {\n type Output;\n fn words_count() -> usize;\n fn read_words(words: &[&str]) -> Result;\n}\n#[macro_export]\nmacro_rules! readable {\n ( $ t : ty , $ words_count : expr , |$ words : ident | $ read_words : expr ) => {\n impl Readable for $t {\n type Output = $t;\n fn words_count() -> usize {\n $words_count\n }\n fn read_words($words: &[&str]) -> Result<$t, String> {\n Ok($read_words)\n }\n }\n };\n}\nreadable!((), 1, |_ss| ());\nreadable!(String, 1, |ss| ss[0].to_string());\nimpl Readable for char {\n type Output = char;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result {\n let chars: Vec = words[0].chars().collect();\n if chars.len() == 1 {\n Ok(chars[0])\n } else {\n Err(format!(\"cannot parse `{}` as a char\", words[0]))\n }\n }\n}\npub struct Chars();\nimpl Readable for Chars {\n type Output = Vec;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result, String> {\n Ok(words[0].chars().collect())\n }\n}\nmacro_rules ! impl_readable_for_ints { ( $ ( $ t : ty ) * ) => { $ ( impl Readable for $ t { type Output = Self ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result <$ t , String > { use std :: str :: FromStr ; <$ t >:: from_str ( words [ 0 ] ) . map_err ( | _ | { format ! ( \"cannot parse `{}` as {}\" , words [ 0 ] , stringify ! ( $ t ) ) } ) } } ) * } ; }\nimpl_readable_for_ints ! ( i8 u8 i16 u16 i32 u32 i64 u64 isize usize f32 f64 ) ;\nmacro_rules ! define_one_origin_int_types { ( $ new_t : ident $ int_t : ty ) => { # [ doc = \" Converts 1-origin integer into 0-origin when read from stdin.\" ] # [ doc = \"\" ] # [ doc = \" # Example\" ] # [ doc = \"\" ] # [ doc = \" ```no_run\" ] # [ doc = \" # #[macro_use] extern crate atcoder_snippets;\" ] # [ doc = \" # use atcoder_snippets::read::*;\" ] # [ doc = \" // Stdin: \\\"1\\\"\" ] # [ doc = \" read!(a = usize_);\" ] # [ doc = \" assert_eq!(a, 0);\" ] # [ doc = \" ```\" ] # [ allow ( non_camel_case_types ) ] pub struct $ new_t ; impl Readable for $ new_t { type Output = $ int_t ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { <$ int_t >:: read_words ( words ) . map ( | n | n - 1 ) } } } ; ( $ new_t : ident $ int_t : ty ; $ ( $ inner_new_t : ident $ inner_int_t : ty ) ;* ) => { define_one_origin_int_types ! ( $ new_t $ int_t ) ; define_one_origin_int_types ! ( $ ( $ inner_new_t $ inner_int_t ) ;* ) ; } ; }\ndefine_one_origin_int_types ! ( u8_ u8 ; u16_ u16 ; u32_ u32 ; u64_ u64 ; usize_ usize ) ;\nmacro_rules ! impl_readable_for_tuples { ( $ t : ident $ var : ident ) => ( ) ; ( $ t : ident $ var : ident ; $ ( $ inner_t : ident $ inner_var : ident ) ;* ) => { impl_readable_for_tuples ! ( $ ( $ inner_t $ inner_var ) ;* ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,*> Readable for ( $ t , $ ( $ inner_t ) ,* ) { type Output = ( <$ t >:: Output , $ ( <$ inner_t >:: Output ) ,* ) ; fn words_count ( ) -> usize { let mut n = <$ t >:: words_count ( ) ; $ ( n += <$ inner_t >:: words_count ( ) ; ) * n } # [ allow ( unused_assignments ) ] fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { let mut start = 0 ; let $ var = <$ t >:: read_words ( & words [ start .. start +<$ t >:: words_count ( ) ] ) ?; start += <$ t >:: words_count ( ) ; $ ( let $ inner_var = <$ inner_t >:: read_words ( & words [ start .. start +<$ inner_t >:: words_count ( ) ] ) ?; start += <$ inner_t >:: words_count ( ) ; ) * Ok ( ( $ var , $ ( $ inner_var ) ,* ) ) } } } ; }\nimpl_readable_for_tuples ! ( T8 x8 ; T7 x7 ; T6 x6 ; T5 x5 ; T4 x4 ; T3 x3 ; T2 x2 ; T1 x1 ) ;\npub trait ReadableFromLine {\n type Output;\n fn read_line(line: &str) -> Result;\n}\nfn split_into_words(line: &str) -> Vec<&str> {\n #[allow(deprecated)]\n line.trim_right_matches('\\n').split_whitespace().collect()\n}\nimpl ReadableFromLine for T {\n type Output = T::Output;\n fn read_line(line: &str) -> Result {\n let words = split_into_words(line);\n if words.len() != T::words_count() {\n return Err(format!(\n \"line `{}` has {} words, expected {}\",\n line,\n words.len(),\n T::words_count()\n ));\n }\n T::read_words(&words)\n }\n}\nmacro_rules ! impl_readable_from_line_for_tuples_with_from_iterator { ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident ) => { impl <$ u : Readable > ReadableFromLine for $ seq_in where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = $ seq_out ; fn read_line ( line : & str ) -> Result <$ seq_out , String > { let n = $ u :: words_count ( ) ; let words = split_into_words ( line ) ; if words . len ( ) % n != 0 { return Err ( format ! ( \"line `{}` has {} words, expected multiple of {}\" , line , words . len ( ) , n ) ) ; } let mut result = Vec :: new ( ) ; for chunk in words . chunks ( n ) { match $ u :: read_words ( chunk ) { Ok ( v ) => result . push ( v ) , Err ( msg ) => { let flagment_msg = if n == 1 { format ! ( \"word {}\" , result . len ( ) ) } else { let l = result . len ( ) ; format ! ( \"words {}-{}\" , n * l + 1 , ( n + 1 ) * l ) } ; return Err ( format ! ( \"{} of line `{}`: {}\" , flagment_msg , line , msg ) ) ; } } } Ok ( result . into_iter ( ) . collect ( ) ) } } impl < T : Readable , $ u : Readable > ReadableFromLine for ( T , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( T :: Output , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let n = T :: words_count ( ) ; # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; Ok ( ( T :: read_words ( words ) ?, <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident , $ ( $ inner_t : ident $ inner_var : ident ) ,+ ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ seq_in , $ seq_out ; $ ( $ inner_t $ inner_var ) ,+ ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,+ , $ u : Readable > ReadableFromLine for ( $ t , $ ( $ inner_t ) ,+ , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( $ t :: Output , $ ( $ inner_t :: Output ) ,+ , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let mut n = $ t :: words_count ( ) ; $ ( n += $ inner_t :: words_count ( ) ; ) + # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; let ( $ var , $ ( $ inner_var ) ,* ) = < ( $ t , $ ( $ inner_t ) ,+ ) >:: read_words ( words ) ?; Ok ( ( $ var , $ ( $ inner_var ) ,* , <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; }\n#[macro_export]\nmacro_rules ! readable_collection { ( $ u : ident => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 x4 , T3 x3 , T2 x2 , T1 x1 ) ; } ; ( $ u : ident : $ ( $ bound : path ) ,* => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 x4 , T3 x3 , T2 x2 , T1 x1 ) ; } }\nreadable_collection ! ( U => Vec < U >, Vec < U :: Output > ) ;\nreadable_collection ! ( U => std :: collections :: VecDeque < U >, std :: collections :: VecDeque < U :: Output > ) ;\nreadable_collection ! ( U : Eq , std :: hash :: Hash => std :: collections :: HashSet < U >, std :: collections :: HashSet < U :: Output > ) ;\nreadable_collection ! ( U : Ord => std :: collections :: BTreeSet < U >, std :: collections :: BTreeSet < U :: Output > ) ;\nreadable_collection ! ( U : Ord => std :: collections :: BinaryHeap < U >, std :: collections :: BinaryHeap < U :: Output > ) ;\npub fn read() -> T::Output {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n T::read_line(&line).unwrap()\n}\n#[macro_export]\nmacro_rules ! read { ( ) => { let mut line = String :: new ( ) ; std :: io :: stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; } ; ( $ pat : pat = $ t : ty ) => { let $ pat = read ::<$ t > ( ) ; } ; ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { read ! ( ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) ) ; } ; }\n#[macro_export]\nmacro_rules ! readls { ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { $ ( read ! ( $ pat = $ t ) ; ) * } ; }\npub fn readx() -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result = stdin\n .lock()\n .lines()\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n result\n}\n#[macro_export]\nmacro_rules ! readx_loop { ( |$ pat : pat = $ t : ty | $ body : expr ) => { { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; for line in stdin . lock ( ) . lines ( ) { let line = line . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readx_loop ! ( | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub fn readn(n: usize) -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result: Vec = stdin\n .lock()\n .lines()\n .take(n)\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n if result.len() < n {\n panic!(\n \"expected reading {} lines, but only {} lines are read\",\n n,\n result.len()\n );\n }\n result\n}\n#[macro_export]\nmacro_rules ! readn_loop { ( $ n : expr , |$ pat : pat = $ t : ty | $ body : expr ) => { { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; let mut lock = stdin . lock ( ) ; for _ in 0 ..$ n { let mut line = String :: new ( ) ; lock . read_line ( & mut line ) . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( $ n : expr , |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readn_loop ! ( $ n , | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub trait Words {\n fn read(&self) -> T::Output;\n}\nimpl<'a> Words for [&'a str] {\n fn read(&self) -> T::Output {\n T::read_words(self).unwrap()\n }\n}\nimpl<'a> Words for &'a str {\n fn read(&self) -> T::Output {\n T::read_words(&[self]).unwrap()\n }\n}\n\n#[derive(Clone)]\npub struct HashCounter {\n counter: std::collections::HashMap,\n}\npub struct HashCounterIter<'a, T: 'a> {\n iter: std::collections::hash_map::Iter<'a, T, usize>,\n}\nimpl<'a, T> Iterator for HashCounterIter<'a, T> {\n type Item = (&'a T, usize);\n fn next(&mut self) -> Option<(&'a T, usize)> {\n while let Some((key, &count)) = self.iter.next() {\n if count > 0 {\n return Some((key, count));\n }\n }\n None\n }\n}\npub struct HashCounterIntoIter {\n iter: std::collections::hash_map::IntoIter,\n}\nimpl<'a, T> Iterator for HashCounterIntoIter {\n type Item = (T, usize);\n fn next(&mut self) -> Option<(T, usize)> {\n while let Some((key, count)) = self.iter.next() {\n if count > 0 {\n return Some((key, count));\n }\n }\n None\n }\n}\npub struct HashCounterValues<'a, T: 'a> {\n iter: std::collections::hash_map::Values<'a, T, usize>,\n}\nimpl<'a, T> Iterator for HashCounterValues<'a, T> {\n type Item = usize;\n fn next(&mut self) -> Option {\n while let Some(&n) = self.iter.next() {\n if n > 0 {\n return Some(n);\n }\n }\n None\n }\n}\nimpl HashCounter {\n pub fn new() -> HashCounter {\n HashCounter {\n counter: std::collections::HashMap::new(),\n }\n }\n pub fn with_capacity(capacity: usize) -> HashCounter {\n HashCounter {\n counter: std::collections::HashMap::with_capacity(capacity),\n }\n }\n pub fn values(&self) -> HashCounterValues {\n HashCounterValues {\n iter: self.counter.values(),\n }\n }\n pub fn iter(&self) -> HashCounterIter {\n HashCounterIter {\n iter: self.counter.iter(),\n }\n }\n}\nstatic HASH_COUNTER_ZERO: usize = 0;\nimpl<'a, T, Q: ?Sized> std::ops::Index<&'a Q> for HashCounter\nwhere\n T: Eq + std::hash::Hash + std::borrow::Borrow,\n Q: Eq + std::hash::Hash,\n{\n type Output = usize;\n fn index(&self, key: &Q) -> &usize {\n self.counter.get(key).unwrap_or(&HASH_COUNTER_ZERO)\n }\n}\nimpl<'a, T, Q: ?Sized> std::ops::IndexMut<&'a Q> for HashCounter\nwhere\n T: Eq + std::hash::Hash + std::borrow::Borrow,\n Q: Eq + std::hash::Hash + std::borrow::ToOwned,\n{\n fn index_mut(&mut self, key: &Q) -> &mut usize {\n self.counter.entry(key.to_owned()).or_insert(0)\n }\n}\nimpl std::iter::FromIterator for HashCounter {\n fn from_iter(iter: I) -> HashCounter\n where\n I: IntoIterator,\n {\n let mut counter = HashCounter::new();\n for item in iter {\n *counter.counter.entry(item).or_insert(0) += 1;\n }\n counter\n }\n}\nimpl std::iter::IntoIterator for HashCounter {\n type Item = (T, usize);\n type IntoIter = HashCounterIntoIter;\n fn into_iter(self) -> HashCounterIntoIter {\n HashCounterIntoIter {\n iter: self.counter.into_iter(),\n }\n }\n}\n#[macro_export]\nmacro_rules ! hash_counter { ( $ ( $ item : expr ) ,* ) => { { let mut counter = HashCounter :: new ( ) ; $ ( counter [ &$ item ] += 1 ; ) * counter } } }\n\n#[macro_export]\n#[cfg(local)]\nmacro_rules! dbg {\n ( ) => {{\n use std::io::{self, Write};\n writeln!(io::stderr(), \"{}: dbg\", line!()).unwrap();\n }};\n ( $ e : expr ) => {{\n use std::io::{self, Write};\n let result = $e;\n writeln!(\n io::stderr(),\n \"{}: {} = {:?}\",\n line!(),\n stringify!($e),\n result\n )\n .unwrap();\n result\n }};\n}\n#[macro_export]\n#[cfg(not(local))]\nmacro_rules! dbg {\n ( ) => {};\n ( $ e : expr ) => {\n $e\n };\n}\n\nuse std::cmp;\n\nfn main() {\n read!(query_count = usize);\n for _ in 0..query_count {\n read!(_ = usize, _ = usize, d = usize);\n read!(aa = Vec);\n let mut l = 0;\n let mut r = d;\n let mut counter: HashCounter = aa[l..r].iter().cloned().collect();\n let mut cnt = counter.iter().count();\n let mut ans = cnt;\n dbg!((l, r, cnt));\n while r < aa.len() {\n if counter[&aa[l]] == 1 {\n cnt -= 1;\n }\n counter[&aa[l]] -= 1;\n l += 1;\n\n if counter[&aa[r]] == 0 {\n cnt += 1;\n }\n counter[&aa[r]] += 1;\n r += 1;\n\n ans = cmp::min(ans, cnt);\n dbg!((l, r, cnt));\n }\n println!(\"{}\", ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6138c141f995a348c56e8c55b6a703a9", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\nuse std::io;\nuse std::fs::File;\nuse std::io::BufReader;\nuse std::io::BufRead;\nuse std::collections::HashMap;\nuse std::cmp;\n\nstruct Reader {\n index: usize,\n items: Vec::,\n reader: Box\n}\n\nimpl Reader {\n fn read(&mut self) -> T {\n if self.index >= self.items.len() {\n let mut buffer = String::new();\n self.reader.read_line(&mut buffer).expect(\"Error reading new line\");\n self.items = buffer.split_ascii_whitespace().map(|x| x.to_string()).collect();\n self.index = 0;\n }\n\n let result = self.items[self.index].parse::();\n self.index += 1;\n return match result {\n Ok(value) => value,\n Err(_) => {\n panic!(\"Error reading next value\");\n }\n }\n }\n\n fn read_vec(&mut self) -> Vec:: {\n let mut buffer = String::new();\n self.reader.read_line(&mut buffer).expect(\"Error reading new line\");\n buffer.split_ascii_whitespace().map(|x| match x.parse::() {\n Ok(v) => v,\n Err(_) => {\n panic!(\"Error reading next value\")\n }\n }).collect()\n }\n\n fn new(from_file: bool) -> Reader {\n Reader {\n index: 0,\n items: Vec::with_capacity(0),\n reader: if from_file {\n Box::new(BufReader::new(File::open(\"./././src/input.txt\").unwrap())) \n }\n else {\n Box::new(BufReader::new(io::stdin())) \n }\n }\n }\n}\n\nfn main() {\n let mut reader = Reader::new(false);\n\n let mut q: i32 = reader.read();\n while q > 0 {\n q -= 1;\n\n let n: i32 = reader.read();\n let k: i32 = reader.read();\n let d: i32 = reader.read();\n let serials: Vec:: = reader.read_vec();\n let mut asnwer = std::i32::MAX;\n let mut i = 0;\n while i + d <= n {\n let mut j = 0;\n let mut used: HashMap:: = HashMap::new();\n let mut curr = 0;\n while j < d {\n let next = serials[(i + j) as usize];\n if !used.contains_key(&next) {\n curr += 1;\n }\n used.entry(next).or_insert(true);\n\n j += 1;\n }\n\n asnwer = cmp::min(asnwer, curr);\n i += 1;\n }\n\n println!(\"{}\", asnwer);\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0d8d6c399784a4f1ca46d4bc621eea4c", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_uint() -> usize {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n input_line.trim().parse::().unwrap()\n}\n\nfn read_uvec() -> Vec {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n input_line.trim().split(\" \").map(|x| x.parse::().unwrap()).collect::>()\n}\n\nfn main() {\n let t = read_uint();\n for _ in 0..t {\n let nkd = read_uvec();\n let n = nkd[0];\n let k = nkd[1];\n let d = nkd[2];\n let x = read_uvec().iter().map( |it| it - 1 ).collect::>();\n let mut c = vec!(0; k);\n let mut r = k;\n let mut s = 0;\n for it in 0..n {\n if c[ x[it] ] == 0 { s += 1 }\n c[ x[it] ] += 1;\n if it >= d {\n c[ x[ it-d ] ] -= 1;\n if c[ x[ it-d ] ] == 0 { s-= 1 }\n }\n if it >= d-1 {\n if s < r { r = s }\n }\n }\n println!(\"{}\", r )\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "cb81813594fed61f5ff92b19b745dc8e", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::collections::HashMap;\n\nmacro_rules! readln {\n () => {{ let mut line = String::new(); stdin().read_line(&mut line).unwrap(); line }};\n ($type:ty) => {{ readln!().split_whitespace().next().unwrap().parse::<$type>().unwrap() }};\n (|$type_vec:ty|) => {{ readln!().split_whitespace().map(|it| it.parse().unwrap()).collect::>() }};\n ($($type:ty),*) => {{ let line = readln!(); let mut iter = line.split_whitespace(); ($(iter.next().unwrap().parse::<$type>().unwrap(),)*) }};\n ($($type:ty),*, |$type_vec:ty|) => {{ let line = readln!(); let mut iter = line.split_whitespace();\n ($(iter.next().unwrap().parse::<$type>().unwrap(),)*iter.map(|it| it.parse().unwrap()).collect::>(),)}};\n}\n\nfn main() {\n let t = readln!(usize);\n for _ in 0..t {\n let (n, k, d) = readln!(usize, usize, usize);\n let a = readln!(|usize|);\n\n let mut count = HashMap::with_capacity(k);\n\n for i in 0..d {\n *count.entry(a[i]).or_insert(0usize) += 1;\n }\n\n let mut size = count.len();\n let mut min_size = size;\n for i in d..n {\n let x = count.entry(a[i - d]).or_insert(0);\n *x -= 1;\n if *x == 0 {\n size -= 1;\n }\n\n let y = count.entry(a[i]).or_insert(0);\n *y += 1;\n if *y == 1 {\n size += 1;\n }\n min_size = min_size.min(size);\n }\n println!(\"{}\", min_size);\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7f6f7183d36a509737a185fee270085f", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case, unused)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::*;\n\nmacro_rules! eprint {\n\t($($t:tt)*) => {{\n\t\tuse ::std::io::Write;\n\t\tlet _ = write!(::std::io::stderr(), $($t)*);\n\t}};\n}\nmacro_rules! eprintln {\n\t() => { eprintln!(\"\"); };\n\t($($t:tt)*) => {{\n\t\tuse ::std::io::Write;\n\t\tlet _ = writeln!(::std::io::stderr(), $($t)*);\n\t}};\n}\nmacro_rules! dbg {\n\t($v:expr) => {{\n\t\tlet val = $v;\n\t\teprintln!(\"[{}:{}] {} = {:?}\", file!(), line!(), stringify!($v), val);\n\t\tval\n\t}}\n}\n\nmacro_rules! mat {\n\t($($e:expr),*) => { Vec::from(vec![$($e),*]) };\n\t($($e:expr,)*) => { Vec::from(vec![$($e),*]) };\n\t($e:expr; $d:expr) => { Vec::from(vec![$e; $d]) };\n\t($e:expr; $d:expr $(; $ds:expr)+) => { Vec::from(vec![mat![$e $(; $ds)*]; $d]) };\n}\n\nmacro_rules! ok {\n\t($a:ident$([$i:expr])*.$f:ident()$(@$t:ident)*) => {\n\t\t$a$([$i])*.$f($($t),*)\n\t};\n\t($a:ident$([$i:expr])*.$f:ident($e:expr$(,$es:expr)*)$(@$t:ident)*) => { {\n\t\tlet t = $e;\n\t\tok!($a$([$i])*.$f($($es),*)$(@$t)*@t)\n\t} };\n}\n\npub fn readln() -> String {\n\tlet mut line = String::new();\n\t::std::io::stdin().read_line(&mut line).unwrap_or_else(|e| panic!(\"{}\", e));\n\tline\n}\n\nmacro_rules! read {\n\t($($t:tt),*; $n:expr) => {{\n\t\tlet stdin = ::std::io::stdin();\n\t\tlet ret = ::std::io::BufRead::lines(stdin.lock()).take($n).map(|line| {\n\t\t\tlet line = line.unwrap();\n\t\t\tlet mut it = line.split_whitespace();\n\t\t\t_read!(it; $($t),*)\n\t\t}).collect::>();\n\t\tret\n\t}};\n\t($($t:tt),*) => {{\n\t\tlet line = readln();\n\t\tlet mut it = line.split_whitespace();\n\t\t_read!(it; $($t),*)\n\t}};\n}\n\nmacro_rules! _read {\n\t($it:ident; [char]) => {\n\t\t_read!($it; String).chars().collect::>()\n\t};\n\t($it:ident; [u8]) => {\n\t\tVec::from(_read!($it; String).into_bytes())\n\t};\n\t($it:ident; usize1) => {\n\t\t$it.next().unwrap_or_else(|| panic!(\"input mismatch\")).parse::().unwrap_or_else(|e| panic!(\"{}\", e)) - 1\n\t};\n\t($it:ident; [usize1]) => {\n\t\t$it.map(|s| s.parse::().unwrap_or_else(|e| panic!(\"{}\", e)) - 1).collect::>()\n\t};\n\t($it:ident; [$t:ty]) => {\n\t\t$it.map(|s| s.parse::<$t>().unwrap_or_else(|e| panic!(\"{}\", e))).collect::>()\n\t};\n\t($it:ident; $t:ty) => {\n\t\t$it.next().unwrap_or_else(|| panic!(\"input mismatch\")).parse::<$t>().unwrap_or_else(|e| panic!(\"{}\", e))\n\t};\n\t($it:ident; $($t:tt),+) => {\n\t\t($(_read!($it; $t)),*)\n\t};\n}\n\npub fn main() {\n\tlet _ = ::std::thread::Builder::new().name(\"run\".to_string()).stack_size(32 * 1024 * 1024).spawn(run).unwrap().join();\n}\n\nconst MOD: u32 = 1_000_000_007;\n\nfn solve() {\n\tlet t = read!(usize);\n\tfor i in 0..t {\n\t\tlet (n,k,d) = read!(usize,usize,usize);\n\t\tlet a = read!([usize]);\n\t\tlet mut ans = n;\n\t\tlet mut sum = 0;\n\t\tlet mut v = vec![0;k+1];\n\t\tfor i in 0..n {\n\t\t\tif i < d {\n\t\t\t\tif v[a[i]]==0 {sum+=1;}\n\t\t\t\tv[a[i]]+=1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tans = min(ans, sum);\n\t\t\tv[a[i-d]]-=1;\n\t\t\tif v[a[i-d]]==0 {sum-=1;}\n\t\t\tv[a[i]]+=1;\n\t\t\tif v[a[i]]==1 {sum+=1;}\n\t\t\tans = min(ans, sum);\n\t\t}\n\t\tans = min(ans, sum);\n\t\tprintln!(\"{}\", ans);\n\t}\n}\n\nfn run() {\n solve();\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6d413fb5c740f5282fd0e4e9921120e8", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::BTreeSet;\nfn main() {\n let mut ri = ReadIn::new();\n let tp = ri.int2();\n let n = tp.0 as usize;\n let m = tp.1;\n let mut it = ri.ints();\n let mut num = Vec::new();\n for _ in 0..n {\n num.push(it.next().unwrap());\n }\n if n == 1 {\n println!(\"{}\", num[0] % m);\n return ;\n }\n let fst = num[0..n/2].to_vec();\n let snd = num[n/2..n].to_vec();\n let s1 = explore(fst,m);\n let s2 = explore(snd,m);\n let mut it3 = s1.iter();\n let mut it4 = s2.iter();\n let x = it3.next_back().unwrap();\n let y = it4.next_back().unwrap();\n let mut ans = (*x + *y) % m;\n let mut it1 = s1.iter();\n loop {\n match it1.next() {\n Some(v1) => {\n match s2.range(0..m-v1).next_back() {\n Some(v2) => {\n if v1 + v2 > ans {\n ans = v1 + v2;\n }\n },\n None => continue,\n }\n },\n None => break,\n }\n }\n println!(\"{}\", ans);\n}\n\nfn explore(v:Vec, m:i32) -> BTreeSet {\n let n = v.len();\n let mut st = BTreeSet::new();\n for msk in 0..1< 0 {\n s = (s + v[i]) % m;\n }\n }\n st.insert(s);\n }\n st\n}\n\nuse std::iter::Map;\nuse std::str::SplitWhitespace;\nuse std::io::stdin;\nuse std::mem::forget;\n\npub struct ReadIn(pub String);\n\nimpl ReadIn {\n pub fn new() -> ReadIn {\n ReadIn(String::new())\n }\n fn read_i32(s: &str) -> i32 {\n s.parse().unwrap()\n }\n pub fn read_line(&mut self) {\n self.0.clear();\n forget(stdin().read_line(&mut self.0));\n }\n pub fn ints(&mut self) -> Map i32> {\n self.read_line();\n self.0.split_whitespace().map(ReadIn::read_i32)\n }\n pub fn int(&mut self) -> i32 {\n self.ints().next().unwrap()\n }\n pub fn int2(&mut self) -> (i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap())\n }\n}\n", "lang_cluster": "Rust", "tags": ["meet-in-the-middle", "divide and conquer", "bitmasks"], "code_uid": "619ba4456c544b82c355aea561a6aada", "src_uid": "d3a8a3e69a55936ee33aedd66e5b7f4a", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn enumerate(a: &[u32], m: u32) -> Vec {\n let mut ans = vec![0];\n for &a in a.iter() {\n let mut next = ans.clone();\n for v in ans {\n next.push((v + a) % m);\n }\n ans = next;\n }\n ans.sort();\n ans.dedup();\n ans\n}\n\nfn run() {\n input! {\n n: usize,\n m: u32,\n a: [u32; n],\n }\n let mid = n / 2;\n let (l, r) = a.split_at(mid);\n let l = enumerate(l, m);\n let r = enumerate(r, m);\n let mut ans = (*l.last().unwrap() + *r.last().unwrap()) % m;\n let mut j = 0;\n for l in l.iter().rev() {\n while j + 1 < r.len() && *l + r[j + 1] < m {\n j += 1;\n }\n ans = std::cmp::max(ans, (*l + r[j]) % m);\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["meet-in-the-middle", "divide and conquer", "bitmasks"], "code_uid": "357dfc01d939a1a85153cae3f880c82e", "src_uid": "d3a8a3e69a55936ee33aedd66e5b7f4a", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn combs(s: &[u64]) -> Vec {\n let mut res = HashSet::new();\n res.insert(0);\n\n for &x in s {\n let copy = res.clone();\n for &y in © {\n res.insert(x + y);\n }\n }\n\n let mut v = res.iter().cloned().collect::>();\n v.sort();\n v\n}\n\nfn bsearch(t: u64, s: &[u64]) -> u64 {\n match s.binary_search(&t) {\n Ok(i) => s[i],\n Err(i) => {\n let mut i = i;\n if i >= s.len() {\n return s.last().cloned().unwrap();\n }\n while i > 0 && s[i] > t {\n i -= 1;\n }\n s[i]\n }\n }\n}\n\nfn main() {\n let (n, m) = get!(usize, u64);\n let s: Vec = get!(u64;;).into_iter().map(|x| x % m).collect();\n\n let v1 = combs(&s[..n / 2]);\n let v2 = combs(&s[n / 2..]);\n\n let ans = (1..40)\n .map(|i| {\n v1.iter()\n .map(|&x| (x + bsearch(i * m - x - 1, &v2)) % m)\n .max()\n .unwrap()\n })\n .max()\n .unwrap();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["meet-in-the-middle", "divide and conquer", "bitmasks"], "code_uid": "a2608fe0b2f68643daee73fa3c520d53", "src_uid": "d3a8a3e69a55936ee33aedd66e5b7f4a", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() -> io::Result<()> {\n let mut buf = String::new();\n io::stdin().read_to_string(&mut buf)?;\n let v: Vec = buf\n .split_ascii_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n let (k, mut l) = (v[0], v[1]);\n\n let mut ans = -1;\n while l % k == 0 {\n l /= k;\n ans += 1;\n }\n\n if l == 1 {\n println!(\"YES\");\n println!(\"{}\", ans);\n } else {\n println!(\"NO\");\n }\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1dcffcb54e9383951e285a2cff2dcc0d", "src_uid": "8ce89b754aa4080e7c3b2c3b10f4be46", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (k, l): (u64, u64);\n inputm!(k);\n inputm!(l);\n let mut cnt = 0;\n let mut buf = k;\n while buf < l {\n cnt += 1;\n buf *= k;\n }\n if buf == l {\n println!(\"YES\");\n println!(\"{}\", cnt);\n } else {\n println!(\"NO\");\n }\n}\n\npub mod input {\n use std::io;\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! inputm {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(clippy::match_wild_err_arm)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\",),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\nuse input::*;\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "3841ac4bb78c6ae214b2c42b5cf14612", "src_uid": "8ce89b754aa4080e7c3b2c3b10f4be46", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\n\nfn exec() {\n let mut sc = Scanner::new();\n let n: usize = sc.ne();\n let _: String = sc.ne();\n let hoge: String = sc.ne();\n if hoge == \"week\" {\n let ans = match n {\n val if val == 5 || val == 6 => 53,\n _ => 52,\n };\n println!(\"{}\", ans);\n } else {\n let ans = match n {\n val if val <= 29 => 12,\n val if val == 30 => 11,\n _ => 7,\n };\n println!(\"{}\", ans);\n }\n}\n\nfn main() {\n const STACK: usize = 16 * 1024 * 1024;\n let _ = std::thread::Builder::new()\n .stack_size(STACK)\n .spawn(|| { exec(); })\n .unwrap()\n .join()\n .unwrap();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => {\n panic!(\"parse error, {:?}\",\n String::from_utf8(self.buf[l..r].to_owned()))\n }\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "029d278e29c15adf629a5ff6b06056e7", "src_uid": "9b8543c1ae3666e6c163d268fdbeef6b", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n input.sk(1);\n if input.bs()[0] == b'm' {\n println!(\"{}\", if n <= 29 {12} else if n <= 30 {11} else {7});\n } else {\n println!(\"{}\", if n == 5 || n == 6 {53} else {52});\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3dc078f6548e9629ed54d92b8bfde5b6", "src_uid": "9b8543c1ae3666e6c163d268fdbeef6b", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::collections::BTreeSet;\n\nfn main() -> () {\n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n handle.read_to_string(&mut buffer).unwrap();\n\n let mut arr = buffer.split_whitespace().take(1).map(|x| x.parse::().unwrap() ).collect::>();\n let n = arr[0] as usize;\n let mut num = buffer.split_whitespace().skip(1).take(1).next().unwrap();\n let mut b = vec![];\n for i in num.chars() {\n let digit = i as u32 - '0' as u32;\n b.push(digit);\n }\n let s : u32 = b.iter().sum();\n\n if s == 0 {\n println!(\"YES\");\n return\n }\n \n 'outer: for i in 1..s+1 {\n if s % i == 0 {\n let ss = s / i;\n let mut segsum = 0;\n let mut count_seg = 0;\n for j in 0..n {\n segsum += b[j];\n if segsum == ss {\n segsum = 0;\n count_seg += 1;\n } else if segsum > ss {\n continue 'outer;\n }\n }\n if count_seg > 1 {\n println!(\"YES\");\n return\n }\n }\n }\n\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "ddc6660524b9896a723c4638cbefbba1", "src_uid": "410296a01b97a0a39b6683569c84d56c", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn can_be_splitted(slice : &[i32], sum : i32) -> bool {\n let mut curr_sum = 0;\n let mut index = 0;\n let mut at_least_one = false;\n loop {\n if index >= slice.len() {\n return at_least_one && curr_sum == 0;\n }\n\n curr_sum += slice[index];\n if curr_sum == sum {\n curr_sum = 0;\n at_least_one = true;\n } else if curr_sum > sum {\n return false;\n }\n index += 1;\n }\n\n true\n}\n\nfn solve(length : usize, digits : Vec) -> (bool, i32) {\n let mut curr_sum = 0;\n for index in 0..(length - 1) {\n curr_sum += digits[index];\n if can_be_splitted(&digits[(index + 1)..], curr_sum) {\n return (true, curr_sum);\n }\n }\n (false, 0)\n}\n\nfn main() {\n let length = readln!(usize);\n \n let digits = readln!();\n let digits : Vec = digits.chars().map(|ch| ch.to_digit(10).unwrap() as i32).collect();\n\n let (result, sum) = solve(length, digits);\n\n println!(\"{}\", if result { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b3a9cb9714f208f29be3e4256ea1401f", "src_uid": "410296a01b97a0a39b6683569c84d56c", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input_text = String::new();\n io::stdin()\n .read_line(&mut input_text)\n .expect(\"failed to read from stdin\");\n\n let trimmed = input_text.trim();\n let mut no_of_digits: u32 = 0;\n match trimmed.parse::() {\n Ok(i) => no_of_digits = i,\n Err(..) => println!(\"this was not an integer: {}\", trimmed),\n };\n\n let mut input_digits = String::new();\n \tio::stdin()\n .read_line(&mut input_digits)\n .expect(\"failed to read from stdin\");\n let digits = input_digits.trim();\n\n \tlet mut answer : bool = false;\n \tlet total_sum: u32 = digits.chars().map(|x| x.to_digit(10).unwrap()).sum();\n for i in 1..total_sum {\n let mut sum: u32 = 0;\n \tfor c in digits.chars() {\n\t\t\tlet current_digit = c.to_digit(10).unwrap();\n\t\t\tsum += current_digit;\n\t\t\tif sum == i {\n\t\t\t\tsum = 0;\n\t\t\t}\n \t}\n \tif sum == 0 {\n \t\tanswer = true;\n \t}\n }\n if answer || total_sum == 0 {\n \tprintln!(\"YES\");\n } else {\n \tprintln!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "01eff0ee906f3baa36469e0883eaee69", "src_uid": "410296a01b97a0a39b6683569c84d56c", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::slice::Iter;\nuse std::iter::Peekable;\n\nfn check_step(iter : &mut Peekable>, check_sum : u64) -> Option {\n if iter.len() == 0 { return None }\n let mut sum = 0;\n while let Some(x) = iter.next() {\n sum += x;\n if sum == check_sum {\n while iter.peek().map(|x| **x == 0).unwrap_or(false) {\n iter.next();\n }\n return Some(true)\n }\n }\n Some(false)\n}\n\nfn check(iter : Iter, check_sum : u64) -> bool {\n if iter.len() == 0 { return false }\n let mut iter = iter.peekable();\n while let Some(flag) = check_step(&mut iter, check_sum) {\n if !flag { \n return false \n }\n }\n true\n}\n\nfn main() {\n let n = {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n buffer.trim().parse().unwrap()\n };\n let nums : Vec = {\n let mut buffer = String::with_capacity(n);\n let mut char_str = String::from(\"0\");\n io::stdin().read_line(&mut buffer).unwrap();\n buffer\n .trim()\n .chars()\n .map(|x| {\n char_str.pop();\n char_str.push(x);\n char_str.trim().parse().unwrap()\n })\n .collect()\n };\n let mut iter = nums.iter();\n let mut sum = 0;\n let mut sum_rest : u64 = nums.iter().fold(0, |acc, x| acc + x);\n while let Some(x) = iter.next() {\n sum_rest -= x;\n sum += x;\n if sum_rest.checked_rem(sum).map(|x| x == 0).unwrap_or_else(|| sum == sum_rest) {\n if check(iter.clone(), sum) {\n println!(\"YES\");\n return\n }\n }\n }\n println!(\"NO\");\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "4cc8e3124262c36f832319c998f1c282", "src_uid": "410296a01b97a0a39b6683569c84d56c", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn can_eat_row(r: &Vec) -> bool {\n for i in 0..r.len() {\n if !r[i] { return false }\n }\n true\n}\n\nfn can_eat_col(m: &Vec>, j: usize) -> bool {\n for r in m {\n if !r[j] { return false }\n }\n true\n}\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let a: Vec = s.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let r = a[0];\n let c = a[1];\n\n let mut v: Vec> = vec![];\n\n for _ in 0..r {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n v.push(s.trim().chars()\n .map(|x| x == '.')\n .collect()\n );\n }\n\n let mut eatable_rows = vec![];\n for i in 0..r as usize {\n if can_eat_row(&v[i]) { eatable_rows.push(i); }\n }\n\n let mut eatable_cols = vec![];\n for j in 0..c as usize {\n if can_eat_col(&v, j) { eatable_cols.push(j); }\n }\n\n let er = eatable_rows.len() as i32;\n let ec = eatable_cols.len() as i32;\n\n if er == 0 {\n println!(\"{}\", ec*r);\n } else if ec == 0 {\n println!(\"{}\", er*c);\n } else {\n println!(\"{}\", er*c + ec*(r-er));\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "fb644cbec4c0dd830df03e687b07bb09", "src_uid": "ebaf7d89c623d006a6f1ffd025892102", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn poisonous_row(r: &Vec) -> bool {\n for i in 0..r.len() {\n if !r[i] { return true }\n }\n false\n}\n\nfn poisonous_col(m: &Vec>, j: usize) -> bool {\n for r in m {\n if !r[j] { return true }\n }\n false\n}\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let a: Vec = s.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let r = a[0];\n let c = a[1];\n\n let mut v: Vec> = vec![];\n\n for _ in 0..r {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n v.push(s.trim().chars()\n .map(|x| x == '.')\n .collect()\n );\n }\n\n let mut poisonous_rows = 0;\n let mut poisonous_cols = 0;\n for i in 0..r as usize {\n if poisonous_row(&v[i]) { poisonous_rows += 1; }\n }\n for j in 0..c as usize {\n if poisonous_col(&v, j) { poisonous_cols += 1; }\n }\n\n println!(\"{}\", r*c - poisonous_rows*poisonous_cols);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "be62fd60c09d7153901ceab6d11ba6ea", "src_uid": "ebaf7d89c623d006a6f1ffd025892102", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: i64,\n m: i64,\n }\n if m % n != 0 {\n puts!(\"-1\\n\");\n return;\n }\n let mut x = m / n;\n let mut c = 0;\n while x % 2 == 0 {\n x /= 2;\n c += 1;\n }\n while x % 3 == 0 {\n x /= 3;\n c += 1;\n }\n if x != 1 {\n puts!(\"-1\\n\");\n } else {\n puts!(\"{}\\n\", c);\n }\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e7890041732bec99302d520d23e24f76", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n\u00ab\u0418\u0433\u0440\u0430 23\u00bb \u2014 \u0432\u043e\u0442 \u0432\u043e \u0447\u0442\u043e \u0441\u0435\u0439\u0447\u0430\u0441 \u0438\u0433\u0440\u0430\u0435\u0442 \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f. ;\n\u0418\u0437\u043d\u0430\u0447\u0430\u043b\u044c\u043d\u043e \u0443 \u043d\u0435\u0433\u043e \u0435\u0441\u0442\u044c \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e n \u0438 \u0435\u0433\u043e \u0446\u0435\u043b\u044c \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u0442\u044c \u0435\u0433\u043e \u0432 \u0446\u0435\u043b\u043e\u0435 \u0447\u0438\u0441\u043b\u043e m. \n\u0417\u0430 \u043e\u0434\u0438\u043d \u0445\u043e\u0434 \u043e\u043d \u043c\u043e\u0436\u0435\u0442 \u0443\u043c\u043d\u043e\u0436\u0438\u0442\u044c n \u043d\u0430 2 \u0438\u043b\u0438 \u0443\u043c\u043d\u043e\u0436\u0438\u0442\u044c n \u043d\u0430 3. \u041e\u043d \u043c\u043e\u0436\u0435\u0442 \u0441\u043e\u0432\u0435\u0440\u0448\u0430\u0442\u044c \u043b\u044e\u0431\u043e\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0445\u043e\u0434\u043e\u0432.\n\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0445\u043e\u0434\u043e\u0432, \u0441\u043a\u043e\u043b\u044c\u043a\u043e \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u041f\u043e\u043b\u0438\u043a\u0430\u0440\u043f\u0443, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u0438\u0437 \u0447\u0438\u0441\u043b\u0430 n \u0447\u0438\u0441\u043b\u043e m. \n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 -1, \u0435\u0441\u043b\u0438 \u044d\u0442\u043e \u043d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0441\u0434\u0435\u043b\u0430\u0442\u044c.\n*/\n\nuse std::io::{BufRead, Write, BufReader, BufWriter};\nconst MULTIPLE_TESTS: bool = false;\n\nfn task(n: u32, m: u32) -> i32 {\n let mut mult: u32 = m / n;\n if mult * n != m { return -1; }\n\n let mut steps = 0;\n while mult % 2 == 0 {\n steps += 1;\n mult /= 2;\n }\n while mult % 3 == 0 {\n steps += 1;\n mult /= 3;\n }\n if mult == 1 { steps } else { -1 }\n}\n\nfn main() -> std::io::Result<()> {\n let stdin = std::io::stdin();\n let stdout = std::io::stdout();\n let reader = BufReader::new(stdin.lock());\n let mut writer = BufWriter::new(stdout.lock());\n \n let mut lines = reader.lines();\n let n_tests: i32 = if MULTIPLE_TESTS {\n lines.next().unwrap().map(|s| s.parse::())?.unwrap()\n } else { 1 };\n\n for i in 0..n_tests {\n // read arguments\n let line = lines.next().unwrap()?;\n let args = line.split_whitespace().map(|s| s.parse::().unwrap()).collect::>();\n // run test\n let result = task(args[0], args[1]);\n writeln!(writer, \"{}\", result)?;\n }\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "2d9256c478e52892950438d27a7c9d31", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let (n, m) = parse_line!(u32, u32);\n if m % n != 0 {\n writeln!(writer, \"-1\").unwrap();\n return;\n }\n let mut q = m / n;\n let mut result = 0;\n while q % 2 == 0 {\n q /= 2;\n result += 1;\n }\n while q % 3 == 0 {\n q /= 3;\n result += 1;\n }\n if q != 1 {\n writeln!(writer, \"-1\").unwrap();\n }else{\n writeln!(writer, \"{}\", result).unwrap();\n }\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "751fdd72c85cadc304a7755fcaf3afc6", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn get_min_transform_move_num(n: usize, m: usize) -> Option {\n if (m % n) != 0 {\n return None;\n }\n let mut value: usize = m / n;\n let mut step_num: usize = 0;\n while value > 1 {\n if (value % 3) == 0 {\n value /= 3;\n step_num += 1;\n } else if (value % 2) == 0 {\n value /= 2;\n step_num += 1;\n } else {\n return None;\n }\n }\n return Some(step_num);\n}\n\n#[cfg(test)]\nmod test {\n use super::get_min_transform_move_num;\n\n #[test]\n fn test1() {\n assert_eq!(get_min_transform_move_num(120, 51840), Some(7));\n }\n #[test]\n fn test2() {\n assert_eq!(get_min_transform_move_num(42, 42), Some(0));\n }\n #[test]\n fn test3() {\n assert_eq!(get_min_transform_move_num(48, 72), None);\n }\n}\n\nfn read_data() -> (usize, usize) {\n let mut data_str: String = String::new();\n stdin().read_line(&mut data_str).unwrap();\n let data_str_values: Vec = data_str\n .trim()\n .split(\" \")\n .map(|s| s.parse::().unwrap())\n .collect();\n\n return (data_str_values[0], data_str_values[1]);\n}\n\nfn main() {\n let (n, m): (usize, usize) = read_data();\n\n let result: Option = get_min_transform_move_num(n, m);\n\n match result {\n Some(x) => println!(\"{}\", x),\n None => println!(\"-1\"),\n };\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d495c36cc07dfc7e28805b0f3e1fa68a", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = input.i();\n let b = input.i();\n let sol = if b % a > 0 {\n -1\n } else {\n let mut c = b / a;\n let mut sol = 0;\n for i in 2..4 {\n while c % i == 0 {\n c /= i;\n sol += 1;\n }\n }\n if c == 1 {\n sol\n } else {\n -1\n }\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "36fc318b5e7a8fa8da289dbd78c8d75a", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: u64,\n m: u64,\n }\n let mut x = m / n;\n let mut ans = 0;\n while x % 2 == 0 {\n x /= 2;\n ans += 1;\n }\n while x % 3 == 0 {\n x /= 3;\n ans += 1;\n }\n if m % n != 0 || x > 1 {\n println!(\"-1\");\n } else {\n println!(\"{}\", ans);\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "1aaefac8039be50cd9588cd3a2b2c128", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let stdin = io::stdin();\n\n let mut ln = String::new();\n stdin.read_line(&mut ln).unwrap();\n let mut iter = ln.split_whitespace();\n let mut n:u32 = iter.next().unwrap().parse().unwrap();\n let m:u32 = iter.next().unwrap().parse().unwrap();\n\n let mut count = 0;\n while m % (n * 2) == 0 {\n n *= 2;\n count += 1;\n }\n while m % (n * 3) == 0 {\n n *= 3;\n count += 1;\n }\n if n != m {\n count = -1;\n }\n println!(\"{}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "4e60e6c5bbc23e4d74912855801090dc", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, clippy::many_single_char_names, unused_variables, non_snake_case, unused_macros, unused_imports, non_upper_case_globals)]\nuse std::{\n collections::*,\n io::{stdin, StdinLock, stdout, StdoutLock, BufReader, BufRead, BufWriter, Write},\n mem::swap\n};\n\nfn parse(n: &str) -> T {\n match n.parse::() {\n Ok(x) => x,\n _ => panic!()\n }\n}\n\nmacro_rules! fill {\n ($r: expr, str, $($x: ident),+) => { fill!($r, str, 30, $($x),+) };\n ($r: expr, $t: ty, $($x: ident),+) => { fill!($r, $t, 30, $($x),+) };\n ($r: expr, str, $c: expr, $($x: ident),+) => {\n let t = read!($r, $c);\n let mut t = t.split(' ');\n\n $(\n $x = t.next().unwrap();\n )+\n };\n ($r: expr, $t: ty, $c: expr, $($x: ident),+) => {\n let t = read!($r, $c);\n let mut t = t.split(' ').map(parse::<$t>);\n\n $(\n $x = t.next().unwrap();\n )+\n }\n}\n\nmacro_rules! read {\n ($r: expr) => { read!($r, 20) };\n ($r: expr, str) => { read!($r, 20) };\n ($r: expr, $t: ty) => { parse::<$t>(&read!($r, 20)) };\n ($r: expr, str, $c: expr) => { read!($r, $c) };\n ($r: expr, $t: ty, $c: expr) => { parse::<$t>(&read!($r, $c)) };\n ($r: expr, $c: expr) => {\n {\n let mut s = String::with_capacity($c+2);\n $r.read_line(&mut s).unwrap();\n\n assert!(s.len() <= $c+2);\n\n if s.ends_with('\\n') {\n s.pop();\n if s.ends_with('\\r') {\n s.pop();\n }\n }\n s\n }\n }\n}\n\nmacro_rules! read_vec {\n ($r: expr) => { read_vec!($r, str, 10_000) };\n ($r: expr, str) => { read_vec!($r, str, 10_000) };\n ($r: expr, $t: ty) => { read_vec!($r, $t, 10_000) };\n ($r: expr, $c: expr) => { read_vec!($r, str, $c) };\n ($r: expr, str, $c: expr) => {\n {\n let v = read!($r, $c).split(' ').collect::>();\n assert!(v.len() <= $c); // $c is upper bound of string\n v\n }\n };\n ($r: expr, $t: ty, $c: expr) => { \n {\n let v = read!($r, $c).split(' ').map(parse::<$t>).collect::>();\n assert!(v.len() <= $c);\n v\n }\n };\n}\n\n\nfn main() {\n let r = stdin();\n let mut r = BufReader::with_capacity(10000, r.lock());\n\n let w = stdout();\n let mut w = BufWriter::with_capacity(10000, w.lock());\n unsafe { solve(&mut r, &mut w); }\n}\n\nconst M: usize = std::usize::MAX;\n\nunsafe fn solve(r: &mut BufReader, w: &mut BufWriter) {\n let (a, b);\n fill!(r, usize, 19, a, b);\n\n if b%a != 0 {\n writeln!(w, \"-1\").unwrap();\n } else {\n let m = b/a;\n let tz = m.trailing_zeros();\n let mut m = m>>tz;\n\n let mut i = 0;\n while m != 1 {\n if m%3 != 0 {\n write!(w, \"-1\").unwrap();\n return;\n }\n m /= 3;\n i += 1;\n }\n\n write!(w, \"{}\", tz+i).unwrap();\n }\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "0b33100635c150335452d3849f5fee54", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let n: u64 = it.next().unwrap().parse().unwrap();\n let k: u64 = it.next().unwrap().parse().unwrap();\n let ans = n / k * k + k;\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d49a52003dbfd4827709b054830d8ace", "src_uid": "75f3835c969c871a609b978e04476542", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::iter;\nuse std::cmp;\n\nfn main() {\n let (a, b): (f64, f64) = {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let mut it = input.split_whitespace().map(|k| k.parse().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let n1 = a.sqrt().floor() - 1.0;\n\n let delta = 1.0 + 4.0 * b;\n let n2 = (delta.sqrt() - 1.0) / 2.0;\n let n2 = n2.floor();\n\n if n1 < n2 {\n println!(\"Vladik\");\n } else {\n println!(\"Valera\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "4bee561c8a4c66f3a6035dd214d9bb54", "src_uid": "87e37a82be7e39e433060fd8cdb03270", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "mod max_flow {\n use std;\n type F = i32;\n pub const INF: F = 1000;\n const ZERO: F = 0;\n fn non_zero(f: F) -> bool {\n f > ZERO\n }\n fn min(a: F, b: F) -> F {\n if a < b {\n a\n } else {\n b\n }\n }\n pub struct Graph {\n n: usize,\n depth: Vec,\n it: Vec,\n g: Vec>,\n }\n impl Graph {\n pub fn new(n: usize) -> Graph {\n Graph {\n n: n,\n depth: vec![n + 1; n],\n it: vec![0; n],\n g: vec![vec![]; n],\n }\n }\n pub fn add_edge(&mut self, s: usize, t: usize, f: F) {\n let x = self.g[s].len();\n let y = self.g[t].len();\n self.g[s].push((t, f, y));\n self.g[t].push((s, ZERO, x));\n }\n fn bfs(&mut self, src: usize, dst: usize) {\n let g = &self.g;\n let n = self.n;\n let dp = &mut self.depth;\n dp.clear();\n dp.resize(n, n + 1);\n dp[src] = 0;\n let mut q = std::collections::VecDeque::new();\n q.push_back(src);\n 'outer: while let Some(v) = q.pop_front() {\n for &(u, f, _) in g[v].iter() {\n if dp[u] > dp[v] + 1 && non_zero(f) {\n dp[u] = dp[v] + 1;\n if u == dst {\n break 'outer;\n }\n q.push_back(u);\n }\n }\n }\n }\n fn dfs(&mut self, v: usize, src: usize, f: F) -> F {\n if v == src {\n return f;\n }\n while self.it[v] < self.g[v].len() {\n let (u, _, inv) = self.g[v][self.it[v]];\n if self.depth[u] < self.depth[v] && non_zero(self.g[u][inv].1) {\n let capa = min(f, self.g[u][inv].1);\n let c = self.dfs(u, src, capa);\n if non_zero(c) {\n self.g[v][self.it[v]].1 += c;\n self.g[u][inv].1 -= c;\n return c;\n }\n }\n self.it[v] += 1;\n }\n ZERO\n }\n pub fn flow(&mut self, src: usize, dst: usize) -> F {\n let mut ans = ZERO;\n loop {\n self.bfs(src, dst);\n if self.depth[dst] > self.n {\n break;\n }\n self.it.clear();\n self.it.resize(self.n, 0);\n loop {\n let f = self.dfs(dst, src, INF);\n if non_zero(f) {\n ans += f;\n } else {\n break;\n }\n }\n }\n ans\n }\n }\n}\n\nfn diff(a: usize, b: usize) -> usize {\n std::cmp::max(a, b) - std::cmp::min(a, b)\n}\n\n#[allow(dead_code)]\nfn test() {\n let n = 25;\n for h in 1..=n {\n print!(\"{:>2}: \", h);\n for w in 1..=n {\n let mut g = max_flow::Graph::new(h * w + 2);\n let src = h * w + 1;\n let dst = src - 1;\n for i in 0..h {\n for j in 0..w {\n if (i + j) & 1 == 0 {\n g.add_edge(src, i * w + j, 1);\n for k in 0..h {\n for l in 0..w {\n if diff(i, k) + diff(j, l) == 3 {\n g.add_edge(i * w + j, k * w + l, 1);\n }\n }\n }\n } else {\n g.add_edge(i * w + j, dst, 1);\n }\n }\n }\n let ans = g.flow(src, dst) * 2;\n let c = if ans as usize == h * w { ' ' } else { '!' };\n print!(\"{:>4}{}\", ans, c);\n }\n println!();\n }\n}\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let mut h: usize = it.next().unwrap().parse().unwrap();\n let mut w: usize = it.next().unwrap().parse().unwrap();\n if h > w {\n std::mem::swap(&mut h, &mut w);\n }\n if h * w <= 100 {\n let mut g = max_flow::Graph::new(h * w + 2);\n let src = h * w + 1;\n let dst = src - 1;\n for i in 0..h {\n for j in 0..w {\n if (i + j) & 1 == 0 {\n g.add_edge(src, i * w + j, 1);\n for k in 0..h {\n for l in 0..w {\n if diff(i, k) + diff(j, l) == 3 {\n g.add_edge(i * w + j, k * w + l, 1);\n }\n }\n }\n } else {\n g.add_edge(i * w + j, dst, 1);\n }\n }\n }\n let ans = g.flow(src, dst) * 2;\n println!(\"{}\", ans);\n } else if h == 1 {\n let mut ans = w / 6 * 6;\n if w % 6 >= 4 {\n ans += 2;\n }\n if w % 6 >= 5 {\n ans += 2;\n }\n println!(\"{}\", ans);\n } else if h % 2 == 1 && w % 2 == 1 {\n let ans = h as u64 * w as u64 - 1;\n println!(\"{}\", ans);\n } else {\n let ans = h as u64 * w as u64;\n println!(\"{}\", ans);\n }\n}\n\nfn main() {\n// test();\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "graph matchings"], "code_uid": "4b6f8d211edc128cdb199f8bd8247323", "src_uid": "02ce135a4b276d1e9ba6a4ce37f2fe70", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn solution(s: String, n: i32) -> i32 {\n let mut chars = s.trim().as_bytes().iter().cloned().map (|x| x - 96u8).collect::>();\n chars.sort();\n let mut iter = chars.iter().peekable();\n let mut not_found = false;\n let mut prev_char = *iter.next().unwrap() as i32;\n let mut sum = prev_char.clone() as i32;\n let mut m = n;\n loop {\n if m < 2 {\n break;\n }\n if iter.peek().is_none() {\n not_found = true;\n break;\n }\n\n let a = *iter.next().unwrap() as i32;\n if a - prev_char < 2 {\n continue;\n } \n sum += a.clone() as i32;\n prev_char = a;\n m-=1;\n }\n if not_found {-1} else {sum}\n}\n\nfn main() {\n assert_eq!(29,solution(String::from(\"xyabd\"),3));\n assert_eq!(34,solution(String::from(\"problem\"),4));\n assert_eq!(-1,solution(String::from(\"ab\"),2));\n assert_eq!(1,solution(String::from(\"abaabbaaabbb\"),1));\n\n\n let mut r = String::new();\n std::io::stdin().read_line(&mut r).unwrap();\n let mut ns = r.split_whitespace().map(|x| x.parse::().unwrap());\n ns.next().unwrap();\n let n = ns.next().unwrap();\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n println!(\"{}\",solution(s,n)); \n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "2920787fe45da16f6bf32cbedc561021", "src_uid": "56b13d313afef9dc6c6ba2758b5ea313", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{Read, stdin};\n\nfn main() {\n let mut buf = String::new();\n stdin().read_to_string(&mut buf).unwrap();\n let mut tok = buf.split_whitespace();\n let mut get = || tok.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(usize));\n }\n \n let _n = get!();\n let k = get!();\n let s = get().as_bytes();\n let mut xs = vec![false; 30];\n for &ch in s {\n xs[ch as usize - b'a' as usize] = true;\n }\n let xs: Vec<_> = xs\n .into_iter()\n .enumerate()\n .filter(|(_, v)| *v)\n .collect();\n \n if k * 2 > 26 || xs.len() < k {\n println!(\"-1\");\n return;\n }\n \n let mut ans = 0;\n let mut b = 27;\n let mut c = 0;\n for (i, _) in xs.iter() {\n let i = *i;\n if b + 1 != i {\n ans += i + 1;\n b = i;\n c += 1;\n if c >= k {\n break;\n }\n }\n }\n if c < k {\n println!(\"-1\");\n } else {\n println!(\"{}\", ans);\n }\n \n}", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "191a930fafa75156bbe82d7cb7f434c2", "src_uid": "56b13d313afef9dc6c6ba2758b5ea313", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n#![allow(non_camel_case_types)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{max, min, Ordering};\nuse std::f64::consts::*;\nuse std::mem::{swap, size_of_val, size_of};\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\nuse std::num::*;\nuse std::process::*;\n//use std::ptr::*;\nuse std::iter::{once, repeat};\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\nstruct Input {\n\tbuffer: Buf,\n}\n\nimpl Input {\n\tfn read_char(&mut self) -> char {\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\tx[0] as char\n\t}\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n}\n\nmacro_rules! read {\n () => {};\n\t($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect(\"Parsing error\"));\n\t($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect(\"Parsing error\")),*));\n}\nfn gcd(mut a: T, mut b: T) -> T\n\twhere T: ShrAssign + BitAnd + Ord + From + Clone + SubAssign + ShlAssign + Copy\n{\n\tlet one = T::from(1);\n\tlet zero = T::from(0);\n\tlet mut ans = 0;\n\tif a < b {\n\t\tswap(&mut a, &mut b);\n\t}\n\twhile b > zero {\n\t\tif (a & one > zero) && (b & one > zero) {\n\t\t\ta -= b;\n\t\t} else if a & one > zero {\n\t\t\tb >>= one;\n\t\t} else if b & one > zero {\n\t\t\ta >>= one;\n\t\t} else {\n\t\t\tans += 1;\n\t\t\ta >>= one;\n\t\t\tb >>= one;\n\t\t}\n\t\tif a < b {\n\t\t\tswap(&mut a, &mut b);\n\t\t}\n\t}\n\ta <<= ans;\n\ta\n}\n\nfn powmod(mut base: X, mut exp: Y, mm: X) -> X\n\twhere X: Copy + Clone + Mul + Rem + From,\n\t Y: ShrAssign + Copy + Clone + BitAnd + From + Ord\n{\n\tlet mut res = X::from(1);\n\twhile exp > Y::from(0) {\n\t\tif exp & Y::from(1) > Y::from(0) {\n\t\t\tres = res * base % mm;\n\t\t}\n\t\tbase = base * base % mm;\n\t\texp >>= Y::from(1);\n\t}\n\tres\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\")) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet stdin = stdin();\n\t\t\tlet istr = stdin.lock();\n\t\t\tlet mut inf = Input { buffer: BufReader::new(istr) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output) {\n\tlet n = read!(inf,usize);\n\tlet mut s1 = 0;\n\tlet mut s2 = 0;\n\tfor _i in 0..n {\n\t\tlet a = read!(inf,i32);\n\t\tif a < 0 {\n\t\t\ts2 += a;\n\t\t} else {\n\t\t\ts1 += a;\n\t\t}\n\t}\n\twriteln!(ouf, \"{}\", s1 - s2);\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "32a9921857d5217d4f140e7b2167cc6f", "src_uid": "4b5d14833f9b51bfd336cc0e661243a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get { \n () => (get().parse::().unwrap());\n }\n let n = get!();\n let mut ans = 0;\n for _ in 0..n {\n let a = get!();\n if a > 0 {\n ans += a;\n } else {\n ans -= a;\n }\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "dc9d0b933e080409ae24f4e1b3e32c9c", "src_uid": "4b5d14833f9b51bfd336cc0e661243a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\nuse std::io;\nuse std::str::SplitWhitespace;\n\nfn main() {\n let size = read_size();\n\n let mut v: Vec = vec![0; size as usize];\n\n let array_str = read_line();\n let mut iter = array_str.split_whitespace();\n\n for i in 0..size {\n v[i as usize] = read_split(&mut iter);\n }\n\n v.sort();\n\n let mut total = 0;\n for el in v.iter() {\n total += *el;\n }\n\n let mut answer = total;\n let mut neg = 0;\n\n for el in v.iter() {\n total -= *el;\n neg += *el;\n answer = cmp::max(answer, total - neg);\n }\n\n println!(\"{}\", answer);\n}\n\nfn read_size() -> i32 {\n let size_str = read_line();\n let mut iter = size_str.split_whitespace();\n read_split(&mut iter)\n}\n\nfn read_split(iter: &mut SplitWhitespace) -> i32 {\n iter.next().unwrap_or(\"-1\").parse::().unwrap_or(-1)\n}\n\nfn read_line() -> String {\n let mut first_line = String::new();\n io::stdin()\n .read_line(&mut first_line)\n .expect(\"stdin read error\");\n first_line\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "6766dd602fe51dab70e25b210111db9d", "src_uid": "4b5d14833f9b51bfd336cc0e661243a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "mod solution {\n use std::io::{self, Write, BufRead};\n\n pub fn solve() {\n let stdin = io::stdin();\n let mut iterator = stdin.lock().lines();\n iterator.next(); // Throw away first input\n let nums: Vec = iterator.next().unwrap().unwrap()\n .split(\" \")\n .into_iter()\n .map(|str_num| {\n let num: i32 = str_num.trim().parse().unwrap();\n num.abs() // Absolute value b/c -(-) -> (+)\n })\n .collect();\n let result: i32 = nums.iter().sum();\n io::stdout().write(&result.to_string().as_bytes()).unwrap();\n }\n}\n\nfn main() {\n solution::solve();\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "49a3b9c28dd81be1207f21d4e6b6c43c", "src_uid": "4b5d14833f9b51bfd336cc0e661243a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n buffer.clear();\n io::stdin().read_line(&mut buffer).unwrap();\n let ans = buffer.split_whitespace()\n .map(|x| i16::abs(x.trim().parse::().unwrap()))\n .sum::();\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "7a9cad3c5ec8aeeb3d166fb684b33f21", "src_uid": "4b5d14833f9b51bfd336cc0e661243a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn digits(mut n: u64) -> u64 {\n let mut count = 0u64;\n while n > 0 {\n count += 1;\n n /= 10;\n }\n return count;\n}\n\nfn main() {\n let n: u64 = read_line().parse().unwrap();\n \n let d = digits(n);\n let mut nums_counted = 0u64;\n let mut nines = 9u64;\n let mut res = 0u64;\n for i in 1 .. d {\n let cur_len = nines - nums_counted;\n nines = nines * 10 + 9;\n res += cur_len * i;\n nums_counted += cur_len;\n }\n \n let cur_len = n - nums_counted;\n res += cur_len * d;\n \n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "23f6413d4a6d3dea9eeaae389ceb98d3", "src_uid": "4e652ccb40632bf4b9dd95b9f8ae1ec9", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty, $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt, $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\n\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl std::iter::Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n: i64 = input.p();\n let mut sol = n * 0;\n let mut d = 1;\n let mut x = 1;\n loop {\n let xx = x * 10;\n if n < xx {\n sol += (n - x + 1) * d;\n break;\n } else {\n sol += (xx - x) * d;\n x = xx;\n d += 1;\n }\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "0dbd687be485f7c2fdc790d6f2069845", "src_uid": "4e652ccb40632bf4b9dd95b9f8ae1ec9", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n if self.f[crt] { return; }\n self.c += 1;\n self.f[crt] = true;\n self.v.push(crt);\n self.vc[crt] = self.c;\n self.u[crt] = self.v.len()-1;\n for i in 0..self.e[crt].len() {\n self.dfs(self.e[crt][i]);\n }\n //debug!(crt, self.c, self.vc[crt]);\n self.vc[crt] = self.c - self.vc[crt];\n }\n}\n\nfn binary_search(s: &Vec, v:i64) -> usize {\n let mut left = 0;\n let mut right = s.len();\n\n while right-left > 1 {\n let mid = (right+left)/2;\n //debug!(left,mid,right,s[mid]);\n if s[mid] < v { left = mid; }\n else { right = mid; }\n }\n left\n}\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let s:Vec = read::().chars().collect();\n\n let mut v:Vec<(String,i64)> = vec![];\n for i in 0..n-1 {\n let mut t = String::new();\n t.push(s[i]);\n t.push(s[i+1]);\n let mut f = false;\n for j in 0..v.len() {\n if t == v[j].0 {\n v[j].1 += 1;\n f = true;\n }\n }\n if !f {\n v.push((t,1));\n }\n }\n\n let mut t = String::new();\n let mut mx = 0;\n for i in 0..v.len() {\n if v[i].1 > mx {\n t = v[i].0.clone();\n mx = v[i].1;\n }\n }\n\n println!(\"{}\", t);\n\n\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "1f000a4314853ae980fad6da6614c4ce", "src_uid": "e78005d4be93dbaa518f3b40cca84ab1", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\n\nstruct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let _n: usize = scan.next();\n let input: Vec = scan.next::().chars().collect();\n let mut map: HashMap = HashMap::new();\n let mut res: String = String::new();\n let mut cnt = 0usize;\n for i in 0..input.len() - 1 {\n let current: String = input[i..=i + 1].iter().collect();\n map.entry(current.clone())\n .and_modify(|x| {\n *x += 1;\n })\n .or_insert(1);\n if map[¤t] > cnt {\n cnt = map[¤t];\n res = current.clone();\n }\n }\n println!(\"{}\", res);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d55969a7198dfe676abcfd80d576b873", "src_uid": "e78005d4be93dbaa518f3b40cca84ab1", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use rand::Rng;\nuse std::collections::HashMap;\nuse std::io;\nmacro_rules! parse_input {\n ($x:expr, $t:ident) => {\n $x.trim().parse::<$t>().unwrap()\n };\n}\n\nmacro_rules! split_line {\n ($y:expr, $t:ident) => {\n $y.split(\" \")\n .map(|z| parse_input!(z, $t))\n .collect::>();\n };\n}\n\nstruct xorrand {\n state: u64,\n}\n#[allow(dead_code)]\nimpl xorrand {\n fn rand(&mut self) -> u64 {\n let mut x = self.state;\n x ^= x << 13;\n x ^= x >> 7;\n x ^= x << 17;\n self.state = x;\n self.state.wrapping_mul(0x2545F4914F6CDD1Du64)\n }\n\n fn randint(&mut self, start: u64, end: u64) -> u64 {\n return (self.rand() % (end - start)) + start;\n }\n\n fn randfloat(&mut self) -> f64 {\n 1.0 / (self.rand() as f64)\n }\n\n fn new(seed: u64) -> xorrand {\n xorrand { state: seed }\n }\n\n fn newtime() -> xorrand {\n let start = std::time::SystemTime::now();\n let ms = start\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap()\n .as_secs();\n xorrand { state: ms }\n }\n\n fn shuffle(&mut self, tgt: &mut Vec) {\n for i in 0..tgt.len() - 1 {\n let j = self.randint(i as u64, tgt.len() as u64) as usize;\n let c = tgt[j].clone();\n tgt[j] = tgt[i].clone();\n tgt[i] = c;\n }\n }\n}\n\n#[derive(Debug, Clone)]\nstruct segment {\n start_0: i64,\n start_1: i64,\n end_0: i64,\n end_1: i64,\n}\n\nimpl segment {}\n\nfn solve(a: String, b: String) {\n let mut counters = vec![Vec::::new(); b.len() + 2];\n let mut start = 1;\n for i in 0..a.len() {\n for j in 0..start {\n if a.as_bytes()[i] == b.as_bytes()[j] {\n counters[j + 1].push(i as i64);\n if j == start - 1 && start < b.len() {\n start += 1;\n }\n }\n }\n }\n let mut end = a.len() as i64;\n for i in (0..b.len()).rev() {\n counters[i + 1].retain(|&x| x < end);\n end = *counters[i + 1].iter().max().unwrap();\n }\n counters[0].push(-1);\n counters[b.len() + 1].push(a.len() as i64);\n let mut best = 0;\n for i in 0..counters.len() - 1 {\n best = std::cmp::max(\n best,\n counters[i + 1].iter().max().unwrap() - counters[i].iter().min().unwrap() - 1,\n );\n }\n println!(\"{}\", best);\n}\n\nfn main() {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n let mut ss = String::new();\n io::stdin().read_line(&mut ss).unwrap();\n let ss = parse_input!(ss, String);\n let input_line = parse_input!(input_line, String);\n solve(input_line, ss);\n // let numTests = parse_input!(input_line, String);\n // solve(numTests as usize, &tgt);\n // // // let numTests = 1;\n // // let mut rng = rand::thread_rng();\n // for _ in 0..numTests {\n // let mut input_line = String::new();\n // io::stdin().read_line(&mut input_line).unwrap();\n // let s = split_line!(input_line, i64);\n // let mut input_line = String::new();\n // io::stdin().read_line(&mut input_line).unwrap();\n // let v = split_line!(input_line, i64);\n // // let v: Vec = (0..10).map(|_| rng.gen_range(0, 10000)).collect();\n\n // solve(s, v);\n // }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "4e4fa5c70682774d16509c26f1bc637f", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::fs::File;\n#[allow(unused_imports)]\nuse std::io::prelude::*;\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufReader, BufWriter, Stdin, Stdout, Write};\n#[allow(unused_imports)]\nuse std::mem::swap;\n#[allow(unused_imports)]\nuse std::str::FromStr;\n \ntype BoxResult = Result>;\n \nfn main() {\n let mut scanner = Scanner::new(stdin());\n let s = scanner.read_chars().unwrap();\n let t = scanner.read_chars().unwrap();\n let mut maximum = 0;\n for i in 0..s.len() {\n for j in i..s.len() {\n if judge(&s, &t, i, j) {\n maximum = max(j - i + 1, maximum);\n }\n }\n }\n println!(\"{}\", maximum);\n}\n\nfn judge(s: &[char], t: &[char], start: usize, end: usize) -> bool {\n let mut index = 0;\n for i in 0..s.len() {\n if i >= start && i <= end {\n continue;\n }\n if s[i] == t[index] {\n index += 1;\n }\n if index == t.len() {\n break;\n }\n }\n index == t.len()\n}\n \n#[allow(dead_code)]\nstruct Scanner {\n reader: BufReader,\n buffer: String,\n}\n \nimpl Scanner\nwhere\n R: Read,\n{\n #[allow(dead_code)]\n fn new(inner: R) -> Scanner {\n let reader = BufReader::new(inner);\n let buffer = String::new();\n Scanner {\n reader: reader,\n buffer: buffer,\n }\n }\n \n #[allow(dead_code)]\n fn with_capacity(capacity: usize, inner: R) -> Scanner {\n let reader = BufReader::with_capacity(capacity, inner);\n let buffer = String::new();\n Scanner {\n reader: reader,\n buffer: buffer,\n }\n }\n \n #[allow(dead_code)]\n fn read(&mut self) -> BoxResult\n where\n T: FromStr,\n T::Err: std::fmt::Debug,\n T::Err: std::error::Error,\n T::Err: 'static,\n {\n self.reader.read_line(&mut self.buffer)?;\n let parsed = self.buffer.trim().parse()?;\n self.buffer.clear();\n Ok(parsed)\n }\n \n #[allow(dead_code)]\n fn read_vector(&mut self) -> BoxResult>\n where\n T: FromStr,\n T::Err: std::fmt::Debug,\n T::Err: std::error::Error,\n T::Err: 'static,\n {\n self.reader.read_line(&mut self.buffer)?;\n let parsed_vec = self\n .buffer\n .trim()\n .split_whitespace()\n .map(|s| s.parse())\n .collect::, _>>()?;\n self.buffer.clear();\n Ok(parsed_vec)\n }\n \n #[allow(dead_code)]\n fn read_matrix(&mut self, lines: usize) -> BoxResult>>\n where\n T: FromStr,\n T::Err: std::fmt::Debug,\n T::Err: std::error::Error,\n T::Err: 'static,\n {\n let mut parsed_matrix = vec![];\n for _ in 0..lines {\n self.reader.read_line(&mut self.buffer)?;\n parsed_matrix.push(\n self.buffer\n .trim()\n .split_whitespace()\n .map(|s| s.parse())\n .collect::, _>>()?,\n );\n self.buffer.clear();\n }\n Ok(parsed_matrix)\n }\n \n #[allow(dead_code)]\n fn read_chars(&mut self) -> BoxResult> {\n self.reader.read_line(&mut self.buffer)?;\n let chars = self.buffer.trim().chars().collect::>();\n self.buffer.clear();\n Ok(chars)\n }\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "4790cde1aee46ce0c7815534a3a2a32f", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n s: chars,\n t: chars,\n }\n let mut dp = vec![0; t.len() + 1];\n dp[t.len()] = s.len();\n let mut j = t.len() - 1;\n for i in (0..s.len()).rev() {\n if s[i] == t[j] {\n dp[j] = i;\n j -= 1;\n }\n if j >= t.len() {\n break;\n }\n }\n let mut ans = dp[0];\n let mut j = 0;\n for i in 0..s.len() {\n if s[i] == t[j] {\n j += 1;\n ans = std::cmp::max(ans, dp[j] - i - 1);\n }\n if j >= t.len() {\n break;\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "897f72df2a878a1ce20be13bcf6660e0", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let s:Vec = read::().chars().collect();\n let t:Vec = read::().chars().collect();\n\n let mut ans = 0;\n // s \u306e substring s[i..j] \u3092\u8003\u3048\u308b\n for i in 0..s.len() {\n for j in i..s.len()+1 {\n //debug!(i,j);\n // substring \u3092\u9664\u3044\u305f\u6587\u5b57\u5217 s[0..i] + s[j..] \u3092\u8003\u3048\u308b\n let mut ss = vec![];\n for k in 0..i { ss.push(s[k]); }\n for k in j..s.len() { ss.push(s[k]); }\n // ss \u306e subsequence \u306b t \u304c\u542b\u307e\u308c\u308b\u304b\u5224\u5b9a\u3059\u308b\n let mut idx = 0;\n for k in 0..ss.len() {\n if idx >= t.len() { break; }\n if ss[k] == t[idx] {\n idx += 1;\n }\n }\n if idx >= t.len() {\n //debug!(i,j,ss);\n ans = max(ans, j-i);\n }\n }\n }\n println!(\"{}\", ans);\n\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "4fe025e55168d0e3d9c14b778a31a775", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::Write;\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($e:expr),*) => {\n #[cfg(debug_assertions)]\n $({\n let (e, mut err) = (stringify!($e), std::io::stderr());\n writeln!(err, \"{} = {:?}\", e, $e).unwrap()\n })*\n };\n}\n\nfn main() {\n let s = read::().chars().collect::>();\n let mut t = read::().chars().collect::>();\n\n let mut fastest_poses = vec![];\n let mut slowest_poses = vec![];\n for i in 0..2 {\n let mut poses;\n if i == 0 {\n poses = &mut fastest_poses;\n } else {\n poses = &mut slowest_poses;\n }\n let mut alpha_poses = vec![vec![]; 26];\n if i == 0 {\n for j in 0..s.len() {\n let ch_idx = s[j].to_digit(36).unwrap() as usize - 10;\n alpha_poses[ch_idx].push(j);\n }\n } else {\n for j in (0..s.len()).rev() {\n let ch_idx = s[j].to_digit(36).unwrap() as usize - 10;\n alpha_poses[ch_idx].push(s.len() - 1 - j);\n }\n }\n\n if i == 1 {\n t.reverse();\n }\n\n let mut prev = 0;\n for (j, &tch) in t.iter().enumerate() {\n let tch_idx = tch.to_digit(36).unwrap() as usize - 10;\n let mut next;\n if j == 0 {\n next = alpha_poses[tch_idx][alpha_poses[tch_idx].lower_bound(&prev)];\n } else {\n next = alpha_poses[tch_idx][alpha_poses[tch_idx].upper_bound(&prev)];\n }\n poses.push(next);\n prev = next;\n }\n }\n let mut slowest_poses = slowest_poses\n .iter()\n .map(|x| s.len() - 1 - x)\n .collect::>();\n slowest_poses.reverse();\n\n debug!(fastest_poses);\n debug!(slowest_poses);\n\n let mut ans = 0;\n for l in 0..s.len() {\n let found = fastest_poses.lower_bound(&l);\n if found == slowest_poses.len() {\n ans = max(ans, s.len() - l);\n continue;\n }\n ans = max(ans, slowest_poses[found] - l);\n }\n println!(\"{}\", ans);\n}\n\nfn read() -> T {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn read_vec() -> Vec {\n read::()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n\npub trait BinarySearch {\n fn lower_bound(&self, x: &T) -> usize;\n fn upper_bound(&self, x: &T) -> usize;\n}\n\nimpl BinarySearch for [T] {\n fn lower_bound(&self, x: &T) -> usize {\n let mut low = 0;\n let mut high = self.len();\n\n while low != high {\n let mid = (low + high) / 2;\n match self[mid].cmp(x) {\n Ordering::Less => {\n low = mid + 1;\n }\n Ordering::Equal | Ordering::Greater => {\n high = mid;\n }\n }\n }\n low\n }\n\n fn upper_bound(&self, x: &T) -> usize {\n let mut low = 0;\n let mut high = self.len();\n\n while low != high {\n let mid = (low + high) / 2;\n match self[mid].cmp(x) {\n Ordering::Less | Ordering::Equal => {\n low = mid + 1;\n }\n Ordering::Greater => {\n high = mid;\n }\n }\n }\n low\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "9518a3e3367974d3e2908752435e764c", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Write;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let stdout = std::io::stdout();\n let mut out = std::io::BufWriter::new(stdout.lock());\n let mut scan = Scanner::default();\n\n // Read input\n let s: Vec = scan.next::().bytes().collect();\n let t: Vec = scan.next::().bytes().collect();\n\n let mut max_prefix: Vec = vec![0; s.len() + 1];\n max_prefix[0] = 0;\n for i in 1..(s.len()+1) {\n max_prefix[i] = max_prefix[i-1];\n if max_prefix[i] < t.len() && t[max_prefix[i]] == s[i-1] {\n max_prefix[i] += 1;\n }\n }\n\n let mut max_suffix: Vec = vec![0; s.len() + 1];\n max_suffix[0] = 0;\n for i in 1..(s.len()+1) {\n max_suffix[i] = max_suffix[i-1];\n if max_suffix[i] < t.len() && t[t.len()-1-max_suffix[i]] == s[s.len()-i] {\n max_suffix[i] += 1;\n }\n }\n\n let can_substr = |len| {\n for prefix in 0..(s.len()+1-len) {\n let suffix = s.len() - prefix - len;\n if max_prefix[prefix] + max_suffix[suffix] >= t.len() {\n return true;\n }\n }\n return false;\n };\n\n let mut l: usize = 0;\n let mut r: usize = s.len() - t.len() + 1;\n while r - l > 1 {\n let m = (l + r) / 2;\n if can_substr(m) {\n l = m;\n } else {\n r = m;\n }\n }\n writeln!(out, \"{}\", l).unwrap();\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "9431599a428e140e652688170203562b", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, stdout, Write, BufReader, BufRead, Read};\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while b != 0 {\n a %= b;\n let c = a;\n a = b;\n b = c;\n }\n return a;\n}\n\n//let n = {\n// let mut line = String::new();\n// input.read_line(&mut line).unwrap();\n// let mut whitespace = line.split_ascii_whitespace();\n// whitespace.next().unwrap().parse::().unwrap()\n// };\n//\n// let mut line = String::new();\n// input.read_line(&mut line).unwrap();\n// let mut split = line.split_ascii_whitespace();\n// let mut a = split.next().unwrap().parse().unwrap();\n// for i in split {\n// let b = i.parse().unwrap();\n// a = gcd(b, a);\n// }\n//\n// let mut count = 0;\n// for i in 1..=a {\n// if a % i == 0 {\n// count += 1;\n// }\n// }\n\nfn solve(input: &mut BufRead, output: &mut Write) {\n let mut input = BufReader::new(input);\n\n let mut first = String::with_capacity(201);\n let mut second = String::with_capacity(201);\n\n input.read_line(&mut first).unwrap();\n input.read_line(&mut second).unwrap();\n\n let s = first.trim().as_bytes();\n let t = second.trim().as_bytes();\n\n let first = s.iter().position(|&it| it == t[0]).unwrap();\n let second = s.iter().rev().position(|&it| it == t[t.len() - 1]).unwrap();\n\n let mut answ = first.max(second);\n\n let mut pos = vec![first; t.len()];\n let mut pos_rev = vec![second; t.len()];\n\n\n let mut prev = first;\n for i in 0..t.len() {\n let pos1 = s.iter().skip(prev).position(|&it| it == t[i]).unwrap();\n prev += pos1;\n pos[i] = prev;\n prev += 1;\n }\n\n let mut rev = second;\n for i in (0..t.len()).rev() {\n let pos1 = s.iter().rev().skip(rev).position(|&it| it == t[i]).unwrap();\n rev += pos1;\n pos_rev[i] = rev;\n rev += 1;\n }\n\n for i in 0..t.len() - 1 {\n answ = answ.max((s.len() - pos_rev[i + 1] - 2) - pos[i])\n }\n\n answ = answ.max(s.len() - pos[pos.len() - 1] - 1);\n answ = answ.max(s.len() - pos_rev[0] - 1);\n\n writeln!(output, \"{}\", answ).unwrap();\n}\n\nfn main() {\n let stdin = stdin();\n let stdout = stdout();\n solve(&mut stdin.lock(), &mut stdout.lock());\n}\n\n#[cfg(test)]\nmod tests {\n use std::fs::File;\n use solve;\n use std::io::BufReader;\n\n #[test]\n fn basic_test() {\n let mut f = BufReader::new(\"bbaba\nbb\n\".as_bytes());\n let mut buf: Vec = Vec::new();\n\n solve(&mut f, &mut buf);\n\n let res = String::from_utf8(buf).unwrap();\n assert_eq!(res, \"3\\n\");\n }\n\n #[test]\n fn basic_test2() {\n let mut f = BufReader::new(\"baaba\nab\n\".as_bytes());\n let mut buf: Vec = Vec::new();\n\n solve(&mut f, &mut buf);\n\n let res = String::from_utf8(buf).unwrap();\n assert_eq!(res, \"2\\n\");\n }\n\n #[test]\n fn basic_test3() {\n let mut f = BufReader::new(\"abcde\nabcde\n\".as_bytes());\n let mut buf: Vec = Vec::new();\n\n solve(&mut f, &mut buf);\n\n let res = String::from_utf8(buf).unwrap();\n assert_eq!(res, \"0\\n\");\n }\n\n #[test]\n fn basic_test4() {\n let mut f = BufReader::new(\"asdfasdf\nfasd\n\".as_bytes());\n let mut buf: Vec = Vec::new();\n\n solve(&mut f, &mut buf);\n\n let res = String::from_utf8(buf).unwrap();\n assert_eq!(res, \"3\\n\");\n }\n\n\n\n\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "df1b535729caf8f895112a1623545a33", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*};\n\n\n#[allow(unused_must_use)]\n#[allow(unused_assignments)]\n#[allow(unused_variables)]\nfn solve(mut scan: Scanner, mut w: W) {\n let k = scan.token::();\n let l = scan.token::();\n let m = scan.token::();\n let n = scan.token::();\n let d = scan.token::();\n\n let mut arr = vec![false; d];\n\n for i in (0..d).skip(k-1).step_by(k) {\n arr[i] = true;\n }\n for i in (0..d).skip(l-1).step_by(l) {\n arr[i] = true;\n }\n for i in (0..d).skip(m-1).step_by(m) {\n arr[i] = true;\n }\n for i in (0..d).skip(n-1).step_by(n) {\n arr[i] = true;\n }\n\n let ans: usize = arr.iter().filter(|&e| *e).count();\n\n writeln!(w, \"{}\", ans);\n}\n \nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let reader = Scanner::new(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n solve(reader, writer);\n}\n#[allow(dead_code)]\nfn vector_to_str(vector: &Vec, separator: &str) -> String { \n use std::fmt::Write;\n let mut ans = String::new();\n for line in vector.iter() {\n write!(&mut ans, \"{}{}\", line.to_string(), separator).unwrap();\n }\n ans\n}\n#[allow(dead_code)]\nfn matrix_to_str(matrix: &Vec>, separator: &str) -> String { \n use std::fmt::Write;\n let mut ans = String::new();\n for line in matrix.iter() {\n for elem in line.iter() {\n write!(&mut ans, \"{}{}\", elem.to_string(), separator).unwrap();\n }\n write!(&mut ans, \"\\n\").unwrap();\n }\n ans\n}\npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace()\n }\n }\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace()) }\n }\n }\n pub fn get_matrix(&mut self, m: usize, n: usize) -> Vec> {\n // m rows and n columns\n let mut ans: Vec> = Vec::with_capacity(m);\n for i in 0..m {\n ans.push(Vec::with_capacity(n));\n for _ in 0..n {\n ans[i].push(self.token::());\n }\n }\n ans\n }\n pub fn get_vector(&mut self, n: usize) -> Vec {\n let mut ans: Vec = Vec::with_capacity(n);\n for _ in 0..n {\n ans.push(self.token::());\n }\n ans\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "50d80c21eef731975918a4a8d3493d86", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (k, l, m, n, d) = {\n let mut bufs: Vec = Vec::new();\n for _ in 0..5 {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n bufs.push(buf.trim_end().parse().unwrap());\n }\n (bufs[0], bufs[1], bufs[2], bufs[3], bufs[4])\n };\n\n let mut ans = 0;\n for i in 0..d {\n let num = i + 1;\n if num % k == 0 || num % l == 0 || num % m == 0 || num % n == 0 {\n ans += 1\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "b77a1a5c163150fd371fdb26fe866eb6", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused)] use std::io::*;\n#[allow(unused)] use std::collections::*;\n#[allow(unused)] use std::mem::*;\n#[allow(unused)] use std::num::*;\n#[allow(unused)] use std::cmp::*;\n#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).collect();\n let mut cnt : usize = 0;\n fn next(cnt: &mut usize, p: &Vec<&str>) -> T where T:std::str::FromStr\n { *cnt += 1; p[*cnt-1].parse().ok().unwrap() }\n ($(next::<$x>(&mut cnt, &s)), +)\n }}; }\n#[allow(unused)] macro_rules! arr { ($n:expr, $T:ty) => {{\n let mut inp = String::new(); stdin().read_line(&mut inp).ok();\n let mut s = inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0);\n let mut v = Vec::new(); v.reserve(($n) as usize);\n for st in s { v.push(st.parse::<$T>().unwrap()); } v\n }}; }\n\n///////////////////////////////////////////////////////////////////////////////\nfn main()\n{\n let k = scan!(i32);\n let l = scan!(i32);\n let m = scan!(i32);\n let n = scan!(i32);\n let v = scan!(i32);\n let mut cnt = 0;\n for i in 1..v+1 {\n if i % k == 0 || i % l == 0 || i % m == 0 || i % n == 0 { cnt += 1; }\n }\n println!(\"{}\", cnt);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "6bc73bed438ab368c7d16ae08aa7bee0", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::collections::{*};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n \nfn main() {\n let mut scanner = Scanner::default();\n let arr: [u64;5] = [scanner.next(), scanner.next(), scanner.next(), scanner.next(), scanner.next()];\n print![\"{}\", (1..=arr[4]).filter(|x| x % arr[0] == 0 || x % arr[1] == 0 || x % arr[2] == 0 || x % arr[3] == 0).count()];\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "7f0818ff5fb5054e42e0a2a7cf592f22", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn read(i: &mut StdinLock) -> T {\n let mut s = String::new();\n i.by_ref().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn main() {\n // initialize stdin\n let sin = std::io::stdin();\n let mut sin = sin.lock();\n let sin = &mut sin;\n\n let k: u32 = read(sin);\n let l: u32 = read(sin);\n let m: u32 = read(sin);\n let n: u32 = read(sin);\n let d: u32 = read(sin);\n\n let ans = (1..d + 1)\n .filter(|x| *x % k == 0 || *x % l == 0 || *x % m == 0 || *x % n == 0)\n .count();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "449467d2bfef4b99d42fe13e970ddc2f", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader : T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader { it : s\n .split_ascii_whitespace()\n .map(String::from).collect::>()\n .into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let mut a = [0; 4];\n for x in a.iter_mut() {\n *x = input.i();\n }\n let n = input.i();\n let sol = (1..n+1).filter(|x| a.iter().any(|y| x % y == 0)).count();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "3dcb176305dc99f3d9b4272710334e49", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\nuse std::str::FromStr;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn parse_t(s : &str) -> T {\n match s.trim().parse() {\n Ok(y) => y,\n Err(_) => panic!(\"Could not read from string!\"),\n }\n}\n\nfn read_t(stdin : &Stdin) -> T {\n let mut line = String::new();\n read_line(stdin, &mut line);\n parse_t(&line)\n}\n\nfn gcd(a : u64, b : u64) -> u64 {\n let mut t_a = if a > b { a } else { b };\n let mut t_b = if t_a == a { b } else { a };\n loop {\n if t_b == 0 {\n return t_a;\n } else {\n let t_a_mod_t_b = t_a % t_b;\n t_a = t_b;\n t_b = t_a_mod_t_b;\n }\n }\n}\n\nfn lcm(a : u64, b : u64) -> u64 {\n let g = gcd(a, b);\n (a / g) * b\n}\n\nmacro_rules! lcm_list {\n ($x:expr) => ($x);\n ($x:expr, $($y:expr),+) => (\n lcm($x, lcm_list!($($y),+))\n )\n}\n\nfn num_damaged_dragons(k : u64, l : u64, m : u64, n : u64, d : u64) -> u64 {\n let t_k = d / k;\n let t_l = d / l;\n let t_m = d / m;\n let t_n = d / n;\n let t_k_l = d / lcm_list!(k, l);\n let t_k_m = d / lcm_list!(k, m);\n let t_k_n = d / lcm_list!(k, n);\n let t_l_m = d / lcm_list!(l, m);\n let t_l_n = d / lcm_list!(l, n);\n let t_m_n = d / lcm_list!(m, n);\n let t_k_l_m = d / lcm_list!(k, l, m);\n let t_k_l_n = d / lcm_list!(k, l, n);\n let t_k_m_n = d / lcm_list!(k, m, n);\n let t_l_m_n = d / lcm_list!(l, m, n);\n let t_k_l_m_n = d / lcm_list!(k, l, m, n);\n let t_1 = t_k + t_l + t_m + t_n;\n let t_2 = t_k_l + t_k_m + t_k_n + t_l_m + t_l_n + t_m_n;\n let t_3 = t_k_l_m + t_k_l_n + t_k_m_n + t_l_m_n;\n let t_4 = t_k_l_m_n;\n t_1 - t_2 + t_3 - t_4\n}\n\nfn main() {\n let stdin = io::stdin();\n let k = read_t(&stdin);\n let l = read_t(&stdin); \n let m = read_t(&stdin); \n let n = read_t(&stdin); \n let d = read_t(&stdin); \n let r = num_damaged_dragons(k, l, m, n, d);\n println!(\"{}\", r);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "fb4249fd0f9e40bfc4ab654c20299920", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let mut iterator = stdin.lock().lines();\n let mut damaged = 0;\n\n let k: i64 = iterator\n .next().unwrap().unwrap().parse().unwrap_or(0);\n let l: i64 = iterator\n .next().unwrap().unwrap().parse().unwrap_or(0);\n let m: i64 = iterator\n .next().unwrap().unwrap().parse().unwrap_or(0);\n let n: i64 = iterator\n .next().unwrap().unwrap().parse().unwrap_or(0);\n let d: i64 = iterator\n .next().unwrap().unwrap().parse().unwrap_or(0);\n\n for i in 1..=d {\n if i % k == 0 ||\n i % l == 0 ||\n i % m == 0 ||\n i % n == 0 {\n damaged += 1;\n }\n }\n\n println!(\"{}\", damaged);\n}", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "ca8f516e302ddb419a10ce917ba7fcf4", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize, k: i64,\n s: chars,\n }\n let s: Vec<_> = s.into_iter().map(|c| c as usize - 97).collect();\n let mut dp = vec![vec![0i64; n + 1]; n + 1];\n let mut nxt = vec![[n; 26]; n + 1];\n for i in (0..n).rev() {\n nxt[i] = nxt[i + 1];\n nxt[i][s[i]] = i;\n }\n dp[n][0] = 1;\n for i in (0..n).rev() {\n dp[i][0] = dp[i][0].saturating_add(1);\n for j in 0..n {\n let mut tot: i64 = 0;\n for l in 0..26 {\n let to = nxt[i][l] + 1;\n if to <= n {\n tot = tot.saturating_add(dp[to][j]);\n }\n }\n dp[i][j + 1] = dp[i][j + 1].saturating_add(tot);\n }\n }\n let mut cost = 0;\n let mut rem = k;\n for i in (0..n + 1).rev() {\n let now = min(dp[0][i], rem);\n cost += now * (n - i) as i64;\n rem -= now;\n if rem <= 0 {\n break;\n }\n }\n puts!(\"{}\\n\", if rem > 0 { -1 } else { cost });\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "74ceffae0996dee77e3d30a4df8cc1b2", "src_uid": "ae5d21919ecac431ea7507cb1b6dc72b", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn vvb(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet n = rin.u();\n\tlet k = rin.l();\n\tlet s = rin.vb();\n\tlet add = |a: i64, b: i64| k.min(a+b);\n\tlet mut dp = v!([n+1][n+1] = 0);\n\tdp[0][0] = 1;\n\tfor i in 1..=n {\n\t\tfor l in 1..=i {\n\t\t\tfor j in 1..=i {\n\t\t\t\tdp[i][j] = add(dp[i][j], dp[i-l][j-1]);\n\t\t\t}\n\t\t\tif l < i && s[i-1] == s[i-1-l] {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tlet mut sum = v!([n+1] = 0);\n\tlet mut sum0 = 0;\n\tfor i in 0..=n {\n\t\tfor j in 0..=n {\n\t\t\tlet x = dp[i][j];\n\t\t\tsum[j] = add(sum[j], x);\n\t\t\tsum0 = add(sum0, x);\n\t\t}\n\t}\n\tif sum0 < k {\n\t\twriteln!(rout, \"-1\").ok();\n\t\treturn;\n\t}\n\tlet mut sol = 0;\n\tlet mut rem = k;\n\tfor i in (0..=n).rev() {\n\t\tlet m = sum[i].min(rem);\n\t\tsol += (n-i) as i64 * m;\n\t\trem -= m;\n\t}\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["dp", "implementation", "graphs", "shortest paths"], "code_uid": "d67d42d002aa024d3306c2a118fa6d03", "src_uid": "ae5d21919ecac431ea7507cb1b6dc72b", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n// use std::cmp::min;\nuse std::collections::{HashSet, VecDeque};\n\nfn main() -> io::Result<()> {\n let stdin = io::stdin();\n let mut input = String::new();\n stdin.read_line(&mut input)?;\n let mut iter = input.split_whitespace()\n .map(|x| x.trim().parse::().unwrap());\n\n let n = iter.next().unwrap();\n let k = iter.next().unwrap();\n\n let mut input = String::new();\n stdin.read_line(&mut input)?;\n let s = input.trim();\n\n let mut visited: HashSet> = HashSet::new();\n let mut queue: VecDeque> = VecDeque::new();\n queue.push_back(s.chars().collect());\n\n let mut count = 0;\n let mut sum = 0;\n while k > count && !queue.is_empty() {\n let s = queue.pop_front().unwrap();\n count += 1;\n sum += s.len();\n\n // println!(\"visited {:?}\", s);\n \n for i in 0..s.len() {\n let mut t = vec![];\n t.extend_from_slice(&s[..i]);\n t.extend_from_slice(&s[i+1..]);\n\n if !visited.contains(&t) {\n queue.push_back(t.clone());\n }\n\n visited.insert(t);\n }\n }\n\n // println!(\"count={} sum={}\", count, sum);\n \n if count < k {\n println!(\"-1\");\n } else {\n println!(\"{}\", n * k - sum);\n }\n \n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["dp", "implementation", "graphs", "shortest paths"], "code_uid": "98cf3ebb692dafba62440f80ecfbda01", "src_uid": "ae5d21919ecac431ea7507cb1b6dc72b", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: usize, k: i64,\n s: chars,\n }\n let s: Vec<_> = s.into_iter().map(|c| c as usize - 97).collect();\n let mut dp = vec![vec![0i64; n + 1]; n + 1];\n let mut nxt = vec![[n; 26]; n + 1];\n for i in (0..n).rev() {\n nxt[i] = nxt[i + 1];\n nxt[i][s[i]] = i;\n }\n dp[n][0] = 1;\n for i in (0..n).rev() {\n dp[i][0] = dp[i][0].saturating_add(1);\n for j in 0..n {\n let mut tot: i64 = 0;\n for l in 0..26 {\n let to = nxt[i][l] + 1;\n if to <= n {\n tot = tot.saturating_add(dp[to][j]);\n }\n }\n dp[i][j + 1] = dp[i][j + 1].saturating_add(tot);\n }\n }\n let mut cost = 0;\n let mut rem = k;\n for i in (0..n + 1).rev() {\n let now = min(dp[0][i], rem);\n cost += now * (n - i) as i64;\n rem -= now;\n if rem <= 0 {\n break;\n }\n }\n puts!(\"{}\\n\", if rem > 0 { -1 } else { cost });\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["dp", "implementation", "graphs", "shortest paths"], "code_uid": "eaea3636a59feae2cf7dbbac784ee426", "src_uid": "ae5d21919ecac431ea7507cb1b6dc72b", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)] use std::{*, io::*, cmp::*, char::* };\n#[allow(unused)] macro_rules! input { ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\n#[allow(unused)] macro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\n#[allow(unused)] macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, usize1) => { read_value!($next, usize) - 1}; ($next:expr, [ $t:tt ]) => {{ let len = read_value!($next, usize);(0..len).map(|_| read_value!($next, $t)).collect::>()}};($next:expr, $t:ty) => {$next().parse::<$t>().expect(\"Parse error\")};}\n#[allow(unused)] macro_rules! debug { ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap()); }\n#[allow(unused)] macro_rules! debugln { ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap()); }\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n #[allow(unused)] macro_rules! puts { ($($format:tt)*) => (let _ = write!(out,$($format)*);); }\n\n let s1: Vec = get_word().chars().collect();\n let s2: Vec = get_word().chars().collect();\n\n let mut sum1 = 0;\n let mut sum2 = 0;\n \n for c in s1 {\n\tsum1 += match c {\n\t '+' => 1,\n\t '-' => -1,\n\t _ => 0,\n\t}\n }\n\n for c in &s2 {\n\tsum2 += match *c {\n\t '+' => 1,\n\t '-' => -1,\n\t _ => 0,\n\t}\n }\n\n let mut q = 0;\n \n for c in &s2 {\n\tif *c == '?' {\n\t q += 1;\n\t}\n }\n\n\n let d: i64 = sum1 - sum2;\n let d = d.abs();\n\n let mut num = 1;\n\n if d > q || d % 2 != q % 2 {\n\t\n\tputs!(\"{}\", 0.0);\n\t\n } else {\n\t\n\tlet m = d + (q - d) / 2;\n\t\n\tfor i in 0..m {\n\t num *= q - i;\n\t}\n\t\n\tfor i in 1..=m {\n\t num /= i;\n\t}\n\t\n\tputs!(\"{}\", num as f64 / (1 << q) as f64);\n }\n}\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n\n#[allow(dead_code)]\nfn get_word() -> String {\n let stdin = std::io::stdin();\n let mut stdin=stdin.lock();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "bitmasks", "probabilities"], "code_uid": "1785e73748e35034ebd53d18f766c626", "src_uid": "f7f68a15cfd33f641132fac265bc5299", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nfn read_vec() -> Vec {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().split_whitespace()\n .map(|e| e.parse().ok().unwrap()).collect()\n}\n\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nuse std::hash::Hash;\nfn inc(map:&mut BTreeMap, key:T) {\n let count = map.entry(key).or_insert(0);\n *count += 1;\n}\n\nfn int(ch: char) -> i64 {\n return (ch as u8 - b'0') as i64\n}\n\nconst MAX:usize = 20;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\n\nfn main() {\n input!{s:chars, t:chars};\n let mut cord = 0;\n for i in 0..s.len() {\n if s[i] == '+' { cord += 1; }\n else { cord -= 1; }\n }\n\n let mut dp = vec![vec![0;MAX+1];s.len()+1];\n dp[0][MAX/2] = 1;\n\n for i in 0..s.len() {\n for j in 0..MAX {\n if dp[i][j] == 0 { continue; }\n if t[i] == '+' {\n dp[i+1][j+1] += dp[i][j];\n }\n else if t[i] == '-' {\n dp[i+1][j-1] += dp[i][j];\n }\n else {\n dp[i+1][j+1] += dp[i][j];\n dp[i+1][j-1] += dp[i][j];\n }\n }\n }\n\n //println!(\"{:#?}\", dp);\n\n let sum = dp[s.len()].iter().sum::();\n let correct = dp[s.len()][cord+MAX/2];\n //debug!(sum,correct);\n\n println!(\"{}\", (correct as f64) / (sum as f64));\n\n}\n\n/*\n\n\u5143\u306e\u30b3\u30de\u30f3\u30c9\u3068\u53d7\u4fe1\u3057\u305f\u30b3\u30de\u30f3\u30c9\u304c\u4e0e\u3048\u3089\u308c\u308b\u3002\n\u53d7\u4fe1\u3057\u305f\u30b3\u30de\u30f3\u30c9\u901a\u308a\u306b\u52d5\u3044\u305f\u3068\u304d\u306b\u3001\u5143\u306e\u30b3\u30de\u30f3\u30c9\u3068\u540c\u3058\u5ea7\u6a19\u306b\u306a\u308b\u78ba\u7387\u306f\u3044\u304f\u3089\u304b\u6c42\u3081\u308b\u3002\n\n\u5168\u3066\u306e\u79fb\u52d5\u65b9\u6cd5\u3092\u5168\u63a2\u7d22\u3059\u308b\u3002\n\u6b63\u3057\u304d\u79fb\u52d5\u306e\u6570 / \u30d1\u30b9\u306e\u7dcf\u6570 \u304c\u7b54\u3048\n\n\u30fbDFS\u3057\u3066\u5168\u63a2\u7d22\n\u30fb?\u306e\u6570\u3060\u3051bit\u5168\u63a2\u7d22\u3059\u308c\u3070\u3044\u3044\n\u30fb\uff12\u6b21\u5143\u914d\u5217\u3067DP\u3082\u3067\u304d\u308b\u304b\u3082\n\n*/\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "bitmasks", "probabilities"], "code_uid": "c9fb56b3eb38222b17e186d05b186c6e", "src_uid": "f7f68a15cfd33f641132fac265bc5299", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn go(s: &String, need: i32, pos: i32, i: usize) -> f64 {\n if i == s.as_bytes().len() {\n if need == pos {\n return 1f64;\n } else {\n return 0f64;\n }\n } else {\n if s.as_bytes()[i] == '+' as u8 {\n return go(s,need,pos+1,i+1);\n } else if s.as_bytes()[i] == '-' as u8 {\n return go(s,need,pos-1,i+1);\n } else if s.as_bytes()[i] == '?' as u8 {\n return (go(s,need,pos-1,i+1)+go(s,need,pos+1,i+1))*0.5;\n } else {\n panic!(\"\");\n }\n }\n}\n\nfn main() {\n let aa = readln!();\n let bb = readln!();\n let mut need = 0;\n for i in aa.chars() {\n if i == '+' {\n need += 1;\n } else if i == '-' {\n need -= 1;\n } else {\n panic!(\"\");\n }\n }\n let p = go(&bb, need, 0, 0);\n println!(\"{}\",p);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "bitmasks", "probabilities"], "code_uid": "5c695fc25657fa1d80b0129b04a01ced", "src_uid": "f7f68a15cfd33f641132fac265bc5299", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let f = |s: &[u8]| {\n let mut x = 0;\n let mut c = 0;\n for &a in s {\n if a == b'+' { x += 1; }\n if a == b'-' { x -= 1; }\n if a == b'?' { c += 1; }\n }\n (x, c)\n };\n\n let a = f(input.bs()).0;\n let (b,c) = f(input.bs());\n let mut res = 0;\n for mut z in 0..1< 0 {\n z -= z & -z;\n x -= 2;\n }\n if x == b {\n res += 1;\n }\n }\n println!(\"{}\", (res as f64) / ((1 << c) as f64));\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "bitmasks", "probabilities"], "code_uid": "5796f8e42d13d21438d5c062c57fdfa2", "src_uid": "f7f68a15cfd33f641132fac265bc5299", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const N:usize = 505; \r\n\r\n\r\nfn main() {\r\n\r\n let mut str = String::new();\r\n\tstd::io::stdin().read_line(&mut str).expect(\"\");\r\n let input :Vec<&str> = str.trim().split(\" \").collect();\r\n let n = input[0].parse::().unwrap();\r\n let modn = input[1].parse::().unwrap();\r\n let mut dp0:Vec = vec![0;N*N];\r\n let mut dp1:Vec = vec![0;N*N];\r\n //let mut temp_dp0:Vec = vec![0;N*N];\r\n //let mut temp_dp1:Vec = vec![0;N*N];\r\n let shift = N*N/2;\r\n dp1[shift]=1;\r\n for _i in 1..n{\r\n let mut new_dp0 :Vec = vec![0;N*N];\r\n let mut new_dp1 :Vec = vec![0;N*N];\r\n\r\n //let mut new_dp0 = temp_dp0;\r\n //let mut new_dp1 = temp_dp1;\r\n //for j in 0..(N*N){\r\n // new_dp0[j]=0;\r\n // new_dp1[j]=0;\r\n ///}\r\n let i = _i as usize;\r\n for _j in 0..(N*N-1){\r\n let j = _j as usize;\r\n if dp1[j]==0 && dp0[j]==0{\r\n continue;\r\n }\r\n new_dp1[j-i] = (new_dp1[j-i]+dp1[j])%modn;\r\n new_dp1[j+1] = (new_dp1[j+1]-2*dp1[j] + modn + modn)%modn;\r\n new_dp1[j+i+2]=(new_dp1[j+i+2]+dp1[j])%modn;\r\n\r\n new_dp0[j+1] = (new_dp0[j+1]+dp1[j]*(i as i64))%modn;\r\n new_dp0[j] = (new_dp0[j]+(modn-dp1[j])*(i as i64+1))%modn;\r\n new_dp0[j-i] = (new_dp0[j-i]+dp1[j])%modn;\r\n\r\n let t:i64 = (i as i64 +1)*dp0[j]%modn;\r\n new_dp0[j] = (new_dp0[j]+t)%modn;\r\n new_dp0[j+1] = (new_dp0[j+1]+(modn-t)*2)%modn;\r\n new_dp0[j+2] = (new_dp0[j+2]+t)%modn;\r\n }\r\n //for j in shift-10..shift+11{\r\n // println!(\"{} {}\",j as i32-shift as i32,new_dp[j][0])\r\n //}\r\n for j in 0..(N*N-1){\r\n new_dp0[j+1]=(new_dp0[j+1]+new_dp0[j])%modn;\r\n new_dp1[j+1]=(new_dp1[j+1]+new_dp1[j])%modn;\r\n }\r\n for j in 0..(N*N-1){\r\n new_dp0[j+1]=(new_dp0[j+1]+new_dp0[j])%modn;\r\n new_dp1[j+1]=(new_dp1[j+1]+new_dp1[j])%modn;\r\n }\r\n //temp_dp0 = dp0;\r\n //temp_dp1 = dp1;\r\n dp0 = new_dp0;\r\n dp1 = new_dp1;\r\n }\r\n let mut ans:i64 = 0;\r\n for j in shift+1..N*N{\r\n ans = (ans + dp0[j])%modn;\r\n }\r\n println!(\"{}\",ans);\r\n\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "fft"], "code_uid": "5f7812e179e69dd1ea1e86a519411278", "src_uid": "ae0320a57d73fab1d05f5d10fbdb9e1a", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin next_permutation ----------\r\nfn next_permutation(a: &mut [T]) -> bool {\r\n a.windows(2).rposition(|a| a[0] < a[1]).map_or(false, |x| {\r\n let y = a.iter().rposition(|b| a[x] < *b).unwrap();\r\n a.swap(x, y);\r\n a[(x + 1)..].reverse();\r\n true\r\n })\r\n}\r\n// ---------- end next_permutation ----------\r\n// ---------- begin ModInt ----------\r\nmod modint {\r\n\r\n #[allow(dead_code)]\r\n pub struct Mod;\r\n impl ConstantModulo for Mod {\r\n const MOD: u32 = 1_000_000_007;\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub struct StaticMod;\r\n static mut STATIC_MOD: u32 = 0;\r\n impl Modulo for StaticMod {\r\n fn modulo() -> u32 {\r\n unsafe { STATIC_MOD }\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl StaticMod {\r\n pub fn set_modulo(p: u32) {\r\n unsafe {\r\n STATIC_MOD = p;\r\n }\r\n }\r\n }\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n }\r\n\r\n pub trait ConstantModulo {\r\n const MOD: u32;\r\n }\r\n\r\n impl Modulo for T\r\n where\r\n T: ConstantModulo,\r\n {\r\n fn modulo() -> u32 {\r\n T::MOD\r\n }\r\n }\r\n\r\n pub struct ModInt(pub u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::new_unchecked(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n ModInt::new_unchecked(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = T::modulo() + self.0 - rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n ModInt::new_unchecked(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n let v = self.0 as u64 * rhs.0 as u64 % T::modulo() as u64;\r\n ModInt::new_unchecked(v as u32)\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::new_unchecked(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n ModInt::new_unchecked(0)\r\n }\r\n pub fn one() -> Self {\r\n ModInt::new_unchecked(1)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new(d: u32) -> Self {\r\n ModInt::new_unchecked(d % T::modulo())\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n\r\nuse modint::*;\r\ntype M = ModInt;\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nuse std::collections::*;\r\nuse std::io::Write;\r\n\r\ntype Map = HashMap;\r\ntype Set = BTreeSet;\r\ntype Deque = VecDeque;\r\n\r\nfn run() {\r\n input!(n: usize, modulo: u32);\r\n StaticMod::set_modulo(modulo);\r\n /*\r\n for n in 1..=6 {\r\n let mut ans = 0;\r\n let mut a = (0..n).collect::>();\r\n while {\r\n let mut b = a.clone();\r\n next_permutation(&mut b);\r\n while {\r\n let inv = |a: &[usize]| -> usize {\r\n let mut cnt = 0;\r\n for i in 0..a.len() {\r\n for j in (i + 1)..a.len() {\r\n if a[i] > a[j] {\r\n cnt += 1;\r\n }\r\n }\r\n }\r\n cnt\r\n };\r\n if inv(&a) > inv(&b) {\r\n ans += 1;\r\n }\r\n next_permutation(&mut b)\r\n }{}\r\n next_permutation(&mut a)\r\n }{}\r\n println!(\"{}: {}\", n, ans);\r\n }\r\n */\r\n let mut binom = vec![vec![M::zero(); n + 1]; n + 1];\r\n binom[0][0] = M::one();\r\n for i in 1..=n {\r\n binom[i][0] = M::one();\r\n for j in 1..=i {\r\n binom[i][j] = binom[i - 1][j - 1] + binom[i - 1][j];\r\n }\r\n }\r\n let mut fact = vec![M::one(); n + 1];\r\n for i in 1..=n {\r\n fact[i] = M::from(i) * fact[i - 1];;\r\n }\r\n let mut dp = Map::new();\r\n for rem in (1..=n).rev() {\r\n let mut next = Map::new();\r\n for i in 0..rem {\r\n for j in (i + 1)..rem {\r\n *next.entry(i as i32 - j as i32).or_insert(M::zero()) += fact[n - rem] * binom[n][rem];\r\n }\r\n }\r\n let mut trans = Map::new();\r\n for i in 0..rem {\r\n for j in 0..rem {\r\n *trans.entry(i as i32 - j as i32).or_insert(M::zero()) += M::one();\r\n }\r\n }\r\n for (diff, way) in dp {\r\n for (d, w) in trans.iter() {\r\n *next.entry(diff + *d).or_insert(M::zero()) += *w * way;\r\n }\r\n }\r\n dp = next;\r\n }\r\n let mut ans = M::zero();\r\n for (diff, way) in dp {\r\n if diff > 0 {\r\n ans += way;\r\n }\r\n }\r\n let ans = ans.0 % modulo;\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "fft"], "code_uid": "8ee5152cdf9fe88e7b4256809f2a7b3f", "src_uid": "ae0320a57d73fab1d05f5d10fbdb9e1a", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const N:usize = 505; \r\n\r\n\r\nfn main() {\r\n\r\n let mut str = String::new();\r\n\tstd::io::stdin().read_line(&mut str).expect(\"\");\r\n let input :Vec<&str> = str.trim().split(\" \").collect();\r\n let n = input[0].parse::().unwrap();\r\n let modn = input[1].parse::().unwrap();\r\n let mut dp0:Vec = vec![0;N*N];\r\n let mut dp1:Vec = vec![0;N*N];\r\n let mut temp_dp0:Vec = vec![0;N*N];\r\n let mut temp_dp1:Vec = vec![0;N*N];\r\n let shift = N*N/2;\r\n dp1[shift]=1;\r\n for _i in 1..n{\r\n //let mut new_dp0 :Vec = vec![0;N*N];\r\n //let mut new_dp1 :Vec = vec![0;N*N];\r\n\r\n let mut new_dp0 = temp_dp0;\r\n let mut new_dp1 = temp_dp1;\r\n for j in 0..(N*N){\r\n new_dp0[j]=0;\r\n new_dp1[j]=0;\r\n }\r\n let i = _i as usize;\r\n for _j in 0..(N*N-1){\r\n let j = _j as usize;\r\n if dp1[j]==0 && dp0[j]==0{\r\n continue;\r\n }\r\n new_dp1[j-i] = (new_dp1[j-i]+dp1[j])%modn;\r\n new_dp1[j+1] = (new_dp1[j+1]-2*dp1[j] + modn + modn)%modn;\r\n new_dp1[j+i+2]=(new_dp1[j+i+2]+dp1[j])%modn;\r\n\r\n new_dp0[j+1] = (new_dp0[j+1]+dp1[j]*(i as i64))%modn;\r\n new_dp0[j] = (new_dp0[j]+(modn-dp1[j])*(i as i64+1))%modn;\r\n new_dp0[j-i] = (new_dp0[j-i]+dp1[j])%modn;\r\n\r\n let t:i64 = (i as i64 +1)*dp0[j]%modn;\r\n new_dp0[j] = (new_dp0[j]+t)%modn;\r\n new_dp0[j+1] = (new_dp0[j+1]+(modn-t)*2)%modn;\r\n new_dp0[j+2] = (new_dp0[j+2]+t)%modn;\r\n }\r\n //for j in shift-10..shift+11{\r\n // println!(\"{} {}\",j as i32-shift as i32,new_dp[j][0])\r\n //}\r\n for j in 0..(N*N-1){\r\n new_dp0[j+1]=(new_dp0[j+1]+new_dp0[j])%modn;\r\n new_dp1[j+1]=(new_dp1[j+1]+new_dp1[j])%modn;\r\n }\r\n for j in 0..(N*N-1){\r\n new_dp0[j+1]=(new_dp0[j+1]+new_dp0[j])%modn;\r\n new_dp1[j+1]=(new_dp1[j+1]+new_dp1[j])%modn;\r\n }\r\n temp_dp0 = dp0;\r\n temp_dp1 = dp1;\r\n dp0 = new_dp0;\r\n dp1 = new_dp1;\r\n }\r\n let mut ans:i64 = 0;\r\n for j in shift+1..N*N{\r\n ans = (ans + dp0[j])%modn;\r\n }\r\n println!(\"{}\",ans);\r\n\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "fft"], "code_uid": "08c9ba4d89dafb6f28e4dbf466225229", "src_uid": "ae0320a57d73fab1d05f5d10fbdb9e1a", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let x: usize = scan.next();\n let y: usize = scan.next();\n let needed = y * n / 100 + if y * n % 100 == 0 { 0 } else { 1 };\n println!(\"{}\", if needed <= x { 0 } else { needed - x });\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "529884a7b17c62fc27ab96bf842bc848", "src_uid": "7038d7b31e1900588da8b61b325e4299", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\nuse std::usize;\nuse std::collections::BinaryHeap;\nuse std::cmp::Ordering;\nuse std::collections::BTreeMap;\nuse std::collections::VecDeque;\nuse std::cmp;\n\nfn main() {\n let (mut h, mut m, s, mut t1, mut t2) = {\n let v = read_values::();\n (v[0], v[1], v[2], v[3], v[4])\n };\n if h == 12.0 { h = 0.0; }\n h *= 5.0;\n t1 *= 5.0;\n t2 *= 5.0;\n\n h += m * 5.0 / 60.0 + s * 5.0 / 3600.0;\n m += s / 60.0;\n\n let (from, to) = {\n if t1 > t2 {\n (t2, t1)\n } else {\n (t1, t2)\n }\n };\n let mut count = 0;\n if from < h && h < to { count += 1; }\n if from < m && m < to { count += 1; }\n if from < s && s < to { count += 1; }\n\n if count == 0 || count == 3 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\nfn read_line() -> String {\n let stdin = io::stdin();\n let mut buf = String::new();\n stdin.read_line(&mut buf).unwrap();\n buf\n}\n\nfn read_values() -> Vec\n where T: std::str::FromStr,\n T::Err: std::fmt::Debug\n{\n read_line()\n .split(' ')\n .map(|a| a.trim().parse().unwrap())\n .collect()\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3352509b54c0721b5ddd86edc27dc256", "src_uid": "912c8f557a976bdedda728ba9f916c95", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let (h, m, s, t1, t2) = parse_line!(i32, i32, i32, i32, i32);\n let h = h * 5 * 2 + if m > 0 || s > 0 {1} else {0};\n let m = m * 2 + if s > 0 {1} else {0};\n let s = s * 2;\n let t1 = t1 * 5 * 2;\n let t2 = t2 * 5 * 2;\n let min = std::cmp::min(t1, t2);\n let max = std::cmp::max(t1, t2);\n let correct = (h > max || h < min) && (m > max || m < min) && (s > max || s < min);\n let incorrect = h > min && h < max && m > min && m < max && s > min && s < max;\n if correct || incorrect {\n println!(\"YES\");\n }else{\n println!(\"NO\");\n }\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f8617685edcf6091d97667343bb2c6ec", "src_uid": "912c8f557a976bdedda728ba9f916c95", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet};\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\nfn main() {\n let input: Vec = util::gets();\n let h = input[0] % 12;\n let m = input[1];\n let s = input[2];\n let t1 = min(input[3] % 12, input[4] % 12);\n let t2 = max(input[3] % 12, input[4] % 12);\n\n let mut is_inside = Vec::new();\n\n is_inside.push(t1 * 5 < s && s < t2 * 5);\n let m_s = m * 60 + s;\n is_inside.push(t1 * 5 * 60 < m_s && m_s < t2 * 5 * 60);\n is_inside.push(t1 <= h && h < t2);\n\n\n if is_inside.iter().all(|&b| b) || is_inside.iter().all(|&b| !b) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0974e671897335719ac0632f7c9e03b6", "src_uid": "912c8f557a976bdedda728ba9f916c95", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn parse_bin_val(s: &str) -> Vec {\n s.bytes().map(|byte| match byte {\n b'0' => false,\n b'1' => true,\n _ => panic!(\"NOT A BIT!\"),\n }).collect()\n}\n\nfn main() {\n let (h, m, s, t1, t2) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let modulo = |a, b| {\n if a % b < 0 {\n a % b + b\n } else {\n a % b\n }\n };\n\n let convert = |x| {\n modulo(x, 12) * 5\n };\n\n // println!(\"{} {} {}\", convert(h), convert(t1), convert(t2));\n\n let mut arr = vec![convert(h) + 1, m, s, convert(t1), convert(t2)];\n\n arr.sort();\n\n let i1 = arr.iter().position(|&x| x == convert(t1)).unwrap() as i64;\n let i2 = arr.iter().position(|&x| x == convert(t2)).unwrap() as i64;\n\n // println!(\"{} {}\", i1, i2);\n\n let ans = modulo(i2 - i1, 5) == 1 || modulo(i1 - i2, 5) == 1;\n\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "808040973b9a5f715be542c92f83be5b", "src_uid": "912c8f557a976bdedda728ba9f916c95", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\n//------------------- Start Field\nconst P5: i32 = 100_000_000;\nconst P6: i64 = P5 as i64;\n#[derive(Debug,Clone,Copy)]\nstruct Field(i32);\n#[allow(dead_code)]\nimpl Field {\n fn new>(a: T) -> Self { Self(Self::cv(a)) }\n fn new_unchecked(a: i32) -> Self { Self(a) }\n fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n fn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n}\nimpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\nimpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\nimpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\nimpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\nimpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\nimpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\nimpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\nuse std::fmt::{Display, Formatter, Result};\nimpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n// impl Default for Field { fn default() -> Self { Field(0) }}\nimpl Default for &Field { fn default() -> Self { &Field(0) }}\nimpl PartialEq for Field { fn eq(&self, a: &Self) -> bool { self.0 == a.0 } }\nimpl PartialOrd for Field { fn partial_cmp(&self, a: &Self) -> Option { Some(self.0.cmp(&a.0)) } }\nimpl Eq for Field {}\nimpl Ord for Field { fn cmp(&self, a: &Self) -> Ordering { self.0.cmp(&a.0) } }\nimpl Sum for Field {\n fn sum(i: I) -> Self where I: Iterator {\n i.fold(Field(0), |a,b| a + b) } }\nimpl<'a> Sum<&'a Self> for Field {\n fn sum(i: I) -> Self where I: Iterator {\n i.fold(Field(0), |a,&b| a + b) } }\nimpl Product for Field {\n fn product(i: I) -> Self where I: Iterator {\n i.fold(Field(1), |a,b| a * b) } }\nimpl<'a> Product<&'a Self> for Field {\n fn product(i: I) -> Self where I: Iterator {\n i.fold(Field(1), |a,&b| a * b) }\n}\n//------------------- End Field\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n const MAX_N: usize = 104;\n const MAX_K: usize = 12;\n\n let id = |n1, n2, w, k| {\n ((n1 * MAX_N + n2) * 2 + w) * MAX_K + k\n };\n let mut dp = vec![Field::new_unchecked(0); MAX_N * MAX_N * 2 * MAX_K];\n\n l!(n1,n2,k1,k2 = input.u());\n let k = [k1, k2];\n dp[id(0,0,0,0)] = Field::new_unchecked(1);\n\n for i in 0..=n1 {\n for j in 0..=n2 {\n for w in 0..=1 {\n let wk = k[w];\n for l in 0..=wk {\n let val = dp[id(i, j, w, l)];\n if val.0 == 0 {\n continue;\n }\n for a in 0..=1 {\n let ii = i + 1 - a;\n let jj = j + a;\n let ll = if a == w {l + 1} else {1};\n dp[id(ii, jj, a, ll)] += val;\n }\n }\n }\n }\n }\n\n let mut sol = Field::new_unchecked(0);\n for w in 0..=1 {\n for l in 0..=k[w] {\n sol += dp[id(n1, n2, w, l)];\n }\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "37d171c1969d2d26985e68edb2dd5752", "src_uid": "63aabef26fe008e4c6fc9336eb038289", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::cmp;\n\n\nfn main() {\n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_to_string(&mut buffer).unwrap();\n\n let arr : Vec<_> = buffer.split_whitespace().map(|x| x.parse::().unwrap() ).collect();\n let t = arr[0] as usize;\n let mut index = 1;\n for _ in 0..t {\n let (a,b) = (arr[index],arr[index+1]);\n if b == a-1 {\n let h = 2*b+1; // = a+b\n let mut j = 3; //just check all odd numbers since 2b + 1 is odd\n let mut divisible = false;\n while j <= (h as f64).sqrt() as u64 + 1{\n if h % j == 0 {\n divisible = true;\n }\n j += 2;\n }\n //println!(\"{},{}: {}\",a,b,divisible);\n if !divisible {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n } else {\n println!(\"NO\");\n }\n index += 2;\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "e9c579d382f0b3476f1ba6ba7ed55286", "src_uid": "5a052e4e6c64333d94c83df890b1183c", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn is_prime(num : i128) -> bool {\n if num == 1 || num != 2 && num % 2 == 0 {\n return false;\n }\n let limit = (num as f64).sqrt() as i128 + 1;\n let mut div = 3;\n while div <= limit {\n if num % div == 0 {\n return false;\n }\n div += 1;\n }\n return true;\n}\n\nfn main() {\n assert!(!is_prime(15));\n\n let tests = readln!(u8);\n for _ in 0..tests {\n let (size1, size2) = readln!(i128, i128);\n\n if size1 - size2 == 1 {\n println!(\"{}\", if is_prime(size1 + size2) { \"YES\" } else { \"NO\" });\n } else {\n println!(\"NO\");\n }\n }\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "0a458f1fdea22f33d6baddb61837eaf0", "src_uid": "5a052e4e6c64333d94c83df890b1183c", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin};\n\nmacro_rules! read {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nfn main() {\n\tlet (k, n, s, p) = read!(i32 , i32 , i32 , i32);\n\tlet x;\n \tif n % s != 0 {\n \tx = n / s + 1;\n \t} else {\n \tx = n / s;\n \t}\n \tlet y = x * k;\n \tlet mut _x;\n \tif y % p != 0 {\n \t_x = y / p + 1;\n \t} else {\n \t_x = y / p;\n \t}\n \tprintln!(\"{}\" , _x);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "dccb6bfbb3d59cd0cc9ec57ecea8057f", "src_uid": "73f0c7cfc06a9b04e4766d6aa61fc780", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n use std::io::prelude::*;\n use std::io;\n\n let mut input = String::new();\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let k: i32 = it.next().unwrap().parse().unwrap();\n let n: i32 = it.next().unwrap().parse().unwrap();\n let s: i32 = it.next().unwrap().parse().unwrap();\n let p: i32 = it.next().unwrap().parse().unwrap();\n\n // For one person:\n // s * (ans - 1) < n <= s * ans\n // 0 < n - s * (ans - 1) <= s\n // 0 <= n - s * (ans - 1) - 1 < s\n // 0 <= n - 1 - s * (ans - 1) < s\n // ans - 1 = (n - 1) / s\n // ans = (n - 1) / s + 1\n let sn = (n - 1) / s + 1;\n // p * (ans - 1) < k * sn <= p * ans\n // 0 < k * sn - p * (ans - 1) <= p\n // 0 <= k * sn - 1 - p * (ans - 1) < p\n // ans - 1 = (k * sn - 1) / p\n let ans = (k * sn - 1) / p + 1;\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "ea2bb8482799ef84dc0d21921760735c", "src_uid": "73f0c7cfc06a9b04e4766d6aa61fc780", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\nuse std::str::FromStr;\n\nfn main() {\n let stdin = stdin();\n let mut sc = Scanner::new(stdin.lock());\n let k = sc.next::();\n let n = sc.next::();\n let s = sc.next::();\n let p = sc.next::();\n\n let mut b = 1 << 28;\n let mut ret = b - 1;\n while b > 0 {\n if ret >= b && n <= s * (((ret - b) * p) / k) {\n ret -= b;\n }\n b /= 2;\n }\n println!(\"{}\", ret);\n}\n\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "583735c1567aca7404d27ce2a2074ac1", "src_uid": "73f0c7cfc06a9b04e4766d6aa61fc780", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n if let Err(_) = io::stdin().read_line(&mut input) {\n std::process::exit(1);\n }\n\n let mut parts = input.trim().split_whitespace();\n let number_of_people: u32 = if let Ok(val) = parts.next().unwrap().parse() { val } else { std::process::exit(2); };\n let number_of_planes_per_person: u32 = if let Ok(val) = parts.next().unwrap().parse() { val } else { std::process::exit(2); };\n let number_of_planes_per_sheet: u32 = if let Ok(val) = parts.next().unwrap().parse() { val } else { std::process::exit(2); };\n let number_of_sheets_per_pack: u32 = if let Ok(val) = parts.next().unwrap().parse() { val } else { std::process::exit(2); };\n\n let number_of_sheets_per_person = f64::ceil(number_of_planes_per_person as f64 / number_of_planes_per_sheet as f64) as u32;\n let total_number_of_sheets = number_of_sheets_per_person * number_of_people;\n let number_of_needed_packs = f64::ceil(total_number_of_sheets as f64 / number_of_sheets_per_pack as f64) as u32;\n println!(\"{}\", number_of_needed_packs);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "b9e56ff53aed70257d92cca6df60e115", "src_uid": "73f0c7cfc06a9b04e4766d6aa61fc780", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin ModInt ----------\r\n// \u30e2\u30f3\u30b4\u30e1\u30ea\u4e57\u7b97\u3092\u7528\u3044\u308b\r\n// \u307b\u307cCodeforces\u7528\r\n// \u6ce8\u610f\r\n// new_unchecked \u306f\u5024x\u304c 0 <= x < modulo \u3067\u3042\u308b\u3053\u3068\u3092\u4eee\u5b9a\r\n// ModInt \u306e\u4e2d\u8eab\u306f\u6b63\u898f\u5316\u3055\u308c\u305f\u5024\u3067\u6301\u3063\u3066\u308b\u306e\u3067\u76f4\u63a5\u8aad\u3093\u3060\u308a\u66f8\u3044\u305f\u308a\u3059\u308b\u3068\u3076\u3063\u58ca\u308c\u308b\r\n// \u5947\u7d20\u6570\u306e\u307f\r\nmod modint {\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n fn rem() -> u32;\r\n fn ini() -> u64;\r\n fn reduce(x: u64) -> u32 {\r\n assert!(x < (Self::modulo() as u64) << 32);\r\n let b = (x as u32 * Self::rem()) as u64;\r\n let t = x + b * Self::modulo() as u64;\r\n let mut c = (t >> 32) as u32;\r\n if c >= Self::modulo() {\r\n c -= Self::modulo();\r\n }\r\n c as u32\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod1_000_000_007 {}\r\n\r\n impl Modulo for Mod1_000_000_007 {\r\n fn modulo() -> u32 {\r\n 1_000_000_007\r\n }\r\n fn rem() -> u32 {\r\n 2226617417\r\n }\r\n fn ini() -> u64 {\r\n 582344008\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod998_244_353 {}\r\n\r\n impl Modulo for Mod998_244_353 {\r\n fn modulo() -> u32 {\r\n 998_244_353\r\n }\r\n fn rem() -> u32 {\r\n 998244351\r\n }\r\n fn ini() -> u64 {\r\n 932051910\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub fn generate_umekomi_modulo(p: u32) {\r\n assert!(p < (1 << 31) && p > 2 && p & 1 == 1 && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0));\r\n let mut t = 1u32;\r\n let mut s = !p + 1;\r\n let mut n = !0u32 >> 2;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n let mut ini = (1u64 << 32) % p as u64;\r\n ini = (ini << 32) % p as u64;\r\n assert!(t * p == !0);\r\n println!(\"pub enum Mod{} {{}}\", p);\r\n println!(\"impl Modulo for Mod{} {{\", p);\r\n println!(\" fn modulo() -> u32 {{\");\r\n println!(\" {}\", p);\r\n println!(\" }}\");\r\n println!(\" fn rem() -> u32 {{\");\r\n println!(\" {}\", t);\r\n println!(\" }}\");\r\n println!(\" fn ini() -> u64 {{\");\r\n println!(\" {}\", ini);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n let mut f = vec![];\r\n let mut n = p - 1;\r\n for i in 2.. {\r\n if i * i > n {\r\n break;\r\n }\r\n if n % i == 0 {\r\n f.push(i);\r\n while n % i == 0 {\r\n n /= i;\r\n }\r\n }\r\n }\r\n if n > 1 {\r\n f.push(n);\r\n }\r\n let mut order = 1;\r\n let mut n = p - 1;\r\n while n % 2 == 0 {\r\n n /= 2;\r\n order <<= 1;\r\n }\r\n let z = (2u64..).find(|z| {\r\n f.iter().all(|f| mod_pow(*z, ((p - 1) / *f) as u64, p as u64) != 1)\r\n }).unwrap();\r\n let zeta = mod_pow(z, ((p - 1) / order) as u64, p as u64);\r\n println!(\"impl transform::NTTFriendly for Mod{} {{\", p);\r\n println!(\" fn order() -> usize {{\");\r\n println!(\" {}\", order);\r\n println!(\" }}\");\r\n println!(\" fn zeta() -> u32 {{\");\r\n println!(\" {}\", zeta);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n }\r\n\r\n pub struct ModInt(u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::build(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 - rhs.0;\r\n if d >= T::modulo() {\r\n d += T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::build(T::reduce(self.0 as u64 * rhs.0 as u64))\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::build(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n fn build(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n Self::build(0)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n Self::build(T::reduce(d as u64 * T::ini()))\r\n }\r\n pub fn new(d: u32) -> Self {\r\n Self::new_unchecked(d % T::modulo())\r\n }\r\n pub fn one() -> Self {\r\n Self::new_unchecked(1)\r\n }\r\n pub fn get(&self) -> u32 {\r\n T::reduce(self.0 as u64)\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n pub fn inv(&self) -> Self {\r\n assert!(!self.is_zero());\r\n self.pow((T::modulo() - 2) as u64)\r\n }\r\n }\r\n\r\n pub fn mod_pow(mut r: u64, mut n: u64, m: u64) -> u64 {\r\n let mut t = 1 % m;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t = t * r % m;\r\n }\r\n r = r * r % m;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n\r\nuse modint::*;\r\n\r\ntype M = ModInt;\r\n\r\n// ---------- begin binary_gcd ----------\r\npub fn binary_gcd(a: u64, b: u64) -> u64 {\r\n if a == 0 || b == 0 {\r\n return a + b;\r\n }\r\n let x = a.trailing_zeros();\r\n let y = b.trailing_zeros();\r\n let mut a = a >> x;\r\n let mut b = b >> y;\r\n while a != b {\r\n let x = (a ^ b).trailing_zeros();\r\n if a < b {\r\n std::mem::swap(&mut a, &mut b);\r\n }\r\n a = (a - b) >> x;\r\n }\r\n a << x.min(y)\r\n}\r\n// ---------- end binary_gcd ----------\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nfn run() {\r\n input! {\r\n n: usize,\r\n a: usize,\r\n x: usize,\r\n y: usize,\r\n k: usize,\r\n m: usize,\r\n }\r\n let mut lcm = 1;\r\n for i in 1..k {\r\n lcm = lcm * i / binary_gcd(i as u64, lcm as u64) as usize;\r\n }\r\n let mut dp = vec![M::zero(); lcm];\r\n let p = M::from(n).inv();\r\n for i in 0..lcm {\r\n dp[i] = M::from(i) * p;\r\n }\r\n for i in (1..k).rev() {\r\n for j in (0..lcm).rev() {\r\n dp[j] = p * (M::from(j) + dp[j - j % i]) + (M::one() - p) * dp[j];\r\n }\r\n }\r\n let mut a = a;\r\n let mut ans = M::zero();\r\n for _ in 0..n {\r\n let c = a % lcm;\r\n let d = a / lcm * lcm;\r\n ans += M::from(d) * p * M::from(k) + dp[c];\r\n a = (a * x + y) % m;\r\n }\r\n println!(\"{}\", ans * M::from(n).pow(k as u64));\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "ab71dcb737377c15516e4112760ddaa8", "src_uid": "1d45491e28d24e2b318605cd328d6ecf", "difficulty": 2800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE.rotate_right(1) >> self.leading_zeros() } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nstruct Affine(ModInt, ModInt);\n\nimpl Default for Affine {\n fn default() -> Self {\n Self(mi(1), mi(0))\n }\n}\n\nimpl Affine {\n fn compose(self, rhs: Self) -> Self {\n Self(self.0 * rhs.0, self.1 * rhs.0 + rhs.1)\n }\n\n fn invoke(self, x: ModInt) -> ModInt {\n self.0 * x + self.1\n }\n}\n\nimpl Add for Affine {\n type Output = Affine;\n\n fn add(self, rhs: Self) -> Self::Output {\n Affine(self.0 + rhs.0, self.1 + rhs.1)\n }\n}\n\nimpl Mul for Affine {\n type Output = Affine;\n\n fn mul(self, rhs: ModInt) -> Self::Output {\n Affine(self.0 * rhs, self.1 * rhs)\n }\n}\n\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let a0 = read!(u64);\n let x = read!(u64);\n let y = read!(u64);\n let k = read!(usize);\n let M = read!(u64);\n\n let p1 = mi(n).inv();\n let p0 = mi(1) - p1;\n let mut dp = vec![Affine(p1, mi(0)); 1];\n for i in (1..k).rev() {\n let c0 = dp.len();\n let c1 = c0 / c0.gcd(i) * i;\n dp = (0..c1).map(|j| {\n let s = j % i;\n let d1 = Affine::default() + Affine(mi(1), -mi(s)).compose(dp[(j - s) % c0]);\n let d0 = dp[j % c0];\n d1 * p1 + d0 * p0\n }).collect();\n //dbg!(\"tick\");\n }\n\n //dbg!(&dp);\n let C = dp.len();\n let mut ans = mi(0);\n let mut a = a0;\n for _ in 0..n {\n ans += dp[(a as usize) % C].invoke(mir(a as _));\n a = (a * x + y) % M;\n }\n\n ans *= mi(n).pow(k as _);\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "cb009f4cc1740a0111a65e5bf9bc36b2", "src_uid": "1d45491e28d24e2b318605cd328d6ecf", "difficulty": 2800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE.rotate_right(1) >> self.leading_zeros() } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n \n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let a0 = read!(u64);\n let x = read!(u64);\n let y = read!(u64);\n let k = read!(usize);\n let M = read!(u64);\n\n let npow = mir(n as _).pow_vec(k-1);\n\n let mut C = 1usize;\n for i in 2..k {\n C = C / C.gcd(i) * i;\n }\n let mut dp = vec![mi(0); C];\n\n let mut ans = mi(0);\n let mut a = a0;\n for _ in 0..n {\n let q = (a as usize) / C;\n let r = (a as usize) % C;\n\n ans += mir(q as _);\n dp[r] = mir(dp[r].val() + 1);\n a = (a * x + y) % M;\n }\n ans *= mir((k * C) as _) * npow[k-1];\n\n for i in 1..=k {\n let mut dn = vec![mi(0); C];\n for j in 0..C {\n ans += dp[j] * npow[k-i] * mir(j as _);\n dn[j] += dp[j] * mir((n-1) as _);\n dn[j - j % i] += dp[j];\n }\n dp = dn;\n }\n\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "28c56c6d1cca072094dd5d49a8294f9d", "src_uid": "1d45491e28d24e2b318605cd328d6ecf", "difficulty": 2800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE.rotate_right(1) >> self.leading_zeros() } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nstruct Affine(ModInt, ModInt);\n\nimpl Default for Affine {\n fn default() -> Self {\n Self(mi(1), mi(0))\n }\n}\n\nimpl Affine {\n fn compose(self, rhs: Self) -> Self {\n Self(self.0 * rhs.0, self.1 * rhs.0 + rhs.1)\n }\n\n fn invoke(self, x: ModInt) -> ModInt {\n self.0 * x + self.1\n }\n}\n\nimpl Add for Affine {\n type Output = Affine;\n\n fn add(self, rhs: Self) -> Self::Output {\n Affine(self.0 + rhs.0, self.1 + rhs.1)\n }\n}\n\nimpl Mul for Affine {\n type Output = Affine;\n\n fn mul(self, rhs: ModInt) -> Self::Output {\n Affine(self.0 * rhs, self.1 * rhs)\n }\n}\n\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let a0 = read!(u64);\n let x = read!(u64);\n let y = read!(u64);\n let k = read!(usize);\n let M = read!(u64);\n\n let p1 = mi(n).inv();\n let p0 = mi(1) - p1;\n let mut dp = vec![Affine(p1, mi(0)); 1];\n for i in (1..k).rev() {\n let c0 = dp.len();\n let c1 = c0 / c0.gcd(i) * i;\n dp = (0..c1).map(|j| {\n let s = j % i;\n let d1 = Affine::default() + Affine(mi(1), -mir(s as _)).compose(dp[(j - s) % c0]);\n let d0 = dp[j % c0];\n d1 * p1 + d0 * p0\n }).collect();\n //dbg!(\"tick\");\n }\n\n //dbg!(&dp);\n let C = dp.len();\n let mut ans = mi(0);\n let mut a = a0;\n for _ in 0..n {\n ans += dp[(a as usize) % C].invoke(mir(a as _));\n a = (a * x + y) % M;\n }\n\n ans *= mi(n).pow(k as _);\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "a18975645a6610e64411c9c6f64cdfb8", "src_uid": "1d45491e28d24e2b318605cd328d6ecf", "difficulty": 2800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::TryInto};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE.rotate_right(1) >> self.leading_zeros() } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self; while a != 0 { swap(&mut a, &mut b); a %= b; }\n b.abs()\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\n#[macro_use]\n#[allow(dead_code)]\nmod modint {\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\n use crate::ModInt;\n \n pub trait RemEuclidU32: Copy {\n /// Calculates `self` _mod_ `modulus` losslessly.\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n \n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n }\n \n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n }\n \n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n \n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n \n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n #[inline]\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\n (a as u64 * b as u64 % m as u64) as u32\n }\n \n // for a, b < m, unspecified otherwise\n #[inline]\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\n if c { r } else { a + b }\n }\n #[inline]\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\n let (r, c) = a.overflowing_sub(b);\n if c { r.wrapping_add(m) } else { r }\n }\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\n if m == 1 { return 0; }\n let mut a = a as u64;\n let m = m as u64;\n let mut r: u64 = 1;\n while k > 0 {\n if k & 1 == 1 {\n r = r * a % m;\n }\n k >>= 1;\n a = a * a % m;\n }\n r as u32\n }\n \n /// # Parameters\n /// * `b` `1 <= b`\n /// # Returns\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = a.rem_euclid(b);\n if a == 0 { return (0, b); }\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n \n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u;\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n \n if m0 < 0 { m0 += b / s; }\n (m0, s)\n }\n \n pub trait Modulus: Copy + Eq {\n fn get_modulus() -> u32;\n }\n \n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\n #[repr(transparent)]\n pub struct ModIntBase { \n val: u32,\n _phantom: PhantomData\n }\n \n impl ModIntBase {\n #[inline(always)]\n pub fn modulus() -> u32 { M::get_modulus() }\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\n pub fn inv(self) -> Self { \n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\n Self::raw(x as u32)\n }\n #[inline] pub fn val(self) -> u32 { self.val }\n #[inline] pub fn pow(self, k: u64) -> Self {\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\n }\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\n pub fn pow_vec(self, n: usize) -> Vec {\n let mut res = vec![Self::raw(0); n+1];\n res[0] += 1;\n for i in 1..=n {\n res[i] = res[i-1] * self;\n }\n res\n }\n\n pub fn invs(a: &[Self]) -> Vec {\n let n = a.len();\n if n == 0 { return vec![]; }\n let mut acc = Self::new(1);\n let mut res = Vec::with_capacity(n);\n for i in 0..n {\n if a[i].val() != 0 { acc *= a[i]; }\n res.push(acc);\n }\n acc = acc.inv();\n for i in (1..n).rev() {\n res[i] = acc * res[i-1];\n if a[i].val() != 0 { acc *= a[i]; }\n }\n res[0] = acc;\n res\n }\n }\n \n #[inline]\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\n \n impl From for ModIntBase {\n #[inline]\n fn from(from: V) -> Self { Self::new(from) }\n }\n impl Default for ModIntBase {\n fn default() -> Self { Self::raw(0) }\n }\n impl FromStr for ModIntBase {\n type Err = std::convert::Infallible;\n #[inline]\n fn from_str(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n }\n impl Display for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n self.val.fmt(f)\n }\n }\n impl std::fmt::Debug for ModIntBase {\n #[inline]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n std::fmt::Debug::fmt(&self.val, f)\n }\n }\n impl Neg for ModIntBase {\n type Output = Self;\n \n #[inline]\n fn neg(self) -> Self::Output {\n Self::raw(0) - self\n }\n }\n \n impl>, M: Modulus> Add for ModIntBase {\n type Output = Self;\n #[inline]\n fn add(self, rhs: V) -> Self::Output {\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Sub for ModIntBase {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: V) -> Self::Output {\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Mul for ModIntBase {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: V) -> Self::Output {\n Self::raw(mul_mod_u32(self.val, rhs.into().val, Self::modulus()))\n }\n }\n impl>, M: Modulus> Div for ModIntBase {\n type Output = Self;\n #[inline]\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\n }\n \n impl >, M: Modulus> AddAssign for ModIntBase {\n #[inline]\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\n }\n impl >, M: Modulus> SubAssign for ModIntBase {\n #[inline]\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\n }\n impl >, M: Modulus> MulAssign for ModIntBase {\n #[inline]\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\n }\n impl >, M: Modulus> DivAssign for ModIntBase {\n #[inline]\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\n }\n \n impl std::iter::Sum for ModIntBase {\n #[inline] fn sum>(iter: I) -> Self {\n iter.fold(Self::raw(0), Add::add)\n }\n }\n impl std::iter::Product for ModIntBase {\n #[inline] fn product>(iter: I) -> Self {\n iter.fold(1.into(), Mul::mul)\n }\n }\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\n #[inline] fn sum>(iter: I) -> ModIntBase {\n iter.fold(Self::raw(0), |a, &b| a + b)\n }\n }\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\n #[inline] fn product>(iter: I) -> ModIntBase {\n iter.fold(1.into(), |a, &b| a * b)\n }\n }\n \n macro_rules! const_modulus {\n ($mint: ident, $name: ident, $modulus: expr) => {\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n macro_rules! dynamic_modulus {\n ($mint: ident, $name: ident, $modulus: ident) => {\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(0));\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n pub enum $name {}\n impl Modulus for $name {\n fn get_modulus() -> u32 { $modulus.0.get() }\n }\n impl $name {\n pub fn set_modulus(val: u32) { $modulus.0.set(val) }\n }\n pub type $mint = ModIntBase<$name>;\n }\n }\n \n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\n}\n \nuse crate::modint::*;\ntype ModInt = ModInt998_244_353;\n// type ModInt = ModInt1_000_000_007;\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\n// type ModInt = DynamicModInt;\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nstruct Affine(ModInt, ModInt);\n\nimpl Default for Affine {\n fn default() -> Self {\n Self(mi(1), mi(0))\n }\n}\n\nimpl Affine {\n fn compose(self, rhs: Self) -> Self {\n Self(self.0 * rhs.0, self.1 * rhs.0 + rhs.1)\n }\n\n fn invoke(self, x: ModInt) -> ModInt {\n self.0 * x + self.1\n }\n}\n\nimpl Add for Affine {\n type Output = Affine;\n\n fn add(self, rhs: Self) -> Self::Output {\n Affine(self.0 + rhs.0, self.1 + rhs.1)\n }\n}\n\nimpl Mul for Affine {\n type Output = Affine;\n\n fn mul(self, rhs: ModInt) -> Self::Output {\n Affine(self.0 * rhs, self.1 * rhs)\n }\n}\n\n \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let a0 = read!(u64);\n let x = read!(u64);\n let y = read!(u64);\n let k = read!(usize);\n let M = read!(u64);\n\n let ninv = mi(n).inv();\n let mut dp = vec![Affine(ninv, mi(0)); 1];\n for i in (1..k).rev() {\n let c0 = dp.len();\n let c1 = c0 / c0.gcd(i) * i;\n dp = (0..c1).map(|j| {\n let s = j % i;\n let yes = Affine::default() + Affine(mi(1), -mi(s)).compose(dp[(j - s) % c0]);\n let no = dp[j % c0];\n (yes + no * mi(n - 1)) * ninv\n }).collect();\n //dbg!(\"tick\");\n }\n\n //dbg!(&dp);\n let C = dp.len();\n let mut ans = mi(0);\n let mut a = a0;\n for _ in 0..n {\n ans += dp[(a as usize) % C].invoke(mir(a as _));\n a = (a * x + y) % M;\n }\n\n ans *= mi(n).pow(k as _);\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "27d42188f2628fb2049d9c0eed4f6d75", "src_uid": "1d45491e28d24e2b318605cd328d6ecf", "difficulty": 2800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "pub mod solution {\n\nuse crate::io::input::Input;\nuse crate::io::output::output;\nuse crate::math::gcd::{gcd, lcm};\nuse crate::math::modulo::Mod_998_244_353;\nuse crate::misc::num_traits::ConvI32;\nuse crate::{dbg, out, out_line};\n\ntype Mod = Mod_998_244_353;\n\nfn solve(input: &mut Input, _test_case: usize) {\n let n = input.usize();\n let a0 = input.i64();\n let x = input.i64();\n let y = input.i64();\n let k = input.usize();\n let m = input.i64();\n\n let mut max = 1;\n for x in 2..=k {\n max = lcm(max, x);\n }\n\n let pr_choose = Mod::ONE / Mod::new(n as i32);\n let pr_not_choose = Mod::ONE - pr_choose;\n\n let mut dp = vec![Mod::ZERO; max];\n for i in (1..=k).rev() {\n for start in (0..max).step_by(i) {\n for shift in (0..i).rev() {\n let j = start + shift;\n dp[j] = pr_choose * (dp[start] + Mod::new(j as i32)) + pr_not_choose * dp[j];\n }\n }\n }\n\n let f = |value: i64| -> Mod {\n let value = value.to_i32() as usize;\n let more = value / dp.len() * dp.len();\n dp[value - more] + pr_choose * Mod::new(k as i32) * Mod::new(more as i32)\n };\n let mut res = f(a0);\n let mut prev = a0;\n for _ in 1..n {\n prev = (prev * x + y) % m;\n res += f(prev);\n }\n res *= Mod::new(n as i32).pown(k);\n out_line!(res);\n}\n\npub(crate) fn run(mut input: Input) -> bool {\n solve(&mut input, 1);\n output().flush();\n input.skip_whitespace();\n input.peek().is_none()\n}\n\n}\npub mod io {\npub mod input {\nuse crate::misc::ord_f64::OrdF64;\nuse std::fmt::Debug;\nuse std::io::Read;\nuse std::marker::PhantomData;\nuse std::str::FromStr;\n\npub struct Input<'s> {\n input: &'s mut dyn Read,\n buf: Vec,\n at: usize,\n buf_read: usize,\n}\n\nmacro_rules! read_integer_fun {\n ($t:ident) => {\n #[allow(unused)]\n pub fn $t(&mut self) -> $t {\n self.read_integer()\n }\n };\n}\n\nimpl<'s> Input<'s> {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n ///\n /// Using with stdin:\n /// ```\n /// use algo_lib::io::input::Input;\n /// let mut stdin = std::io::stdin();\n /// let input = Input::new(&mut stdin);\n /// ```\n ///\n /// Using file file:\n /// ```\n /// use algo_lib::io::input::Input;\n /// let mut file = std::fs::File::open(\"input.txt\").unwrap();\n /// let input = Input::new(&mut file);\n ///```\n ///\n ///\n pub fn new(input: &'s mut dyn Read) -> Self {\n Self {\n input,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn new_with_size(input: &'s mut dyn Read, buf_size: usize) -> Self {\n Self {\n input,\n buf: vec![0; buf_size],\n at: 0,\n buf_read: 0,\n }\n }\n\n pub fn get(&mut self) -> Option {\n if self.refill_buffer() {\n let res = self.buf[self.at];\n self.at += 1;\n Some(res)\n } else {\n None\n }\n }\n\n pub fn peek(&mut self) -> Option {\n if self.refill_buffer() {\n Some(self.buf[self.at])\n } else {\n None\n }\n }\n\n pub fn skip_whitespace(&mut self) {\n while let Some(b) = self.peek() {\n if !char::from(b).is_whitespace() {\n return;\n }\n self.get();\n }\n }\n\n pub fn next_token(&mut self) -> Option> {\n self.skip_whitespace();\n let mut res = Vec::new();\n while let Some(c) = self.get() {\n if char::from(c).is_whitespace() {\n break;\n }\n res.push(c);\n }\n if res.is_empty() {\n None\n } else {\n Some(res)\n }\n }\n\n //noinspection RsSelfConvention\n pub fn is_exhausted(&mut self) -> bool {\n self.peek().is_none()\n }\n\n pub fn has_more_elements(&mut self) -> bool {\n !self.is_exhausted()\n }\n\n pub fn read(&mut self) -> T {\n T::read(self)\n }\n\n pub fn read_vec(&mut self, size: usize) -> Vec {\n let mut res = Vec::with_capacity(size);\n for _ in 0usize..size {\n res.push(self.read());\n }\n res\n }\n\n pub fn read_line(&mut self) -> String {\n let mut res = String::new();\n while let Some(c) = self.get() {\n if c == b'\\n' {\n break;\n }\n if c == b'\\r' {\n if self.peek() == Some(b'\\n') {\n self.get();\n }\n break;\n }\n res.push(c.into());\n }\n res\n }\n\n #[allow(clippy::should_implement_trait)]\n pub fn into_iter(self) -> InputIterator<'s, T> {\n InputIterator {\n input: self,\n phantom: Default::default(),\n }\n }\n\n fn read_integer(&mut self) -> T\n where\n ::Err: Debug,\n {\n let res = self.read_string();\n res.parse::().unwrap()\n }\n\n fn read_string(&mut self) -> String {\n match self.next_token() {\n None => {\n panic!(\"Input exhausted\");\n }\n Some(res) => unsafe { String::from_utf8_unchecked(res) },\n }\n }\n\n pub fn string(&mut self) -> String {\n self.read_string()\n }\n\n pub fn string_as_vec(&mut self) -> Vec {\n self.read_string().into_bytes()\n }\n\n fn read_char(&mut self) -> char {\n self.skip_whitespace();\n self.get().unwrap().into()\n }\n\n fn read_float(&mut self) -> OrdF64 {\n self.read_string().parse().unwrap()\n }\n\n pub fn f64(&mut self) -> OrdF64 {\n self.read_float()\n }\n\n fn refill_buffer(&mut self) -> bool {\n if self.at == self.buf_read {\n self.at = 0;\n self.buf_read = self.input.read(&mut self.buf).unwrap();\n self.buf_read != 0\n } else {\n true\n }\n }\n\n read_integer_fun!(i32);\n read_integer_fun!(i64);\n read_integer_fun!(u32);\n read_integer_fun!(u64);\n read_integer_fun!(usize);\n}\n\npub trait Readable {\n fn read(input: &mut Input) -> Self;\n}\n\nimpl Readable for String {\n fn read(input: &mut Input) -> Self {\n input.read_string()\n }\n}\n\nimpl Readable for char {\n fn read(input: &mut Input) -> Self {\n input.read_char()\n }\n}\n\nimpl Readable for f64 {\n fn read(input: &mut Input) -> Self {\n input.read_string().parse().unwrap()\n }\n}\n\nimpl Readable for Vec {\n fn read(input: &mut Input) -> Self {\n let size = input.read();\n input.read_vec(size)\n }\n}\n\npub struct InputIterator<'s, T: Readable> {\n input: Input<'s>,\n phantom: PhantomData,\n}\n\nimpl<'s, T: Readable> Iterator for InputIterator<'s, T> {\n type Item = T;\n\n fn next(&mut self) -> Option {\n self.input.skip_whitespace();\n self.input.peek().map(|_| self.input.read())\n }\n}\n\nmacro_rules! read_integer {\n ($t:ident) => {\n impl Readable for $t {\n fn read(input: &mut Input) -> Self {\n input.read_integer()\n }\n }\n };\n}\n\nread_integer!(i8);\nread_integer!(i16);\nread_integer!(i32);\nread_integer!(i64);\nread_integer!(i128);\nread_integer!(isize);\nread_integer!(u8);\nread_integer!(u16);\nread_integer!(u32);\nread_integer!(u64);\nread_integer!(u128);\nread_integer!(usize);\n\nmacro_rules! tuple_readable {\n ( $( $name:ident )+ ) => {\n impl<$($name: Readable), +> Readable for ($($name,)+) {\n fn read(input: &mut Input) -> Self {\n ($($name::read(input),)+)\n }\n }\n }\n}\n\ntuple_readable! {T}\ntuple_readable! {T U}\ntuple_readable! {T U V}\ntuple_readable! {T U V X}\ntuple_readable! {T U V X Y}\ntuple_readable! {T U V X Y Z}\ntuple_readable! {T U V X Y Z A}\ntuple_readable! {T U V X Y Z A B}\ntuple_readable! {T U V X Y Z A B C}\ntuple_readable! {T U V X Y Z A B C D}\ntuple_readable! {T U V X Y Z A B C D E}\ntuple_readable! {T U V X Y Z A B C D E F}\n}\npub mod output {\nuse std::io::Write;\n\npub struct Output {\n output: Box,\n buf: Vec,\n at: usize,\n auto_flush: bool,\n}\n\nimpl Output {\n const DEFAULT_BUF_SIZE: usize = 4096;\n\n pub fn new(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: false,\n }\n }\n\n pub fn new_with_auto_flush(output: Box) -> Self {\n Self {\n output,\n buf: vec![0; Self::DEFAULT_BUF_SIZE],\n at: 0,\n auto_flush: true,\n }\n }\n\n pub fn flush(&mut self) {\n if self.at != 0 {\n self.output.write_all(&self.buf[..self.at]).unwrap();\n self.at = 0;\n self.output.flush().expect(\"Couldn't flush output\");\n }\n }\n\n pub fn print(&mut self, s: &T) {\n s.write(self);\n }\n\n pub fn put(&mut self, b: u8) {\n self.buf[self.at] = b;\n self.at += 1;\n if self.at == self.buf.len() {\n self.flush();\n }\n }\n\n pub fn maybe_flush(&mut self) {\n if self.auto_flush {\n self.flush();\n }\n }\n\n pub fn print_per_line(&mut self, arg: &[T]) {\n for i in arg {\n i.write(self);\n self.put(b'\\n');\n }\n }\n\n pub fn print_iter>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n\n pub fn print_iter_ref<'a, T: 'a + Writable, I: Iterator>(&mut self, iter: I) {\n let mut first = true;\n for e in iter {\n if first {\n first = false;\n } else {\n self.put(b' ');\n }\n e.write(self);\n }\n }\n}\n\nimpl Write for Output {\n fn write(&mut self, buf: &[u8]) -> std::io::Result {\n let mut start = 0usize;\n let mut rem = buf.len();\n while rem > 0 {\n let len = (self.buf.len() - self.at).min(rem);\n self.buf[self.at..self.at + len].copy_from_slice(&buf[start..start + len]);\n self.at += len;\n if self.at == self.buf.len() {\n self.flush();\n }\n start += len;\n rem -= len;\n }\n if self.auto_flush {\n self.flush();\n }\n Ok(buf.len())\n }\n\n fn flush(&mut self) -> std::io::Result<()> {\n self.flush();\n Ok(())\n }\n}\n\npub trait Writable {\n fn write(&self, output: &mut Output);\n}\n\nimpl Writable for &str {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for String {\n fn write(&self, output: &mut Output) {\n output.write_all(self.as_bytes()).unwrap();\n }\n}\n\nimpl Writable for char {\n fn write(&self, output: &mut Output) {\n output.put(*self as u8);\n }\n}\n\nimpl Writable for [T] {\n fn write(&self, output: &mut Output) {\n output.print_iter_ref(self.iter());\n }\n}\n\nimpl Writable for Vec {\n fn write(&self, output: &mut Output) {\n self[..].write(output);\n }\n}\n\nmacro_rules! write_to_string {\n ($t:ident) => {\n impl Writable for $t {\n fn write(&self, output: &mut Output) {\n self.to_string().write(output);\n }\n }\n };\n}\n\nwrite_to_string!(u8);\nwrite_to_string!(u16);\nwrite_to_string!(u32);\nwrite_to_string!(u64);\nwrite_to_string!(u128);\nwrite_to_string!(usize);\nwrite_to_string!(i8);\nwrite_to_string!(i16);\nwrite_to_string!(i32);\nwrite_to_string!(i64);\nwrite_to_string!(i128);\nwrite_to_string!(isize);\nwrite_to_string!(f32);\nwrite_to_string!(f64);\n\nimpl Writable for (T, U) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n }\n}\n\nimpl Writable for (T, U, V) {\n fn write(&self, output: &mut Output) {\n self.0.write(output);\n output.put(b' ');\n self.1.write(output);\n output.put(b' ');\n self.2.write(output);\n }\n}\n\npub static mut OUTPUT: Option = None;\n\npub fn set_global_output_to_stdout() {\n unsafe {\n OUTPUT = Some(Output::new(Box::new(std::io::stdout())));\n }\n}\n\npub fn output() -> &'static mut Output {\n unsafe {\n match &mut OUTPUT {\n None => {\n panic!(\"Panic\");\n }\n Some(output) => output,\n }\n }\n}\n\n#[macro_export]\nmacro_rules! out {\n ($first: expr $(,$args:expr )*) => {\n output().print(&$first);\n $(output().put(b' ');\n output().print(&$args);\n )*\n }\n}\n\n#[macro_export]\nmacro_rules! out_line {\n ($first: expr $(, $args:expr )* ) => {\n out!($first $(,$args)*);\n output().put(b'\\n');\n };\n () => {\n output().put(b'\\n');\n };\n}\n}\n}\npub mod math {\npub mod gcd {\nuse crate::misc::num_traits::Number;\n\n#[allow(dead_code)]\nfn extended_gcd(a: i64, b: i64, x: &mut i64, y: &mut i64) -> i64 {\n if a == 0 {\n *x = 0;\n *y = 1;\n return b;\n }\n let mut x1 = 0;\n let mut y1 = 0;\n let d = extended_gcd(b % a, a, &mut x1, &mut y1);\n *x = y1 - (b / a) * x1;\n *y = x1;\n d\n}\n\n///\n///\n/// Find any solution to equation A*x + B*y = C\n///\n/// Returns [false] if [C] is not divisible by gcd(A, B)\n///\n#[allow(dead_code)]\npub fn diophantine(a: i64, b: i64, c: i64, x0: &mut i64, y0: &mut i64, g: &mut i64) -> bool {\n *g = extended_gcd(a.abs(), b.abs(), x0, y0);\n if c % *g != 0 {\n return false;\n }\n *x0 *= c / *g;\n *y0 *= c / *g;\n if a < 0 {\n *x0 *= -1;\n }\n if b < 0 {\n *y0 *= -1;\n }\n true\n}\n\n#[allow(dead_code)]\npub fn gcd(x: T, y: T) -> T\nwhere\n T: Number + std::ops::Rem,\n{\n if x == T::ZERO {\n y\n } else {\n gcd(y % x, x)\n }\n}\n\npub fn lcm(x: T, y: T) -> T\nwhere\n T: Number + std::ops::Rem,\n{\n x / gcd(x, y) * y\n}\n}\npub mod modulo {\nuse crate::io::output::{Output, Writable};\nuse crate::misc::num_traits::{ConvI32, HasConstants};\nuse std::io::Write;\nuse std::marker::PhantomData;\n\npub trait Value: Clone + Copy {\n fn val() -> i32;\n}\n\n#[derive(Copy, Clone, Eq, PartialEq, Default, Ord, PartialOrd)]\npub struct ModWithValue(i32, PhantomData)\nwhere\n M: Value;\n\nimpl ModWithValue\nwhere\n M: Value,\n{\n #[allow(unused)]\n pub const ZERO: Self = Self(0, PhantomData);\n\n #[allow(unused)]\n pub const ONE: Self = Self(1, PhantomData);\n\n #[allow(unused)]\n pub const TWO: Self = Self(2, PhantomData);\n\n fn rev_rec(a: i32, m: i32) -> i32 {\n if a == 1 {\n return a;\n }\n return ((1 - Self::rev_rec(m % a, a) as i64 * m as i64) / a as i64 + m as i64) as i32;\n }\n\n #[allow(dead_code)]\n fn inv(self) -> Self {\n ModWithValue(Self::rev_rec(self.0, M::val()), PhantomData)\n }\n\n #[allow(dead_code)]\n pub fn new(mut x: i32) -> Self {\n if x < 0 {\n x += M::val();\n if x < 0 {\n x %= M::val();\n x += M::val();\n }\n } else if x >= M::val() {\n x -= M::val();\n if x >= M::val() {\n x %= M::val();\n }\n }\n assert!(0 <= x && x < M::val());\n Self(x, PhantomData)\n }\n\n pub fn pown(self, pw: usize) -> Self {\n if pw == 0 {\n Self::ONE\n } else if pw == 1 {\n self\n } else {\n let half = self.pown(pw / 2);\n let res = half * half;\n if pw % 2 == 0 {\n res\n } else {\n res * self\n }\n }\n }\n}\n\nimpl std::fmt::Display for ModWithValue\nwhere\n M: Value,\n{\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::fmt::Debug for ModWithValue\nwhere\n M: Value + Copy + Eq,\n{\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n const MAX: usize = 100;\n if self.0 <= MAX as i32 {\n write!(f, \"{}\", self.0)\n } else if self.0 >= M::val() - MAX as i32 {\n write!(f, \"-{}\", M::val() - self.0)\n } else {\n for denum in 1..MAX {\n for num in 1..MAX {\n if Self(num as i32, PhantomData) / Self(denum as i32, PhantomData) == *self {\n return write!(f, \"{}/{}\", num, denum);\n }\n }\n }\n write!(f, \"(?? {} ??)\", self.0)\n }\n }\n}\n\nimpl std::ops::Add for ModWithValue\nwhere\n M: Value,\n{\n type Output = Self;\n\n fn add(self, rhs: Self) -> Self::Output {\n let res = self.0 + rhs.0;\n if res >= M::val() {\n ModWithValue(res - M::val(), PhantomData)\n } else {\n ModWithValue(res, PhantomData)\n }\n }\n}\n\nimpl std::ops::AddAssign for ModWithValue\nwhere\n M: Value,\n{\n fn add_assign(&mut self, rhs: Self) {\n self.0 += rhs.0;\n if self.0 >= M::val() {\n self.0 -= M::val();\n }\n }\n}\n\nimpl std::ops::Sub for ModWithValue\nwhere\n M: Value,\n{\n type Output = Self;\n\n fn sub(self, rhs: Self) -> Self::Output {\n let res = self.0 - rhs.0;\n if res < 0 {\n ModWithValue(res + M::val(), PhantomData)\n } else {\n ModWithValue(res, PhantomData)\n }\n }\n}\n\nimpl std::ops::SubAssign for ModWithValue\nwhere\n M: Value,\n{\n fn sub_assign(&mut self, rhs: Self) {\n self.0 -= rhs.0;\n if self.0 < 0 {\n self.0 += M::val();\n }\n }\n}\n\nimpl std::ops::Mul for ModWithValue\nwhere\n M: Value,\n{\n type Output = Self;\n\n fn mul(self, rhs: Self) -> Self::Output {\n let res = (self.0 as i64) * (rhs.0 as i64) % (M::val() as i64);\n ModWithValue(res as i32, PhantomData)\n }\n}\n\nimpl std::ops::MulAssign for ModWithValue\nwhere\n M: Value,\n{\n fn mul_assign(&mut self, rhs: Self) {\n self.0 = ((self.0 as i64) * (rhs.0 as i64) % (M::val() as i64)) as i32;\n }\n}\n\nimpl std::ops::Div for ModWithValue\nwhere\n M: Value,\n{\n type Output = Self;\n\n fn div(self, rhs: Self) -> Self::Output {\n let rhs_inv = rhs.inv();\n self * rhs_inv\n }\n}\n\nimpl std::ops::DivAssign for ModWithValue\nwhere\n M: Value,\n{\n fn div_assign(&mut self, rhs: Self) {\n *self *= rhs.inv();\n }\n}\n\nimpl Writable for ModWithValue\nwhere\n M: Value,\n{\n fn write(&self, output: &mut Output) {\n output.write_fmt(format_args!(\"{}\", self.0)).unwrap();\n }\n}\n\nimpl HasConstants> for ModWithValue\nwhere\n M: Value,\n{\n // This doesn't make much sense, but hope we never use\n const MAX: ModWithValue = ModWithValue::ZERO;\n const MIN: ModWithValue = ModWithValue::ZERO;\n const ZERO: ModWithValue = ModWithValue::ZERO;\n const ONE: ModWithValue = ModWithValue::ONE;\n const TWO: ModWithValue = ModWithValue::TWO;\n}\n\nimpl ConvI32> for ModWithValue\nwhere\n M: Value,\n{\n fn from_i32(val: i32) -> ModWithValue {\n ModWithValue::new(val)\n }\n\n fn to_i32(self) -> i32 {\n self.0\n }\n}\n\npub trait ConstValue: Value + Copy {\n const VAL: i32;\n}\n\nimpl Value for V {\n fn val() -> i32 {\n Self::VAL\n }\n}\n\n#[derive(Copy, Clone, Eq, PartialEq, Default, Ord, PartialOrd)]\npub struct Value7();\nimpl ConstValue for Value7 {\n const VAL: i32 = 1_000_000_007;\n}\npub type Mod7 = ModWithValue;\n\n#[derive(Copy, Clone, Eq, PartialEq, Default, Ord, PartialOrd)]\npub struct Value9();\nimpl ConstValue for Value9 {\n const VAL: i32 = 1_000_000_009;\n}\npub type Mod9 = ModWithValue;\n\n#[derive(Copy, Clone, Eq, PartialEq, Default, Ord, PartialOrd)]\n#[allow(non_camel_case_types)]\npub struct Value_998_244_353();\nimpl ConstValue for Value_998_244_353 {\n const VAL: i32 = 998_244_353;\n}\n#[allow(non_camel_case_types)]\npub type Mod_998_244_353 = ModWithValue;\n\n#[cfg(test)]\nmod tests {\nuse crate::math::modulo::*;\n\n type Mod = Mod7;\n\n #[test]\n fn add() {\n let x = Mod::new(1);\n let y = Mod::new(2);\n assert_eq!(format!(\"{}\", x + y), \"3\");\n }\n\n #[test]\n fn sub() {\n let x = Mod::new(1);\n let y = Mod::new(2);\n assert_eq!(format!(\"{}\", x - y), \"1000000006\");\n assert_eq!(format!(\"{:?}\", x - y), \"-1\");\n }\n\n #[test]\n fn mul() {\n let x = Mod::new(3);\n let y = Mod::new(5);\n assert_eq!(format!(\"{}\", x * y), \"15\");\n }\n\n #[test]\n fn div() {\n let x = Mod::new(3);\n let y = Mod::new(5);\n assert_eq!(format!(\"{}\", x / y), \"200000002\");\n assert_eq!(format!(\"{:?}\", x / y), \"3/5\");\n }\n\n #[test]\n fn div_assign() {\n let mut x = Mod::new(3);\n let y = Mod::new(5);\n x /= y;\n assert_eq!(format!(\"{}\", x), \"200000002\");\n assert_eq!(format!(\"{:?}\", x), \"3/5\");\n }\n\n #[test]\n fn dbg_format() {\n let x = Mod::new(1) / Mod::new(2);\n let y = Mod::new(1) / Mod::new(3);\n assert_eq!(format!(\"{}\", x + y), \"833333340\");\n assert_eq!(format!(\"{:?}\", x + y), \"5/6\");\n }\n\n #[test]\n fn dbg_format_big() {\n let x = Mod::new(123) / Mod::new(457);\n assert_eq!(format!(\"{:?}\", x), \"(?? 262582059 ??)\");\n }\n\n #[test]\n fn dbg_format_more() {\n assert_eq!(format!(\"{:?}\", Mod::new(1)), \"1\");\n assert_eq!(format!(\"{:?}\", Mod::new(3)), \"3\");\n assert_eq!(format!(\"{:?}\", Mod::new(-5)), \"-5\");\n }\n\n #[test]\n fn consts() {\n let one = Mod::ONE - Mod::ZERO;\n assert_eq!(format!(\"{:?}\", one), \"1\");\n }\n}\n}\n}\npub mod misc {\npub mod dbg_macro {\n#[macro_export]\n#[allow(unused_macros)]\nmacro_rules! dbg {\n ($first_val:expr, $($val:expr),+ $(,)?) => {\n eprint!(\"[{}:{}] {} = {:?}\",\n file!(), line!(), stringify!($first_val), &$first_val);\n ($(eprint!(\", {} = {:?}\", stringify!($val), &$val)),+,);\n eprintln!();\n };\n ($first_val:expr) => {\n eprintln!(\"[{}:{}] {} = {:?}\",\n file!(), line!(), stringify!($first_val), &$first_val);\n };\n}\n}\npub mod num_traits {\nuse std::fmt::Debug;\nuse std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};\n\npub trait HasConstants {\n const MAX: T;\n const MIN: T;\n const ZERO: T;\n const ONE: T;\n const TWO: T;\n}\n\npub trait ConvI32 {\n fn from_i32(val: i32) -> T;\n fn to_i32(self) -> i32;\n}\n\npub trait Number:\n Copy\n + Add\n + AddAssign\n + Sub\n + SubAssign\n + Mul\n + MulAssign\n + Div\n + DivAssign\n + Ord\n + PartialOrd\n + Eq\n + PartialEq\n + HasConstants\n + Default\n + Debug\n + Sized\n + ConvI32\n{\n}\n\nimpl<\n T: Copy\n + Add\n + AddAssign\n + Sub\n + SubAssign\n + Mul\n + MulAssign\n + Div\n + DivAssign\n + Ord\n + PartialOrd\n + Eq\n + PartialEq\n + HasConstants\n + Default\n + Debug\n + Sized\n + ConvI32,\n > Number for T\n{\n}\n\nmacro_rules! has_constants_impl {\n ($t: ident) => {\n impl HasConstants<$t> for $t {\n const MAX: $t = $t::MAX;\n const MIN: $t = $t::MIN;\n const ZERO: $t = 0;\n const ONE: $t = 1;\n const TWO: $t = 2;\n }\n\n impl ConvI32<$t> for $t {\n fn from_i32(val: i32) -> $t {\n val as $t\n }\n\n fn to_i32(self) -> i32 {\n self as i32\n }\n }\n };\n}\n\nhas_constants_impl!(i32);\nhas_constants_impl!(i64);\nhas_constants_impl!(i128);\nhas_constants_impl!(u32);\nhas_constants_impl!(u64);\nhas_constants_impl!(u128);\nhas_constants_impl!(usize);\nhas_constants_impl!(u8);\n\nimpl ConvI32 for f64 {\n fn from_i32(val: i32) -> Self {\n val as f64\n }\n\n fn to_i32(self) -> i32 {\n self as i32\n }\n}\n\nimpl HasConstants for f64 {\n const MAX: Self = Self::MAX;\n const MIN: Self = -Self::MAX;\n const ZERO: Self = 0.0;\n const ONE: Self = 1.0;\n const TWO: Self = 2.0;\n}\n}\npub mod ord_f64 {\nuse crate::io::input::{Input, Readable};\nuse crate::io::output::{Output, Writable};\nuse crate::misc::num_traits::{ConvI32, HasConstants};\nuse std::cmp::{min, Ordering};\nuse std::fmt::{Debug, Display, Formatter};\nuse std::io::Write;\nuse std::ops::Neg;\nuse std::str::FromStr;\nuse std::num::ParseFloatError;\n\n#[derive(PartialOrd, PartialEq, Copy, Clone, Default)]\npub struct OrdF64(pub f64);\n\nimpl OrdF64 {\n pub(crate) const EPS: Self = Self(1e-9);\n\n pub fn abs(&self) -> Self {\n Self(self.0.abs())\n }\n\n pub fn eq_with_eps(&self, other: &Self) -> bool {\n let abs_diff = (*self - *other).abs();\n abs_diff <= Self::EPS || abs_diff <= min(self.abs(), other.abs()) * Self::EPS\n }\n\n pub fn sqrt(&self) -> Self {\n Self(self.0.sqrt())\n }\n\n pub fn powf(&self, n: f64) -> Self {\n Self(self.0.powf(n))\n }\n}\n\nimpl Eq for OrdF64 {}\n\nimpl Ord for OrdF64 {\n fn cmp(&self, other: &Self) -> Ordering {\n self.partial_cmp(other).unwrap()\n }\n}\n\nimpl std::ops::Add for OrdF64 {\n type Output = Self;\n\n fn add(self, rhs: Self) -> Self::Output {\n Self(self.0 + rhs.0)\n }\n}\n\nimpl std::ops::AddAssign for OrdF64 {\n fn add_assign(&mut self, rhs: Self) {\n self.0 += rhs.0;\n }\n}\n\nimpl std::ops::Sub for OrdF64 {\n type Output = Self;\n\n fn sub(self, rhs: Self) -> Self::Output {\n Self(self.0 - rhs.0)\n }\n}\n\nimpl std::ops::SubAssign for OrdF64 {\n fn sub_assign(&mut self, rhs: Self) {\n self.0 -= rhs.0;\n }\n}\n\nimpl std::ops::Mul for OrdF64 {\n type Output = Self;\n\n fn mul(self, rhs: Self) -> Self::Output {\n Self(self.0 * rhs.0)\n }\n}\n\nimpl std::ops::MulAssign for OrdF64 {\n fn mul_assign(&mut self, rhs: Self) {\n self.0 *= rhs.0;\n }\n}\n\nimpl std::ops::Div for OrdF64 {\n type Output = Self;\n\n fn div(self, rhs: Self) -> Self::Output {\n Self(self.0 / rhs.0)\n }\n}\n\nimpl std::ops::DivAssign for OrdF64 {\n fn div_assign(&mut self, rhs: Self) {\n self.0 /= rhs.0;\n }\n}\n\nimpl Neg for OrdF64 {\n type Output = Self;\n\n fn neg(self) -> Self::Output {\n Self(-self.0)\n }\n}\n\nimpl Display for OrdF64 {\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n Display::fmt(&self.0, f)\n }\n}\n\nimpl Debug for OrdF64 {\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n Debug::fmt(&self.0, f)\n }\n}\n\nimpl Writable for OrdF64 {\n fn write(&self, output: &mut Output) {\n output.write_fmt(format_args!(\"{}\", self.0)).unwrap();\n }\n}\n\nimpl Readable for OrdF64 {\n fn read(input: &mut Input) -> Self {\n Self(input.read::())\n }\n}\n\nimpl HasConstants for OrdF64 {\n const MAX: Self = Self(f64::MAX);\n const MIN: Self = Self(-f64::MAX);\n const ZERO: Self = Self(0.0);\n const ONE: Self = Self(1.0);\n const TWO: Self = Self(2.0);\n}\n\nimpl ConvI32 for OrdF64 {\n fn from_i32(val: i32) -> Self {\n Self(val as f64)\n }\n\n fn to_i32(self) -> i32 {\n self.0 as i32\n }\n}\n\nimpl FromStr for OrdF64 {\n type Err = ParseFloatError;\n\n fn from_str(s: &str) -> Result {\n match s.parse::() {\n | Ok(value ) => Ok(Self(value)),\n | Err(error) => Err(error),\n }\n }\n}\n}\n}\nfn main() {\n let mut sin = std::io::stdin();\n let input = crate::io::input::Input::new(&mut sin);\n unsafe {\n crate::io::output::OUTPUT = Some(crate::io::output::Output::new(Box::new(std::io::stdout())));\n }\n crate::solution::run(input);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "ef42c3efbe2305eeb6b20d32d20f227d", "src_uid": "1d45491e28d24e2b318605cd328d6ecf", "difficulty": 2800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::cmp;\n\nfn main() {\n let (n, m) = R!(usize, usize);\n let mut dp = vec![vec![n+1; m]; n+1];\n dp[0][0] = 0;\n for i in 0..n {\n for j in 0..m {\n dp[i+1][(j+1) % m] = cmp::min(dp[i+1][(j+1) % m], dp[i][j] + 1);\n if i + 2 <= n {\n dp[i+2][(j+1) % m] = cmp::min(dp[i+2][(j+1) % m], dp[i][j] + 1);\n }\n }\n }\n\n W!(if dp[n][0] <= n { dp[n][0] as i32 } else { -1 })\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "63a39466d4136edf863f09c770693cae", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: isize = scan.next();\n let m: isize = scan.next();\n let mut twomoves: isize = n / 2;\n let mut onemoves: isize = n % 2;\n for _ in 0..m {\n if (twomoves + onemoves ) % m == 0 {\n println!(\"{}\", twomoves+onemoves);\n return;\n }\n if twomoves > 0 {\n twomoves -= 1;\n onemoves += 2;\n }\n }\n println!(\"-1\");\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "5bb77208130446341df8f1e17aa71a4e", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let v: Vec = s.trim().split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n if v[0] < v[1] {\n println!(\"-1\");\n return;\n }\n\n let mut steps = 0;\n\n if v[0] % 2 == 1 {\n steps += 1;\n }\n\n steps += v[0] / 2;\n\n if steps % v[1] != 0 {\n steps += v[1] - steps % v[1];\n }\n\n println!(\"{}\", steps);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "8524d9368a2f150bc2bd529fed3f2199", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let ints:Vec = s.split_whitespace().map(|x| x.parse().unwrap()).collect();\n let (n,m)=(ints[0], ints[1]);\n if n < m {\n println!(\"-1\");\n } else {\n for i in (0..=n/2).rev() {\n let j = n-i*2;\n if (i+j)%m == 0 {\n println!(\"{}\", i+j);\n break;\n }\n }\n }\n}\n \n\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "24316d5533c90671ee9aabe00716b5af", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i();\n let m = input.i();\n let a = (n + 1) / 2;\n let res = a + (m - a % m) % m;\n let sol = if res <= n {\n res\n } else {\n -1\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "270935e71a463001fa68aed85695af24", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports, deprecated, dead_code)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{VecDeque,HashMap,HashSet,BTreeMap,BTreeSet,BinaryHeap};\n// Module for v1.15.1\nuse std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead\n\n// Functions\n\n// Main\nfn main() {\n\n input! {\n N: isize,\n M: isize,\n }\n\n let mut ans = -1;\n\n for i in (N+1)/2..N+1 {\n if i%M==0 {\n ans = i;\n break;\n }\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "ec6820405b6fc986e23c833a86bb71fe", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::str::FromStr;\nuse std::fmt::Debug;\nuse std::vec::IntoIter;\nuse std::cmp::{max, min};\n\nstruct InputReader {\n tokens: IntoIter\n}\n\nimpl InputReader {\n fn new() -> InputReader {\n let mut input = String::new();\n io::stdin().read_to_string(&mut input).unwrap();\n let tokens: Vec = input.split_whitespace().map(|a| a.to_string()).collect();\n InputReader {\n tokens: tokens.into_iter()\n }\n }\n\n fn next(&mut self) -> String {\n self.tokens.next().unwrap()\n }\n\n fn next_val(&mut self) -> V {\n self.next().parse::().ok().unwrap()\n }\n\n fn next_val_array(&mut self, n: usize) -> Vec {\n let mut vec = Vec::with_capacity(n);\n for _ in 0..n {\n vec.push(self.next_val::());\n }\n vec\n }\n}\n\n\nfn main() {\n let mut reader = InputReader::new();\n let n: i64 = reader.next_val();\n let mut answer = (0i64, 0i64);\n let mut diff = i64::max_value();\n for a in 1..(n+1) {\n if n % a == 0 {\n let b = n / a;\n if b >= a && b - a < diff {\n diff = b - a;\n answer = (a, b);\n }\n }\n }\n println!(\"{} {}\", answer.0, answer.1);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "33a1ff7505cc5c04421c30f5a320a088", "src_uid": "f52af273954798a4ae38a1378bfbf77a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let input = buffer.split_whitespace()\n .map(|x| x.trim().parse::().unwrap())\n .collect::>();\n let n = input[0];\n let k = input[1];\n let d = (n / 2) / (k + 1);\n let c = d * k;\n let o = n - d - c;\n println!(\"{} {} {}\", d, c, o);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a0b98562b03fb287bcf2a1c60f1e04e0", "src_uid": "405a70c3b3f1561a9546910ab3fb5c80", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s);\n let v: Vec = s.split_whitespace().map(|x| x.parse().unwrap()).collect();\n let mut lo: i64 = 0;\n let mut hi: i64 = 1e12 as i64;\n while lo <= hi {\n let mid = (lo+hi)/2;\n if (mid as f64).log10()+(v[1] as f64).log10() <= 15.0 && mid + mid*v[1] <= v[0]/2 {\n lo = mid+1;\n } else {\n hi = mid-1;\n }\n }\n println!(\"{} {} {}\", hi, hi*v[1], v[0]-hi-hi*v[1]);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "91014068a0df98d802c7e60e79a87271", "src_uid": "405a70c3b3f1561a9546910ab3fb5c80", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let (n, k): (u64, u64) = {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let mut iter = buffer.split_whitespace().map(|x| x.parse().unwrap());\n (iter.next().unwrap(), iter.next().unwrap())\n };\n let d = n/(2*k+2);\n println!(\"{} {} {}\", d, d*k, n-d*(k+1));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "02f061586cc200b442608a2c948f3d56", "src_uid": "405a70c3b3f1561a9546910ab3fb5c80", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::Write;\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($e:expr),*) => {\n #[cfg(debug_assertions)]\n $({\n let (e, mut err) = (stringify!($e), std::io::stderr());\n writeln!(err, \"{} = {:?}\", e, $e).unwrap()\n })*\n };\n}\n\nfn main() {\n let v = read_vec::();\n let (a, b, c, d) = (v[0], v[1], v[2], v[3]);\n\n let mut count = vec![0i64; b + c + 2];\n for x in a..b + 1 {\n count[x + b] += 1;\n count[x + c + 1] -= 1;\n }\n let mut accum = vec![0i64; b + c + 2];\n accum[0] = count[0];\n for x in 1..b + c + 1 {\n accum[x] = accum[x - 1] + count[x];\n }\n\n let mut ans = 0i64;\n for x_p_y in 1..b + c + 1 {\n let z_max = min(x_p_y - 1, d) as i64;\n let z_min = c as i64;\n ans += accum[x_p_y] * max(z_max - z_min + 1, 0);\n }\n println!(\"{}\", ans);\n}\n\nfn read() -> T {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn read_vec() -> Vec {\n read::()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "math", "implementation", "binary search"], "code_uid": "cb0a8b3294ae8f5abd2e3f5de781597b", "src_uid": "4f92791b9ec658829f667fcea1faee01", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt, $x:expr, $y:expr) => {{\n\t\tlet b = $y; let a = &mut $x;\n\t\tif b $c *a { *a = b; true } else { false }\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),* =$i:ident.$f:ident $a:tt) => {$(let$v=$i.$f$a;)*};\n\t($($v:ident),*:$t:ty=$i:ident.$f:ident $a:tt) => {$(let$v:$t=$i.$f$a;)*};\n\t(mut $($v:ident),+ =$i:ident.$f:ident $a:tt) => {$(let mut$v=$i.$f$a;)*};\n\t(mut $($v:ident),*:$t:ty=$i:ident.$f:ident $a:tt) => {$(let mut$v:$t=$i.$f$a;)*};\n}\nstruct WordReaderC {\n\tq: std::io::StdinLock<'static>, buf: Vec, pos: usize//'\n}\n#[allow(dead_code)]\nimpl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp::(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp::(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\nfn reader() -> WordReaderC { WordReaderC::new() }\nfn writer() -> BufWriter { BufWriter::new(stdout()) }\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tl!(a,b,c,d = rin.l());\n\tlet calc = |z| -> i64 {\n\t\tlet mut res = 0;\n\t\tfor (x,y,v) in vec![(a-1,b-1,1),(b,c,1),(a-1,c,-1),(b,b-1,-1)] {\n\t\t\tlet s = x + y - z;\n\t\t\tif s > 0 {\n\t\t\t\tres += v * s * (s + 1);\n\t\t\t}\n\t\t}\n\t\tres / 2\n\t};\n\tlet mut sol = 0;\n\tfor z in c..=d {\n\t\tsol += calc(z);\n\t}\n\twriteln!(rout, \"{}\", sol).ok();\n}\n\n", "lang_cluster": "Rust", "tags": ["two pointers", "math", "implementation", "binary search"], "code_uid": "99d9608033a764c93cf2ad529a29c107", "src_uid": "4f92791b9ec658829f667fcea1faee01", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n}\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\nuse input::*;\n\nconst N: usize = 2000000;\n\nfn main() {\n let (a, b, c, d): (usize, usize, usize, usize);\n input!(a, b, c, d);\n let mut ans = 0_i64;\n\n let mut s = vec![0_i64; N];\n for i in a..=b {\n s[i + b] += 1;\n s[i + c + 1] -= 1;\n }\n for i in 1..N {\n s[i] += s[i - 1];\n }\n for i in 1..N {\n s[i] += s[i - 1];\n }\n for z in c..=d {\n ans += s[N - 1] - s[z];\n }\n\n println!(\"{}\", ans);\n}\n\n", "lang_cluster": "Rust", "tags": ["two pointers", "math", "implementation", "binary search"], "code_uid": "ca962768d687413d8a7c7c28b653de80", "src_uid": "4f92791b9ec658829f667fcea1faee01", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt, $x:expr, $y:expr) => {{\n\t\tlet b = $y; let a = &mut $x;\n\t\tif b $c *a { *a = b; true } else { false }\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),* =$i:ident.$f:ident $a:tt) => {$(let$v=$i.$f$a;)*};\n\t($($v:ident),*:$t:ty=$i:ident.$f:ident $a:tt) => {$(let$v:$t=$i.$f$a;)*};\n\t(mut $($v:ident),+ =$i:ident.$f:ident $a:tt) => {$(let mut$v=$i.$f$a;)*};\n\t(mut $($v:ident),*:$t:ty=$i:ident.$f:ident $a:tt) => {$(let mut$v:$t=$i.$f$a;)*};\n}\nstruct WordReaderC {\n\tq: std::io::StdinLock<'static>, buf: Vec, pos: usize//'\n}\n#[allow(dead_code)]\nimpl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp::(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp::(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\nfn reader() -> WordReaderC { WordReaderC::new() }\nfn writer() -> BufWriter { BufWriter::new(stdout()) }\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tl!(a,b,c,d = rin.l());\n\tlet mut sol = 0;\n\tfor z in c..=d {\n\t\tfor (x,y,v) in vec![(a-1,b-1,1),(b,c,1),(a-1,c,-1),(b,b-1,-1)] {\n\t\t\tlet s = x + y - z;\n\t\t\tif s > 0 {\n\t\t\t\tsol += v * s * (s + 1);\n\t\t\t}\n\t\t}\n\t}\n\tsol /= 2;\n\twriteln!(rout, \"{}\", sol).ok();\n}\n\n", "lang_cluster": "Rust", "tags": ["two pointers", "math", "implementation", "binary search"], "code_uid": "a621c49543d1b692dd1f1bd2fdd3749c", "src_uid": "4f92791b9ec658829f667fcea1faee01", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! https://github.com/hatoo/competitive-rust-snippets\n//!\n//! MIT License\n//!\n//! Copyright (c) 2018 hatoo\n//!\n//! Permission is hereby granted, free of charge, to any person obtaining a copy\n//! of this software and associated documentation files (the \"Software\"), to deal\n//! in the Software without restriction, including without limitation the rights\n//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//! copies of the Software, and to permit persons to whom the Software is\n//! furnished to do so, subject to the following conditions:\n//!\n//! The above copyright notice and this permission notice shall be included in all\n//! copies or substantial portions of the Software.\n//!\n//! THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//! SOFTWARE.\n#![allow(\n unused_imports,\n unused_attributes,\n unused_macros,\n dead_code,\n non_snake_case\n)]\nuse std::cmp::{max, min, Ordering};\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\nuse std::io::{stdin, stdout, BufWriter, Write};\nuse std::iter::FromIterator;\n#[macro_export]\nmacro_rules !get {(@inner [$src :expr ] chars ) =>{{let mut buf =String ::new () ;$src .read_line (&mut buf ) .unwrap () ;buf .trim () .chars () .collect ::>() } } ;(@inner [$src :expr ] usize1 ) =>{{get !(@inner [$src ] usize ) -1 } } ;(@inner [$src :expr ] [usize1 ] ) =>{{get !(@inner [$src ] [usize ] ) .into_iter () .map (|v |v -1 ) .collect ::>() } } ;(@inner [$src :expr ] [[usize1 ] ;$n :expr ] ) =>{{(0 ..$n ) .map (|_ |get !(@inner [$src ] [usize1 ] ) ) .collect ::>() } } ;(@inner [$src :expr ] [usize1 ;$n :expr ] ) =>{{(0 ..$n ) .map (|_ |get !(@inner [$src ] [usize1 ] ) ) .flatten () .collect ::>() } } ;(@inner [$src :expr ] [[chars ] ;$n :expr ] ) =>{{(0 ..$n ) .map (|_ |get !(@inner [$src ] chars ) ) .collect ::>() } } ;(@inner [$src :expr ] [chars ;$n :expr ] ) =>{{(0 ..$n ) .map (|_ |get !(@inner [$src ] chars ) ) .collect ::>() } } ;(@inner [$src :expr ] [($($tt :tt ) ,*) ;$n :expr ] ) =>{{(0 ..$n ) .map (|_ |get !(@inner [$src ] ($($tt ) ,*) ) ) .collect ::>() } } ;(@inner [$src :expr ] ($($tt :tt ) ,*) ) =>{{let mut buf :String =String ::new () ;$src .read_line (&mut buf ) .unwrap () ;let mut iter =buf .split_whitespace () ;($(get !(@inner_elem_parse [$tt ] iter .next () .unwrap () ) ,) *) } } ;(@inner [$src :expr ] [$t :ty ] ) =>{{let mut buf =String ::new () ;$src .read_line (&mut buf ) .unwrap () ;buf .trim () .split_whitespace () .map (|t |t .parse ::<$t >() .unwrap () ) .collect ::>() } } ;(@inner [$src :expr ] [[$t :ty ] ;$n :expr ] ) =>{{(0 ..$n ) .map (|_ |get !(@inner [$src ] [$t ] ) ) .collect ::>() } } ;(@inner [$src :expr ] [$t :ty ;$n :expr ] ) =>{{(0 ..$n ) .map (|_ |get !(@inner [$src ] [$t ] ) ) .flatten () .collect ::>() } } ;(@inner [$src :expr ] $t :ty ) =>{{let mut buf =String ::new () ;$src .read_line (&mut buf ) .unwrap () ;buf .trim () .split_whitespace () .next () .unwrap () .parse ::<$t >() .unwrap () } } ;(@inner_elem_parse [usize1 ] $elem :expr ) =>{{get !(@inner_elem_parse [usize ] $elem ) -1 } } ;(@inner_elem_parse [$t :ty ] $elem :expr ) =>{{$elem .parse ::<$t >() .unwrap () } } ;($tt :tt ) =>{{use std ::io ::BufRead ;let get_stdin =std ::io ::stdin () ;let mut locked_stdin =get_stdin .lock () ;get !(@inner [&mut locked_stdin ] $tt ) } } ;}\nmacro_rules !debug {($($a :expr ) ,*$(,) *) =>{#[cfg (debug_assertions ) ] eprintln !(concat !($(\"| \" ,stringify !($a ) ,\"={:?} \" ) ,*,\"|\" ) ,$(&$a ) ,*) ;} ;}\nmacro_rules !echo {($($a :expr ) ,*) =>{let mut s =Vec ::new () ;$(s .push (format !(\"{}\" ,$a ) ) ;) *println !(\"{}\" ,s .join (\" \" ) ) ;} }\n#[macro_export]\nmacro_rules !chmin {($base :expr ,$($cmps :expr ) ,+$(,) *) =>{{let cmp_min =min !($($cmps ) ,+) ;if $base >cmp_min {$base =cmp_min ;true } else {false } } } ;}\n#[macro_export]\nmacro_rules !chmax {($base :expr ,$($cmps :expr ) ,+$(,) *) =>{{let cmp_max =max !($($cmps ) ,+) ;if $base {{$a } } ;($a :expr ,$b :expr $(,) *) =>{{std ::cmp ::min ($a ,$b ) } } ;($a :expr ,$($rest :expr ) ,+$(,) *) =>{{std ::cmp ::min ($a ,min !($($rest ) ,+) ) } } ;}\n#[macro_export]\nmacro_rules !max {($a :expr $(,) *) =>{{$a } } ;($a :expr ,$b :expr $(,) *) =>{{std ::cmp ::max ($a ,$b ) } } ;($a :expr ,$($rest :expr ) ,+$(,) *) =>{{std ::cmp ::max ($a ,max !($($rest ) ,+) ) } } ;}\nconst BIG_STACK_SIZE: bool = true;\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\nfn solve() {\n let (a, b, c, d) = get!((i64, i64, i64, i64));\n const N: usize = 1_000_100;\n let mut imos = vec![0i64; N];\n for x in a..=b {\n let from = (x + b) as usize;\n let to = (x + c + 1) as usize;\n imos[from] += 1;\n imos[to] -= 1;\n }\n for i in 1..N {\n imos[i] += imos[i - 1];\n }\n let mut cumsum = vec![0i64; N];\n for i in 1..N {\n cumsum[i] = cumsum[i - 1] + imos[i - 1];\n }\n let mut ans = 0;\n for z in c..=d {\n ans += cumsum[N - 1] - cumsum[z as usize + 1];\n }\n echo!(ans);\n}\n\nfn solve2() {\n let (a, b, c, d) = get!((i64, i64, i64, i64));\n let height = c - b;\n let width = b - a;\n let mut appear = vec![0i64; (height + width + 10) as usize];\n for i in 0..=(height + width) {\n debug!(i, width, height);\n if min(width, height) <= i && i <= max(width, height) {\n appear[i as usize] = min(width, height) + 1;\n } else if i < min(width, height) {\n appear[i as usize] = i + 1;\n } else {\n appear[i as usize] = height + width - i + 1;\n }\n }\n let mut counts = vec![0i64; (height + width + 10) as usize];\n for i in 0..=(height + width) {\n let k = i + a + b;\n if i == 0 {\n counts[i as usize] = 0;\n } else if k < c {\n counts[i as usize] = 0;\n } else if c <= k && k <= d {\n counts[i as usize] = k - c + 1;\n } else if d < k {\n counts[i as usize] = d - c + 1;\n }\n }\n debug!(counts);\n let mut ans = 0;\n for i in 0..=(height + width) {\n let i = i as usize;\n ans += counts[i] * appear[i];\n }\n echo!(ans);\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "math", "implementation", "binary search"], "code_uid": "89198dadd1dc9387b89889fedb029432", "src_uid": "4f92791b9ec658829f667fcea1faee01", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let (a, b, c, d) = parse_line!(u64, u64, u64, u64);\n let mut result = 0;\n // for x in a..=b {\n // for y in b..=c {\n // for z in c..=d {\n // if x + y > z {\n // result += 1;\n // }\n // }\n // }\n // }\n // eprintln!(\"{}\", result);\n // result = 0;\n for x in a..=b {\n if c - b + 1 >= x {\n if d - c + 1 >= x {\n result += x * (x + 1) / 2;\n }else{\n let grow = d - c + 1;\n let fix = x - grow;\n result += grow * (grow + 1) / 2 + fix * grow;\n }\n }else{\n if d - c + 1 >= x {\n let min = c - b + 1;\n result += (x - min + 1 + x) * min / 2;\n }else{\n if d - b + 1 >= x {\n let grow = d - b + 1 - x;\n result += (d - c + 1 - grow + d - c) * grow / 2 +\n (c - b + 1 - grow) * (d - c + 1);\n }else{\n result += (c - b + 1) * (d - c + 1);\n }\n }\n }\n }\n writeln!(writer, \"{}\", result).unwrap();\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["two pointers", "math", "implementation", "binary search"], "code_uid": "4e1252b761b8fd6c6b01c67c0d1f44a3", "src_uid": "4f92791b9ec658829f667fcea1faee01", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse utils::*;\n\npub fn main() {\n let i = stdin();\n let mut o = Vec::new();\n run(i.lock(), &mut o);\n stdout().write_all(&o).unwrap();\n}\n\n#[derive(PartialEq, Eq, Hash, Clone, Copy)]\nstruct Tile {\n num: usize,\n suit: char,\n}\nimpl CpIn for Tile {\n fn read_from(r: &mut CpReader) -> Self {\n let s = r.read_word_str();\n let num: usize = s[..1].parse().unwrap();\n Tile {\n num: num - 1,\n suit: s[1..].parse().unwrap(),\n }\n }\n}\n\npub fn run(i: R, o: &mut W) {\n let mut i = CpReader::new(i);\n let (t0, t1, t2) = i.read();\n writeln!(o, \"{}\", solve([t0, t1, t2])).unwrap();\n}\nfn solve(ts: [Tile; 3]) -> usize {\n let mut m = HashMap::new();\n for &t in &ts {\n *m.entry(t).or_insert(0) += 1;\n }\n let mut ans = 3 - *m.values().max().unwrap();\n\n for &suit in &['m', 'p', 's'] {\n let mut es = [false; 9];\n for &t in &ts {\n if t.suit == suit {\n es[t.num] = true;\n }\n }\n for i in 0..=9 - 3 {\n let mut c = 0;\n for j in 0..3 {\n if es[i + j] {\n c += 1;\n }\n }\n ans = min(ans, 3 - c);\n }\n }\n ans\n}\n\npub mod utils {\n use super::*;\n\n pub struct CpReader {\n r: R,\n b: Vec,\n }\n impl CpReader {\n pub fn new(r: R) -> Self {\n CpReader {\n r: r,\n b: Vec::new(),\n }\n }\n pub fn read_word(&mut self) -> &[u8] {\n self.b.clear();\n let mut consume = 0;\n loop {\n self.r.consume(consume);\n let b = self.r.fill_buf().unwrap();\n assert!(b.len() != 0);\n if let Some(p) = b.iter().position(|&x| x.is_ascii_whitespace()) {\n self.b.extend_from_slice(&b[..p]);\n consume = p + 1;\n break;\n }\n self.b.extend_from_slice(b);\n consume = b.len();\n }\n self.r.consume(consume);\n consume_ws(&mut self.r);\n &self.b\n }\n pub fn read_word_str(&mut self) -> &str {\n unsafe { std::str::from_utf8_unchecked(self.read_word()) }\n }\n\n pub fn read_line(&mut self) -> &[u8] {\n self.b.clear();\n self.r.read_until(b'\\n', &mut self.b).unwrap();\n let end = self\n .b\n .iter()\n .rposition(|x| !x.is_ascii_whitespace())\n .map(|idx| idx + 1)\n .unwrap_or(0);\n &self.b[..end]\n }\n pub fn read_line_str(&mut self) -> &str {\n unsafe { std::str::from_utf8_unchecked(self.read_line()) }\n }\n\n pub fn read(&mut self) -> T {\n T::read_from(self)\n }\n\n pub fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {\n CpIter {\n r: self,\n n: n,\n _pd: Default::default(),\n }\n }\n }\n pub struct CpIter<'a, R: BufRead + 'a, T> {\n r: &'a mut CpReader,\n n: usize,\n _pd: std::marker::PhantomData T>,\n }\n impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {\n type Item = T;\n fn next(&mut self) -> Option {\n if self.n == 0 {\n None\n } else {\n self.n -= 1;\n Some(self.r.read())\n }\n }\n }\n\n pub trait CpIn {\n fn read_from(r: &mut CpReader) -> Self;\n }\n\n impl CpIn for u64 {\n fn read_from(r: &mut CpReader) -> Self {\n read_u64_fast(&mut r.r)\n }\n }\n impl CpIn for i64 {\n fn read_from(r: &mut CpReader) -> Self {\n read_i64_fast(&mut r.r)\n }\n }\n impl CpIn for char {\n fn read_from(r: &mut CpReader) -> Self {\n let b = r.r.fill_buf().unwrap()[0] as char;\n r.r.consume(1);\n let s = r.r.fill_buf().unwrap()[0];\n assert!(s == b' ' || s == b'\\n');\n r.r.consume(1);\n b\n }\n }\n\n macro_rules! cpin_tuple {\n ($($t:ident),*) => {\n impl<$($t: CpIn),*> CpIn for ($($t),*) {\n fn read_from(r: &mut CpReader) -> Self {\n ($($t::read_from(r)),*)\n }\n }\n };\n }\n\n macro_rules! cpin_cast {\n ($t_self:ty, $t_read:ty) => {\n impl CpIn for $t_self {\n fn read_from(r: &mut CpReader) -> Self {\n <$t_read>::read_from(r) as $t_self\n }\n }\n };\n }\n macro_rules! cpin_parse {\n ($t:ty) => {\n impl CpIn for $t {\n fn read_from(r: &mut CpReader) -> Self {\n r.read_word_str().parse().unwrap()\n }\n }\n };\n }\n cpin_cast!(usize, u64);\n cpin_cast!(u32, u64);\n cpin_cast!(u16, u64);\n cpin_cast!(i32, i64);\n cpin_cast!(i16, i64);\n cpin_cast!(i8, i64);\n\n cpin_parse!(f64);\n\n cpin_tuple!(T1, T2);\n cpin_tuple!(T1, T2, T3);\n cpin_tuple!(T1, T2, T3, T4);\n cpin_tuple!(T1, T2, T3, T4, T5);\n\n fn read_u64_fast(r: &mut R) -> u64 {\n let mut value = 0;\n loop {\n let mut idx = 0;\n let buf_len;\n {\n let buf = r.fill_buf().unwrap();\n buf_len = buf.len();\n assert!(buf_len != 0);\n while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {\n value = value * 10 + (buf[idx] - b'0') as u64;\n idx += 1;\n }\n }\n if idx < buf_len {\n r.consume(idx);\n consume_ws(r);\n return value;\n }\n r.consume(idx);\n }\n }\n fn read_i64_fast(r: &mut R) -> i64 {\n let (consume, sign) = match r.fill_buf().unwrap()[0] {\n b'+' => (true, 1),\n b'-' => (true, -1),\n _ => (false, 1),\n };\n if consume {\n r.consume(1);\n }\n read_u64_fast(r) as i64 * sign\n }\n fn consume_ws(r: &mut R) {\n let mut c = 0;\n loop {\n r.consume(c);\n let b = r.fill_buf().unwrap();\n if b.len() == 0 {\n return;\n }\n if let Some(p) = b.iter().position(|&x| !x.is_ascii_whitespace()) {\n c = p;\n break;\n }\n c = b.len();\n }\n r.consume(c);\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "bea45ca79f86f12a032542b28f7d1d0e", "src_uid": "7e42cebc670e76ace967e01021f752d3", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::{HashMap, HashSet};\nuse std::cmp::max;\n\nfn read_string() -> String {\n let mut string: String = String::new();\n\n std::io::stdin().read_line(&mut string)\n .ok()\n .expect(\"Error read line!\");\n return string;\n}\n\nfn koutsu_count(koutsu : &HashMap<&str, usize> ) -> usize\n{\n koutsu.values().max().unwrap().to_owned()\n}\n\nfn shuntsu_count(shuntsu : &HashMap<&str, HashSet> ) -> usize\n{\n shuntsu.values().map(|x| suit_set_count(&x))\n .max().to_owned().unwrap()\n\n}\n\nfn suit_set_count(set : &HashSet) -> usize\n{\n if set.len() <= 1 { return set.len() }\n\n let mut list :Vec<_> = set.iter().collect();\n list.sort();\n let mut currrent_count = 1;\n let mut max_count = 1;\n let mut prev = list[0];\n for item in list\n {\n match item - prev\n {\n i if i > 2 =>\n {\n max_count = max(currrent_count, max_count);\n currrent_count = 1;\n }\n 1 =>\n {\n currrent_count += 1;\n max_count = max(currrent_count, max_count);\n }\n 2 =>\n {\n max_count = max(2, max_count);\n currrent_count = 1;\n }\n _ => { }\n\n }\n prev = item;\n }\n max_count\n}\n\nfn main() {\n\n let line : String= read_string().trim().into();\n let mut koutsu : HashMap<&str, usize> = HashMap::new();\n let mut shuntsu : HashMap<&str, HashSet> = HashMap::new();\n for elem in line.split(\" \")\n {\n koutsu.entry(elem).and_modify(|e| *e+=1).or_insert(1);\n let value = &elem[0..1].parse().unwrap();\n let suit = &elem[1..2];\n shuntsu.entry(suit).or_default().insert(*value);\n\n }\n println!(\"{}\", 3 - max(koutsu_count(&koutsu) ,shuntsu_count(&shuntsu)))\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "97ce94c4db102ad5cd20cb4118830b58", "src_uid": "7e42cebc670e76ace967e01021f752d3", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n b: usize,\n g: usize,\n n: usize,\n }\n let mut ans = 0;\n for i in 0..=n {\n let x = i;\n let y = n - i;\n if x <= b && y <= g {\n ans += 1;\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "56fe26f1bd50e7b1862e63380a870de7", "src_uid": "9266a69e767df299569986151852e7b1", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\nuse std::*;\nuse io::*;\n\nstruct Parser {\n tokens : Vec,\n}\n\nimpl Parser {\n fn new() -> Parser {\n Parser {\n tokens : Vec::new()\n }\n }\n\n fn renew_tokens(&mut self) -> () {\n let mut line = String::new();\n match stdin().read_line(&mut line) {\n Err(_) => {\n println!(\"Something terrible has happend!\");\n process::exit(1);\n },\n _ => ()\n }\n\n let tmp : Vec<&str> = line.split_whitespace().collect();\n self.tokens = tmp.into_iter().map(String::from).collect();\n self.tokens.reverse();\n }\n\n fn get_token(&mut self) -> String {\n let mut res = String::from(\"\");\n\n loop {\n if self.tokens.len() == 0 {\n self.renew_tokens();\n continue;\n }\n \n if let Some(s) = self.tokens.last() {\n res = s.clone();\n self.tokens.pop();\n }\n if res != \"\" {\n return res;\n }\n }\n }\n\n fn get_int_token(&mut self) -> String {\n let mut res = String::from(\"\");\n let has_digit = |s: &String| -> bool {\n for (_, c) in s.chars().enumerate() {\n if '0' <= c && c <= '9' {\n return true;\n }\n }\n false\n };\n\n loop {\n if self.tokens.len() == 0 {\n self.renew_tokens();\n continue;\n }\n\n if let Some(s) = self.tokens.last() {\n if has_digit(s) {\n res = s.clone();\n }\n }\n\n self.tokens.pop();\n if res != \"\" {\n return res;\n }\n }\n }\n\n fn get_i32(&mut self) -> i32 {\n let token : String = self.get_int_token();\n let mut entered = false;\n let mut num : i32 = 0;\n\n for (_, c) in token.chars().enumerate() {\n if !entered {\n if let Some(tmp) = c.to_digit(10) {\n num = tmp as i32;\n entered = true;\n }\n }\n else {\n if let Some(tmp) = c.to_digit(10) {\n num = num * 10 + (tmp as i32);\n }\n else {\n break;\n }\n }\n }\n return num;\n }\n\n fn get_i64(&mut self) -> i64 {\n let token : String = self.get_int_token();\n let mut entered = false;\n let mut num : i64 = 0;\n\n for (_, c) in token.chars().enumerate() {\n if !entered {\n if let Some(tmp) = c.to_digit(10) {\n num = tmp as i64;\n entered = true;\n }\n }\n else {\n if let Some(tmp) = c.to_digit(10) {\n num = num * 10 + (tmp as i64);\n }\n else {\n break;\n }\n }\n }\n return num;\n }\n}\n\n\n\nfn main() {\n let mut cin = Parser::new();\n\n let b = cin.get_i64();\n let g = cin.get_i64();\n let n = cin.get_i64();\n\n let mut mnb :i64 = i64::MAX;\n let mut mng :i64 = i64::MAX;\n\n for i in 0..=b {\n if n - i <= g {\n mng = n - i;\n }\n }\n for i in 0..=g {\n if n - i <= b {\n mnb = n - i\n }\n }\n\n let mut ans = 0;\n for i in 0..=n {\n if mnb <= i && mng <= n - i {\n ans+= 1;\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "d41dbde7b19566dea8977ebf7a533007", "src_uid": "9266a69e767df299569986151852e7b1", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub trait Readable {\n type Output;\n fn words_count() -> usize;\n fn read_words(words: &[&str]) -> Result;\n}\n#[macro_export]\nmacro_rules! readable {\n ( $ t : ty , $ words_count : expr , |$ words : ident | $ read_words : expr ) => {\n impl Readable for $t {\n type Output = $t;\n fn words_count() -> usize {\n $words_count\n }\n fn read_words($words: &[&str]) -> Result<$t, String> {\n Ok($read_words)\n }\n }\n };\n}\nreadable!((), 1, |_ss| ());\nreadable!(String, 1, |ss| ss[0].to_string());\nimpl Readable for char {\n type Output = char;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result {\n let chars: Vec = words[0].chars().collect();\n if chars.len() == 1 {\n Ok(chars[0])\n } else {\n Err(format!(\"cannot parse `{}` as a char\", words[0]))\n }\n }\n}\npub struct Chars();\nimpl Readable for Chars {\n type Output = Vec;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result, String> {\n Ok(words[0].chars().collect())\n }\n}\nmacro_rules ! impl_readable_for_ints { ( $ ( $ t : ty ) * ) => { $ ( impl Readable for $ t { type Output = Self ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result <$ t , String > { use std :: str :: FromStr ; <$ t >:: from_str ( words [ 0 ] ) . map_err ( | _ | { format ! ( \"cannot parse `{}` as {}\" , words [ 0 ] , stringify ! ( $ t ) ) } ) } } ) * } ; }\nimpl_readable_for_ints ! ( i8 u8 i16 u16 i32 u32 i64 u64 isize usize f32 f64 ) ;\nmacro_rules ! define_one_origin_int_types { ( $ new_t : ident $ int_t : ty ) => { # [ doc = \" Converts 1-origin integer into 0-origin when read from stdin.\" ] # [ doc = \"\" ] # [ doc = \" # Example\" ] # [ doc = \"\" ] # [ doc = \" ```no_run\" ] # [ doc = \" # #[macro_use] extern crate atcoder_snippets;\" ] # [ doc = \" # use atcoder_snippets::read::*;\" ] # [ doc = \" // Stdin: \\\"1\\\"\" ] # [ doc = \" read!(a = usize_);\" ] # [ doc = \" assert_eq!(a, 0);\" ] # [ doc = \" ```\" ] # [ allow ( non_camel_case_types ) ] pub struct $ new_t ; impl Readable for $ new_t { type Output = $ int_t ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { <$ int_t >:: read_words ( words ) . map ( | n | n - 1 ) } } } ; ( $ new_t : ident $ int_t : ty ; $ ( $ inner_new_t : ident $ inner_int_t : ty ) ;* ) => { define_one_origin_int_types ! ( $ new_t $ int_t ) ; define_one_origin_int_types ! ( $ ( $ inner_new_t $ inner_int_t ) ;* ) ; } ; }\ndefine_one_origin_int_types ! ( u8_ u8 ; u16_ u16 ; u32_ u32 ; u64_ u64 ; usize_ usize ) ;\nmacro_rules ! impl_readable_for_tuples { ( $ t : ident $ var : ident ) => ( ) ; ( $ t : ident $ var : ident ; $ ( $ inner_t : ident $ inner_var : ident ) ;* ) => { impl_readable_for_tuples ! ( $ ( $ inner_t $ inner_var ) ;* ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,*> Readable for ( $ t , $ ( $ inner_t ) ,* ) { type Output = ( <$ t >:: Output , $ ( <$ inner_t >:: Output ) ,* ) ; fn words_count ( ) -> usize { let mut n = <$ t >:: words_count ( ) ; $ ( n += <$ inner_t >:: words_count ( ) ; ) * n } # [ allow ( unused_assignments ) ] fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { let mut start = 0 ; let $ var = <$ t >:: read_words ( & words [ start .. start +<$ t >:: words_count ( ) ] ) ?; start += <$ t >:: words_count ( ) ; $ ( let $ inner_var = <$ inner_t >:: read_words ( & words [ start .. start +<$ inner_t >:: words_count ( ) ] ) ?; start += <$ inner_t >:: words_count ( ) ; ) * Ok ( ( $ var , $ ( $ inner_var ) ,* ) ) } } } ; }\nimpl_readable_for_tuples ! ( T8 x8 ; T7 x7 ; T6 x6 ; T5 x5 ; T4 x4 ; T3 x3 ; T2 x2 ; T1 x1 ) ;\npub trait ReadableFromLine {\n type Output;\n fn read_line(line: &str) -> Result;\n}\nfn split_into_words(line: &str) -> Vec<&str> {\n #[allow(deprecated)]\n line.trim_right_matches('\\n').split_whitespace().collect()\n}\nimpl ReadableFromLine for T {\n type Output = T::Output;\n fn read_line(line: &str) -> Result {\n let words = split_into_words(line);\n if words.len() != T::words_count() {\n return Err(format!(\n \"line `{}` has {} words, expected {}\",\n line,\n words.len(),\n T::words_count()\n ));\n }\n T::read_words(&words)\n }\n}\nmacro_rules ! impl_readable_from_line_for_tuples_with_from_iterator { ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident ) => { impl <$ u : Readable > ReadableFromLine for $ seq_in where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = $ seq_out ; fn read_line ( line : & str ) -> Result <$ seq_out , String > { let n = $ u :: words_count ( ) ; let words = split_into_words ( line ) ; if words . len ( ) % n != 0 { return Err ( format ! ( \"line `{}` has {} words, expected multiple of {}\" , line , words . len ( ) , n ) ) ; } let mut result = Vec :: new ( ) ; for chunk in words . chunks ( n ) { match $ u :: read_words ( chunk ) { Ok ( v ) => result . push ( v ) , Err ( msg ) => { let flagment_msg = if n == 1 { format ! ( \"word {}\" , result . len ( ) ) } else { let l = result . len ( ) ; format ! ( \"words {}-{}\" , n * l + 1 , ( n + 1 ) * l ) } ; return Err ( format ! ( \"{} of line `{}`: {}\" , flagment_msg , line , msg ) ) ; } } } Ok ( result . into_iter ( ) . collect ( ) ) } } impl < T : Readable , $ u : Readable > ReadableFromLine for ( T , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( T :: Output , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let n = T :: words_count ( ) ; # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; Ok ( ( T :: read_words ( words ) ?, <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident , $ ( $ inner_t : ident $ inner_var : ident ) ,+ ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ seq_in , $ seq_out ; $ ( $ inner_t $ inner_var ) ,+ ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,+ , $ u : Readable > ReadableFromLine for ( $ t , $ ( $ inner_t ) ,+ , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( $ t :: Output , $ ( $ inner_t :: Output ) ,+ , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let mut n = $ t :: words_count ( ) ; $ ( n += $ inner_t :: words_count ( ) ; ) + # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; let ( $ var , $ ( $ inner_var ) ,* ) = < ( $ t , $ ( $ inner_t ) ,+ ) >:: read_words ( words ) ?; Ok ( ( $ var , $ ( $ inner_var ) ,* , <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; }\n#[macro_export]\nmacro_rules ! readable_collection { ( $ u : ident => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 t4 , T3 t3 , T2 t2 , T1 t1 ) ; } ; ( $ u : ident : $ ( $ bound : path ) ,* => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 t4 , T3 t3 , T2 t2 , T1 t1 ) ; } }\nreadable_collection ! ( U => Vec < U >, Vec < U :: Output > ) ;\nreadable_collection ! ( U : Eq , std :: hash :: Hash => std :: collections :: HashSet < U >, std :: collections :: HashSet < U :: Output > ) ;\npub fn read() -> T::Output {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n T::read_line(&line).unwrap()\n}\n#[macro_export]\nmacro_rules ! read { ( ) => { let mut line = String :: new ( ) ; std :: io :: stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; } ; ( $ pat : pat = $ t : ty ) => { let $ pat = read ::<$ t > ( ) ; } ; ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { read ! ( ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) ) ; } ; }\n#[macro_export]\nmacro_rules ! readls { ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { $ ( read ! ( $ pat = $ t ) ; ) * } ; }\npub fn readx() -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result = stdin\n .lock()\n .lines()\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n result\n}\n#[macro_export]\nmacro_rules ! readx_loop { ( |$ pat : pat = $ t : ty | $ body : expr ) => { { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; for line in stdin . lock ( ) . lines ( ) { let line = line . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readx_loop ! ( | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub fn readn(n: usize) -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result: Vec = stdin\n .lock()\n .lines()\n .take(n)\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n if result.len() < n {\n panic!(\n \"expected reading {} lines, but only {} lines are read\",\n n,\n result.len()\n );\n }\n result\n}\n#[macro_export]\nmacro_rules ! readn_loop { ( $ n : expr , |$ pat : pat = $ t : ty | $ body : expr ) => { { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; let mut lock = stdin . lock ( ) ; for _ in 0 ..$ n { let mut line = String :: new ( ) ; lock . read_line ( & mut line ) . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( $ n : expr , |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readn_loop ! ( $ n , | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub trait Words {\n fn read(&self) -> T::Output;\n}\nimpl<'a> Words for [&'a str] {\n fn read(&self) -> T::Output {\n T::read_words(self).unwrap()\n }\n}\nimpl<'a> Words for &'a str {\n fn read(&self) -> T::Output {\n T::read_words(&[self]).unwrap()\n }\n}\n\nuse std::cmp;\n\nfn main() {\n readls!(b = u16, g = u16, n = u16);\n let b = cmp::min(b, n);\n let g = cmp::min(g, n);\n println!(\"{}\", b+g - (n-1));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "9684fd8ec72438e93b04ccfc075adde5", "src_uid": "9266a69e767df299569986151852e7b1", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let mut buffer_iter = buffer.split_whitespace().map(|n| n.parse::().unwrap());\n let b = buffer_iter.next().unwrap();\n let g = buffer_iter.next().unwrap();\n let n = buffer_iter.next().unwrap();\n\n let (x1, x2) = if b >= g {\n (b, g)\n } else {\n (g, b)\n };\n\n let result = if x2 < n {\n x2 + 1 - if n > x1 { n - x1 } else { 0 }\n } else {\n n + 1\n };\n println!(\"{}\", result);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "af588f7f1353cc9b89b2dba85a8e9e21", "src_uid": "9266a69e767df299569986151852e7b1", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: u64 = scan.next();\n let m: u64 = scan.next();\n let maxcalc = (n-m+1) * (n-m) / 2;\n let minval1 = n/m + 1;\n let minval2 = n/m;\n let minn1 = n%m;\n let minn2 = m - minn1;\n let mincalc = (minval1*(minval1-1)/2)*minn1 \n + (minval2*(minval2-1)/2)*minn2;\n println!(\"{} {}\", mincalc, maxcalc);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "95440df957b4891e3a0d8c404c5c5d7b", "src_uid": "a081d400a5ce22899b91df38ba98eecc", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn solve() {\n let (n, m): (i64, i64) = {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let mut ws = buf.split_whitespace();\n let n = ws.next().unwrap().parse().unwrap();\n let m = ws.next().unwrap().parse().unwrap();\n (n, m)\n };\n\n let min = {\n let a = n / m;\n let b = n - a * m;\n (a + 1) * a / 2 * b + a * (a - 1) / 2 * (m - b)\n };\n\n let max = {\n let t = n - (m - 1);\n t * (t - 1) / 2\n };\n\n println!(\"{} {}\", min, max);\n}\n\nfn main() {\n // let t: u32 = {\n // let mut buf = String::new();\n // std::io::stdin().read_line(&mut buf).unwrap();\n // buf.trim_end().parse().unwrap()\n // };\n\n // for _ in 0..t {}\n solve();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "10bee1744412938467bde26aed5b41bb", "src_uid": "a081d400a5ce22899b91df38ba98eecc", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n let mut bout = BufWriter::new(stdout());\n\n let f = |n,x| x * n * (n - 1) / 2;\n let n: i64 = input.p();\n let m: i64 = input.p();\n let r = n % m;\n writeln!(bout, \"{} {}\", f(n/m, m-r) + f(n/m+1, r), f(n-m+1, 1)).ok();\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "22a8dcd92db449db890047e24931e980", "src_uid": "a081d400a5ce22899b91df38ba98eecc", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn c2 (x:i64) -> i64 { let y=x as i64; y * (y-1)/2 }\n\nfn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut ints = s.split_whitespace().map(|x| x.parse::().unwrap());\n let n = ints.next().unwrap();\n let t = ints.next().unwrap();\n if n == t {\n println!(\"0 0\");\n } else {\n let max = c2(n - t + 1);\n let a = n/t;\n let b = n%t;\n let min = b*c2(a+1)+(t-b)*c2(a);\n println!(\"{} {}\",min, max);\n }\n\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "27ad3624506f9d7ca6305d5bcf92db23", "src_uid": "a081d400a5ce22899b91df38ba98eecc", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io;\nuse std::cmp::*;\nuse std::collections::*;\n#[allow(dead_code)]\nconst M: i64 = 1e9 as i64 + 7;\n\nfn read_line() -> String {\n let stdin = io::stdin();\n let mut buf = String::new();\n stdin.read_line(&mut buf).unwrap();\n buf\n}\n#[allow(dead_code)]\nfn read() -> T where T: std::str::FromStr, T::Err : std::fmt::Debug {\n read_line().trim().parse().unwrap()\n}\n#[allow(dead_code)]\nfn readv() -> Vec where T: std::str::FromStr, T::Err : std::fmt::Debug {\n read_line().split(' ').map(|a| a.trim().parse().unwrap()).collect()\n}\n\nfn get_diff(n: i64) -> i64{\n let mut diff = n;\n for i in 0..19 {\n diff -= n / 10i64.pow(i) % 10;\n }\n diff\n}\n\nfn main() {\n let input = readv::();\n let (n, s) = (input[0], input[1]);\n let mut num = n;\n if get_diff(n) < s {\n println!(\"{}\", 0);\n return;\n }\n for i in (1..19).rev() {\n let p = 10i64.pow(i);\n loop {\n num -= p;\n if get_diff(num) < s {\n num += p;\n break;\n }\n }\n }\n num = num / 10 * 10;\n println!(\"{}\", n - num + 1);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "binary search"], "code_uid": "f3167b02d22493ad33c7a6ab90c95c4a", "src_uid": "9704e2ac6a158d5ced8fd1dc1edb356b", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn gcd(a: u64, b: u64) -> u64 {\n if a < b {\n return gcd(b, a);\n }\n if b == 0 {\n return a;\n }\n return gcd(b, a % b);\n}\n\nfn main() {\n let mut size = String::new();\n io::stdin().read_line(&mut size).unwrap();\n let size: Vec<&str> = size.split(\" \").collect();\n let a: u64 = size[0].trim().parse().unwrap();\n let b: u64 = size[1].trim().parse().unwrap();\n let mut x: u64 = size[2].trim().parse().unwrap();\n let mut y: u64 = size[3].trim().parse().unwrap();\n let g = gcd(x, y);\n x /= g;\n y /= g;\n // Case 1: keep b and cut a\n let mut area1 = 0;\n let b1 = b / y * y;\n let a1 = b1 * x / y;\n if b1 > 0 && a1 <= a {\n area1 = b1 * a1;\n }\n\n // Case 2: keep a and cut b\n let mut area2 = 0;\n let a2 = a / x * x;\n let b2 = a2 * y / x;\n if a2 > 0 && b2 <= b {\n area2 = a2 * b2;\n }\n\n if area2 > area1 {\n print!(\"{} {}\", a2, b2);\n } else if area1 >= area2 && area1 > 0 {\n print!(\"{} {}\", a1, b1);\n } else {\n print!(\"{} {}\", 0, 0);\n }\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "number theory"], "code_uid": "100978606bb59b4060f95f7678f669d2", "src_uid": "97999cd7c6de79a4e39f56a41ff59e7a", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let mut p = vec![0; n + 1];\n let mut sol = 0;\n for i in 2..=n {\n if p[i] == 0 {\n let mut j = i;\n while j <= n {\n p[j] += 1;\n j += i;\n }\n } else if p[i] == 2 {\n sol += 1;\n }\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "c93a65c24e1c2caf5185113017b22958", "src_uid": "356666366625bc5358bc8b97c8d67bd5", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn sieve_of_eratosthene(n: usize) -> Vec {\n let mut is_prime = vec![true; std::cmp::max(n, 2)];\n\n is_prime[0] = false;\n is_prime[1] = false;\n \n\n let mut i = 2;\n loop {\n while i < n && !is_prime[i] {\n i += 1;\n }\n\n let cur_prime = i;\n\n let mut q = 2;\n while q * cur_prime < n {\n is_prime[q * cur_prime] = false;\n q += 1;\n }\n\n i += 1;\n if i >= n {\n return is_prime;\n }\n }\n}\n\nfn primes(is_prime: &Vec) -> Vec {\n let mut primes = Vec::new();\n for i in 0..is_prime.len() {\n if is_prime[i] {\n primes.push(i);\n }\n }\n \n primes\n}\n\nfn is_number_good(prime: &Vec, n: usize) -> bool {\n let mut firstmult = 0;\n\n for i in 0..prime.len() {\n if n % prime[i] == 0 {\n firstmult = prime[i];\n break;\n }\n }\n\n let mut secmult = 0;\n for i in 0..prime.len() {\n if n % prime[i] == 0 && prime[i] != firstmult {\n secmult = prime[i];\n break;\n }\n }\n\n if secmult == 0 {\n return false;\n }\n\n for i in 0..prime.len() {\n if n % prime[i] == 0 && prime[i] != firstmult && prime[i] != secmult {\n return false\n }\n }\n\n true\n}\nfn main() {\n let mut str = String::new();\n\n std::io::stdin().read_line(&mut str).unwrap();\n\n let n = str.trim().parse::().unwrap();\n\n let is_prime = sieve_of_eratosthene(n);\n\n let mut c = 0;\n for i in 2..=n {\n if is_number_good(&primes(&is_prime), i) {\n c += 1;\n }\n }\n\n println!(\"{}\", c);\n}\n\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "def50c60fd7a299f1c19f67258443db1", "src_uid": "356666366625bc5358bc8b97c8d67bd5", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\nuse std::collections::HashSet;\n\nstruct Reader {}\n\nimpl Reader {\n #[allow(unused)]\n fn read_string() -> String {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.trim().to_string()\n }\n\n #[allow(unused)]\n fn read_tokens() -> Vec:: {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n v\n }\n}\n\n//mod math;\n\nfn generate_simple_numbers(max_value: i64) -> Vec {\n let mut src = vec![true; max_value as usize + 1];\n let mut dst = Vec::new();\n\n for i in 2 .. max_value as usize + 1 {\n if src[i] {\n let mut ind = i * i;\n while ind <= max_value as usize {\n src[ind] = false;\n ind += i;\n }\n }\n }\n for i in 2 .. max_value as usize + 1 {\n if src[i] {\n dst.push(i as i64);\n }\n }\n dst\n}\n\n\nfn main() {\n\n let n = Reader::read_string().parse::().unwrap();\n let simple_numbers = generate_simple_numbers(3000);\n let mut ans = 0_i64;\n for i in 1..=n {\n let mut number = i;\n let mut map = std::collections::BTreeSet::::new();\n for value in simple_numbers.iter() {\n if *value > number {\n break;\n }\n while number % *value == 0 {\n map.insert(*value);\n number /= *value;\n }\n }\n if map.len() == 2 {\n ans += 1;\n }\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "7a78fcac34f549da20a37a901f3b1a6d", "src_uid": "356666366625bc5358bc8b97c8d67bd5", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\nuse std::collections::HashSet;\n\nstruct Reader {}\n\nimpl Reader {\n #[allow(unused)]\n fn read_string() -> String {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n string.trim().to_string()\n }\n\n #[allow(unused)]\n fn read_tokens() -> Vec:: {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string).unwrap();\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n v\n }\n}\n\n//mod math;\n\nfn generate_simple_numbers(max_value: i64) -> Vec {\n let mut src = vec![true; max_value as usize + 1];\n let mut dst = Vec::new();\n\n for i in 2 .. max_value as usize + 1 {\n if src[i] {\n let mut ind = i * i;\n while ind <= max_value as usize {\n src[ind] = false;\n ind += i;\n }\n }\n }\n for i in 2 .. max_value as usize + 1 {\n if src[i] {\n dst.push(i as i64);\n }\n }\n dst\n}\n\n\nfn main() {\n\n let n = Reader::read_string().parse::().unwrap();\n let simple_numbers = generate_simple_numbers(3000);\n let mut ans = 0_i64;\n for i in 1..=n {\n let mut number = i;\n let mut map = std::collections::HashMap::::new();\n for value in simple_numbers.iter() {\n if *value > number {\n break;\n }\n while number % *value == 0 {\n map.insert(*value, 1);\n number /= *value;\n }\n }\n if map.len() == 2 {\n ans += 1;\n }\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "7bf16cbf678b37359571a54c74c40a9e", "src_uid": "356666366625bc5358bc8b97c8d67bd5", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn find_xy(r: i64) -> Option<(i64, i64)> {\n let mut x = 1;\n while x * x <= r {\n let term = r - x * x - x - 1;\n if term > 0 && term % (2 * x) == 0 {\n let y = term / (2 * x);\n return Some((x, y));\n }\n x += 1;\n }\n None\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let r: i64 = scan.token();\n match find_xy(r) {\n Some((x, y)) => writeln!(out, \"{} {}\", x, y).ok(),\n None => writeln!(out, \"NO\").ok(),\n };\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "d2be76ea3b591d1239ca13b678612a09", "src_uid": "3ff1c25a1026c90aeb14d148d7fb96ba", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\n#[derive(Clone)]\nstruct Graph {\n nodes: usize,\n edges: Vec>,\n}\n\nimpl Graph {\n fn new(n: usize) -> Self {\n Self {\n nodes: n,\n edges: vec![Vec::new(); n + 1],\n }\n }\n\n fn add_edge(&mut self, x: usize, y: usize, cost: u64) {\n self.edges[x].push((y, cost));\n self.edges[y].push((x, cost));\n }\n\n fn dijkstra(&mut self, start: usize, end: usize) -> u64 {\n let mut dist = vec![None; self.nodes + 1];\n let mut prev = vec![None; self.nodes + 1];\n dist[start] = Some(0);\n let mut queue = (1..=self.nodes).collect::>();\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n while let Some(next_node) = queue.pop() {\n if next_node == end {\n return dist[next_node].unwrap();\n }\n for (neighbour, cost) in self.edges[next_node].iter() {\n let alt = dist[next_node].unwrap() + cost;\n if dist[*neighbour].is_none() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n } else {\n if alt < dist[*neighbour].unwrap() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n }\n }\n }\n //println!(\"{:?} {:?}\", dist, prev);\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n }\n 0\n }\n\n fn set_cost(&mut self, x: usize, y: usize, cost: u64) {\n for i in 0..self.edges[x].len() {\n if self.edges[x][i].0 == y {\n self.edges[x][i].1 = cost\n }\n }\n for i in 0..self.edges[y].len() {\n if self.edges[y][i].0 == x {\n self.edges[y][i].1 = cost\n }\n }\n }\n}\n\nconst MODULO: u64 = 1_000_000_007;\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\nstruct BigPrimeRing {\n inner: u64,\n}\n\nimpl From for BigPrimeRing\nwhere\n T: Into,\n{\n fn from(n: T) -> Self {\n Self {\n inner: n.into() % MODULO,\n }\n }\n}\n\nimpl std::ops::Add for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn add(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::AddAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn add_assign(&mut self, rhs: T) {\n self.inner += rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Sub for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn sub(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + MODULO - rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::SubAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn sub_assign(&mut self, rhs: T) {\n self.inner += MODULO;\n self.inner -= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Mul for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn mul(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner * rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::MulAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn mul_assign(&mut self, rhs: T) {\n self.inner *= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl BigPrimeRing {\n fn inverse(self) -> Self {\n if self.inner == 0 {\n return self;\n }\n let (_g, mut x, _y) = egcd(self.inner as i64, MODULO as i64);\n if x < 0 {\n x += MODULO as i64;\n }\n Self { inner: x as u64 }\n }\n}\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn main() -> Result<(), Box> {\n let r = read::();\n if r < 5 {\n println!(\"NO\");\n return Ok(());\n }\n let mut x = 1;\n let mut part = x * x + x + 1;\n while part < r {\n if (r - part) % (2 * x) == 0 {\n println!(\"{} {}\", x, (r - part) / (2 * x));\n return Ok(());\n }\n x += 1;\n part = x * x + x + 1;\n }\n println!(\"NO\");\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "0ee00fd7874aad4c4f350364fefc5e92", "src_uid": "3ff1c25a1026c90aeb14d148d7fb96ba", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut text = String::new();\n std::io::stdin().read_line(&mut text).expect(\"\");\n let n = text.trim().parse::().expect(\"\");\n\n if n > 3 && n % 2 == 1 {\n println!(\"1 {}\", (n - 3) / 2)\n } else {\n println!(\"NO\")\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "2b4ec933ca5bd92064a75b6dd963a6fa", "src_uid": "3ff1c25a1026c90aeb14d148d7fb96ba", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let mut line = String::new();\n let stdin = io::stdin();\n stdin\n .lock()\n .read_line(&mut line)\n .expect(\"could not read line!\");\n\n let line = line.trim();\n let path = line\n .split('/')\n .filter(|s| !s.is_empty())\n .collect::>();\n\n println!(\"/{}\", path.join(\"/\"));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "27e3fc0fe669f7cdbe145e3819bb7834", "src_uid": "6c2e658ac3c3d6b0569dd373806fa031", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused)]\n#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::collections::{HashSet, HashMap};\nuse std::cmp::{min,max,Reverse};\nuse std::io::{self, prelude::*};\nuse std::{str, iter};\n\nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: vec![], buf_iter: \"\".split_whitespace() }\n }\n fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace())\n }\n }\n }\n}\n\nconst MAX : usize = 444;\n\nfn solve(scan: &mut Scanner, w: &mut W) {\n let N : usize = scan.token();\n let K : usize = scan.token();\n let L : i64 = scan.token();\n let d : Vec = iter::repeat_with(|| scan.token()).take(N).collect();\n let p : Vec = (0..K).chain((1..K+1).rev()).cycle().take(4*K).map(|x| x as i64).collect();\n\n let mut dp = [[false; MAX]; MAX];\n dp[N] = [true; MAX];\n\n for i in (0..N).rev() {\n for j in (0..4*K).rev() {\n dp[i][j] = (d[i] + p[j] <= L) && (dp[i][j+1] || dp[i+1][(j+1)%(2*K)]);\n }\n }\n // for i in (0..N).rev() {\n // println!(\"{}, {:?}\",i,&dp[i][0..2*K]);\n // }\n\n\n writeln!(w, \"{}\", if dp[0].iter().any(|&x|x) {\"Yes\"} else {\"No\"});\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n for _ in 0..scan.token::() {\n solve(&mut scan, &mut out);\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "dp"], "code_uid": "774c23288f238324fc5ef1896c04205f", "src_uid": "4941b0a365f86b2e2cf686cdf5d532f8", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::fmt::Debug;\nuse std::str::FromStr;\n\npub struct TokenReader {\n reader: std::io::Stdin,\n tokens: Vec,\n index: usize,\n}\n\nimpl TokenReader {\n pub fn new() -> Self {\n Self {\n reader: std::io::stdin(),\n tokens: Vec::new(),\n index: 0,\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index += 1;\n self.tokens[self.index - 1].parse().unwrap()\n }\n\n pub fn vector(&mut self) -> Vec\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index = self.tokens.len();\n self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()\n }\n\n pub fn load_next_line(&mut self) {\n let mut line = String::new();\n self.reader.read_line(&mut line).unwrap();\n\n self.tokens = line\n .split_whitespace()\n .map(String::from)\n .collect();\n self.index = 0;\n }\n}\n\nfn tide(k: usize, time: usize) -> usize {\n let time = time % (2 * k);\n if time <= k {\n time\n } else {\n 2 * k - time\n }\n}\n\nfn depth(k: usize, depths: &Vec, time: usize, index: usize) -> usize {\n depths[index] + tide(k, time)\n}\n\nfn prev_time(k: usize, time: usize) -> usize {\n if time == 0 {\n 2 * k - 1\n } else {\n time - 1\n }\n}\n\nfn possible(k: usize, l: usize, depths: &Vec) -> bool {\n let mut dp = vec![vec![false; 2 * k]; depths.len()];\n for i in 0..2 * k {\n if depth(k, depths, i, 0) <= l {\n dp[0][i] = true;\n }\n }\n\n for i in 1..depths.len() {\n for t in 0..2 * k {\n let p = prev_time(k, t);\n let d = depth(k, depths, t, i);\n\n if d > l {\n continue;\n } else if dp[i - 1][p] {\n dp[i][t] = true;\n } else if dp[i][p] {\n dp[i][t] = true;\n }\n }\n }\n dp[depths.len() - 1].iter().any(|&b| b)\n}\n\nfn main() {\n let mut reader = TokenReader::new();\n let tests = reader.next();\n\n for _ in 0..tests {\n let _ = reader.next::();\n let k = reader.next();\n let l = reader.next();\n let depths = reader.vector();\n\n let res = possible(k, l, &depths);\n println!(\"{}\", if res { \"Yes\" } else { \"No\" });\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "dp"], "code_uid": "e2e35e6b7ca37b5351229b55df31976f", "src_uid": "4941b0a365f86b2e2cf686cdf5d532f8", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io;\nuse std::ops::{self, Range};\nuse std::str::FromStr;\n\n#[derive(Clone, Debug, Default)]\nstruct ProblemState {\n}\n\nimpl Problem {\n fn solve(&mut self) {\n let n: usize = self.scan();\n let k: usize = self.scan();\n let l: usize = self.scan();\n let d: Vec = self.scan_vec(n);\n\n let mut x = vec![vec![0; 2 * k]; n];\n let mut p = vec![0; 2 * k];\n\n for i in 0..k {\n p[i] = i;\n p[2 * k - i - 1] = i + 1;\n }\n\n for i in 0..n {\n for j in 0..2 * k {\n if d[i] + p[j] <= l {\n if i == 0 {\n x[i][j] = 1;\n } else {\n x[i][j] |= x[i - 1][(j - 1 + 2 * k) % (2 * k)];\n x[i][j] |= x[i][(j - 1 + 2 * k) % (2 * k)];\n }\n }\n }\n }\n\n if x[n - 1].iter().any(|x_i| *x_i == 1) {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n\n// eprintln!(\"{:?}\", x[n - 1]);\n }\n}\n\nfn main() {\n Problem::new().solve_cases();\n}\n\nstruct Problem {\n input_state: InputState,\n problem_state: ProblemState,\n}\n\nstruct InputState {\n stdin: io::Stdin,\n buffer: String,\n tokens: VecDeque,\n}\n\nimpl Problem {\n fn new() -> Self {\n Self {\n input_state: InputState {\n stdin: io::stdin(),\n buffer: String::new(),\n tokens: VecDeque::new(),\n },\n problem_state: Default::default(),\n }\n }\n\n fn solve_cases(&mut self) {\n for _ in 0usize..self.scan() {\n self.solve()\n }\n }\n\n fn scan(&mut self) -> T {\n while self.input_state.tokens.is_empty() {\n self.input_state.stdin.read_line(&mut self.input_state.buffer).unwrap();\n\n for token in self.input_state.buffer.split_ascii_whitespace() {\n self.input_state.tokens.push_back(token.to_string());\n }\n\n self.input_state.buffer.clear();\n }\n\n self.input_state.tokens.pop_front().unwrap().parse().ok().unwrap()\n }\n\n fn scan_vec(&mut self, n: usize) -> Vec {\n (0..n).into_iter().map(|_| self.scan()).collect()\n }\n\n fn scan_line(&mut self) -> String {\n let mut line = String::new();\n self.input_state.stdin.read_line(&mut line).unwrap();\n while line.ends_with('\\n') || line.ends_with('\\r') { line.pop(); }\n line\n }\n\n fn scan_line_vec(&mut self, n: usize) -> Vec {\n (0..n).into_iter().map(|_| self.scan_line()).collect()\n }\n}\n\nimpl ops::Deref for Problem {\n type Target = ProblemState;\n\n fn deref(&self) -> &ProblemState {\n &self.problem_state\n }\n}\n\nimpl ops::DerefMut for Problem {\n fn deref_mut(&mut self) -> &mut ProblemState {\n &mut self.problem_state\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "dp"], "code_uid": "ff614fd5f7e9c61375a6f80bf16c85d5", "src_uid": "4941b0a365f86b2e2cf686cdf5d532f8", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::Write;\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($e:expr),*) => {\n #[cfg(debug_assertions)]\n $({\n let (e, mut err) = (stringify!($e), std::io::stderr());\n writeln!(err, \"{} = {:?}\", e, $e).unwrap()\n })*\n };\n}\n\nfn calc_depth(d: &Vec, p: &Vec, ki: usize, ni: usize) -> i64 {\n d[ni - 1] + p[ki]\n}\n\nfn solve() -> bool {\n let v = read_vec::();\n let (n, k, l) = (v[0], v[1], v[2] as i64);\n let d = read_vec::();\n let p = (0..2 * k)\n .map(|x| if x <= k { x as i64 } else { (2 * k - x) as i64 })\n .collect::>();\n\n let mut dp = vec![vec![false; 2 * k]; n + 1];\n for ki in 0..2 * k {\n dp[0][ki] = true;\n }\n\n for ni in 1..n + 1 {\n for ki in 0..2 * k {\n let next_k = (ki + 1) % (2 * k);\n if dp[ni - 1][ki] && calc_depth(&d, &p, next_k, ni) <= l {\n dp[ni][next_k] = true;\n }\n }\n for ki in 0..2 * k {\n let next_k = (ki + 1) % (2 * k);\n if dp[ni][ki] && calc_depth(&d, &p, next_k, ni) <= l {\n dp[ni][next_k] = true;\n }\n }\n }\n\n dp[n].iter().any(|&x| x)\n}\n\nfn main() {\n let n = read::();\n for i in 0..n {\n if solve() {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n }\n}\n\nfn read() -> T {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).ok();\n s.trim().parse().ok().unwrap()\n}\n\nfn read_vec() -> Vec {\n read::()\n .split_whitespace()\n .map(|e| e.parse().ok().unwrap())\n .collect()\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "dp"], "code_uid": "974366c7ec0b6b0fe946c23a240e5086", "src_uid": "4941b0a365f86b2e2cf686cdf5d532f8", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub trait Readable {\n type Output;\n fn words_count() -> usize;\n fn read_words(words: &[&str]) -> Result;\n}\n#[macro_export]\nmacro_rules! readable {\n ( $ t : ty , $ words_count : expr , |$ words : ident | $ read_words : expr ) => {\n impl Readable for $t {\n type Output = $t;\n fn words_count() -> usize {\n $words_count\n }\n fn read_words($words: &[&str]) -> Result<$t, String> {\n Ok($read_words)\n }\n }\n };\n}\nreadable!((), 1, |_ss| ());\nreadable!(String, 1, |ss| ss[0].to_string());\nimpl Readable for char {\n type Output = char;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result {\n let chars: Vec = words[0].chars().collect();\n if chars.len() == 1 {\n Ok(chars[0])\n } else {\n Err(format!(\"cannot parse `{}` as a char\", words[0]))\n }\n }\n}\npub struct Chars();\nimpl Readable for Chars {\n type Output = Vec;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result, String> {\n Ok(words[0].chars().collect())\n }\n}\nmacro_rules ! impl_readable_for_ints { ( $ ( $ t : ty ) * ) => { $ ( impl Readable for $ t { type Output = Self ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result <$ t , String > { use std :: str :: FromStr ; <$ t >:: from_str ( words [ 0 ] ) . map_err ( | _ | { format ! ( \"cannot parse `{}` as {}\" , words [ 0 ] , stringify ! ( $ t ) ) } ) } } ) * } ; }\nimpl_readable_for_ints ! ( i8 u8 i16 u16 i32 u32 i64 u64 isize usize f32 f64 ) ;\nmacro_rules ! define_one_origin_int_types { ( $ new_t : ident $ int_t : ty ) => { # [ doc = \" Converts 1-origin integer into 0-origin when read from stdin.\" ] # [ doc = \"\" ] # [ doc = \" # Example\" ] # [ doc = \"\" ] # [ doc = \" ```no_run\" ] # [ doc = \" # #[macro_use] extern crate atcoder_snippets;\" ] # [ doc = \" # use atcoder_snippets::read::*;\" ] # [ doc = \" // Stdin: \\\"1\\\"\" ] # [ doc = \" read!(a = usize_);\" ] # [ doc = \" assert_eq!(a, 0);\" ] # [ doc = \" ```\" ] # [ allow ( non_camel_case_types ) ] pub struct $ new_t ; impl Readable for $ new_t { type Output = $ int_t ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { <$ int_t >:: read_words ( words ) . map ( | n | n - 1 ) } } } ; ( $ new_t : ident $ int_t : ty ; $ ( $ inner_new_t : ident $ inner_int_t : ty ) ;* ) => { define_one_origin_int_types ! ( $ new_t $ int_t ) ; define_one_origin_int_types ! ( $ ( $ inner_new_t $ inner_int_t ) ;* ) ; } ; }\ndefine_one_origin_int_types ! ( u8_ u8 ; u16_ u16 ; u32_ u32 ; u64_ u64 ; usize_ usize ) ;\nmacro_rules ! impl_readable_for_tuples { ( $ t : ident $ var : ident ) => ( ) ; ( $ t : ident $ var : ident ; $ ( $ inner_t : ident $ inner_var : ident ) ;* ) => { impl_readable_for_tuples ! ( $ ( $ inner_t $ inner_var ) ;* ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,*> Readable for ( $ t , $ ( $ inner_t ) ,* ) { type Output = ( <$ t >:: Output , $ ( <$ inner_t >:: Output ) ,* ) ; fn words_count ( ) -> usize { let mut n = <$ t >:: words_count ( ) ; $ ( n += <$ inner_t >:: words_count ( ) ; ) * n } # [ allow ( unused_assignments ) ] fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { let mut start = 0 ; let $ var = <$ t >:: read_words ( & words [ start .. start +<$ t >:: words_count ( ) ] ) ?; start += <$ t >:: words_count ( ) ; $ ( let $ inner_var = <$ inner_t >:: read_words ( & words [ start .. start +<$ inner_t >:: words_count ( ) ] ) ?; start += <$ inner_t >:: words_count ( ) ; ) * Ok ( ( $ var , $ ( $ inner_var ) ,* ) ) } } } ; }\nimpl_readable_for_tuples ! ( T8 x8 ; T7 x7 ; T6 x6 ; T5 x5 ; T4 x4 ; T3 x3 ; T2 x2 ; T1 x1 ) ;\npub trait ReadableFromLine {\n type Output;\n fn read_line(line: &str) -> Result;\n}\nfn split_into_words(line: &str) -> Vec<&str> {\n #[allow(deprecated)]\n line.trim_right_matches('\\n').split_whitespace().collect()\n}\nimpl ReadableFromLine for T {\n type Output = T::Output;\n fn read_line(line: &str) -> Result {\n let words = split_into_words(line);\n if words.len() != T::words_count() {\n return Err(format!(\n \"line `{}` has {} words, expected {}\",\n line,\n words.len(),\n T::words_count()\n ));\n }\n T::read_words(&words)\n }\n}\nmacro_rules ! impl_readable_from_line_for_tuples_with_from_iterator { ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident ) => { impl <$ u : Readable > ReadableFromLine for $ seq_in where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = $ seq_out ; fn read_line ( line : & str ) -> Result <$ seq_out , String > { let n = $ u :: words_count ( ) ; let words = split_into_words ( line ) ; if words . len ( ) % n != 0 { return Err ( format ! ( \"line `{}` has {} words, expected multiple of {}\" , line , words . len ( ) , n ) ) ; } let mut result = Vec :: new ( ) ; for chunk in words . chunks ( n ) { match $ u :: read_words ( chunk ) { Ok ( v ) => result . push ( v ) , Err ( msg ) => { let flagment_msg = if n == 1 { format ! ( \"word {}\" , result . len ( ) ) } else { let l = result . len ( ) ; format ! ( \"words {}-{}\" , n * l + 1 , ( n + 1 ) * l ) } ; return Err ( format ! ( \"{} of line `{}`: {}\" , flagment_msg , line , msg ) ) ; } } } Ok ( result . into_iter ( ) . collect ( ) ) } } impl < T : Readable , $ u : Readable > ReadableFromLine for ( T , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( T :: Output , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let n = T :: words_count ( ) ; # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; Ok ( ( T :: read_words ( words ) ?, <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; ( $ u : ident : $ ( + $ bound : path ) * => $ seq_in : ty , $ seq_out : ty ; $ t : ident $ var : ident , $ ( $ inner_t : ident $ inner_var : ident ) ,+ ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ seq_in , $ seq_out ; $ ( $ inner_t $ inner_var ) ,+ ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,+ , $ u : Readable > ReadableFromLine for ( $ t , $ ( $ inner_t ) ,+ , $ seq_in ) where <$ u as Readable >:: Output : Sized $ ( + $ bound ) * { type Output = ( $ t :: Output , $ ( $ inner_t :: Output ) ,+ , $ seq_out ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let mut n = $ t :: words_count ( ) ; $ ( n += $ inner_t :: words_count ( ) ; ) + # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line `{}` has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; let ( $ var , $ ( $ inner_var ) ,* ) = < ( $ t , $ ( $ inner_t ) ,+ ) >:: read_words ( words ) ?; Ok ( ( $ var , $ ( $ inner_var ) ,* , <$ seq_in >:: read_line ( rest ) ? ) ) } } } ; }\n#[macro_export]\nmacro_rules ! readable_collection { ( $ u : ident => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 t4 , T3 t3 , T2 t2 , T1 t1 ) ; } ; ( $ u : ident : $ ( $ bound : path ) ,* => $ collection_in : ty , $ collection_out : ty ) => { impl_readable_from_line_for_tuples_with_from_iterator ! ( $ u : $ ( + $ bound ) * => $ collection_in , $ collection_out ; T8 x8 , T7 x7 , T6 x6 , T5 x5 , T4 t4 , T3 t3 , T2 t2 , T1 t1 ) ; } }\nreadable_collection ! ( U => Vec < U >, Vec < U :: Output > ) ;\nreadable_collection ! ( U : Eq , std :: hash :: Hash => std :: collections :: HashSet < U >, std :: collections :: HashSet < U :: Output > ) ;\npub fn read() -> T::Output {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n T::read_line(&line).unwrap()\n}\n#[macro_export]\nmacro_rules ! read { ( ) => { let mut line = String :: new ( ) ; std :: io :: stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; } ; ( $ pat : pat = $ t : ty ) => { let $ pat = read ::<$ t > ( ) ; } ; ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { read ! ( ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) ) ; } ; }\n#[macro_export]\nmacro_rules ! readls { ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { $ ( read ! ( $ pat = $ t ) ; ) * } ; }\npub fn readx() -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result = stdin\n .lock()\n .lines()\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n result\n}\n#[macro_export]\nmacro_rules ! readx_loop { ( |$ pat : pat = $ t : ty | $ body : expr ) => { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; for line in stdin . lock ( ) . lines ( ) { let line = line . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } ; ( |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readx_loop ! ( | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub fn readn(n: usize) -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result: Vec = stdin\n .lock()\n .lines()\n .take(n)\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n })\n .collect();\n if result.len() < n {\n panic!(\n \"expected reading {} lines, but only {} lines are read\",\n n,\n result.len()\n );\n }\n result\n}\n#[macro_export]\nmacro_rules ! readn_loop { ( $ n : expr , |$ pat : pat = $ t : ty | $ body : expr ) => { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; { let mut lock = stdin . lock ( ) ; for _ in 0 ..$ n { let mut line = String :: new ( ) ; lock . read_line ( & mut line ) . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( $ n : expr , |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readn_loop ! ( $ n , | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub trait Words {\n fn read(&self) -> T::Output;\n}\nimpl<'a> Words for [&'a str] {\n fn read(&self) -> T::Output {\n T::read_words(self).unwrap()\n }\n}\nimpl<'a> Words for &'a str {\n fn read(&self) -> T::Output {\n T::read_words(&[self]).unwrap()\n }\n}\n\nfn main() {\n read!(x = i16, y = i16, z = i16);\n let t = x - y;\n let ans = if t - z > 0 {\n '+'\n } else if t + z < 0 {\n '-'\n } else if t == 0 && z == 0 {\n '0'\n } else {\n '?'\n };\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "5b1b4a802424aab40636ce3639340f92", "src_uid": "66398694a4a142b4a4e709d059aca0fa", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input! {\n x: i32,\n y: i32,\n z: i32,\n }\n\n let a = x - y;\n if a > 0 && a > z {\n println!(\"+\");\n } else if a < 0 && -a > z {\n println!(\"-\");\n } else if a == 0 && z == 0 {\n println!(\"0\");\n } else {\n println!(\"?\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "9c23e01b7c73b4a2ecb62b3c52ef3072", "src_uid": "66398694a4a142b4a4e709d059aca0fa", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// use wyf_lib::*;\n\nfn main() {\n let n: usize = read();\n let m: usize = read();\n\n if n == 1 {\n println!(\"1\");\n return;\n }\n\n let mut k = 0;\n while 1 << k < n {\n k += 1;\n }\n let mut dp = vec![false; k * m + 1];\n let mut cnts = vec![0];\n for i in 1..=k {\n let mut cnt = 0;\n for j in 1..=m {\n let cur = i * j;\n if !dp[cur] {\n dp[cur] = true;\n cnt += 1;\n }\n }\n cnts.push(cnt);\n }\n let mut counted = vec![false; n + 1];\n\n let mut res: i64 = 1;\n 'i: for i in 2..=n {\n let mut c = 1;\n let mut curr = i;\n\n while curr <= n {\n if counted[curr] {\n continue 'i;\n }\n counted[curr] = true;\n res += cnts[c];\n curr *= i;\n c += 1;\n }\n }\n\n res.println();\n}\n\nuse std::error;\nuse std::fmt;\nuse std::str::FromStr;\n\n#[non_exhaustive]\n#[derive(Debug, PartialEq)]\npub enum Error {\n MissingMatch,\n MissingClosingBrace,\n UnexpectedValue(u8, Option),\n InvalidUtf8(Vec),\n PartialUtf8(usize, Vec),\n Parse(String, &'static str),\n}\n\nimpl error::Error for Error {}\n\nimpl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n use crate::Error::*;\n use std::str::from_utf8;\n\n match *self {\n InvalidUtf8(ref raw) => write!(f, \"input was not valid utf8: {:?}\", raw),\n Parse(ref s, arg) => write!(f, \"could not parse {} as target type of {}\", s, arg),\n UnexpectedValue(exp, act) => write!(\n f,\n \"found value {:?} not matching the pattern value {}\",\n act.map(|b| b as char),\n exp as char\n ),\n PartialUtf8(n, ref raw) => write!(\n f,\n \"input was only partially valid utf8: \\\"{}\\\" followed by {:?}\",\n from_utf8(&raw[..n]).unwrap(),\n &raw[n..]\n ),\n MissingMatch => write!(f, \"Bad read! format string: did not contain {{}}\"),\n MissingClosingBrace => write!(\n f,\n \"found single open curly brace at the end of the format string\"\n ),\n }\n }\n}\n\npub fn match_next(expected: u8, iter: &mut dyn Iterator) -> Result<(), Error> {\n let next = iter.next();\n if next != Some(expected) {\n return Err(Error::UnexpectedValue(expected, next));\n }\n Ok(())\n}\n\npub fn parse_capture(\n name: &'static str,\n next: Option,\n iter: &mut dyn Iterator,\n) -> Result\nwhere\n T: FromStr,\n ::Err: ::std::fmt::Debug,\n{\n static WHITESPACES: &[u8] = b\"\\t\\r\\n \";\n let raw: Vec = match next {\n Some(c) => iter.take_while(|&ch| ch != c).collect(),\n None => iter\n .skip_while(|ch| WHITESPACES.contains(ch))\n .take_while(|ch| !WHITESPACES.contains(ch))\n .collect(),\n };\n match String::from_utf8(raw) {\n Ok(s) => FromStr::from_str(&s).map_err(|_| Error::Parse(s, name)),\n Err(e) => {\n let n = e.utf8_error().valid_up_to();\n let raw = e.into_bytes();\n if n == 0 {\n Err(Error::InvalidUtf8(raw))\n } else {\n Err(Error::PartialUtf8(n, raw))\n }\n }\n }\n}\n\n#[macro_export]\nmacro_rules! try_read(\n () => { $crate::try_read!(\"{}\") };\n ($text:expr) => {{\n (|| -> std::result::Result<_, $crate::Error> {\n let __try_read_var__;\n $crate::try_scan!($text, __try_read_var__);\n Ok(__try_read_var__)\n })()\n }};\n ($text:expr, $input:expr) => {{\n (|| -> std::result::Result<_, $crate::Error> {\n let __try_read_var__;\n $crate::try_scan!($input => $text, __try_read_var__);\n Ok(__try_read_var__)\n })()\n }};\n);\n\n#[macro_export]\nmacro_rules! try_scan(\n ($pattern:expr, $($arg:expr),*) => {\n use ::std::io::Read;\n $crate::try_scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $pattern, $($arg),*);\n };\n ($input:expr => $pattern:expr, $($arg:expr),*) => {{\n $crate::try_scan!(@impl question_mark; $input => $pattern, $($arg),*)\n }};\n (@question_mark: $($e:tt)+) => {{\n ($($e)+)?\n }};\n (@unwrap: $($e:tt)+) => {{\n ($($e)+).unwrap()\n }};\n (@impl $action:tt; $input:expr => $pattern:expr, $($arg:expr),*) => {{\n #![allow(clippy::try_err)]\n use $crate::{Error, match_next, parse_capture};\n\n // typesafe macros :)\n let pattern: &'static str = $pattern;\n let stdin: &mut dyn Iterator = &mut ($input);\n\n let mut pattern = pattern.bytes();\n\n $(\n $arg = loop {\n match $crate::try_scan!(@$action: pattern.next().ok_or(Error::MissingMatch)) {\n b'{' => match $crate::try_scan!(@$action: pattern.next().ok_or(Error::MissingClosingBrace)) {\n b'{' => $crate::try_scan!(@$action: match_next(b'{', stdin)),\n b'}' => break $crate::try_scan!(@$action: parse_capture(stringify!($arg), pattern.next(), stdin)),\n _ => return $crate::try_scan!(@$action: Err(Error::MissingClosingBrace)),\n },\n c => $crate::try_scan!(@$action: match_next(c, stdin)),\n }\n };\n )*\n\n for c in pattern {\n $crate::try_scan!(@$action: match_next(c, stdin))\n }\n\n format_args!($pattern, $($arg),*);\n }};\n);\n\n#[macro_export]\nmacro_rules! read(\n ($($arg:tt)*) => {\n $crate::try_read!($($arg)*).unwrap()\n };\n);\n\n#[macro_export]\nmacro_rules! scan(\n ($text:expr, $($arg:expr),*) => {\n {\n use ::std::io::Read;\n $crate::scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $text, $($arg),*);\n }\n };\n ($input:expr => $pattern:expr, $($arg:expr),*) => {{\n $crate::try_scan!(@impl unwrap; $input => $pattern, $($arg),*)\n }};\n);\nuse std::marker::PhantomData;\r\nuse std::ops;\r\n\r\n// use text_io::read;\r\n\r\n/*** READ and WRITE ***/\r\n\r\npub trait Readable {\r\n fn read() -> Self;\r\n}\r\n\r\npub trait Printable {\r\n fn print(self: &Self);\r\n fn println(self: &Self) {\r\n self.print();\r\n println!();\r\n }\r\n}\r\n\r\nmacro_rules! impl_rp_simple {\r\n ($($t:ident), +) => {\r\n $(\r\n impl Readable for $t {\r\n fn read() -> Self {\r\n read!()\r\n }\r\n }\r\n\r\n impl Printable for $t {\r\n fn print(self: &Self) {\r\n print!(\"{self} \");\r\n }\r\n }\r\n )+\r\n };\r\n}\r\n\r\nimpl_rp_simple!(\r\n String, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, char\r\n);\r\n\r\nmacro_rules! impl_rp_tuple {\r\n () => {};\r\n ($t0:ident, $($t:ident,) *) => {\r\n impl<$t0: Readable, $($t: Readable), *> Readable for ($t0, $($t,)*) {\r\n fn read() -> Self {\r\n (read(), $(read::<$t>(),)*)\r\n }\r\n }\r\n\r\n impl<$t0: Printable, $($t: Printable), *> Printable for ($t0, $($t,)*) {\r\n fn print(self: &Self) {\r\n #[allow(non_snake_case)]\r\n let (ref $t0, $(ref $t,)*) = &self;\r\n $t0.print();\r\n $(\r\n $t.print();\r\n )*\r\n }\r\n }\r\n\r\n impl_rp_tuple!{$($t,) *}\r\n };\r\n}\r\n\r\nimpl Printable for Vec {\r\n fn print(self: &Self) {\r\n for x in self {\r\n x.print();\r\n }\r\n }\r\n}\r\n\r\nimpl Printable for [T] {\r\n fn print(self: &Self) {\r\n for x in self {\r\n x.print();\r\n }\r\n }\r\n}\r\n\r\nimpl_rp_tuple! {T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,}\r\n\r\npub fn read() -> T {\r\n T::read()\r\n}\r\n\r\npub fn readv(size: usize) -> Vec {\r\n let mut res = Vec::with_capacity(size);\r\n for _ in 0..size {\r\n res.push(read());\r\n }\r\n res\r\n}\r\n\r\npub fn readb() -> Vec {\r\n let s: String = read!();\r\n s.as_bytes().into_iter().cloned().collect()\r\n}\r\n\r\n/*** RECURSIVE LAMBDA ***/\r\n\r\nmacro_rules! recursive_fn {\r\n () => {};\r\n ($name0:ident $trait0:ident $_:ident $__:ident, $($name:ident $trait:ident $Arg:ident $arg:ident,)*) => {\r\n pub trait $trait0<$($Arg,)* Output> {\r\n fn call(&mut self, $($arg: $Arg,)*) -> Output;\r\n }\r\n\r\n pub struct $name0\r\n where\r\n F: FnMut(&mut dyn $trait0<$($Arg,)* Output>, $($Arg,)*) -> Output,\r\n {\r\n f: std::cell::UnsafeCell,\r\n $(\r\n $arg: PhantomData<$Arg>,\r\n )*\r\n phantom_output: PhantomData,\r\n }\r\n\r\n impl $name0\r\n where\r\n F: FnMut(&mut dyn $trait0<$($Arg,)* Output>, $($Arg,)*) -> Output,\r\n {\r\n pub fn new(f: F) -> Self {\r\n Self {\r\n f: std::cell::UnsafeCell::new(f),\r\n $(\r\n $arg: PhantomData,\r\n )*\r\n phantom_output: PhantomData,\r\n }\r\n }\r\n }\r\n\r\n impl $trait0<$($Arg,)* Output> for $name0\r\n where\r\n F: FnMut(&mut dyn $trait0<$($Arg,)* Output>, $($Arg,)*) -> Output,\r\n {\r\n fn call(&mut self, $($arg: $Arg,)*) -> Output {\r\n unsafe { (&mut *self.f.get())(self, $($arg,)*) }\r\n }\r\n }\r\n\r\n recursive_fn!{$($name $trait $Arg $arg,)*}\r\n };\r\n}\r\n\r\nrecursive_fn! {\r\n RecursiveFn11 Callable11 Arg11 arg11,\r\n RecursiveFn10 Callable10 Arg10 arg10,\r\n RecursiveFn9 Callable9 Arg9 arg9,\r\n RecursiveFn8 Callable8 Arg8 arg8,\r\n RecursiveFn7 Callable7 Arg7 arg7,\r\n RecursiveFn6 Callable6 Arg6 arg6,\r\n RecursiveFn5 Callable5 Arg5 arg5,\r\n RecursiveFn4 Callable4 Arg4 arg4,\r\n RecursiveFn3 Callable3 Arg3 arg3,\r\n RecursiveFn2 Callable2 Arg2 arg2,\r\n RecursiveFn1 Callable1 Arg1 arg1,\r\n RecursiveFn0 Callable0 Arg0 arg0,\r\n}\r\n\r\n/*** MOD ***/\r\n\r\n// gcd, x, y\r\npub fn extended_gcd(a: i64, b: i64) -> (i64, i64, i64) {\r\n if a == 0 {\r\n (b, 0, 1)\r\n } else {\r\n let (g, y, mut x) = extended_gcd(b % a, a);\r\n x -= (b / a) * y;\r\n (g, x, y)\r\n }\r\n}\r\n\r\npub trait HasConstVal {\r\n const VAL: i64;\r\n}\r\n\r\n// const of V has to be prime\r\n#[derive(Copy, Clone, Eq, PartialEq)]\r\npub struct ModBase {\r\n v: i64,\r\n phantom: PhantomData,\r\n}\r\n\r\nimpl ModBase {\r\n pub fn new(mut v: i64) -> Self {\r\n v %= M::VAL;\r\n if v < 0 {\r\n v = v + M::VAL;\r\n }\r\n Self {\r\n v,\r\n phantom: PhantomData,\r\n }\r\n }\r\n\r\n pub fn inv(&self) -> Self {\r\n let (_, x, _) = extended_gcd(self.v, M::VAL);\r\n Self::new(x)\r\n }\r\n\r\n pub fn pow(&self, n: usize) -> Self {\r\n let v = self.v;\r\n let mut res = Self::new(1);\r\n for _ in 0..n {\r\n res *= v;\r\n }\r\n res\r\n }\r\n}\r\n\r\nimpl ops::Add for ModBase {\r\n type Output = Self;\r\n\r\n fn add(self, rhs: i64) -> Self {\r\n Self::new(self.v + rhs)\r\n }\r\n}\r\n\r\nimpl ops::Add for ModBase {\r\n type Output = Self;\r\n\r\n fn add(self, rhs: Self) -> Self {\r\n Self::new(self.v + rhs.v)\r\n }\r\n}\r\n\r\nimpl ops::AddAssign for ModBase {\r\n fn add_assign(&mut self, rhs: i64) {\r\n self.v = (self.v + rhs) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::AddAssign for ModBase {\r\n fn add_assign(&mut self, rhs: Self) {\r\n self.v = (self.v + rhs.v) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::Sub for ModBase {\r\n type Output = Self;\r\n\r\n fn sub(self, rhs: i64) -> Self {\r\n Self::new(self.v - rhs)\r\n }\r\n}\r\n\r\nimpl ops::Sub for ModBase {\r\n type Output = Self;\r\n\r\n fn sub(self, rhs: Self) -> Self {\r\n Self::new(self.v - rhs.v)\r\n }\r\n}\r\n\r\nimpl ops::SubAssign for ModBase {\r\n fn sub_assign(&mut self, rhs: i64) {\r\n self.v = (self.v - rhs) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::SubAssign for ModBase {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n self.v = (self.v - rhs.v) % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::Mul for ModBase {\r\n type Output = Self;\r\n\r\n fn mul(self, rhs: i64) -> Self::Output {\r\n Self::new(self.v * rhs)\r\n }\r\n}\r\n\r\nimpl ops::Mul for ModBase {\r\n type Output = Self;\r\n\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::new(self.v * rhs.v)\r\n }\r\n}\r\n\r\nimpl ops::MulAssign for ModBase {\r\n fn mul_assign(&mut self, rhs: i64) {\r\n self.v = self.v * rhs % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::MulAssign for ModBase {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n self.v = self.v * rhs.v % M::VAL;\r\n }\r\n}\r\n\r\nimpl ops::Div for ModBase {\r\n type Output = Self;\r\n\r\n fn div(self, rhs: i64) -> Self::Output {\r\n self * Self::new(rhs).inv()\r\n }\r\n}\r\n\r\nimpl ops::Div for ModBase {\r\n type Output = Self;\r\n\r\n fn div(self, rhs: Self) -> Self::Output {\r\n self * rhs.inv()\r\n }\r\n}\r\n\r\nimpl ops::DivAssign for ModBase {\r\n fn div_assign(&mut self, rhs: i64) {\r\n self.v = (Self::new(self.v) / rhs).v;\r\n }\r\n}\r\n\r\nimpl ops::DivAssign for ModBase {\r\n fn div_assign(&mut self, rhs: Self) {\r\n self.v = (Self::new(self.v) / rhs).v;\r\n }\r\n}\r\n\r\nimpl ops::Neg for ModBase {\r\n type Output = Self;\r\n\r\n fn neg(self) -> Self::Output {\r\n Self::new(-self.v)\r\n }\r\n}\r\n\r\nimpl ops::Deref for ModBase {\r\n type Target = i64;\r\n\r\n fn deref(&self) -> &Self::Target {\r\n &self.v\r\n }\r\n}\r\n\r\n#[macro_export]\r\nmacro_rules! Mod {\r\n ($val: expr) => {\r\n Mod!(Mod, ModV, $val);\r\n };\r\n ($name: ident, $v_name: ident, $val: expr) => {\r\n #[derive(Copy, Clone, Eq, PartialEq)]\r\n pub struct $v_name {}\r\n\r\n impl crate::HasConstVal for $v_name {\r\n const VAL: i64 = $val as i64;\r\n }\r\n\r\n type $name = ModBase<$v_name>;\r\n };\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "number theory"], "code_uid": "53ee782abff369180eca78644b2ddb35", "src_uid": "6ca310cb0b6fc4e62e63a731cd55aead", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::{TryInto, TryFrom}, marker::PhantomData};\n\nconst IO_BUF_SIZE: usize = 1 << 16;\ntype Input = Scanner;\ntype Output = BufWriter;\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\n\n#[repr(transparent)] struct Unsync(T);\nunsafe impl Sync for Unsync {}\n \ntype BadLazy = Unsync>>;\nimpl BadLazy {\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\n}\n \nstatic INPUT: BadLazy = BadLazy::new();\nstatic OUTPUT: BadLazy = BadLazy::new();\n \nfn inp R, R>(f: F) -> R {\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\n}\nfn out R, R>(f: F) -> R {\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\n}\n\nmacro_rules! read {\n () => { read() };\n ($t: ty) => { read::<$t>() };\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\n}\nmacro_rules! println { \n () => { out(|x| { let _ = writeln!(x); }) };\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\n}\nmacro_rules! print { \n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\n}\n\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\n\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\nfn read_byte() -> u8 { inp(|x| x.byte()) }\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\n\nstruct Scanner {\n src: R,\n _buf: Vec,\n _pt: usize, // pointer\n _rd: usize, // bytes read\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(src: R) -> Scanner {\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\n }\n \n fn _check_buf(&mut self) {\n if self._pt == self._rd {\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\n self._pt = (self._rd == 0) as usize;\n }\n }\n \n // returns true if end of file\n fn eof(&mut self) -> bool {\n self._check_buf();\n self._rd == 0\n }\n \n // filters \\r, returns \\0 if eof\n fn byte(&mut self) -> u8 {\n loop {\n self._check_buf();\n if self._rd == 0 { return 0; }\n let res = self._buf[self._pt];\n self._pt += 1;\n if res != b'\\r' { return res; }\n }\n }\n\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\n fn bytes(&mut self, n: usize) -> Vec {\n let res = self.bytes_no_skip(n);\n self.byte();\n res\n }\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\n \n fn token_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c <= b' ' {\n if c == b'\\0' { return res; }\n c = self.byte();\n }\n loop {\n res.push(c);\n c = self.byte();\n if c <= b' ' { return res; }\n }\n }\n \n fn line_bytes(&mut self) -> Vec {\n let mut res = Vec::new();\n let mut c = self.byte();\n while c != b'\\n' && c != b'\\0' {\n res.push(c);\n c = self.byte();\n }\n res\n }\n}\n\ntrait JoinToStr { \n fn join_to_str(self, sep: &str) -> String;\n fn concat_to_str(self) -> String;\n}\nimpl> JoinToStr for I { \n fn join_to_str(mut self, sep: &str) -> String {\n match self.next() {\n Some(first) => {\n let mut res = first.to_string();\n while let Some(item) = self.next() {\n res.push_str(sep);\n res.push_str(&item.to_string());\n }\n res\n }\n None => { String::new() }\n }\n }\n \n fn concat_to_str(self) -> String {\n let mut res = String::new();\n for item in self { res.push_str(&item.to_string()); }\n res\n }\n}\ntrait AsStr { fn as_str(&self) -> &str; }\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\n\nmacro_rules! veci {\n ($n:expr , $i:ident : $gen:expr) => {{\n let _veci_n = $n;\n let mut _veci_list = Vec::with_capacity(_veci_n);\n for $i in 0.._veci_n {\n _veci_list.push($gen);\n }\n _veci_list\n }};\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\n}\n\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\n if x < y { y - x } else { x - y }\n}\n\ntrait CommonNumExt {\n fn div_ceil(self, b: Self) -> Self;\n fn div_floor(self, b: Self) -> Self;\n fn gcd(self, b: Self) -> Self;\n fn highest_one(self) -> Self;\n fn lowest_one(self) -> Self;\n fn sig_bits(self) -> u32;\n}\n\nmacro_rules! impl_common_num_ext {\n ($($ix:tt = $ux:tt),*) => {\n $(\n impl CommonNumExt for $ux {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { self / b }\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self;\n if a == 0 || b == 0 { return a | b; }\n let shift = (a | b).trailing_zeros();\n a >>= a.trailing_zeros();\n b >>= b.trailing_zeros();\n while a != b {\n if a > b { a -= b; a >>= a.trailing_zeros(); }\n else { b -= a; b >>= b.trailing_zeros(); }\n }\n a << shift\n }\n #[inline] fn highest_one(self) -> Self { \n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \n }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\n }\n\n impl CommonNumExt for $ix {\n fn div_ceil(self, b: Self) -> Self {\n let q = self / b; let r = self % b;\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\n }\n fn div_floor(self, b: Self) -> Self { \n let q = self / b; let r = self % b;\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\n }\n fn gcd(self, b: Self) -> Self {\n fn w_abs(x: $ix) -> $ux { (if x.is_negative() { x.wrapping_neg() } else { x }) as _ }\n w_abs(self).gcd(w_abs(b)) as _\n }\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\n }\n )*\n }\n}\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\n\ntrait ChMaxMin {\n fn chmax(&mut self, v: T) -> bool;\n fn chmin(&mut self, v: T) -> bool;\n}\nimpl ChMaxMin for Option {\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\n}\nimpl ChMaxMin for T {\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\n}\n\n// * end commons * //\n\t\n\n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n\t\n for _case_num in 1..=num_cases {\n let p1 = read!(usize);\n\t\tlet t1 = read!(i64);\n\t\tlet p2 = read!(usize);\n\t\tlet t2 = read!(i64);\n\t\tlet h = read!(usize);\n\t\tlet s = read!(usize);\n\t\t\n\t\tlet x1 = p1 - s;\n\t\tlet x2 = p2 - s;\n\t\tlet x3 = p1 + p2 - s;\n\t\t\n\t\tlet inf = i64::MAX;\n\t\tlet mut ans = inf;\n\t\tlet mut dp = vec![inf; h+1];\n\t\tdp[0] = 0;\n\t\t\n\t\tfor i in 0..h { if dp[i] != inf {\n\t\t\tlet t = dp[i];\n\t\t\t\n\t\t\tlet mut k1 = 0;\n\t\t\tlet mut k2 = 0;\n\t\t\tlet mut dm = 0;\n\t\t\tloop {\n\t\t\t\tif i + dm >= h {\n\t\t\t\t\tans.chmin(t + max(k1 * t1, k2 * t2));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdp[min(h, i+dm+x3)].chmin(t + max((k1+1) * t1, (k2+1) * t2));\n\t\t\t\t\n\t\t\t\tif (k1 + 1) * t1 < (k2 + 1) * t2 {\n\t\t\t\t\tk1 += 1;\n\t\t\t\t\tdm += x1;\n\t\t\t\t} else {\n\t\t\t\t\tk2 += 1;\n\t\t\t\t\tdm += x2;\n\t\t\t\t}\n\t\t\t}\n\t\t}}\n\t\t\n\t\t//println!(\"{:?}\", &dp);\n\t\t\n\t\tans.chmin(dp[h]);\n\t\tprintln!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["dp", "binary search"], "code_uid": "b70b8e109eb454e6dcc6fec0cd1922a3", "src_uid": "ca9d48e48e69b931236907a9ac262433", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "fn run() {\r\n input! {\r\n a: (usize, i64),\r\n b: (usize, i64),\r\n e: (usize, usize),\r\n }\r\n let inf = std::i64::MAX / 2;\r\n let mut memo = vec![inf; e.0 + 1];\r\n for i in 0..=e.0 {\r\n for j in 0..=e.0 {\r\n let d = e.0.min(i * (a.0 - e.1) + j * (b.0 - e.1));\r\n let t = (i as i64 * a.1).max(j as i64 * b.1);\r\n memo[d] = memo[d].min(t);\r\n }\r\n }\r\n for i in 1..=e.0 {\r\n for j in 1..=e.0 {\r\n let t = (i as i64 * a.1).max(j as i64 * b.1);\r\n let d = (i - 1) * (a.0 - e.1) + (j - 1) * (b.0 - e.1) + a.0 + b.0 - e.1;\r\n for k in 0..=(e.0 / d + 1) {\r\n let d = (k * d).min(e.0);\r\n memo[d] = memo[d].min(t * k as i64);\r\n }\r\n }\r\n }\r\n for i in (0..e.0).rev() {\r\n memo[i] = memo[i].min(memo[i + 1]);\r\n }\r\n for i in 1..=e.0 {\r\n let t = memo[i];\r\n for j in (i + 1)..=e.0 {\r\n memo[j] = memo[j].min(memo[j - i] + t);\r\n }\r\n }\r\n println!(\"{}\", memo[e.0]);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\n#[macro_export]\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\n#[macro_export]\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\n#[macro_export]\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n", "lang_cluster": "Rust", "tags": ["dp", "binary search"], "code_uid": "94595bd8089d94285aa10065258831f2", "src_uid": "ca9d48e48e69b931236907a9ac262433", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "mod cp {\n #[allow(dead_code)]\n pub mod io {\n use std::io::prelude::*;\n pub trait Parseable: Sized {\n fn parse(p: &mut Parser) -> Option;\n }\n pub trait ParseableScalar: std::str::FromStr + Sized {}\n impl Parseable for T {\n fn parse(p: &mut Parser) -> Option {\n p.parse_scalar()\n }\n }\n macro_rules ! declare_parseable_scalar { ($ ($ x : ty) ,*) => { $ (impl ParseableScalar for $ x { }) * } }\n declare_parseable_scalar!(\n i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, isize, usize, f32, f64, String\n );\n macro_rules ! impl_parseable_tuple { ($ ($ name : ident) +) => { impl <$ ($ name : Parseable) ,+> Parseable for ($ ($ name ,) +) { fn parse (p : & mut Parser) -> Option < Self > { Some (($ ($ name :: parse (p) ?,) +)) } } } ; }\n impl_parseable_tuple! { A }\n impl_parseable_tuple! { A B }\n impl_parseable_tuple! { A B C }\n impl_parseable_tuple! { A B C D }\n impl_parseable_tuple! { A B C D E }\n impl_parseable_tuple! { A B C D E F }\n impl_parseable_tuple! { A B C D E F G }\n impl_parseable_tuple! { A B C D E F G H }\n impl_parseable_tuple! { A B C D E F G H I }\n impl_parseable_tuple! { A B C D E F G H I J }\n impl_parseable_tuple! { A B C D E F G H I J K }\n impl_parseable_tuple! { A B C D E F G H I J K L }\n impl Parseable for [T; N] {\n fn parse(p: &mut Parser) -> Option {\n let x = [0; N].map(|_| T::parse(p));\n if x.iter().all(Option::<_>::is_some) {\n Some(x.map(Option::<_>::unwrap))\n } else {\n None\n }\n }\n }\n pub fn stdin_to_string() -> String {\n let mut content = String::new();\n let stdin = std::io::stdin();\n let mut rd = stdin.lock();\n rd.read_to_string(&mut content).unwrap();\n content\n }\n pub struct Parser<'a> {\n tokens: std::str::SplitWhitespace<'a>,\n }\n impl<'a> Parser<'a> {\n pub fn new(text: &'a str) -> Self {\n Self {\n tokens: text.split_whitespace(),\n }\n }\n pub fn parse_scalar(&mut self) -> Option {\n self.next().map(|s| match s.parse() {\n Ok(x) => x,\n Err(_) => panic!(\"cannot parse {:?}\", s),\n })\n }\n pub fn read_or_eof(&mut self) -> Option {\n T::parse(self)\n }\n pub fn read(&mut self) -> T {\n self.read_or_eof::().expect(\"unexpected end-of-file\")\n }\n }\n impl<'a> Iterator for Parser<'a> {\n type Item = &'a str;\n fn next(&mut self) -> Option<&'a str> {\n self.tokens.next()\n }\n }\n pub struct ParserWrapper<'a, 'b, T> {\n p: &'b mut Parser<'a>,\n _marker: std::marker::PhantomData,\n }\n impl<'a, 'b, T: Parseable> Iterator for ParserWrapper<'a, 'b, T> {\n type Item = T;\n fn next(&mut self) -> Option {\n self.p.read_or_eof()\n }\n }\n impl<'a> Parser<'a> {\n pub fn iter<'b, T>(&'b mut self) -> ParserWrapper<'a, 'b, T> {\n ParserWrapper::<'a, 'b, T> {\n p: self,\n _marker: std::marker::PhantomData {},\n }\n }\n }\n }\n}\nuse cp::io;\nuse std::cmp::{max, min};\nfn main() {\n let content = io::stdin_to_string();\n let mut rd = io::Parser::new(&content);\n let (p1, t1): (i64, i64) = rd.read();\n let (p2, t2): (i64, i64) = rd.read();\n let (h, s): (i64, i64) = rd.read();\n let mut f: Vec = (0..=h)\n .map(|y| {\n (0..=y)\n .map(|x1| max(x1 * t1, (y - x1 * (p1 - s) + p2 - s - 1) / (p2 - s) * t2))\n .min()\n .unwrap()\n })\n .collect();\n let t: Vec = (0..=h)\n .map(|y| {\n (1..=y)\n .map(|x1| {\n [\n x1 * t1,\n (y - s - x1 * (p1 - s) + p2 - s - 1) / (p2 - s) * t2,\n t2,\n ]\n .iter()\n .copied()\n .max()\n .unwrap()\n })\n .min()\n .unwrap_or(i64::MIN)\n })\n .collect();\n for i in 1..=(h as usize) {\n for j in 1..=i {\n f[i] = min(f[i], f[i - j] + t[j]);\n }\n }\n println!(\"{}\", f[h as usize]);\n}\n", "lang_cluster": "Rust", "tags": ["dp", "binary search"], "code_uid": "f2f75d3923206496b7b88cf7b60dceac", "src_uid": "ca9d48e48e69b931236907a9ac262433", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::arch::x86_64::_mm256_undefined_si256;\nuse std::cell::RefCell;\nuse std::cmp::Ordering;\nuse std::collections::*;\nuse std::error::Error;\nuse std::fmt::write;\nuse std::hash::Hash;\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::stderr;\nuse std::io::StdinLock;\nuse std::io::StdoutLock;\nuse std::io::Write;\nuse std::io::{stdin, stdout, BufRead, BufWriter};\nuse std::ops::*;\nuse std::process::id;\n\nmacro_rules! fprintvec {\n ($dst:expr, $arg:expr) => {{\n writeln!(\n $dst,\n \"{}\",\n $arg.iter()\n .map(|x| format!(\"{} \", x))\n .collect::>()\n .join(\"\"),\n )\n .ok();\n }};\n}\n\npub struct Scanner {\n reader: B,\n buf_str: Vec,\n buf_iter: std::str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_whitespace(),\n }\n }\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace())\n }\n }\n }\n\n pub fn next_split(&mut self) -> Vec {\n loop {\n let mut v = Vec::new();\n while let Some(token) = self.buf_iter.next() {\n v.push(token.parse().ok().expect(\"Failed parse\"));\n }\n if v.len() > 0 {\n return v;\n }\n\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_whitespace())\n }\n }\n }\n}\n\n// #[derive(Debug, Clone, Default, Copy)]\nfn lcm(first: usize, second: usize) -> usize {\n first * second / gcd(first, second)\n}\n\nfn gcd(first: usize, second: usize) -> usize {\n let mut max = first;\n let mut min = second;\n if min > max {\n let val = max;\n max = min;\n min = val;\n }\n\n loop {\n let res = max % min;\n if res == 0 {\n return min;\n }\n\n max = min;\n min = res;\n }\n}\n\nfn main() -> Result<(), Box> {\n let stdout = io::stdout();\n let lock = stdout.lock();\n let stdin = io::stdin();\n let mut ow = io::BufWriter::new(lock);\n let mut scan = Scanner::new(stdin.lock());\n // let n_tests = scan.next::();\n let n_tests = 1;\n for _t_num in 1..=n_tests {\n let p1 = scan.next::();\n let t1 = scan.next::();\n let p2 = scan.next::();\n let t2 = scan.next::();\n let h = scan.next::();\n let s = scan.next::();\n\n let mut dp = vec![i64::MAX; h as usize + 1];\n let mut best = i64::MAX;\n dp[0] = 0;\n for th in (0..h) {\n let st = dp[th as usize];\n if st == i64::MAX {\n continue;\n }\n for (src, other) in [((p1, t1), (p2, t2)), ((p2, t2), (p1, t1))] {\n //fire 1 continously\n let d = src.0 - s;\n if d == 0 {\n continue;\n }\n let d2 = other.0 - s;\n for i in 0..=h {\n let c2 = (i * src.1) / other.1;\n let td2 = c2 * d2;\n let td1 = d * i;\n if th + td1 + td2 >= h {\n best = std::cmp::min(best, st + i * src.1);\n // println!(\"{} {} {} {} {:?}\", best, st, i, c2, src);\n break;\n }\n let dd = (src.0 + other.0) - s;\n let nt = std::cmp::max((i + 1) * src.1, (c2 + 1) * other.1) + st;\n if th + td1 + td2 + dd >= h {\n best = std::cmp::min(best, nt);\n // println!(\"b{} {} {} {} {:?}\", best, st, i, c2, src);\n } else {\n dp[(th + td1 + td2 + dd) as usize] =\n std::cmp::min(nt, dp[(th + td1 + td2 + dd) as usize]);\n }\n }\n }\n }\n // writeln!(ow, \"{:?}\", dp[0]);\n writeln!(ow, \"{:?}\", best);\n // writeln!(ow, \"{}\", bops);\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["dp", "binary search"], "code_uid": "41a2c06686e0638198c19245e7920c5a", "src_uid": "ca9d48e48e69b931236907a9ac262433", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// This file is a \"Hello, world!\" in Rust language for wandbox.\nuse std::io;\n\nfn main()\n{\n let stdin = io::stdin();\n let mut buffer = String::new();\n stdin.read_line(&mut buffer).unwrap();\n buffer = buffer.trim().to_string();\n let mut n = buffer.parse::().unwrap();\n let mut cnt = 0;\n while n > 0 {\n n >>= 1;\n cnt += 1;\n }\n \n println!(\"{}\", cnt);\n}\n\n// Rust language references:\n// https://www.rust-lang.org/\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms"], "code_uid": "cb566ba7aba4eea928c30d85a4905207", "src_uid": "95cb79597443461085e62d974d67a9a0", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() -> () {\n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n handle.read_to_string(&mut buffer).expect(\"stdin\");\n\n let arr : Vec<_> = buffer.split_whitespace().map(|x| x.parse::().unwrap() ).collect();\n\n let mut n = *arr.iter().nth(0).unwrap();\n\n let mut curr = 1;\n let mut total = 0;\n let mut count = 0;\n \n while total < n {\n count += 1;\n total += curr;\n curr = curr * 2;\n }\n\n println!(\"{}\", count );\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms"], "code_uid": "d9bee1001ec1e027891a4a4ca6aaa6d8", "src_uid": "95cb79597443461085e62d974d67a9a0", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//================================================================================\n#[allow(unused_imports)] use std::cmp::{max, min, Ordering};\n#[allow(unused_imports)] use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)] use std::iter::FromIterator;\nuse std::io::Write;\nstatic mut GLOBAL_STDIN: *mut std::io::Stdin = 0usize as _;\nstatic mut GLOBAL_STDINLOCK: *mut std::io::StdinLock<'static> = 0usize as _;\nstatic mut GLOBAL_STDOUT: *mut std::io::Stdout = 0usize as _;\nstatic mut GLOBAL_STDOUTLOCK: *mut std::io::StdoutLock<'static> = 0usize as _;\nconst BUF_SIZE: usize = 1024*1024;\nstatic mut GLOBAL_INPUT_BUF: *mut u8 = 0usize as _;\nstatic mut GLOBAL_INPUT_PTR: *const u8 = 0usize as _;\nstatic mut GLOBAL_INPUT_END: *const u8 = 0usize as _;\nfn init() {\n unsafe {\n use std::boxed::Box;\n GLOBAL_STDIN = Box::into_raw(Box::new(std::io::stdin()));\n GLOBAL_STDINLOCK = Box::into_raw(Box::new(GLOBAL_STDIN.as_ref().unwrap().lock()));\n GLOBAL_STDOUT = Box::into_raw(Box::new(std::io::stdout()));\n GLOBAL_STDOUTLOCK = Box::into_raw(Box::new(GLOBAL_STDOUT.as_mut().unwrap().lock()));\n let buf = Box::<[u8]>::into_raw(vec![0u8; BUF_SIZE].into_boxed_slice());\n GLOBAL_INPUT_BUF = (*buf).as_mut_ptr();\n GLOBAL_INPUT_PTR = GLOBAL_INPUT_BUF;\n GLOBAL_INPUT_END = GLOBAL_INPUT_BUF;\n }\n}\nfn peek() -> u8 { unsafe {\n use std::io::Read;\n if GLOBAL_INPUT_PTR == GLOBAL_INPUT_END {\n let n = GLOBAL_STDINLOCK.as_mut().unwrap().read(std::slice::from_raw_parts_mut(GLOBAL_INPUT_BUF, BUF_SIZE)).expect(\"I/O error\");\n GLOBAL_INPUT_PTR = GLOBAL_INPUT_BUF;\n GLOBAL_INPUT_END = GLOBAL_INPUT_PTR.offset(n as isize);\n }\n *GLOBAL_INPUT_PTR\n} }\nfn getchar() -> u8 { let c = peek(); unsafe { GLOBAL_INPUT_PTR = GLOBAL_INPUT_PTR.offset(1); } c }\nfn ungetc() { unsafe { GLOBAL_INPUT_PTR = GLOBAL_INPUT_PTR.offset(-1); } }\nfn skip_whitespaces() { loop { match getchar() as char { ' ' | '\\t' | '\\n' | '\\r' => { }, _ => { ungetc(); break; } } } }\ntrait FastRead { fn read() -> Self; }\nmacro_rules! read_int_impl {\n ( $signed:expr, $($T:ident,)* ) => {\n $(impl FastRead for $T {\n fn read() -> $T {\n skip_whitespaces(); let is_negative = if $signed && peek() == '-' as u8 { getchar(); true } else { false }; let mut val: $T = 0;\n loop {\n let c = getchar(); let d = c.wrapping_sub('0' as u8);\n if d >= 10 { match c as char {\n ' ' | '\\t' | '\\n' | '\\r' => { ungetc(); return if is_negative { 0-val } else { val }; },\n _ => panic!(\"invalid input character: `{}' (code: {})\", c as char, c),\n }}\n val = 10*val + (d as $T);\n }\n }\n })*\n };\n}\nmacro_rules! read_tuple_impl {\n ( ) => ();\n ( $a:ident, $($name:ident,)* ) => {\n impl<$a:FastRead, $($name:FastRead),*> FastRead for ($a, $($name,)*) { fn read() -> Self { ( $a::read(), $($name::read()),* ) } }\n read_tuple_impl!($($name,)*);\n }\n}\nmacro_rules! snd_arg_impl { ($a:expr; $e:expr) => { $e }; }\nmacro_rules! read_array_impl {\n () => {};\n ($len:expr, $($lens:expr,)*) => {\n impl FastRead for [T; $len] { fn read() -> Self { [ $(snd_arg_impl!($lens; read::())),* ] } }\n read_array_impl!($($lens,)*);\n };\n}\nunsafe fn extend_vec(v: &mut Vec, first: *const u8, last: *const u8) {\n let len = usize::wrapping_sub(last as _, first as _);\n v.extend_from_slice(&std::slice::from_raw_parts(first, len));\n}\nmacro_rules! read_string_inplace {\n ($func:ident, $($pattern:pat)|+) => {\n #[allow(unused)] fn $func(s: &mut String) -> bool {\n skip_whitespaces();\n unsafe { let mut ptr = GLOBAL_INPUT_PTR; let end = GLOBAL_INPUT_END; let v = s.as_mut_vec(); v.clear();\n loop {\n if ptr == end { extend_vec(v, GLOBAL_INPUT_PTR, end); GLOBAL_INPUT_PTR = GLOBAL_INPUT_END; peek(); ptr = GLOBAL_INPUT_PTR; }\n match *ptr as char {\n $($pattern)|+ => { extend_vec(v, GLOBAL_INPUT_PTR, ptr); GLOBAL_INPUT_PTR = ptr; return v.is_empty(); }\n _ => { ptr = ptr.offset(1); }\n }\n }\n }\n }\n };\n}\nread_string_inplace!(getword, ' ' | '\\t' | '\\n' | '\\r');\nread_string_inplace!(getline, '\\n');\n#[allow(unused)] fn read_line() -> String { let mut s = String::new(); getline(&mut s); s }\nimpl FastRead for String { fn read() -> String { let mut s = String::new(); getword(&mut s); s } }\nimpl FastRead for char { fn read() -> char { skip_whitespaces(); getchar() as char } }\nread_int_impl!(false, u8, u16, u32, u64, usize,);\nread_int_impl!(true, i8, i16, i32, i64, isize,);\nread_tuple_impl!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,);\nread_array_impl!(12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,);\n#[allow(dead_code)] fn read() -> T { T::read() }\n#[allow(unused_macros)] macro_rules! print { ($($arg:tt)*) => { write! (unsafe { GLOBAL_STDOUTLOCK.as_mut().unwrap() }, $($arg)*).unwrap() } }\n#[allow(unused_macros)] macro_rules! println { ($($arg:tt)*) => { writeln!(unsafe { GLOBAL_STDOUTLOCK.as_mut().unwrap() }, $($arg)*).unwrap() } }\n#[allow(dead_code)] fn read_vec(n: usize) -> Vec { let mut v = Vec::with_capacity(n); for _ in 0..n { v.push(read()); } v }\n#[allow(dead_code)] fn print_iter, T: std::fmt::Display>(iter: I) { let mut iter = iter; if let Some(x) = iter.next() { print!(\"{}\", x); for x in iter { print!(\" {}\", x); } } println!(\"\"); }\n#[allow(dead_code)] fn print_vec(v: &Vec) { print_iter(v.iter()); }\n#[allow(unused_macros)] macro_rules! debug { ($a:expr, $($b:expr),*) => (if cfg!(debug_assertions) { println!(concat!(\"DEBUG: \", stringify!($a), \" = {:?}\", $(\", \", stringify!($b), \" = {:?}\"),*), $a, $($b),*); } ) }\n//================================================================================\n\nfn main() {\n init();\n let n: u64 = read();\n let mut k=1u64;\n while (1u64< {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let count = readln!(i32);\n let votes = readvec!(i32);\n let votes_max = *votes.iter().max().unwrap();\n let votes_sum : i32 = votes.iter().sum();\n\n println!(\"{}\", max(votes_max, 2 * votes_sum / count + 1));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e3344d397c269939a21bfe372eef5e88", "src_uid": "d215b3541d6d728ad01b166aae64faa2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_variables)]\n#![allow(unused_must_use)]\n#![allow(unused_imports)]\n#![allow(non_snake_case)]\n#![allow(dead_code)]\n\nuse std::u64;\nuse std::io;\nuse std::cmp;\nuse std::io::prelude::*;\nuse std::fs::File;\nuse std::collections::HashSet;\n\nuse std::str::FromStr;\n\nfn solve(sum: i64, max: i64, n: i64) -> i64 {\n let mut ans = 2 * sum / n;\n while 2 * sum >= ans * n {\n ans += 1;\n }\n\n cmp::max(max, ans)\n}\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let stderr = io::stderr();\n\n //let r = &mut io::BufReader::new(File::open(\"input.txt\").unwrap()).lines();\n let r = &mut io::BufReader::new(stdin.lock()).lines();\n let w = &mut io::BufWriter::new(stdout.lock());\n let e = &mut io::BufWriter::new(stderr.lock());\n\n let n: usize = read_var(r);\n let a: Vec = read_vec(r); \n let mut sum: i64 = 0;\n let mut max: i64 = 0;\n for ai in a.into_iter() {\n sum += ai;\n max = cmp::max(max, ai);\n }\n\n // writeln!(e, \"sum: {}, max: {}\", sum, max);\n writeln!(w, \"{}\", solve(sum, max, n as i64));\n}\n\nfn to_vec(res: io::Result) -> Vec {\n res.unwrap().split(' ').map(|x| x.trim().parse().ok().unwrap()).collect()\n}\n\nfn read_vec(r: &mut io::Lines) -> Vec {\n to_vec(r.next().unwrap())\n}\n\nfn read_var(r: &mut io::Lines) -> T {\n r.next().unwrap().unwrap().trim().parse().ok().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "c6ffdca8cb763d7271b1e1989d7fb493", "src_uid": "d215b3541d6d728ad01b166aae64faa2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io::prelude::*;\nuse std::io;\n\nfn main() {\n let sin = io::stdin();\n let mut f = sin.lock();\n let mut buf = String::new();\n f.read_line(&mut buf).unwrap();\n let n: usize = buf.trim().parse().unwrap();\n buf = \"\".to_string();\n f.read_line(&mut buf).unwrap();\n let a: Vec = buf.split_whitespace().map(|s| s.parse().unwrap()).collect();\n let mut mx: usize = a[0];\n let mut sum: usize = 0;\n for p in a.iter() {\n sum += *p;\n if *p > mx {\n mx = *p;\n }\n }\n\n let mut k = mx;\n loop {\n let tot = (k * n) - sum;\n if tot > sum {\n break;\n }\n k += 1;\n }\n\n println!(\"{}\", k);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e3a4578207b14cab51623ee3dbbb671b", "src_uid": "d215b3541d6d728ad01b166aae64faa2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn max(a: i32, b: i32) -> i32\n{\n if (a > b) {a} else {b}\n}\n\nfn main()\n{\n let n: i32;\n let mut s = String::new();\n std::io::stdin().read_line(&mut s);\n n = s.trim().parse().unwrap();\n s = String::new();\n std::io::stdin().read_line(&mut s);\n let a: Vec<&str> = s.trim().split(\" \").collect();\n let mut s = 0;\n let mut mx = 0;\n for i in a\n {\n let c = i.to_string().parse::().unwrap();\n s += c;\n mx = max(mx, c);\n }\n let ans = (2 * s + 1) / n + if (2 * s + 1) % n == 0 {0} else {1};\n println!(\"{}\", max(mx, ans));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "af5394ec7d564a877eee87428cbb942d", "src_uid": "d215b3541d6d728ad01b166aae64faa2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let mut a = std::collections::HashMap::::new();\n for _ in 0..n {\n let x = input.i();\n let k = 1 + if let Some(&k) = a.get(&x) { k } else { 0 };\n a.insert(x, k);\n }\n let sol = a.into_iter().map(|(_,k)| k).max().unwrap();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "705717efa145d25413d359594127e31a", "src_uid": "f30329023e84b4c50b1b118dc98ae73c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min,Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n readln!();\n let mut s = readvec!(i32);\n s.sort();\n let gg = String::new();\n let mut res = vec![];\n let mut i = 0;\n while i < s.len() {\n let fr = i;\n while i < s.len() && s[i] == s[fr] {\n i+=1;\n }\n res.push(i-fr);\n }\n println!(\"{:?}\",res.iter().max().unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "06bd65f8aa776ddd69f53e61cbf932b4", "src_uid": "f30329023e84b4c50b1b118dc98ae73c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let mut arr = [0usize; 101];\n let mut res = 0;\n for _ in 0..n {\n let current: usize = scan.next();\n arr[current] += 1;\n res = res.max(arr[current]);\n }\n println!(\"{}\", res);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "08121f51adadd261317a82ef12f635a3", "src_uid": "f30329023e84b4c50b1b118dc98ae73c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n\n let amount = input.trim().parse::().expect(\"AMOUNT::parse to usize failed\");\n input.clear();\n\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n let mut input = input.trim().split(' ');\n\n let mut vec = vec![i32::default();100];\n\n for _i in 0..amount {\n let index = input.next().unwrap().parse::().unwrap();\n vec[index - 1] += 1;\n }\n\n let mut max = i32::default();\n for item in vec.iter() {\n if *item > max {\n max = *item;\n }\n\n }\n\n println!(\"{}\", max);\n\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "820b583bb09fee54768dcb56c16d3450", "src_uid": "f30329023e84b4c50b1b118dc98ae73c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n if self.f[crt] { return; }\n self.c += 1;\n self.f[crt] = true;\n self.v.push(crt);\n self.vc[crt] = self.c;\n self.u[crt] = self.v.len()-1;\n for i in 0..self.e[crt].len() {\n self.dfs(self.e[crt][i]);\n }\n //debug!(crt, self.c, self.vc[crt]);\n self.vc[crt] = self.c - self.vc[crt];\n }\n}\n\nfn main() {\n //let t:usize = read();\n //'outer: for _ in 0..t {\n let n:usize = read();\n let a:Vec = (0..n).map(|_| read()).collect();\n\n let mut map = HashMap::new();\n let mut ans = 0;\n for e in a {\n let cnt = map.entry(e).or_insert(0);\n *cnt += 1;\n ans = max(*cnt, ans);\n }\n\n println!(\"{}\", ans);\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "73dcbe0292b75c665054ce9cc873cbfb", "src_uid": "f30329023e84b4c50b1b118dc98ae73c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut v = String::new();\n\n io::stdin().read_line(&mut v).expect(\"read error\");\n\n let v = v.split_whitespace()\n .map(|x| x.parse::().expect(\"parse error\"))\n .collect::>();\n\n let n = v[0];\n\n let x = v[1];\n\n let mut ans: u128 = 0;\n\n for i in 1..=n {\n if x % i == 0 && x <= i * n {\n ans += 1;\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "e08d7de911963ec5ac543ef1def0beb1", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nfn main() {\n let (n, x) = R!(usize, usize);\n println!(\"{}\", (1..(n+1)).filter(|i| x % i == 0 && x / i <= n).count());\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "51383d4cb6a275605610d768e3d82e83", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n,x) = readln!(i64,i64);\n let mut res = 0;\n for i in 1..(n+1) {\n if x%i == 0 && x/i <= n{\n res += 1;\n }\n }\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "7ac4dca07c29e42bc54016cfeeba403c", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(non_snake_case, unused_imports, deprecated, dead_code)]\n\n// Input macros\nmacro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect() }; input_inner!{next, $($r)*} }; }\nmacro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => { let mut $var = read_value!($next, $t); input_inner!{$next $($r)*} }; }\nmacro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, [ $t:tt ]) => { { let len = read_value!($next, usize); (0..len).map(|_| read_value!($next, $t)).collect::>() } }; ($next:expr, chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, bytes) => { read_value!($next, String).into_bytes() }; ($next:expr, usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect(\"Parse error\") }; }\n\n// Module\nuse std::cmp::{min,max};\nuse std::collections::{VecDeque,HashSet,HashMap,BinaryHeap};\n// Module for v1.15.1\nuse std::ascii::AsciiExt; // deprecated since 1.26.0: use inherent method instead\n\n// Functions\n\n// Main\nfn main() {\n\n input! {\n N: usize,\n X: usize\n }\n\n let mut ans = 0;\n for i in 1..N+1{\n if X%i==0 && X/i<=N {\n ans += 1;\n }\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "29ee3e7545fe86c17a64e1a8c319c8c5", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Vicfred\n// https://codeforces.com/problemset/problem/577/A\nuse std::io;\n\nfn main() {\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let words: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let n = words[0];\n let x = words[1];\n\n let limit: i64 = f64::sqrt(x as f64) as i64;\n\n let mut ans = 0;\n\n for d in 1..=limit {\n if x%d == 0 && d <= n && x/d <= n {\n ans += 1;\n }\n }\n\n if x != 1 {\n ans *= 2;\n }\n\n if limit*limit == x && x != 1 && ans > 0 {\n ans -= 1;\n }\n\n println!(\"{}\", ans);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "656b8865e7d67100d5c98a48ccff30aa", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let x: usize = scan.next();\n let mut result: usize = 0;\n for i in 1..=n {\n if x/i <= n && x%i == 0 { result+=1; }\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "72bff79dc2db94bbd9f6df94a4cabd7c", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Pair = (u32, u32);\nfn input_pair() -> Pair {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let buf: Vec = buf\n .trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect();\n (buf[0], buf[1])\n}\n\nfn main() {\n let (n, x) = input_pair();\n let mut occurance_count = 0;\n\n if n == 1 {\n if x == 1 {\n println!(\"1\");\n } else {\n println!(\"0\");\n }\n } else if n == 2 {\n if x == 1 || x == 4 {\n println!(\"1\");\n } else if x == 2 {\n println!(\"2\");\n } else {\n println!(\"0\");\n }\n } else if x == 1 {\n println!(\"1\");\n } else {\n for i in 2..=n {\n if x % i == 0 && x / i <= n {\n if x == i {\n occurance_count += 2;\n } else {\n occurance_count += 1;\n }\n }\n }\n println!(\"{}\", occurance_count);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "64e5222c1b746fff05394095373438c4", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader {\n it : std::vec::IntoIter,\n}\n#[allow(dead_code)]\nimpl WordReader {\n fn new(mut reader: T) -> WordReader {\n let mut s = String::new();\n reader.read_to_string(&mut s).unwrap();\n WordReader {\n it : s.split_ascii_whitespace().map(String::from)\n .collect::>().into_iter()\n }\n }\n fn from_stdin() -> WordReader {\n WordReader::new(std::io::stdin())\n }\n fn s(&mut self) -> String {\n self.it.next().unwrap()\n }\n fn ab(&mut self) -> Vec {\n self.it.next().unwrap().into_bytes()\n }\n fn i(&mut self) -> i32 {\n self.it.next().unwrap().parse().unwrap()\n }\n fn ai(&mut self, n: usize) -> Vec {\n let mut a = Vec::with_capacity(n);\n for _ in 0..n { a.push(self.i()); }\n a\n }\n}\n\nfn main() {\n let mut input = WordReader::from_stdin();\n let n = input.i();\n let x = input.i();\n let sol = (1..(n+1)).filter(|a| x % a == 0 && x / a <= n).count();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "93c9231018a2fc848a69427106fef8ac", "src_uid": "c4b139eadca94201596f1305b2f76496", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\n/// min{x | x * (x + 1) / 2 >= v }\nfn calc(v: i64) -> i64 {\n assert! (v > 0);\n let piv = (2. * v as f64).sqrt() as i64;\n for k in max(piv - 10, 0) .. piv + 10 {\n if k * (k + 1) >= 2 * v {\n return k;\n }\n }\n panic!();\n}\n\nfn solve() {\n let n: i64 = get();\n let m: i64 = get();\n if n <= m {\n println!(\"{}\", n);\n return;\n }\n println!(\"{}\", m + calc(n - m));\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "binary search"], "code_uid": "fc2852b09d8e43d3f0de7427b6234596", "src_uid": "3b585ea852ffc41034ef6804b6aebbd8", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec(s: String) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n s.split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let (n, m): (u64, u64) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n if n <= m {\n println!(\"{}\", n);\n return;\n }\n\n let n_max = 2_000_000_000 + m;\n\n let mut lower_bound: u64 = m;\n let mut upper_bound: u64 = n_max;\n\n let check = |k| {\n (k - m) * (k - m + 1) / 2 >= n - m\n };\n\n while upper_bound - lower_bound != 1 {\n let middle = (lower_bound + upper_bound) / 2;\n if check(middle) {\n upper_bound = middle;\n } else {\n lower_bound = middle;\n }\n }\n\n let ans = upper_bound;\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "binary search"], "code_uid": "a67bde3c47e7a1835bd2229155d18233", "src_uid": "3b585ea852ffc41034ef6804b6aebbd8", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nstatic ALPHABET: &str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nfn find_number_of_ops(length_of_string: usize, s: String) -> usize {\n let mut number_of_ops = vec![];\n for i in 0..length_of_string-3 {\n let substring = &s[i..i+4];\n let mut ops = 0;\n for (index_of_letter_in_substring, letter) in substring.chars().enumerate() {\n if letter != \"ACTG\".chars().nth(index_of_letter_in_substring).unwrap() {\n // number of operations is not zero for this letter\n let position_of_letter_in_alphabet = ALPHABET.find(letter).unwrap();\n let position_of_target_in_alphabet = ALPHABET.find(\"ACTG\".chars().nth(index_of_letter_in_substring).unwrap()).unwrap();\n let x: usize = (position_of_letter_in_alphabet as isize - position_of_target_in_alphabet as isize).abs() as usize;\n let y: usize = 26 - (position_of_target_in_alphabet as isize - position_of_letter_in_alphabet as isize).abs() as usize;\n ops += if x < y {x} else {y};\n }\n if index_of_letter_in_substring == 3 {\n number_of_ops.push(ops);\n }\n }\n }\n let mut minimum_ops = number_of_ops[0];\n for ops in number_of_ops.iter() {\n if ops < &minimum_ops {\n minimum_ops = *ops;\n }\n }\n minimum_ops\n}\n\nfn main() {\n let mut length_of_string = String::new();\n io::stdin().read_line(&mut length_of_string).unwrap();\n let length_of_string: usize = length_of_string.trim().parse().unwrap();\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n println!(\"{}\", find_number_of_ops(length_of_string, s.trim().to_string()));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings"], "code_uid": "f39f652d59f01b294a8351b337bcdfdb", "src_uid": "ee4f88abe4c9fa776abd15c5f3a94543", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nconst MOD: i64 = 1_000_000_007;\n\n/// Refers external ::MOD.\n/// Verified by: https://beta.atcoder.jp/contests/arc099/submissions/2893648\nmod mod_int {\n use ::MOD;\n use std::ops::*;\n #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64 }\n impl ModInt {\n fn check_integrity(self) {\n debug_assert!(self.x >= 0);\n debug_assert!(self.x < MOD);\n }\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt { x: x % MOD } }\n #[allow(dead_code)]\n pub fn mul_fast(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n ModInt { x: self.x * other.x % MOD }\n }\n #[allow(dead_code)]\n pub fn mul_slow(self, other: Self) -> Self {\n // Naive multiplication in order to avoid overflow\n self.check_integrity();\n other.check_integrity();\n let mut sum = ModInt::new(0);\n let mut cur = self;\n let mut e = other.x;\n if self.x < other.x {\n cur = other;\n e = self.x;\n }\n while e > 0 {\n if e % 2 == 1 {\n sum = sum + cur;\n }\n cur = cur + cur;\n e /= 2;\n }\n sum\n }\n pub fn pow(self, mut e: i64) -> Self {\n self.check_integrity();\n debug_assert!(e >= 0);\n let mut sum = ModInt::new(1);\n let mut cur = ModInt::new(self.x);\n while e > 0 {\n if e % 2 != 0 {\n sum = sum * cur;\n }\n cur = cur * cur;\n e /= 2;\n }\n sum\n }\n pub fn inv(self) -> Self { self.pow(MOD - 2) }\n }\n impl Add for ModInt {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x + other.x;\n if sum >= MOD { sum -= MOD; }\n ModInt { x: sum }\n }\n }\n impl Sub for ModInt {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n self.check_integrity();\n other.check_integrity();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += MOD; }\n ModInt { x: sum }\n }\n }\n impl Mul for ModInt {\n type Output = Self;\n fn mul(self, other: Self) -> Self {\n self.mul_fast(other)\n }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n} // mod mod_int\n\nuse mod_int::*;\n\nfn solve() {\n let n: usize = get();\n let s: Vec = get_word().chars().collect();\n let m = s.len();\n let mut rev = vec![vec![0; m + 1]; 2];\n for i in 0 .. m {\n let idx = if s[i] == '(' { 0 } else { 1 };\n let opp = if s[i] == '(' { ')' } else { '(' };\n let mut grow = s[0 .. i].to_vec();\n grow.push(opp);\n let mut aa = 0;\n for j in 0 .. i + 1 {\n if grow[j ..] == s[.. i + 1 - j] {\n aa = i + 1 - j;\n break;\n }\n }\n rev[1 - idx][i] = aa;\n rev[idx][i] = i + 1;\n }\n rev[0][m] = m;\n rev[1][m] = m;\n let mut dp = vec![vec![vec![ModInt::new(0); m + 1]; n + 1]; 2 * n + 1];\n dp[0][0][0] = ModInt::new(1);\n for i in 0 .. 2 * n {\n for j in 0 .. n + 1 {\n for k in 0 .. m + 1 {\n if j < n {\n dp[i + 1][j + 1][rev[0][k]] =\n dp[i + 1][j + 1][rev[0][k]] + dp[i][j][k];\n }\n if j > 0 {\n dp[i + 1][j - 1][rev[1][k]] =\n dp[i + 1][j - 1][rev[1][k]] + dp[i][j][k];\n }\n }\n }\n }\n println!(\"{}\", dp[2 * n][0][m]);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "cdfdef1174f2d238a59107569db00e83", "src_uid": "590a49a7af0eb83376ed911ed488d7e5", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\n/* \nimpl std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n*/\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n pub fn comb(n: u32, k: u32) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n let k = std::cmp::min(k, n - k);\n let mut nu = ModInt::one();\n let mut de = ModInt::one();\n for i in 0..k {\n nu *= ModInt(n - i);\n de *= ModInt(i + 1);\n }\n nu * de.inv()\n }\n}\n\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end ModInt ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n s: chars,\n }\n let len = s.len();\n let mut index = vec![vec![0; len + 1]; 2];\n for i in 0..len {\n if s[i] == '(' {\n index[0][i] = i + 1;\n let mut t = s.clone();\n t[i] = ')';\n for k in (1..=i).rev() {\n if s[0..k] == t[(i + 1 - k)..(i + 1)] {\n index[1][i] = k;\n break;\n }\n }\n } else {\n index[1][i] = i + 1;\n let mut t = s.clone();\n t[i] = '(';\n for k in (1..=i).rev() {\n if s[0..k] == t[(i + 1 - k)..(i + 1)] {\n index[0][i] = k;\n break;\n }\n }\n }\n }\n index[0][len] = len;\n index[1][len] = len;\n let mut dp = vec![vec![ModInt::zero(); n + 1]; len + 1];\n dp[0][0] = ModInt::one();\n for _ in 0..(2 * n) {\n let mut next = vec![vec![ModInt::zero(); n + 1]; len + 1];\n for j in 0..=len {\n for k in 0..=n {\n let v = dp[j][k];\n if k < n {\n next[index[0][j]][k + 1] += v;\n }\n if k > 0 {\n next[index[1][j]][k - 1] += v;\n }\n }\n }\n dp = next;\n }\n let ans = dp[len][0].0;\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "dp"], "code_uid": "20daa57a5f9413f1b36974ebdc1fd536", "src_uid": "590a49a7af0eb83376ed911ed488d7e5", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::mem::swap;\nuse std::str;\n\nfn has_valid_prime_factors(n: i64) -> bool {\n let mut n = n;\n while n % 2 == 0 {\n n /= 2;\n }\n while n % 3 == 0 {\n n /= 3;\n }\n while n % 5 == 0 {\n n /= 5;\n }\n n == 1\n}\n\nfn gcd(a: i64, b: i64) -> i64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn factorize(n: i64) -> Vec<(i64, i64)> {\n let mut n = n;\n let mut p = 2;\n let mut ans = Vec::new();\n while p * p <= n && n > 1 {\n let mut expo = 0;\n while n % p == 0 {\n expo += 1;\n n /= p;\n }\n if expo > 0 {\n ans.push((p, expo));\n }\n p += 1;\n }\n if n > 1 {\n ans.push((n, 1));\n }\n ans\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let mut a: i64 = scan.token();\n let mut b: i64 = scan.token();\n if a > b {\n swap(&mut a, &mut b);\n }\n\n // a and b must be reduced each to its gcd.\n // a should become gcd(a, b) only dividing it by 2, 3 or 5.\n // b should become gcd(a, b) only dividing it by 2, 3 or 5.\n // In other words, a / gcd(a, b) and b / gcd(a, b) must only have 2, 3 or 5 as prime factors.\n let g = gcd(a, b);\n if a == b || (has_valid_prime_factors(a / g) && has_valid_prime_factors(b / g)) {\n let factors_without_gcd = factorize((a / g) * (b / g));\n let ans = factors_without_gcd.iter().fold(0i64, |acc, val| acc + val.1);\n writeln!(out, \"{}\", ans).ok();\n } else {\n writeln!(out, \"-1\").ok();\n }\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "8a03dc948461115dbe5598ae79d29b07", "src_uid": "75a97f4d85d50ea0e1af0d46f7565b49", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn get_order(x: usize, y: usize) -> usize {\n if x == 0 {\n return 0;\n }\n let mut x = x;\n let mut count = 0usize;\n while x % y == 0 {\n x /= y;\n count += 1;\n }\n count\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut a: usize = scan.next();\n let mut b: usize = scan.next();\n let mut result = 0usize;\n let possible: Vec = vec![2, 3, 5];\n for i in possible {\n let ia = get_order(a, i);\n let ib = get_order(b, i);\n let diff = ia.max(ib) - ia.min(ib);\n result += diff;\n\n if ia > ib {\n a /= i.pow(diff as u32);\n } else if ia < ib {\n b /= i.pow(diff as u32);\n }\n }\n if a != b {\n println!(\"-1\");\n } else {\n println!(\"{}\", result);\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "6f92a2a94763d7be9603670c138f2317", "src_uid": "75a97f4d85d50ea0e1af0d46f7565b49", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (mut a, mut b) = readln!(i32,i32);\n let mut res = 0;\n while a>0 && b>0 && !(a==1 && b==1){\n res += 1;\n if a >= b {\n a = max(0,a-2);\n b = min(100,b+1);\n } else {\n a = min(100,a+1);\n b = max(0,b-2);\n }\n }\n println!(\"{}\",res);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp", "implementation"], "code_uid": "a30bda7a452d616875c5635b062a7a26", "src_uid": "ba0f9f5f0ad4786b9274c829be587961", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let mut a = input.i();\n let mut b = input.i();\n let mut sol = 0;\n while a > 0 && b > 0 && a + b > 2 {\n if a < b {\n a += 1;\n b -= 2;\n } else {\n a -= 2;\n b += 1;\n }\n sol += 1;\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp", "implementation"], "code_uid": "637c6b8a601fc006b6a6ca42965a2f62", "src_uid": "ba0f9f5f0ad4786b9274c829be587961", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn minval(a1: usize, a2: usize, depth: usize, table: &mut [[usize; 256]; 256]) -> usize {\n if a1 == 0 || a2 == 0 {\n return depth;\n }\n if table[a1][a2] != 0 {\n return table[a1][a2];\n }\n let mut result = 0usize;\n if a2 >= 2 {\n let val = {\n let a1 = a1 + 1;\n let a2 = a2 - 2;\n minval(a1.max(a2), a1.min(a2), depth + 1, table)\n };\n result = result.max(val);\n }\n if a1 >= 2 {\n let val = {\n let a1 = a1 - 2;\n let a2 = a2 + 1;\n minval(a1.max(a2), a1.min(a2), depth + 1, table)\n };\n result = result.max(val);\n }\n table[a1][a2] = result;\n result\n}\n\nfn _main() {\n let mut table = [[0; 256]; 256];\n let mut scan = Scan::new();\n let a1: usize = scan.next();\n let a2: usize = scan.next();\n let result = minval(a1.max(a2), a1.min(a2), 0, &mut table);\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp", "implementation"], "code_uid": "2f317487a0cf7cafe7b8996f71af0243", "src_uid": "ba0f9f5f0ad4786b9274c829be587961", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn dfs(a: &[u64], k: usize, sup: bool, used: u64, b: &mut Vec) {\n if k == a.len() {\n b.push(used);\n return;\n }\n let y = if !sup {\n a[k]\n } else {\n 6\n };\n for i in 0..=y {\n if used >> i & 1 == 0 {\n dfs(a, k + 1, sup || i < a[k], used | (1 << i), b);\n }\n }\n}\n\nfn run() {\n input! {\n n: u64,\n m: u64,\n }\n let mut a = vec![];\n let mut x = m - 1;\n if x == 0 {\n a.push(0);\n } else {\n while x > 0 {\n a.push(x % 7);\n x /= 7;\n }\n }\n a.reverse();\n let mut b = vec![];\n dfs(&a, 0, false, 0, &mut b);\n let sa = a;\n let mut a = vec![];\n let mut x = n - 1;\n if x == 0 {\n a.push(x);\n } else {\n while x > 0 {\n a.push(x % 7);\n x /= 7;\n }\n }\n if a.len() + sa.len() > 7 {\n println!(\"0\");\n return;\n }\n a.reverse();\n let mut c = vec![];\n dfs(&a, 0, false, 0, &mut c);\n let mut ans = 0;\n for b in b.iter() {\n for c in c.iter() {\n if *b & *c == 0 {\n ans += 1;\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics"], "code_uid": "9b2bfa58ca58b5e84ff2c12e120c0273", "src_uid": "0930c75f57dd88a858ba7bb0f11f1b1c", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::LinkedList;\nuse std::iter::FromIterator;\n\nmacro_rules! read_line {\n ($v:ident) => {\n let mut temp = String::new();\n std::io::stdin().read_line(&mut temp).unwrap();\n let $v = temp;\n };\n (var, $t:ty, $($v:ident), *) => {\n read_line!(input_line);\n let mut iter = parse_token!($t, input_line);\n $(\n let $v = iter.next().unwrap();\n )*\n };\n (vec, $t:ty, $v:ident) => {\n read_line!(input_line);\n let iter = parse_token!($t, input_line);\n let $v: Vec<$t> = iter.collect();\n };\n ($($v:ident; $t:ty), *) => {\n read_line!(input_line);\n let mut iter = input_line.split_whitespace();\n $(\n let $v: $t = iter.next().unwrap().parse().unwrap();\n )*\n };\n}\n\nmacro_rules! parse_token {\n ($t:ty, $e:expr) => {\n $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());\n };\n}\n\nfn trivial_coincide(a_barrier: &LinkedList, b_barrier: &LinkedList) -> bool {\n let iter = a_barrier.iter().zip(b_barrier.iter());\n let mut difference = None;\n for (a, b) in iter {\n match difference {\n Some(diff) => {\n if (*a - *b) != diff {\n return false;\n }\n },\n None => {\n difference = Some(*a - *b);\n }\n }\n }\n return true;\n}\n\nfn main() {\n read_line!(barriers;i32,track_length;i32);\n read_line!(vec,i32,a_barrier);\n read_line!(vec,i32,b_barrier);\n let a_barrier = LinkedList::from_iter(a_barrier.into_iter());\n let mut b_barrier = LinkedList::from_iter(b_barrier.into_iter());\n for _ in 0..barriers {\n let extend_front = b_barrier.pop_front().unwrap() + track_length;\n b_barrier.push_back(extend_front);\n if trivial_coincide(&a_barrier, &b_barrier) {\n println!(\"YES\");\n return;\n }\n }\n println!(\"NO\");\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "2c685bf3d6007cf89170b3df6e5f4995", "src_uid": "3d931684ca11fe6141c6461e85d91d63", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (_, l) = {\n let r = getvec::();\n (r[0] as usize, r[1])\n };\n let a = getvec::();\n let b = getvec::();\n let am = calc(&a, l);\n // for x in am.clone() {\n // println!(\"{}\", x);\n // }\n let bm = calc(&b, l);\n println!(\"{}\",\n match ok(&am, &bm) {\n true => \"YES\",\n false => \"NO\",\n });\n}\nfn ok(a: &Vec, b: &Vec) -> bool {\n let n = a.len();\n for i in 0..n {\n let mut r = true;\n for j in 0..n {\n let j_ = (j + i) % n;\n if a[j] != b[j_] {\n r = false;\n break;\n }\n }\n if r {\n return true;\n }\n }\n false\n}\nfn calc(seq: &Vec, l: i32) -> Vec {\n let mut res = Vec::new();\n let n = seq.len();\n for i in 0..n - 1 {\n res.push(seq[i + 1] - seq[i]);\n }\n res.push(l - seq[n - 1] + seq[0]);\n res\n}\n#[allow(dead_code)]\nfn next_line() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n input\n}\n\n#[allow(dead_code)]\nfn getnum() -> T {\n let res = next_line();\n res.trim().parse::().ok().unwrap()\n}\n\n#[allow(dead_code)]\nfn getvec() -> Vec {\n let res = next_line();\n res.split_whitespace().map(|x| x.parse::().ok().unwrap()).collect()\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "13703e6295057cc2b5c77763ced3edbb", "src_uid": "3d931684ca11fe6141c6461e85d91d63", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{ self, Write };\nuse std::str::FromStr;\nuse std::cmp::{ min, max };\nuse std::collections::{ BinaryHeap, VecDeque };\n\nmacro_rules! trace {\n ($var:expr) => ({\n let _ = writeln!(&mut std::io::stderr(), \">>> {} = {:?}\", stringify!($var), $var);\n })\n}\nmacro_rules! swap { ($a:expr, $b:expr) => ({ let t = $b; $b = $a; $a = t; }) }\n\nfn main() {\n let mut sc = Scanner::new();\n let n: usize = sc.cin();\n let l: usize = sc.cin();\n\n let mut a = vec![false; l];\n {\n a[0] = true;\n let base: usize = sc.cin();\n for i in 1..n {\n let x: usize = sc.cin();\n a[(x - base + l) % l] = true;\n }\n }\n trace!(a);\n\n let mut ys = vec![0; n];\n for i in 0..n {\n let y = sc.cin();\n ys[i] = y;\n }\n\n for base in 0..l {\n let mut ok = true;\n for i in 0..n {\n if !a[(ys[i] + base + l) % l] {\n ok = false;\n break;\n }\n }\n if ok {\n println!(\"YES\");\n return;\n }\n }\n\n println!(\"NO\");\n}\n\n#[allow(dead_code)]\nstruct Scanner { stdin: io::Stdin, buffer: VecDeque, }\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }\n fn reserve(&mut self) {\n while self.buffer.len() == 0 {\n let mut line = String::new();\n let _ = self.stdin.read_line(&mut line);\n for w in line.split_whitespace() {\n self.buffer.push_back(String::from(w));\n }\n }\n }\n fn cin(&mut self) -> T {\n self.reserve();\n match self.buffer.pop_front().unwrap().parse::() {\n Ok(a) => a,\n Err(_) => panic!(\"parse err\")\n }\n }\n fn get_char(&mut self) -> char {\n self.reserve();\n let head = self.buffer[0].chars().nth(0).unwrap();\n let tail = String::from( &self.buffer[0][1..] );\n if tail.len()>0 { self.buffer[0]=tail } else { self.buffer.pop_front(); }\n head\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "87d9ec077724e640229093b7750dd0a1", "src_uid": "3d931684ca11fe6141c6461e85d91d63", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Practice Codeforces\n// author: Leonardone @ NEETSDKASU\n\n// \u89e3\u8aac\u8aad\u5f8c\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n let m = get!(usize);\n \n if n < -2000 {\n let ans = brute_force(n, m as i64);\n println!(\"{}\", ans);\n }\n \n let mut xs = vec![0; m];\n \n for i in 0..m {\n let mut c = n / m as i64;\n if i as i64 <= n % m as i64 {\n c += 1;\n }\n xs[i * i % m] += c;\n }\n xs[0] -= 1;\n // println!(\"{:?}\", xs);\n let mut ans = 0;\n let c = n / m as i64;\n for i in 0..xs.len() {\n for j in 0..xs.len() {\n let k = (i+j) % m;\n if k == 0 {\n ans += xs[i] * xs[j];\n }\n }\n }\n\n println!(\"{}\", ans);\n}\n\nfn brute_force(n: i64, m: i64) -> i64 {\n let mut ret = 0;\n for i in 1..=n {\n for j in 1..=n {\n let k = i * i + j * j;\n if k % m == 0 {\n ret += 1;\n }\n }\n }\n ret\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "1c9b5ef573167f1074b39012394de46a", "src_uid": "2ec9e7cddc634d7830575e14363a4657", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::min;\n\npub fn process(n: i32, m: i32) -> u64 {\n let mut res: u64 = 0;\n for i in 1..=min(m, n) {\n for j in 1..=min(m, n) {\n if (i * i + j * j) % m != 0 { continue }\n let k = ((n - i) / m) as u64;\n let l = ((n - j) / m) as u64;\n res += ((k + 1) * (l + 1));\n }\n }\n res\n}\n\nfn main() {\n let mut s = String::new();\n stdin().read_line(&mut s).unwrap();\n let mut input = s.split_whitespace();\n let n = input.next().unwrap().parse::().unwrap();\n let m = input.next().unwrap().parse::().unwrap();\n\n println!(\"{}\", process(n, m));\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test1() {\n assert_eq!(process(3, 3), 1);\n }\n\n #[test]\n fn test2() {\n assert_eq!(process(6, 5), 13);\n }\n\n #[test]\n fn test3() {\n assert_eq!(process(1000_000_000, 1), 1000_000_000_000_000_000);\n }\n #[test]\n fn test4() {\n assert_eq!(process(15, 1_000), 0);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "10b3f2174f68890cadb4281c0192678b", "src_uid": "2ec9e7cddc634d7830575e14363a4657", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Practice Codeforces\n// author: Leonardone @ NEETSDKASU\n\n// \u89e3\u8aac\u8aad\u5f8c\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n let m = get!(usize);\n \n if n < -2000 {\n let ans = brute_force(n, m as i64);\n println!(\"{}\", ans);\n }\n \n let mut xs = vec![0; m];\n \n for i in 0..m {\n let mut c = n / m as i64;\n if i as i64 <= n % m as i64 {\n c += 1;\n }\n xs[i] += c;\n }\n xs[0] -= 1;\n // println!(\"{:?}\", xs);\n let mut ans = 0;\n let c = n / m as i64;\n for i in 0..xs.len() {\n for j in 0..xs.len() {\n let k = (i*i+j*j) % m;\n if k == 0 {\n ans += xs[i] * xs[j];\n }\n }\n }\n\n println!(\"{}\", ans);\n}\n\nfn gcd(a: i64, b: i64) -> i64 {\n fn _gcd(a: i64, b: i64) -> i64 {\n if a == 0 { b } else { _gcd(b % a, a) }\n }\n let a = a.abs();\n let b = b.abs();\n if a < b { _gcd(a, b) } else { _gcd(b, a) }\n}\n\nfn brute_force(n: i64, m: i64) -> i64 {\n let mut ret = 0;\n for i in 1..=n {\n for j in 1..=n {\n let k = i * i + j * j;\n if k % m == 0 {\n ret += 1;\n }\n }\n }\n ret\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "e61a5c43076e2d3a1053db9b6aa489d7", "src_uid": "2ec9e7cddc634d7830575e14363a4657", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Practice Codeforces\n// author: Leonardone @ NEETSDKASU\n\n// \u89e3\u8aac\u8aad\u5f8c\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n let m = get!(usize);\n \n if n < -2000 {\n let ans = brute_force(n, m as i64);\n println!(\"{}\", ans);\n }\n \n let mut xs = vec![0; m];\n \n // 24 6 -> 32 (32)\n // 23 6 -> 25 (24)\n // 22 6 -> 25 (24)\n // 21 6 -> 25 (24)\n // 20 6 -> 18 (18)\n // 19 6 -> 18 (18)\n // 18 6 -> 18 (18)\n // 17 6 -> 13 (12)\n // 125 6 -> 841 (840)\n // 1123 24 -> 17485 (17484)\n // 1223 25 -> 155380 (155624)\n // 13 5 -> 64 (66)\n // 6 5 -> 13 (14)\n // 23 5 -> 196 (200)\n // 23 7 -> 9 (12)\n \n // 18 19 20 21 23\n for i in 1..=(n % m as i64) as usize {\n let k = (i * i) % m;\n xs[k] += 1;\n }\n let c = n / m as i64;\n // 23 / 6 = 3\n // 0 1 2 3 4 5\n // 6 7 8 9 10 11\n // 12 13 14 15 16 17\n for i in 0..m {\n let k = (i * i) % m;\n xs[k] += c;\n }\n // println!(\"{} {}\", n / m as i64, n % m as i64);\n // println!(\"{:?}\", xs);\n let mut ans = 0;\n let c = n / m as i64;\n for i in 0..xs.len() {\n for j in 0..xs.len() {\n let k = (i+j) % m;\n if k == 0 {\n ans += xs[i] * xs[j];\n }\n }\n }\n\n println!(\"{}\", ans);\n}\n\nfn brute_force(n: i64, m: i64) -> i64 {\n let mut ret = 0;\n for i in 1..=n {\n for j in 1..=n {\n let k = i * i + j * j;\n if k % m == 0 {\n ret += 1;\n }\n }\n }\n ret\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "d115d823e89c58d2f6693274e9447843", "src_uid": "2ec9e7cddc634d7830575e14363a4657", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(dead_code)]\n#![allow(unused_labels)]\n\nuse std::char::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::io::*;\nuse std::str::FromStr;\n\nmacro_rules! debug {($($a:expr),*) => {eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);}}\nmacro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\nmacro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\nmacro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n\n\nfn read() -> T {\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.expect(\"failed to read char\") as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n token.parse().ok().expect(\"failed to parse token\")\n}\n\nuse std::f64;\n\nfn min(a:T, b:T) -> T {\n if a < b { a }\n else { b }\n}\n\nfn max(a:T, b:T) -> T {\n if a < b { b }\n else { a }\n}\n\nconst MAX:usize = 30;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\nstruct Graph {\n e: Vec>,\n v: Vec,\n u: Vec,\n f: Vec,\n c: i64,\n vc: Vec,\n}\n\nimpl Graph {\n fn new(n:usize) -> Self {\n Graph {\n e: vec![vec![];n],\n v: vec![],\n u: vec![n;n],\n f: vec![false;n],\n c: 0,\n vc: vec![0;n],\n }\n }\n\n fn dfs(&mut self, crt: usize) {\n if self.f[crt] { return; }\n self.c += 1;\n self.f[crt] = true;\n self.v.push(crt);\n self.vc[crt] = self.c;\n self.u[crt] = self.v.len()-1;\n for i in 0..self.e[crt].len() {\n self.dfs(self.e[crt][i]);\n }\n //debug!(crt, self.c, self.vc[crt]);\n self.vc[crt] = self.c - self.vc[crt];\n }\n}\n\nfn main() {\n //let t:usize = read();\n\n //'outer: for _ in 0..t {\n let n:usize = read();\n let k:i64 = read();\n let a:Vec = (0..n).map(|_| read()).collect();\n\n let mut idx = 0;\n for i in 0..n {\n if a[i] > k { break; }\n idx = i+1;\n }\n let mut idx2 = n;\n for i in (0..n).rev() {\n if a[i] > k { break; }\n idx2 = i;\n }\n if idx == n {\n println!(\"{}\", n);\n } else {\n println!(\"{}\", idx+(n-idx2));\n }\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "2ebd08b1869973697ab24a60eda84bd7", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let k: usize = scan.next();\n let arr: Vec = scan.next_n(n);\n let mut result = 0usize;\n for &item in arr.iter() {\n if item <= k {\n result += 1;\n } else {\n break;\n }\n }\n let initial = result;\n for &item in arr.iter().skip(initial).rev() {\n if item <= k {\n result += 1;\n } else {\n break;\n }\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "0c160c288c4aed9c44c0399800897089", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_ints() -> Vec {\n let mut ln = String::new();\n std::io::stdin().read_line(&mut ln).expect(\"\");\n ln.split_whitespace().filter_map(|w| w.parse().ok()).collect()\n}\n\nfn main() {\n let (n, k): (usize, i32);\n if let [_n, _k] = read_ints()[..] { n = _n as usize; k = _k; } else { panic!(\"> <\"); }\n let a = read_ints();\n assert_eq!(n, a.len());\n\n let mut ans = 0;\n for &el in a.iter() {\n if el <= k { ans += 1; } else { break; }\n }\n for &el in a.iter().rev() {\n if el <= k { ans += 1; } else { break; }\n }\n\n if ans == n * 2 { ans = n; }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "71adcabe739b94d1ed200f81eb929675", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input_text = String::new();\n io::stdin().read_line(&mut input_text).expect(\"fail\");\n let input_text = input_text.trim();\n let mut tuples = input_text.split_whitespace();\n let n = tuples.next().unwrap().parse::().expect(\"parse error\");\n let k = tuples.next().unwrap().parse::().expect(\"parse error\");\n\n let mut input_text = String::new();\n io::stdin().read_line(&mut input_text).expect(\"fail\");\n let list = input_text.split_whitespace();\n let numbers: Vec<&str> = list.collect();\n\n let mut max = std::u32::MIN;\n let mut min = std::u32::MAX;\n for i in 0..n {\n let x = numbers[i as usize].parse::().expect(\"parse error\");\n if x > k {\n max = std::cmp::max(i, max);\n min = std::cmp::min(i, min);\n }\n }\n\n if min > max {\n println!(\"{}\", n);\n } else if min == max {\n println!(\"{}\", n-1);\n } else {\n println!(\"{}\", n - (max - min + 1));\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "713381da3008abf28dc407817f11f6df", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use io::*;\n\nfn main() {\n let con = read_string();\n let mut sc = Scanner::new(&con);\n\n let n: i32 = sc.next();\n let k: i32 = sc.next();\n let v: Vec = sc.next_vec(n as _);\n\n let mut l = 0;\n let mut r = n - 1;\n let mut ans = 0;\n\n while l <= r {\n if v[l as usize] <= k {\n l += 1;\n ans += 1;\n } else if v[r as usize] <= k {\n r -= 1;\n ans += 1;\n } else {\n break;\n }\n }\n\n println!(\"{}\", ans);\n}\n\n//-----\n\npub mod io {\n use std;\n use std::str::FromStr;\n\n pub struct Scanner<'a> {\n iter: std::str::SplitWhitespace<'a>,\n }\n\n impl<'a> Scanner<'a> {\n pub fn new(s: &'a str) -> Scanner<'a> {\n Scanner {\n iter: s.split_whitespace(),\n }\n }\n\n pub fn next(&mut self) -> T {\n let s = self.iter.next().unwrap();\n if let Ok(v) = s.parse::() {\n v\n } else {\n panic!(\"Parse error\")\n }\n }\n\n pub fn next_vec_len(&mut self) -> Vec {\n let n: usize = self.next();\n self.next_vec(n)\n }\n\n pub fn next_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n }\n\n pub fn read_string() -> String {\n use std::io::Read;\n\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n }\n\n pub fn read_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim_right().to_owned()\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "5d27725ff145e7f98e1b1fc5e12243a3", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std:: io;\n\nfn read_ints() -> Vec {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.split_whitespace().filter_map(|ss| ss.parse().ok()).collect()\n}\n\nfn main() {\n let n: u8;\n let k: u8;\n if let [_n, _k] = read_ints()[..] { n = _n; k = _k; } else { panic!(\"x\"); }\n\n let a: Vec = read_ints();\n\n let mut ans: u8 = 0;\n let mut flag: usize = n as usize - 1;\n for (i, aa) in a.iter().enumerate() {\n if aa <= &k {\n ans += 1;\n } else {\n flag = i;\n break;\n }\n }\n flag = n as usize - 1 - flag;\n for (i, aa) in a.iter().rev().enumerate() {\n if i < flag && aa <= &k {\n ans += 1;\n } else {\n break;\n }\n }\n\n println!(\"{}\", ans);\n\n return;\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "cadb1e159fe79f8b9738ca1c7942d3a4", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std:: io;\n\nfn read_ints() -> Vec {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.split_whitespace().filter_map(|ss| ss.parse().ok()).collect()\n}\n\nfn main() {\n let n: u8;\n let k: u8;\n if let [_n, _k] = read_ints()[..] { n = _n; k = _k; } else { panic!(\"x\"); }\n\n let a: Vec = read_ints();\n\n let mut ans: u8 = 0;\n //let mut flag: usize = n as usize - 1;\n //for (i, aa) in a.iter().enumerate() {\n //if aa <= &k {\n //ans += 1;\n //} else {\n //flag = i;\n //break;\n //}\n //}\n //flag = n as usize - 1 - flag;\n //for (i, aa) in a.iter().rev().enumerate() {\n //if i < flag && aa <= &k {\n //ans += 1;\n //} else {\n //break;\n //}\n //}\n \n for aa in a.iter() {\n if aa <= &k { ans += 1; }\n else { break; }\n }\n for aa in a.iter().rev() {\n if aa <= &k { ans += 1; }\n else { break; }\n }\n\n if ans == n * 2 { ans = n }\n\n println!(\"{}\", ans);\n\n return;\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "233b5412492ca24e45c7e3d99921f340", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::collections::VecDeque;\n\nfn main() {\n let mut count = 0;\n let num = read();\n let mut text = VecDeque::new();\n let number = read();\n for a in number.into_iter() {\n text.push_back(a);\n }\n loop {\n let a = text.pop_front();\n if a <= Some(*&num[1]) {\n if a != None {\n count += 1;\n continue;\n }\n }\n break;\n }\n loop {\n let a = text.pop_back();\n if a <= Some(*&num[1]) {\n if a != None {\n count += 1;\n continue;\n }\n }\n break;\n }\n println!(\"{}\", count);\n}\n\nfn read() -> Vec {\n let mut a = String::new();\n io::stdin().read_line(&mut a).unwrap();\n a.trim().to_string();\n let mut num = Vec::new();\n for a in a.split_whitespace() {\n num.push(a.parse::().unwrap());\n }\n num\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "d05421862166f1759a77fffec371608b", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let s = \"aeiou13579\";\n let sol = input.sl().chars().filter(|&c| s.chars().any(|a| a == c)).count();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "9cf01ba57e99747edaefe424ce2e7341", "src_uid": "b4af2b8a7e9844bf58ad3410c2cb5223", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn main() {\n let stdin = std::io::stdin();\n let x = stdin.bytes().map(|c| {\n let c = c.unwrap();\n c == b'a' || c == b'e' || c == b'i' || c == b'o' || c == b'u' || (c >= b'0' && c <= b'9' && (c - b'0') % 2 == 1)\n }).filter(|&x| x).count();\n println!(\"{}\", x);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "589748d7b5db4403c10fc8b26e0481f7", "src_uid": "b4af2b8a7e9844bf58ad3410c2cb5223", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn is_vowel(ch: char) -> bool {\n return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut result = 0usize;\n for ch in scan.next::().chars() {\n if is_vowel(ch) || ch.to_digit(10).unwrap_or(2) % 2 == 1 {\n result += 1;\n }\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "37aec1ee3254388fac32ab6118d2c17a", "src_uid": "b4af2b8a7e9844bf58ad3410c2cb5223", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn is_vowel(z: char)->bool {\n let s = \"aeoiu\";\n return s.chars().any(|x|x==z);\n}\n\nfn is_odd(z: char)->bool {\n let s = \"13579\";\n return s.chars().any(|x|x==z);\n}\n\nfn main() {\nlet s = readln!();\nprintln!(\"{}\",s.chars().filter(|&x| is_vowel(x) || is_odd(x)).count());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "bc1e5becab542bf1d923723ce97ce863", "src_uid": "b4af2b8a7e9844bf58ad3410c2cb5223", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::prelude::BufRead;\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufReader, BufWriter, Write};\n#[allow(unused_imports)]\nuse std::mem::swap;\n#[allow(unused_imports)]\nuse std::str::FromStr;\n\nfn main() {\n let line = read_vector::();\n let (n, k) = (line[0], line[1] - 1);\n let min_n = min(k, n - 1 - k);\n println!(\"{}\", 3 * n + min_n);\n}\n\n#[allow(dead_code)]\nfn read() -> T\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n return buf.trim().parse().unwrap();\n}\n\n#[allow(dead_code)]\nfn read_vector() -> Vec\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n let mut buf = String::with_capacity(100);\n stdin().read_line(&mut buf).unwrap();\n return buf.split_whitespace().map(|s| s.parse().unwrap()).collect();\n}\n\n#[allow(dead_code)]\nfn read_matrix() -> Vec>\nwhere\n T: std::str::FromStr,\n T::Err: std::fmt::Debug,\n{\n use std::io::prelude::*;\n let stdin = stdin();\n let mut reader = BufReader::with_capacity(100 * 1024, stdin);\n let mut line = String::with_capacity(100);\n let mut matrix: Vec> = Vec::new();\n\n while reader.read_line(&mut line).unwrap() > 0 {\n matrix.push(\n line.trim()\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect(),\n );\n line.clear();\n }\n\n return matrix;\n}\n\n#[allow(dead_code)]\nfn read_chars() -> Vec {\n let stdin = stdin();\n let mut buf = String::new();\n let _bytes = stdin.read_line(&mut buf).unwrap();\n return buf.trim().chars().collect();\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "11be7e494dd2780a07adb5529ec31027", "src_uid": "24b02afe8d86314ec5f75a00c72af514", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (write!(out,$($format)*).unwrap());\n }\n input! {\n n: i32,\n k: i32,\n }\n let ans = min((n - k) + n - 1, (k - 1) + n - 1);\n puts!(\"{}\\n\", ans + 2 * n + 1);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "c8d5e05717c28dfa63d5a7aad4d0f43e", "src_uid": "24b02afe8d86314ec5f75a00c72af514", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n// input macro\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn main() {\n input!{\n n: usize,\n k: usize,\n }\n println!(\"{}\", 2 * n + min(k - 1, n - k) * 2 + max(k - 1, n - k) + 1);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "9d7c97479461e00333998bacce9472a6", "src_uid": "24b02afe8d86314ec5f75a00c72af514", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::iter::*;\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty; $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt; $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let sol = (1..).flat_map(|a| a.to_string().into_bytes()).nth(n - 1);\n println!(\"{}\", sol.unwrap() as char);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3dba8028e8d074a5aae517bc16a26588", "src_uid": "2d46e34839261eda822f0c23c6e19121", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\nuse std::collections::{*};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n \nfn main() {\n let mut scanner = Scanner::default();\n let (a, b, c): (f64, f64, f64) = (scanner.next(), scanner.next(), scanner.next());\n let tot = (a*b*c).sqrt();\n println![\"{}\", 4.0*(tot/a + tot/b + tot/c)];\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "ce0667cab33a91b4b98dccf49b8cc50a", "src_uid": "c0a3290be3b87f3a232ec19d4639fefc", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nfn main() {\n let areas: Vec = get_input().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect();\n \n let a = (areas[0] * areas[1] / areas[2]).sqrt();\n let b = (areas[0] * areas[2] / areas[1]).sqrt();\n let c = (areas[2] * areas[1] / areas[0]).sqrt();\n let res = 4 * (a+b+c) as u32;\n\n println!(\"{}\", res);\n \n}\n\nfn get_input() -> String {\n let mut buffer = String::new();\n std::io::stdin().read_line(&mut buffer).expect(\"Failed\");\n buffer.trim().to_owned()\n}\n\nfn get_input_usize() -> usize {\n get_input().parse().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "2bffe5041efb52a8a6f0d7e84a40ead5", "src_uid": "c0a3290be3b87f3a232ec19d4639fefc", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! scan {\n ( $string:expr, $sep:expr, $( $x:ty ),+ ) => {{\n let mut iter = $string.split($sep);\n ($(iter.next().and_then(|word| word.parse::<$x>().ok()).unwrap(),)*)\n }}\n}\n\nuse std::io;\n\nfn dist(l: &mut i32, r: &mut i32, a: &i32) {\n for _ in 0..*a {\n if l <= r {\n *l += 1;\n } else {\n *r += 1;\n }\n }\n}\n\nfn cnt(l: &i32, r: &i32) -> i32 {\n std::cmp::min(*l, *r) * 2\n}\n\nfn solve(mut l: i32, mut r: i32, a: i32) -> i32 {\n dist(&mut l, &mut r, &a);\n cnt(&l, &r)\n}\n\nfn main() {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n\n let (l, r, a) = scan!(buf, char::is_whitespace, i32, i32, i32);\n\n println!(\"{}\", solve(l, r, a));\n}\n\n#[cfg(test)]\nmod test{\n use super::*;\n\n #[test]\n fn test_dist() { let (mut l, mut r, a) = (2, 3, 5);\n\n dist(&mut l, &mut r, &a);\n assert_eq!(l, 5);\n assert_eq!(r, 5);\n\n let (mut l, mut r, a) = (1, 5, 5);\n\n dist(&mut l, &mut r, &a);\n assert_eq!(l, 6);\n assert_eq!(r, 5);\n }\n\n #[test]\n fn test_cnt() {\n assert_eq!(cnt(&2, &3), 4);\n assert_eq!(cnt(&3, &4), 6);\n assert_eq!(cnt(&1, &0), 0);\n assert_eq!(cnt(&0, &0), 0);\n }\n\n #[test]\n fn acpt() {\n assert_eq!(solve(1, 4, 2), 6);\n assert_eq!(solve(5, 5, 5), 14);\n assert_eq!(solve(0, 2, 0), 0);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "758730e32df17f6a747244e14ecefb93", "src_uid": "e8148140e61baffd0878376ac5f3857c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::cmp;\n\npub fn main() {\n let mut input_string = String::new();\n io::stdin().read_line(&mut input_string)\n .expect(\"uh oh\");\n let input_vector: Vec = input_string\n .split_whitespace()\n .map(|x| x.parse::()\n .expect(\"uh oh\"))\n .collect();\n let max = cmp::max(input_vector[0], input_vector[1]);\n let min = cmp::min(input_vector[0], input_vector[1]);\n if min + input_vector[2] > max {\n let extra = input_vector[2] - (max - min);\n println!(\"{}\", (max + extra / 2) * 2);\n } else {\n println!(\"{}\", (min + input_vector[2]) * 2);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "538cc9dd18b4c80628eb24776866b88b", "src_uid": "e8148140e61baffd0878376ac5f3857c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_variables, dead_code, non_snake_case, unused_macros)]\nuse std::io::{stdin, Read, StdinLock};\nuse std::str::FromStr;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nfn getline() -> String{\n let mut res = String::new();\n std::io::stdin().read_line(&mut res).ok();\n res\n}\n\nmacro_rules! readl {\n ($t: ty) => {\n {\n let s = getline();\n s.trim().parse::<$t>().unwrap()\n }\n };\n ($( $t: ty),+ ) => {\n {\n let s = getline();\n let mut iter = s.trim().split(' ');\n ($(iter.next().unwrap().parse::<$t>().unwrap(),)*) \n }\n };\n}\n\nmacro_rules! readlvec {\n ($t: ty) => {\n {\n let s = getline();\n let iter = s.trim().split(' ');\n iter.map(|x| x.parse().unwrap()).collect::>()\n }\n }\n}\n\nmacro_rules! mvec {\n ($v: expr, $s: expr) => {\n vec![$v; $s]\n };\n ($v: expr, $s: expr, $($t: expr),*) => {\n vec![mvec!($v, $($t),*); $s]\n };\n}\n\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn printiter<'a, T>(v: &'a T)\nwhere\n &'a T: std::iter::IntoIterator, \n <&'a T as std::iter::IntoIterator>::Item: std::fmt::Display {\n for (i,e) in v.into_iter().enumerate() {\n if i != 0 {\n print!(\" \");\n }\n print!(\"{}\", e);\n }\n println!(\"\");\n}\n\nstruct ContestPrinter {\n s: String,\n}\n\nimpl ContestPrinter {\n fn new() -> ContestPrinter {\n ContestPrinter {\n s: String::new(),\n }\n }\n\n fn print(&mut self, x: T)\n where T: std::fmt::Display {\n self.s.push_str(format!(\"{}\", x).as_str());\n }\n\n fn println(&mut self, x: T)\n where T: std::fmt::Display {\n self.s.push_str(format!(\"{}\\n\", x).as_str());\n }\n}\n\nimpl std::ops::Drop for ContestPrinter {\n fn drop(&mut self) {\n print!(\"{}\", self.s);\n }\n}\n\nfn main() {\n let mut printer = ContestPrinter::new();\n \n let (L, R, A) = readl!(i32, i32, i32);\n let mut l = L;\n let mut r = R;\n if l > r {\n r += A;\n } else {\n l += A;\n }\n while (l - r).abs() > 1 {\n if l > r {\n if l == L { break; }\n l -= 1;\n r += 1;\n } else {\n if r == R { break; }\n r -= 1;\n l += 1;\n }\n }\n printer.println(2 * min(l, r));\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "184d1a7602adf81ab357c309c45ff095", "src_uid": "e8148140e61baffd0878376ac5f3857c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/**\n* _ _ __ _ _ _ _ _ _ _\n* | | | | / / | | (_) | (_) | | (_) | |\n* | |__ __ _| |_ ___ ___ / /__ ___ _ __ ___ _ __ ___| |_ _| |_ ___ _____ ______ _ __ _ _ ___| |_ ______ ___ _ __ _ _ __ _ __ ___| |_ ___\n* | '_ \\ / _` | __/ _ \\ / _ \\ / / __/ _ \\| '_ ` _ \\| '_ \\ / _ \\ __| | __| \\ \\ / / _ \\______| '__| | | / __| __|______/ __| '_ \\| | '_ \\| '_ \\ / _ \\ __/ __|\n* | | | | (_| | || (_) | (_) / / (_| (_) | | | | | | |_) | __/ |_| | |_| |\\ V / __/ | | | |_| \\__ \\ |_ \\__ \\ | | | | |_) | |_) | __/ |_\\__ \\\n* |_| |_|\\__,_|\\__\\___/ \\___/_/ \\___\\___/|_| |_| |_| .__/ \\___|\\__|_|\\__|_| \\_/ \\___| |_| \\__,_|___/\\__| |___/_| |_|_| .__/| .__/ \\___|\\__|___/\n* | | | | | |\n* |_| |_| |_|\n*\n* https://github.com/hatoo/competitive-rust-snippets\n*/\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\nmod util {\n use std::io::{stdin, stdout, BufWriter, StdoutLock};\n use std::str::FromStr;\n use std::fmt::Debug;\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n #[allow(dead_code)]\n pub fn chars() -> Vec {\n line().chars().collect()\n }\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n #[allow(dead_code)]\n pub fn with_bufwriter) -> ()>(f: F) {\n let out = stdout();\n let writer = BufWriter::new(out.lock());\n f(writer)\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; ( $ t : ty ;; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ;; ) ) . collect ::< Vec < _ >> ( ) } ; }\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[allow(dead_code)]\nfn main() {\n let (l, r, a) = get!(usize, usize, usize);\n let ans = 2\n * (0..)\n .take_while(|&t| {\n let mut d = 0;\n if l < t {\n d += t - l;\n }\n if r < t {\n d += t - r;\n }\n\n d <= a\n })\n .last()\n .unwrap();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "ca6514e8abf8e92fafd7a8554465adb7", "src_uid": "e8148140e61baffd0878376ac5f3857c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Basics\n\n#![allow(unused_imports)]\n\nuse std::mem;\nuse std::io;\nuse std::string;\nuse std::cmp::*;\nuse std::collections::*;\n\nfn load() -> Vec {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let vec: Vec<&str> = line.split(\" \").collect();\n let mut data: Vec = Vec::new();\n for i in vec {\n let el: i64 = i.trim().parse().unwrap();\n data.push(el);\n }\n data\n}\n\nfn main() {\n let w = load();\n let (a, b) = (w[0], w[1]);\n if b - a >= 10 {\n println!(\"0\");\n } else {\n let mut end = 1;\n for i in (a + 1)..(b + 1) {\n end *= i % 10;\n }\n println!(\"{}\", (end % 10));\n }\n}\n\n//\n//mod strings;\n//\n//fn main() {\n// strings_sample();\n//}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "dd4cafb5f3e19ac8f11275ddea2f8ae0", "src_uid": "2ed5a7a6176ed9b0bda1de21aad13d60", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let stdin = std::io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n String::from(line.trim())\n}\n\nmacro_rules! scan_line {\n ($($ty: ty),*) => {{\n let line = read_line();\n let mut tok = line.split_whitespace();\n ($(tok.next().unwrap().parse::<$ty>().unwrap()),*)\n }}\n}\n\nfn main() {\n let (a, b) = scan_line!(u64, u64);\n let mut acc = 1;\n for i in (a + 1)..(b + 1) {\n acc = (acc * i % 10) % 10;\n if acc == 0 {\n break;\n }\n }\n println!(\"{}\", acc);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "4c7ec2c637fa6cc2f88fcff478d2c4cc", "src_uid": "2ed5a7a6176ed9b0bda1de21aad13d60", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet};\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\nfn main() {\n let (a, b): (u64, u64) = util::get2();\n\n let mut f = 1;\n\n for x in a + 1..b + 1 {\n f = (f * (x % 10)) % 10;\n if f == 0 {\n break;\n }\n }\n\n println!(\"{}\", f);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "0eb13a835cb3f6eb2de5733b1f3cd309", "src_uid": "2ed5a7a6176ed9b0bda1de21aad13d60", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\n#[derive(Clone)]\nstruct Graph {\n nodes: usize,\n edges: Vec>,\n}\n\nimpl Graph {\n fn new(n: usize) -> Self {\n Self {\n nodes: n,\n edges: vec![Vec::new(); n + 1],\n }\n }\n\n fn add_edge(&mut self, x: usize, y: usize, cost: u64) {\n self.edges[x].push((y, cost));\n self.edges[y].push((x, cost));\n }\n\n fn dijkstra(&mut self, start: usize, end: usize) -> u64 {\n let mut dist = vec![None; self.nodes + 1];\n let mut prev = vec![None; self.nodes + 1];\n dist[start] = Some(0);\n let mut queue = (1..=self.nodes).collect::>();\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n while let Some(next_node) = queue.pop() {\n if next_node == end {\n return dist[next_node].unwrap();\n }\n for (neighbour, cost) in self.edges[next_node].iter() {\n let alt = dist[next_node].unwrap() + cost;\n if dist[*neighbour].is_none() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n } else {\n if alt < dist[*neighbour].unwrap() {\n dist[*neighbour] = Some(alt);\n prev[*neighbour] = Some(next_node);\n }\n }\n }\n //println!(\"{:?} {:?}\", dist, prev);\n queue.sort_unstable_by_key(|node| dist[*node].unwrap_or(std::u64::MAX));\n queue.reverse();\n }\n 0\n }\n\n fn set_cost(&mut self, x: usize, y: usize, cost: u64) {\n for i in 0..self.edges[x].len() {\n if self.edges[x][i].0 == y {\n self.edges[x][i].1 = cost\n }\n }\n for i in 0..self.edges[y].len() {\n if self.edges[y][i].0 == x {\n self.edges[y][i].1 = cost\n }\n }\n }\n}\n\nconst MODULO: u64 = 1_000_000_007;\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\nstruct BigPrimeRing {\n inner: u64,\n}\n\nimpl From for BigPrimeRing\nwhere\n T: Into,\n{\n fn from(n: T) -> Self {\n Self {\n inner: n.into() % MODULO,\n }\n }\n}\n\nimpl std::ops::Add for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn add(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::AddAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn add_assign(&mut self, rhs: T) {\n self.inner += rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Sub for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn sub(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner + MODULO - rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::SubAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn sub_assign(&mut self, rhs: T) {\n self.inner += MODULO;\n self.inner -= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl std::ops::Mul for BigPrimeRing\nwhere\n T: Into,\n{\n type Output = BigPrimeRing;\n fn mul(self, rhs: T) -> Self::Output {\n Self {\n inner: (self.inner * rhs.into().inner) % MODULO,\n }\n }\n}\n\nimpl std::ops::MulAssign for BigPrimeRing\nwhere\n T: Into,\n{\n fn mul_assign(&mut self, rhs: T) {\n self.inner *= rhs.into().inner;\n self.inner %= MODULO;\n }\n}\n\nimpl BigPrimeRing {\n fn inverse(self) -> Self {\n if self.inner == 0 {\n return self;\n }\n let (_g, mut x, _y) = egcd(self.inner as i64, MODULO as i64);\n if x < 0 {\n x += MODULO as i64;\n }\n Self { inner: x as u64 }\n }\n}\n\nfn main() -> Result<(), Box> {\n let (a, b) = read_2::();\n let mut res = 1;\n 'lop: for i in (a + 1)..=b {\n res *= i;\n res %= 10;\n if res == 0 {\n break 'lop;\n }\n }\n println!(\"{}\", res);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "452740aa522479b899bd387fb3816213", "src_uid": "2ed5a7a6176ed9b0bda1de21aad13d60", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\n\nfn inv(mut a: i64, modulo: i64) -> i64 {\n let mut b: i64 = modulo - 2;\n let mut ans: i64 = 1;\n while b > 0 {\n if b & 1 == 1 {\n ans = (ans * a) % modulo;\n }\n a = (a * a) % modulo;\n b >>= 1;\n }\n ans\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut sc = cf_scanner::Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n let (n, modulo): (usize, i64) = (sc.next(), sc.next());\n\n let mut pow2: Vec = vec![1; n + 1];\n (1..=n).for_each(|i| pow2[i] = (2 * pow2[i-1]) % modulo);\n\n let mut fact: Vec = vec![1; n + 1];\n (1..=n).for_each(|i| fact[i] = (i as i64 * fact[i-1]) % modulo);\n\n let i_fact: Vec = (0..=n).map(|i| inv(fact[i], modulo)).collect();\n\n let mut choose: Vec> = vec![vec![0; n + 1]; n + 1];\n for i in 0..=n {\n for j in 0..=i {\n choose[i][j] = ((fact[i] * i_fact[j]) % modulo * i_fact[i - j]) % modulo;\n }\n }\n\n let mut dp: Vec> = vec![vec![0; n + 5]; n + 5];\n dp[0][0] = 1;\n for i in 1..=n {\n dp[i][i] = pow2[i-1];\n for j in 1..=i {\n for k in 1..j {\n if i < k + 1 {\n break;\n } \n dp[i][j] += ((pow2[k-1] * choose[j][k]) % modulo * dp[i - k - 1][j - k]) % modulo;\n dp[i][j] %= modulo;\n }\n }\n }\n \n let ans: i64 = (1..=n).fold(0 as i64, |x, y| (x + dp[n][y]) % modulo);\n\n writeln!(out, \"{}\", ans).unwrap();\n}\n\n#[allow(dead_code)]\nmod cf_scanner {\n use std::io;\n use std::str::{FromStr, SplitAsciiWhitespace};\n\n pub struct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n }\n\n impl Scanner {\n pub fn new(reader: R) -> Scanner {\n Scanner {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn next_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "4cfef4b44ab2bf08c81d24bbf12bfd49", "src_uid": "4f0e0d1deef0761a46b64de3eb98e774", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\n\nfn inv(mut a: i64, modulo: i64) -> i64 {\n let mut b: i64 = modulo - 2;\n let mut ans: i64 = 1;\n while b > 0 {\n if b & 1 == 1 {\n ans = (ans * a) % modulo;\n }\n a = (a * a) % modulo;\n b >>= 1;\n }\n ans\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut sc = cf_scanner::Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n\n let (n, modulo): (usize, i64) = (sc.next(), sc.next());\n\n let mut pow2: Vec = vec![1; n + 1];\n (1..=n).for_each(|i| pow2[i] = (2 * pow2[i-1]) % modulo);\n\n let mut fact: Vec = vec![1; n + 1];\n (1..=n).for_each(|i| fact[i] = (i as i64 * fact[i-1]) % modulo);\n\n let i_fact: Vec = (0..=n).map(|i| inv(fact[i], modulo)).collect();\n\n let choose: Vec> = (0..=n).map(|i| {\n (0..=i).map(|j| ((fact[i] * i_fact[j]) % modulo * i_fact[i - j]) % modulo).collect()\n }).collect();\n\n let mut dp: Vec> = vec![vec![0; n + 5]; n + 5];\n dp[0][0] = 1;\n for i in 1..=n {\n dp[i][i] = pow2[i-1];\n for j in 1..=i {\n for k in 1..j {\n if i < k + 1 {\n break;\n } \n dp[i][j] += ((pow2[k-1] * choose[j][k]) % modulo * dp[i - k - 1][j - k]) % modulo;\n dp[i][j] %= modulo;\n }\n }\n }\n \n let ans: i64 = (1..=n).fold(0 as i64, |x, y| (x + dp[n][y]) % modulo);\n\n writeln!(out, \"{}\", ans).unwrap();\n}\n\n#[allow(dead_code)]\nmod cf_scanner {\n use std::io;\n use std::str::{FromStr, SplitAsciiWhitespace};\n\n pub struct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n }\n\n impl Scanner {\n pub fn new(reader: R) -> Scanner {\n Scanner {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = std::str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn next_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "64599dc56fe49cdad042ba87e5aa0e83", "src_uid": "4f0e0d1deef0761a46b64de3eb98e774", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros)]\n\nuse kyoproio::*;\nuse std::{\n collections::*,\n io::{self, prelude::*},\n iter, mem,\n};\n\nfn run(mut kin: I, mut out: O) {\n let t: usize = 1; // kin.parse();\n for _ in 0..t {\n case(&mut kin, &mut out);\n }\n} \nfn case(mut kin: I, mut out: O) {\n let (n, m): (usize, u32) = kin.parse();\n set_var_mod(m);\n let mut dp = vec![vec![mint(0); n + 1]; n + 1]; // [count][pos]\n let mut miss = vec![mint(0); n + 1];\n miss[0] = mint(1);\n let mut any = vec![vec![mint(0); n + 1]; n + 1];\n for i in 1..=n {\n let mut dp_new = vec![vec![mint(0); n + 1]; n + 1];\n let mut any_new = vec![vec![mint(0); n + 1]; n + 1];\n for c in 0..i {\n let mut sum = mint(0);\n for j in 0..c {\n sum += dp[c][j] + any[c][j];\n dp_new[c + 1][j + 1] += sum;\n }\n let miss_new = sum;\n let mut sum = mint(0);\n for j in (0..c).rev() {\n sum += any[c][j];\n any_new[c + 1][j] += sum;\n }\n for j in 0..=c {\n any_new[c + 1][j] += miss[c];\n }\n miss[c] = miss_new;\n }\n dp = dp_new;\n any = any_new;\n // d!(dp, any, miss);\n }\n let s1: Mint = dp.iter().flatten().copied().sum();\n let s2: Mint = any.iter().flatten().copied().sum();\n let ans = s1 + s2;\n wln!(out, \"{}\", ans);\n}\nuse std::{cmp, fmt, marker::PhantomData, ops, sync::atomic};\npub type Mint = ModInt;\npub fn mint(x: u32) -> Mint {\n ModInt::new(x)\n}\npub trait Modulo {\n fn modulo() -> u32;\n}\nmacro_rules! modulo_impl {\n ($($Type:ident $val:tt)*) => {\n $(pub struct $Type;\n impl Modulo for $Type {\n fn modulo() -> u32 {\n $val\n }\n })*\n };\n}\nmodulo_impl!(Mod998244353 998244353 Mod1000000007 1000000007);\npub struct VarMod;\nstatic VAR_MOD: atomic::AtomicU32 = atomic::AtomicU32::new(0);\npub fn set_var_mod(m: u32) {\n VAR_MOD.store(m, atomic::Ordering::Relaxed);\n}\nimpl Modulo for VarMod {\n fn modulo() -> u32 {\n VAR_MOD.load(atomic::Ordering::Relaxed)\n }\n}\n#[repr(transparent)]\npub struct ModInt(u32, PhantomData<*const M>);\nimpl ModInt {\n pub fn new(x: u32) -> Self {\n debug_assert!(x < M::modulo());\n Self(x, PhantomData)\n }\n pub fn normalize(self) -> Self {\n if self.0 < M::modulo() {\n self\n } else {\n Self::new(self.0 % M::modulo())\n }\n }\n pub fn get(self) -> u32 {\n self.0\n }\n pub fn inv(self) -> Self {\n assert_ne!(self, Self::new(0));\n self.pow(M::modulo() - 2)\n }\n pub fn half(self) -> Self {\n Self::new(self.0 / 2 + self.0 % 2 * ((M::modulo() + 1) / 2))\n }\n pub fn modulo() -> u32 {\n M::modulo()\n }\n}\nimpl ops::Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self {\n Self::new(if self.0 == 0 { 0 } else { M::modulo() - self.0 })\n }\n}\nimpl ops::Add for ModInt {\n type Output = Self;\n fn add(self, rhs: Self) -> Self {\n let s = self.0 + rhs.0;\n Self::new(if s < M::modulo() { s } else { s - M::modulo() })\n }\n}\nimpl ops::Sub for ModInt {\n type Output = Self;\n fn sub(self, rhs: Self) -> Self {\n Self::new(if self.0 >= rhs.0 {\n self.0 - rhs.0\n } else {\n M::modulo() + self.0 - rhs.0\n })\n }\n}\nimpl ops::Mul for ModInt {\n type Output = Self;\n fn mul(self, rhs: Self) -> Self {\n Self::new((self.0 as u64 * rhs.0 as u64 % M::modulo() as u64) as u32)\n }\n}\nimpl ops::Div for ModInt {\n type Output = Self;\n fn div(self, rhs: Self) -> Self {\n self * rhs.inv()\n }\n}\nmacro_rules! op_impl {\n ($($Op:ident $op:ident $OpAssign:ident $op_assign:ident)*) => {\n $(impl ops::$Op<&Self> for ModInt {\n type Output = Self;\n fn $op(self, rhs: &Self) -> Self {\n self.$op(*rhs)\n }\n }\n impl ops::$Op> for &ModInt {\n type Output = ModInt;\n fn $op(self, rhs: ModInt) -> ModInt {\n (*self).$op(rhs)\n }\n }\n impl ops::$Op<&ModInt> for &ModInt {\n type Output = ModInt;\n fn $op(self, rhs: &ModInt) -> ModInt {\n (*self).$op(*rhs)\n }\n }\n impl ops::$OpAssign for ModInt {\n fn $op_assign(&mut self, rhs: Self) {\n *self = ops::$Op::$op(*self, rhs);\n }\n }\n impl ops::$OpAssign<&ModInt> for ModInt {\n fn $op_assign(&mut self, rhs: &ModInt) {\n self.$op_assign(*rhs);\n }\n })*\n };\n}\nop_impl! {\n Add add AddAssign add_assign\n Sub sub SubAssign sub_assign\n Mul mul MulAssign mul_assign\n Div div DivAssign div_assign\n}\nimpl std::iter::Sum for ModInt {\n fn sum>(iter: I) -> Self {\n iter.fold(ModInt::new(0), |x, y| x + y)\n }\n}\nimpl std::iter::Product for ModInt {\n fn product>(iter: I) -> Self {\n iter.fold(ModInt::new(1), |x, y| x * y)\n }\n}\npub trait Pow {\n fn pow(self, n: T) -> Self;\n}\nimpl Pow for ModInt {\n fn pow(mut self, mut n: u32) -> Self {\n let mut y = Self::new(1);\n while n > 0 {\n if n % 2 == 1 {\n y *= self;\n }\n self *= self;\n n /= 2;\n }\n y\n }\n}\nmacro_rules! mod_int_pow_impl {\n ($($T:ident)*) => {\n $(impl Pow<$T> for ModInt {\n fn pow(self, n: $T) -> Self {\n self.pow(n.rem_euclid(M::modulo() as $T - 1) as u32)\n }\n })*\n };\n}\nmod_int_pow_impl!(isize i32 i64 usize u64);\nmacro_rules! mod_int_from_impl {\n ($($T:ident)*) => {\n $(impl From<$T> for ModInt {\n #[allow(unused_comparisons)]\n fn from(x: $T) -> Self {\n if M::modulo() <= $T::max_value() as u32 {\n Self::new(x.rem_euclid(M::modulo() as $T) as u32)\n } else if x < 0 {\n Self::new((M::modulo() as i32 + x as i32) as u32)\n } else {\n Self::new(x as u32)\n }\n }\n })*\n }\n}\nmod_int_from_impl!(isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128);\nimpl Copy for ModInt {}\nimpl Clone for ModInt {\n fn clone(&self) -> Self {\n *self\n }\n}\nimpl Default for ModInt {\n fn default() -> Self {\n Self::new(0)\n }\n}\nimpl cmp::PartialEq for ModInt {\n fn eq(&self, other: &Self) -> bool {\n self.0 == other.0\n }\n}\nimpl cmp::Eq for ModInt {}\nimpl cmp::PartialOrd for ModInt {\n fn partial_cmp(&self, other: &Self) -> Option {\n self.0.partial_cmp(&other.0)\n }\n}\nimpl cmp::Ord for ModInt {\n fn cmp(&self, other: &Self) -> cmp::Ordering {\n self.0.cmp(&other.0)\n }\n}\nimpl std::hash::Hash for ModInt {\n fn hash(&self, state: &mut H) {\n self.0.hash(state);\n }\n}\nimpl fmt::Display for ModInt {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n self.0.fmt(f)\n }\n}\nimpl fmt::Debug for ModInt {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n self.0.fmt(f)\n }\n}\n\n\n// -----------------------------------------------------------------------------\nfn main() -> io::Result<()> {\n std::thread::Builder::new()\n .stack_size(1 << 26)\n .spawn(|| {\n run(\n Scanner::new(io::stdin().lock()),\n io::BufWriter::new(io::stdout().lock()),\n )\n })?\n .join()\n .unwrap();\n Ok(())\n}\n\n#[macro_export]\nmacro_rules! w {\n ($($arg:tt)*) => { write!($($arg)*).unwrap(); }\n}\n#[macro_export]\nmacro_rules! wln {\n ($dst:expr $(, $($arg:tt)*)?) => {{\n writeln!($dst $(, $($arg)*)?).unwrap();\n #[cfg(debug_assertions)]\n $dst.flush().unwrap();\n }}\n}\n#[macro_export]\nmacro_rules! w_iter {\n ($dst:expr, $fmt:expr, $iter:expr, $delim:expr) => {{\n let mut first = true;\n for elem in $iter {\n if first {\n w!($dst, $fmt, elem);\n first = false;\n } else {\n w!($dst, concat!($delim, $fmt), elem);\n }\n }\n }};\n ($dst:expr, $fmt:expr, $iter:expr) => {\n w_iter!($dst, $fmt, $iter, \" \")\n };\n}\n#[macro_export]\nmacro_rules! w_iter_ln {\n ($dst:expr, $($t:tt)*) => {{\n w_iter!($dst, $($t)*);\n wln!($dst);\n }}\n}\n#[macro_export]\nmacro_rules! e {\n ($($t:tt)*) => {\n #[cfg(debug_assertions)]\n eprint!($($t)*)\n }\n}\n#[macro_export]\nmacro_rules! eln {\n ($($t:tt)*) => {\n #[cfg(debug_assertions)]\n eprintln!($($t)*)\n }\n}\n#[macro_export]\nmacro_rules! __tstr {\n ($h:expr $(, $t:expr)+) => { concat!(__tstr!($($t),+), \", \", __tstr!(@)) };\n ($h:expr) => { concat!(__tstr!(), \" \", __tstr!(@)) };\n () => { \"\\x1B[94m[{}:{}]\\x1B[0m\" };\n (@) => { \"\\x1B[1;92m{}\\x1B[0m = {:?}\" }\n}\n#[macro_export]\nmacro_rules! d {\n ($($a:expr),*) => { eln!(__tstr!($($a),*), file!(), line!(), $(stringify!($a), $a),*) };\n}\n\npub mod kyoproio {\n use std::{\n fmt::Display,\n io::{self, prelude::*},\n iter::FromIterator,\n marker::PhantomData,\n mem::{self, MaybeUninit},\n str,\n };\n\n pub trait Input {\n fn bytes(&mut self) -> &[u8];\n fn str(&mut self) -> &str {\n str::from_utf8(self.bytes()).unwrap()\n }\n fn parse(&mut self) -> T {\n T::parse(self)\n }\n fn parse_iter(&mut self) -> ParseIter {\n ParseIter(self, PhantomData)\n }\n fn collect>(&mut self, n: usize) -> B {\n self.parse_iter().take(n).collect()\n }\n fn map U, B: FromIterator>(&mut self, n: usize, f: F) -> B {\n self.parse_iter().take(n).map(f).collect()\n }\n }\n impl Input for &mut I {\n fn bytes(&mut self) -> &[u8] {\n (**self).bytes()\n }\n }\n pub struct Scanner {\n src: R,\n buf: Vec,\n pos: usize,\n len: usize,\n }\n impl Scanner {\n pub fn new(src: R) -> Self {\n Self {\n src,\n buf: vec![0; 1 << 16],\n pos: 0,\n len: 0,\n }\n }\n fn read(&mut self) -> usize {\n if self.pos > 0 {\n self.buf.copy_within(self.pos..self.len, 0);\n self.len -= self.pos;\n self.pos = 0;\n } else if self.len >= self.buf.len() {\n self.buf.resize(2 * self.buf.len(), 0);\n }\n let n = self.src.read(&mut self.buf[self.len..]).unwrap();\n self.len += n;\n assert!(self.len <= self.buf.len());\n n\n }\n }\n impl Input for Scanner {\n fn bytes(&mut self) -> &[u8] {\n loop {\n while let Some(d) = unsafe { self.buf.get_unchecked(self.pos..self.len) }\n .iter()\n .position(u8::is_ascii_whitespace)\n {\n let p = self.pos;\n self.pos += d + 1;\n if d > 0 {\n return unsafe { self.buf.get_unchecked(p..p + d) };\n }\n }\n if self.read() == 0 {\n let p = self.pos;\n self.pos = self.len;\n return unsafe { self.buf.get_unchecked(p..self.len) };\n }\n }\n }\n }\n pub struct ParseIter<'a, T, I: ?Sized>(&'a mut I, PhantomData<*const T>);\n impl<'a, T: Parse, I: Input + ?Sized> Iterator for ParseIter<'a, T, I> {\n type Item = T;\n fn next(&mut self) -> Option {\n Some(self.0.parse())\n }\n fn size_hint(&self) -> (usize, Option) {\n (!0, None)\n }\n }\n pub trait Parse: Sized {\n fn parse(src: &mut I) -> Self;\n }\n macro_rules! from_bytes {\n ($($T:ty)*) => {$(\n impl Parse for $T {\n fn parse(src: &mut I) -> Self {\n src.bytes().into()\n }\n }\n )*}\n }\n from_bytes!(Vec Box<[u8]>);\n macro_rules! from_str {\n ($($T:ty)*) => {$(\n impl Parse for $T {\n fn parse(src: &mut I) -> Self {\n src.str().parse::<$T>().unwrap()\n }\n }\n )*}\n }\n from_str!(String char bool f32 f64);\n macro_rules! int {\n ($($I:ty: $U:ty)*) => {$(\n impl Parse for $I {\n fn parse(src: &mut I) -> Self {\n let f = |s: &[u8]| s.iter().fold(0, |x, b| 10 * x + (b & 0xf) as $I);\n let s = src.bytes();\n if let Some((&b'-', t)) = s.split_first() { -f(t) } else { f(s) }\n }\n }\n impl Parse for $U {\n fn parse(src: &mut I) -> Self {\n src.bytes().iter().fold(0, |x, b| 10 * x + (b & 0xf) as $U)\n }\n }\n )*}\n }\n int!(isize:usize i8:u8 i16:u16 i32:u32 i64:u64 i128:u128);\n macro_rules! tuple {\n ($H:ident $($T:ident)*) => {\n impl<$H: Parse, $($T: Parse),*> Parse for ($H, $($T),*) {\n fn parse(src: &mut I) -> Self {\n ($H::parse(src), $($T::parse(src)),*)\n }\n }\n tuple!($($T)*);\n };\n () => {}\n }\n tuple!(A B C D E F G);\n macro_rules! array {\n ($($N:literal)*) => {$(\n impl Parse for [T; $N] {\n fn parse(src: &mut I) -> Self {\n unsafe {\n let mut arr: [MaybeUninit; $N] = MaybeUninit::uninit().assume_init();\n for elem in &mut arr {\n *elem = MaybeUninit::new(src.parse());\n }\n mem::transmute_copy(&arr)\n }\n }\n }\n )*}\n }\n array!(1 2 3 4 5 6 7 8);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "1b5d8e3efafb1684c209ed872db795c7", "src_uid": "4f0e0d1deef0761a46b64de3eb98e774", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\r\nmod modint {\r\n\r\n #[allow(dead_code)]\r\n pub struct Mod;\r\n impl ConstantModulo for Mod {\r\n const MOD: u32 = 1_000_000_007;\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub struct StaticMod;\r\n static mut STATIC_MOD: u32 = 0;\r\n impl Modulo for StaticMod {\r\n fn modulo() -> u32 {\r\n unsafe { STATIC_MOD }\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl StaticMod {\r\n pub fn set_modulo(p: u32) {\r\n unsafe {\r\n STATIC_MOD = p;\r\n }\r\n }\r\n }\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n }\r\n\r\n pub trait ConstantModulo {\r\n const MOD: u32;\r\n }\r\n\r\n impl Modulo for T\r\n where\r\n T: ConstantModulo,\r\n {\r\n fn modulo() -> u32 {\r\n T::MOD\r\n }\r\n }\r\n\r\n pub struct ModInt(pub u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::new_unchecked(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n ModInt::new_unchecked(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = T::modulo() + self.0 - rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n ModInt::new_unchecked(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n let v = self.0 as u64 * rhs.0 as u64 % T::modulo() as u64;\r\n ModInt::new_unchecked(v as u32)\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::new_unchecked(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n ModInt::new_unchecked(0)\r\n }\r\n pub fn one() -> Self {\r\n ModInt::new_unchecked(1)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new(d: u32) -> Self {\r\n ModInt::new_unchecked(d % T::modulo())\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n pub fn inv(&self) -> Self {\r\n assert!(self.0 != 0);\r\n self.pow(T::modulo() as u64 - 2)\r\n }\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n// ---------- begin Precalc ----------\r\nmod precalc {\r\n use super::modint::*;\r\n #[allow(dead_code)]\r\n pub struct Precalc {\r\n inv: Vec>,\r\n fact: Vec>,\r\n ifact: Vec>,\r\n }\r\n #[allow(dead_code)]\r\n impl Precalc {\r\n pub fn new(n: usize) -> Precalc {\r\n let mut inv = vec![ModInt::one(); n + 1];\r\n let mut fact = vec![ModInt::one(); n + 1];\r\n let mut ifact = vec![ModInt::one(); n + 1];\r\n for i in 2..(n + 1) {\r\n fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);\r\n }\r\n ifact[n] = fact[n].inv();\r\n if n > 0 {\r\n inv[n] = ifact[n] * fact[n - 1];\r\n }\r\n for i in (1..n).rev() {\r\n ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);\r\n inv[i] = ifact[i] * fact[i - 1];\r\n }\r\n Precalc {\r\n inv: inv,\r\n fact: fact,\r\n ifact: ifact,\r\n }\r\n }\r\n pub fn inv(&self, n: usize) -> ModInt {\r\n assert!(n > 0);\r\n self.inv[n]\r\n }\r\n pub fn fact(&self, n: usize) -> ModInt {\r\n self.fact[n]\r\n }\r\n pub fn ifact(&self, n: usize) -> ModInt {\r\n self.ifact[n]\r\n }\r\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[n - k]\r\n }\r\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\r\n if k > n {\r\n return ModInt::zero();\r\n }\r\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\r\n }\r\n }\r\n}\r\n// ---------- end Precalc ----------\r\n\r\nuse modint::*;\r\ntype M = ModInt;\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nfn run() {\r\n input! {\r\n n: usize,\r\n m: u32,\r\n }\r\n StaticMod::set_modulo(m);\r\n let pc = precalc::Precalc::new(n);\r\n let mut pow = vec![M::one(); n + 1];\r\n let two = M::new(2);\r\n for i in 1..=n {\r\n pow[i] = pow[i - 1] * two;\r\n }\r\n // dp[a][b]: \u6700\u5f8c\u306e\u7a7a\u767d\u304ca, b\u500b\u7f6e\u3044\u305f\r\n let mut dp = vec![vec![M::zero(); n + 2]; n + 2];\r\n dp[0][0] = M::one();\r\n for i in 0..=n {\r\n for j in 0..=i {\r\n let way = dp[i][j];\r\n if way.is_zero() {\r\n continue;\r\n }\r\n for k in 1..=(n - i) {\r\n dp[i + k + 1][j + k] += pow[k - 1] * way * pc.comb(j + k, j);\r\n }\r\n }\r\n }\r\n let mut ans = M::zero();\r\n for dp in dp[n + 1].iter() {\r\n ans += *dp;\r\n }\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "6524c36ef92a7c2782fec2590c0b5713", "src_uid": "4f0e0d1deef0761a46b64de3eb98e774", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// codesnip-guard: main\nfn main() {\n #![allow(unused_imports, unused_macros)]\n prepare_io!(_in_buf, scanner, _out);\n macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n scan!(scanner, n, m);\n mint_basic::DynModuloU32::set_mod(m as _);\n let f = MemorizedFactorial::new(n * 2);\n let mut ans = M::zero();\n let mut dp = vec![vec![M::zero(); n + 1]; n + 1];\n let mut pre = vec![M::zero(); n + 1];\n for i in 1..=n {\n for j in 0..i {\n pre[i] += f.inv_fact[j] * f.inv_fact[i - j - 1];\n }\n pre[i] *= M::from(i).inv();\n }\n // processed, sikiri\n dp[0][0] = M::one();\n for i in 0..n {\n for j in 0..=i {\n let d = dp[i][j];\n if d.is_zero() {\n continue;\n }\n for k in 1..=n - i {\n let mut ni = i + k;\n let mut nj = j;\n if i > 0 {\n ni += 1;\n nj += 1;\n }\n if ni <= n {\n dp[ni][nj] += d * pre[k];\n }\n }\n }\n }\n for j in 0..=n {\n ans += dp[n][j] * f.fact[n - j];\n }\n println!(\"{}\", ans);\n}\npub type M = mint_basic::DynMIntU32;\n#[macro_export]\nmacro_rules! prepare_io {\n ($ in_buf : ident , $ scanner : ident , $ out : ident) => {\n use std::io::{stdout, BufWriter, Write as _};\n let $in_buf = read_stdin_all_unchecked();\n let mut $scanner = Scanner::new(&$in_buf);\n let $out = stdout();\n let mut $out = BufWriter::new($out.lock());\n };\n}\n// codesnip-guard: _echo\npub fn echo(\n mut writer: impl std::io::Write,\n iter: impl IntoIterator,\n sep: impl std::fmt::Display,\n) -> std::io::Result<()> {\n let mut iter = iter.into_iter();\n if let Some(item) = iter.next() {\n write!(writer, \"{}\", item)?;\n }\n for item in iter {\n write!(writer, \"{}{}\", sep, item)?;\n }\n writeln!(writer)\n}\n// codesnip-guard: scanner\npub fn read_stdin_all_unchecked() -> String {\n use std::io::Read as _;\n let mut buf = Vec::new();\n std::io::stdin().read_to_end(&mut buf).expect(\"io error\");\n unsafe { String::from_utf8_unchecked(buf) }\n}\npub fn read_stdin_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).expect(\"io error\");\n s\n}\npub trait IterScan: Sized {\n type Output;\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option;\n}\npub trait MarkedIterScan: Sized {\n type Output;\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option;\n}\n#[derive(Clone, Debug)]\npub struct Scanner<'a> {\n iter: std::str::SplitAsciiWhitespace<'a>,\n}\nmod scanner_impls {\n use super::*;\n impl<'a> Scanner<'a> {\n #[inline]\n pub fn new(s: &'a str) -> Self {\n let iter = s.split_ascii_whitespace();\n Self { iter }\n }\n #[inline]\n pub fn scan(&mut self) -> ::Output {\n ::scan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn mscan(&mut self, marker: T) -> ::Output {\n marker.mscan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn scan_vec(&mut self, size: usize) -> Vec<::Output> {\n (0..size)\n .map(|_| ::scan(&mut self.iter).expect(\"scan error\"))\n .collect()\n }\n #[inline]\n pub fn iter<'b, T: IterScan>(&'b mut self) -> ScannerIter<'a, 'b, T> {\n ScannerIter {\n inner: self,\n _marker: std::marker::PhantomData,\n }\n }\n }\n macro_rules ! iter_scan_impls { ($ ($ t : ty) *) => { $ (impl IterScan for $ t { type Output = Self ; # [inline] fn scan <'a , I : Iterator < Item = &'a str >> (iter : & mut I) -> Option < Self > { iter . next () ?. parse ::<$ t > () . ok () } }) * } ; }\n iter_scan_impls ! (char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);\n macro_rules ! iter_scan_tuple_impl { ($ ($ T : ident) *) => { impl <$ ($ T : IterScan) ,*> IterScan for ($ ($ T ,) *) { type Output = ($ (<$ T as IterScan >:: Output ,) *) ; # [inline] fn scan <'a , It : Iterator < Item = &'a str >> (_iter : & mut It) -> Option < Self :: Output > { Some (($ (<$ T as IterScan >:: scan (_iter) ?,) *)) } } } ; }\n iter_scan_tuple_impl!();\n iter_scan_tuple_impl!(A);\n iter_scan_tuple_impl ! (A B);\n iter_scan_tuple_impl ! (A B C);\n iter_scan_tuple_impl ! (A B C D);\n iter_scan_tuple_impl ! (A B C D E);\n iter_scan_tuple_impl ! (A B C D E F);\n iter_scan_tuple_impl ! (A B C D E F G);\n iter_scan_tuple_impl ! (A B C D E F G H);\n iter_scan_tuple_impl ! (A B C D E F G H I);\n iter_scan_tuple_impl ! (A B C D E F G H I J);\n iter_scan_tuple_impl ! (A B C D E F G H I J K);\n pub struct ScannerIter<'a, 'b, T> {\n inner: &'b mut Scanner<'a>,\n _marker: std::marker::PhantomData T>,\n }\n impl<'a, 'b, T: IterScan> Iterator for ScannerIter<'a, 'b, T> {\n type Item = ::Output;\n #[inline]\n fn next(&mut self) -> Option {\n ::scan(&mut self.inner.iter)\n }\n }\n}\n#[derive(Debug, Copy, Clone)]\npub struct Usize1;\n#[derive(Debug, Copy, Clone)]\npub struct CharWithBase(pub char);\n#[derive(Debug, Copy, Clone)]\npub struct Chars;\n#[derive(Debug, Copy, Clone)]\npub struct CharsWithBase(pub char);\n#[derive(Debug, Copy, Clone)]\npub struct Collect::Output>> {\n size: usize,\n _marker: std::marker::PhantomData (T, B)>,\n}\nmod marker_impls {\n use super::*;\n use std::{iter::FromIterator, marker::PhantomData};\n impl IterScan for Usize1 {\n type Output = usize;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n ::scan(iter)?.checked_sub(1)\n }\n }\n impl MarkedIterScan for CharWithBase {\n type Output = usize;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some((::scan(iter)? as u8 - self.0 as u8) as usize)\n }\n }\n impl IterScan for Chars {\n type Output = Vec;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(iter.next()?.chars().collect())\n }\n }\n impl MarkedIterScan for CharsWithBase {\n type Output = Vec;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n iter.next()?\n .chars()\n .map(|c| (c as u8 - self.0 as u8) as usize)\n .collect(),\n )\n }\n }\n impl::Output>> Collect {\n pub fn new(size: usize) -> Self {\n Self {\n size,\n _marker: PhantomData,\n }\n }\n }\n impl::Output>> MarkedIterScan for Collect {\n type Output = B;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n (0..self.size)\n .map(|_| ::scan(iter).expect(\"scan error\"))\n .collect::(),\n )\n }\n }\n}\n#[macro_export]\nmacro_rules ! scan_value { ($ scanner : expr , ($ ($ t : tt) ,*)) => { ($ ($ crate :: scan_value ! ($ scanner , $ t)) ,*) } ; ($ scanner : expr , [$ t : tt ; $ len : expr]) => { (0 ..$ len) . map (| _ | $ crate :: scan_value ! ($ scanner , $ t)) . collect ::< Vec < _ >> () } ; ($ scanner : expr , [$ t : ty ; $ len : expr]) => { $ scanner . scan_vec ::<$ t > ($ len) } ; ($ scanner : expr , [$ t : ty]) => { $ scanner . iter ::<$ t > () } ; ($ scanner : expr , { $ e : expr }) => { $ scanner . mscan ($ e) } ; ($ scanner : expr , $ t : ty) => { $ scanner . scan ::<$ t > () } ; }\n#[macro_export]\nmacro_rules ! scan { ($ scanner : expr) => { } ; ($ scanner : expr ,) => { } ; ($ scanner : expr , mut $ var : tt : $ t : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , $ var : tt : $ t : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , mut $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , mut $ var : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , $ var : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , mut $ var : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; }\n// codesnip-guard: MInt\npub mod mint_basic {\n use super::*;\n #[macro_export]\n macro_rules ! define_basic_mintbase { ($ name : ident , $ m : expr , $ basety : ty , $ signedty : ty , $ upperty : ty , [$ ($ unsigned : ty) ,*] , [$ ($ signed : ty) ,*]) => { pub struct $ name ; impl MIntBase for $ name { type Inner = $ basety ; # [inline] fn get_mod () -> Self :: Inner { $ m } # [inline] fn mod_zero () -> Self :: Inner { 0 } # [inline] fn mod_one () -> Self :: Inner { 1 } # [inline] fn mod_add (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { let z = x + y ; let m = Self :: get_mod () ; if z >= m { z - m } else { z } } # [inline] fn mod_sub (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { if x < y { x + Self :: get_mod () - y } else { x - y } } # [inline] fn mod_mul (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { (x as $ upperty * y as $ upperty % Self :: get_mod () as $ upperty) as $ basety } # [inline] fn mod_div (x : Self :: Inner , y : Self :: Inner) -> Self :: Inner { Self :: mod_mul (x , Self :: mod_inv (y)) } # [inline] fn mod_neg (x : Self :: Inner) -> Self :: Inner { if x == 0 { 0 } else { Self :: get_mod () - x } } fn mod_inv (x : Self :: Inner) -> Self :: Inner { let p = Self :: get_mod () as $ signedty ; let (mut a , mut b) = (x as $ signedty , p) ; let (mut u , mut x) = (1 , 0) ; while a != 0 { let k = b / a ; x -= k * u ; b -= k * a ; std :: mem :: swap (& mut x , & mut u) ; std :: mem :: swap (& mut b , & mut a) ; } (if x < 0 { x + p } else { x }) as _ } } $ (impl MIntConvert <$ unsigned > for $ name { # [inline] fn from (x : $ unsigned) -> Self :: Inner { (x % < Self as MIntBase >:: get_mod () as $ unsigned) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ unsigned { x as $ unsigned } # [inline] fn mod_into () -> $ unsigned { < Self as MIntBase >:: get_mod () as $ unsigned } }) * $ (impl MIntConvert <$ signed > for $ name { # [inline] fn from (x : $ signed) -> Self :: Inner { let x = x % < Self as MIntBase >:: get_mod () as $ signed ; if x < 0 { (x + < Self as MIntBase >:: get_mod () as $ signed) as $ basety } else { x as $ basety } } # [inline] fn into (x : Self :: Inner) -> $ signed { x as $ signed } # [inline] fn mod_into () -> $ signed { < Self as MIntBase >:: get_mod () as $ signed } }) * } ; }\n #[macro_export]\n macro_rules ! define_basic_mint32 { ($ ([$ name : ident , $ m : expr , $ mint_name : ident]) ,*) => { $ (crate :: define_basic_mintbase ! ($ name , $ m , u32 , i32 , u64 , [u32 , u64 , u128 , usize] , [i32 , i64 , i128 , isize]) ; pub type $ mint_name = MInt <$ name >;) * } ; }\n define_basic_mint32!(\n [Modulo998244353, 998_244_353, MInt998244353],\n [Modulo1000000007, 1_000_000_007, MInt1000000007],\n [Modulo1000000009, 1_000_000_009, MInt1000000009],\n [\n DynModuloU32,\n DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() }),\n DynMIntU32\n ]\n );\n thread_local ! (static DYN_MODULUS_U32 : std :: cell :: UnsafeCell < u32 > = std :: cell :: UnsafeCell :: new (1_000_000_007));\n impl DynModuloU32 {\n pub fn set_mod(m: u32) {\n DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() = m })\n }\n }\n thread_local ! (static DYN_MODULUS_U64 : std :: cell :: UnsafeCell < u64 > = std :: cell :: UnsafeCell :: new (1_000_000_007));\n define_basic_mintbase!(\n DynModuloU64,\n DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() }),\n u64,\n i64,\n u128,\n [u64, u128, usize],\n [i64, i128, isize]\n );\n impl DynModuloU64 {\n pub fn set_mod(m: u64) {\n DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() = m })\n }\n }\n pub type DynMIntU64 = MInt;\n pub struct Modulo2;\n impl MIntBase for Modulo2 {\n type Inner = u32;\n #[inline]\n fn get_mod() -> Self::Inner {\n 2\n }\n #[inline]\n fn mod_zero() -> Self::Inner {\n 0\n }\n #[inline]\n fn mod_one() -> Self::Inner {\n 1\n }\n #[inline]\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x ^ y\n }\n #[inline]\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n x | y\n }\n #[inline]\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n assert_ne!(y, 0);\n x\n }\n #[inline]\n fn mod_neg(x: Self::Inner) -> Self::Inner {\n x\n }\n #[inline]\n fn mod_inv(x: Self::Inner) -> Self::Inner {\n assert_ne!(x, 0);\n x\n }\n #[inline]\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n if y == 0 {\n 1\n } else {\n x\n }\n }\n }\n macro_rules ! impl_to_mint_base_for_modulo2 { ($ name : ident , $ basety : ty , [$ ($ t : ty) ,*]) => { $ (impl MIntConvert <$ t > for $ name { # [inline] fn from (x : $ t) -> Self :: Inner { (x & 1) as $ basety } # [inline] fn into (x : Self :: Inner) -> $ t { x as $ t } # [inline] fn mod_into () -> $ t { 1 } }) * } ; }\n impl_to_mint_base_for_modulo2!(\n Modulo2,\n u32,\n [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]\n );\n pub type MInt2 = MInt;\n}\n// codesnip-guard: MIntBase\n#[repr(transparent)]\npub struct MInt\nwhere\n M: MIntBase,\n{\n x: M::Inner,\n _marker: std::marker::PhantomData M>,\n}\npub trait MIntBase {\n type Inner: Sized + Copy + Eq + std::fmt::Debug + std::hash::Hash;\n fn get_mod() -> Self::Inner;\n fn mod_zero() -> Self::Inner;\n fn mod_one() -> Self::Inner;\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_neg(x: Self::Inner) -> Self::Inner;\n fn mod_inv(x: Self::Inner) -> Self::Inner;\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n let (mut x, mut y, mut z) = (x, y, Self::mod_one());\n while y > 0 {\n if y & 1 == 1 {\n z = Self::mod_mul(z, x);\n }\n x = Self::mod_mul(x, x);\n y >>= 1;\n }\n z\n }\n}\npub trait MIntConvert::Inner>: MIntBase {\n fn from(x: T) -> ::Inner;\n fn into(x: ::Inner) -> T;\n fn mod_into() -> T;\n}\nmod mint_base {\n use super::*;\n use std::{\n fmt::{self, Debug, Display},\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n };\n impl MInt\n where\n M: MIntConvert,\n {\n #[inline]\n pub fn new(x: M::Inner) -> Self {\n Self::new_unchecked(>::from(x))\n }\n #[inline]\n pub fn inner(self) -> M::Inner {\n >::into(self.x)\n }\n }\n impl MInt\n where\n M: MIntBase,\n {\n #[inline]\n pub fn new_unchecked(x: M::Inner) -> Self {\n Self {\n x,\n _marker: PhantomData,\n }\n }\n #[inline]\n pub fn get_mod() -> M::Inner {\n M::get_mod()\n }\n #[inline]\n pub fn pow(self, y: usize) -> Self {\n Self::new_unchecked(M::mod_pow(self.x, y))\n }\n #[inline]\n pub fn inv(self) -> Self {\n Self::new_unchecked(M::mod_inv(self.x))\n }\n }\n impl Clone for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn clone(&self) -> Self {\n Self {\n x: Clone::clone(&self.x),\n _marker: PhantomData,\n }\n }\n }\n impl Copy for MInt where M: MIntBase {}\n impl Debug for MInt\n where\n M: MIntBase,\n {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Debug::fmt(&self.x, f)\n }\n }\n impl Default for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn default() -> Self {\n ::zero()\n }\n }\n impl PartialEq for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n PartialEq::eq(&self.x, &other.x)\n }\n }\n impl Eq for MInt where M: MIntBase {}\n impl Hash for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn hash(&self, state: &mut H) {\n Hash::hash(&self.x, state)\n }\n }\n macro_rules ! impl_mint_from { ($ ($ t : ty) ,*) => { $ (impl < M > From <$ t > for MInt < M > where M : MIntConvert <$ t >, { # [inline] fn from (x : $ t) -> Self { Self :: new_unchecked (< M as MIntConvert <$ t >>:: from (x)) } } impl < M > From < MInt < M >> for $ t where M : MIntConvert <$ t >, { # [inline] fn from (x : MInt < M >) -> $ t { < M as MIntConvert <$ t >>:: into (x . x) } }) * } ; }\n impl_mint_from!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n impl Zero for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn zero() -> Self {\n Self::new_unchecked(M::mod_zero())\n }\n }\n impl One for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn one() -> Self {\n Self::new_unchecked(M::mod_one())\n }\n }\n impl Add for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_add(self.x, rhs.x))\n }\n }\n impl Sub for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_sub(self.x, rhs.x))\n }\n }\n impl Mul for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_mul(self.x, rhs.x))\n }\n }\n impl Div for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_div(self.x, rhs.x))\n }\n }\n impl Neg for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn neg(self) -> Self::Output {\n Self::new_unchecked(M::mod_neg(self.x))\n }\n }\n impl Sum for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl Product for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl<'a, M: 'a> Sum<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl<'a, M: 'a> Product<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl Display for MInt\n where\n M: MIntConvert,\n M::Inner: Display,\n {\n fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {\n write!(f, \"{}\", self.inner())\n }\n }\n impl FromStr for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Err = ::Err;\n #[inline]\n fn from_str(s: &str) -> Result {\n s.parse::().map(Self::new)\n }\n }\n impl IterScan for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Output = Self;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n iter.next()?.parse::>().ok()\n }\n }\n macro_rules! impl_mint_ref_binop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp<$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: $t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, other)\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(self, *other)\n }\n }\n impl $imp<&$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, *other)\n }\n }\n };\n }\n impl_mint_ref_binop!(Add, add, MInt);\n impl_mint_ref_binop!(Sub, sub, MInt);\n impl_mint_ref_binop!(Mul, mul, MInt);\n impl_mint_ref_binop!(Div, div, MInt);\n macro_rules! impl_mint_ref_unop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp>::Output;\n #[inline]\n fn $method(self) -> <$t as $imp>::Output {\n $imp::$method(*self)\n }\n }\n };\n }\n impl_mint_ref_unop!(Neg, neg, MInt);\n macro_rules! impl_mint_ref_op_assign {\n ($ imp : ident , $ method : ident , $ t : ty , $ fromimp : ident , $ frommethod : ident) => {\n impl $imp<$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, rhs: $t) {\n *self = $fromimp::$frommethod(*self, rhs);\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, other: &$t) {\n $imp::$method(self, *other);\n }\n }\n };\n }\n impl_mint_ref_op_assign!(AddAssign, add_assign, MInt, Add, add);\n impl_mint_ref_op_assign!(SubAssign, sub_assign, MInt, Sub, sub);\n impl_mint_ref_op_assign!(MulAssign, mul_assign, MInt, Mul, mul);\n impl_mint_ref_op_assign!(DivAssign, div_assign, MInt, Div, div);\n}\n// codesnip-guard: zero_one\npub trait Zero: Sized {\n fn zero() -> Self;\n #[inline]\n fn is_zero(&self) -> bool\n where\n Self: PartialEq,\n {\n self == &Self::zero()\n }\n #[inline]\n fn set_zero(&mut self) {\n *self = Self::zero();\n }\n}\npub trait One: Sized {\n fn one() -> Self;\n #[inline]\n fn is_one(&self) -> bool\n where\n Self: PartialEq,\n {\n self == &Self::one()\n }\n #[inline]\n fn set_one(&mut self) {\n *self = Self::one();\n }\n}\nmacro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { fn $ method () -> Self { $ e } }) *) * } ; }\nzero_one_impls ! ({ Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 0 } { Zero zero f32 f64 , 0. } { One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 1 } { One one f32 f64 , 1. });\n// codesnip-guard: factorial\n#[derive(Clone, Debug)]\npub struct MemorizedFactorial> {\n pub fact: Vec>,\n pub inv_fact: Vec>,\n}\nimpl> MemorizedFactorial {\n pub fn new(max_n: usize) -> Self {\n let mut fact = vec![MInt::one(); max_n + 1];\n let mut inv_fact = vec![MInt::one(); max_n + 1];\n for i in 2..=max_n {\n fact[i] = fact[i - 1] * MInt::from(i);\n }\n inv_fact[max_n] = fact[max_n].inv();\n for i in (3..=max_n).rev() {\n inv_fact[i - 1] = inv_fact[i] * MInt::from(i);\n }\n Self { fact, inv_fact }\n }\n #[inline]\n pub fn combination(&self, n: usize, r: usize) -> MInt {\n debug_assert!(n < self.fact.len());\n if r <= n {\n self.fact[n] * self.inv_fact[r] * self.inv_fact[n - r]\n } else {\n MInt::zero()\n }\n }\n #[inline]\n pub fn permutation(&self, n: usize, r: usize) -> MInt {\n debug_assert!(n < self.fact.len());\n if r <= n {\n self.fact[n] * self.inv_fact[n - r]\n } else {\n MInt::zero()\n }\n }\n #[inline]\n pub fn homogeneous_product(&self, n: usize, r: usize) -> MInt {\n debug_assert!(n + r < self.fact.len() + 1);\n if n != 0 && r != 0 {\n self.combination(n + r - 1, r)\n } else {\n MInt::one()\n }\n }\n #[inline]\n pub fn inv(&self, n: usize) -> MInt {\n debug_assert!(n < self.fact.len());\n debug_assert!(n > 0);\n self.inv_fact[n] * self.fact[n - 1]\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "6672dd7461d360873f1195e6cc06bd40", "src_uid": "4f0e0d1deef0761a46b64de3eb98e774", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn readstring() -> String {\n read_string_from_buffer(&io::stdin())\n}\n\nfn readint() -> i32 {\n read_int_from_buffer(&io::stdin())\n}\n\nfn read_string_from_buffer(buf: &io::Stdin) -> String {\n let mut input_text = String::new();\n buf.read_line(&mut input_text)\n .expect(\"failed to read from stdin\");\n input_text.trim_right().to_string()\n}\n\nfn read_int_from_buffer(buf: &io::Stdin) -> i32 {\n read_string_from_buffer(buf)\n .parse::()\n .expect(\"couldn't parse data to an integer\")\n}\n\nfn read_line_of_integers() -> Vec {\n readstring()\n .split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect()\n}\n\nfn read_line_of_longs() -> Vec {\n readstring()\n .split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect()\n}\n\nfn main() {\n let (x, y) = (readint(), readint());\n let z = (y - x).abs() / 2;\n let r = (y - x).abs() % 2;\n println!(\"{}\", z * (z + 1) + r * (z + 1));\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "brute force"], "code_uid": "6c206bd34d31700278512320fd0dddc5", "src_uid": "d3f2c6886ed104d7baba8dd7b70058da", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io;\n use std::io::prelude::*;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let a: i32 = it.next().unwrap().parse().unwrap();\n let b: i32 = it.next().unwrap().parse().unwrap();\n\n let d = (b - a).abs();\n\n let q = d / 2;\n let r = d % 2;\n\n let ans = q * (q + 1) + if r == 1 { q + 1 } else { 0 };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation", "brute force"], "code_uid": "a356b69e878f156bb824cd00afc60c94", "src_uid": "d3f2c6886ed104d7baba8dd7b70058da", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n//const INF: i32 = 0x3f3f3f3f;\n\nstruct Scanner {\n buffer: std::collections::VecDeque\n}\n\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn next(&mut self) -> T {\n while self.buffer.is_empty() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n self.buffer = input.split_whitespace()\n .map(ToString::to_string).collect();\n }\n let front = self.buffer.pop_front().unwrap();\n front.parse::().ok().unwrap()\n }\n}\n\nfn main1() {\n let mut scan = Scanner::new();\n let n = scan.next::();\n \n let mut lo = 99;\n let mut rep = 0;\n for _ in 0..n {\n let a = scan.next::();\n if lo > a {\n lo = a;\n rep = 0;\n }\n if lo == a {\n rep += 1;\n }\n }\n if rep <= n / 2 {\n println!(\"Alice\");\n } else {\n println!(\"Bob\");\n }\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}", "lang_cluster": "Rust", "tags": ["games"], "code_uid": "9639baaa31e6a1f3a5e448972ada82b5", "src_uid": "4b9cf82967aa8441e9af3db3101161e9", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet n = rin.u();\n\tlet mut a = rin.vi(n);\n\ta.sort();\n\tlet mut c = 0;\n\twhile c < n && a[0] == a[c] {\n\t\tc += 1;\n\t}\n\tif c <= n/2 {\n\t\twriteln!(rout, \"Alice\").ok();\n\t} else {\n\t\twriteln!(rout, \"Bob\").ok();\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["games"], "code_uid": "1871b8a52af6ef61ac85c7f1495a1447", "src_uid": "4b9cf82967aa8441e9af3db3101161e9", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n a: [usize; n],\n }\n let mut a = a;\n a.sort();\n let ans = if a[0] == a[n / 2] {\n \"Bob\"\n } else {\n \"Alice\"\n };\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["games"], "code_uid": "90fb939b4b95cb135dae1228e39b5172", "src_uid": "4b9cf82967aa8441e9af3db3101161e9", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut good = true;\n for _ in 0..8 {\n let line: Vec = scan.next::().chars().collect();\n for j in 1..8 {\n good = good && line[j] != line[j - 1];\n }\n }\n println!(\"{}\", if good { \"YES\" } else { \"NO\" });\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings"], "code_uid": "2c73e915088cdf27fa4af5f408d33bb3", "src_uid": "ca65e023be092b2ce25599f52acc1a67", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let mut arr = vec!();\n for _ in 0..8 {\n arr.push(parse())\n }\n for i in arr {\n if !is_alternate(i){\n println!(\"NO\");\n return;\n }\n }\n println!(\"YES\")\n}\nenum Chess{\n W,\n B\n}\n\nfn parse()->Vec{\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let mut vec = vec!();\n\n for c in input.trim().chars(){\n if 'W' ==c{\n vec.push(Chess::W)\n }else{\n vec.push(Chess::B)\n }\n }\n vec\n}\nfn is_alternate(arr:Vec)->bool{\n for c in 0..arr.len()-1{\n match arr[c]{\n Chess::W => match arr[c+1]{\n Chess::W => return false,\n _=> continue\n },\n Chess::B=>match arr[c+1]{\n Chess::W=> continue,\n _=> return false\n }\n } \n } \n true\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings"], "code_uid": "436a7a5cdc1503eace6a529f7213c1e4", "src_uid": "ca65e023be092b2ce25599f52acc1a67", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::collections::{HashSet, HashMap};\nuse std::cmp::{min,max};\nuse std::io;\nuse std::str;\n \nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: vec![], buf_iter: \"\".split_whitespace() }\n }\n fn token(&mut self) -> T {\n loop {\n // If we have another token in this line\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\"); // calls parse::() on the current token and returns it.\n }\n\n // If we do not have another token in the line then\n // we should go to the next line.\n self.buf_str.clear(); // empty out the buffer that holds the current line\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\"); // read a new line into the buffer\n\n // create an iterator over the white space delimited strings of the current line\n self.buf_iter = unsafe { \n let slice = str::from_utf8_unchecked(&self.buf_str); // makes a string from utf8 characters in the current line\n std::mem::transmute(slice.split_whitespace()) // transmutes the memory in place \n }\n }\n }\n}\n \nfn solve(scan: &mut Scanner, out: &mut W) {\n let mut ans = \"YES\";\n for _ in 0..8 {\n let row = scan.token::();\n if !alternates(row) {\n ans = \"NO\";\n }\n }\n writeln!(out, \"{}\", ans);\n}\n\nfn alternates(s: String) -> bool {\n s.chars().collect::>().windows(2).all(|win| win[0] != win[1])\n}\n \nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings"], "code_uid": "fa078bfb0e000e6a0587a75fe45534ba", "src_uid": "ca65e023be092b2ce25599f52acc1a67", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let x1: i32 = scan.token();\n let y1: i32 = scan.token();\n let x2: i32 = scan.token();\n let y2: i32 = scan.token();\n let x: i32 = scan.token();\n let y: i32 = scan.token();\n let dx = (x2 - x1).abs();\n let dy = (y2 - y1).abs();\n if dx % (2 * x) == 0 && dy % (2 * y) == 0 {\n writeln!(out, \"YES\").ok();\n } else if dx % (2 * x) == x && dy % (2 * y) == y {\n writeln!(out, \"YES\").ok();\n } else {\n writeln!(out, \"NO\").ok();\n }\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "9ab4458a0f6acbc59dad0cff2fc64705", "src_uid": "1c80040104e06c9f24abfcfe654a851f", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io;\nuse std::cmp::*;\nuse std::collections::*;\n#[allow(dead_code)]\nconst M: i64 = 1e9 as i64 + 7;\n\nfn read_line() -> String {\n let stdin = io::stdin();\n let mut buf = String::new();\n stdin.read_line(&mut buf).unwrap();\n buf\n}\n#[allow(dead_code)]\nfn read() -> T where T: std::str::FromStr, T::Err : std::fmt::Debug {\n read_line().trim().parse().unwrap()\n}\n#[allow(dead_code)]\nfn readv() -> Vec where T: std::str::FromStr, T::Err : std::fmt::Debug {\n read_line().split(' ').map(|a| a.trim().parse().unwrap()).collect()\n}\n\nfn main() {\n let input = readv::();\n let (x1, y1, x2, y2) = (input[0], input[1], input[2], input[3]);\n let input = readv::();\n let (x, y) = (input[0], input[1]);\n let xx = i32::abs(x2 - x1);\n let yy = i32::abs(y2 - y1);\n if xx % x != 0 || yy % y != 0 {\n println!(\"NO\");\n return;\n }\n println!(\"{}\", if xx / x % 2 == yy / y % 2 { \"YES\" } else { \"NO \"});\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "350b90b5709237b6d0345f7d72d432bf", "src_uid": "1c80040104e06c9f24abfcfe654a851f", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n return line.trim().to_string();\n}\n\nfn read_ints() -> Vec {\n let line = read_line();\n return line.split(\" \")\n .filter(|&s| s.len() > 0)\n .map(|s| {\n s.parse::().unwrap()\n }).collect();\n}\n\nfn main() {\n let params = read_ints();\n let x1 = params[0];\n let y1 = params[1];\n let x2 = params[2];\n let y2 = params[3];\n let params = read_ints();\n let a = params[0];\n let b = params[1];\n let dx = x2 - x1;\n let dy = y2 - y1;\n if dx % a != 0 || dy % b != 0 {\n println!(\"NO\");\n return;\n }\n let sx = dx / a;\n let sy = dy / b;\n println!(\"{}\", if (sx - sy) %2 == 0 {\"YES\"} else {\"NO\"});\n}", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "827f613e00d244c18b15c662faae3afa", "src_uid": "1c80040104e06c9f24abfcfe654a851f", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// codesnip-guard: main\nfn main() {\n #![allow(unused_imports, unused_macros)]\n prepare_io!(_in_buf, scanner, _out);\n macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect (\"io error\")) }\n scan!(scanner, n, m, s: [{CharsWithBase('a')}; n]);\n let mut t = Trie::new(26);\n let mut deq = std::collections::VecDeque::new();\n deq.push_back((0, 0));\n let mut idx = Indexing::new();\n idx.get((0, 0));\n for s in s.iter() {\n t.insert(s.iter().cloned());\n }\n let mut mp = std::collections::HashMap::<_, M>::new();\n while let Some((u, v)) = deq.pop_front() {\n let i = idx.get((u, v));\n for ch in 0..26 {\n if let (Some(nu), Some(nv)) = (t.next_node(u, ch), t.next_node(v, ch)) {\n let x = minmax!(nu, nv);\n if !idx.contains(&x) {\n deq.push_back(x);\n }\n *mp.entry((i, idx.get(x))).or_default() += M::one();\n if t.count(nv) > 0 {\n let x = minmax!(nu, 0);\n if !idx.contains(&x) {\n deq.push_back(x);\n }\n *mp.entry((i, idx.get(x))).or_default() += M::one();\n }\n if t.count(nu) > 0 {\n let x = minmax!(0, nv);\n if !idx.contains(&x) {\n deq.push_back(x);\n }\n *mp.entry((i, idx.get(x))).or_default() += M::one();\n }\n if t.count(nu) > 0 && t.count(nv) > 0 {\n *mp.entry((i, 0)).or_default() += M::one();\n }\n }\n }\n }\n let k = idx.len();\n let mut mat = vec![vec![M::zero(); k]; k];\n for ((i, j), v) in mp {\n mat[i][j] += v;\n }\n let ans = Matrix::from_vec(mat).pow(m)[0][0];\n println!(\"{}\", ans);\n}\n#[derive(Debug, Clone)]\npub struct Indexing {\n map: std::collections::HashMap,\n}\nimpl Indexing {\n pub fn new() -> Self {\n Self {\n map: Default::default(),\n }\n }\n pub fn len(&self) -> usize {\n self.map.len()\n }\n pub fn contains(&self, key: &T) -> bool {\n self.map.contains_key(key)\n }\n pub fn get(&mut self, key: T) -> usize {\n if let Some(index) = self.map.get(&key) {\n *index\n } else {\n let index = self.map.len();\n self.map.insert(key, index);\n index\n }\n }\n}\npub type M = montgomery::MInt998244353;\n#[macro_export]\nmacro_rules! prepare_io {\n ($ in_buf : ident , $ scanner : ident , $ out : ident) => {\n use std::io::{stdout, BufWriter, Write as _};\n let $in_buf = read_stdin_all_unchecked();\n let mut $scanner = Scanner::new(&$in_buf);\n let $out = stdout();\n let mut $out = BufWriter::new($out.lock());\n };\n}\n// codesnip-guard: _echo\npub fn echo(\n mut writer: impl std::io::Write,\n iter: impl IntoIterator,\n sep: impl std::fmt::Display,\n) -> std::io::Result<()> {\n let mut iter = iter.into_iter();\n if let Some(item) = iter.next() {\n write!(writer, \"{}\", item)?;\n }\n for item in iter {\n write!(writer, \"{}{}\", sep, item)?;\n }\n writeln!(writer)\n}\n// codesnip-guard: scanner\npub fn read_stdin_all_unchecked() -> String {\n use std::io::Read as _;\n let mut buf = Vec::new();\n std::io::stdin().read_to_end(&mut buf).expect(\"io error\");\n unsafe { String::from_utf8_unchecked(buf) }\n}\npub fn read_stdin_line() -> String {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).expect(\"io error\");\n s\n}\npub trait IterScan: Sized {\n type Output;\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option;\n}\npub trait MarkedIterScan: Sized {\n type Output;\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option;\n}\n#[derive(Clone, Debug)]\npub struct Scanner<'a> {\n iter: std::str::SplitAsciiWhitespace<'a>,\n}\nmod scanner_impls {\n use super::*;\n impl<'a> Scanner<'a> {\n #[inline]\n pub fn new(s: &'a str) -> Self {\n let iter = s.split_ascii_whitespace();\n Self { iter }\n }\n #[inline]\n pub fn scan(&mut self) -> ::Output {\n ::scan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn mscan(&mut self, marker: T) -> ::Output {\n marker.mscan(&mut self.iter).expect(\"scan error\")\n }\n #[inline]\n pub fn scan_vec(&mut self, size: usize) -> Vec<::Output> {\n (0..size)\n .map(|_| ::scan(&mut self.iter).expect(\"scan error\"))\n .collect()\n }\n #[inline]\n pub fn iter<'b, T: IterScan>(&'b mut self) -> ScannerIter<'a, 'b, T> {\n ScannerIter {\n inner: self,\n _marker: std::marker::PhantomData,\n }\n }\n }\n macro_rules ! iter_scan_impls { ($ ($ t : ty) *) => { $ (impl IterScan for $ t { type Output = Self ; # [inline] fn scan <'a , I : Iterator < Item = &'a str >> (iter : & mut I) -> Option < Self > { iter . next () ?. parse ::<$ t > () . ok () } }) * } ; }\n iter_scan_impls ! (char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);\n macro_rules ! iter_scan_tuple_impl { ($ ($ T : ident) *) => { impl <$ ($ T : IterScan) ,*> IterScan for ($ ($ T ,) *) { type Output = ($ (<$ T as IterScan >:: Output ,) *) ; # [inline] fn scan <'a , It : Iterator < Item = &'a str >> (_iter : & mut It) -> Option < Self :: Output > { Some (($ (<$ T as IterScan >:: scan (_iter) ?,) *)) } } } ; }\n iter_scan_tuple_impl!();\n iter_scan_tuple_impl!(A);\n iter_scan_tuple_impl ! (A B);\n iter_scan_tuple_impl ! (A B C);\n iter_scan_tuple_impl ! (A B C D);\n iter_scan_tuple_impl ! (A B C D E);\n iter_scan_tuple_impl ! (A B C D E F);\n iter_scan_tuple_impl ! (A B C D E F G);\n iter_scan_tuple_impl ! (A B C D E F G H);\n iter_scan_tuple_impl ! (A B C D E F G H I);\n iter_scan_tuple_impl ! (A B C D E F G H I J);\n iter_scan_tuple_impl ! (A B C D E F G H I J K);\n pub struct ScannerIter<'a, 'b, T> {\n inner: &'b mut Scanner<'a>,\n _marker: std::marker::PhantomData T>,\n }\n impl<'a, 'b, T: IterScan> Iterator for ScannerIter<'a, 'b, T> {\n type Item = ::Output;\n #[inline]\n fn next(&mut self) -> Option {\n ::scan(&mut self.inner.iter)\n }\n }\n}\n#[derive(Debug, Copy, Clone)]\npub struct Usize1;\n#[derive(Debug, Copy, Clone)]\npub struct CharWithBase(pub char);\n#[derive(Debug, Copy, Clone)]\npub struct Chars;\n#[derive(Debug, Copy, Clone)]\npub struct CharsWithBase(pub char);\n#[derive(Debug, Copy, Clone)]\npub struct Collect::Output>> {\n size: usize,\n _marker: std::marker::PhantomData (T, B)>,\n}\nmod marker_impls {\n use super::*;\n use std::{iter::FromIterator, marker::PhantomData};\n impl IterScan for Usize1 {\n type Output = usize;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n ::scan(iter)?.checked_sub(1)\n }\n }\n impl MarkedIterScan for CharWithBase {\n type Output = usize;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some((::scan(iter)? as u8 - self.0 as u8) as usize)\n }\n }\n impl IterScan for Chars {\n type Output = Vec;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n Some(iter.next()?.chars().collect())\n }\n }\n impl MarkedIterScan for CharsWithBase {\n type Output = Vec;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n iter.next()?\n .chars()\n .map(|c| (c as u8 - self.0 as u8) as usize)\n .collect(),\n )\n }\n }\n impl::Output>> Collect {\n pub fn new(size: usize) -> Self {\n Self {\n size,\n _marker: PhantomData,\n }\n }\n }\n impl::Output>> MarkedIterScan for Collect {\n type Output = B;\n #[inline]\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\n Some(\n (0..self.size)\n .map(|_| ::scan(iter).expect(\"scan error\"))\n .collect::(),\n )\n }\n }\n}\n#[macro_export]\nmacro_rules ! scan_value { ($ scanner : expr , ($ ($ t : tt) ,*)) => { ($ ($ crate :: scan_value ! ($ scanner , $ t)) ,*) } ; ($ scanner : expr , [$ t : tt ; $ len : expr]) => { (0 ..$ len) . map (| _ | $ crate :: scan_value ! ($ scanner , $ t)) . collect ::< Vec < _ >> () } ; ($ scanner : expr , [$ t : ty ; $ len : expr]) => { $ scanner . scan_vec ::<$ t > ($ len) } ; ($ scanner : expr , [$ t : ty]) => { $ scanner . iter ::<$ t > () } ; ($ scanner : expr , { $ e : expr }) => { $ scanner . mscan ($ e) } ; ($ scanner : expr , $ t : ty) => { $ scanner . scan ::<$ t > () } ; }\n#[macro_export]\nmacro_rules ! scan { ($ scanner : expr) => { } ; ($ scanner : expr ,) => { } ; ($ scanner : expr , mut $ var : tt : $ t : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , $ var : tt : $ t : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; } ; ($ scanner : expr , mut $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt : $ t : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , $ t) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , mut $ var : tt) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , $ var : tt) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; } ; ($ scanner : expr , mut $ var : tt , $ ($ rest : tt) *) => { let mut $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; ($ scanner : expr , $ var : tt , $ ($ rest : tt) *) => { let $ var = $ crate :: scan_value ! ($ scanner , usize) ; scan ! ($ scanner , $ ($ rest) *) } ; }\n// codesnip-guard: Trie\npub struct Trie {\n child: Vec>,\n accept: Vec,\n char_size: usize,\n}\nimpl Trie {\n pub fn new(char_size: usize) -> Self {\n Self {\n child: vec![vec![0; char_size]],\n accept: vec![0],\n char_size,\n }\n }\n pub fn insert_at(\n &mut self,\n mut node: usize,\n iter: impl IntoIterator,\n ) -> Vec {\n let mut path = Vec::new();\n for ch in iter.into_iter() {\n path.push(node);\n if self.child[node][ch] == 0 {\n self.child[node][ch] = self.child.len();\n self.child.push(vec![0; self.char_size]);\n self.accept.push(0);\n }\n node = self.child[node][ch];\n }\n path.push(node);\n self.accept[node] += 1;\n path\n }\n pub fn insert(&mut self, iter: impl IntoIterator) -> Vec {\n self.insert_at(0, iter)\n }\n pub fn find_at(\n &self,\n mut node: usize,\n iter: impl IntoIterator,\n ) -> Result {\n for ch in iter.into_iter() {\n if let Some(v) = self.child.get(node) {\n node = v[ch];\n } else {\n return Err(node);\n }\n }\n Ok(node)\n }\n pub fn find(&self, iter: impl IntoIterator) -> Result {\n self.find_at(0, iter)\n }\n pub fn next_node(&self, node: usize, ch: usize) -> Option {\n if self.child[node][ch] == 0 {\n None\n } else {\n Some(self.child[node][ch])\n }\n }\n pub fn count(&self, node: usize) -> usize {\n self.accept[node]\n }\n pub fn next_count(&self, node: usize, ch: usize) -> usize {\n if let Some(node) = self.next_node(node, ch) {\n self.count(node)\n } else {\n 0\n }\n }\n}\n// codesnip-guard: ord_tools\npub trait PartialOrdExt: Sized {\n fn chmin(&mut self, other: Self);\n fn chmax(&mut self, other: Self);\n fn minmax(self, other: Self) -> (Self, Self);\n}\nimpl PartialOrdExt for T\nwhere\n T: PartialOrd,\n{\n #[inline]\n fn chmin(&mut self, other: Self) {\n if *self > other {\n *self = other;\n }\n }\n #[inline]\n fn chmax(&mut self, other: Self) {\n if *self < other {\n *self = other;\n }\n }\n #[inline]\n fn minmax(self, other: Self) -> (Self, Self) {\n if self < other {\n (self, other)\n } else {\n (other, self)\n }\n }\n}\n#[macro_export]\nmacro_rules ! min { ($ l : expr) => { $ l } ; ($ l : expr ,) => { $ crate :: min ! ($ l) } ; ($ l : expr , $ r : expr) => { ($ l) . min ($ r) } ; ($ l : expr , $ r : expr ,) => { $ crate :: min ! ($ l , $ r) } ; ($ l : expr , $ r : expr , $ ($ t : tt) *) => { $ crate :: min ! ($ crate :: min ! ($ l , $ r) , $ ($ t) *) } ; }\n#[macro_export]\nmacro_rules ! chmin { ($ l : expr) => { } ; ($ l : expr ,) => { } ; ($ l : expr , $ r : expr) => { { let r = $ r ; if $ l > r { $ l = r ; } } } ; ($ l : expr , $ r : expr ,) => { $ crate :: chmin ! ($ l , $ r) } ; ($ l : expr , $ r : expr , $ ($ t : tt) *) => { $ crate :: chmin ! ($ l , $ r) ; $ crate :: chmin ! ($ l , $ ($ t) *) } ; }\n#[macro_export]\nmacro_rules ! max { ($ l : expr) => { $ l } ; ($ l : expr ,) => { $ crate :: max ! ($ l) } ; ($ l : expr , $ r : expr) => { ($ l) . max ($ r) } ; ($ l : expr , $ r : expr ,) => { $ crate :: max ! ($ l , $ r) } ; ($ l : expr , $ r : expr , $ ($ t : tt) *) => { $ crate :: max ! ($ crate :: max ! ($ l , $ r) , $ ($ t) *) } ; }\n#[macro_export]\nmacro_rules ! chmax { ($ l : expr) => { } ; ($ l : expr ,) => { } ; ($ l : expr , $ r : expr) => { { let r = $ r ; if $ l < r { $ l = r ; } } } ; ($ l : expr , $ r : expr ,) => { $ crate :: chmax ! ($ l , $ r) } ; ($ l : expr , $ r : expr , $ ($ t : tt) *) => { $ crate :: chmax ! ($ l , $ r) ; $ crate :: chmax ! ($ l , $ ($ t) *) } ; }\n#[macro_export]\nmacro_rules ! minmax { ($ ($ t : tt) *) => { ($ crate :: min ! ($ ($ t) *) , $ crate :: max ! ($ ($ t) *)) } ; }\n// codesnip-guard: montgomery\npub mod montgomery {\n use super::*;\n pub struct Modulo998244353;\n pub type MInt998244353 = MInt;\n impl MIntBase for M\n where\n M: MontgomeryReduction32,\n {\n type Inner = u32;\n #[inline]\n fn get_mod() -> Self::Inner {\n ::get_mod()\n }\n #[inline]\n fn mod_zero() -> Self::Inner {\n 0\n }\n #[inline]\n fn mod_one() -> Self::Inner {\n Self::n1()\n }\n #[inline]\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n let z = x + y;\n let m = Self::get_mod();\n if z >= m {\n z - m\n } else {\n z\n }\n }\n #[inline]\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n if x < y {\n x + Self::get_mod() - y\n } else {\n x - y\n }\n }\n #[inline]\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n Self::reduce(x as u64 * y as u64)\n }\n #[inline]\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner {\n Self::mod_mul(x, Self::mod_inv(y))\n }\n #[inline]\n fn mod_neg(x: Self::Inner) -> Self::Inner {\n if x == 0 {\n 0\n } else {\n Self::get_mod() - x\n }\n }\n fn mod_inv(x: Self::Inner) -> Self::Inner {\n let mut a = x;\n let m = Self::get_mod();\n let (mut b, mut u, mut s) = (m, 1, 0);\n let k = a.trailing_zeros();\n a >>= k;\n for _ in 0..k {\n if u & 1 == 1 {\n u += m;\n }\n u /= 2;\n }\n while a != b {\n if b < a {\n std::mem::swap(&mut a, &mut b);\n std::mem::swap(&mut u, &mut s);\n }\n b -= a;\n if s < u {\n s += m;\n }\n s -= u;\n let k = b.trailing_zeros();\n b >>= k;\n for _ in 0..k {\n if s & 1 == 1 {\n s += m;\n }\n s /= 2;\n }\n }\n Self::reduce(s as u64 * Self::n3() as u64)\n }\n }\n impl MIntConvert for M\n where\n M: MontgomeryReduction32,\n {\n #[inline]\n fn from(x: u32) -> Self::Inner {\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> u32 {\n Self::reduce(x as u64) as u32\n }\n #[inline]\n fn mod_into() -> u32 {\n ::get_mod() as u32\n }\n }\n impl MIntConvert for M\n where\n M: MontgomeryReduction32,\n {\n #[inline]\n fn from(x: u64) -> Self::Inner {\n Self::reduce(x % Self::get_mod() as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> u64 {\n Self::reduce(x as u64) as u64\n }\n #[inline]\n fn mod_into() -> u64 {\n ::get_mod() as u64\n }\n }\n impl MIntConvert for M\n where\n M: MontgomeryReduction32,\n {\n #[inline]\n fn from(x: usize) -> Self::Inner {\n Self::reduce(x as u64 % Self::get_mod() as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> usize {\n Self::reduce(x as u64) as usize\n }\n #[inline]\n fn mod_into() -> usize {\n ::get_mod() as usize\n }\n }\n impl MIntConvert for Modulo998244353 {\n #[inline]\n fn from(x: i32) -> Self::Inner {\n let x = x % ::get_mod() as i32;\n let x = if x < 0 {\n (x + ::get_mod() as i32) as u64\n } else {\n x as u64\n };\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> i32 {\n Self::reduce(x as u64) as i32\n }\n #[inline]\n fn mod_into() -> i32 {\n ::get_mod() as i32\n }\n }\n impl MIntConvert for Modulo998244353 {\n #[inline]\n fn from(x: i64) -> Self::Inner {\n let x = x % ::get_mod() as i64;\n let x = if x < 0 {\n (x + ::get_mod() as i64) as u64\n } else {\n x as u64\n };\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> i64 {\n Self::reduce(x as u64) as i64\n }\n #[inline]\n fn mod_into() -> i64 {\n ::get_mod() as i64\n }\n }\n impl MIntConvert for Modulo998244353 {\n #[inline]\n fn from(x: isize) -> Self::Inner {\n let x = x % ::get_mod() as isize;\n let x = if x < 0 {\n (x + ::get_mod() as isize) as u64\n } else {\n x as u64\n };\n Self::reduce(x as u64 * Self::n2() as u64)\n }\n #[inline]\n fn into(x: Self::Inner) -> isize {\n Self::reduce(x as u64) as isize\n }\n #[inline]\n fn mod_into() -> isize {\n ::get_mod() as isize\n }\n }\n /// m is prime, n = 2^32\n pub trait MontgomeryReduction32 {\n /// m\n fn get_mod() -> u32;\n /// (-m)^{-1} mod n\n fn r() -> u32 {\n let m = Self::get_mod();\n let mut r = 0;\n let mut t = 0;\n for i in 0..32 {\n if t % 2 == 0 {\n t += m;\n r += 1 << i;\n }\n t /= 2;\n }\n r\n }\n /// n^1 mod m\n fn n1() -> u32;\n /// n^2 mod m\n fn n2() -> u32;\n /// n^3 mod m\n fn n3() -> u32;\n /// n^{-1}x = (x + (xr mod n)m) / n\n fn reduce(x: u64) -> u32 {\n let m: u32 = Self::get_mod();\n let r = Self::r();\n let mut x = ((x + r.wrapping_mul(x as u32) as u64 * m as u64) >> 32) as u32;\n if x >= m {\n x -= m;\n }\n x\n }\n }\n macro_rules! impl_montgomery_reduction_32 {\n ($ name : ident , $ m : expr , $ r : expr , $ n1 : expr , $ n2 : expr , $ n3 : expr) => {\n impl MontgomeryReduction32 for $name {\n #[inline]\n fn get_mod() -> u32 {\n $m\n }\n #[inline]\n fn r() -> u32 {\n $r\n }\n #[inline]\n fn n1() -> u32 {\n $n1\n }\n #[inline]\n fn n2() -> u32 {\n $n2\n }\n #[inline]\n fn n3() -> u32 {\n $n3\n }\n }\n };\n }\n impl_montgomery_reduction_32!(\n Modulo998244353,\n 998_244_353,\n 998_244_351,\n 301_989_884,\n 932_051_910,\n 679_058_953\n );\n}\n// codesnip-guard: MIntBase\n#[repr(transparent)]\npub struct MInt\nwhere\n M: MIntBase,\n{\n x: M::Inner,\n _marker: std::marker::PhantomData M>,\n}\npub trait MIntBase {\n type Inner: Sized + Copy + Eq + std::fmt::Debug + std::hash::Hash;\n fn get_mod() -> Self::Inner;\n fn mod_zero() -> Self::Inner;\n fn mod_one() -> Self::Inner;\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner;\n fn mod_neg(x: Self::Inner) -> Self::Inner;\n fn mod_inv(x: Self::Inner) -> Self::Inner;\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\n let (mut x, mut y, mut z) = (x, y, Self::mod_one());\n while y > 0 {\n if y & 1 == 1 {\n z = Self::mod_mul(z, x);\n }\n x = Self::mod_mul(x, x);\n y >>= 1;\n }\n z\n }\n}\npub trait MIntConvert::Inner>: MIntBase {\n fn from(x: T) -> ::Inner;\n fn into(x: ::Inner) -> T;\n fn mod_into() -> T;\n}\nmod mint_base {\n use super::*;\n use std::{\n fmt::{self, Debug, Display},\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n };\n impl MInt\n where\n M: MIntConvert,\n {\n #[inline]\n pub fn new(x: M::Inner) -> Self {\n Self::new_unchecked(>::from(x))\n }\n #[inline]\n pub fn inner(self) -> M::Inner {\n >::into(self.x)\n }\n }\n impl MInt\n where\n M: MIntBase,\n {\n #[inline]\n pub fn new_unchecked(x: M::Inner) -> Self {\n Self {\n x,\n _marker: PhantomData,\n }\n }\n #[inline]\n pub fn get_mod() -> M::Inner {\n M::get_mod()\n }\n #[inline]\n pub fn pow(self, y: usize) -> Self {\n Self::new_unchecked(M::mod_pow(self.x, y))\n }\n #[inline]\n pub fn inv(self) -> Self {\n Self::new_unchecked(M::mod_inv(self.x))\n }\n }\n impl Clone for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn clone(&self) -> Self {\n Self {\n x: Clone::clone(&self.x),\n _marker: PhantomData,\n }\n }\n }\n impl Copy for MInt where M: MIntBase {}\n impl Debug for MInt\n where\n M: MIntBase,\n {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Debug::fmt(&self.x, f)\n }\n }\n impl Default for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn default() -> Self {\n ::zero()\n }\n }\n impl PartialEq for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n PartialEq::eq(&self.x, &other.x)\n }\n }\n impl Eq for MInt where M: MIntBase {}\n impl Hash for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn hash(&self, state: &mut H) {\n Hash::hash(&self.x, state)\n }\n }\n macro_rules ! impl_mint_from { ($ ($ t : ty) ,*) => { $ (impl < M > From <$ t > for MInt < M > where M : MIntConvert <$ t >, { # [inline] fn from (x : $ t) -> Self { Self :: new_unchecked (< M as MIntConvert <$ t >>:: from (x)) } } impl < M > From < MInt < M >> for $ t where M : MIntConvert <$ t >, { # [inline] fn from (x : MInt < M >) -> $ t { < M as MIntConvert <$ t >>:: into (x . x) } }) * } ; }\n impl_mint_from!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\n impl Zero for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn zero() -> Self {\n Self::new_unchecked(M::mod_zero())\n }\n }\n impl One for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn one() -> Self {\n Self::new_unchecked(M::mod_one())\n }\n }\n impl Add for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn add(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_add(self.x, rhs.x))\n }\n }\n impl Sub for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn sub(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_sub(self.x, rhs.x))\n }\n }\n impl Mul for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn mul(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_mul(self.x, rhs.x))\n }\n }\n impl Div for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn div(self, rhs: Self) -> Self::Output {\n Self::new_unchecked(M::mod_div(self.x, rhs.x))\n }\n }\n impl Neg for MInt\n where\n M: MIntBase,\n {\n type Output = Self;\n #[inline]\n fn neg(self) -> Self::Output {\n Self::new_unchecked(M::mod_neg(self.x))\n }\n }\n impl Sum for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl Product for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl<'a, M: 'a> Sum<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn sum>(iter: I) -> Self {\n iter.fold(::zero(), Add::add)\n }\n }\n impl<'a, M: 'a> Product<&'a MInt> for MInt\n where\n M: MIntBase,\n {\n #[inline]\n fn product>(iter: I) -> Self {\n iter.fold(::one(), Mul::mul)\n }\n }\n impl Display for MInt\n where\n M: MIntConvert,\n M::Inner: Display,\n {\n fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {\n write!(f, \"{}\", self.inner())\n }\n }\n impl FromStr for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Err = ::Err;\n #[inline]\n fn from_str(s: &str) -> Result {\n s.parse::().map(Self::new)\n }\n }\n impl IterScan for MInt\n where\n M: MIntConvert,\n M::Inner: FromStr,\n {\n type Output = Self;\n #[inline]\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\n iter.next()?.parse::>().ok()\n }\n }\n macro_rules! impl_mint_ref_binop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp<$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: $t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, other)\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(self, *other)\n }\n }\n impl $imp<&$t> for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp<$t>>::Output;\n #[inline]\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\n $imp::$method(*self, *other)\n }\n }\n };\n }\n impl_mint_ref_binop!(Add, add, MInt);\n impl_mint_ref_binop!(Sub, sub, MInt);\n impl_mint_ref_binop!(Mul, mul, MInt);\n impl_mint_ref_binop!(Div, div, MInt);\n macro_rules! impl_mint_ref_unop {\n ($ imp : ident , $ method : ident , $ t : ty) => {\n impl $imp for &$t\n where\n M: MIntBase,\n {\n type Output = <$t as $imp>::Output;\n #[inline]\n fn $method(self) -> <$t as $imp>::Output {\n $imp::$method(*self)\n }\n }\n };\n }\n impl_mint_ref_unop!(Neg, neg, MInt);\n macro_rules! impl_mint_ref_op_assign {\n ($ imp : ident , $ method : ident , $ t : ty , $ fromimp : ident , $ frommethod : ident) => {\n impl $imp<$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, rhs: $t) {\n *self = $fromimp::$frommethod(*self, rhs);\n }\n }\n impl $imp<&$t> for $t\n where\n M: MIntBase,\n {\n #[inline]\n fn $method(&mut self, other: &$t) {\n $imp::$method(self, *other);\n }\n }\n };\n }\n impl_mint_ref_op_assign!(AddAssign, add_assign, MInt, Add, add);\n impl_mint_ref_op_assign!(SubAssign, sub_assign, MInt, Sub, sub);\n impl_mint_ref_op_assign!(MulAssign, mul_assign, MInt, Mul, mul);\n impl_mint_ref_op_assign!(DivAssign, div_assign, MInt, Div, div);\n}\n// codesnip-guard: zero_one\npub trait Zero: PartialEq + Sized {\n fn zero() -> Self;\n #[inline]\n fn is_zero(&self) -> bool {\n self == &Self::zero()\n }\n}\npub trait One: PartialEq + Sized {\n fn one() -> Self;\n #[inline]\n fn is_one(&self) -> bool {\n self == &Self::one()\n }\n}\nmacro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { # [inline] fn $ method () -> Self { $ e } }) *) * } ; }\nzero_one_impls ! ({ Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 0 } { Zero zero f32 f64 , 0. } { One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128 , 1 } { One one f32 f64 , 1. });\n// codesnip-guard: Matrix\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct Matrix {\n pub shape: (usize, usize),\n pub data: Vec>,\n}\nmod matrix_impls {\n use super::*;\n use std::ops::{Add, Div, Index, IndexMut, Mul, Sub};\n impl Matrix {\n pub fn new(shape: (usize, usize), z: T) -> Self {\n Self {\n shape,\n data: vec![vec![z; shape.1]; shape.0],\n }\n }\n }\n impl Matrix {\n pub fn from_vec(data: Vec>) -> Self {\n Self {\n shape: (data.len(), data.first().map(Vec::len).unwrap_or_default()),\n data,\n }\n }\n }\n impl Matrix {\n pub fn zeros(shape: (usize, usize)) -> Self {\n Self {\n shape,\n data: vec![vec![Zero::zero(); shape.1]; shape.0],\n }\n }\n }\n impl Matrix {\n pub fn eye(shape: (usize, usize)) -> Self {\n let mut data = vec![vec![Zero::zero(); shape.1]; shape.0];\n for (i, d) in data.iter_mut().enumerate() {\n d[i] = One::one();\n }\n Self { shape, data }\n }\n }\n impl Index for Matrix {\n type Output = Vec;\n fn index(&self, index: usize) -> &Self::Output {\n &self.data[index]\n }\n }\n impl IndexMut for Matrix {\n fn index_mut(&mut self, index: usize) -> &mut Self::Output {\n &mut self.data[index]\n }\n }\n impl Index<(usize, usize)> for Matrix {\n type Output = T;\n fn index(&self, index: (usize, usize)) -> &Self::Output {\n &self.data[index.0][index.1]\n }\n }\n impl IndexMut<(usize, usize)> for Matrix {\n fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {\n &mut self.data[index.0][index.1]\n }\n }\n impl<'a, T: Copy + Zero + Add> Add for &'a Matrix {\n type Output = Matrix;\n fn add(self, rhs: Self) -> Self::Output {\n assert_eq!(self.shape, rhs.shape);\n let mut res = Matrix::zeros(self.shape);\n for i in 0..self.shape.0 {\n for j in 0..self.shape.1 {\n res[i][j] = self[i][j] + rhs[i][j];\n }\n }\n res\n }\n }\n impl<'a, T: Copy + Zero + Sub> Sub for &'a Matrix {\n type Output = Matrix;\n fn sub(self, rhs: Self) -> Self::Output {\n assert_eq!(self.shape, rhs.shape);\n let mut res = Matrix::zeros(self.shape);\n for i in 0..self.shape.0 {\n for j in 0..self.shape.1 {\n res[i][j] = self[i][j] - rhs[i][j];\n }\n }\n res\n }\n }\n impl<'a, T: Copy + Zero + Add + Mul> Mul for &'a Matrix {\n type Output = Matrix;\n fn mul(self, rhs: Self) -> Self::Output {\n assert_eq!(self.shape.1, rhs.shape.0);\n let mut res = Matrix::zeros((self.shape.0, rhs.shape.1));\n for i in 0..self.shape.0 {\n for j in 0..rhs.shape.1 {\n for k in 0..self.shape.1 {\n res[i][j] = res[i][j] + self[i][k] * rhs[k][j];\n }\n }\n }\n res\n }\n }\n impl + Mul> Matrix {\n pub fn pow(&self, mut n: usize) -> Self {\n assert_eq!(self.shape.0, self.shape.1);\n let mut x = self.clone();\n let mut res = Matrix::eye(self.shape);\n while n > 0 {\n if n & 1 == 1 {\n res = &res * &x;\n }\n x = &x * &x;\n n >>= 1;\n }\n res\n }\n }\n impl + Mul + Div> Matrix {\n pub fn row_reduction(&mut self) {\n let (n, m) = self.shape;\n let mut c = 0;\n for r in 0..n {\n loop {\n if c >= m {\n return;\n }\n if let Some(pivot) = (r..n).find(|&p| !self[p][c].is_zero()) {\n self.data.swap(r, pivot);\n break;\n };\n c += 1;\n }\n let d = T::one() / self[r][c];\n for j in c..m {\n self[r][j] = self[r][j] * d;\n }\n for i in (0..n).filter(|&i| i != r) {\n let d = self[i][c];\n for j in c..m {\n self[i][j] = self[i][j] - d * self[r][j];\n }\n }\n c += 1;\n }\n }\n pub fn rank(&mut self) -> usize {\n let n = self.shape.0;\n self.row_reduction();\n (0..n)\n .filter(|&i| !self.data[i].iter().all(|x| x.is_zero()))\n .count()\n }\n pub fn solve_system_of_linear_equations(&self, b: &[T]) -> Option> {\n assert_eq!(self.shape.0, self.shape.1);\n assert_eq!(self.shape.0, b.len());\n let n = self.shape.0;\n let mut c = Matrix::::zeros((n, n + 1));\n for i in 0..n {\n c[i][..n].clone_from_slice(&self[i]);\n c[i][n] = b[i];\n }\n c.row_reduction();\n if (0..n).any(|i| c[i][i].is_zero()) {\n None\n } else {\n Some((0..n).map(|i| c[i][n]).collect::>())\n }\n }\n pub fn inverse(&self) -> Option> {\n assert_eq!(self.shape.0, self.shape.1);\n let n = self.shape.0;\n let mut c = Matrix::::zeros((n, n * 2));\n for i in 0..n {\n c[i][..n].clone_from_slice(&self[i]);\n c[i][n + i] = T::one();\n }\n c.row_reduction();\n if (0..n).any(|i| c[i][i].is_zero()) {\n None\n } else {\n Some(Self::from_vec(\n c.data.into_iter().map(|r| r[n..].to_vec()).collect(),\n ))\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "data structures", "matrices", "strings", "dp"], "code_uid": "f5f89813d16fcb01b3bba53af5ea8c7e", "src_uid": "711d15e11016d0164fb2b0c3756e4857", "difficulty": 2700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//---------- begin union_find ----------\r\npub struct DSU {\r\n p: Vec,\r\n}\r\nimpl DSU {\r\n pub fn new(n: usize) -> DSU {\r\n assert!(n < std::i32::MAX as usize);\r\n DSU { p: vec![-1; n] }\r\n }\r\n pub fn init(&mut self) {\r\n self.p.iter_mut().for_each(|p| *p = -1);\r\n }\r\n pub fn root(&self, mut x: usize) -> usize {\r\n assert!(x < self.p.len());\r\n while self.p[x] >= 0 {\r\n x = self.p[x] as usize;\r\n }\r\n x\r\n }\r\n pub fn same(&self, x: usize, y: usize) -> bool {\r\n assert!(x < self.p.len() && y < self.p.len());\r\n self.root(x) == self.root(y)\r\n }\r\n pub fn unite(&mut self, x: usize, y: usize) -> Option<(usize, usize)> {\r\n assert!(x < self.p.len() && y < self.p.len());\r\n let mut x = self.root(x);\r\n let mut y = self.root(y);\r\n if x == y {\r\n return None;\r\n }\r\n if self.p[x] > self.p[y] {\r\n std::mem::swap(&mut x, &mut y);\r\n }\r\n self.p[x] += self.p[y];\r\n self.p[y] = x as i32;\r\n Some((x, y))\r\n }\r\n pub fn parent(&self, x: usize) -> Option {\r\n assert!(x < self.p.len());\r\n let p = self.p[x];\r\n if p >= 0 {\r\n Some(p as usize)\r\n } else {\r\n None\r\n }\r\n }\r\n pub fn sum(&self, mut x: usize, mut f: F) -> usize\r\n where\r\n F: FnMut(usize),\r\n {\r\n while let Some(p) = self.parent(x) {\r\n f(x);\r\n x = p;\r\n }\r\n x\r\n }\r\n pub fn size(&self, x: usize) -> usize {\r\n assert!(x < self.p.len());\r\n let r = self.root(x);\r\n (-self.p[r]) as usize\r\n }\r\n}\r\n//---------- end union_find ----------\r\n// ---------- begin Matrix ----------\r\nmod matrix {\r\n use std::ops::*;\r\n pub trait SemiRing: Add + Mul + Copy {\r\n fn zero() -> Self;\r\n fn one() -> Self;\r\n }\r\n pub trait Inverse: SemiRing {\r\n fn is_zero() -> bool;\r\n fn inv(self) -> Self;\r\n }\r\n #[derive(Clone)]\r\n pub struct SquareMatrix {\r\n size: usize,\r\n buf: Box<[R]>,\r\n }\r\n #[allow(dead_code)]\r\n impl SquareMatrix {\r\n pub fn zero(size: usize) -> Self {\r\n SquareMatrix {\r\n size: size,\r\n buf: vec![R::zero(); size * size].into_boxed_slice(),\r\n }\r\n }\r\n pub fn identity(size: usize) -> Self {\r\n let mut e = Self::zero(size);\r\n for i in 0..size {\r\n e.buf[i * size + i] = R::one();\r\n }\r\n e\r\n }\r\n pub fn set_at(&mut self, x: usize, y: usize, val: R) {\r\n assert!(x < self.size && y < self.size);\r\n self.buf[x * self.size + y] = val;\r\n }\r\n pub fn get_at(&self, x: usize, y: usize) -> R {\r\n assert!(x < self.size && y < self.size);\r\n self.buf[x * self.size + y]\r\n }\r\n pub fn get_mut(&mut self, x: usize, y: usize) -> &mut R {\r\n assert!(x < self.size && y < self.size);\r\n &mut self.buf[x * self.size + y]\r\n }\r\n pub fn matadd(&self, rhs: &Self) -> Self {\r\n assert!(self.size == rhs.size);\r\n let buf: Vec = self\r\n .buf\r\n .iter()\r\n .zip(rhs.buf.iter())\r\n .map(|p| *p.0 + *p.1)\r\n .collect();\r\n SquareMatrix {\r\n size: self.size,\r\n buf: buf.into_boxed_slice(),\r\n }\r\n }\r\n pub fn matmul(&self, rhs: &Self) -> Self {\r\n let size = self.size;\r\n assert!(size == rhs.size);\r\n let mut res = Self::zero(size);\r\n for (x, a) in res.buf.chunks_mut(size).zip(self.buf.chunks(size)) {\r\n for (a, b) in a.iter().zip(rhs.buf.chunks(size)) {\r\n for (x, b) in x.iter_mut().zip(b.iter()) {\r\n *x = *x + *a * *b;\r\n }\r\n }\r\n }\r\n res\r\n }\r\n pub fn mat_pow(&self, mut n: usize) -> Self {\r\n let size = self.size;\r\n let mut t = Self::identity(size);\r\n let mut s = self.clone();\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t = t.matmul(&s);\r\n }\r\n s = s.matmul(&s);\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n }\r\n #[allow(dead_code)]\r\n impl> SquareMatrix {\r\n pub fn matsub(&self, rhs: &Self) -> Self {\r\n assert!(self.size == rhs.size);\r\n let buf: Vec = self\r\n .buf\r\n .iter()\r\n .zip(rhs.buf.iter())\r\n .map(|p| *p.0 - *p.1)\r\n .collect();\r\n SquareMatrix {\r\n size: self.size,\r\n buf: buf.into_boxed_slice(),\r\n }\r\n }\r\n }\r\n /*\r\n #[allow(dead_code)]\r\n impl> SquareMatrix {\r\n pub fn inverse(&self) -> Self {\r\n }\r\n }\r\n */\r\n}\r\n// ---------- end Matrix ----------\r\n// ---------- begin ModInt ----------\r\n// \u30e2\u30f3\u30b4\u30e1\u30ea\u4e57\u7b97\u3092\u7528\u3044\u308b\r\n// \u307b\u307cCodeforces\u7528\r\n// \u6ce8\u610f\r\n// new_unchecked \u306f\u5024x\u304c 0 <= x < modulo \u3067\u3042\u308b\u3053\u3068\u3092\u4eee\u5b9a\r\n// ModInt \u306e\u4e2d\u8eab\u306f\u6b63\u898f\u5316\u3055\u308c\u305f\u5024\u3067\u6301\u3063\u3066\u308b\u306e\u3067\u76f4\u63a5\u8aad\u3093\u3060\u308a\u66f8\u3044\u305f\u308a\u3059\u308b\u3068\u3076\u3063\u58ca\u308c\u308b\r\n// \u5947\u7d20\u6570\u306e\u307f\r\nmod modint {\r\n\r\n use std::marker::*;\r\n use std::ops::*;\r\n\r\n pub trait Modulo {\r\n fn modulo() -> u32;\r\n fn rem() -> u32;\r\n fn ini() -> u64;\r\n fn reduce(x: u64) -> u32 {\r\n assert!(x < (Self::modulo() as u64) << 32);\r\n let b = (x as u32 * Self::rem()) as u64;\r\n let t = x + b * Self::modulo() as u64;\r\n let mut c = (t >> 32) as u32;\r\n if c >= Self::modulo() {\r\n c -= Self::modulo();\r\n }\r\n c as u32\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod1_000_000_007 {}\r\n\r\n impl Modulo for Mod1_000_000_007 {\r\n fn modulo() -> u32 {\r\n 1_000_000_007\r\n }\r\n fn rem() -> u32 {\r\n 2226617417\r\n }\r\n fn ini() -> u64 {\r\n 582344008\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub enum Mod998_244_353 {}\r\n\r\n impl Modulo for Mod998_244_353 {\r\n fn modulo() -> u32 {\r\n 998_244_353\r\n }\r\n fn rem() -> u32 {\r\n 998244351\r\n }\r\n fn ini() -> u64 {\r\n 932051910\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n pub fn generate_umekomi_modulo(p: u32) {\r\n assert!(\r\n p < (1 << 31)\r\n && p > 2\r\n && p & 1 == 1\r\n && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0)\r\n );\r\n let mut t = 1u32;\r\n let mut s = !p + 1;\r\n let mut n = !0u32 >> 2;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n let mut ini = (1u64 << 32) % p as u64;\r\n ini = (ini << 32) % p as u64;\r\n assert!(t * p == !0);\r\n println!(\"pub enum Mod{} {{}}\", p);\r\n println!(\"impl Modulo for Mod{} {{\", p);\r\n println!(\" fn modulo() -> u32 {{\");\r\n println!(\" {}\", p);\r\n println!(\" }}\");\r\n println!(\" fn rem() -> u32 {{\");\r\n println!(\" {}\", t);\r\n println!(\" }}\");\r\n println!(\" fn ini() -> u32 {{\");\r\n println!(\" {}\", ini);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n let mut f = vec![];\r\n let mut n = p - 1;\r\n for i in 2.. {\r\n if i * i > n {\r\n break;\r\n }\r\n if n % i == 0 {\r\n f.push(i);\r\n while n % i == 0 {\r\n n /= i;\r\n }\r\n }\r\n }\r\n if n > 1 {\r\n f.push(n);\r\n }\r\n let mut order = 1;\r\n let mut n = p - 1;\r\n while n % 2 == 0 {\r\n n /= 2;\r\n order <<= 1;\r\n }\r\n let z = (2u64..)\r\n .find(|z| {\r\n f.iter()\r\n .all(|f| mod_pow(*z, ((p - 1) / *f) as u64, p as u64) != 1)\r\n })\r\n .unwrap();\r\n let zeta = mod_pow(z, ((p - 1) / order) as u64, p as u64);\r\n println!(\"impl transform::NTTFriendly for Mod{} {{\", p);\r\n println!(\" fn order() -> usize {{\");\r\n println!(\" {}\", order);\r\n println!(\" }}\");\r\n println!(\" fn zeta() -> u32 {{\");\r\n println!(\" {}\", zeta);\r\n println!(\" }}\");\r\n println!(\"}}\");\r\n }\r\n\r\n pub struct ModInt(u32, PhantomData);\r\n\r\n impl Clone for ModInt {\r\n fn clone(&self) -> Self {\r\n ModInt::build(self.0)\r\n }\r\n }\r\n\r\n impl Copy for ModInt {}\r\n\r\n impl Add for ModInt {\r\n type Output = ModInt;\r\n fn add(self, rhs: Self) -> Self::Output {\r\n let mut d = self.0 + rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl AddAssign for ModInt {\r\n fn add_assign(&mut self, rhs: Self) {\r\n *self = *self + rhs;\r\n }\r\n }\r\n\r\n impl Sub for ModInt {\r\n type Output = ModInt;\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n let mut d = T::modulo() + self.0 - rhs.0;\r\n if d >= T::modulo() {\r\n d -= T::modulo();\r\n }\r\n Self::build(d)\r\n }\r\n }\r\n\r\n impl SubAssign for ModInt {\r\n fn sub_assign(&mut self, rhs: Self) {\r\n *self = *self - rhs;\r\n }\r\n }\r\n\r\n impl Mul for ModInt {\r\n type Output = ModInt;\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::build(T::reduce(self.0 as u64 * rhs.0 as u64))\r\n }\r\n }\r\n\r\n impl MulAssign for ModInt {\r\n fn mul_assign(&mut self, rhs: Self) {\r\n *self = *self * rhs;\r\n }\r\n }\r\n\r\n impl Neg for ModInt {\r\n type Output = ModInt;\r\n fn neg(self) -> Self::Output {\r\n if self.0 == 0 {\r\n Self::zero()\r\n } else {\r\n Self::build(T::modulo() - self.0)\r\n }\r\n }\r\n }\r\n\r\n impl std::fmt::Display for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::fmt::Debug for ModInt {\r\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\r\n write!(f, \"{}\", self.get())\r\n }\r\n }\r\n\r\n impl std::str::FromStr for ModInt {\r\n type Err = std::num::ParseIntError;\r\n fn from_str(s: &str) -> Result {\r\n let val = s.parse::()?;\r\n Ok(ModInt::new(val))\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: usize) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: u64) -> ModInt {\r\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\r\n }\r\n }\r\n\r\n impl From for ModInt {\r\n fn from(val: i64) -> ModInt {\r\n let m = T::modulo() as i64;\r\n ModInt::new((val % m + m) as u32)\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n fn build(d: u32) -> Self {\r\n ModInt(d, PhantomData)\r\n }\r\n pub fn zero() -> Self {\r\n Self::build(0)\r\n }\r\n pub fn is_zero(&self) -> bool {\r\n self.0 == 0\r\n }\r\n }\r\n\r\n #[allow(dead_code)]\r\n impl ModInt {\r\n pub fn new_unchecked(d: u32) -> Self {\r\n Self::build(T::reduce(d as u64 * T::ini()))\r\n }\r\n pub fn new(d: u32) -> Self {\r\n Self::new_unchecked(d % T::modulo())\r\n }\r\n pub fn one() -> Self {\r\n Self::new_unchecked(1)\r\n }\r\n pub fn get(&self) -> u32 {\r\n T::reduce(self.0 as u64)\r\n }\r\n pub fn pow(&self, mut n: u64) -> Self {\r\n let mut t = Self::one();\r\n let mut s = *self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t *= s;\r\n }\r\n s *= s;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n pub fn inv(&self) -> Self {\r\n assert!(!self.is_zero());\r\n self.pow((T::modulo() - 2) as u64)\r\n }\r\n }\r\n\r\n pub fn mod_pow(mut r: u64, mut n: u64, m: u64) -> u64 {\r\n let mut t = 1 % m;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n t = t * r % m;\r\n }\r\n r = r * r % m;\r\n n >>= 1;\r\n }\r\n t\r\n }\r\n}\r\n// ---------- end ModInt ----------\r\n\r\nuse modint::*;\r\n\r\ntype M = ModInt;\r\n\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\n// \u884c\u5217\u7d2f\u4e57\u3063\u307d\u3044\u304c\u72b6\u614b\u6570\u53b3\u3057\u3052\u3067\u306f...\r\n\r\nuse matrix::*;\r\ntype Mat = SquareMatrix;\r\n\r\nimpl SemiRing for M {\r\n fn zero() -> Self {\r\n M::zero()\r\n }\r\n fn one() -> Self {\r\n M::one()\r\n }\r\n}\r\n\r\nfn lcp(x: &[u8], y: &[u8]) -> usize {\r\n x.iter().zip(y).take_while(|p| *p.0 == *p.1).count()\r\n}\r\n\r\nfn run() {\r\n input! {\r\n n: usize,\r\n m: usize,\r\n s: [bytes; n],\r\n }\r\n let mut id = 0;\r\n let mut map = std::collections::BTreeMap::new();\r\n for s in s.iter() {\r\n for i in 0..s.len() {\r\n let s = s[i..].iter().cloned().collect::>();\r\n map.entry(s).or_insert_with(|| {\r\n let v = id;\r\n id += 1;\r\n v\r\n });\r\n }\r\n }\r\n map.insert(vec![], id);\r\n id += 1;\r\n let mut edge = vec![];\r\n for (x, &src) in map.iter() {\r\n if x.is_empty() {\r\n for a in s.iter() {\r\n for b in s.iter() {\r\n let len = lcp(a, b);\r\n let a = a[len..].iter().cloned().collect::>();\r\n let b = b[len..].iter().cloned().collect::>();\r\n if !a.is_empty() && !b.is_empty() {\r\n continue;\r\n }\r\n let mut pre = src;\r\n for _ in 1..len {\r\n edge.push((pre, id));\r\n pre = id;\r\n id += 1;\r\n }\r\n if a.is_empty() {\r\n let dst = *map.get(&b).unwrap();\r\n edge.push((pre, dst));\r\n } else if b.is_empty() {\r\n let dst = *map.get(&a).unwrap();\r\n edge.push((pre, dst));\r\n }\r\n }\r\n }\r\n } else {\r\n for a in s.iter() {\r\n let len = lcp(a, x);\r\n let a = a[len..].iter().cloned().collect::>();\r\n let b = x[len..].iter().cloned().collect::>();\r\n if !a.is_empty() && !b.is_empty() {\r\n continue;\r\n }\r\n let mut pre = src;\r\n for _ in 1..len {\r\n edge.push((pre, id));\r\n pre = id;\r\n id += 1;\r\n }\r\n if a.is_empty() {\r\n let dst = *map.get(&b).unwrap();\r\n edge.push((pre, dst));\r\n } else if b.is_empty() {\r\n let dst = *map.get(&a).unwrap();\r\n edge.push((pre, dst));\r\n }\r\n }\r\n }\r\n }\r\n let src = *map.get(&vec![]).unwrap();\r\n let mut dsu = DSU::new(id);\r\n for &(a, b) in edge.iter() {\r\n dsu.unite(a, b);\r\n }\r\n let mut index = vec![id; id];\r\n let mut p = 0;\r\n for i in 0..id {\r\n if dsu.same(i, src) {\r\n index[i] = p;\r\n p += 1;\r\n }\r\n }\r\n let mut mat = Mat::zero(p);\r\n for &(a, b) in edge.iter() {\r\n if index[a] < id {\r\n *mat.get_mut(index[a], index[b]) += M::one();\r\n }\r\n }\r\n let pow = mat.mat_pow(m);\r\n let ans = pow.get_at(index[src], index[src]);\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "data structures", "matrices", "strings", "dp"], "code_uid": "b76b7d43d49b20dd52fe14fd2b64cf4d", "src_uid": "711d15e11016d0164fb2b0c3756e4857", "difficulty": 2700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nconst p: i64 = 1_000_000_007;\n\nfn main() {\n let (n, m, k) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|x| x.parse::().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n // (2^{n - 1})^{m - 1}\n // 2^{n + m - 2}\n\n if k == -1 && (n + m) % 2 != 0 {\n println!(\"0\");\n return;\n }\n\n let n0 = {\n let p0 = p - 1;\n ((n - 1) % p0) * ((m - 1) % p0) % p0\n };\n\n let mut two_pow_two_pow = Vec::new();\n\n let mul = |a, b| {\n ((a % p) * (b % p)) % p\n };\n\n let mut i = 2;\n for _ in 0..40 {\n two_pow_two_pow.push(i);\n i = mul(i, i);\n }\n\n let mut ans = 1;\n\n for i in 0..40 {\n if n0 & (1 << i) != 0 {\n ans = mul(ans, two_pow_two_pow[i]);\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "combinatorics", "number theory"], "code_uid": "137252cce5a841e2c3a33dd3e8048b89", "src_uid": "6b9eff690fae14725885cbc891ff7243", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nconst MOD: u64 = 1_000_000_007;\n\nfn mod_pow(r: u64, mut n: u64) -> u64 {\n let mut t = 1;\n let mut s = r % MOD;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s % MOD;\n }\n s = s * s % MOD;\n n >>= 1;\n }\n t\n}\n\nfn run() {\n input! {\n n: u64,\n m: u64,\n k: i32,\n }\n if k == -1 && m % 2 != n % 2 {\n println!(\"0\");\n return;\n }\n let ans = mod_pow(mod_pow(2, n - 1), m - 1);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "combinatorics", "number theory"], "code_uid": "2783385bab31200e70d1616a01fc6fb9", "src_uid": "6b9eff690fae14725885cbc891ff7243", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let stdin = std::io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n String::from(line.trim())\n}\n\nmacro_rules! scan_line {\n ($($ty: ty),*) => {{\n let line = read_line();\n let mut tok = line.split_whitespace();\n ($(tok.next().unwrap().parse::<$ty>().unwrap()),*)\n }}\n}\n\nconst MOD: i64 = 1_000_000_007;\n\nfn pow_with_mod(mut a: i64, mut n: i64) -> i64 {\n let mut acc = 1;\n a = a % MOD;\n while n > 0 {\n if n & 1 == 1 {\n acc = (acc * a) % MOD;\n }\n a = (a * a) % MOD;\n n >>= 1;\n }\n acc\n}\n\nfn main() {\n let (n, m, k) = scan_line!(i64, i64, i32);\n let ans = if n % 2 != m % 2 && k == -1 {\n 0\n } else {\n pow_with_mod(pow_with_mod(2, n - 1), m - 1)\n };\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "combinatorics", "number theory"], "code_uid": "82810ec5b8c7b2d80c8c9acfe31dbbbc", "src_uid": "6b9eff690fae14725885cbc891ff7243", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let (a, b) = parse();\n let mut values = 0;\n for i in a..b + 1 {\n for c in i.to_string().chars() {\n values += calculate_segment(c)\n }\n }\n println!(\"{}\", values)\n}\nfn parse() -> (usize, usize) {\n let mut text = String::new();\n stdin().read_line(&mut text).unwrap();\n let text: Vec = text\n .trim()\n .split_whitespace()\n .map(|e| e.parse().unwrap())\n .collect();\n (text[0], text[1])\n}\nfn calculate_segment(ch: char) -> usize {\n match ch {\n '0' | '6' | '9' => 6,\n '1' => 2,\n '2' | '3' | '5' => 5,\n '4' => 4,\n '7' => 3,\n '8' => 7,\n _ => 0,\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b4c716a27a412e07bf8d22665736ef58", "src_uid": "1193de6f80a9feee8522a404d16425b9", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, [graph1; $len:expr]) => {{\n let mut g = vec![vec![]; $len];\n let ab = read_value!($next, [(usize1, usize1)]);\n for (a, b) in ab {\n g[a].push(b);\n g[b].push(a);\n }\n g\n }};\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n ($next:expr, usize1) => (read_value!($next, usize) - 1);\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n read_value!($next, [$t; len])\n }};\n ($next:expr, $t:ty) => ($next().parse::<$t>().expect(\"Parse error\"));\n}\n\n#[allow(unused)]\nmacro_rules! debug {\n ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());\n}\n#[allow(unused)]\nmacro_rules! debugln {\n ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());\n}\n\n/// Verified by https://atcoder.jp/contests/arc093/submissions/3968098\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData }\n impl ModInt {\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n pub fn pow(self, mut e: i64) -> Self {\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl>> Add for ModInt {\n type Output = Self;\n fn add(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Sub for ModInt {\n type Output = Self;\n fn sub(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Mul for ModInt {\n type Output = Self;\n fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }\n }\n impl>> AddAssign for ModInt {\n fn add_assign(&mut self, other: T) { *self = *self + other; }\n }\n impl>> SubAssign for ModInt {\n fn sub_assign(&mut self, other: T) { *self = *self - other; }\n }\n impl>> MulAssign for ModInt {\n fn mul_assign(&mut self, other: T) { *self = *self * other; }\n }\n impl Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self { ModInt::new(0) - self }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n let (mut a, mut b, _) = red(self.x, M::m());\n if b < 0 {\n a = -a;\n b = -b;\n }\n write!(f, \"{}/{}\", a, b)\n }\n }\n impl From for ModInt {\n fn from(x: i64) -> Self { Self::new(x) }\n }\n // Finds the simplest fraction x/y congruent to r mod p.\n // The return value (x, y, z) satisfies x = y * r + z * p.\n fn red(r: i64, p: i64) -> (i64, i64, i64) {\n if r.abs() <= 10000 {\n return (r, 1, 0);\n }\n let mut nxt_r = p % r;\n let mut q = p / r;\n if 2 * nxt_r >= r {\n nxt_r -= r;\n q += 1;\n }\n if 2 * nxt_r <= -r {\n nxt_r += r;\n q -= 1;\n }\n let (x, z, y) = red(nxt_r, r);\n (x, y - q * z, z)\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 1_000_000_007;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n input! {\n k: usize, pa: i64, pb: i64,\n }\n let mut dp = vec![vec![ModInt::new(0); k + 1]; k + 1];\n let pa = ModInt::new(pa);\n let pb = ModInt::new(pb);\n let pab = pa + pb;\n let pabinv = pab.inv();\n for i in (0..k).rev() {\n dp[i][k] = pa * pb.inv() + ModInt::new((i + k) as i64);\n for j in (1..k).rev() {\n let mut val = dp[i][j + 1] * pa;\n if i + j < k {\n val += dp[min(k, i + j)][j] * pb;\n } else {\n val += pb * ModInt::new((i + j) as i64);\n }\n dp[i][j] = val * pabinv;\n }\n let val = dp[i][1];\n dp[i][0] = val;\n }\n puts!(\"{}\\n\", dp[0][0]);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "probabilities"], "code_uid": "ae443ff55eb8c7a32231b3924e44366b", "src_uid": "0dc9f5d75143a2bc744480de859188b4", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Read;\n\nfn main() {\n let mut text = String::new();\n io::stdin().read_to_string(&mut text).unwrap();\n let mut iter = text.split_whitespace();//.map(|x| x.parse::().unwrap());\n let n = iter.next().unwrap().parse::().unwrap();\n let s = iter.next().unwrap();\n let mut up = true;\n let mut down = true;\n let mut left = true;\n let mut right = true;\n for c in s.chars() {\n let d = c as i64 - '0' as i64;\n if d == 1 || d == 2 || d == 3 {\n up = false;\n }\n if d == 7 || d == 9 || d == 0 {\n down = false;\n }\n if d == 1 || d == 4 || d == 7 || d == 0 {\n left = false;\n }\n if d == 3 || d == 6 || d == 9 || d == 0 {\n right = false;\n }\n }\n println!(\"{}\", if (up || down || left || right) {\"NO\"} else {\"YES\"});\n\n}\n\nfn get_pos(num: i64) -> (i64, i64) {\n if num == 0 {\n (3, 1)\n } else {\n ((num - 1) / 3, (num - 1) % 3)\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "implementation"], "code_uid": "e666ff36147879af8f551d87dc08ffe7", "src_uid": "d0f5174bb0bcca5a486db327b492bf33", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\nuse std::io::Write;\n\n#[derive(Debug,Clone,Copy,Default)]\nstruct Problem {\n buf: [u8;9],\n len: u8,\n}\n\nimpl Problem {\n fn as_slice(&self) -> &[u8] {\n &self.buf[0..self.len as usize]\n }\n}\n\nfn loc(d: u8) -> (u8,u8) {\n assert!(d < 10);\n if d == 0 {\n (1,3)\n } else {\n ((d-1)%3,(d-1)/3)\n }\n}\n\nfn read_problem() -> Problem {\n let stdin = std::io::stdin();\n let mut lines = stdin.lock().lines();\n\n let ct = str::parse::(&lines.next().unwrap().unwrap()).unwrap();\n let mut ret = Problem::default();\n for (c,b) in lines.next().unwrap().unwrap().chars().zip(ret.buf.iter_mut()) {\n *b = c.to_digit(10).unwrap() as u8;\n ret.len += 1;\n }\n assert_eq!(ret.len, ct);\n assert!(lines.next().is_none());\n ret\n}\n\nfn solve(problem: Problem) -> bool {\n let mut min_x = u8::max_value();\n let mut min_y = u8::max_value();\n let mut max_x = 0;\n let mut max_y = 0;\n let mut max_side_y = 0;\n\n for &d in problem.as_slice() {\n let (x,y) = loc(d);\n if x < min_x {\n min_x = x;\n }\n if x > max_x {\n max_x = x;\n }\n if y < min_y {\n min_y = y;\n }\n if y > max_y {\n max_y = y;\n }\n if x != 1 && y > max_side_y {\n max_side_y = y;\n }\n }\n\n let dx = max_x - min_x;\n let dy = max_y - min_y;\n let dsy = max_side_y - min_y;\n writeln!(&mut std::io::stderr(), \"{:?}\", (dx,dy,dsy)).unwrap();\n dy == 3 || (dx,dsy) == (2,2)\n}\n\nfn main() {\n let p = read_problem();\n println!(\"{}\", if solve(p) { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "implementation"], "code_uid": "f643ec64204febf48cbdb061a2c234d0", "src_uid": "d0f5174bb0bcca5a486db327b492bf33", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n \nfn get_input(input: &mut String) {\n input.clear();\n stdin().read_line(input).expect(\"error\");\n}\n \nfn main() {\n let mut input = String::new();\n \n get_input(&mut input);\n let mut numbers = input.trim().split_whitespace();\n let n = numbers.next().unwrap().parse::().unwrap();\n let k = numbers.next().unwrap().parse::().unwrap();\n let max_price = std::cmp::min(n, k-1);\n let min_price = k - max_price;\n if min_price >= max_price {\n println!(\"0\");\n } else {\n let length = max_price - min_price;\n println!(\"{}\", length / 2 + length % 2);\n }\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "13e6b42bac8e8c05b9998f6fdeb7f6f6", "src_uid": "98624ab2fcd2a50a75788a29e04999ad", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: i64,\n k: i64,\n }\n let l = std::cmp::max(1, k - n);\n let ans = if k % 2 == 1 {\n let r = k / 2;\n if r + 1 > n || l > r {\n 0\n } else {\n r - l + 1\n }\n } else {\n let r = k / 2 - 1;\n if r + 2 > n || l > r {\n 0\n } else {\n r - l + 1\n }\n };\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "96a7ee1f2a704deab511d497a53736bd", "src_uid": "98624ab2fcd2a50a75788a29e04999ad", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cell::RefCell;\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Formatter, Write as FmtWrite};\nuse std::io::{stderr, stdin, BufRead, Write};\nuse std::mem::{replace, swap};\nuse std::ops::*;\nuse std::rc::Rc;\n\n// -----------------------------------------------\n// Framework \n// -----------------------------------------------\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($t:ty) =>\n (rl().parse::<$t>().unwrap());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($arg:expr),*) => {\n #[cfg(debug_assertions)]\n $(writeln!(stderr(), \"{} = {:?}\", stringify!($arg), $arg).unwrap());*\n };\n}\n\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_owned()\n}\n\ntrait IteratorExt: Iterator + Sized {\n fn vec(self) -> Vec {\n self.collect()\n }\n}\n\nimpl IteratorExt for T {}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\nfn solve(N: i64, K: i64) -> i64 {\n let r = min(N + 1, K);\n let l = min(r, K / 2 + 1);\n r - l\n}\n\nfn main() {\n let (N, K) = read!(i64, i64);\n println!(\"{}\", solve(N, K))\n}\n\n#[cfg(test)]\nmod tests {\n use super::solve;\n\n #[test]\n fn tests() {\n assert_eq!(solve(8, 5), 2);\n assert_eq!(solve(8, 15), 1);\n assert_eq!(solve(7, 20), 0);\n assert_eq!(solve(1000000000000, 1000000000001), 500000000000);\n\n assert_eq!(solve(1, 1), 0);\n assert_eq!(solve(2, 3), 1);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "834d6c6d0ed93d0055d6b10a9634d0b6", "src_uid": "98624ab2fcd2a50a75788a29e04999ad", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let (a, x, y) = parse_line!(i64, i64, i64);\n if y <= 0 || y % a == 0 || x.abs() >= a {\n return println!(\"-1\");\n }\n if y < a {\n if (x * 2).abs() < a {\n println!(\"1\");\n }else{\n println!(\"-1\");\n }\n return;\n }\n let y = y - a;\n let period = y / (2 * a);\n let left = y % (2 * a);\n if left < a {\n if (x * 2).abs() < a {\n println!(\"{}\", 2 + period * 3);\n }else{\n println!(\"-1\");\n }\n }else{\n if x < 0 {\n println!(\"{}\", 3 + period * 3);\n }else if x > 0 {\n println!(\"{}\", 4 + period * 3);\n }else{\n println!(\"-1\");\n }\n }\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "581a382648f84562f21d48bb7740daa9", "src_uid": "cf48ff6ba3e77ba5d4afccb8f775fb02", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, Read, StdinLock};\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::collections::{HashSet, HashMap, BinaryHeap};\n#[allow(unused_imports)]\nuse std::vec::Vec;\n\n#[allow(dead_code)]\nconst INF: i32 = 1000_000_000;\n#[allow(dead_code)]\nconst INFLL: i64 = 1000_000_000_000_000_000;\n#[allow(dead_code)]\nconst EPS: f64 = 1.0e-10;\n#[allow(dead_code)]\nconst MOD: i32 = 1000_000_007;\n\nstruct Scanner<'a> {\n cin: StdinLock<'a>,\n}\n\nimpl<'a> Scanner<'a> {\n #[allow(dead_code)]\n fn new(cin: StdinLock<'a>) -> Scanner<'a> {\n Scanner {cin: cin}\n }\n\n #[allow(dead_code)]\n fn read1(&mut self) -> Option {\n let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect::();\n token.parse::().ok()\n }\n\n #[allow(dead_code)]\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\n\nfn main() {\n let cin = stdin();\n let cin = cin.lock();\n let mut sc = Scanner::new(cin);\n\n let a: i32 = sc.read();\n let x: i32 = sc.read();\n let y: i32 = sc.read();\n let x = 2 * x;\n let y = 2 * y;\n let a = 2 * a;\n let mut ans = -1;\n if y % a != 0 { \n if 0 < y && y < a {\n if -a / 2 < x && x < a / 2 {\n ans = 1;\n }\n } else {\n let j = (y - a) / a;\n if j % 2 == 0 {\n if -a / 2 < x && x < a / 2 {\n ans = 3 * j / 2 + 2;\n }\n } else {\n if -a < x && x < 0 {\n ans = 3 * (j + 1) / 2;\n } else if 0 < x && x < a {\n ans = 3 * (j + 1) / 2 + 1;\n }\n }\n }\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "55dd409110e4495fdf1b2d0503398443", "src_uid": "cf48ff6ba3e77ba5d4afccb8f775fb02", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn gcd(mut a: usize, mut b: usize) -> usize {\n if b > a {\n std::mem::swap(&mut a, &mut b);\n }\n while b != 0 {\n let new_b = a % b;\n a = b;\n b = new_b;\n }\n if a == 0 {\n 1\n } else {\n a\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: usize = scan.next();\n let b: usize = scan.next();\n let x = 6 - a.max(b) + 1;\n let common = gcd(x, 6);\n println!(\"{}/{}\", x / common, 6 / common);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "probabilities"], "code_uid": "88264683fbd5fc55ff572b2483aecfaf", "src_uid": "f97eb4ecffb6cbc8679f0c621fd59414", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (u8, u8) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\nfn main() {\n let (a, b) = read_line_pair();\n let c = 6 - std::cmp::max(a, b) + 1;\n match c {\n 2 => println!(\"1/3\"),\n 3 => println!(\"1/2\"),\n 4 => println!(\"2/3\"),\n 6 => println!(\"1/1\"),\n _ => println!(\"{}/6\", c)\n }\n}", "lang_cluster": "Rust", "tags": ["math", "probabilities"], "code_uid": "451027d6b013dbb7679c8d4196b232f3", "src_uid": "f97eb4ecffb6cbc8679f0c621fd59414", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut reader = scanner::TokenReader::new();\n let (a, b) = (reader.next::(), reader.next::());\n\n println!(\n \"{}\",\n [\"\", \"1/1\", \"5/6\", \"2/3\", \"1/2\", \"1/3\", \"1/6\"][std::cmp::max(a, b) as usize]\n );\n}\n\n// ---------- Begin Scanner ----------\n#[allow(dead_code)]\nmod scanner {\n use std::fmt::Debug;\n use std::str::FromStr;\n\n pub struct TokenReader {\n reader: std::io::Stdin,\n tokens: Vec,\n index: usize,\n }\n\n impl TokenReader {\n pub fn new() -> Self {\n Self {\n reader: std::io::stdin(),\n tokens: Vec::new(),\n index: 0,\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index += 1;\n self.tokens[self.index - 1].parse().unwrap()\n }\n\n pub fn vector(&mut self) -> Vec\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index = self.tokens.len();\n self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()\n }\n\n pub fn load_next_line(&mut self) {\n let mut line = String::new();\n self.reader.read_line(&mut line).unwrap();\n\n self.tokens = line.split_whitespace().map(String::from).collect();\n self.index = 0;\n }\n }\n}\n// ---------- End Scanner ----------\n", "lang_cluster": "Rust", "tags": ["math", "probabilities"], "code_uid": "69673de2d566164a81dcc787c29aa38c", "src_uid": "f97eb4ecffb6cbc8679f0c621fd59414", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/9/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let mut ns = buf.split(\" \")\n .map(|str| str.trim().parse::().unwrap());\n let y = ns.next().unwrap();\n let w = ns.next().unwrap();\n let r = std::cmp::max(y, w);\n println!(\"{}\",\n match (6 - r) + 1 {\n 1 => \"1/6\",\n 2 => \"1/3\",\n 3 => \"1/2\",\n 4 => \"2/3\",\n 5 => \"5/6\",\n 6 => \"1/1\",\n _ => unreachable!()\n }\n );\n}\n", "lang_cluster": "Rust", "tags": ["math", "probabilities"], "code_uid": "c17305a0a90d8735a568ae0eb09424cb", "src_uid": "f97eb4ecffb6cbc8679f0c621fd59414", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_nums() -> Vec {\n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input)\n\t\t.expect(\"\");\n\n\tinput.trim()\n\t\t.split_whitespace()\n\t\t.map(|d| i32::from_str(d).unwrap())\n\t\t.collect::>()\n}\n\n\nfn get_pair() -> (i32, i32) {\n\tlet v = get_nums();\n\n\t(v[0], v[1])\n}\n\n\nfn gcd(x: i32, y: i32) -> i32 {\n\tif y == 0 {\n\t\tx\n\t} else {\n\t\tgcd(y, x%y)\n\t}\n}\n\t\t\n\nfn main() {\n\tlet (y, w) = get_pair();\n\n\tlet m = if y > w { y } else { w };\n\tlet c = 7-m;\n\tlet g = gcd(c, 6);\n\n\tprintln!(\"{}/{}\", c/g, 6/g); \n}", "lang_cluster": "Rust", "tags": ["math", "probabilities"], "code_uid": "d53a9b34993132d3f9aa53a044d7f051", "src_uid": "f97eb4ecffb6cbc8679f0c621fd59414", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// This code is licensed under the terms of Apache-2.0 or MIT License , at your choice.\n\nuse crate::comprog_lib::scanner::Scanner;\nuse std::io::{self, Read, Write};\npub fn solve(read: R, out: &mut W) -> io::Result<()> {\n\tlet mut sc = Scanner::from(read);\n\tlet n = sc.usize();\n\tlet s = sc.token();\n\tlet mut dp = vec![vec![std::i32::MAX; n + 1]; n + 1];\n\tfor i in 0..=n {\n\t\tdp[i][i] = 0;\n\t}\n\tfor len in 1..=n {\n\t\tfor l in 0..=n - len {\n\t\t\tlet r = l + len;\n\t\t\tdp[l][r] = std::iter::once(1 + dp[l + 1][r])\n\t\t\t\t.chain((l + 1..r).filter(|&i| s[l] == s[i]).map(|i| dp[l + 1][i] + dp[i][r]))\n\t\t\t\t.min()\n\t\t\t\t.unwrap();\n\t\t}\n\t}\n\tlet ans = dp[0][n]; //assert_eq!(ans, naive(&s));\n\twriteln!(out, \"{}\", ans)?;\n\tOk(())\n}\nfn main() {\n\tlet stdin = io::stdin();\n\tlet mut stdout = io::BufWriter::new(io::stdout());\n\tsolve(stdin.lock(), &mut stdout).unwrap();\n}\nmod comprog_lib {\n\t// comprog_lib-0.1.0\n\tpub mod scan_buf {\n\t\tuse std::io::{self, Read};\n\t\t#[derive(Debug, Clone)]\n\t\tpub struct ScanBuf {\n\t\t\tbuf: Vec,\n\t\t\tpos: usize,\n\t\t\tend: usize,\n\t\t}\n\t\t#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]\n\t\tpub struct ScanRange(pub usize, pub usize);\n\t\timpl ScanRange {\n\t\t\tpub fn slice(self, buf: &ScanBuf) -> &[u8] {\n\t\t\t\t&buf.buf[self.0..self.1]\n\t\t\t}\n\t\t}\n\t\timpl ScanBuf {\n\t\t\tpub fn new(initial_capacity: usize) -> Self {\n\t\t\t\tScanBuf { buf: vec![0; initial_capacity], pos: 0, end: 0 }\n\t\t\t}\n\t\t\tpub fn scan bool>(\n\t\t\t\t&mut self,\n\t\t\t\tmut reader: R,\n\t\t\t\tmut pred: P,\n\t\t\t) -> io::Result {\n\t\t\t\tlet start = self.pos;\n\t\t\t\tloop {\n\t\t\t\t\tif self.pos >= self.end {\n\t\t\t\t\t\tif self.pos >= self.buf.len() {\n\t\t\t\t\t\t\tlet new_len = std::cmp::max(self.buf.len(), 1) * 2;\n\t\t\t\t\t\t\tself.buf.resize(new_len, 0);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tself.end += match reader.read(&mut self.buf[self.pos..]) {\n\t\t\t\t\t\t\tOk(0) => return Ok(ScanRange(start, self.pos)),\n\t\t\t\t\t\t\tOk(n) => n,\n\t\t\t\t\t\t\tErr(ref e) if e.kind() == io::ErrorKind::Interrupted => 0,\n\t\t\t\t\t\t\tErr(e) => return Err(e),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tassert!(self.end <= self.buf.len());\n\t\t\t\t\twhile self.pos < self.end {\n\t\t\t\t\t\tif pred(self.buf[self.pos]) {\n\t\t\t\t\t\t\treturn Ok(ScanRange(start, self.pos));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tself.pos += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tpub mod scanner {\n\t\tuse crate::comprog_lib::scan_buf::{ScanBuf, ScanRange};\n\t\tuse std::io::Read;\n\t\t#[derive(Debug, Clone)]\n\t\tpub struct Scanner {\n\t\t\tpub reader: R,\n\t\t\tpub buf: ScanBuf,\n\t\t}\n\t\timpl From for Scanner {\n\t\t\tfn from(r: R) -> Self {\n\t\t\t\tScanner { reader: r, buf: ScanBuf::new(8192) }\n\t\t\t}\n\t\t}\n\t\timpl Scanner {\n\t\t\tpub fn scan bool>(&mut self, pred: P) -> ScanRange {\n\t\t\t\tself.buf.scan(&mut self.reader, pred).unwrap()\n\t\t\t}\n\t\t\tfn digits(&mut self) -> (bool, &[u8]) {\n\t\t\t\tself.scan(|b| b' ' < b);\n\t\t\t\tlet mut negative = false;\n\t\t\t\tself.scan(|b| b != b'-' || std::mem::replace(&mut negative, true));\n\t\t\t\tlet digits = self.scan(|b| b < b'0' || b'9' < b);\n\t\t\t\t(negative, digits.slice(&self.buf))\n\t\t\t}\n\t\t\tpub fn token_range(&mut self) -> ScanRange {\n\t\t\t\tself.scan(|b| b' ' < b);\n\t\t\t\tself.scan(|b| b <= b' ')\n\t\t\t}\n\t\t\tpub fn token(&mut self) -> Vec {\n\t\t\t\tself.token_range().slice(&self.buf).to_owned()\n\t\t\t}\n\t\t}\n\t\tmacro_rules! impl_scan_int { ($($name:ident),*) => { impl Scanner { $( #[allow(unused)] pub fn $name(&mut self) -> $name { let (neg, digits) = self.digits(); if !neg { digits.iter().fold($name::default(), |x, b| x * 10 + $name::from(b - b'0')) } else { digits.iter().fold($name::default(), |x, b| x * 10 - $name::from(b - b'0')) } } )* } } }\n\t\timpl_scan_int!(u32, i32, u64, i64, usize);\n\t}\n}\n// Module comprog_lib contains code from comprog_lib licensed under Apache-2.0 OR MIT\n// Built by comprog-0.1.0 \n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "8d6820d54bc5599fa9d116dc218f9159", "src_uid": "516a89f4d1ae867fc1151becd92471e6", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// This code is licensed under the terms of Apache-2.0 or MIT License , at your choice.\n\nuse crate::comprog_lib::scanner::Scanner;\nuse std::cmp::min;\nuse std::io::{self, Read, Write};\npub fn solve(read: R, out: &mut W) -> io::Result<()> {\n let mut sc = Scanner::from(read);\n let n = sc.usize();\n let s = sc.token();\n let mut next = vec![[n; 26]; n + 1];\n for i in (0..n).rev() {\n next[i] = next[i + 1].clone();\n next[i][(s[i] - b'a') as usize] = i;\n }\n #[allow(non_snake_case)]\n let INF = std::i32::MAX;\n let mut dp = vec![vec![INF; n + 1]; n + 1];\n let mut dp2 = vec![vec![[INF; 26]; n + 1]; n + 1];\n for i in 0..=n {\n dp[i][i] = 0;\n for a in 0..26 {\n dp2[i][i][a] = 0;\n }\n }\n for len in 1..=n {\n for l in 0..=n - len {\n let r = l + len;\n for a in 0..26 {\n let mut x = len as i32;\n if (s[r - 1] - b'a') as usize == a {\n x = min(x, dp2[l][r - 1][a]);\n }\n for k in l + 1..r {\n x = min(x, dp2[l][k][a] + dp[k][r]);\n }\n dp2[l][r][a] = x;\n }\n dp[l][r] = dp2[l][r].iter().cloned().min().unwrap() + 1;\n }\n }\n let ans = dp[0][n];\n writeln!(out, \"{}\", ans)?;\n Ok(())\n}\nfn main() {\n let stdin = io::stdin();\n let mut stdout = io::BufWriter::new(io::stdout());\n solve(stdin.lock(), &mut stdout).unwrap();\n}\nmod comprog_lib {\n // comprog_lib-0.1.0\n pub mod scan_buf {\n use std::io::{self, Read};\n #[derive(Debug, Clone)]\n pub struct ScanBuf {\n buf: Vec,\n pos: usize,\n end: usize,\n }\n #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]\n pub struct ScanRange(pub usize, pub usize);\n impl ScanRange {\n pub fn slice(self, buf: &ScanBuf) -> &[u8] {\n &buf.buf[self.0..self.1]\n }\n }\n impl ScanBuf {\n pub fn new(initial_capacity: usize) -> Self {\n ScanBuf {\n buf: vec![0; initial_capacity],\n pos: 0,\n end: 0,\n }\n }\n pub fn scan bool>(\n &mut self,\n mut reader: R,\n mut pred: P,\n ) -> io::Result {\n let start = self.pos;\n loop {\n if self.pos >= self.end {\n if self.pos >= self.buf.len() {\n let new_len = std::cmp::max(self.buf.len(), 1) * 2;\n self.buf.resize(new_len, 0);\n }\n self.end += match reader.read(&mut self.buf[self.pos..]) {\n Ok(0) => return Ok(ScanRange(start, self.pos)),\n Ok(n) => n,\n Err(ref e) if e.kind() == io::ErrorKind::Interrupted => 0,\n Err(e) => return Err(e),\n };\n }\n assert!(self.end <= self.buf.len());\n while self.pos < self.end {\n if pred(self.buf[self.pos]) {\n return Ok(ScanRange(start, self.pos));\n }\n self.pos += 1;\n }\n }\n }\n }\n }\n pub mod scanner {\n use crate::comprog_lib::scan_buf::{ScanBuf, ScanRange};\n use std::io::Read;\n #[derive(Debug, Clone)]\n pub struct Scanner {\n pub reader: R,\n pub buf: ScanBuf,\n }\n impl From for Scanner {\n fn from(r: R) -> Self {\n Scanner {\n reader: r,\n buf: ScanBuf::new(8192),\n }\n }\n }\n impl Scanner {\n pub fn scan bool>(&mut self, pred: P) -> ScanRange {\n self.buf.scan(&mut self.reader, pred).unwrap()\n }\n fn digits(&mut self) -> (bool, &[u8]) {\n self.scan(|b| b' ' < b);\n let mut negative = false;\n self.scan(|b| b != b'-' || std::mem::replace(&mut negative, true));\n let digits = self.scan(|b| b < b'0' || b'9' < b);\n (negative, digits.slice(&self.buf))\n }\n pub fn token_range(&mut self) -> ScanRange {\n self.scan(|b| b' ' < b);\n self.scan(|b| b <= b' ')\n }\n pub fn token(&mut self) -> Vec {\n self.token_range().slice(&self.buf).to_owned()\n }\n }\n macro_rules! impl_scan_int { ($($name:ident),*) => { impl Scanner { $( #[allow(unused)] pub fn $name(&mut self) -> $name { let (neg, digits) = self.digits(); if !neg { digits.iter().fold($name::default(), |x, b| x * 10 + $name::from(b - b'0')) } else { digits.iter().fold($name::default(), |x, b| x * 10 - $name::from(b - b'0')) } } )* } } }\n impl_scan_int!(u32, i32, u64, i64, usize);\n }\n}\n// Module comprog_lib contains code from comprog_lib licensed under Apache-2.0 OR MIT\n// Built by comprog-0.1.0 \n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "a9d9a3898b94d6b71677d24cbf338216", "src_uid": "516a89f4d1ae867fc1151becd92471e6", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let n: usize = it.next().unwrap().parse().unwrap();\n let s: Vec = it.next().unwrap().chars().collect();\n let mut dp = vec![vec![0; n]; n];\n for len in 1..=n {\n for l in 0..=(n - len) {\n let r = l + len - 1;\n dp[l][r] = len;\n if l + 1 < n {\n dp[l][r] = dp[l + 1][r] + 1;\n }\n for k in (l + 1)..=r {\n if s[l] == s[k] {\n dp[l][r] = std::cmp::min(dp[l][r], dp[l + 1][k - 1] + dp[k][r]);\n }\n }\n }\n }\n println!(\"{}\", dp[0][n - 1]);\n}\n\nfn main() {\n run();\n}", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "12e63ed30f06c6f7f14da94588070c22", "src_uid": "516a89f4d1ae867fc1151becd92471e6", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt,$x:expr,$y:expr) => {{\n\t\tlet b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! vec_dim {\n\t([$d:expr]$($s:tt)+) => {vec![vec_dim!($($s)+);$d]}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn rec(l: usize, r: usize, s: &[u8], memo: &mut [Vec>]) -> usize {\n\tif l > r { return 0; }\n\tif let Some(res) = memo[l][r] {\n\t\treturn res;\n\t}\n\tlet mut res = r-l+1;\n\tfor i in l+1..=r {\n\t\tm!(<, res, rec(l,i-1,s,memo) + rec(i,r,s,memo));\n\t\tif s[l] == s[i] {\n\t\t\tm!(<, res, rec(l+1,i-1,s,memo) + rec(i,r,s,memo));\n\t\t}\n\t}\n\tmemo[l][r].replace(res);\n\tres\n}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet n = rin.u();\n\tlet s = rin.vb();\n\tlet mut dp = vec_dim!([n][n] = None);\n\tfor i in 0..n {\n\t\tdp[i][i].replace(1);\n\t}\n\tlet sol = rec(0, n-1, &s, &mut dp);\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "fee8547962edbbe28681a69a5320def7", "src_uid": "516a89f4d1ae867fc1151becd92471e6", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut sin = ReadIn::new();\n let a = sin.intvec();\n let s: i32 = a.iter().sum();\n let x = (0..64).any(|b| if count(b) != 3 { false } else {\n (0..6)\n .filter_map(|i| if b & (1 << i) != 0 { Some(a[i as usize]) } else { None })\n .sum::() * 2 == s\n });\n println!(\"{}\", if x {\"YES\"} else {\"NO\"});\n}\n\nfn count(i: i32) -> i32 {\n if i == 0 { 0 } else { 1 + count(i & (i - 1)) }\n}\n\nuse std::iter::*;\nuse std::str::SplitWhitespace;\nuse std::io::stdin;\nuse std::mem::forget;\n\npub struct ReadIn(pub String);\n\nimpl ReadIn {\n pub fn new() -> ReadIn { ReadIn(String::new()) }\n fn read_i32(s: &str) -> i32 { s.parse().unwrap() }\n pub fn read_line(&mut self) {\n self.0.clear();\n forget(stdin().read_line(&mut self.0));\n }\n pub fn ints(&mut self) -> Map i32> {\n self.read_line();\n self.0.split_whitespace().map(ReadIn::read_i32)\n }\n pub fn intvec(&mut self) -> Vec { self.ints().collect() }\n pub fn int(&mut self) -> i32 { self.ints().next().unwrap() }\n pub fn int2(&mut self) -> (i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap())\n }\n\n pub fn int3(&mut self) -> (i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n pub fn int4(&mut self) -> (i32, i32, i32, i32) {\n let mut it = self.ints();\n (it.next().unwrap(), it.next().unwrap(), it.next().unwrap(), it.next().unwrap())\n }\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "bbe64e4552cf64f5897025e9037b39f0", "src_uid": "2acf686862a34c337d1d2cbc0ac3fd11", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let a = get!(usize;;);\n\n for p in 0usize..1 << 6 {\n if p.count_ones() != 3 {\n continue;\n }\n\n let mut x = 0;\n let mut y = 0;\n\n for k in 0..6 {\n if (p >> k) & 1 == 1 {\n x += a[k];\n } else {\n y += a[k];\n }\n }\n if x == y {\n println!(\"YES\");\n return;\n }\n }\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "b7acc7e14bfb9ddda0edaecff4a2a126", "src_uid": "2acf686862a34c337d1d2cbc0ac3fd11", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut s=String::new();\n let mut c:usize=0;\n let mut a:Vec=Vec::new();\n let mut b:Vec=Vec::new();\n let mut n:usize=0;\n let mut sum:i32=0;\n let mut p:usize=0;\n io::stdin().read_line(&mut s).unwrap();\n s.trim();\n while c0{println!(\"YES\")}\n else{println!(\"NO\")}\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "99c9093820daee01c19252707a34357b", "src_uid": "2acf686862a34c337d1d2cbc0ac3fd11", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line(mut buffer: &mut String) -> Vec {\n std::io::stdin().read_line(&mut buffer).expect(\"Error while reading input.\");\n let data = buffer.split_whitespace().map(|x| x.parse::().unwrap()).collect();\n buffer.clear();\n data\n}\n\nfn get_index(i: usize, n: usize) -> String {\n let bin_str = format!(\"{:0width$b}\", i, width = n);\n bin_str\n}\n\nfn limit(n: usize) -> usize {\n let mut n_bin = String::with_capacity(n);\n for _i in 0..n {\n n_bin.push('1');\n }\n let limit = usize::from_str_radix(&n_bin, 2).unwrap();\n limit\n}\nfn calculate(index: &String, c: &Vec, min: usize, max: usize, diff: usize) -> usize {\n let mut sum = 0;\n let mut cmin = 10_usize.pow(6) + 1;\n let mut cmax = 0;\n for (i, ch) in index.chars().enumerate() {\n if ch == '1' {\n if c[i] > cmax {\n cmax = c[i];\n }\n if c[i] < cmin {\n cmin = c[i];\n }\n sum += c[i]; \n }\n }\n // need to find min and max\n if sum >= min && sum <= max && (cmax - cmin) >= diff {\n return 1 \n }\n 0\n}\n\nfn get_count(index: &String) -> usize {\n let mut count = 0;\n for ch in index.split(\"\") {\n if ch == \"1\" {\n count += 1;\n }\n }\n count\n}\n\nfn main() {\n let mut buffer = String::new();\n \n let d = read_line(&mut buffer);\n //println!(\"D: {:?}\", d);\n \n let (n, min, max, diff) = (d[0], d[1], d[2], d[3]);\n \n let c = read_line(&mut buffer);\n //println!(\"c: {:?}\", c);\n\n let limit = limit(n);\n let mut result = 0;\n\n for i in 1..=limit {\n let index = get_index(i, n);\n let count = get_count(&index);\n if count > 1 { \n //println!(\"{:?}\", index);\n let res = calculate(&index, &c, min, max, diff);\n if res == 1 {\n //println!(\"now\");\n }\n result += res;\n }\n }\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "bitmasks"], "code_uid": "8bf8c454e2bf57c72b92813a6956fe81", "src_uid": "0d43104a0de924cdcf8e4aced5aa825d", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn board(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn framed_board(&mut self, r: usize, c: usize, f: u8) -> Vec> {\n\t\tlet mut res = v!([r+2]);\n\t\tres.push( v!([c+2] = f) );\n\t\trep!{[r]\n\t\t\tlet mut t = self.vb();\n\t\t\tassert!(t.len() == c);\n\t\t\tt.reserve(2);\n\t\t\tt.insert(0,f);\n\t\t\tt.push(f);\n\t\t\tres.push(t);\n\t\t}\n\t\tres.push( v!([c+2] = f) );\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n\tfn graph(&mut self, n: usize, m: usize) -> Vec> {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e\n\t}\n\tfn graph_w(&mut self, n: usize, m: usize) -> Vec> where T::Err: Debug {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet b = rin.l();\n\tlet s = rin.vb();\n\tlet n = s.len();\n\tlet mut dp = v!([n+1] = std::i64::MAX);\n\tdp[0] = 0;\n\tfor i in 0..n {\n\t\tlet mut x = 0;\n\t\tfor j in i..n {\n\t\t\tx = x * 10 + (s[j] - b'0') as i64;\n\t\t\tif (s[i] == b'0' && j > i) || x >= b {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmin!(dp[j+1], dp[i].saturating_mul(b).saturating_add(x));\n\t\t}\n\t}\n\twriteln!(rout, \"{}\", dp[n]).ok();\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "math", "dp", "greedy", "strings"], "code_uid": "978e2f7a28d05ac98ef5ce16ffcb91bb", "src_uid": "be66399c558c96566a6bb0a63d2503e5", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let n = parse_line!(u64);\n let s: Vec<_> = parse_line!(String).bytes().map(|c| (c - b'0') as u64).collect();\n let l = s.len();\n let mut dp = vec![std::u64::MAX; l + 1];\n dp[0] = 0;\n let mut digits = vec![0; l + 1];\n for (i, &c) in s.iter().enumerate() {\n for j in (1..=i + 1).rev() {\n digits[j] = digits[j - 1] * 10 + c;\n }\n for j in 0..=i {\n if digits[j + 1] >= n {\n break;\n }\n if j > 0 && s[i - j] == 0 {\n continue;\n }\n dp[i + 1] = std::cmp::min(dp[i + 1], dp[i - j] * n + digits[j + 1]);\n }\n }\n println!(\"{}\", dp[l]);\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "math", "dp", "greedy", "strings"], "code_uid": "f9b4351c0f06e9d28491a6d2991585e5", "src_uid": "be66399c558c96566a6bb0a63d2503e5", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::*;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok();\n return ret;\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.is_err() || res.ok().unwrap() == 0 || u8b[0] <= ' ' as u8 {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = std::string::String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\nfn parse(s: &str) -> T { s.parse::().ok().unwrap() }\n\n#[allow(dead_code)]\nfn get() -> T { parse(&get_word()) }\n\nfn numero(v: &[i64], b: i64) -> Option {\n let mut cur: i64 = 0;\n for &t in v.iter() {\n cur = match cur.checked_mul(b) {\n Some(v) => v,\n None => return None,\n };\n cur = match cur.checked_add(t) {\n Some(v) => v,\n None => return None,\n }\n }\n Some(cur)\n}\n\nfn checked_propagate(b: i64, x: i64, y: i64) -> Option {\n let cur = match x.checked_mul(b) {\n Some(v) => v,\n None => return None,\n };\n cur.checked_add(y)\n}\n\n\nfn main() {\n let b: i64 = get();\n let s: Vec<_> = get_word().bytes().map(|b| b as i64 - 0x30).collect();\n let n = s.len();\n if b <= 9 {\n // simply read b-base rep.\n let mut cur = 0;\n for v in s {\n cur *= b;\n cur += v;\n }\n println!(\"{}\", cur);\n return;\n }\n let mut dp = vec![-1i64; n + 1];\n const INF: i64 = 1i64 << 60;\n dp[0] = 0;\n for i in 1 .. n + 1 {\n let mut mi = INF;\n for j in 1 .. i + 1 {\n // s[i - j ..i] < b ?\n if j >= 10 || dp[i - j] < 0 || (j >= 2 && s[i - j] == 0) {\n continue;\n }\n let sl = numero(&s[i - j .. i], 10);\n match sl {\n Some(v) if v < b => match checked_propagate(b, dp[i - j], v) {\n Some(v) => { mi = min(mi, v) },\n None => {},\n },\n _ => {},\n }\n }\n if mi < INF {\n dp[i] = mi;\n }\n }\n //println!(\"{:?}\", dp);\n println!(\"{}\", dp[n]);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "math", "dp", "greedy", "strings"], "code_uid": "35df3bcdeb74b9792f53f314670deac4", "src_uid": "be66399c558c96566a6bb0a63d2503e5", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\nuse std::str::FromStr;\n\nfn main() {\n let stdin = stdin();\n let mut sc = Scanner::new(stdin.lock());\n let n = sc.next::();\n let m = sc.next::();\n let k = sc.next::();\n\n if k < n {\n println!(\"{} 1\", k + 1);\n return;\n }\n let y = n - (k - n) / (m - 1);\n let r = (k - n) % (m - 1);\n let x = if y % 2 == 0 { 2 + r } else { m - r };\n println!(\"{} {}\", y, x);\n}\n\n// k < n \u306a\u30891\u5217\u76ee\n// n < k \u306a\u3089 snake \u79fb\u52d5\u306e\u9014\u4e2d\n// \u4e0b\u304b\u3089 (n - k) / (m - 1)\n\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "2bdb64c75ef591e1a5a508871b16b76b", "src_uid": "e88bb7621c7124c54e75109a00f96301", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\n\nfn solve(n: i64, m: i64, k: i64) -> (i64, i64) {\n \n if k < n {\n return (k + 1, 1);\n }\n \n let e = k - n;\n let r = e / (m - 1);\n let c = e % (m - 1);\n \n let y = n - r;\n let x = if r % 2 == 0 { c + 2 } else { m - c }; \n \n return (y, x);\n}\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n let m = get!();\n let k = get!();\n \n if n * m < 20 {\n for e in 0..n*m {\n let (row, col) = solve(n, m, e);\n let (r, c) = brute_force(n, m, e);\n if row != r || col != c {\n //println!(\"error {} {} {}\", n, m, e);\n //println!(\"solve {} {}\", row, col);\n //println!(\"bf {} {}\", r, c);\n //panic!();\n break;\n }\n }\n }\n \n let (row, col) = solve(n, m, k);\n \n println!(\"{} {}\", row, col);\n \n}\n\nfn brute_force(n: i64, m: i64, k: i64) -> (i64, i64) {\n let mut row = 1;\n let mut col = 1;\n let mut rem = k;\n \n if rem == 0 {\n return (row, col);\n }\n \n for _ in 0..n-1 {\n row += 1;\n rem -= 1;\n if rem == 0 {\n return (row, col);\n }\n }\n \n let mut state = 0;\n for _ in 0..rem {\n match state {\n 0 => {\n col += 1;\n if col == m {\n state += 1;\n }\n },\n 2 => {\n col -= 1;\n if col == 2 {\n state += 1;\n }\n },\n _ => {\n row -= 1;\n state = (state + 1) % 4;\n },\n }\n }\n return (row, col);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "50cc4a4bdb3fd9590616fbdde138d40c", "src_uid": "e88bb7621c7124c54e75109a00f96301", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::BinaryHeap;\nuse std::io;\n\nfn get_line() -> io::Result {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf)?;\n Ok(buf)\n}\n\nfn main() -> io::Result<()> {\n get_line()?;\n let buf = get_line()?;\n let mut iter = buf.split_ascii_whitespace().map(|x| x.parse().unwrap());\n\n let init = iter.next().unwrap();\n let a: Vec = iter.collect();\n\n let mut heap = BinaryHeap::from(a);\n let mut ans = 0;\n\n while *heap.peek().unwrap() >= init + ans {\n let top = heap.pop().unwrap();\n heap.push(top - 1);\n ans += 1;\n }\n\n println!(\"{}\", ans);\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "c9a7778539f1fb320b021f98d498835a", "src_uid": "aa8fabf7c817dfd3d585b96a07bb7f58", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n}\n\nfn process(colors: &[u64], perm: &Vec) -> u64 {\n let mut result = 0u64;\n let mut lcolors = [0u64, 0, 0];\n lcolors.clone_from_slice(colors);\n for current in perm {\n if *current == 3 {\n let take = *lcolors.iter().min().unwrap();\n result += take;\n for i in &mut lcolors {\n *i -= take;\n }\n continue;\n }\n result += lcolors[*current] / 3;\n lcolors[*current] %= 3;\n }\n result\n}\n\nfn permutations(colors: &[u64], current: &mut Vec, step: usize, result: &mut u64) {\n if step == 4 {\n *result = (*result).max(process(colors, current));\n return;\n }\n for i in 0..4 {\n if let None = current.iter().find(|x| **x == i) {\n current.push(i);\n permutations(colors, current, step + 1, result);\n current.pop();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let colors: Vec = scan.next_n(3);\n let mut result = 0u64;\n let mut perm: Vec = vec![];\n permutations(&colors, &mut perm, 0, &mut result);\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "0048706ff11fca71e25fe79b8deee638", "src_uid": "acddc9b0db312b363910a84bd4f14d8e", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_string() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n input\n}\n\nfn main(){\n \n let mut x = read_string();\n x = x.replace(\"\\r\", \"\");\n let vec: Vec<&str> = x.split(\"\").collect();\n let mut found: bool = false;\n for n in 2..(vec.len()-3){\n if ((vec[n] != \".\") && (vec[n+1] != \".\") && (vec[n-1] != \".\")) &&\n ((vec[n] != vec[n+1]) && (vec[n-1] != vec[n+1]) && (vec[n] != vec[n-1]))\n {\n found = true;\n break\n }\n }\n println!(\"{}\", if found {\"YES\"} else {\"NO\"});\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "bd361e7b5a8b67ef0f5451100d675371", "src_uid": "ba6ff507384570152118e2ab322dd11f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Stdin;\n\nfn read_line(stdin : &Stdin, line : &mut String) {\n match stdin.read_line(line) {\n Ok(_) => return,\n Err(msg) => panic!(\"Could not read line! Message: {}.\", msg),\n }\n}\n\nfn contains_3_colors(s : &String) -> bool {\n let contains_abc = s.contains(\"ABC\");\n let contains_acb = s.contains(\"ACB\");\n let contains_bac = s.contains(\"BAC\");\n let contains_bca = s.contains(\"BCA\");\n let contains_cab = s.contains(\"CAB\");\n let contains_cba = s.contains(\"CBA\");\n contains_abc || contains_acb ||\n contains_bac || contains_bca ||\n contains_cab || contains_cba\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut s = String::new();\n read_line(&stdin, &mut s);\n if contains_3_colors(&s) {\n println!(\"Yes\")\n } else {\n println!(\"No\");\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "17e2237a4d6517ad8f96af3999216185", "src_uid": "ba6ff507384570152118e2ab322dd11f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let n: usize = get_line().trim().parse().unwrap();\n\n let mut input = String::new();\n use std::io::Read;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let a: Vec = input.split_whitespace()\n .map(|x| x.parse().unwrap()).collect();\n\n let next = |winner, spec| {\n 6 - winner - spec\n };\n\n let specs: Vec<_> = a.iter().scan(3, |state, winner| {\n let spec = *state;\n *state = next(winner, spec);\n Some(spec)\n }).collect();\n\n let ans = (0..n).all(|i| a[i] != specs[i]);\n\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\nstruct Solver {\n\n}\n\nimpl Solver {\n\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "225f997c49206fc04319d3843d133bd8", "src_uid": "6c7ab07abdf157c24be92f49fd1d8d87", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet, BinaryHeap, VecDeque, BTreeSet, BTreeMap};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let n = get!(usize);\n let games = get!(usize;n);\n\n let mut players = (1, 2);\n let mut spec = 3;\n\n for g in games {\n if g == players.0 {\n let t = spec;\n spec = players.1;\n players = (g, t);\n } else if g == players.1 {\n let t = spec;\n spec = players.0;\n players = (g, t);\n } else {\n println!(\"NO\");\n return;\n }\n }\n\n println!(\"YES\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f9339a35a80bdfe3e6dd27fa6a459889", "src_uid": "6c7ab07abdf157c24be92f49fd1d8d87", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n a: [usize; n],\n }\n let mut x = 1;\n let mut y = 2;\n let mut z = 3;\n for a in a {\n if a == x {\n std::mem::swap(&mut y, &mut z);\n } else if a == y {\n std::mem::swap(&mut x, &mut z);\n } else {\n println!(\"NO\");\n return;\n }\n }\n println!(\"YES\");\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "224db373adf38dbb028652129bb2c486", "src_uid": "6c7ab07abdf157c24be92f49fd1d8d87", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let nk = input.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n let k = &nk[1];\n\n input.clear();\n stdin().read_line(&mut input).unwrap();\n let buckets = input.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n\n let mut best_time = 100;\n for bucket in buckets {\n if k % bucket == 0 && k / bucket < best_time {\n best_time = k / bucket;\n }\n }\n println!(\"{}\", best_time);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5cc8967da29b7daee031c1a8af81c838", "src_uid": "80520be9916045aca3a7de7bc925af1f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let k = buffer.split_whitespace()\n .map(|x| x.trim().parse::().unwrap())\n .last()\n .unwrap();\n buffer.clear();\n io::stdin().read_line(&mut buffer).unwrap();\n let bucket = buffer.split_whitespace()\n .map(|x| x.trim().parse::().unwrap())\n .filter(|x| k % x == 0)\n .max()\n .unwrap();\n\n println!(\"{}\", k / bucket);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e8e66729816f4c95e0158e67a8afaaf6", "src_uid": "80520be9916045aca3a7de7bc925af1f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let k = input.i();\n let sol = k / input.ii(n).filter(|&x| k % x == 0).max().unwrap();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "eceabc012d709520f69a0813c0b6f270", "src_uid": "80520be9916045aca3a7de7bc925af1f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n\nfn main() {\n let (n, k) = get!(usize, usize);\n let aa = get!(usize;;);\n\n let ans = aa.iter()\n .filter_map(|&a| if k % a == 0 { Some(k / a) } else { None })\n .min()\n .unwrap();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7df100b03302a1d396d0199d3bfca5b2", "src_uid": "80520be9916045aca3a7de7bc925af1f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn main () {\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Can't read input\\n\");\n let inp = input\n .split_whitespace()\n .map(|s| s.parse()\n .expect(\"Can't parse input\")).collect::>();\n let (n, k) = (inp[0], inp[1]);\n input.clear();\n stdin().read_line(&mut input).expect(\"Can't read input\\n\");\n let inp1 = input\n .split_whitespace()\n .map(|s| s.parse().expect(\"Can't parse input\"))\n .collect::>();\n\n let h = inp1\n .into_iter()\n .map(|x| (k / x, k % x))\n .filter(|&(_, r)| r == 0)\n .min_by(|a, b| a.0.cmp(&b.0))\n .unwrap()\n .0;\n println!(\"{}\", h);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "cb1fe42e5cd7be98675f51606a5e4328", "src_uid": "80520be9916045aca3a7de7bc925af1f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut s:String=String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut c:usize=0;\n let mut n:usize=0;\n let mut a:Vec=Vec::new();\n while c=Vec::new();\n while ca/b[c] && a%b[c]==0{\n n=a/b[c];\n }\n }\n println!(\"{}\",n)\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a65617bfc5e0f93778915c3dd450b4ed", "src_uid": "80520be9916045aca3a7de7bc925af1f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n println!(\n \"{}\",\n match n {\n 11..=19 | 21 => {\n 4\n }\n 20 => {\n 15\n }\n _ => {\n 0\n }\n }\n );\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5872d883a628dd976b30ed9e175ad005", "src_uid": "5802f52caff6015f21b80872274ab16c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::prelude::*;\n use std::io;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let n: usize = it.next().unwrap().parse().unwrap();\n let d: i32 = it.next().unwrap().parse().unwrap();\n\n let mut cl: Vec = it.map(|x| x.parse().unwrap()).collect();\n\n cl.sort_unstable();\n\n for i in (1..n + 1).rev() {\n let p = cl.windows(i).any(|win| *win.last().unwrap() - *win.first().unwrap() <= d);\n if p {\n let ans = n - i;\n println!(\"{}\", ans);\n return;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "3c56ba7efa59dc98ed0a712a6fddc2a7", "src_uid": "6bcb324c072f796f4d50bafea5f624b2", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::max;\n//use std::io::prelude::*;\n\n\nfn main() {\n let nd = get_ints();\n let mut nums = get_ints();\n nums.sort();\n\n println!(\"{}\", min_points(nd, nums));\n\n}\n\n\nfn min_points(nd : Vec, nums : Vec) -> i32 {\n let n = nd[0] as usize;\n let d = nd[1] ;\n\n let mut high : usize = 0;\n let mut ans : usize = 0;\n\n for low in 0..n {\n while high < n && nums[high] - nums[low] <= d {\n ans = max(ans, high - low);\n high += 1;\n }\n }\n\n (n-ans-1) as i32\n\n}\n\n\nfn get_ints() -> Vec {\n let mut input_text = String::new();\n io::stdin().read_line( &mut input_text )\n .expect( \"could not read line\" );\n let numbers : Vec = input_text.trim()\n .split_whitespace()\n .map(|x| x.parse::().unwrap())\n .collect();\n\n numbers\n}", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "9bc625c63a4ca670bae2ab1ab2048dfb", "src_uid": "6bcb324c072f796f4d50bafea5f624b2", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros, dead_code)]\nuse std::f64::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! dump{\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nconst INF: i64 = 0x3f3f3f3f3f3f3f3f;\nconst MOD: i64 = 1000000007;\nconst NOTHING: usize = std::usize::MAX;\nconst DX: [usize; 4] = [1, 0, std::usize::MAX, 0];\nconst DY: [usize; 4] = [0, 1, 0, std::usize::MAX];\n\nfn main() {\n let (n, d): (usize, usize) = readln();\n let xs: Vec = readln();\n\n let mut res: usize = n;\n for l in 1..101 {\n let r = l + d;\n let mut cnt = 0;\n for &x in &xs {\n if x < l || r < x {\n cnt += 1;\n }\n }\n res = min(res, cnt);\n }\n println!(\"{}\", res);\n}\n\ntrait Read {\n fn read(s: &str) -> Self;\n}\n\nfn readln() -> T {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n T::read(buf.trim_right())\n}\n\nmacro_rules! read_impl{\n ($($t:ty)*) => ($(\n impl Read for $t {\n fn read(s: &str) -> $t{\n s.parse().unwrap()\n }\n }\n )*)\n}\nread_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }\n\nimpl Read for String {\n fn read(s: &str) -> Self {\n s.to_string()\n }\n}\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.chars().collect()\n }\n}\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.split_whitespace().map(T::read).collect()\n }\n}\n\nimpl Read for (A, B) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]))\n }\n}\n\nimpl Read for (A, B, C) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))\n }\n}\n\nimpl Read for (A, B, C, D) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]), D::read(tokens[3]))\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "d7a5990be12e9d48ad81769fd5d489b1", "src_uid": "6bcb324c072f796f4d50bafea5f624b2", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n#![allow(non_camel_case_types)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{max, min, Ordering};\nuse std::f64::consts::*;\nuse std::mem::{swap, size_of_val, size_of};\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\nuse std::num::*;\nuse std::process::*;\n//use std::ptr::*;\nuse std::iter::{once, repeat};\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\nstruct Input {\n\tbuffer: Buf,\n}\n\nimpl Input {\n\tfn read_char(&mut self) -> char {\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\tx[0] as char\n\t}\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n}\n\nmacro_rules! read {\n () => {};\n\t($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect(\"Parsing error\"));\n\t($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect(\"Parsing error\")),*));\n}\nfn gcd(mut a: T, mut b: T) -> T\n\twhere T: ShrAssign + BitAnd + Ord + From + Clone + SubAssign + ShlAssign + Copy\n{\n\tlet one = T::from(1);\n\tlet zero = T::from(0);\n\tlet mut ans = 0;\n\tif a < b {\n\t\tswap(&mut a, &mut b);\n\t}\n\twhile b > zero {\n\t\tif (a & one > zero) && (b & one > zero) {\n\t\t\ta -= b;\n\t\t} else if a & one > zero {\n\t\t\tb >>= one;\n\t\t} else if b & one > zero {\n\t\t\ta >>= one;\n\t\t} else {\n\t\t\tans += 1;\n\t\t\ta >>= one;\n\t\t\tb >>= one;\n\t\t}\n\t\tif a < b {\n\t\t\tswap(&mut a, &mut b);\n\t\t}\n\t}\n\ta <<= ans;\n\ta\n}\n\nfn powmod(mut base: X, mut exp: Y, mm: X) -> X\n\twhere X: Copy + Clone + Mul + Rem + From,\n\t Y: ShrAssign + Copy + Clone + BitAnd + From + Ord\n{\n\tlet mut res = X::from(1);\n\twhile exp > Y::from(0) {\n\t\tif exp & Y::from(1) > Y::from(0) {\n\t\t\tres = res * base % mm;\n\t\t}\n\t\tbase = base * base % mm;\n\t\texp >>= Y::from(1);\n\t}\n\tres\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\")) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet stdin = stdin();\n\t\t\tlet istr = stdin.lock();\n\t\t\tlet mut inf = Input { buffer: BufReader::new(istr) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output) {\n\tlet (n, d) = read!(inf,usize,i32);\n\tlet mut a = vec![0; n];\n\tfor i in 0..n {\n\t\ta[i] = read!(inf,i32);\n\t}\n\ta.sort_unstable();\n\tlet mut ans = n;\n\tfor i in 0..n {\n\t\tfor j in i..n {\n\t\t\tif a[j] - a[i] <= d {\n\t\t\t\tans = min(ans, i + n - 1 - j);\n\t\t\t}\n\t\t}\n\t}\n\twriteln!(ouf, \"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "b851d7e5d512f5fbe6b2a539bb841de0", "src_uid": "6bcb324c072f796f4d50bafea5f624b2", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::i32;\nuse std::cmp;\n\nfn read() -> Vec {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf);\n let nums: Vec = buf.split(' ')\n .map(|x| x.trim().parse().unwrap())\n .collect();\n return nums;\n}\n\nfn main() {\n let nums = read();\n let n = nums[0];\n let d = nums[1];\n let mut cnt = [0; 101];\n let xs = read();\n for x in xs {\n cnt[x as usize] += 1;\n }\n let mut mn = 0;\n for i in 1..100 {\n let mut sum = 0;\n for j in i..cmp::min(i+d, 100)+1 {\n sum += cnt[j as usize];\n }\n mn = cmp::max(mn, sum);\n }\n println!(\"{}\", n-mn);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "758fcf72cd0ea0ce9fa85a4a74c45266", "src_uid": "6bcb324c072f796f4d50bafea5f624b2", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n\nconst INF: i32 = 1000000000;\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: usize = scan.token();\n let jump_length: usize = scan.token();\n let s: Vec = scan.token::().chars().collect();\n let mut dp = vec![INF; n];\n dp[0] = 0;\n for i in 1..n {\n if s[i] == '1' {\n for j in 1..=jump_length {\n if i >= j {\n dp[i] = dp[i].min(dp[i - j] + 1);\n }\n }\n }\n }\n let ans = if dp[n - 1] >= INF { - 1 } else { dp[n - 1] };\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "greedy", "dp", "implementation"], "code_uid": "7b285dba71547e7aa379f383311e48c1", "src_uid": "c08d2ecdfc66cd07fbbd461b1f069c9e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n\nconst INF: i32 = 1000000000;\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: usize = scan.token();\n let jump_length: usize = scan.token();\n let s: Vec = scan.token::().chars().collect();\n let mut dp = vec![INF; n];\n dp[0] = 0;\n // for i in 1..n {\n // if s[i] == '1' {\n // for j in 1..=jump_length {\n // if i >= j {\n // dp[i] = dp[i].min(dp[i - j] + 1);\n // }\n // }\n // }\n // }\n // let ans = if dp[n - 1] >= INF { - 1 } else { dp[n - 1] };\n for i in 0..n {\n if s[i] == '1' {\n for j in 1..=jump_length {\n if i + j < n {\n dp[i + j] = dp[i + j].min(dp[i] + 1);\n }\n }\n }\n }\n let ans = if dp[n - 1] >= INF { - 1 } else { dp[n - 1] };\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "greedy", "dp", "implementation"], "code_uid": "7a730e0268116c481ab4d46d9fe0517e", "src_uid": "c08d2ecdfc66cd07fbbd461b1f069c9e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[warn(unused_variables)]\nfn main() {\n let v = input_vec::(\" \");\n let n = v[0];\n let d = v[1];\n\n let mut count = 0;\n let mut pu = true;\n let p = input_str();\n let s: Vec<&str> = p.trim().split(\"1\").collect();\n for n in s {\n if n.chars().count() >= d {\n pu = false;\n }\n }\n\n if !pu {\n println!(\"-1\")\n } else {\n let mut ci = 0;\n let mut cs = d;\n 'a: loop {\n if ci + d >= n-1 {\n println!(\"{}\", count+1);\n break 'a;\n }\n\n if p.chars().collect::>()[ci + cs] != '0' {\n count += 1;\n ci += cs;\n cs = d;\n } else {\n cs -= 1;\n }\n }\n }\n\n}\n\nfn input_str() -> String {\n let mut buff = String::new();\n std::io::stdin().read_line(&mut buff).expect(\"Err\");\n buff\n}\n\nfn input_() -> T\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().parse::().expect(\"Err pars\")\n}\n\n\nfn input_vec(sep: &str) -> Vec \nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n input_str().trim().split(sep).map(|c| c.parse::().expect(\"Err pars\")).collect()\n}\n\nfn input_vec_chars() -> Vec {\n input_str().trim().chars().collect()\n}", "lang_cluster": "Rust", "tags": ["dfs and similar", "greedy", "dp", "implementation"], "code_uid": "d545fefd4fdf775de60439ff31564c19", "src_uid": "c08d2ecdfc66cd07fbbd461b1f069c9e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\nuse std::str::FromStr;\n\nfn main() {\n let stdin = stdin();\n let mut sc = Scanner::new(stdin.lock());\n let n = sc.next::();\n let s = sc.next::();\n let zeros = s.chars().filter(|&c| c == '0').count() as u32;\n let result = std::iter::repeat(\"0\")\n .take(zeros as usize)\n .collect::();\n if n == zeros {\n println!(\"{}\", result);\n } else {\n println!(\"1{}\", result);\n }\n}\n\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "fd5ba8093bcf7a66dcf7025f1e64a090", "src_uid": "ac244791f8b648d672ed3de32ce0074d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n if n == 1 {\n let s = get();\n println!(\"{}\", s);\n return;\n }\n let s = get().as_bytes();\n let mut zeros = 0;\n for &c in s {\n if c== b'0' {\n zeros += 1;\n }\n }\n print!(\"1\");\n for _ in 0..zeros {\n print!(\"0\");\n }\n println!();\n \n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5cb5977e1497d56c180716675c219502", "src_uid": "ac244791f8b648d672ed3de32ce0074d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n\n}\nfn _main() {\n let mut scan = Scan::new();\n let sum1: usize = scan.next_n(3).iter().sum();\n let sum2: usize = scan.next_n(3).iter().sum();\n let n: usize = scan.next();\n let needed: usize = sum1/5 + sum2/10 + if sum1%5!=0 {1} else {0} \n + if sum2%10!=0 {1} else {0};\n println!(\"{}\", if n>=needed {\"YES\"} else {\"NO\"});\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6e8fe9e18f46fa5acf0ec2eb0fd69d6b", "src_uid": "fe6301816dea7d9cea1c3a06a7d1ea7e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 2018-10-14 22:34\nfn main() {\n let v1: Vec = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim()\n .split(\" \")\n .map(|s| s.parse::().unwrap())\n .collect()\n };\n let v2: Vec = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim()\n .split(\" \")\n .map(|s| s.parse::().unwrap())\n .collect()\n };\n let n: i32 = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n };\n\n let n1 = (v1.iter().sum::() as f32 / 5.0).ceil() as i32;\n let n2 = (v2.iter().sum::() as f32 / 10.0).ceil() as i32;\n println!(\"{}\", if (n1 + n2) <= n { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9aba351830c2cb7e1bd6c40543c19e25", "src_uid": "fe6301816dea7d9cea1c3a06a7d1ea7e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, std::io::stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut buffer = String::new();\n let mut input = WordReader::from_stdin(&mut buffer);\n\n let need = {\n let mut f = |d: i32| (input.vp::(3).into_iter().sum::() + d - 1) / d;\n f(5) + f(10)\n };\n let n = input.i();\n let sol = if need <= n {\n \"YES\"\n } else {\n \"NO\"\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d5d40b66a61ead71e8a0d4e06755a8cd", "src_uid": "fe6301816dea7d9cea1c3a06a7d1ea7e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\n\n\nfn main(){\n let cin = std::io::stdin();\n let mut mp = HashMap::with_capacity(10);\n let mut origs = String::new();\n cin.read_line(&mut origs)\n .expect(\"lol\");\n for i in 0u32..11u32{\n let mut s = String::new();\n cin.read_line(&mut s)\n .expect(\"lol\");\n mp.insert(String::from(s.trim()),i);\n }\n for i in 0..=7{\n let sl: &str = &origs[i*10..i*10+10];\n let s = String::from(sl);\n let val: &u32 = mp.get(&s).expect(\"\");\n print!(\"{}\",val);\n }\n println!(\"\");\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "e1dec65b74d4de4cbd96661dcdb8324b", "src_uid": "0f4f7ca388dd1b2192436c67f9ac74d9", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn count_pre(m: u64, n: u64) -> u64 {\n let mut ans = 0;\n let mut k = 0;\n while (m << k) <= n {\n if (m << k) + (1 << k) - 1 <= n {\n ans += 1 << k;\n } else {\n ans += n - (m << k) + 1;\n }\n k += 1;\n }\n ans\n}\n\nfn count(m: u64, n: u64) -> u64 {\n if m % 2 == 1 {\n count_pre(m, n)\n } else {\n count_pre(m, n) + count_pre(m + 1, n)\n }\n}\n\nfn run() {\n input! {\n n: u64,\n k: u64,\n }\n let mut ans = 1;\n let mut ok = 0;\n let mut ng = n / 2 + 1;\n while ng - ok > 1 {\n let m = (ok + ng) / 2;\n if count(2 * m + 1, n) >= k {\n ok = m;\n } else {\n ng = m;\n }\n }\n ans = std::cmp::max(ans, 2 * ok + 1);\n if count(2, n) >= k {\n let mut ok = 1;\n let mut ng = n / 2 + 1;\n while ng - ok > 1 {\n let m = (ok + ng) / 2;\n if count(2 * m, n) >= k {\n ok = m;\n } else {\n ng = m;\n }\n }\n ans = std::cmp::max(ans, 2 * ok);\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "binary search", "dp", "combinatorics"], "code_uid": "9edcd0876e49ba747a20064861ede618", "src_uid": "783c4b3179c558369f94f4a16ac562d4", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::max;\n\nfn check(res: i64, k: i64, pow: i64, n:i64) -> bool{\n if res % 2 == 0 {\n res * pow + (k - 2 * pow + 1) <= n\n } else {\n let mut pow_k = 1;\n let mut b_k = k;\n loop {\n if b_k > 1{\n pow_k *= 2;\n b_k /= 2;\n } else { break; }\n }\n res * pow_k + (k - pow_k) <= n\n }\n}\n\nfn main() {\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n let mut n:i64 = iter.next().unwrap().parse().unwrap();\n let mut k:i64 = iter.next().unwrap().parse().unwrap();\n let mut b_k = k + 1;\n let mut pow = 1;\n loop {\n if b_k > 1{\n pow *= 2;\n b_k /= 2;\n } else { break; }\n }\n pow /= 2;\n let mut res = n / pow;\n while !check(res, k, pow, n) { res -=1; }\n loop {\n if check(res + 1, k, pow, n) { res +=1; }\n else if check(res + 2, k, pow, n) { res +=2; }\n else {break;}\n }\n println!(\"{}\", res);\n //println!(\"{}\", pow);\n}\n//4 5 8 9 10 11\n//5 -> 3 -> \n//3 -> 1\n\n// k <= 2 + 4 + 8 + .. pow => k + 2 <= 2 * pow\n// 2 + 4 +8 + .. + pow = 2\n// 6 * 2 + (5 - 2)\n// 2 + 4 + 8 //+ 16 20 - 2,4,8 = 6 .. 2 * 8 = 16 + (20 - 2 - 4 - 8 - 1) = 21\n\n// 5 - 2,2 - 1, 4\n// 6 <= 2 + 4\n// 10 2 -> 9\n\n// 12 ,13 24,25,26,27 48\n// 13, 26,27.. 52 \n// 14,15 28,29,30\n\n//27, 3\n", "lang_cluster": "Rust", "tags": ["math", "binary search", "dp", "combinatorics"], "code_uid": "121e702fc6260af7880c8f0154850a93", "src_uid": "783c4b3179c558369f94f4a16ac562d4", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//---------- begin union_find ----------\npub struct DSU {\n parent: Vec,\n size: Vec,\n stack: Vec>,\n}\n\nimpl DSU {\n pub fn new(n: usize) -> DSU {\n assert!(n < std::u32::MAX as usize);\n let mut res = DSU {\n parent: vec![0; n],\n size: vec![1; n],\n stack: vec![],\n };\n res.init();\n res\n }\n pub fn init(&mut self) {\n self.stack.clear();\n for (i, (parent, size)) in self.parent.iter_mut().zip(self.size.iter_mut()).enumerate() {\n *parent = i as u32;\n *size = 1;\n }\n }\n pub fn root(&self, mut x: usize) -> usize {\n assert!(x < self.parent.len());\n while self.parent[x] != x as u32 {\n x = self.parent[x] as usize;\n }\n x\n }\n pub fn same(&self, x: usize, y: usize) -> bool {\n assert!(x < self.parent.len());\n assert!(y < self.parent.len());\n self.root(x) == self.root(y)\n }\n pub fn unite(&mut self, x: usize, y: usize) -> Option<(usize, usize)> {\n assert!(x < self.parent.len());\n assert!(y < self.parent.len());\n let mut x = self.root(x);\n let mut y = self.root(y);\n if x == y {\n self.stack.push(None);\n return None;\n }\n if self.size[x] < self.size[y] {\n std::mem::swap(&mut x, &mut y);\n }\n self.size[x] += self.size[y];\n self.parent[y] = x as u32;\n self.stack.push(Some((x as u32, y as u32)));\n Some((x, y))\n }\n pub fn parent(&self, x: usize) -> Option {\n assert!(x < self.parent.len());\n let p = self.parent[x];\n if p != x as u32 {\n Some(p as usize)\n } else {\n None\n }\n }\n pub fn size(&self, x: usize) -> usize {\n assert!(x < self.parent.len());\n let r = self.root(x);\n self.size[r] as usize\n }\n pub fn undo(&mut self) -> Option<(usize, usize)> {\n self.stack.pop().unwrap().map(|(x, y)| {\n let x = x as usize;\n let y = y as usize;\n self.size[x] -= self.size[y];\n self.parent[y] = y as u32;\n (x, y)\n })\n }\n}\n//---------- end union_find ----------\n// ---------- begin SegmentTree Point update Range query ----------\nmod segment_tree {\n pub struct PURQ {\n n: usize,\n a: Vec,\n id: T,\n op: F,\n }\n #[allow(dead_code)]\n impl T> PURQ {\n pub fn new(n: usize, id: T, op: F) -> PURQ {\n let mut k = 1;\n while k < n {\n k *= 2;\n }\n PURQ {\n n: k,\n a: vec![id.clone(); 2 * k],\n id: id,\n op: op,\n }\n }\n pub fn update(&mut self, x: usize, v: T) {\n let mut k = self.n + x;\n let a = &mut self.a;\n a[k] = v;\n k >>= 1;\n while k > 0 {\n a[k] = (self.op)(&a[2 * k], &a[2 * k + 1]);\n k >>= 1;\n }\n }\n pub fn update_tmp(&mut self, x: usize, v: T) {\n self.a[x + self.n] = v;\n }\n pub fn update_all(&mut self) {\n let a = &mut self.a;\n for k in (1..(self.n)).rev() {\n a[k] = (self.op)(&a[2 * k], &a[2 * k + 1]);\n }\n }\n pub fn find(&self, mut l: usize, mut r: usize) -> T {\n let mut p = self.id.clone();\n let mut q = self.id.clone();\n l += self.n;\n r += self.n;\n let a = &self.a;\n while l < r {\n if (l & 1) == 1 {\n p = (self.op)(&p, &a[l]);\n l += 1;\n }\n if (r & 1) == 1 {\n r -= 1;\n q = (self.op)(&a[r], &q);\n }\n l >>= 1;\n r >>= 1;\n }\n (self.op)(&p, &q)\n }\n }\n}\n// ---------- end SegmentTree Point update Range query ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\n// N <= 2 * 10^5, Q <= 5 * 10^5\n// \u30af\u30a8\u30ea\u5e73\u65b9\u5206\u5272\u3067\u884c\u3051\u308b\u304cTL\u602a\u3057\u3044\n// \u524a\u9664\u30af\u30a8\u30ea\u6271\u3044\u8f9b\u3044\n// \u9006\u304b\u3089\u898b\u308b\uff1f\n// \u6700\u5927\u5024\u30af\u30a8\u30ea\u304c\u5bfe\u51e6\u4e0d\u80fd\u306b\u898b\u3048\u308b\n// \u6728\u3067\u3068\u3051\u308b\u304b\n// \u9006\u304b\u3089\u307f\u3066\u3063\u305f\u8fba\u524a\u9664\u30af\u30a8\u30ea\u3067\u68ee\u304c\u4f5c\u308c\u3066\u3001\u3053\u308c\u3067\u89e3\u3051\u308c\u3070\u3044\u3044\n// \u3046\u307e\u3044\u3053\u3068\u68ee\u3092\u533a\u9593\u3067\u7ba1\u7406\u3067\u304d\u308c\u3070\u3088\u3044\n// \u3069\u3046\u3084\u3063\u3066\u533a\u9593\u3092\u4f5c\u308d\u3046\n\nuse std::io::Write;\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n q: usize,\n val: [u32; n],\n e: [(usize1, usize1); m],\n ask: [(u8, usize1); q],\n }\n let mut dsu = DSU::new(n);\n let mut del = vec![false; m];\n for &(op, k) in ask.iter() {\n if op == 2 {\n del[k] = true;\n }\n }\n let mut add = vec![0; n];\n for (&(a, b), del) in e.iter().zip(del.iter()) {\n if !*del {\n if let Some((a, b)) = dsu.unite(a, b) {\n dsu.undo();\n add[b] = dsu.size(a);\n dsu.unite(a, b);\n }\n }\n }\n let mut width = vec![0; q];\n for (width, &(op, k)) in width.iter_mut().zip(ask.iter()).rev() {\n if op == 2 {\n let (a, b) = e[k];\n if let Some((a, b)) = dsu.unite(a, b) {\n dsu.undo();\n add[b] = dsu.size(a);\n dsu.unite(a, b);\n }\n } else {\n *width = dsu.size(k);\n }\n }\n let mut r = vec![];\n for i in 0..n {\n if i == dsu.root(i) {\n r.push(i);\n }\n }\n for r in r.windows(2) {\n let (a, b) = (r[0], r[1]);\n if let Some((a, b)) = dsu.unite(a, b) {\n dsu.undo();\n add[b] = dsu.size(a);\n dsu.unite(a, b);\n }\n }\n let mut index = vec![0; n];\n for i in 0..n {\n let mut pos = i;\n let mut sum = add[pos];\n while let Some(p) = dsu.parent(pos) {\n pos = p;\n sum += add[pos];\n }\n index[i] = sum;\n }\n for r in r.windows(2) {\n dsu.undo();\n }\n let mut seg = segment_tree::PURQ::new(n, (0, n), |a, b| std::cmp::max(*a, *b));\n for (i, &val) in val.iter().enumerate() {\n let k = index[i];\n seg.update_tmp(k, (val, k));\n }\n seg.update_all();\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n for (&(op, k), &width) in ask.iter().zip(width.iter()) {\n if op == 1 {\n let l = index[dsu.root(k)];\n let r = l + width;\n let (val, k) = seg.find(l, r);\n if k < n {\n seg.update(k, (0, n));\n }\n writeln!(out, \"{}\", val).ok();\n } else {\n dsu.undo();\n }\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dsu", "graphs", "data structures", "implementation", "trees"], "code_uid": "bee4a019e9833384e6619470c1ca1ba5", "src_uid": "ad014bde729222db14f38caa521e4167", "difficulty": 2600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//---------- begin union_find ----------\npub struct DSU {\n parent: Vec,\n size: Vec,\n stack: Vec>,\n}\n\nimpl DSU {\n pub fn new(n: usize) -> DSU {\n assert!(n < std::u32::MAX as usize);\n let mut res = DSU {\n parent: vec![0; n],\n size: vec![1; n],\n stack: vec![],\n };\n res.init();\n res\n }\n pub fn init(&mut self) {\n self.stack.clear();\n for (i, (parent, size)) in self.parent.iter_mut().zip(self.size.iter_mut()).enumerate() {\n *parent = i as u32;\n *size = 1;\n }\n }\n pub fn root(&self, mut x: usize) -> usize {\n assert!(x < self.parent.len());\n while self.parent[x] != x as u32 {\n x = self.parent[x] as usize;\n }\n x\n }\n pub fn same(&self, x: usize, y: usize) -> bool {\n assert!(x < self.parent.len());\n assert!(y < self.parent.len());\n self.root(x) == self.root(y)\n }\n pub fn unite(&mut self, x: usize, y: usize) -> Option<(usize, usize)> {\n assert!(x < self.parent.len());\n assert!(y < self.parent.len());\n let mut x = self.root(x);\n let mut y = self.root(y);\n if x == y {\n self.stack.push(None);\n return None;\n }\n if (self.size[x], x) < (self.size[y], y) {\n std::mem::swap(&mut x, &mut y);\n }\n self.size[x] += self.size[y];\n self.parent[y] = x as u32;\n self.stack.push(Some((x as u32, y as u32)));\n Some((x, y))\n }\n pub fn parent(&self, x: usize) -> Option {\n assert!(x < self.parent.len());\n let p = self.parent[x];\n if p != x as u32 {\n Some(p as usize)\n } else {\n None\n }\n }\n pub fn size(&self, x: usize) -> usize {\n assert!(x < self.parent.len());\n let r = self.root(x);\n self.size[r] as usize\n }\n pub fn undo(&mut self) -> Option<(usize, usize)> {\n self.stack.pop().unwrap().map(|(x, y)| {\n let x = x as usize;\n let y = y as usize;\n self.size[x] -= self.size[y];\n self.parent[y] = y as u32;\n (x, y)\n })\n }\n}\n//---------- end union_find ----------\n// ---------- begin SegmentTree Point update Range query ----------\nmod segment_tree {\n pub struct PURQ {\n n: usize,\n a: Vec,\n id: T,\n op: F,\n }\n #[allow(dead_code)]\n impl T> PURQ {\n pub fn new(n: usize, id: T, op: F) -> PURQ {\n let mut k = 1;\n while k < n {\n k *= 2;\n }\n PURQ {\n n: k,\n a: vec![id.clone(); 2 * k],\n id: id,\n op: op,\n }\n }\n pub fn update(&mut self, x: usize, v: T) {\n let mut k = self.n + x;\n let a = &mut self.a;\n a[k] = v;\n k >>= 1;\n while k > 0 {\n a[k] = (self.op)(&a[2 * k], &a[2 * k + 1]);\n k >>= 1;\n }\n }\n pub fn update_tmp(&mut self, x: usize, v: T) {\n self.a[x + self.n] = v;\n }\n pub fn update_all(&mut self) {\n let a = &mut self.a;\n for k in (1..(self.n)).rev() {\n a[k] = (self.op)(&a[2 * k], &a[2 * k + 1]);\n }\n }\n pub fn find(&self, mut l: usize, mut r: usize) -> T {\n let mut p = self.id.clone();\n let mut q = self.id.clone();\n l += self.n;\n r += self.n;\n let a = &self.a;\n while l < r {\n if (l & 1) == 1 {\n p = (self.op)(&p, &a[l]);\n l += 1;\n }\n if (r & 1) == 1 {\n r -= 1;\n q = (self.op)(&a[r], &q);\n }\n l >>= 1;\n r >>= 1;\n }\n (self.op)(&p, &q)\n }\n }\n}\n// ---------- end SegmentTree Point update Range query ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\n// N <= 2 * 10^5, Q <= 5 * 10^5\n// \u30af\u30a8\u30ea\u5e73\u65b9\u5206\u5272\u3067\u884c\u3051\u308b\u304cTL\u602a\u3057\u3044\n// \u524a\u9664\u30af\u30a8\u30ea\u6271\u3044\u8f9b\u3044\n// \u9006\u304b\u3089\u898b\u308b\uff1f\n// \u6700\u5927\u5024\u30af\u30a8\u30ea\u304c\u5bfe\u51e6\u4e0d\u80fd\u306b\u898b\u3048\u308b\n// \u6728\u3067\u3068\u3051\u308b\u304b\n// \u9006\u304b\u3089\u307f\u3066\u3063\u305f\u8fba\u524a\u9664\u30af\u30a8\u30ea\u3067\u68ee\u304c\u4f5c\u308c\u3066\u3001\u3053\u308c\u3067\u89e3\u3051\u308c\u3070\u3044\u3044\n// \u3046\u307e\u3044\u3053\u3068\u68ee\u3092\u533a\u9593\u3067\u7ba1\u7406\u3067\u304d\u308c\u3070\u3088\u3044\n// \u3069\u3046\u3084\u3063\u3066\u533a\u9593\u3092\u4f5c\u308d\u3046\n\nuse std::io::Write;\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n q: usize,\n val: [u32; n],\n e: [(usize1, usize1); m],\n ask: [(u8, usize1); q],\n }\n let mut dsu = DSU::new(n);\n let mut del = vec![false; m];\n for &(op, k) in ask.iter() {\n if op == 2 {\n del[k] = true;\n }\n }\n let mut offset = vec![0; n];\n for (&(a, b), del) in e.iter().zip(del.iter()) {\n if !*del {\n if let Some((a, b)) = dsu.unite(a, b) {\n dsu.undo();\n offset[b] = dsu.size(a);\n dsu.unite(a, b);\n }\n }\n }\n let mut width = vec![0; q];\n for (width, &(op, k)) in width.iter_mut().zip(ask.iter()).rev() {\n if op == 2 {\n let (a, b) = e[k];\n if let Some((a, b)) = dsu.unite(a, b) {\n dsu.undo();\n offset[b] = dsu.size(a);\n dsu.unite(a, b);\n }\n } else {\n *width = dsu.size(k);\n }\n }\n let mut r = vec![];\n for i in 0..n {\n if i == dsu.root(i) {\n r.push(i);\n }\n }\n for r in r.windows(2) {\n let (a, b) = (r[0], r[1]);\n if let Some((a, b)) = dsu.unite(a, b) {\n dsu.undo();\n offset[b] = dsu.size(a);\n dsu.unite(a, b);\n }\n }\n let mut index = vec![0; n];\n for i in 0..n {\n let mut pos = i;\n let mut sum = offset[pos];\n while let Some(p) = dsu.parent(pos) {\n pos = p;\n sum += offset[pos];\n }\n index[i] = sum;\n }\n for _ in r.windows(2) {\n dsu.undo();\n }\n let mut seg = segment_tree::PURQ::new(n, (0, n), |a, b| std::cmp::max(*a, *b));\n for (i, &val) in val.iter().enumerate() {\n let k = index[i];\n seg.update_tmp(k, (val, k));\n }\n seg.update_all();\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n for (&(op, k), &width) in ask.iter().zip(width.iter()) {\n if op == 1 {\n let l = index[dsu.root(k)];\n let r = l + width;\n let (val, k) = seg.find(l, r);\n if k < n {\n seg.update(k, (0, n));\n }\n writeln!(out, \"{}\", val).ok();\n } else {\n dsu.undo();\n }\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dsu", "graphs", "data structures", "implementation", "trees"], "code_uid": "1a460bd5ae957e414596d34b5ded86a5", "src_uid": "ad014bde729222db14f38caa521e4167", "difficulty": 2600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut iter = s.trim().split_whitespace().map(|x| x.parse().unwrap());\n let (n, m, a, b): (u64, u64, u64, u64) = (iter.next().unwrap(), iter.next().unwrap(), iter.next().unwrap(), iter.next().unwrap());\n let demolition_cost = (n % m) * b;\n let build_cost = (m - (n % m)) * a;\n println!(\"{}\", cmp::min(demolition_cost, build_cost));\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "0c352c3c5dca943102b28de1d5a9bbd0", "src_uid": "c05d753b35545176ad468b99ff13aa39", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::*;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok();\n return ret;\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.is_err() || res.ok().unwrap() == 0 || u8b[0] <= ' ' as u8 {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = std::string::String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\nfn parse(s: &str) -> T { s.parse::().ok().unwrap() }\n\n#[allow(dead_code)]\nfn get() -> T { parse(&get_word()) }\n\nfn main() {\n let mut col: [u8; 4] = [0, 0, 0, 0];\n let mut col_no = HashMap::::new();\n col_no.insert(b'R', 0);\n col_no.insert(b'B', 1);\n col_no.insert(b'Y', 2);\n col_no.insert(b'G', 3);\n let s: Vec = get_word().bytes().collect();\n for i in 0 .. s.len() {\n if s[i] != b'!' {\n col[i % 4] = s[i];\n }\n }\n let mut nums = [0usize; 4];\n for i in 0 .. s.len() {\n if s[i] == b'!' {\n nums[*col_no.get(&col[i % 4]).unwrap()] += 1;\n }\n }\n for i in 0 .. 4 {\n print!(\"{}{}\", nums[i], if i == 3 { \"\\n\" } else { \" \" });\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "number theory"], "code_uid": "7672b2024bc89828f3f689d6f3c81634", "src_uid": "64fc6e9b458a9ece8ad70a8c72126b33", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io;\n\nfn main() {\n let blobs = \"RBYG\";\n\n let mut failure_position = HashMap::new();\n let mut pattern_position = HashMap::new();\n\n let mut garland = String::new();\n\n io::stdin().read_line(&mut garland).unwrap();\n\n for (index, blob) in garland.chars().enumerate() {\n let position = index % blobs.len();\n match blob {\n '!' => {\n *failure_position.entry(position).or_insert(0) += 1;\n },\n x => {\n pattern_position.insert(x, position);\n }\n }\n }\n\n for blob in blobs.chars() {\n match pattern_position.get(&blob) {\n Some(position) => print!(\"{} \", {\n failure_position.entry(*position).or_insert(0);\n failure_position[position]\n }),\n None => println!(\"Cannot infer position of {} from input\", blob)\n }\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "number theory"], "code_uid": "baa2e5dfefa5dd3457a43977c738c11e", "src_uid": "64fc6e9b458a9ece8ad70a8c72126b33", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io;\n\nfn main() {\n const BLOBS: &'static str = \"RBYG\";\n\n let mut failure_count: HashMap = HashMap::new();\n let mut pattern_position: HashMap = HashMap::new();\n\n let mut garland = String::new();\n\n io::stdin().read_line(&mut garland).unwrap();\n\n for (index, blob) in garland.chars().enumerate() {\n let position = index % BLOBS.len();\n match blob {\n '!' => {\n *failure_count.entry(position).or_insert(0) += 1;\n },\n x => {\n pattern_position.insert(x, position);\n }\n }\n }\n\n for blob in BLOBS.chars() {\n match pattern_position.get(&blob) {\n Some(position) => {\n print!(\"{} \", *failure_count.entry(*position).or_insert(0));\n },\n None => {\n println!(\"Cannot infer position of {} from input\", blob);\n }\n }\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "number theory"], "code_uid": "5e934e7505cfc161ab05938353ba79ce", "src_uid": "64fc6e9b458a9ece8ad70a8c72126b33", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Read;\nuse std::collections::VecDeque;\n\n\nfn main() {\n let mut text = String::new();\n io::stdin().read_to_string(&mut text).unwrap();\n let mut iter = text.split_whitespace().map(|x| x.parse::().unwrap());\n let m = iter.next().unwrap();\n let mut left = 1u64;\n let mut right = m * 100;\n while left < right {\n let mid = (left + right) / 2;\n if f(mid) < m {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n println!(\"{}\", if f(left) == m {left as i64} else {-1});\n}\n\nfn f(n: u64) -> u64 {\n let mut i = 2u64;\n let mut res = 0u64;\n while i * i * i <= n {\n res += n / (i * i * i);\n i += 1;\n }\n res\n}\n", "lang_cluster": "Rust", "tags": ["math", "binary search", "combinatorics"], "code_uid": "f9d0a01cab486aa78142d401ab4695f9", "src_uid": "602deaad5c66e264997249457d555129", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io;\nuse std::process;\n\nfn main() {\n if let Err(e) = run() {\n println!(\"error: {}\", e);\n process::exit(1);\n }\n}\n\nfn run() -> Result<(), Box> {\n let mut x = String::new();\n io::stdin().read_line(&mut x)?;\n let x: Vec = x.trim().split(\" \").map(|x| x.parse().expect(\"\")).collect();\n let a1 = x[0] * x[1] + x[3] * 2;\n let a2 = x[0] * x[2] + x[4] * 2;\n if a1 < a2 {\n println!(\"First\");\n } else if a1 == a2 {\n println!(\"Friendship\");\n } else {\n println!(\"Second\");\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "32ad871c9d12243616951bc740a48d15", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(isize);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n use std::cmp::Ordering;\n scanln!(s: u64, v1: u64, v2: u64, t1: u64, t2: u64);\n let e1 = (s * v1) + (2 * t1);\n let e2 = (s * v2) + (2 * t2);\n println!(\"{}\",\n match e1.cmp(&e2) {\n Ordering::Less => \"First\",\n Ordering::Greater => \"Second\",\n Ordering::Equal => \"Friendship\"\n }\n );\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "0d86cbef0f7a2e02e1f899e354a6fac6", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"INPUT::read line failed\");\n let mut input = input.trim().split(' ');\n let mut vec = vec![i32::default(); 5];\n\n\n for item in vec.iter_mut() {\n *item = input.next().unwrap().parse::().unwrap();\n }\n\n let outcome = (-vec[1] * vec[0] - vec[3] * 2) + (vec[2] * vec[0] + vec[4] * 2);\n\n if outcome > 0 {\n println!(\"First\");\n } else if outcome < 0 {\n println!(\"Second\");\n } else {\n println!(\"Friendship\");\n }\n\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "e4593e3ef44c784343cec690368e5334", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::fs::File;\nuse std::io::prelude::*;\nuse std::path::Path;\n\nfn main() -> std::io::Result<()> {\n let mut contents = String::new();\n\tstd::io::stdin().read_line(&mut contents)?;\n\tlet contents: Vec<&str> = contents.split(\"\\r\\n\").collect();\n\tlet contents: &str = contents[0];\n\tlet contents: Vec<&str> = contents.split_whitespace().collect();\n\tlet s = contents[0].trim().parse::().unwrap();\n\tlet v1 = contents[1].trim().parse::().unwrap();\n\tlet v2 = contents[2].trim().parse::().unwrap();\n\tlet t1 = contents[3].trim().parse::().unwrap();\n\tlet t2 = contents[4].trim().parse::().unwrap();\n\tlet first = t1+s*v1+t1;\n\tlet second = t2+s*v2+t2;\n\tif first < second {\n\t\tprintln!(\"First\");\n\t} else if first > second {\n\t\tprintln!(\"Second\");\n\t} else {\n\t\tprintln!(\"Friendship\");\n\t}\n\tOk(())\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "9e39bba43f81d63729da4c18a2bd6124", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n use std::io::stdin;\n\n let mut input = String::new();\n\n stdin().read_line(&mut input).unwrap();\n\n let mut input = input.split_whitespace().map(|k| k.parse::().unwrap());\n\n let s = input.next().unwrap();\n let v1 = input.next().unwrap();\n let v2 = input.next().unwrap();\n let t1 = input.next().unwrap();\n let t2 = input.next().unwrap();\n\n let d1 = v1 * s + 2 * t1;\n let d2 = v2 * s + 2 * t2;\n\n if d1 < d2 {\n println!(\"First\");\n } else if d2 < d1 {\n println!(\"Second\");\n } else {\n println!(\"Friendship\");\n };\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "98fdf90a045c7b0d50bb995fedcbbbe5", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (s,v1,v2,t1,t2) = readln!(i32,i32,i32,i32,i32);\n println!(\"{}\",match (t1*2+s*v1).cmp(&(t2*2+s*v2)) {\n std::cmp::Ordering::Less => \"First\",\n std::cmp::Ordering::Greater => \"Second\",\n std::cmp::Ordering::Equal => \"Friendship\",\n });\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "abee491f9339caedac5e1f76982ed64c", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::Ordering::*;\n\nfn input_split() -> Vec {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let input = input_split();\n let first = input[0] * input[1] + 2 * input[3];\n let second = input[0] * input[2] + 2 * input[4];\n print!(\n \"{}\",\n match first.cmp(&second) {\n Less => \"First\",\n Greater => \"Second\",\n Equal => \"Friendship\",\n }\n );\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "634d935589dc31d1f1e229d439d16b1a", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n let v = input.i();\n let w = input.i();\n let s = input.i();\n let t = input.i();\n use std::cmp::Ordering::*;\n println!(\"{}\", match (2*s + n*v).cmp(&(2*t + n*w)) {\n Less => \"First\",\n Greater => \"Second\",\n Equal => \"Friendship\",\n });\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "ef5bb170b1eb91518690b6b21b1ea6de", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve_part(v: &Vec<(usize, i64)>) -> Option {\n let diff = v[1].1 - v[0].1;\n let mut was_skipped = false;\n let mut skipped_id = v[0].0;\n let mut last = v[0].1 - diff;\n for (_, (pos, x)) in v.iter().enumerate() {\n if last + diff != *x {\n if was_skipped {\n return None;\n }\n was_skipped = true;\n skipped_id = *pos;\n continue;\n }\n last = *x;\n }\n Some(skipped_id as i64 + 1)\n}\n\nfn solve() {\n let s: Vec<_> = parse_line!(String).bytes().collect();\n let n = parse_line!(usize);\n let mut same = false;\n let mut first = false;\n let mut second = false;\n for _ in 0..n {\n let q: Vec<_> = parse_line!(String).bytes().collect();\n same |= s[0] == q[0] && s[1] == q[1];\n first |= s[0] == q[1];\n second |= s[1] == q[0];\n }\n println!(\"{}\", if same || (first && second) {\"YES\"} else {\"NO\"})\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "829ff94bb92ffbd527778b59ef4db367", "src_uid": "cad8283914da16bc41680857bd20fe9f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet};\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\nfn main() {\n let pass: Vec = util::line().chars().collect();\n let n: usize = util::get();\n let mut one = false;\n let mut second = false;\n\n for _ in 0..n {\n let w: Vec = util::line().chars().collect();\n if w == pass {\n println!(\"YES\");\n return;\n }\n one |= w[1] == pass[0];\n second |= w[0] == pass[1];\n\n if one && second {\n break;\n }\n }\n\n if one && second {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "a7fa98c042eda0e70b35b09cdec98917", "src_uid": "cad8283914da16bc41680857bd20fe9f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn parse_bin_val(s: &str) -> Vec {\n s.bytes().map(|byte| match byte {\n b'0' => false,\n b'1' => true,\n _ => panic!(\"NOT A BIT!\"),\n }).collect()\n}\n\nfn main() {\n let password = get_line().trim().to_string();\n\n let n: usize = get_line().trim().parse().unwrap();\n\n let words: Vec = BufReader::new(io::stdin()).lines().map(|s| {\n s.unwrap()\n }).collect();\n\n let mut first_letters = vec![false; 26];\n\n for b in words.iter().map(|s| s.bytes().nth(0).unwrap() - b'a') {\n first_letters[b as usize] = true;\n }\n\n let mut second_letters = vec![false; 26];\n\n for b in words.iter().map(|s| s.bytes().nth(1).unwrap() - b'a') {\n second_letters[b as usize] = true;\n }\n\n let l0 = password.bytes().nth(0).unwrap() - b'a';\n let l1 = password.bytes().nth(1).unwrap() - b'a';\n\n let ans = if let Some(_) = words.into_iter().find(|s| *s == password) {\n true\n } else {\n second_letters[l0 as usize] && first_letters[l1 as usize]\n };\n\n if ans {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "fee17623806fb2a0b2d4c2e759955bd8", "src_uid": "cad8283914da16bc41680857bd20fe9f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\nuse std::usize;\nuse std::collections::BinaryHeap;\nuse std::cmp::Ordering;\nuse std::collections::BTreeMap;\nuse std::collections::VecDeque;\nuse std::cmp;\n\nfn main() {\n let pass = read_line();\n let n = read_values::()[0];\n let words = (0..n).map(|_| read_line()).collect::>();\n for i in 0..n {\n if pass == words[i] {\n println!(\"YES\");\n return;\n }\n for j in 0..n {\n let b1 = pass.clone().into_bytes()[0];\n let b2 = pass.clone().into_bytes()[1];\n if b1 == words[i].clone().into_bytes()[1] && b2 == words[j].clone().into_bytes()[0] {\n println!(\"YES\");\n return;\n }\n }\n }\n println!(\"NO\");\n}\n\nfn read_line() -> String {\n let stdin = io::stdin();\n let mut buf = String::new();\n stdin.read_line(&mut buf).unwrap();\n buf\n}\n\nfn read_values() -> Vec\n where T: std::str::FromStr,\n T::Err: std::fmt::Debug\n{\n read_line()\n .split(' ')\n .map(|a| a.trim().parse().unwrap())\n .collect()\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "712d582b0f684c463ecb604f8535733c", "src_uid": "cad8283914da16bc41680857bd20fe9f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// SNIPPET read\npub trait Readable {\n type Output;\n fn words_count() -> usize;\n fn read_words(words: &[&str]) -> Result;\n}\n#[macro_export]\nmacro_rules! readable {\n ( $t:ty, $words_count:expr, |$words:ident| $read_words:expr ) => {\n impl Readable for $t {\n type Output = $t;\n fn words_count() -> usize { $words_count }\n fn read_words($words: &[&str]) -> Result<$t, String> {\n Ok($read_words)\n }\n }\n };\n}\nreadable!((), 1, |_ss| ());\nreadable!(String, 1, |ss| ss[0].to_string());\nimpl Readable for char {\n type Output = char;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n let chars: Vec = words[0].chars().collect();\n if chars.len() == 1 {\n Ok(chars[0])\n } else {\n Err(format!(\"cannot parse `{}` as a char\", words[0]))\n }\n }\n}\npub struct Chars();\nimpl Readable for Chars {\n type Output = Vec;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result, String> {\n Ok(words[0].chars().collect())\n }\n}\nimpl Readable for i8 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n i8::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(i8))\n })\n }\n}\nimpl Readable for u8 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n u8::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(u8))\n })\n }\n}\nimpl Readable for i16 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n i16::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(i16))\n })\n }\n}\nimpl Readable for u16 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n u16::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(u16))\n })\n }\n}\nimpl Readable for i32 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n i32::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(i32))\n })\n }\n}\nimpl Readable for u32 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n u32::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(u32))\n })\n }\n}\nimpl Readable for i64 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n i64::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(i64))\n })\n }\n}\nimpl Readable for u64 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n u64::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(u64))\n })\n }\n}\nimpl Readable for isize {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n ::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(isize))\n })\n }\n}\nimpl Readable for usize {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n ::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(usize))\n })\n }\n}\nimpl Readable for f32 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n f32::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(usize))\n })\n }\n}\nimpl Readable for f64 {\n type Output = Self;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n use std::str::FromStr;\n f64::from_str(words[0]).map_err(|_| {\n format!(\"cannot parse `{}` as {}\", words[0], stringify!(usize))\n })\n }\n}\n#[allow(non_camel_case_types)]\npub struct u8_;\nimpl Readable for u8_ {\n type Output = u8;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n u8::read_words(words).map(|n| n-1)\n }\n}\n#[allow(non_camel_case_types)]\npub struct u16_;\nimpl Readable for u16_ {\n type Output = u16;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n u16::read_words(words).map(|n| n-1)\n }\n}\n#[allow(non_camel_case_types)]\npub struct u32_;\nimpl Readable for u32_ {\n type Output = u32;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n u32::read_words(words).map(|n| n-1)\n }\n}\n#[allow(non_camel_case_types)]\npub struct u64_;\nimpl Readable for u64_ {\n type Output = u64;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n u64::read_words(words).map(|n| n-1)\n }\n}\n#[allow(non_camel_case_types)]\npub struct usize_;\nimpl Readable for usize_ {\n type Output = usize;\n fn words_count() -> usize { 1 }\n fn read_words(words: &[&str]) -> Result {\n ::read_words(words).map(|n| n-1)\n }\n}\nimpl Readable for (T1, T2) {\n type Output = (T1::Output, T2::Output);\n fn words_count() -> usize {\n T1::words_count() + T2::words_count()\n }\n fn read_words(words: &[&str]) -> Result {\n assert_eq!(words.len(), Self::words_count());\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let val2 = T2::read_words(&words[start..])?;\n Ok((val1, val2))\n }\n}\nimpl Readable for (T1, T2, T3) {\n type Output = (T1::Output, T2::Output, T3::Output);\n fn words_count() -> usize {\n T1::words_count() + T2::words_count() + T3::words_count()\n }\n fn read_words(words: &[&str]) -> Result {\n assert_eq!(words.len(), Self::words_count());\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let count2 = T2::words_count();\n let val2 = T2::read_words(&words[start .. start+count2])?;\n start += count2;\n let val3 = T3::read_words(&words[start..])?;\n Ok((val1, val2, val3))\n }\n}\nimpl Readable for (T1, T2, T3, T4) {\n type Output = (T1::Output, T2::Output, T3::Output, T4::Output);\n fn words_count() -> usize {\n T1::words_count() + T2::words_count() + T3::words_count() + T4::words_count()\n }\n fn read_words(words: &[&str]) -> Result {\n assert_eq!(words.len(), Self::words_count());\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let count2 = T2::words_count();\n let val2 = T2::read_words(&words[start .. start+count2])?;\n start += count2;\n let count3 = T3::words_count();\n let val3 = T3::read_words(&words[start .. start+count3])?;\n start += count3;\n let val4 = T4::read_words(&words[start..])?;\n Ok((val1, val2, val3, val4))\n }\n}\nimpl Readable for (T1, T2, T3, T4, T5) {\n type Output = (T1::Output, T2::Output, T3::Output, T4::Output, T5::Output);\n fn words_count() -> usize {\n T1::words_count() + T2::words_count() + T3::words_count() + T4::words_count() + T5::words_count()\n }\n fn read_words(words: &[&str]) -> Result {\n assert_eq!(words.len(), Self::words_count());\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let count2 = T2::words_count();\n let val2 = T2::read_words(&words[start .. start+count2])?;\n start += count2;\n let count3 = T3::words_count();\n let val3 = T3::read_words(&words[start .. start+count3])?;\n start += count3;\n let count4 = T4::words_count();\n let val4 = T4::read_words(&words[start .. start+count4])?;\n start += count4;\n let val5 = T5::read_words(&words[start..])?;\n Ok((val1, val2, val3, val4, val5))\n }\n}\nimpl Readable for (T1, T2, T3, T4, T5, T6) {\n type Output = (T1::Output, T2::Output, T3::Output, T4::Output, T5::Output, T6::Output);\n fn words_count() -> usize {\n T1::words_count() + T2::words_count() + T3::words_count() + T4::words_count() + T5::words_count() + T6::words_count()\n }\n fn read_words(words: &[&str]) -> Result {\n assert_eq!(words.len(), Self::words_count());\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let count2 = T2::words_count();\n let val2 = T2::read_words(&words[start .. start+count2])?;\n start += count2;\n let count3 = T3::words_count();\n let val3 = T3::read_words(&words[start .. start+count3])?;\n start += count3;\n let count4 = T4::words_count();\n let val4 = T4::read_words(&words[start .. start+count4])?;\n start += count4;\n let count5 = T5::words_count();\n let val5 = T5::read_words(&words[start .. start+count5])?;\n start += count5;\n let val6 = T6::read_words(&words[start..])?;\n Ok((val1, val2, val3, val4, val5, val6))\n }\n}\npub trait ReadableFromLine {\n type Output;\n fn read_line(line: &str) -> Result;\n}\nfn split_into_words(line: &str) -> Vec<&str> {\n #[allow(deprecated)]\n line.trim_right_matches('\\n').split_whitespace().collect()\n}\nimpl ReadableFromLine for T {\n type Output = T::Output;\n fn read_line(line: &str) -> Result {\n let words = split_into_words(line);\n if words.len() != T::words_count() {\n return Err(format!(\"line `{}` has {} words, expected {}\",\n line, words.len(), T::words_count()));\n }\n T::read_words(&words)\n }\n}\nfn read_words_into_vec(words: &[&str], line: &str) -> Result, String> {\n let n = T::words_count();\n assert_eq!(words.len() % n, 0);\n let mut result = Vec::new();\n for chunk in words.chunks(n) {\n match T::read_words(chunk) {\n Ok(v) => result.push(v),\n Err(msg) => {\n let fragment_msg = if n == 1 {\n format!(\"word {}\", result.len())\n } else {\n let l = result.len();\n format!(\"words {}-{}\", n*l + 1, (n+1) * l)\n };\n return Err(format!(\n \"{} of line `{}`: {}\", fragment_msg, line, msg\n ));\n }\n }\n }\n Ok(result)\n}\nfn split_into_words_for_collection(\n line: &str, prefix_words_count: usize\n) -> Result, String> {\n let n = T::words_count();\n let words = split_into_words(line);\n if words.len() < prefix_words_count {\n return Err(\n format!(\"line `{}` has {} words, expected at least {}\",\n line, words.len(), prefix_words_count)\n );\n }\n if (words.len() - prefix_words_count) % T::words_count() != 0 {\n return Err(\n format!(\"line `{}` has {} words, expected {} + {}n\",\n line, words.len(), prefix_words_count, n)\n );\n }\n Ok(words)\n}\n#[macro_export]\nmacro_rules! readable_collection {\n ($u:ident => $collection_in:ty, $collection_out:ty) => {\n readable_collection!($u: => $collection_in, $collection_out);\n };\n ($u:ident : $( $bound:path ),* => $collection_in:ty, $collection_out:ty) => {\n impl<$u: Readable> ReadableFromLine for $collection_in\n where\n <$u as Readable>::Output: Sized $(+ $bound)*\n {\n type Output = $collection_out;\n fn read_line(line: &str) -> Result {\n let words = split_into_words_for_collection::<$u>(line, 0)?;\n Ok(read_words_into_vec::<$u>(&words, line)?.into_iter().collect())\n }\n }\n impl ReadableFromLine for (T1, $collection_in)\n where\n <$u as Readable>::Output: Sized $(+ $bound)*\n {\n type Output = (T1::Output, $collection_out);\n fn read_line(line: &str) -> Result {\n let prefix_len = T1::words_count();\n let words = split_into_words_for_collection::<$u>(line, prefix_len)?;\n let val1 = T1::read_words(&words[..prefix_len])?;\n let rest = read_words_into_vec::<$u>(&words[prefix_len..], line)?;\n Ok((val1, rest.into_iter().collect()))\n }\n }\n impl ReadableFromLine for (T1, T2, $collection_in)\n where\n <$u as Readable>::Output: Sized $(+ $bound)*\n {\n type Output = (T1::Output, T2::Output, $collection_out);\n fn read_line(line: &str) -> Result {\n let prefix_len = <(T1, T2)>::words_count();\n let words = split_into_words_for_collection::<$u>(line, prefix_len)?;\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let count2 = T2::words_count();\n let val2 = T2::read_words(&words[start .. start+count2])?;\n let rest = read_words_into_vec::<$u>(&words[prefix_len..], line)?;\n Ok((val1, val2, rest.into_iter().collect()))\n }\n }\n impl ReadableFromLine for (T1, T2, T3, $collection_in)\n where\n <$u as Readable>::Output: Sized $(+ $bound)*\n {\n type Output = (T1::Output, T2::Output, T3::Output, $collection_out);\n fn read_line(line: &str) -> Result {\n let prefix_len = <(T1, T2, T3)>::words_count();\n let words = split_into_words_for_collection::<$u>(line, prefix_len)?;\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let count2 = T2::words_count();\n let val2 = T2::read_words(&words[start .. start+count2])?;\n start += count2;\n let count3 = T3::words_count();\n let val3 = T3::read_words(&words[start .. start+count3])?;\n let rest = read_words_into_vec::<$u>(&words[prefix_len..], line)?;\n Ok((val1, val2, val3, rest.into_iter().collect()))\n }\n }\n impl ReadableFromLine for (T1, T2, T3, T4, $collection_in)\n where\n <$u as Readable>::Output: Sized $(+ $bound)*\n {\n type Output = (T1::Output, T2::Output, T3::Output, T4::Output, $collection_out);\n fn read_line(line: &str) -> Result {\n let prefix_len = <(T1, T2, T3, T4)>::words_count();\n let words = split_into_words_for_collection::<$u>(line, prefix_len)?;\n let mut start = 0;\n let count1 = T1::words_count();\n let val1 = T1::read_words(&words[start .. start+count1])?;\n start += count1;\n let count2 = T2::words_count();\n let val2 = T2::read_words(&words[start .. start+count2])?;\n start += count2;\n let count3 = T3::words_count();\n let val3 = T3::read_words(&words[start .. start+count3])?;\n start += count3;\n let count4 = T4::words_count();\n let val4 = T4::read_words(&words[start .. start+count4])?;\n let rest = read_words_into_vec::<$u>(&words[prefix_len..], line)?;\n Ok((val1, val2, val3, val4, rest.into_iter().collect()))\n }\n }\n };\n}\nreadable_collection!(U => Vec, Vec);\npub fn read() -> T::Output {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n T::read_line(&line).unwrap()\n}\n#[macro_export]\nmacro_rules! read {\n () => {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n };\n ( $pat:pat = $t:ty $(,)* ) => {\n let $pat = read::<$t>();\n };\n ( ! $(,)* ) => {\n let _ = read::<()>();\n };\n ( $pat:pat = $t:ty, $( $rest:tt )+ ) => {\n read_inner!($pat = $t; $($rest)+);\n };\n ( !, $( $rest:tt )+ ) => {\n read_inner!(_ = (); $($rest)+);\n };\n}\n#[macro_export]\n#[doc(hidden)]\nmacro_rules! read_inner {\n ( $( $acc_pat:pat = $acc_t:ty ),+ ; $pat:pat = $t:ty, $( $rest:tt )* ) => {\n read_inner!($( $acc_pat = $acc_t ),+ , $pat = $t ; $($rest)*);\n };\n ( $( $acc_pat:pat = $acc_t:ty ),+ ; !, $( $rest:tt )* ) => {\n read_inner!($( $acc_pat = $acc_t ),+ , _ = () ; $($rest)*);\n };\n ( $( $acc_pat:pat = $acc_t:ty ),+ ; $pat:pat = $t:ty ) => {\n read_inner!($( $acc_pat = $acc_t ),+ , $pat = $t ;);\n };\n ( $( $acc_pat:pat = $acc_t:ty ),+ ; ! ) => {\n read_inner!($( $acc_pat = $acc_t ),+ , _ = () ;);\n };\n ( $( $pat:pat = $t:ty ),+ ; ) => {\n let ($($pat),+) = read::<($($t),+)>();\n };\n}\n#[macro_export]\nmacro_rules! readls {\n ( $( $pat:pat = $t:ty ),+ ) => {\n $(\n read!($pat = $t);\n )*\n };\n}\npub fn readx() -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result = stdin.lock().lines().map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n }).collect();\n result\n}\n#[macro_export]\nmacro_rules! readx_loop {\n ( |$pat:pat = $t:ty| $body:expr ) => {\n {\n use std::io::BufRead;\n let stdin = std::io::stdin();\n for line in stdin.lock().lines() {\n let line = line.expect(\"read from stdin failed\");\n let $pat = <$t>::read_line(&line).unwrap();\n $body\n }\n }\n };\n ( |$($pat:pat = $t:ty),*| $body:expr ) => {\n readx_loop!(|($($pat),*) = ($($t),*)| $body);\n };\n}\npub fn readn(n: usize) -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result: Vec = stdin.lock().lines().take(n).map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n }).collect();\n if result.len() < n {\n panic!(\"expected reading {} lines, but only {} lines are read\",\n n, result.len());\n }\n result\n}\n#[macro_export]\nmacro_rules! readn_loop {\n ( $n:expr, |$pat:pat = $t:ty| $body:expr ) => {\n {\n use std::io::BufRead;\n let stdin = std::io::stdin();\n let mut lock = stdin.lock();\n for _ in 0..$n {\n let mut line = String::new();\n lock.read_line(&mut line).expect(\"read from stdin failed\");\n let $pat = <$t>::read_line(&line).unwrap();\n $body\n }\n }\n };\n ( $n:expr, |$($pat:pat = $t:ty),*| $body:expr ) => {\n readn_loop!($n, |($($pat),*) = ($($t),*)| $body);\n };\n}\npub trait Words {\n fn read(&self) -> T::Output;\n}\nimpl<'a> Words for [&'a str] {\n fn read(&self) -> T::Output {\n T::read_words(self).unwrap()\n }\n}\nimpl<'a> Words for &'a str {\n fn read(&self) -> T::Output {\n T::read_words(&[self]).unwrap()\n }\n}\n\n// SNIPPET op_macros\nmacro_rules! forward_ref_unop {\n (impl $op:ident, $method:ident for $t:ty) => {\n impl std::ops::$op for &$t {\n type Output = <$t as std::ops::$op>::Output;\n fn $method(self) -> <$t as std::ops::$op>::Output {\n std::ops::$op::$method(*self)\n }\n }\n }\n}\nmacro_rules! forward_ref_binop {\n (impl $op:ident, $method:ident for $t:ty, $u:ty) => {\n impl<'a> std::ops::$op<$u> for &'a $t {\n type Output = <$t as std::ops::$op<$u>>::Output;\n fn $method(self, other: $u) -> <$t as std::ops::$op<$u>>::Output {\n std::ops::$op::$method(*self, other)\n }\n }\n impl std::ops::$op<&$u> for $t {\n type Output = <$t as std::ops::$op<$u>>::Output;\n fn $method(self, other: &$u) -> <$t as std::ops::$op<$u>>::Output {\n std::ops::$op::$method(self, *other)\n }\n }\n impl std::ops::$op<&$u> for &$t {\n type Output = <$t as std::ops::$op<$u>>::Output;\n fn $method(self, other: &$u) -> <$t as std::ops::$op<$u>>::Output {\n std::ops::$op::$method(*self, *other)\n }\n }\n }\n}\nmacro_rules! forward_ref_op_assign {\n (impl $op:ident, $method:ident for $t:ty, $u:ty) => {\n impl std::ops::$op<&$u> for $t {\n fn $method(&mut self, other: &$u) {\n std::ops::$op::$method(self, *other);\n }\n }\n }\n}\n\n// SNIPPET modp\npub type ModPBase = u64;\npub type ModPModulus = u32;\nstatic mut MODULUS: ModPBase = 0;\n#[derive(Clone, Copy, PartialEq, Eq)]\npub struct ModP {\n base: ModPBase\n}\nimpl ModP {\n pub unsafe fn set_mod(modulus: ModPModulus) -> Result<(), String> {\n if modulus <= 1 {\n return Err(format!(\"{} is not a prime number.\", modulus));\n }\n if modulus >= 4 {\n if modulus % 2 == 0 || modulus % 3 == 0 {\n return Err(format!(\"{} is not a prime number.\", modulus));\n }\n let mut divisor = 5;\n loop {\n if divisor * divisor > modulus {\n break;\n }\n if modulus % divisor == 0 {\n return Err(format!(\"{} is not a prime number.\", modulus));\n }\n divisor += 2;\n if divisor * divisor > modulus {\n break;\n }\n if modulus % divisor == 0 {\n return Err(format!(\"{} is not a prime number.\", modulus));\n }\n divisor += 4;\n }\n }\n MODULUS = modulus as ModPBase;\n Ok(())\n }\n pub fn new(n: ModPBase) -> ModP {\n if !cfg!(test) {\n assert!(unsafe { MODULUS } != 0,\n \"Call ModP::set_mod before using ModP.\");\n }\n ModP { base: n % unsafe { MODULUS } }\n }\n pub unsafe fn new_unchecked(n: ModPBase) -> ModP {\n ModP { base: n }\n }\n pub fn base(&self) -> ModPBase {\n self.base\n }\n pub fn pow(self, exp: ModPBase) -> ModP {\n if exp == 0 { ModP::new(1) } else {\n let sub = self.pow(exp / 2);\n if exp % 2 == 0 {\n sub * sub\n } else {\n self * sub * sub\n }\n }\n }\n pub fn inv(self) -> ModP {\n assert!(self.base() != 0);\n self.pow(unsafe { MODULUS } - 2)\n }\n pub fn fact_cache() -> FactCache {\n FactCache {\n table: vec![ModP::new(1)]\n }\n }\n pub fn inv_cache() -> InvCache {\n InvCache {\n table: vec![ModP::new(0), ModP::new(1)]\n }\n }\n pub fn pow_cache(base: ModPBase) -> PowCache {\n PowCache {\n base: base,\n table: vec![ModP::new(1)]\n }\n }\n pub fn combinatorics_cache() -> CombinatoricsCache {\n CombinatoricsCache {\n facts: ModP::fact_cache(),\n invs: ModP::inv_cache(),\n finvs: vec![ModP::new(1)],\n }\n }\n}\npub fn modp(x: ModPBase) -> ModP {\n ModP::new(x)\n}\nimpl std::fmt::Display for ModP {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"{}\", self.base())\n }\n}\nimpl std::fmt::Debug for ModP {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"{} mod P\", self.base())\n }\n}\nimpl PartialEq for ModP {\n fn eq(&self, other: &ModPBase) -> bool {\n self.base() == other % unsafe { MODULUS }\n }\n}\nimpl PartialEq for ModPBase {\n fn eq(&self, other: &ModP) -> bool {\n self % unsafe { MODULUS } == other.base() % unsafe { MODULUS }\n }\n}\nimpl std::ops::Add for ModP {\n type Output = ModP;\n fn add(self, rhs: ModP) -> ModP {\n let m = unsafe { MODULUS };\n ModP { base: (self.base() + rhs.base() % m) % m }\n }\n}\nimpl std::ops::Add for ModP {\n type Output = ModP;\n fn add(self, rhs: ModPBase) -> ModP {\n self + ModP::new(rhs)\n }\n}\nimpl std::ops::Add for ModPBase {\n type Output = ModP;\n fn add(self, rhs: ModP) -> ModP {\n ModP::new(self) + rhs.base()\n }\n}\nimpl std::ops::AddAssign for ModP {\n fn add_assign(&mut self, rhs: ModP) {\n *self = *self + rhs\n }\n}\nimpl std::ops::AddAssign for ModP {\n fn add_assign(&mut self, rhs: ModPBase) {\n *self = *self + ModP::new(rhs)\n }\n}\nimpl std::ops::Neg for ModP {\n type Output = ModP;\n fn neg(self) -> ModP {\n ModP::new(unsafe { MODULUS } - self.base())\n }\n}\nimpl std::ops::Sub for ModP {\n type Output = ModP;\n fn sub(self, rhs: ModP) -> ModP {\n self + (-rhs)\n }\n}\nimpl std::ops::Sub for ModP {\n type Output = ModP;\n fn sub(self, rhs: ModPBase) -> ModP {\n self - ModP::new(rhs)\n }\n}\nimpl std::ops::Sub for ModPBase {\n type Output = ModP;\n fn sub(self, rhs: ModP) -> ModP {\n ModP::new(self) - rhs\n }\n}\nimpl std::ops::SubAssign for ModP {\n fn sub_assign(&mut self, rhs: ModP) {\n *self = *self - rhs;\n }\n}\nimpl std::ops::SubAssign for ModP {\n fn sub_assign(&mut self, rhs: ModPBase) {\n *self = *self - ModP::new(rhs)\n }\n}\nimpl std::ops::Mul for ModP {\n type Output = ModP;\n fn mul(self, rhs: ModP) -> ModP {\n let m = unsafe { MODULUS };\n ModP { base: self.base() * (rhs.base() % m) % m }\n }\n}\nimpl std::ops::Mul for ModP {\n type Output = ModP;\n fn mul(self, rhs: ModPBase) -> ModP {\n self * ModP::new(rhs)\n }\n}\nimpl std::ops::Mul for ModPBase {\n type Output = ModP;\n fn mul(self, rhs: ModP) -> ModP {\n ModP::new(self) * rhs.base()\n }\n}\nimpl std::ops::MulAssign for ModP {\n fn mul_assign(&mut self, rhs: ModP) {\n *self = *self * rhs\n }\n}\nimpl std::ops::MulAssign for ModP {\n fn mul_assign(&mut self, rhs: ModPBase) {\n *self = *self * ModP::new(rhs)\n }\n}\nimpl std::ops::Div for ModP {\n type Output = ModP;\n fn div(self, rhs: ModP) -> ModP {\n self * rhs.inv()\n }\n}\nimpl std::ops::Div for ModP {\n type Output = ModP;\n fn div(self, rhs: ModPBase) -> ModP {\n self * ModP::new(rhs).inv()\n }\n}\nimpl std::ops::Div for ModPBase {\n type Output = ModP;\n fn div(self, rhs: ModP) -> ModP {\n ModP::new(self) * rhs.inv()\n }\n}\nimpl std::ops::DivAssign for ModP {\n fn div_assign(&mut self, rhs: ModP) {\n *self = *self / rhs;\n }\n}\nimpl std::ops::DivAssign for ModP {\n fn div_assign(&mut self, rhs: ModPBase) {\n *self = *self / ModP::new(rhs)\n }\n}\nforward_ref_binop!(impl Add, add for ModP, ModP);\nforward_ref_binop!(impl Add, add for ModP, ModPBase);\nforward_ref_binop!(impl Add, add for ModPBase, ModP);\nforward_ref_op_assign!(impl AddAssign, add_assign for ModP, ModP);\nforward_ref_op_assign!(impl AddAssign, add_assign for ModP, ModPBase);\nforward_ref_unop!(impl Neg, neg for ModP);\nforward_ref_binop!(impl Sub, sub for ModP, ModP);\nforward_ref_binop!(impl Sub, sub for ModP, ModPBase);\nforward_ref_binop!(impl Sub, sub for ModPBase, ModP);\nforward_ref_op_assign!(impl SubAssign, sub_assign for ModP, ModP);\nforward_ref_op_assign!(impl SubAssign, sub_assign for ModP, ModPBase);\nforward_ref_binop!(impl Mul, mul for ModP, ModP);\nforward_ref_binop!(impl Mul, mul for ModP, ModPBase);\nforward_ref_binop!(impl Mul, mul for ModPBase, ModP);\nforward_ref_op_assign!(impl MulAssign, mul_assign for ModP, ModP);\nforward_ref_op_assign!(impl MulAssign, mul_assign for ModP, ModPBase);\nforward_ref_binop!(impl Div, div for ModP, ModP);\nforward_ref_binop!(impl Div, div for ModP, ModPBase);\nforward_ref_binop!(impl Div, div for ModPBase, ModP);\nforward_ref_op_assign!(impl DivAssign, div_assign for ModP, ModP);\nforward_ref_op_assign!(impl DivAssign, div_assign for ModP, ModPBase);\nimpl std::iter::Sum for ModP {\n fn sum>(iter: I) -> ModP {\n let mut ans = 0;\n for n in iter {\n ans += n.base();\n }\n ModP::new(ans)\n }\n}\nimpl<'a> std::iter::Sum<&'a ModP> for ModP {\n fn sum>(iter: I) -> ModP {\n let mut ans = 0;\n for n in iter {\n ans += n.base();\n }\n ModP::new(ans)\n }\n}\nimpl std::iter::Product for ModP {\n fn product>(iter: I) -> ModP {\n let mut ans = unsafe { ModP::new_unchecked(1) };\n for n in iter {\n ans *= n;\n }\n ans\n }\n}\nimpl<'a> std::iter::Product<&'a ModP> for ModP {\n fn product>(iter: I) -> ModP {\n let mut ans = unsafe { ModP::new_unchecked(1) };\n for &n in iter {\n ans *= n;\n }\n ans\n }\n}\nreadable!(ModP, 1, |ws| ModP::new(ws[0].read::()));\npub struct FactCache {\n table: Vec\n}\nimpl FactCache {\n pub fn get(&mut self, n: ModPBase) -> ModP {\n self.extend(n as usize);\n self.table[n as usize]\n }\n fn extend(&mut self, max: usize) {\n for i in self.table.len()..max+1 {\n let prev = self.table[i-1];\n self.table.push(prev * i as ModPBase);\n }\n }\n}\npub struct InvCache {\n table: Vec\n}\nimpl InvCache {\n pub fn get(&mut self, n: ModPBase) -> ModP {\n assert!(n > 0);\n self.extend(n as usize);\n self.table[n as usize]\n }\n fn extend(&mut self, max: usize) {\n for i in self.table.len()..max+1 {\n let m = unsafe { MODULUS };\n let prev = self.table[m as usize % i];\n self.table.push(m / i as ModPBase * (-prev));\n }\n }\n}\npub struct PowCache {\n base: ModPBase,\n table: Vec\n}\nimpl PowCache {\n pub fn get(&mut self, n: ModPBase) -> ModP {\n self.extend(n as usize);\n self.table[n as usize]\n }\n fn extend(&mut self, max: usize) {\n for i in self.table.len()..max+1 {\n let prev = self.table[i-1];\n self.table.push(prev * self.base);\n }\n }\n}\npub struct CombinatoricsCache {\n facts: FactCache,\n invs: InvCache,\n finvs: Vec,\n}\nimpl CombinatoricsCache {\n pub fn choose(&mut self, n: ModPBase, m: ModPBase) -> ModP {\n if n < m {\n return ModP::new(0);\n }\n self.extend_finvs(std::cmp::max(m, n-m) as usize);\n self.fact(n) * self.finvs[m as usize] * self.finvs[(n-m) as usize]\n }\n pub fn homo(&mut self, n: ModPBase, m: ModPBase) -> ModP {\n if m == 0 {\n ModP::new(1)\n } else {\n self.choose(n+m-1, m)\n }\n }\n pub fn fact(&mut self, n: ModPBase) -> ModP {\n self.facts.get(n)\n }\n pub fn inv(&mut self, n: ModPBase) -> ModP {\n self.invs.get(n)\n }\n fn extend_finvs(&mut self, max: usize) {\n for i in self.finvs.len()..max+1 {\n let prev = self.finvs[i-1];\n self.finvs.push(prev * self.invs.get(i as ModPBase))\n }\n }\n}\n\n// SNIPPET dbg\n#[macro_export]\n#[cfg(local)]\nmacro_rules! dbg {\n () => {\n {\n use std::io::{self, Write};\n writeln!(io::stderr(), \"{}: dbg\", line!()).unwrap();\n }\n };\n ($e: expr) => {\n {\n use std::io::{self, Write};\n let result = $e;\n writeln!(io::stderr(), \"{}: {} = {:?}\",\n line!(), stringify!($e), result)\n .unwrap();\n result\n }\n }\n}\n#[macro_export]\n#[cfg(not(local))]\nmacro_rules! dbg {\n () => {};\n ($e: expr) => {\n { $e }\n }\n}\n\n// END SNIPPETS\n\nfn main() {\n unsafe { ModP::set_mod(998244353).unwrap(); }\n read!(n = u64, m = u64);\n if n == 2 {\n println!(\"0\");\n return;\n }\n let mut cc = ModP::combinatorics_cache();\n println!(\"{}\", (1..m).map(|i| {\n cc.choose(i, n-2) * (n-2) * modp(2).pow(n-3)\n }).sum::());\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "7d281b0983f8707df692a457273c8640", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use crate::mod_int::ModInt;\n\nconst MOD: u64 = 998244353;\n\nfn main() {\n let (r, w) = (std::io::stdin(), std::io::stdout());\n let mut sc = IO::new(r.lock(), w.lock());\n let n: u64 = sc.read();\n let m: u64 = sc.read();\n\n let comb = Combination::new(m, MOD);\n if n == 2 {\n println!(\"0\");\n return;\n }\n let c = mint(comb.get(m, n - 1));\n let ans = c * (n - 2) * mint(2).pow(n - 3);\n println!(\"{}\", ans.value());\n}\n\nfn mint(v: u64) -> ModInt {\n ModInt::new(v, MOD)\n}\npub mod mod_int {\n use std::ops::{\n Add, AddAssign, BitAnd, Div, DivAssign, Mul, MulAssign, RemAssign, ShrAssign, Sub,\n SubAssign,\n };\n\n pub struct ModInt {\n v: T,\n m: T,\n }\n\n impl ModInt\n where\n T: Copy,\n {\n pub fn value(&self) -> T {\n self.v\n }\n pub fn modulo(&self) -> T {\n self.m\n }\n }\n\n impl ModInt {\n fn new_unchecked(v: T, modulo: T) -> Self {\n Self { v, m: modulo }\n }\n }\n\n impl ModInt\n where\n T: Copy + RemAssign + PartialOrd,\n {\n pub fn new(mut v: T, modulo: T) -> Self {\n if v >= modulo {\n v %= modulo;\n }\n Self::new_unchecked(v, modulo)\n }\n }\n\n impl ModInt\n where\n T: Copy\n + Sub\n + ShrAssign\n + BitAnd\n + PartialEq\n + PartialOrd\n + Div\n + RemAssign,\n ModInt: MulAssign,\n {\n pub fn pow(self, e: T) -> Self {\n let zero = self.modulo() - self.modulo();\n let one = self.modulo() / self.modulo();\n let mut e = e;\n let mut result = Self::new_unchecked(one, self.modulo());\n let mut cur = self;\n while e > zero {\n if e & one == one {\n result *= cur;\n }\n e >>= one;\n cur *= cur;\n }\n result\n }\n }\n\n impl Copy for ModInt where T: Copy {}\n impl Clone for ModInt\n where\n T: Copy,\n {\n fn clone(&self) -> Self {\n Self::new_unchecked(self.value(), self.modulo())\n }\n }\n\n impl Add for ModInt\n where\n T: AddAssign + SubAssign + RemAssign + Copy + PartialOrd,\n {\n type Output = Self;\n fn add(self, mut rhs: T) -> Self::Output {\n if rhs >= self.modulo() {\n rhs %= self.modulo();\n }\n rhs += self.value();\n if rhs >= self.modulo() {\n rhs -= self.modulo();\n }\n Self::new_unchecked(rhs, self.modulo())\n }\n }\n\n impl Sub for ModInt\n where\n T: AddAssign + SubAssign + RemAssign + Copy + PartialOrd,\n {\n type Output = Self;\n fn sub(self, mut rhs: T) -> Self::Output {\n if rhs >= self.modulo() {\n rhs %= self.modulo();\n }\n\n let mut result = self.value();\n result += self.modulo();\n result -= rhs;\n\n if result >= self.modulo() {\n result -= self.modulo();\n }\n Self::new_unchecked(result, self.modulo())\n }\n }\n\n impl Mul for ModInt\n where\n T: MulAssign + RemAssign + Copy + PartialOrd,\n {\n type Output = Self;\n fn mul(self, mut rhs: T) -> Self::Output {\n if rhs >= self.modulo() {\n rhs %= self.modulo();\n }\n rhs *= self.value();\n rhs %= self.modulo();\n Self::new_unchecked(rhs, self.modulo())\n }\n }\n\n impl Add> for ModInt\n where\n T: Copy,\n ModInt: Add>,\n {\n type Output = Self;\n fn add(self, rhs: ModInt) -> Self::Output {\n self + rhs.value()\n }\n }\n impl Sub> for ModInt\n where\n T: Copy,\n ModInt: Sub>,\n {\n type Output = Self;\n fn sub(self, rhs: ModInt) -> Self::Output {\n self - rhs.value()\n }\n }\n impl Mul> for ModInt\n where\n T: Copy,\n ModInt: Mul>,\n {\n type Output = Self;\n fn mul(self, rhs: ModInt) -> Self::Output {\n self * rhs.value()\n }\n }\n impl Div> for ModInt\n where\n T: Copy,\n ModInt: Div>,\n {\n type Output = Self;\n fn div(self, rhs: ModInt) -> Self::Output {\n self / rhs.value()\n }\n }\n\n impl AddAssign for ModInt\n where\n T: Copy,\n ModInt: Add>,\n {\n fn add_assign(&mut self, other: T) {\n *self = *self + other;\n }\n }\n impl AddAssign> for ModInt\n where\n T: Copy,\n ModInt: Add, Output = ModInt>,\n {\n fn add_assign(&mut self, other: ModInt) {\n *self = *self + other;\n }\n }\n\n impl SubAssign for ModInt\n where\n T: Copy,\n ModInt: Sub>,\n {\n fn sub_assign(&mut self, other: T) {\n *self = *self - other;\n }\n }\n\n impl SubAssign> for ModInt\n where\n T: Copy,\n ModInt: Sub, Output = ModInt>,\n {\n fn sub_assign(&mut self, other: ModInt) {\n *self = *self - other;\n }\n }\n\n impl DivAssign for ModInt\n where\n T: Copy,\n ModInt: Div>,\n {\n fn div_assign(&mut self, rhs: T) {\n *self = *self / rhs\n }\n }\n impl DivAssign> for ModInt\n where\n T: Copy,\n ModInt: Div, Output = ModInt>,\n {\n fn div_assign(&mut self, rhs: ModInt) {\n *self = *self / rhs\n }\n }\n\n impl MulAssign for ModInt\n where\n T: Copy,\n ModInt: Mul>,\n {\n fn mul_assign(&mut self, rhs: T) {\n *self = *self * rhs;\n }\n }\n\n impl MulAssign> for ModInt\n where\n T: Copy,\n ModInt: Mul, Output = ModInt>,\n {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n }\n\n impl Div for ModInt\n where\n T: Copy\n + Add\n + Sub\n + Div\n + BitAnd\n + PartialEq\n + PartialOrd\n + ShrAssign\n + RemAssign\n + MulAssign,\n {\n type Output = Self;\n fn div(self, mut rhs: T) -> Self::Output {\n if rhs >= self.modulo() {\n rhs %= self.modulo();\n }\n let one = self.modulo() / self.modulo();\n let two = one + one;\n self * Self::new_unchecked(rhs, self.modulo()).pow(self.modulo() - two)\n }\n }\n}\n\npub struct Combination {\n fact: Vec,\n inv_fact: Vec,\n modulo: u64,\n}\n\nimpl Combination {\n pub fn new(max: u64, modulo: u64) -> Self {\n let mut inv = vec![0; max as usize + 1];\n let mut fact = vec![0; max as usize + 1];\n let mut inv_fact = vec![0; max as usize + 1];\n inv[1] = 1;\n for i in 2..(max + 1) {\n inv[i as usize] = inv[(modulo % i) as usize] * (modulo - modulo / i) % modulo;\n }\n fact[0] = 1;\n inv_fact[0] = 1;\n for i in 0..max {\n fact[i as usize + 1] = fact[i as usize] * (i + 1) % modulo;\n }\n for i in 0..max {\n inv_fact[i as usize + 1] = inv_fact[i as usize] * inv[i as usize + 1] % modulo;\n }\n Self {\n fact,\n inv_fact,\n modulo,\n }\n }\n\n pub fn get(&self, x: u64, y: u64) -> u64 {\n assert!(x >= y);\n self.fact[x as usize] * self.inv_fact[y as usize] % self.modulo\n * self.inv_fact[x as usize - y as usize]\n % self.modulo\n }\n}\n\npub struct IO(R, std::io::BufWriter);\n\nimpl IO {\n pub fn new(r: R, w: W) -> Self {\n Self(r, std::io::BufWriter::new(w))\n }\n pub fn write(&mut self, s: S) {\n use std::io::Write;\n self.1.write_all(s.to_string().as_bytes()).unwrap();\n }\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let buf = self\n .0\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t')\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r' && b != b'\\t')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "6e3515a1386a602566c459af23725906", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// -*- outline-regexp: \"[ ]*//[*]+\"; eval: (outline-minor-mode 1) eval: (outline-hide-body) -*-\n//* Imports\n#![allow(unused_imports)]\n#![allow(dead_code)]\n#![allow(unused_variables)]\nuse std::collections::BTreeMap;\nuse std::collections::BTreeSet;\nuse std::collections::BinaryHeap;\nuse std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::collections::LinkedList;\nuse std::collections::VecDeque;\nuse std::io::Cursor;\nuse std::io::{self, prelude::*};\nuse std::str;\nuse std::num::Wrapping;\nmacro_rules! S {\n ($i:ident $sel:ident $e:block) => (\nstruct $i<'a> {\n rw: RWE<'a>,\n}\n\nimpl<'a> $i<'a> {\n fn new(rw: RWE<'a>) -> Self {\n Self { rw }\n }\n}\n\nimpl<'a> Solution<'a> for $i<'a> {\n fn rw(&mut $sel) -> &mut RWE<'a> {\n &mut $sel.rw\n }\n\n fn solve(&mut $sel) $e\n}\n )\n}\n//* Solution\nstruct Ring {\n p: Wrapping,\n f: Option>\n}\n\nimpl Ring {\n fn new() -> Self { Self { p: Wrapping(998244353), f: None } }\n\n fn mult(&self, a:i64, b: i64) -> i64 {\n (((Wrapping(a) * Wrapping(b)) % self.p + self.p) % self.p).0\n }\n\n fn precompute_factorial(&mut self, v: i64) {\n let mut r = 1;\n let mut tmp = vec![1; v as usize + 1];\n for j in 2..=v {\n r = self.mult(r, j);\n tmp[j as usize] = r;\n }\n self.f = Some(tmp);\n }\n\n fn factorial(&mut self, v: i64) -> i64 {\n if let None = self.f {\n self.precompute_factorial(v);\n }\n self.precompute_factorial(v);\n *self.f.as_ref().unwrap().get(v as usize).unwrap()\n }\n\n fn bin_pow(&self, mut n:i64, mut k: i64) -> i64 {\n let mut res = 1;\n while k > 0 {\n if k & 1 == 1 {\n res = self.mult(res, n);\n }\n n = self.mult(n, n);\n k >>= 1;\n }\n res\n }\n\n fn inverse(&self, n:i64) -> i64 {\n self.bin_pow(n, self.p.0-2)\n }\n}\n\n\nS!(SolutionA self {\n let n: i64 = self.rw().scan();\n let m: i64 = self.rw().scan();\n let mut ans;\n if m <= 2 {\n ans = 0;\n } else {\n let mut r = Ring::new();\n let a = r.factorial(m);\n let bp = r.factorial(n-1);\n let bz = r.factorial(m-(n-1));\n let br = r.inverse(bz);\n let b = r.inverse(bp);\n ans = r.mult(a, b);\n ans = r.mult(ans, br);\n ans = r.mult(ans, n-2);\n ans = r.mult(ans, r.bin_pow(2, n-3));\n }\n writeln!(self.rw(), \"{}\", ans).unwrap();\n});\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let scan = Scanner::new(stdin.lock());\n let out = io::BufWriter::new(stdout.lock());\n let r = RWE::Stdio(scan, out);\n //* Main\n let mut s = SolutionA::new(r);\n s.solve();\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_fermat() {\n let r = Ring::new();\n for i in 3..1000 {\n assert_eq!(r.bin_pow(i, 998244352), 1);\n }\n }\n\n #[test]\n fn test_inverse() {\n let r = Ring::new();\n for i in 1..1000 {\n assert_eq!(r.mult(r.inverse(i), i), 1, \"testing {}\", i);\n }\n }\n\n #[test]\n fn test_case_a() {\n fn tc(input: &'static str, expected: &'static str) {\n tcc(&|rwe| Box::new(SolutionA::new(rwe)), input, expected);\n }\n tc(\"2 5\", \"0\\n\");\n tc(\"3 4\", \"6\\n\");\n tc(\"3 3\", \"3\\n\");\n tc(\"4 4\", \"16\\n\");\n tc(\"5 5\", \"60\\n\");\n tc(\"3 5\", \"10\\n\");\n tc(\"42 1337\", \"806066790\\n\");\n tc(\"100000 200000\", \"707899035\\n\");\n }\n\n //** Test Utils\n fn tcc<'a>(f: &dyn Fn(RWE<'a>) -> Box>, input: &'a str, expected: &str) {\n let s = Scanner::new(Cursor::new(input));\n let w = vec![];\n let r = RWE::InMemory(s, w);\n\n let mut sol = f(r);\n sol.solve();\n if let RWE::InMemory(r, w) = sol.rw() {\n let output = std::str::from_utf8(w.as_mut_slice()).unwrap();\n assert_eq!(expected, output);\n } else {\n unreachable!(\"Huh, how'd we manage to pass stdio?\");\n }\n }\n}\n\n//*** IO\nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>,\n}\n\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: Vec::new(),\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n fn t(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n}\n\ntrait RW {\n fn reader(&mut self) -> &mut Scanner;\n fn writer(&mut self) -> &mut W;\n}\n\nenum RWE<'a> {\n InMemory(Scanner>, Vec),\n Stdio(\n Scanner>,\n std::io::BufWriter>,\n ),\n}\n\nimpl<'a> RWE<'a> {\n fn scan(&mut self) -> T {\n match self {\n RWE::InMemory(r, _) => r.t(),\n RWE::Stdio(r, _) => r.t(),\n }\n }\n}\n\nimpl<'a> std::io::Write for RWE<'a> {\n fn write(&mut self, buf: &[u8]) -> io::Result {\n match self {\n RWE::InMemory(_, w) => w.write(buf),\n RWE::Stdio(_, w) => w.write(buf),\n }\n }\n fn flush(&mut self) -> io::Result<()> {\n match self {\n RWE::InMemory(_, w) => w.flush(),\n RWE::Stdio(_, w) => w.flush(),\n }\n }\n}\n\ntrait Solution<'a> {\n fn rw(&mut self) -> &mut RWE<'a>;\n fn solve(&mut self);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "9cb87ac2c4f137ddcb0f8385aed8ccd9", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "mod scanner {\n use std::io::{Read, Stdin, stdin};\n use std::str::FromStr;\n\n pub struct Scanner {\n source: T,\n buffer: Vec,\n available: usize,\n ptr: usize\n }\n\n impl Scanner {\n pub fn new(source: T) -> Scanner {\n const BUFFER_SIZE: usize = 32 * 1024 * 1024; // 32 MB of buffer size\n Scanner {\n source,\n buffer: vec![0u8; BUFFER_SIZE],\n available: 0,\n ptr: 0\n }\n }\n\n fn read_block(&mut self) {\n self.available = self.source.read(self.buffer.as_mut()).unwrap();\n self.ptr = 0;\n }\n\n fn read_byte(&mut self) -> Option {\n if self.ptr >= self.available {\n self.read_block();\n if self.available == 0 {\n // Hit EOF.\n return None;\n }\n }\n\n let value = self.buffer[self.ptr];\n self.ptr += 1;\n\n Some(value)\n }\n\n pub fn read_token(&mut self) -> Option {\n // Skip any leading whitespace characters.\n let mut b;\n loop {\n b = match self.read_byte() {\n Some(b) => b,\n None => return None\n };\n if !(b as char).is_ascii_whitespace() {\n break;\n }\n }\n\n let mut buffer = String::new();\n loop {\n if (b as char).is_ascii_whitespace() {\n break;\n }\n\n buffer.push(b as char);\n b = match self.read_byte() {\n Some(b) => b,\n None => break\n };\n }\n\n Some(buffer)\n }\n\n pub fn read(&mut self) -> Option {\n let token = self.read_token()?;\n ::from_str(token.as_str()).ok()\n }\n }\n\n impl Scanner {\n pub fn from_stdin() -> Scanner {\n Scanner::new(stdin())\n }\n }\n}\n\nuse scanner::Scanner;\n\nconst MOD: i64 = 998244353i64;\n\nstruct Binom {\n fact: Vec,\n inv: Vec,\n factinv: Vec,\n}\n\nimpl Binom {\n fn new(max_n: usize) -> Self {\n let mut b = Binom {\n fact: vec![0i64; max_n + 1],\n inv: vec![0i64; max_n + 1],\n factinv: vec![0i64; max_n + 1],\n };\n\n b.fact[0] = 1;\n for i in 1..=max_n {\n b.fact[i] = b.fact[i - 1] * i as i64 % MOD;\n }\n\n b.inv[1] = 1;\n for i in 2..=max_n {\n b.inv[i] = (-MOD / i as i64 * b.inv[(MOD % i as i64) as usize] % MOD + MOD) % MOD;\n }\n\n b.factinv[0] = 1;\n for i in 1..=max_n {\n b.factinv[i] = b.factinv[i - 1] * b.inv[i] % MOD;\n }\n\n b\n }\n\n fn binom(&self, n: i64, m: i64) -> i64 {\n let n = n as usize;\n let m = m as usize;\n self.fact[n] * self.factinv[m] % MOD * self.factinv[n - m] % MOD\n }\n}\n\nfn fast_pow(mut base: i64, mut e: i64) -> i64 {\n let mut res = 1i64;\n while e > 0 {\n if e & 1 == 1 {\n res = res * base % MOD;\n }\n base = base * base % MOD;\n e >>= 1;\n }\n\n res\n}\n\nfn main() {\n let mut reader = Scanner::from_stdin();\n let binom = Binom::new(200000);\n\n let n: i64 = reader.read().unwrap();\n let m: i64 = reader.read().unwrap();\n if n <= 2 {\n println!(\"0\");\n return;\n }\n\n let ans = binom.binom(m, n - 1) * (n - 2) % MOD * fast_pow(2i64, n - 3) % MOD;\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "acbe0403ef024e080b008e81b0636b04", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused)]\n\nuse kyoproio::*;\nuse std::{\n collections::*,\n iter,\n io::{self, prelude::*},\n mem::{replace, swap},\n};\n\nfn main() -> io::Result<()> {\n std::thread::Builder::new()\n .stack_size(50 * 1024 * 1024)\n .spawn(solve)?\n .join()\n .unwrap();\n Ok(())\n}\n\nfn solve() {\n let stdin = io::stdin();\n let mut kin = Input::new(stdin.lock());\n let stdout = io::stdout();\n let mut out = io::BufWriter::new(stdout.lock());\n macro_rules! output {\n ($($args:expr),+) => { write!(&mut out, $($args),+) };\n }\n\n const MOD: i64 = 998244353;\n let (n, m): (i64, i64) = kin.input();\n\n let comb = Combination::new((m + 1) as usize, MOD);\n let mut ans = 0;\n for h in 2..=m {\n ans += comb.comb(h - 1, n - 2) * mod_pow(2, n - 2, MOD) % MOD * (n - 2) % MOD;\n ans %= MOD;\n }\n ans *= mod_inv(2, MOD);\n ans %= MOD;\n output!(\"{}\\n\", ans);\n}\n\npub fn mod_pow(mut a: i64, mut b: i64, m: i64) -> i64 {\n let mut y = 1;\n while b > 0 {\n if b & 1 == 1 {\n y = y * a % m;\n }\n a = a * a % m;\n b >>= 1;\n }\n y\n}\npub fn mod_inv(x: i64, m: i64) -> i64 {\n mod_pow(x, m - 2, m)\n}\npub struct Combination {\n m: i64,\n fact: Vec,\n}\nimpl Combination {\n pub fn new(size: usize, m: i64) -> Self {\n let mut comb = Self {\n m,\n fact: Vec::new(),\n };\n comb.resize(size);\n comb\n }\n pub fn resize(&mut self, size: usize) {\n let old_len = self.fact.len();\n self.fact.resize(size + 1, 0);\n for i in old_len..size + 1 {\n self.fact[i] = if i == 0 {\n 1\n } else {\n i as i64 * self.fact[i - 1] % self.m\n };\n }\n }\n pub fn fact(&self, x: i64) -> i64 {\n self.fact[x as usize]\n }\n pub fn perm(&self, a: i64, b: i64) -> i64 {\n if a >= b {\n self.fact(a) * mod_inv(self.fact(a - b), self.m) % self.m\n } else {\n 0\n }\n }\n pub fn comb(&self, a: i64, b: i64) -> i64 {\n if a >= b {\n self.fact(a) * mod_inv(self.fact(b) * self.fact(a - b) % self.m, self.m) % self.m\n } else {\n 0\n }\n }\n}\n// -----------------------------------------------------------------------------\npub mod kyoproio {\n #![warn(unused)]\n\n pub use std::io::prelude::*;\n\n pub struct Input {\n src: R,\n buf: String,\n pos: usize,\n }\n impl Input {\n pub fn new(src: R) -> Self {\n Self {\n src,\n buf: String::with_capacity(256),\n pos: 0,\n }\n }\n pub fn str(&mut self) -> &str {\n loop {\n if self.pos >= self.buf.len() {\n self.buf.clear();\n let len = self.src.read_line(&mut self.buf).expect(\"io error\");\n self.pos = 0;\n if len == 0 {\n return &self.buf\n }\n }\n let range = self.pos\n ..self.buf[self.pos..]\n .find(|c: char| c.is_ascii_whitespace())\n .map(|i| i + self.pos)\n .unwrap_or(self.buf.len());\n self.pos = range.end + 1;\n if range.end - range.start > 0 {\n return &self.buf[range];\n }\n }\n }\n pub fn bytes(&mut self) -> &[u8] {\n self.str().as_ref()\n }\n pub fn input(&mut self) -> T {\n self.input_fallible().expect(\"input error\")\n }\n pub fn input_fallible(&mut self) -> Result {\n T::input(self)\n }\n pub fn iter(&mut self) -> Iter {\n Iter {\n input: self,\n _t: std::marker::PhantomData,\n }\n }\n }\n pub struct Iter<'a, T, R> {\n input: &'a mut Input,\n _t: std::marker::PhantomData,\n }\n impl<'a, T: InputParse, R: BufRead> Iterator for Iter<'a, T, R> {\n type Item = T;\n fn next(&mut self) -> Option {\n Some(self.input.input())\n }\n }\n type Result = std::result::Result>;\n pub trait InputParse: Sized {\n fn input(input: &mut Input) -> Result;\n }\n macro_rules! input_from_str_impls {\n { $($T:ty)* } => {\n $(impl InputParse for $T {\n fn input(input: &mut Input) -> Result {\n input.str().parse::<$T>().map_err(|e| e.into())\n }\n })*\n };\n }\n macro_rules! input_tuple_impls {\n { $(($($T:ident),+))* } => {\n $(impl<$($T:InputParse),+> InputParse for ($($T),+) {\n fn input(input: &mut Input) -> Result {\n Ok(($($T::input(input)?),+))\n }\n })*\n };\n }\n input_from_str_impls! {\n String char bool f32 f64\n isize i8 i16 i32 i64 i128\n usize u8 u16 u32 u64 u128\n }\n input_tuple_impls! {\n (A, B)\n (A, B, C)\n (A, B, C, D)\n (A, B, C, D, E)\n (A, B, C, D, E, F)\n (A, B, C, D, E, F, G)\n }\n}", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "ea6b4d7def0824033afd1f92fc32c02b", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::max;\n\nfn my_pow(modulo: i64, a: i64, k: i64) -> i64{\n let mut rule = k;\n let mut power = a;\n let mut res = 1;\n loop {\n if rule < 1 {\n break;\n }\n if rule % 2 == 1{\n res = (res * power) % modulo;\n }\n rule /= 2;\n power = (power * power) % modulo;\n }\n res % modulo\n}\n\n\nfn c_n_k(modulo: i64, n: i64, k: i64) -> i64{\n let mut res = 1;\n for j in 1..(k + 1) {\n res = (res * (n - k + j)) % modulo;\n res = (res * my_pow(modulo, j, modulo - 2)) % modulo;\n }\n res % modulo\n}\n\nfn main() {\n let d:i64 = 998244353;\n let mut str = String::new();\n let _ = stdin().read_line(&mut str).unwrap();\n let mut iter = str.split_whitespace();\n let k:i64 = iter.next().unwrap().parse().unwrap();\n let n:i64 = iter.next().unwrap().parse().unwrap();\n let sequence = c_n_k(d, n, k - 1);\n let double_sequence = (sequence * (k - 2)) % d;\n let sequence_with_peak = double_sequence * my_pow(d, 2, k - 3);\n println!(\"{}\", sequence_with_peak % d);\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "f830d1ee1101be0b46b8b66a1f050924", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[macro_export]\nmacro_rules ! chmax { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: max ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! chmin { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: min ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! max { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: max ( $ x , max ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! min { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: min ( $ x , min ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! dvec { ( $ t : expr ; $ len : expr ) => { vec ! [ $ t ; $ len ] } ; ( $ t : expr ; $ len : expr , $ ( $ rest : expr ) ,* ) => { vec ! [ dvec ! ( $ t ; $ ( $ rest ) ,* ) ; $ len ] } ; }\n#[macro_export]\nmacro_rules ! cfor { ( ; $ ( $ rest : tt ) * ) => { cfor ! ( ( ) ; $ ( $ rest ) * ) } ; ( $ ( $ init : stmt ) ,+; ; $ ( $ rest : tt ) * ) => { cfor ! ( $ ( $ init ) ,+; ! false ; $ ( $ rest ) * ) } ; ( $ ( $ init : stmt ) ,+; $ cond : expr ; ; $ body : block ) => { cfor ! { $ ( $ init ) ,+; $ cond ; ( ) ; $ body } } ; ( $ ( $ init : stmt ) ,+; $ cond : expr ; $ ( $ step : expr ) ,+; $ body : block ) => { { $ ( $ init ; ) + while $ cond { let mut _first = true ; let mut _continue = false ; loop { if ! _first { _continue = true ; break } _first = false ; $ body } if ! _continue { break } $ ( $ step ; ) + } } } ; }\n#[doc = \" main\"]\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\n#[macro_export]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\nuse std::io;\nuse std::io::BufRead;\nuse std::str;\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len, complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n if len == 0 {\n break;\n }\n (len, buf2[len - 1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n } else {\n self.update_buf();\n }\n }\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\nconst BIG_STACK_SIZE: bool = true;\n#[allow(dead_code)]\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\nconst MO: i64 = 998244353;\nfn solve() {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n input!{\n n:i64,\n m:i64,\n }\n let mut mc = ModComb::new(200200, MO);\n let mut loc = 0;\n for k in n-1..=m {\n loc += (n-2) * mc.nCk(k-1,n-2);\n loc %= MO;\n }\n let mut tot = 0;\n for i in 2..=n-1 {\n let L = i-1;\n let R = n-i;\n tot += loc * mc.nCk(n-3,min(L-1,R-1));\n tot %= MO;\n }\n tot %= MO;\n writeln!(out,\"{}\",tot);\n}\npub mod modular {\n const M: i64 = 998244353;\n #[derive(Debug, Clone, Copy, Default, PartialOrd, Ord, PartialEq, Eq)]\n pub struct Mod(pub i64);\n impl ::std::fmt::Display for Mod {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n impl Mod {\n pub fn new(v: i64) -> Mod {\n Mod((v + M) % M)\n }\n pub fn pow(self, mut r: i64) -> Mod {\n let mut k = self;\n let mut ret = 1.into();\n while r > 0 {\n if r % 2 != 0 {\n ret = ret * k;\n }\n r /= 2;\n k = k * k;\n }\n ret\n }\n pub fn recip(self) -> Mod {\n self.pow(M - 2)\n }\n }\n use std::ops::*;\n impl> Add for Mod {\n type Output = Mod;\n fn add(self, rhs: T) -> Self::Output {\n Mod::new(self.0 + rhs.into().0)\n }\n }\n impl> AddAssign for Mod {\n fn add_assign(&mut self, rhs: T) {\n *self = *self + rhs;\n }\n }\n impl> Sub for Mod {\n type Output = Mod;\n fn sub(self, rhs: T) -> Self::Output {\n Mod::new(self.0 - rhs.into().0 + M)\n }\n }\n impl> SubAssign for Mod {\n fn sub_assign(&mut self, rhs: T) {\n *self = *self - rhs;\n }\n }\n impl> Mul for Mod {\n type Output = Mod;\n fn mul(self, rhs: T) -> Self::Output {\n Mod::new(self.0 * rhs.into().0)\n }\n }\n impl> MulAssign for Mod {\n fn mul_assign(&mut self, rhs: T) {\n *self = *self * rhs;\n }\n }\n impl> Div for Mod {\n type Output = Mod;\n fn div(self, rhs: T) -> Self::Output {\n self * rhs.into().recip()\n }\n }\n impl> DivAssign for Mod {\n fn div_assign(&mut self, rhs: T) {\n *self = *self / rhs;\n }\n }\n impl Neg for Mod {\n type Output = Mod;\n fn neg(self) -> Self::Output {\n Mod(0) - self\n }\n }\n impl> ::std::convert::From for Mod {\n fn from(v: T) -> Self {\n Mod::new(v.into())\n }\n }\n}\n#[doc = \"ay=1 (mod m) -> y=a^{-1}\"]\npub fn modinv(a: i64, m: i64) -> i64 {\n let (_, x, _) = extgcd(a, m);\n (m + x % m) % m\n}\n#[doc = \"ax+by=gcd(a,b) returns (gcd, x, y)\"]\n#[allow(dead_code)]\npub fn extgcd(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (gcd, x, y) = extgcd(b, a % b);\n (gcd, y, x - (a / b) * y)\n }\n}\npub type Mod = modular::Mod;\nstruct ModComb {\n fact: Vec,\n fact_inv: Vec,\n n: usize,\n p: i64,\n}\nimpl ModComb {\n fn initialize(ft: &mut Self) {\n let n = ft.n;\n ft.fact[0] = 1;\n for i in 1..n {\n ft.fact[i] = (ft.fact[i - 1] * i as i64) % ft.p;\n }\n ft.fact_inv[n - 1] = modpow(ft.fact[n - 1], ft.p - 2, ft.p);\n for i in (0..n - 1).rev() {\n ft.fact_inv[i] = (ft.fact_inv[i + 1] * (i + 1) as i64) % ft.p;\n }\n }\n #[doc = \"O(N)\"]\n fn new(max_n: usize, p: i64) -> ModComb {\n let mut ft = ModComb {\n fact: vec![0; max_n + 1],\n fact_inv: vec![0; max_n + 1],\n n: max_n + 1,\n p: p,\n };\n Self::initialize(&mut ft);\n ft\n }\n fn fact(&self, n: usize) -> i64 {\n self.fact[n]\n }\n #[doc = \"choose k numbers from 1..n\"]\n fn nCk(&self, n: i64, k: i64) -> i64 {\n if n < k {\n return 0;\n }\n (self.nPk(n, k) * self.fact_inv[k as usize]) % self.p\n }\n fn nPk(&self, n: i64, k: i64) -> i64 {\n if n < k {\n return 0;\n }\n self.fact[n as usize] * self.fact_inv[(n - k) as usize] % self.p\n }\n #[doc = \"split k into n number as x1+x2+...xn=k\"]\n fn nHk(&self, n: i64, k: i64) -> i64 {\n if n == 0 && k == 0 {\n return 1;\n }\n self.nCk(n + k - 1, k)\n }\n #[doc = \"put n balls into k different boxes. In case of n=3,k+2 [[1,2],[3]]==[[3],[1,2]]\"]\n fn nSk(&self, n: i64, k: i64) -> i64 {\n if n < k {\n return 0;\n }\n let mut res = 0;\n for i in 0..k + 1 {\n let v = self.nCk(k, i) * modpow(i, n, self.p) % self.p;\n if (k - i) % 2 == 1 {\n res = (res + self.p - v) % self.p;\n } else {\n res = (res + v) % self.p;\n }\n }\n return res * self.fact_inv[k as usize] % self.p;\n }\n fn nBk(&self, n: i64, k: i64) -> i64 {\n 0\n }\n}\n#[allow(dead_code)]\n#[doc = \" x ^ n % m\"]\npub fn modpow(x: i64, n: i64, m: i64) -> i64 {\n let mut res = 1;\n let mut x = x % m;\n let mut n = n;\n while n > 0 {\n if n & 1 == 1 {\n res = (res * x) % m;\n }\n x = (x * x) % m;\n n >>= 1;\n }\n res\n}", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "948fdbe38ff41975df1369df97f983d5", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(isize);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(c: u32, v0: u32, v1: u32, a: u32, l: u32);\n let mut speed = v0;\n let mut pages = 0;\n let mut days = 0;\n loop {\n days += 1;\n pages += speed;\n if pages >= c { break; }\n speed = std::cmp::min(speed + a, v1);\n pages -= l;\n }\n println!(\"{}\", days);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7b006ad3a11ae7fa843685db85c417e7", "src_uid": "b743110117ce13e2090367fd038d3b50", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_num() -> usize {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n usize::from_str(input.trim()).unwrap()\n}\n\nfn get_string() -> String {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n input.trim().to_string()\n}\n\nfn main() {\n let n = get_num();\n let s = get_string();\n\n for c in s.chars() {\n if c != '4' && c != '7' {\n println!(\"NO\");\n return;\n }\n }\n\n let mut fs = 0;\n let mut ss = 0;\n for (i, c) in s.chars().enumerate() {\n if i == n / 2 {\n break;\n }\n fs += c.to_digit(10).unwrap();\n }\n\n for (_, c) in s.chars().enumerate().skip(n / 2) {\n ss += c.to_digit(10).unwrap();\n }\n\n if fs == ss {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f1cccb63dc367cc6034d18183f61c7dd", "src_uid": "435b6d48f99d90caab828049a2c9e2a7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty; $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt; $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.s().into_bytes();\n let sol = (1..).flat_map(|a| iter::repeat(a).take(1< usize {\n let mut digits = format!(\"{}\", n);\n let mut s = Vec::from(digits);\n let mut i = s.len();\n while i > 0 {\n i -= 1;\n if s[i] == C4 {\n s[i] = C7;\n break;\n }\n s[i] = C4;\n }\n\n let mut n = str::from_utf8(&s).unwrap().parse().unwrap();\n if i == 0 && s[0] == C4 { // got all fours, need to add new digit\n n += 4 * 10usize.pow(s.len() as u32);\n }\n\n n\n}\n\n/*\n * Utility Functions\n */\n\n// get numbers from line seperated by spaces\nfn get_numbers(line: &str) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n line.split_whitespace()\n .map(|chunk| chunk.parse::().expect(\"failed to parse\"))\n .collect()\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "combinatorics", "bitmasks"], "code_uid": "2e7a60edb807167352e066f00ba55303", "src_uid": "6a10bfe8b3da9c11167e136b3c6fb2a3", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, Read, StdinLock};\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::collections::{HashSet, HashMap};\n#[allow(unused_imports)]\nuse std::vec::Vec;\n\n#[allow(dead_code)]\nconst INF: i32 = 1000_000_000;\n#[allow(dead_code)]\nconst INFLL: i64 = 1000_000_000_000_000_000;\n\nstruct Scanner<'a> {\n cin: StdinLock<'a>,\n}\n\nimpl<'a> Scanner<'a> {\n #[allow(dead_code)]\n fn new(cin: StdinLock<'a>) -> Scanner<'a> {\n Scanner {cin: cin}\n }\n\n #[allow(dead_code)]\n fn read1(&mut self) -> Option {\n let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect::();\n token.parse::().ok()\n }\n\n #[allow(dead_code)]\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\nfn main() {\n let cin = stdin();\n let cin = cin.lock();\n let mut sc = Scanner::new(cin);\n let n: i32 = sc.read();\n let r1: f64 = sc.read();\n let r2: f64 = sc.read();\n if n > 1 {\n let theta = std::f64::consts::PI / (n as f64);\n let mr: f64 = r1 * theta.sin() / (1.0 + theta.sin());\n //println!(\"{} <-> {}\", mr, r2);\n match r2 <= mr + 0.0000000001 {\n false => println!(\"NO\"),\n _ => println!(\"YES\"),\n }\n } else {\n if r2 <= r1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n }\n}", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "6f3806baf05a2363ef8d9f11cc029f4a", "src_uid": "2fedbfccd893cde8f2fab2b5bf6fb6f6", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\nfn main() {\n let mut buf = String::new();\n std::io::stdin().read_to_string(&mut buf).unwrap();\n let mut iter = buf.split_whitespace();\n let p: u32 = iter.next().unwrap().parse().unwrap();\n let y: u32 = iter.next().unwrap().parse().unwrap();\n for x in (p..(y+1)).rev() {\n if check(x, p) {\n println!(\"{}\", x);\n return\n }\n }\n println!(\"{}\", -1);\n}\n\nfn check(x : u32, p : u32) -> bool {\n for i in 2..(p+1) {\n if i*i>x {\n break;\n }\n if x%i==0 {\n return false;\n }\n }\n return !(x%p==0);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "8f6a3413f7baf0a2f057f02f4747de83", "src_uid": "b533203f488fa4caf105f3f46dd5844d", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io;\n use std::io::prelude::*;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let p: u64 = it.next().unwrap().parse().unwrap();\n let y: u64 = it.next().unwrap().parse().unwrap();\n\n let ans = (p + 1..y + 1).rev().find(|&i| {\n let k = std::cmp::min(p, (y as f64).sqrt().floor() as u64);\n (2..k + 1).all(|j| i % j != 0)\n });\n\n match ans {\n Some(ans) => println!(\"{}\", ans),\n None => println!(\"-1\"),\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "e6d46e1de8431855569941681730a17e", "src_uid": "b533203f488fa4caf105f3f46dd5844d", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n#![allow(non_camel_case_types)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{max, min, Ordering};\nuse std::f64::consts::*;\nuse std::mem::{swap, size_of_val, size_of};\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\nuse std::num::*;\nuse std::process::*;\n//use std::ptr::*;\nuse std::iter::{once, repeat};\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\nstruct Input {\n\tbuffer: Buf,\n}\n\nimpl Input {\n\tfn read_char(&mut self) -> char {\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\tx[0] as char\n\t}\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n}\n\nmacro_rules! read {\n () => {};\n\t($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect(\"Parsing error\"));\n\t($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect(\"Parsing error\")),*));\n}\nfn gcd(mut a: T, mut b: T) -> T\n\twhere T: ShrAssign + BitAnd + Ord + From + Clone + SubAssign + ShlAssign + Copy\n{\n\tlet one = T::from(1);\n\tlet zero = T::from(0);\n\tlet mut ans = 0;\n\tif a < b {\n\t\tswap(&mut a, &mut b);\n\t}\n\twhile b > zero {\n\t\tif (a & one > zero) && (b & one > zero) {\n\t\t\ta -= b;\n\t\t} else if a & one > zero {\n\t\t\tb >>= one;\n\t\t} else if b & one > zero {\n\t\t\ta >>= one;\n\t\t} else {\n\t\t\tans += 1;\n\t\t\ta >>= one;\n\t\t\tb >>= one;\n\t\t}\n\t\tif a < b {\n\t\t\tswap(&mut a, &mut b);\n\t\t}\n\t}\n\ta <<= ans;\n\ta\n}\n\nfn powmod(mut base: X, mut exp: Y, mm: X) -> X\n\twhere X: Copy + Clone + Mul + Rem + From,\n\t Y: ShrAssign + Copy + Clone + BitAnd + From + Ord\n{\n\tlet mut res = X::from(1);\n\twhile exp > Y::from(0) {\n\t\tif exp & Y::from(1) > Y::from(0) {\n\t\t\tres = res * base % mm;\n\t\t}\n\t\tbase = base * base % mm;\n\t\texp >>= Y::from(1);\n\t}\n\tres\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\")) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet stdin = stdin();\n\t\t\tlet istr = stdin.lock();\n\t\t\tlet mut inf = Input { buffer: BufReader::new(istr) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output) {\n\tlet (p, mut y) = read!(inf,i32,i32);\n\twhile y > p {\n\t\tlet mut fl = true;\n\t\tlet mut i = 2;\n\t\twhile i * i <= y {\n\t\t\tif y % i == 0 {\n\t\t\t\tif i <= p {\n\t\t\t\t\tfl = false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti += 1;\n\t\t}\n\t\tif fl {\n\t\t\twriteln!(ouf, \"{}\", y);\n\t\t\treturn;\n\t\t}\n\t\ty -= 1;\n\t}\n\twriteln!(ouf, \"-1\");\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "3876773e188277d9f85a65d95b350f8f", "src_uid": "b533203f488fa4caf105f3f46dd5844d", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::fs::File;\nuse std::cmp;\n\nfn main() {\n let stdin = io::stdin();\n let buf :Box = if cfg!(feature = \"intxt\") {\n eprintln!(\"file mode\");\n let file = File::open(\"in.txt\").unwrap();\n Box::new(io::BufReader::new(file))\n } else {\n eprintln!(\"stdin mode\");\n Box::new(stdin.lock())\n };\n let mut sc = Scanner::new(buf);\n\n let (p, y) :(i32, i32) = (sc.next(), sc.next());\n\n for x in (p+1..y+1).rev() {\n let mut prime = true;\n let md = cmp::min(p, (x as f32).sqrt() as i32) + 1;\n for d in 2..md {\n if x % d == 0 {\n prime = false;\n break;\n }\n }\n if prime {\n println!(\"{}\", x);\n return;\n }\n }\n println!(\"{}\", -1);\n}\n\n\nstruct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n }\n\n fn next(&mut self) -> T\n where\n T::Err: std::fmt::Debug,\n {\n if let Some(s) = self.buffer.pop() {\n T::from_str(&s).unwrap()\n } else {\n let mut s = String::new();\n let r = self.reader.read_line(&mut s).unwrap();\n assert!(r > 0);\n self.buffer = s.split_whitespace().rev().map(String::from).collect();\n return self.next();\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "97cd0684a5851166b91705ad3180d5c2", "src_uid": "b533203f488fa4caf105f3f46dd5844d", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn gcd(a: u64, b: u64) -> u64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn run() {\n input! {\n n: u64,\n a: u64,\n b: u64,\n p: u64,\n q: u64,\n }\n let z = n / (a / gcd(a, b) * b);\n let x = n / a - z;\n let y = n / b - z;\n let ans = p * x + q * y + std::cmp::max(p, q) * z;\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "4c0fd8e8a0450f25974a52655b12333b", "src_uid": "35d8a9f0d5b5ab22929ec050b55ec769", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\nuse std::io::{stdin};\n\nfn get_pos(n: u16, x: u16, y: u16) -> Option {\n if (x > n) || (y > n) {\n return None;\n }\n\n if y == 0 {\n if x == 0 {\n return Some(0);\n } else {\n return Some(4 * n - x);\n }\n } else if y == n {\n return Some(n + x);\n } else if x == 0 {\n return Some(y);\n } else if x == n {\n return Some(3 * n - y);\n } else {\n return None;\n }\n}\n\nfn get_distance(n: u16, x1: u16, y1: u16, x2: u16, y2: u16) -> Option {\n let pos1: u16 = get_pos(n, x1, y1)?;\n let pos2: u16 = get_pos(n, x2, y2)?;\n\n let distance_naive: u16;\n if pos1 > pos2 {\n distance_naive = pos1 - pos2;\n } else {\n distance_naive = pos2 - pos1;\n }\n\n return Some(min(distance_naive, 4 * n - distance_naive));\n}\n\n#[cfg(test)]\nmod tests {\n use super::get_distance;\n\n #[test]\n fn test1() {\n assert_eq!(get_distance(2, 0, 0, 1, 0), Some(1));\n }\n\n #[test]\n fn test2() {\n assert_eq!(get_distance(2, 0, 1, 2, 1), Some(4));\n }\n\n #[test]\n fn test3() {\n assert_eq!(get_distance(100, 0, 0, 100, 100), Some(200));\n }\n}\n\nfn main() {\n let stdin = stdin();\n let mut input_line: String = String::new();\n stdin.read_line(&mut input_line).unwrap();\n let input_vec: Vec = input_line\n .trim()\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n\n let n: u16 = input_vec[0];\n let x1: u16 = input_vec[1];\n let y1: u16 = input_vec[2];\n let x2: u16 = input_vec[3];\n let y2: u16 = input_vec[4];\n\n let distance: u16 = get_distance(n, x1, y1, x2, y2).unwrap();\n\n println!(\"{}\", distance);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "greedy", "implementation"], "code_uid": "f90f879fbd1271aaa17df2b1dc7b4783", "src_uid": "685fe16c217b5b71eafdb4198822250e", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt,$x:expr,$y:expr) => {{\n\t\tlet b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\n// Mint (mod any) {{{\nmod mint {\n\tuse std::ops::*;\n\t#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Mint(i32,i32);\n\t#[allow(dead_code)] impl Mint {\n\t\tpub fn new>(a: T, m: T) -> Self { Self(Self::cv(a,m),m.into() as i32) }\n\t\tpub unsafe fn new_unchecked(a: i32, m: i32) -> Self { Self(a,m) }\n\t\tfn hi(mut a: i32, m: i32) -> i32 { if a >= m { a -= m; } a }\n\t\tfn lo(mut a: i32, m: i32) -> i32 { if a < 0 { a += m; } a }\n\t\tfn cv>(a: T, m: T) -> i32 { Self::lo((a.into() % m.into()) as i32, m.into() as i32) }\n\t\tpub unsafe fn inv(self) -> Self { self.pow(self.1-2) } // ONLY FOR PRIMES!\n\t\tpub fn pow>(self, b: T) -> Self {\n\t\t\tlet b = b.into(); if b == 0 { Self(1,self.1) } else {\n\t\t\t\tlet mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res\n\t\t\t}\n\t\t}\n\t}\n\timpl Add for Mint { type Output = Self; fn add(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::hi(self.0 + a.0, self.1), self.1) }}\n\timpl Sub for Mint { type Output = Self; fn sub(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::lo(self.0 - a.0, self.1), self.1) }}\n\timpl Mul for Mint { type Output = Self; fn mul(self, a: Self) -> Self::Output { assert!(self.1==a.1); Self(Self::cv(self.0 as i64 * a.0 as i64, self.1 as i64), self.1) }}\n\timpl Div for Mint { type Output = Self; fn div(self, a: Self) -> Self::Output { self * unsafe {a.inv()} }}\n\timpl Neg for Mint { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0, self.1), self.1) }}\n\timpl AddAssign for Mint { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\n\timpl SubAssign for Mint { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\n\timpl MulAssign for Mint { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\n\timpl DivAssign for Mint { fn div_assign(&mut self, a: Self) { *self = *self / a; } }\n\tuse std::fmt::{Display, Formatter, Result};\n\timpl Display for Mint { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n}\nuse mint::Mint;\n//}}}\n// Square Matrix (any) {{{\ntype MatT = Mint;\n#[derive(Debug,Clone)] struct Mat { n: usize, a: Vec, v0: MatT, v1: MatT }\n#[allow(dead_code)] impl Mat {\n\tfn new(n:usize,v0:MatT,v1:MatT)->Self{Self{n,a:vec![v0;n*n],v0,v1}}\n\tfn diag(n:usize,v0:MatT,v1:MatT,v:MatT)->Self{let mut m=Self::new(n,v0,v1);let mut p=0;for _ in 0..n{m.a[p]=v;p+=n+1;}m}\n\tfn pow(&self,n:u64)->Self{if n==0{Self::diag(self.n,self.v0,self.v1,self.v1)}else{let mut t=self.pow(n/2);t*=t.clone();if n%2==1{t*=self.clone();}t}}\n\tfn range(&self,r:Range,c:Range)->Vec>{if r.startMatT{self.a[r*self.n+c]}\n\tfn at_mut<'a>(&'a mut self,r:usize,c:usize)->&'a mut MatT{&mut self.a[r*self.n+c]}//'\n}\nimpl Mul for Mat{type Output=Self;fn mul(self,o:Self)->Self::Output{assert!(self.n==o.n);let n=self.n;let mut res=Self::new(n,self.v0,self.v1);\n\tfor ii in(0..n).map(|i|i*n){for j in 0..n{let mut t=self.v0;let mut kk=j;for k in 0..n{t+=self.a[ii+k]*o.a[kk];kk+=n;}res.a[ii+j]=t;}}res}}\nimpl Add for Mat{type Output=Self;fn add(mut self,o:Self)->Self{self+=o;self}}\nimpl Sub for Mat{type Output=Self;fn sub(mut self,o:Self)->Self{self-=o;self}}\nimpl MulAssign for Mat{fn mul_assign(&mut self,a:Self){*self=self.clone()*a;}}\nimpl AddAssign for Mat{fn add_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x+=y;}} }\nimpl SubAssign for Mat{fn sub_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x-=y;}} }\nimpl PartialEq for Mat{fn eq(&self,o:&Self)->bool{self.n==o.n&&self.a==o.a}}impl Eq for Mat{}\n// }}}\n\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tl!(n,k,l,m = rin.l());\n\tif l <= 60 && k >= 1 << l {\n\t\twriteln!(rout, \"0\").ok();\n\t\treturn;\n\t}\n\tlet m0 = Mint::new(0,m);\n\tlet m1 = Mint::new(1,m);\n\n\tlet b1 = k.count_ones() as i64;\n\tlet b0 = l - b1;\n\tlet mut f = Mat::new(2,m0,m1);\n\t*f.at_mut(0,0) = m0;\n\t*f.at_mut(0,1) = m1;\n\t*f.at_mut(1,0) = m1;\n\t*f.at_mut(1,1) = m1;\n\tlet res_f = f.pow(n as u64 + 2).at(0,1);\n\tlet res_b = Mint::new(2,m).pow(n);\n\tlet sol = (res_b - res_f).pow(b1) * res_f.pow(b0);\n\twriteln!(rout, \"{}\", sol).ok();\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "matrices", "implementation", "number theory"], "code_uid": "2ead0c698b9122219c781ab7fbdae8ec", "src_uid": "2163eec2ea1eed5da8231d1882cb0f8e", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let n = parse_line!(usize);\n let a = parse_line_to_vec!(u32);\n let mut dp = vec![vec![[n, n]; n + 1]; n + 1];\n dp[0][0][0] = 0;\n dp[0][0][1] = 0;\n for i in 0..n {\n if a[i] != 0 {\n if a[i] % 2 == 0 {\n for i in (1..=n).rev() {\n for j in 0..=n {\n dp[i][j][0] = std::cmp::min(dp[i][j][0],\n std::cmp::min(dp[i - 1][j][0], dp[i - 1][j][1] + 1));\n }\n }\n }else{\n for i in 0..=n {\n for j in (1..=n).rev() {\n dp[i][j][1] = std::cmp::min(dp[i][j][1],\n std::cmp::min(dp[i][j - 1][1], dp[i][j - 1][0] + 1));\n }\n }\n }\n continue;\n }\n for i in (0..=n).rev() {\n for j in (0..=n).rev() {\n if i > 0 {\n dp[i][j][0] = std::cmp::min(dp[i][j][0],\n std::cmp::min(dp[i - 1][j][0], dp[i - 1][j][1] + 1));\n }\n if j > 0 {\n dp[i][j][1] = std::cmp::min(dp[i][j][1],\n std::cmp::min(dp[i][j - 1][1], dp[i][j - 1][0] + 1));\n }\n }\n }\n }\n writeln!(writer, \"{}\", dp[n / 2][n - n / 2].iter().min().unwrap()).unwrap();\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "dp", "greedy"], "code_uid": "f09cfe94e388e8d1ba7ef380753575d5", "src_uid": "90db6b6548512acfc3da162144169dba", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nuse std::cmp::*;\nuse std::collections::BTreeMap;\n\nfn run() {\n input! {\n n: usize,\n p: [usize; n],\n }\n let mut cnt = [0; 2];\n for p in p.iter() {\n if *p == 0 {\n continue;\n }\n cnt[*p % 2] += 1;\n }\n let even = n / 2 - cnt[0];\n let odd = (n + 1) / 2 - cnt[1];\n let inf = n;\n let mut dp = BTreeMap::<(usize, usize, usize), usize>::new();\n dp.insert((0, even, odd), 0);\n dp.insert((1, even, odd), 0);\n for p in p.iter().rev() {\n let mut next = BTreeMap::<(usize, usize, usize), usize>::new();\n for ((b, x, y), v) in dp {\n if *p == 0 {\n if x > 0 {\n let po = next.entry((0, x - 1, y)).or_insert(inf);\n *po = min(*po, v + (b ^ 0));\n }\n if y > 0 {\n let po = next.entry((1, x, y - 1)).or_insert(inf);\n *po = min(*po, v + (b ^ 1));\n }\n } else {\n let po = next.entry((*p % 2, x, y)).or_insert(inf);\n *po = min(*po, v + (b ^ (*p & 1)));\n }\n }\n dp = next;\n }\n let mut ans = inf;\n for (_, v) in dp {\n ans = min(ans, v);\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "dp", "greedy"], "code_uid": "eee5e698e065f4445a189838e7b8c49a", "src_uid": "90db6b6548512acfc3da162144169dba", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unknown_lints)]\n#![allow(unused_imports, unused_macros, non_snake_case, bare_trait_objects)]\n#![allow(renamed_and_removed_lints, redundant_field_names)]\nuse std::cmp::Ordering::{self, Greater, Less};\nuse std::cmp::{max, min};\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\nuse std::error::Error;\nuse std::io::{self, BufReader, BufWriter, Read, Write};\nuse text_scanner::{scan, scan_iter, scanln, scanln_iter};\nuse utils::adj4_iter;\n\nfn run() {\n let n: usize = scan();\n let p: Vec = scan_iter().collect();\n let mut zero = 0;\n let mut one = 0;\n for i in 1..n + 1 {\n if !p.contains(&i) {\n if i % 2 == 0 {\n zero += 1;\n } else {\n one += 1;\n }\n }\n }\n let mut dp = vec![vec![vec![vec![i32::max_value(); 2]; one + 1]; zero + 1]; n + 1];\n dp[0][0][0][0] = 0;\n dp[0][0][0][1] = 0;\n for i in 0..n {\n for z in 0..zero + 1 {\n for o in 0..one + 1 {\n for cur in 0..2 {\n if dp[i][z][o][cur] == i32::max_value() {\n continue;\n }\n for next in 0..2 {\n if p[i] != 0 && p[i] % 2 != next {\n continue;\n }\n let nz = if p[i] == 0 && next == 0 { z + 1 } else { z };\n let no = if p[i] == 0 && next == 1 { o + 1 } else { o };\n if nz > zero || no > one {\n continue;\n }\n let nvalue =\n dp[i][z][o][cur] + if cur as i32 != next as i32 { 1 } else { 0 };\n dp[i + 1][nz as usize][no as usize][next as usize].set_min(nvalue);\n }\n }\n }\n }\n }\n let mut ans = i32::max_value();\n for z in 0..zero + 1 {\n for o in 0..one + 1 {\n for cur in 0..2 {\n ans.set_min(dp[n][z][o][cur]);\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n std::thread::Builder::new()\n .name(\"run\".to_string())\n .stack_size(256 * 1024 * 1024)\n .spawn(run)\n .unwrap()\n .join()\n .unwrap()\n}\n\n//{{{ utils\npub mod utils {\n static DY: [isize; 8] = [0, 1, 0, -1, 1, -1, 1, -1];\n static DX: [isize; 8] = [1, 0, -1, 0, 1, 1, -1, -1];\n\n fn try_adj(\n y: usize,\n x: usize,\n dy: isize,\n dx: isize,\n h: usize,\n w: usize,\n ) -> Option<(usize, usize)> {\n let ny = y as isize + dy;\n let nx = x as isize + dx;\n if ny >= 0 && nx >= 0 {\n let ny = ny as usize;\n let nx = nx as usize;\n if ny < h && nx < w {\n Some((ny, nx))\n } else {\n None\n }\n } else {\n None\n }\n }\n\n pub struct Adj4 {\n y: usize,\n x: usize,\n h: usize,\n w: usize,\n r: usize,\n }\n\n impl Iterator for Adj4 {\n type Item = (usize, usize);\n\n fn next(&mut self) -> Option {\n loop {\n if self.r >= 4 {\n return None;\n }\n\n let dy = DY[self.r];\n let dx = DX[self.r];\n self.r += 1;\n\n if let Some((ny, nx)) = try_adj(self.y, self.x, dy, dx, self.h, self.w) {\n return Some((ny, nx));\n }\n }\n }\n }\n\n pub fn adj4_iter(y: usize, x: usize, h: usize, w: usize) -> Adj4 {\n Adj4 {\n y: y,\n x: x,\n h: h,\n w: w,\n r: 0,\n }\n }\n}\npub mod text_scanner {\n use std;\n #[derive(Debug)]\n pub enum Error {\n IoError(std::io::Error),\n EncodingError(std::string::FromUtf8Error),\n ParseError(String),\n Eof,\n }\n\n impl std::fmt::Display for Error {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n match *self {\n Error::IoError(ref e) => writeln!(f, \"IO Error: {}\", e),\n Error::EncodingError(ref e) => writeln!(f, \"Encoding Error: {}\", e),\n Error::ParseError(ref e) => writeln!(f, \"Parse Error: {}\", e),\n Error::Eof => writeln!(f, \"EOF\"),\n }\n }\n }\n\n impl std::error::Error for Error {\n // dummy implementation for 1.15.1\n fn description(&self) -> &str {\n \"description() is deprecated; use Display\"\n }\n }\n\n pub fn read_line() -> Option {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n fread_line(&mut stdin).expect(\"IO error\")\n }\n\n pub fn scan() -> T {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n fscan(&mut stdin).expect(\"IO error\")\n }\n\n pub fn scanln() -> T {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n fscanln(&mut stdin).expect(\"IO error\")\n }\n\n pub fn scan_iter() -> ScanIter {\n ScanIter {\n item_type: std::marker::PhantomData,\n }\n }\n\n pub fn scanln_iter() -> ScanlnIter {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n let s = fread_line(&mut stdin)\n .expect(\"IO error\")\n .unwrap_or_else(String::new);\n ScanlnIter {\n cursor: std::io::Cursor::new(s),\n item_type: std::marker::PhantomData,\n }\n }\n\n pub fn fread_line(r: &mut R) -> Result, std::io::Error> {\n let mut buf = String::new();\n let length = r.read_line(&mut buf)?;\n if let Some('\\n') = buf.chars().last() {\n buf.pop();\n }\n if let Some('\\r') = buf.chars().last() {\n buf.pop();\n }\n if length == 0 {\n Ok(None)\n } else {\n Ok(Some(buf))\n }\n }\n\n pub fn fscan(reader: &mut R) -> Result {\n let mut tokenizer = Tokenizer::new(reader);\n FromTokens::from_tokens(&mut tokenizer)\n }\n\n pub fn fscanln(reader: &mut R) -> Result {\n let s = match fread_line(reader) {\n Ok(Some(s)) => s,\n Ok(None) => return Err(Error::Eof),\n Err(e) => return Err(Error::IoError(e)),\n };\n let mut bytes = s.as_bytes();\n let mut tokenizer = Tokenizer::new(&mut bytes);\n FromTokens::from_tokens(&mut tokenizer)\n }\n\n pub fn fscan_iter(reader: &mut R) -> FscanIter {\n FscanIter {\n tokenizer: Tokenizer::new(reader),\n item_type: std::marker::PhantomData,\n }\n }\n\n pub fn fscanln_iter(\n reader: &mut R,\n ) -> Result, Error> {\n let s = match fread_line(reader) {\n Ok(Some(s)) => s,\n Ok(None) => \"\".to_string(),\n Err(e) => return Err(Error::IoError(e)),\n };\n Ok(ScanlnIter {\n cursor: std::io::Cursor::new(s),\n item_type: std::marker::PhantomData,\n })\n }\n\n pub struct ScanIter\n where\n T: FromTokens,\n {\n item_type: std::marker::PhantomData,\n }\n\n impl Iterator for ScanIter {\n type Item = T;\n\n fn next(&mut self) -> Option {\n let stdin = std::io::stdin();\n let mut stdin = stdin.lock();\n let mut tokenizer = Tokenizer::new(&mut stdin);\n match FromTokens::from_tokens(&mut tokenizer) {\n Err(Error::Eof) => None,\n r => Some(r.expect(\"IO error\")),\n }\n }\n }\n\n pub struct FscanIter<'a, R, T>\n where\n R: std::io::Read + 'a,\n T: FromTokens,\n {\n tokenizer: Tokenizer<'a, R>,\n item_type: std::marker::PhantomData,\n }\n\n impl<'a, R: std::io::Read, T: FromTokens> Iterator for FscanIter<'a, R, T> {\n type Item = Result;\n\n fn next(&mut self) -> Option {\n match FromTokens::from_tokens(&mut self.tokenizer) {\n Err(Error::Eof) => None,\n r => Some(r),\n }\n }\n }\n\n pub struct ScanlnIter\n where\n T: FromTokens,\n {\n cursor: std::io::Cursor,\n item_type: std::marker::PhantomData,\n }\n\n impl<'a, T: FromTokens> Iterator for ScanlnIter {\n type Item = T;\n\n fn next(&mut self) -> Option {\n let mut tokenizer = Tokenizer::new(&mut self.cursor);\n match FromTokens::from_tokens(&mut tokenizer) {\n Err(Error::Eof) => None,\n r => Some(r.expect(\"IO error\")),\n }\n }\n }\n\n pub trait FromTokens\n where\n Self: Sized,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result;\n }\n\n macro_rules! from_tokens_primitives {\n ($($t:ty),*) => { $(\n impl FromTokens for $t {\n fn from_tokens(tokenizer: &mut Iterator>) -> Result {\n let token = tokenizer.next();\n match token {\n Some(s) => s?\n .parse::<$t>()\n .map_err(|e| Error::ParseError(format!(\"{}\", e))),\n None => Err(Error::Eof),\n }\n }\n }\n )* }\n}\n\n from_tokens_primitives! {\n String,\n bool,\n f32,\n f64,\n isize,\n i8,\n i16,\n i32,\n i64,\n usize,\n u8,\n u16,\n u32,\n u64\n }\n\n impl FromTokens for Vec {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok(String::from_tokens(tokenizer)?.chars().collect())\n }\n }\n\n impl FromTokens for (T1, T2)\n where\n T1: FromTokens,\n T2: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((T1::from_tokens(tokenizer)?, T2::from_tokens(tokenizer)?))\n }\n }\n\n impl FromTokens for (T1, T2, T3)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n ))\n }\n }\n\n impl FromTokens for (T1, T2, T3, T4)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n T4: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n T4::from_tokens(tokenizer)?,\n ))\n }\n }\n\n impl FromTokens for (T1, T2, T3, T4, T5)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n T4: FromTokens,\n T5: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n T4::from_tokens(tokenizer)?,\n T5::from_tokens(tokenizer)?,\n ))\n }\n }\n\n impl FromTokens for (T1, T2, T3, T4, T5, T6)\n where\n T1: FromTokens,\n T2: FromTokens,\n T3: FromTokens,\n T4: FromTokens,\n T5: FromTokens,\n T6: FromTokens,\n {\n fn from_tokens(\n tokenizer: &mut Iterator>,\n ) -> Result {\n Ok((\n T1::from_tokens(tokenizer)?,\n T2::from_tokens(tokenizer)?,\n T3::from_tokens(tokenizer)?,\n T4::from_tokens(tokenizer)?,\n T5::from_tokens(tokenizer)?,\n T6::from_tokens(tokenizer)?,\n ))\n }\n }\n\n struct Tokenizer<'a, R: std::io::Read + 'a> {\n reader: &'a mut R,\n }\n\n impl<'a, R: std::io::Read> Tokenizer<'a, R> {\n pub fn new(reader: &'a mut R) -> Self {\n Tokenizer { reader: reader }\n }\n\n pub fn next_token(&mut self) -> Result, Error> {\n use std::io::Read;\n let mut token = Vec::new();\n for b in self.reader.by_ref().bytes() {\n let b = b.map_err(Error::IoError)?;\n match (is_ascii_whitespace(b), token.is_empty()) {\n (false, _) => token.push(b),\n (true, false) => break,\n (true, true) => {}\n }\n }\n if token.is_empty() {\n return Ok(None);\n }\n String::from_utf8(token)\n .map(Some)\n .map_err(Error::EncodingError)\n }\n }\n\n impl<'a, R: std::io::Read> Iterator for Tokenizer<'a, R> {\n type Item = Result;\n fn next(&mut self) -> Option {\n match self.next_token() {\n Ok(Some(s)) => Some(Ok(s)),\n Ok(None) => None,\n Err(e) => Some(Err(e)),\n }\n }\n }\n\n fn is_ascii_whitespace(b: u8) -> bool {\n // Can use u8::is_ascii_whitespace once removing support of 1.15.1\n match b {\n b'\\t' | b'\\n' | b'\\x0C' | b'\\r' | b' ' => true,\n _ => false,\n }\n }\n}\n\npub trait SetMinMax {\n fn set_min(&mut self, v: Self) -> bool;\n fn set_max(&mut self, v: Self) -> bool;\n}\n\nimpl SetMinMax for T\nwhere\n T: PartialOrd,\n{\n fn set_min(&mut self, v: T) -> bool {\n *self > v && {\n *self = v;\n true\n }\n }\n fn set_max(&mut self, v: T) -> bool {\n *self < v && {\n *self = v;\n true\n }\n }\n}\n\n#[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]\npub struct Reverse(pub T);\n\nimpl PartialOrd for Reverse {\n #[inline]\n fn partial_cmp(&self, other: &Reverse) -> Option {\n other.0.partial_cmp(&self.0)\n }\n\n #[inline]\n fn lt(&self, other: &Self) -> bool {\n other.0 < self.0\n }\n #[inline]\n fn le(&self, other: &Self) -> bool {\n other.0 <= self.0\n }\n #[inline]\n fn ge(&self, other: &Self) -> bool {\n other.0 >= self.0\n }\n #[inline]\n fn gt(&self, other: &Self) -> bool {\n other.0 > self.0\n }\n}\n\nimpl Ord for Reverse {\n #[inline]\n fn cmp(&self, other: &Reverse) -> Ordering {\n other.0.cmp(&self.0)\n }\n}\n\n#[derive(PartialEq, PartialOrd, Debug, Copy, Clone, Default)]\npub struct Num(pub f64);\n\nimpl Eq for Num {}\n\nimpl Ord for Num {\n fn cmp(&self, other: &Num) -> Ordering {\n self.0\n .partial_cmp(&other.0)\n .expect(\"unexpected NaN when compare\")\n }\n}\n\n// See https://docs.rs/superslice/1.0.0/superslice/trait.Ext.html\npub trait SliceExt {\n type Item;\n\n fn lower_bound(&self, x: &Self::Item) -> usize\n where\n Self::Item: Ord;\n\n fn lower_bound_by<'a, F>(&'a self, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering;\n\n fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord;\n\n fn upper_bound(&self, x: &Self::Item) -> usize\n where\n Self::Item: Ord;\n\n fn upper_bound_by<'a, F>(&'a self, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering;\n\n fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord;\n}\n\nimpl SliceExt for [T] {\n type Item = T;\n\n fn lower_bound(&self, x: &Self::Item) -> usize\n where\n T: Ord,\n {\n self.lower_bound_by(|y| y.cmp(x))\n }\n\n fn lower_bound_by<'a, F>(&'a self, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering,\n {\n let s = self;\n let mut size = s.len();\n if size == 0 {\n return 0;\n }\n let mut base = 0usize;\n while size > 1 {\n let half = size / 2;\n let mid = base + half;\n let cmp = f(unsafe { s.get_unchecked(mid) });\n base = if cmp == Less { mid } else { base };\n size -= half;\n }\n let cmp = f(unsafe { s.get_unchecked(base) });\n base + (cmp == Less) as usize\n }\n\n fn lower_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord,\n {\n self.lower_bound_by(|e| f(e).cmp(k))\n }\n\n fn upper_bound(&self, x: &Self::Item) -> usize\n where\n T: Ord,\n {\n self.upper_bound_by(|y| y.cmp(x))\n }\n\n fn upper_bound_by<'a, F>(&'a self, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> Ordering,\n {\n let s = self;\n let mut size = s.len();\n if size == 0 {\n return 0;\n }\n let mut base = 0usize;\n while size > 1 {\n let half = size / 2;\n let mid = base + half;\n let cmp = f(unsafe { s.get_unchecked(mid) });\n base = if cmp == Greater { base } else { mid };\n size -= half;\n }\n let cmp = f(unsafe { s.get_unchecked(base) });\n base + (cmp != Greater) as usize\n }\n\n fn upper_bound_by_key<'a, K, F>(&'a self, k: &K, mut f: F) -> usize\n where\n F: FnMut(&'a Self::Item) -> K,\n K: Ord,\n {\n self.upper_bound_by(|e| f(e).cmp(k))\n }\n}\n\n//}}}\n", "lang_cluster": "Rust", "tags": ["sortings", "dp", "greedy"], "code_uid": "ad7602452b020fd9210520fed685cd15", "src_uid": "90db6b6548512acfc3da162144169dba", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let stdin = std::io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n line.trim().into()\n}\n\nmacro_rules! scan_line {\n ($($ty: ty),*) => {{\n let line = read_line();\n let mut iter = line.split_whitespace();\n ($(iter.next().unwrap().parse::<$ty>().unwrap()),*)\n }}\n}\n\nfn main() {\n let (n, a, b) = scan_line!(i32, i32, i32);\n let mut lo = 1;\n let mut hi = n;\n let mut max_min = 0;\n while lo < hi {\n let mid = lo + (hi - lo) / 2;\n let ap = a / mid;\n let bp = b / (n - mid);\n max_min = std::cmp::max(max_min, std::cmp::min(ap, bp));\n if ap == bp {\n break;\n } else if ap < bp {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n println!(\"{}\", max_min);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "7113f6b8a2f8843b6be9178b6952ca0f", "src_uid": "a254b1e3451c507cf7ce3e2496b3d69e", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n}\n\npub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n}\n\nfn main() {\n try_main().unwrap();\n}\n\nfn try_main() -> Result<(), Box> {\n let stdin = io::stdin();\n let mut sc = Scanner::new(stdin.lock());\n let n : usize = sc.next();\n let a : usize = sc.next();\n let b : usize = sc.next();\n let mut mc : usize = 0;\n for to_a in 1..n {\n let to_b = n.checked_sub(to_a).unwrap();\n let num_a = a / to_a;\n let num_b = b / to_b;\n mc = std::cmp::max(std::cmp::min(num_a, num_b), mc);\n }\n println!(\"{}\", mc);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "1c6d6dc59b288fc90fd5088f94a8e0b4", "src_uid": "a254b1e3451c507cf7ce3e2496b3d69e", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn main() {\n let (n, a, b) = get!(usize, usize, usize);\n\n let mut ans = 1;\n for i in 1..n {\n let k = n - i;\n\n if a >= i && b >= k {\n ans = max(ans, min(a / i, b / k));\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "90379a6033823d68c3670ec03cc305d6", "src_uid": "a254b1e3451c507cf7ce3e2496b3d69e", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut input = String::new();\n\tio::stdin().read_line(&mut input).unwrap();\n\t\n\tlet mut iter = input.split_whitespace();\n\tlet n: u16 = iter.next().unwrap().parse().unwrap();\n\tlet a: u16 = iter.next().unwrap().parse().unwrap();\n\tlet b: u16 = iter.next().unwrap().parse().unwrap();\n\tlet lower: u16 = if a < b { a } else { b };\n\t\n\tlet mut max: u16 = if a > b { a } else { b };\n\tlet mut min: u16 = 1;\n\tlet mut x: u16 = 1;\n\n\twhile min <= max {\n\t\tlet cur = (max + min) / 2;\n\n\t\tif cur <= lower && a / cur + b / cur >= n {\n\t\t\tx = cur;\n\t\t\tmin = cur + 1;\n\t\t} else {\n\t\t\tmax = cur - 1;\n\t\t}\n\t}\n\n\tprintln!(\"{}\", x);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "210d5260d5fdd1177690cda033d8e333", "src_uid": "a254b1e3451c507cf7ce3e2496b3d69e", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut input = String::new();\n\tio::stdin().read_line(&mut input).unwrap();\n\t\n\tlet mut iter = input.split_whitespace();\n\tlet n: u16 = iter.next().unwrap().parse().unwrap();\n\tlet a: u16 = iter.next().unwrap().parse().unwrap();\n\tlet b: u16 = iter.next().unwrap().parse().unwrap();\n\n\tlet mut max: u16 = if a > b { a } else { b };\n\tlet mut min: u16 = 1;\n\tlet mut x: u16 = 1;\n\n\twhile min <= max {\n\t\tlet cur = (max + min) / 2;\n\t\tlet max_a = a / cur;\n\t\tlet max_b = b / cur;\n\n\t\tif max_a >= 1 && max_b >= 1 && max_a + max_b >= n {\n\t\t\tx = cur;\n\t\t\tmin = cur + 1;\n\t\t} else {\n\t\t\tmax = cur - 1;\n\t\t}\n\t}\n\n\tprintln!(\"{}\", x);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "18eb59fa252032050c71e46c4af144f6", "src_uid": "a254b1e3451c507cf7ce3e2496b3d69e", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\nuse std::str;\nuse std::cmp::min;\n\nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitAsciiWhitespace<'static>\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: Vec::new(), buf_iter: \"\".split_ascii_whitespace() }\n }\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n fn next_line(&mut self) -> String {\n let mut line = String::new();\n self.reader.read_line(&mut line).expect(\"Failed to read line\");\n line\n }\n\n fn next_vec(&mut self) -> Vec {\n let mut res: Vec = Vec::new();\n loop {\n loop {\n match self.buf_iter.next() {\n Some(token) => res.push(token.parse().ok().expect(\"Failed parse\")),\n None => break,\n }\n }\n if res.len() > 0 {\n return res;\n }\n self.buf_str.clear();\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n fn next_vec_n(&mut self, n: u32) -> Vec {\n (0..n).map(|_| self.next()).collect()\n }\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut cin = Scanner::new(stdin.lock());\n let mut cout = io::BufWriter::new(stdout.lock());\n\n let n = cin.next::();\n let m = cin.next::();\n let t = cin.next_vec_n::(n);\n let mut count = [0 as u32; 101];\n let mut sum: u32 = 0;\n\n for v in t {\n sum += v;\n let mut ret = 0;\n let mut tsum = sum;\n for i in 1..101 {\n if count[(101 - i) as usize] == 0 {\n continue;\n }\n if tsum <= m {\n break;\n }\n let x: u32 = min((tsum - m + 101 - i - 1) / (101 - i), count[(101 - i) as usize]);\n tsum -= x * (101 - i) as u32;\n ret += x;\n }\n count[v as usize] += 1;\n write!(cout, \"{} \", ret).ok();\n }\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "greedy"], "code_uid": "f9120b1f8cd8068a62a483e81bc19eb5", "src_uid": "d3c1dc3ed7af2b51b4c49c9b5052c346", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{BufReader, BufWriter, stdin, stdout, Write};\nuse std::cmp::{min, max};\nuse std::collections::{VecDeque, HashMap, BTreeMap, HashSet, BTreeSet, BinaryHeap};\n\nfn main() {\n\tlet mut inp = my_input::default();\n\tlet out = &mut BufWriter::new(stdout());\n\tlet n = inp.scan::();\n\tlet m = inp.scan::();\n\tlet T:Vec = (0..n).map(|_| inp.scan::()).collect();\n\tlet mut acnt = vec![0 as usize; 101];\n\tlet mut ans:Vec = Vec::new();\n\tfor i in T {\n\t\tlet mut cnt = 0 as usize;\n\t\tlet mut sum = i as usize;\n\t\tfor j in 1..101 {\n\t\t\tlet mut C = min(acnt[j], (m - sum) / j);\n\t\t\tsum += j * C;\n\t\t\tcnt += acnt[j] - C;\n\t\t}\n\t\tans.push(cnt);\n\t\tacnt[i] += 1;\n\t}\n\tfor i in ans {\n\t\twrite!(out, \"{} \", i);\n\t}\n}\n\n#[derive(Default)]\nstruct my_input {\n\tbuffer: Vec\n}\n\nimpl my_input {\n\tfn scan(&mut self) -> T {\n\t\tloop {\n\t\t\tif let Some(token) = self.buffer.pop() {\n\t\t\t\treturn token.parse().ok().expect(\"Parsing Error\");\n\t\t\t}\n\t\t\tlet mut s = String::new();\n\t\t\tstdin().read_line(&mut s).expect(\"Reading Error\");\n\t\t\tself.buffer = s.split_whitespace().rev().map(String::from).collect();\n\t\t}\n\t}\n}", "lang_cluster": "Rust", "tags": ["sortings", "greedy"], "code_uid": "1905326797c6b334fde97aeb79a33dc4", "src_uid": "d3c1dc3ed7af2b51b4c49c9b5052c346", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n let mut bout = BufWriter::new(stdout());\n\n let n = input.u();\n let m = input.i();\n let mut c = vec![0; 101];\n let mut sum = 0;\n for _ in 0..n {\n let t = input.i();\n sum += t;\n let mut s = sum - m;\n let mut res = 0;\n if s > 0 {\n for i in (1..101).rev() {\n let x = c[i as usize];\n if x * i <= s {\n s -= x * i;\n res += x;\n } else {\n res += (s + i - 1) / i;\n break;\n }\n }\n }\n c[t as usize] += 1;\n write!(bout, \"{} \", res).ok();\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["sortings", "greedy"], "code_uid": "8293d4877e4ed9612e6cc5225fde7358", "src_uid": "d3c1dc3ed7af2b51b4c49c9b5052c346", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let sol = input.i().min(input.i()/2).min(input.i()/4) * 7;\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "3319b18ff9f907b965d5ee9aa94316de", "src_uid": "82a4a60eac90765fb62f2a77d2305c01", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let a = readln!(i32);\n let b = readln!(i32);\n let c = readln!(i32);\n let t = min(a,min(b/2,c/4));\n println!(\"{}\",t*7);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a78f10f6c111d8c554db84bb3d4b3b9a", "src_uid": "82a4a60eac90765fb62f2a77d2305c01", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::*;\n\nfn main() {\n let (n, _) = {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n (it.next().unwrap(), it.next().unwrap())\n };\n\n let mut a = String::new();\n stdin().read_line(&mut a).unwrap();\n let a = a.split_whitespace().map(|k| k.parse::().unwrap());\n let (mut a1, mut a2, mut a4) = a.fold((0, 0, 0), |(a1, a2, a4), ai| (a1 + ai % 2, a2 + ai % 4 - ai % 2, a4 + ai - ai % 4));\n\n let mut s4 = 4 * n;\n let mut s2 = 4 * n;\n\n let tmp = min(a2, s2);\n a2 -= tmp;\n s2 -= tmp;\n let tmp = min(a2, s4 / 2);\n a2 -= tmp;\n s4 -= tmp;\n let tmp = min(2 * a2, s4);\n a2 -= tmp / 2;\n s4 -= tmp;\n let tmp = min(a4, s4);\n a4 -= tmp;\n s4 -= tmp;\n let tmp = min(a4, s2);\n a4 -= tmp;\n s2 -= tmp;\n let tmp = min(a1, s4 / 2);\n a1 -= tmp;\n let tmp = min(a1, s2 / 2);\n a1 -= tmp;\n\n if a1 + a2 + a4 > 0 {\n println!(\"NO\");\n } else {\n println!(\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "21f1e28fbf85736fd2e8543b7e780d9b", "src_uid": "d1f88a97714d6c13309c88fcf7d86821", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//jdoodle.com:rustc 1.10.0--codeforces.com:1.19\nfn main(){\n let mut z=String::new();std::io::stdin().read_line(&mut z);let mut a:i32=z.trim().parse().expect(\"\");a*=2;let mut b=false;\n for i in 1..(a as f32).sqrt()as i32{\n let c=a-i*i-i;let d=(c as f32).sqrt()as i32;\n if d*(d+1)==c{b=true}\n }\n print!(\"{}\",if b{\"YES\"}else{\"NO\"})\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "79183717687323d2444a1ecb632af354", "src_uid": "245ec0831cd817714a4e5c531bffd099", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 991B\nuse std::io;\n\nfn main() {\n let n: u32 = read_one(&io::stdin());\n let mut v: Vec = read_vector(&io::stdin());\n\n v.sort();\n let target_score = (4.5 * (n as f32)).ceil() as u32;\n let mut current_score: u32 = v.iter().sum();\n let mut labs = 0;\n for e in v {\n if current_score < target_score {\n current_score += (5 - e);\n labs += 1;\n } else {\n break;\n }\n }\n println!(\"{}\", labs);\n}\n\nfn read_vector(stdin: &io::Stdin) -> Vec\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n s = s.trim().to_string();\n let mut v: Vec = Vec::new();\n for n in s.split_whitespace() {\n let i: T = n.parse().unwrap();\n v.push(i);\n }\n v\n}\n\nfn read_one(stdin: &io::Stdin) -> T\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n s.trim().split_whitespace().next().unwrap().parse().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "greedy"], "code_uid": "9f1730d6e25e39b0e719526cf03ad450", "src_uid": "715608282b27a0a25b66f08574a6d5bd", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut ss: String = String::new();\n io::stdin().read_line(&mut ss).unwrap();\n let n: isize = ss.trim().parse().unwrap();\n\n let mut s: String = String::new();\n io::stdin().read_line(&mut s).unwrap();\n io::stdin().read_line(&mut s).unwrap();\n let v: Vec = s.trim()\n .split(' ')\n .map(|n| n.parse().unwrap())\n .collect();\n\n let mut g = vec![0.0; 4];\n\n for a in v.iter() {\n g[a - 2] += 1.0;\n }\n\n let cg = ((g[0]*2.0 + g[1]*3.0 + g[2]*4.0 + g[3]*5.0) / n as f32) + 0.5;\n\n let agg = vec![\n 3.0/n as f32,\n 2.0/n as f32,\n 1.0/n as f32,\n ];\n\n // println!(\"{}\", cg);\n // println!(\"{:?}\", agg);\n\n let mut sol = 5.0 - cg;\n if sol <= 0.0 {\n println!(\"0\");\n return;\n } else {\n let mut nn = (sol / agg[0] - 0.0001).ceil();\n // println!(\"{} {} {}\", sol, agg[0], sol / agg[0]);\n if nn <= g[0] {\n println!(\"{}\", nn);\n return;\n }\n sol -= g[0] * agg[0];\n\n nn = (sol / agg[1] - 0.0001).ceil();\n if nn <= g[1] {\n println!(\"{}\", nn + g[0]);\n return;\n }\n sol -= g[1] * agg[1];\n\n nn = (sol / agg[2] - 0.0001).ceil();\n if nn <= g[2] {\n println!(\"{}\", nn + g[0] + g[1]);\n return;\n }\n\n println!(\"{}\", g[0] + g[1] + g[2]);\n }\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "greedy"], "code_uid": "1d37f8e4285a77b6cd6627b8acf7fb3f", "src_uid": "715608282b27a0a25b66f08574a6d5bd", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nconst N: i64 = 998_244_353;\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let (n, m) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let f_v: Vec = get_vec();\n let s_v: Vec = get_vec();\n\n let first_list = f_v.into_iter()\n .fold(vec![false; 9], |mut acc, d| {\n acc[d - 1] = true;\n acc\n });\n\n let second_list = s_v.into_iter()\n .fold(vec![false; 9], |mut acc, d| {\n acc[d - 1] = true;\n acc\n });\n\n if let Some(i) = (0..first_list.len()).filter(|&i| first_list[i] && second_list[i]).min() {\n println!(\"{}\", i + 1);\n } else {\n let f = first_list.into_iter().position(|p| p).unwrap() + 1;\n let s = second_list.into_iter().position(|p| p).unwrap() + 1;\n print!(\"{}\", min(f, s));\n println!(\"{}\", max(f, s));\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "410fdeed940a971bcd342e3d75174661", "src_uid": "3a0c1b6d710fd8f0b6daf420255d76ee", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::boxed::Box;\nuse std::cmp::*;\nuse std::io;\n\nstruct Rand {\n state: u64,\n}\n\nimpl Rand {\n pub fn new() -> Self {\n Rand { state: 13 }\n }\n\n pub fn rand(&mut self) -> u64 {\n self.state = ((self.state ^ 1000000007) * 10000009) % 1000000013;\n self.state\n }\n}\n\n#[derive(Clone)]\nstruct Node {\n pub key: T,\n pub weight: u64,\n pub left: Option>>,\n pub right: Option>>,\n}\n\nimpl Node {\n fn new(value: T, weight: u64) -> Self {\n Node {\n key: value,\n weight: weight,\n left: None,\n right: None,\n }\n }\n\n pub fn split(\n node: Option>>,\n key: &T,\n ) -> (Option>>, Option>>) {\n match node {\n None => (None, None),\n Some(mut node) => match node.key.cmp(key) {\n Ordering::Less => {\n let (l, r) = Self::split(node.right, key);\n node.right = l;\n (Some(node), r)\n }\n _ => {\n let (l, r) = Self::split(node.left, key);\n node.left = r;\n (l, Some(node))\n }\n },\n }\n }\n\n pub fn merge(left: Option>>, right: Option>>) -> Option>> {\n match (left, right) {\n (None, None) => None,\n (left, None) => left,\n (None, right) => right,\n (Some(mut left), Some(mut right)) => match left.weight.cmp(&right.weight) {\n Ordering::Less => {\n left.right = Self::merge(left.right, Some(right));\n Some(left)\n }\n _ => {\n right.left = Self::merge(Some(left), right.left);\n Some(right)\n }\n },\n }\n }\n\n fn find(node: &Option>>, key: &T) -> bool {\n match node {\n None => false,\n Some(node) => match node.key.cmp(key) {\n Ordering::Less => Self::find(&node.right, key),\n Ordering::Greater => Self::find(&node.left, key),\n Ordering::Equal => true,\n },\n }\n }\n\n fn less(node: &Box>) -> T {\n match node.left {\n None => node.key.clone(),\n Some(ref left) => Self::less(left),\n }\n }\n}\n\nstruct Treap {\n root: Option>>,\n}\n\nimpl Treap {\n pub fn insert(&mut self, key: T, weight: u64) {\n let (mut l, r) = Node::split(self.root.take(), &key);\n l = Node::merge(l, Some(Box::new(Node::new(key, weight))));\n self.root = Node::merge(l, r);\n }\n\n pub fn delete(&mut self, key: &T) {\n let (l, mut r) = Node::split(self.root.take(), key);\n r = match r {\n None => None,\n Some(node) => {\n if &node.key == key {\n Node::merge(node.left, node.right)\n } else {\n Some(node)\n }\n }\n };\n self.root = Node::merge(l, r);\n }\n\n pub fn find(&self, key: &T) -> bool {\n Node::find(&self.root, key)\n }\n\n pub fn less(&self) -> Option {\n match self.root {\n Some(ref root) => Some(Node::less(root)),\n _ => None,\n }\n }\n\n pub fn new() -> Self {\n Treap { root: None }\n }\n}\n\nfn main() {\n let mut buffer = String::new();\n let mut rand = Rand::new();\n io::stdin().read_line(&mut buffer);\n buffer = String::new();\n io::stdin().read_line(&mut buffer);\n buffer.retain(|s| s != '\\r' && s != '\\n');\n let a: Vec = buffer\n .split_whitespace()\n .map(|n| n.parse::().unwrap())\n .collect();\n\n buffer = String::new();\n io::stdin().read_line(&mut buffer);\n buffer.retain(|s| s != '\\r' && s != '\\n');\n let b: Vec = buffer\n .split_whitespace()\n .map(|n| n.parse::().unwrap())\n .collect();\n\n let mut t1 = Treap::new();\n let mut t2 = Treap::new();\n //println!(\"{:?} | {:?}\", &a, &b);\n for n in a {\n t1.insert(n, rand.rand() as u64);\n }\n let mut m3 = 99;\n for n in b {\n t2.insert(n, rand.rand() as u64);\n if t1.find(&n) {\n m3 = std::cmp::min(m3, n);\n }\n }\n let (m1, m2) = (t1.less().unwrap(), t2.less().unwrap());\n\n if m1 != m2 && m3 < 99 {\n println!(\"{}\", m3);\n } else {\n match m1.cmp(&m2) {\n Ordering::Less => println!(\"{}{}\", m1, m2),\n Ordering::Greater => println!(\"{}{}\", m2, m1),\n Ordering::Equal => println!(\"{}\", m2),\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "df3c7662ecda2d1920e96271b652cb16", "src_uid": "3a0c1b6d710fd8f0b6daf420255d76ee", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::io::BufRead;\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n\n lines.next().unwrap().unwrap();\n\n let mut first_list = [false; 10];\n let mut second_list = [false; 10];\n\n lines.next().unwrap().unwrap().split(\" \")\n .map(|x| x.parse::().unwrap())\n .for_each(|x| first_list[x] = true);\n lines.next().unwrap().unwrap().split(\" \")\n .map(|x| x.parse::().unwrap())\n .for_each(|x| second_list[x] = true);\n\n let mut min_first = 10;\n let mut min_second = 10;\n\n for i in 1..10 {\n if first_list[i] && second_list[i] {\n println!(\"{}\", i);\n return;\n }\n if first_list[i] && min_first > i {\n min_first = i;\n }\n if second_list[i] && min_second > i {\n min_second = i;\n }\n }\n\n let result = if min_first > min_second {\n min_second * 10 + min_first\n } else {\n min_first * 10 + min_second\n };\n\n println!(\"{}\", result);\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "f8ce2ab97b4cea811f60dea4d1b0accc", "src_uid": "3a0c1b6d710fd8f0b6daf420255d76ee", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet};\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n\n #[allow(dead_code)]\n pub fn get3() -> (S, T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($x: expr) => {\n println!(\"{}: {:?}\", stringify!($x), $x)\n }\n}\n\nfn main() {\n let (_n, _m): (usize, usize) = util::get2();\n let a: HashSet = util::gets().iter().cloned().collect();\n let b: HashSet = util::gets().iter().cloned().collect();\n\n for i in 1..100 {\n if i < 10 {\n if a.contains(&i) && b.contains(&i) {\n println!(\"{}\", i);\n return;\n }\n } else {\n if (a.contains(&(i / 10)) || a.contains(&(i % 10))) &&\n (b.contains(&(i / 10)) || b.contains(&(i % 10)))\n {\n println!(\"{}\", i);\n return;\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2912759134115bbb0c082fd5e5c8d395", "src_uid": "3a0c1b6d710fd8f0b6daf420255d76ee", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufReader, Stdin};\nuse std::io::prelude::*;\nuse std::collections::BTreeSet;\nuse std::iter::Map;\nuse std::str::SplitWhitespace;\n\nfn main() {\n let mut reader = ReadIn::new();\n\n reader.read_line();\n let a: BTreeSet = reader.read_iter().collect();\n let b: BTreeSet = reader.read_iter().collect();\n let c: BTreeSet = a.intersection(&b).map(|&x| x).collect();\n let res = (if !c.is_empty() { c.iter().map(|&x| x).next() } else {\n a.iter().next().and_then(\n |&ax| b.iter().next().map(\n |&bx| if (ax < bx) { ax * 10 + bx } else { bx * 10 + ax }))\n }).unwrap();\n print!(\"{}\", res);\n}\n\nstruct ReadIn { reader: BufReader, buf: String }\n\nimpl ReadIn {\n fn new() -> ReadIn { ReadIn { reader: BufReader::new(io::stdin()), buf: String::new() } }\n fn read_i32(s: &str) -> i32 { s.parse().unwrap() }\n fn read_line(&mut self) {\n self.buf.clear();\n self.reader.read_line(&mut self.buf);\n }\n fn read_iter(&mut self) -> Map i32> {\n self.read_line();\n self.buf.split_whitespace().map(ReadIn::read_i32)\n }\n fn read_vec(&mut self) -> Vec {\n self.read_iter().collect()\n }\n}\n\n\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7d177348baf2427cca60c0ae9ba96d08", "src_uid": "3a0c1b6d710fd8f0b6daf420255d76ee", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\nimpl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt((val % MOD as usize) as u32)\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n assert!(self.0 > 0);\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Matrix ----------\n#[allow(dead_code)]\nmod matrix {\n use std::ops::{Add, Mul};\n pub trait SemiRing: Add + Mul + Copy {\n fn zero() -> Self;\n fn one() -> Self;\n }\n pub const SIZE: usize = 2;\n #[derive(Clone)]\n pub struct SquareMatrix {\n buf: [[T; SIZE]; SIZE],\n }\n impl SquareMatrix {\n pub fn zero() -> Self {\n let z = T::zero();\n SquareMatrix {\n buf: [[z; SIZE]; SIZE],\n }\n }\n pub fn identity() -> Self {\n let mut m = Self::zero();\n for i in 0..SIZE {\n m.buf[i][i] = T::one();\n }\n m\n }\n pub fn set_at(&mut self, i: usize, j: usize, v: T) {\n self.buf[i][j] = v;\n }\n pub fn get_at(&self, i: usize, j: usize) -> T {\n self.buf[i][j]\n }\n pub fn matmul(&self, rhs: &Self) -> Self {\n let mut res = Self::zero();\n for (x, a) in res.buf.iter_mut().zip(self.buf.iter()) {\n for (a, b) in a.iter().zip(rhs.buf.iter()) {\n for (x, b) in x.iter_mut().zip(b.iter()) {\n *x = *x + *a * *b;\n }\n }\n }\n res\n }\n pub fn matadd(&self, rhs: &Self) -> Self {\n let mut c = Self::zero();\n for (c, (a, b)) in c.buf.iter_mut().zip(self.buf.iter().zip(rhs.buf.iter())) {\n for (c, (a, b)) in c.iter_mut().zip(a.iter().zip(b.iter())) {\n *c = *a + *b;\n }\n }\n c\n }\n pub fn matpow(&self, mut n: usize) -> Self {\n let mut t = Self::identity();\n let mut s = self.clone();\n while n > 0 {\n if n & 1 == 1 {\n t = t.matmul(&s);\n }\n s = s.matmul(&s);\n n >>= 1;\n }\n t\n }\n }\n}\n// ---------- end Matrix ----------\n\nuse matrix::*;\n\nimpl SemiRing for ModInt {\n fn zero() -> Self {\n ModInt::zero()\n }\n fn one() -> Self {\n ModInt::one()\n }\n}\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let mut it = s.trim().split_whitespace();\n let a: ModInt = it.next().unwrap().parse().unwrap();\n let b: ModInt = it.next().unwrap().parse().unwrap();\n let mut n: u64 = it.next().unwrap().parse().unwrap();\n let x: ModInt = it.next().unwrap().parse().unwrap();\n type M = SquareMatrix;\n let mut t = M::identity();\n let mut s = M::zero();\n s.set_at(0, 0, a);\n s.set_at(0, 1, b);\n s.set_at(1, 1, ModInt::one());\n while n > 0 {\n if n & 1 == 1 {\n t = t.matmul(&s);\n }\n s = s.matmul(&s);\n n >>= 1;\n }\n let ans = t.get_at(0, 0) * x + t.get_at(0, 1);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "5b53c58746866c274ad18b5cf4e0f91d", "src_uid": "e22a1fc38c8b2a4cc30ce3b9f893028e", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\nconst MOD: i128 = 1_000_000_007;\n\nfn modpow(a: i128, b: i128) -> i128 {\n let mut a = a;\n let mut b = b;\n let mut ans = 1;\n while b > 0 {\n if b % 2 != 0 {\n ans = (ans * a) % MOD;\n }\n a = (a * a) % MOD;\n b /= 2;\n }\n ans\n}\n\nfn modinv(a: i128) -> i128 {\n modpow(a, MOD - 2) % MOD\n}\n\nfn modadd(a: i128, b: i128) -> i128 {\n let mut ans = (a + b) % MOD;\n if ans < 0 {\n ans += MOD;\n }\n ans\n}\n\nfn modmult(a: i128, b: i128) -> i128 {\n let mut ans = (a * b) % MOD;\n if ans < 0 {\n ans += MOD;\n }\n ans\n}\n\nfn moddiv(a: i128, b: i128) -> i128 {\n (a * modinv(b)) % MOD\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let a: i128 = scan.token();\n let b: i128 = scan.token();\n let n: i128 = scan.token();\n let x: i128 = scan.token();\n let mut ans;\n if n == 0 {\n ans = x % MOD;\n } else if n == 1 {\n ans = modadd(modmult(a, x), b);\n } else if a == 1 {\n ans = modadd(x, modmult(b, n));\n } else {\n ans = modpow(a, n);\n ans = modmult(ans, x);\n let mut quotient = modpow(a, n);\n quotient = modadd(quotient, -1);\n quotient = moddiv(quotient, a - 1);\n let mut part = b % MOD;\n part = modmult(part, quotient);\n ans = modadd(ans, part);\n // ans = ((modpow(a, n) * x) % MOD + ((b * (modpow(a, n) - 1).rem_euclid(MOD)) % MOD * modinv(a - 1)) % MOD) % MOD;\n }\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "f3ea3337cf692c60427a3804ff02bd0c", "src_uid": "e22a1fc38c8b2a4cc30ce3b9f893028e", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nconst M: u64 = 1_000_000_007;\n\nfn mult((a, b): (u64, u64), (c, d): (u64, u64)) -> (u64, u64) {\n ((a*c) % M, (a*d + b) % M)\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let input = input.split_whitespace().map(|s| s.parse().unwrap()).collect::>();\n let a = input[0];\n let b = input[1];\n let mut n = input[2];\n let x = input[3];\n\n let mut g = (1, 0);\n let mut f = (a, b);\n\n while n != 0 {\n if n % 2 == 1 {\n g = mult(g, f);\n }\n f = mult(f, f);\n n = n / 2;\n }\n\n let (a, b) = g;\n println!(\"{}\", (a*x + b) % M);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "b1140f5eca2e9662fee08f2ef8c27c3d", "src_uid": "e22a1fc38c8b2a4cc30ce3b9f893028e", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = [2, 5, 8];\n l!(n,k = input.i());\n let sol: i32 = a.into_iter().map(|x| (x * n + k - 1) / k).sum();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "068e90a22832f8921f01385db85bdfd6", "src_uid": "d259a3a5c38af34b2a15d61157cc0a39", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const RED: i32 = 2;\nconst GREEN: i32 = 5;\nconst BLUE: i32 = 8;\n\n\nfn main() {\n\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"input: read line failed\");\n let mut input = input.trim().split_whitespace();\n\n let friends: i32 = input.next().unwrap().parse().expect(\"friends: parse to i32 failed\");\n let sheets_per_notebook = input.next().unwrap().parse().expect(\"sheets_per_notebook: parse to i32 failed\");\n\n let outcome = notebooks_amount(friends, sheets_per_notebook);\n\n println!(\"{}\", &outcome);\n\n}\n\nfn notebooks_amount(friends: i32, sheets_per_notebook: i32) -> i32 {\n let red_notebook_amount = (friends * RED) / sheets_per_notebook\n + if (friends * RED) % sheets_per_notebook != 0 { 1 } else { 0 };\n let green_notebook_amount = friends * GREEN / sheets_per_notebook\n + if (friends * GREEN) % sheets_per_notebook != 0 { 1 } else { 0 };\n let blue_notebook_amount = friends * BLUE / sheets_per_notebook\n + if (friends * BLUE) % sheets_per_notebook != 0 { 1 } else { 0 };\n\n let total_amount = red_notebook_amount + green_notebook_amount + blue_notebook_amount;\n\n total_amount\n}\n\n\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "819f25e1f02a9becf44d25936f729101", "src_uid": "d259a3a5c38af34b2a15d61157cc0a39", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() -> std::io::Result<()> {\n let mut contents = String::new();\n\tstd::io::stdin().read_line(&mut contents)?;\n\tlet contents: Vec<&str> = contents.split(\"\\r\\n\").collect();\n\tlet contents: &str = contents[0];\n\tlet contents: Vec<&str> = contents.split_whitespace().collect();\n\tlet n:u32 = contents[0].parse().unwrap();\n\tlet k:u32 = contents[1].parse().unwrap();\n\tlet mut r = n*2/k;\n\tif n*2%k!=0{\n\t\tr+=1;\n\t}\n\tlet mut g = n*5/k;\n\tif n*5%k!=0{\n\t\tg+=1;\n\t}\n\tlet mut b = n*8/k;\n\tif n*8%k!=0{\n\t\tb+=1;\n\t}\n\tprintln!(\"{}\",r+g+b);\n\tOk(())\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1106fbb941fdc404166e2591ac7a03a6", "src_uid": "d259a3a5c38af34b2a15d61157cc0a39", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn div_and_ceil(a: i32, b: i32) -> i32 {\n if a % b == 0 { a / b } else { a / b + 1 }\n}\n\nfn main() {\n let (guests, lists) = readln!(i32, i32);\n \n let red = div_and_ceil(2 * guests, lists);\n let green = div_and_ceil(5 * guests, lists);\n let blue = div_and_ceil(8 * guests, lists);\n \n println!(\"{}\", red + green + blue);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "4d5ae75836b94bda95fb81e125bb322d", "src_uid": "d259a3a5c38af34b2a15d61157cc0a39", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($format:expr) => (write!(out,$format).unwrap());\n ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())\n }\n input! {\n n: i64,\n k: i64,\n }\n puts!(\"{}\\n\", (2 * n + k - 1) / k + (5 * n + k - 1) / k + (8 * n + k - 1) / k);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "db48a9591a60fd3db96dd0eb2270e2f8", "src_uid": "d259a3a5c38af34b2a15d61157cc0a39", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\n#[allow(unused_macros)]\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($x:expr, $($xs:expr),*; $sep:expr) => { concat!($x, $($sep, $xs),*) }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dump {\n ($($x:expr),*) => {\n eprintln!(join!($(concat!(stringify!($x), \" = {:?}\")),*; \", \"), $($x),*);\n }\n}\n\n// }}}\n\nuse std::cmp;\n\nfn main() {\n let (a, b, c) = R!(u32, u32, u32);\n let ans = cmp::min(cmp::min(2*(a+b), 2*(b+c)), cmp::min(2*(a+c), a+b+c));\n W!(ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a1d5b6fcad7bd41e6f2ca2229fb86b1e", "src_uid": "26cd7954a21866dbb2824d725473673e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\nfn main() {\n let mut reader = scanner::TokenReader::new();\n let (a, b, c) = (\n reader.next::(),\n reader.next::(),\n reader.next::(),\n );\n\n println!(\n \"{}\",\n min(a + b + c, min((a + b) * 2, min((b + c) * 2, (a + c) * 2)))\n );\n}\n\n// ---------- Begin Scanner ----------\n#[allow(dead_code)]\nmod scanner {\n use std::fmt::Debug;\n use std::str::FromStr;\n\n pub struct TokenReader {\n reader: std::io::Stdin,\n tokens: Vec,\n index: usize,\n }\n\n impl TokenReader {\n pub fn new() -> Self {\n Self {\n reader: std::io::stdin(),\n tokens: Vec::new(),\n index: 0,\n }\n }\n\n pub fn next(&mut self) -> T\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index += 1;\n self.tokens[self.index - 1].parse().unwrap()\n }\n\n pub fn vector(&mut self) -> Vec\n where\n T: FromStr,\n T::Err: Debug,\n {\n if self.index >= self.tokens.len() {\n self.load_next_line();\n }\n self.index = self.tokens.len();\n self.tokens.iter().map(|tok| tok.parse().unwrap()).collect()\n }\n\n pub fn load_next_line(&mut self) {\n let mut line = String::new();\n self.reader.read_line(&mut line).unwrap();\n\n self.tokens = line.split_whitespace().map(String::from).collect();\n self.index = 0;\n }\n }\n}\n// ---------- End Scanner ----------\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7ddb7e73fba83fce57f297bf5ddcf7da", "src_uid": "26cd7954a21866dbb2824d725473673e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n\nuse std::mem;\nuse std::io;\nuse std::string;\nuse std::cmp::*;\nuse std::collections::*;\n\nfn load() -> Vec {\n let mut line = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\n let vec: Vec<&str> = line.split(\" \").collect();\n let mut data: Vec = Vec::new();\n for i in vec {\n let el: i64 = i.trim().parse().unwrap();\n data.push(el);\n }\n data\n}\n\nfn main() {\n let s = load();\n let (a, b, c) = (s[0], s[1], s[2]);\n let mx = max(a, max(b, c));\n let sum = a + b + c;\n println!(\"{}\", min(sum, 2 * (sum - mx)));\n}\n// min, max\n// HashSet, insert, contains\n// HashMap, insert, get\n// Vec, len, sort\n// primitive retype: i as f64\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ec09aaa296f3d2696ca64de3b1b96fbd", "src_uid": "26cd7954a21866dbb2824d725473673e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::cmp::{min, max};\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Scanner {\n Scanner {\n reader: reader,\n buffer: Vec::new(),\n }\n }\n\n /// Use \"turbofish\" syntax next::() to select data type of next token.\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n\n pub fn next_vec(&mut self, len: usize) -> Vec\n where\n T::Err: ::std::fmt::Debug,\n {\n (0..len).map(|_| self.next::()).collect::>()\n }\n}\n\nfn main1() {\n let stdin = io::stdin();\n let mut input = Scanner::new(stdin.lock());\n let d = input.next_vec::(3);\n println!(\"{}\", min(d[0] + d[1] + d[2], min(2 * (d[0] + d[1]), 2 * min(d[0], d[1]) + 2 * d[2])));\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8a536286851367fe0b66ff21fde7540f", "src_uid": "26cd7954a21866dbb2824d725473673e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, std::io::stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut buffer = String::new();\n let mut input = WordReader::from_stdin(&mut buffer);\n\n let a = input.i();\n let b = input.i();\n let c = input.i();\n let sol = a.min(b + c) + b.min(a + c) + c.min(a + b);\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5a85bed10e9503ef1874501a5045d8e7", "src_uid": "26cd7954a21866dbb2824d725473673e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let a = readvec!(i32);\n println!(\"{}\",\n min(min(a[0]+a[2]+a[1],\n a[0]*2+a[1]*2),\n min(a[0]*2+a[2]*2,\n a[1]*2+a[2]*2)));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "908a1c07577328ec8c957ba0f1a64aaa", "src_uid": "26cd7954a21866dbb2824d725473673e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn main() {\n \"abc\".split_whitespace();\n let mut input = String::new();\n io::stdin().read_line(&mut input);\n let mut iter = input.split_whitespace();\n let distance: i64 = iter.next().expect(\"distance expected\").parse().expect(\"integer distance expected\");\n let km_per_stop: i64 = iter.next().expect(\"km_per_stop expected\").parse().expect(\"integer km_per_stop expected\");\n let car_km_time: i64 = iter.next().expect(\"car_km_time expected\").parse().expect(\"car_km_time distance expected\");\n let walk_km_time: i64 = iter.next().expect(\"walk_km_time expected\").parse().expect(\"walk_km_time distance expected\");\n let repair_time: i64 = iter.next().expect(\"repair_time expected\").parse().expect(\"repair_time distance expected\");\n\n let trip_time;\n let car_cost : i64 = car_km_time * km_per_stop - walk_km_time * km_per_stop + repair_time;\n if car_cost >= 0 || km_per_stop >= distance {\n let car_dist = cmp::min(km_per_stop, distance);\n let walk_dist = distance - car_dist;\n trip_time = car_dist * car_km_time + walk_dist * walk_km_time;\n } else {\n let full_stops = distance / km_per_stop;\n let distance_cost = full_stops * km_per_stop * car_km_time;\n let repair_cost = (full_stops - 1) * repair_time;\n let full_stops_cost = distance_cost + repair_cost;\n\n let remaining_dist = distance % km_per_stop;\n let remaining_walk = remaining_dist * walk_km_time;\n let remaining_car = remaining_dist * car_km_time + repair_time;\n let remaining_cost = cmp::min(remaining_walk, remaining_car);\n\n trip_time = full_stops_cost + remaining_cost;\n }\n println!(\"{}\", trip_time);\n\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "7e0459b04ab32465691177f1b37e2d0a", "src_uid": "359ddf1f1aed9b3256836e5856fe3466", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/287/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n/// Stores elements in row-major order.\npub struct Matrix {\n pub elements: Vec,\n pub width: usize\n}\n\nimpl Matrix {\n pub fn row_major_index(&self, idx: (usize, usize)) -> usize {\n let (x, y) = idx;\n y * self.width + x\n }\n\n pub fn get(&self, idx: (usize, usize)) -> Option<&T> {\n let index = self.row_major_index(idx);\n if index < self.elements.len() {\n Some(&self.elements[index])\n } else {\n None\n }\n }\n\n pub fn get_mut(&mut self, idx: (usize, usize)) -> Option<&mut T> {\n let index = self.row_major_index(idx);\n if index < self.elements.len() {\n Some(&mut self.elements[index])\n } else {\n None\n }\n }\n}\n\nimpl Matrix where T: Default + Clone {\n pub fn new(width: usize, height: usize) -> Self {\n Matrix {\n elements: vec![T::default(); width * height],\n width: width\n }\n }\n}\n\nimpl Matrix where T: Clone {\n pub fn with_default(width: usize, height: usize, default: T) -> Self {\n Matrix {\n elements: vec![default; width * height],\n width: width\n }\n }\n}\n\nconst __IMPL_INDEX_FOR_MATRIX: () = {\n use std::ops::{Index, IndexMut};\n \n impl Index<(usize, usize)> for Matrix {\n type Output = T;\n fn index(&self, idx: (usize, usize)) -> &Self::Output {\n self.get(idx).unwrap()\n }\n }\n \n impl IndexMut<(usize, usize)> for Matrix {\n fn index_mut(&mut self, idx: (usize, usize)) -> &mut Self::Output {\n self.get_mut(idx).unwrap()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n let mut square = Matrix::new(4, 4);\n for j in 0..4 {\n scanln!(row: String);\n for (i, &b) in row.as_bytes().iter().enumerate() {\n square[(i, j)] = if b == b'#' { 1u64 } else { 0u64 };\n }\n }\n for i in 0..3 {\n for j in 0..3 {\n let sum = square[(i, j)] + square[(i+1, j)]\n + square[(i, j+1)] + square[(i+1, j+1)];\n match sum {\n 0 | 1 | 3 | 4 => {\n println!(\"YES\");\n return;\n },\n _ => ()\n }\n }\n }\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "cebb6be8a4f3bb4e8e3d4b396c3bd558", "src_uid": "01b145e798bbdf0ca2ecc383676d79f3", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let k: usize = scan.next();\n let l: usize = scan.next();\n let c: usize = scan.next();\n let d: usize = scan.next();\n let p: usize = scan.next();\n let nl: usize = scan.next();\n let np: usize = scan.next();\n let l_person = l*k/nl;\n let c_person = c*d;\n let p_person = p/np;\n let result = l_person.min(c_person).min(p_person)/n;\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "048e9f73eee46523f2fb7aa46db8263b", "src_uid": "67410b7d36b9d2e6a97ca5c7cff317c1", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = input.vp::(8);\n let sol = (a[1] * a[2] / a[6]).min(a[3] * a[4]).min(a[5] / a[7]) / a[0];\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "512d3308ef89b877427097ac3af1202b", "src_uid": "67410b7d36b9d2e6a97ca5c7cff317c1", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_nums() -> (i32, i32, i32, i32, i32, i32, i32, i32) {\n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input)\n\t\t.expect(\"\");\n\n\tlet v = input.trim()\n\t\t\t.split_whitespace()\n\t\t\t.map(|d| i32::from_str(d).unwrap())\n\t\t\t.collect::>();\n\n\t(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7])\n}\n\nfn main() {\n\tlet (n, k, l, c, d, p, nl, np) = get_nums();\n\n\tprintln!(\"{}\", min((k*l)/nl, c*d, p/np)/n);\n\n\tfn min(x: i32, y: i32, z: i32) -> i32 {\n\t\tif x < y {\n\t\t\tif x < z {\n\t\t\t\tx\n\t\t\t} else {\n\t\t\t\tz\n\t\t\t}\n\t\t} else if y < z {\n\t\t\ty\n\t\t} else {\n\t\t\tz\n\t\t}\n\t}\t\t\t\t\t\t\t\t\t\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "26e44c7a66acbcaf1bc90e33c6202322", "src_uid": "67410b7d36b9d2e6a97ca5c7cff317c1", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nenum Protocol { HTTP, FTP }\n\nfn fix_protocol(s: &String) -> (String, Protocol) {\n let mut res: String = String::new();\n if s.chars().nth(0) == Some('f') {\n (s.chars().skip(3).collect(), Protocol::FTP)\n } else {\n (s.chars().skip(4).collect(), Protocol::HTTP)\n }\n}\n\n\n\nfn main() {\n let mut s = read_line();\n let (s_skip_proto, protocol) = fix_protocol(&s);\n let mut s_res = s_skip_proto.clone();\n let s_res_skipped: String = s_skip_proto.chars().skip(1).collect();\n\n // res = String::from(\"http://\");\n // let appendix: String = s.chars().skip(4).collect();\n // res.push_str(&appendix);\n\n // println!(\"{}\", s_skip_proto);\n\n match s_res_skipped.find(\"ru\") {\n Some(i) => {\n s_res.insert(i + 1, '.');\n if i + 4 < s_res.len() {\n // println!(\"------------- {}\", i + 5);\n s_res.insert(i + 4, '/');\n }\n },\n _ => panic!(\"no ruurururur\")\n }\n\n let mut s_res_res = match protocol {\n Protocol::HTTP => String::from(\"http://\"),\n _ => String::from(\"ftp://\") \n };\n s_res_res.push_str(&s_res);\n \n \n println!(\"{}\", s_res_res);\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "12fda1e9e2eb92cb73bc31e8a7a57f13", "src_uid": "4c999b7854a8a08960b6501a90b3bba3", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin chmin, chmax ----------\ntrait ChangeMinMax {\n fn chmin(&mut self, x: Self) -> bool;\n fn chmax(&mut self, x: Self) -> bool;\n}\n\nimpl ChangeMinMax for T {\n fn chmin(&mut self, x: Self) -> bool {\n *self > x && {\n *self = x;\n true\n }\n }\n fn chmax(&mut self, x: Self) -> bool {\n *self < x && {\n *self = x;\n true\n }\n }\n}\n// ---------- end chmin, chmax ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nuse std::cmp::*;\n\nfn run() {\n input! {\n n: usize,\n s: chars,\n }\n let s: Vec = s.into_iter().map(|c| {\n match c {\n 'V' => 0,\n 'K' => 1,\n _ => 2,\n }\n }).collect();\n let mut cnt = [0; 3];\n for k in s.iter() {\n cnt[*k] += 1;\n }\n let inf = n * (n + 1) / 2 + 1;\n // [\u672b\u5c3e\u304cV][\u4f7f\u3063\u305fV\u306e\u6570][\u4f7f\u3063\u305fK\u306e\u6570][\u4f7f\u3063\u305f\u305d\u308c\u4ee5\u5916]\n let mut dp = vec![vec![vec![vec![inf; cnt[2] + 1]; cnt[1] + 1]; cnt[0] + 1]; 2];\n dp[0][0][0][0] = 0;\n for v in 0..=cnt[0] {\n for k in 0..=cnt[1] {\n for a in 0..=cnt[2] {\n let x = dp[0][v][k][a];\n let y = dp[1][v][k][a];\n let z = [v, k, a];\n let count = |p: usize| -> usize {\n let mut val = [0; 3];\n let mut ans = 0;\n for &q in s.iter() {\n val[q] += 1;\n if q == p && val[q] > z[p] {\n break;\n }\n if val[q] > z[q] {\n ans += 1;\n }\n }\n ans\n };\n if v + 1 <= cnt[0] {\n let val = min(x, y) + count(0);\n dp[1][v + 1][k][a].chmin(val);\n }\n if k + 1 <= cnt[1] {\n let val = x + count(1);\n dp[0][v][k + 1][a].chmin(val);\n }\n if a + 1 <= cnt[2] {\n let val = min(x, y) + count(2);\n dp[0][v][k][a + 1].chmin(val);\n }\n }\n }\n }\n let (v, k, a) = (cnt[0], cnt[1], cnt[2]);\n let ans = min(dp[0][v][k][a], dp[1][v][k][a]);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "1fbbabe2301b9a6aebcf4a85fce55ebe", "src_uid": "08444f9ab1718270b5ade46852b155d7", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nconst MAX: usize = 5;\n\nfn get_row() -> (i32, i32, i32) {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n let v = input.trim()\n .split_whitespace()\n .map(|d| i32::from_str(d).unwrap())\n .collect::>();\n (v[0], v[1], v[2])\n} \n\nfn main() {\n let mut a = [[0;MAX]; MAX];\n\n for i in 0..3 {\n let (x, y, z) = get_row();\n a[i][0] = x;\n a[i][1] = y;\n a[i][2] = z;\n }\n\n let x = (a[0][2]+a[2][0] - (a[1][0]+ a[2][0] - (a[0][2]+a[1][2])))/2;\n let y = x + (a[1][0]+ a[2][0]-(a[0][1]+a[2][1]));\n let z = x + (a[1][0]+ a[2][0]-(a[0][2]+a[1][2]));\n\n a[0][0] = x;\n a[1][1] = y;\n a[2][2] = z;\n\n for i in 0..3 {\n for j in 0..3 {\n print!(\"{} \", a[i][j]);\n }\n println!();\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "477ad2a53a3a4897ae6f04baeb38145b", "src_uid": "0c42eafb73d1e30f168958a06a0f9bca", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp;\nuse std::fs::File;\nuse std::io::Read;\n\n#[allow(dead_code)]\nfn pow_speedy_with_mod(mut p: i64, mut q: i64, m: i64) -> i64 {\n p %= m;\n let mut r = p;\n let mut ret: i64 = 1;\n while q > 0 {\n ret *= if q % 2 == 1 { r } else { 1 };\n r *= r;\n r %= m;\n q /= 2;\n ret %= m;\n }\n return ret;\n}\n\n#[allow(dead_code)]\nfn comb(n: usize, k: usize, m: i64, frac: &[i64], frac_inv: &[i64]) -> i64 {\n let mut ret = 1i64;\n if n < k {\n return 0;\n }\n ret *= frac[n] * frac_inv[n - k];\n ret %= m;\n ret *= frac_inv[k];\n ret %= m;\n ret\n}\n\nfn main() {\n let inputstatus = 1;\n\n let mut buf = String::new();\n let filename = \"inputrust.txt\";\n\n if inputstatus == 0 {\n let mut f = File::open(filename).expect(\"file not found\");\n f.read_to_string(&mut buf)\n .expect(\"something went wrong reading the file\");\n } else {\n std::io::stdin().read_to_string(&mut buf).unwrap();\n }\n\n let mut iter = buf.split_whitespace();\n\n let a: i64 = iter.next().unwrap().parse().unwrap();\n let mut b: i64 = iter.next().unwrap().parse().unwrap();\n let mut ans: i64 = 0;\n for i in 0..b + 1 {\n let x = a * i;\n ans = cmp::max(ans, (x + b) * (x + 1) * (b + 1) / 2);\n b -= 1;\n }\n println!(\"{}\", ans);\n // let n = iter.next().unwrap().parse().unwrap();\n\n // println!(\"{}\", n);\n // println!(\"{:?}\", cum_num);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "e7c4716995ffd2e3f1b51cdfbe57e419", "src_uid": "9300f1c07dd36e0cf7e6cb7911df4cf2", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(t,s,x = input.i());\n if x >= t && x != t + 1 && (x - t) % s <= 1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d8e9a31167dc6ad31e6e9eae9e34685a", "src_uid": "3baf9d841ff7208c66f6de1b47b0f952", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let x: isize = scan.next();\n let y: isize = scan.next();\n let val = x.abs() + y.abs();\n let first = (0, val * y.signum());\n let second = (val * x.signum(), 0);\n let min = first.min(second);\n let max = first.max(second);\n println!(\"{} {} {} {}\", min.0, min.1, max.0, max.1);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "17faa0c616dbaecda3cd8d702b150189", "src_uid": "e2f15a9d9593eec2e19be3140a847712", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(&mut std::io::stdin(), &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get { () => (get().parse().unwrap()) }\n \n \n let f0 = b\"What are you doing at the end of the world? Are you busy? Will you save us?\";\n let f1a = b\"What are you doing while sending \\\"\";\n let f1b = b\"\\\"? Are you busy? Will you send \\\"\";\n let f1c = b\"\\\"?\";\n \n let mut w = vec![0_u64; 100001];\n \n w[0] = f0.len() as u64;\n for i in 1..w.len() {\n w[i] = w[i-1] * 2 + (f1a.len() + f1b.len() + f1c.len()) as u64;\n }\n \n let q = get!();\n let mut v = vec![];\n for _ in 0..q {\n let mut n: usize = get!();\n let mut k: u64 = get!();\n k -= 1;\n loop {\n if k > w[n] {\n v.push(b'.');\n break;\n } else if n == 0 {\n v.push(f0[k as usize]);\n break;\n } else {\n n -= 1;\n if k < f1a.len() as u64 {\n v.push(f1a[k as usize]);\n break;\n }\n k -= f1a.len() as u64;\n if k < w[n] {\n continue;\n }\n k -= w[n];\n if k < f1b.len() as u64 {\n v.push(f1b[k as usize]);\n break;\n }\n k -= f1b.len() as u64;\n if k < w[n] {\n continue;\n }\n k -= w[n];\n if k < f1c.len() as u64 {\n v.push(f1c[k as usize]);\n break;\n }\n v.push(b'.');\n break;\n }\n }\n }\n println!(\"{}\", String::from_utf8(v).unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["math", "binary search", "combinatorics"], "code_uid": "d130bd0604d7671352a0f89450b8640d", "src_uid": "da09a893a33f2bf8fd00e321e16ab149", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"failed to read input\");\n let mut input_iter = input.split_whitespace();\n let a = input_iter.next().unwrap();\n let b = input_iter.next().unwrap();\n if a == b {\n println!(\"{}\", a);\n } else {\n println!(\"1\");\n }\n}", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "65948ca4772b2b3f3939b5669e9e7c19", "src_uid": "9c5b6d8a20414d160069010b2965b896", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get!(i64));\n ($t:ty) => (get().parse::<$t>().unwrap());\n }\n \n let n = get!() + 1;\n let ans;\n if n == 1 {\n ans = 0;\n } else if n % 2 == 0 {\n ans = n / 2;\n } else {\n ans = n;\n }\n \n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "b490b76cb0aa19bd8c8783b3a5384749", "src_uid": "236177ff30dafe68295b5d33dc501828", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn is_vowel(c: char) -> bool {\n match c {\n 'a' | 'e' | 'i' | 'o'| 'u' | 'y' => {\n true\n },\n _ => false\n }\n}\n\nfn main () {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n buf.clear();\n stdin().read_line(&mut buf).unwrap();\n let s = buf.trim();\n let mut res = Vec::::new();\n let mut second_vowel = false;\n for c in s.chars() {\n if is_vowel(c) {\n if !second_vowel {\n second_vowel = true;\n res.push(c);\n }\n } else {\n res.push(c);\n second_vowel = false;\n }\n }\n println!(\"{}\", res.into_iter().collect::());\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e15c861c5f7b1f601908ddd4f6b46212", "src_uid": "63a4a5795d94f698b0912bb8d4cdf690", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{stdin, Read, StdinLock};\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::collections::{HashSet, HashMap, BinaryHeap, VecDeque};\n#[allow(unused_imports)]\nuse std::vec::Vec;\n\n#[allow(dead_code)]\nconst INF: i32 = 1000_000_000;\n#[allow(dead_code)]\nconst INFLL: i64 = 1000_000_000_000_000_000;\n#[allow(dead_code)]\nconst EPS: f64 = 1.0e-10;\n#[allow(dead_code)]\nconst MOD: i32 = 1000_000_007;\n#[allow(dead_code)]\nconst MODLL: i64 = 1000_000_007;\n\nstruct Scanner<'a> {\n cin: StdinLock<'a>,\n}\n\n#[allow(dead_code)]\nimpl<'a> Scanner<'a> {\n fn new(cin: StdinLock<'a>) -> Scanner<'a> {\n Scanner {cin: cin}\n }\n fn read1(&mut self) -> Option {\n let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect::();\n token.parse::().ok()\n }\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\nfn main() {\n let cin = stdin();\n let cin = cin.lock();\n let mut sc = Scanner::new(cin);\n\n let _n: usize = sc.read();\n let s: String = sc.read();\n let s: Vec = s.chars().collect();\n\n fn vowel(c: char) -> bool {\n return c == 'a' || c == 'i' || c == 'e' || c == 'o' || c == 'u' || c == 'y';\n }\n\n let mut ans: String = String::new();\n let mut last = '0';\n for c in s {\n if ans.len() == 0 {\n ans.push(c);\n last = c;\n } else {\n if vowel(last) && vowel(c) {\n continue;\n }\n ans.push(c);\n last = c;\n }\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e1d29111216fe443cdfa8dc71f1ae86d", "src_uid": "63a4a5795d94f698b0912bb8d4cdf690", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main(){\n let mut s:String=String::new();\n stdin().read_line(&mut s).unwrap();\n s.clear();\n stdin().read_line(&mut s).unwrap();\n s.trim();\n let b=\"aeyuio\";\n let mut c:usize=1;\n let mut p:i32=0;\n let mut l:i32=0;\n while cp=1,\n 'e'=>p=1,\n 'y'=>p=1,\n 'u'=>p=1,\n 'i'=>p=1,\n 'o'=>p=1,\n _=>p=0,\n }\n match s.chars().nth(c-1).unwrap(){\n 'a'=>l=1,\n 'e'=>l=1,\n 'y'=>l=1,\n 'u'=>l=1,\n 'i'=>l=1,\n 'o'=>l=1,\n _=>l=2,\n }\n if p==l{\n s.remove(c);\n }\n else{c+=1;}\n }\n println!(\"{}\",s);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6d207f90e4aeca6806d1004610db2bb8", "src_uid": "63a4a5795d94f698b0912bb8d4cdf690", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let mut text = String::new();\n stdin().read_line(&mut text).unwrap();\n let text = text.trim();\n let mut counter4: usize = 0;\n let mut counter7: usize = 0;\n for i in text.chars() {\n if '4' == i {\n counter4 += 1;\n } else if '7' == i {\n counter7 += 1;\n }\n }\n if counter4 == 0 && counter7 == 0 {\n println!(\"-1\");\n } else if counter4 >= counter7 {\n println!(\"4\")\n } else {\n println!(\"7\")\n }\n}\n\nfn delete_leading_zeroes(arr: Vec) -> Vec {\n let mut finded = false;\n let mut last = 0;\n for i in 0..arr.len() {\n if '0' == arr[i] {\n continue;\n } else {\n last = i;\n finded = true;\n break;\n }\n }\n if finded {\n arr[last..].to_vec()\n } else {\n arr\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "7eddbb1afcdf72165f48377d5f909ab9", "src_uid": "639b8b8d0dc42df46b139f0aeb3a7a0a", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::io::{stderr, stdin, stdout, BufWriter, StdoutLock, Write};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::{i64, u64, usize};\n#[allow(unused_macros)]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; ( $ next : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }\n#[allow(unused_macros)]\nmacro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , [ $ t : tt ] ) => { { let len = read_value ! ( $ next , usize ) ; ( 0 .. len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , bytes ) => { read_value ! ( $ next , String ) . into_bytes ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\n#[allow(dead_code)]\nstruct Writer {\n s: String,\n}\n#[allow(unused_imports)]\nuse std::fmt::Display;\n#[allow(dead_code)]\n#[doc = \" let mut writer = Writer::new();\"]\n#[doc = \" writer.writeln(hoge);\"]\n#[doc = \" writer.flush()\"]\nimpl Writer {\n #[allow(dead_code)]\n pub fn new() -> Writer {\n Writer { s: String::new() }\n }\n #[allow(dead_code)]\n pub fn flush(&mut self) {\n print!(\"{}\", self.s);\n self.s.clear();\n }\n pub fn write(&mut self, x: T) {\n self.s.push_str(&format!(\"{}\", x));\n }\n pub fn writeln(&mut self, x: T) {\n self.s.push_str(&format!(\"{}\", x));\n self.s.push('\\n');\n }\n #[allow(dead_code)]\n pub fn write_vec(&mut self, xs: &Vec) {\n if xs.len() == 0 {\n self.writeln(\"\");\n return;\n }\n self.write(&format!(\"{}\", xs[0]));\n for i in 1..xs.len() {\n self.write(&format!(\" {}\", xs[i]));\n }\n self.writeln(\"\");\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! dbg { ( $ ( $ a : expr ) ,* ) => { writeln ! ( & mut stderr ( ) , concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) . unwrap ( ) ; } }\n#[allow(dead_code)]\nconst INF_U: u64 = 1_000_000_000_000_000;\n#[allow(dead_code)]\nconst INF_I: i64 = 1_000_000_000_000_000;\n#[allow(non_snake_case)]\n#[allow(dead_code)]\nfn main() {\n input! {\n n: usize,\n a: [usize; n]\n }\n let mut ans = 0;\n let mut flag = false;\n for i in 1..n {\n dbg!(ans);\n if a[i-1] == 1 {\n if a[i] == 2 {\n if flag { ans += 2; }\n else { ans += 3; }\n } else {\n ans += 4;\n }\n } else if a[i-1] == 2 {\n if a[i] == 1 {\n ans += 3;\n } else {\n println!(\"Infinite\");\n return;\n }\n } else {\n if a[i] == 1 {\n ans += 4;\n flag = true;\n continue;\n } else {\n println!(\"Infinite\");\n return;\n }\n }\n flag = false;\n }\n println!(\"Finite\");\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["geometry"], "code_uid": "a3aec27524887f2b191a507c2a4efc7c", "src_uid": "6c8f028f655cc77b05ed89a668273702", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\n#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[macro_export]\nmacro_rules ! chmax { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: max ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! chmin { ( $ x : expr , $ ( $ v : expr ) ,+ ) => { $ ( $ x = std :: cmp :: min ( $ x ,$ v ) ; ) + } ; }\n#[macro_export]\nmacro_rules ! max { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: max ( $ x , max ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! min { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { std :: cmp :: min ( $ x , min ! ( $ ( $ xs ) ,+ ) ) } ; }\n#[macro_export]\nmacro_rules ! dvec { ( $ t : expr ; $ len : expr ) => { vec ! [ $ t ; $ len ] } ; ( $ t : expr ; $ len : expr , $ ( $ rest : expr ) ,* ) => { vec ! [ dvec ! ( $ t ; $ ( $ rest ) ,* ) ; $ len ] } ; }\n#[doc = \" main\"]\n#[allow(unused_imports)]\nuse std::io::{stdin, stdout, BufWriter, Write};\n#[macro_export]\nmacro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }\n#[macro_export]\nmacro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( \"Parse error\" ) } ; }\nuse std::io;\nuse std::io::BufRead;\nuse std::str;\npub struct Parser {\n reader: R,\n buf: Vec,\n pos: usize,\n}\nimpl Parser {\n pub fn from_str(s: &str) -> Parser {\n Parser {\n reader: io::empty(),\n buf: s.as_bytes().to_vec(),\n pos: 0,\n }\n }\n}\nimpl Parser {\n pub fn new(reader: R) -> Parser {\n Parser {\n reader: reader,\n buf: vec![],\n pos: 0,\n }\n }\n pub fn update_buf(&mut self) {\n self.buf.clear();\n self.pos = 0;\n loop {\n let (len, complete) = {\n let buf2 = self.reader.fill_buf().unwrap();\n self.buf.extend_from_slice(buf2);\n let len = buf2.len();\n if len == 0 {\n break;\n }\n (len, buf2[len - 1] <= 0x20)\n };\n self.reader.consume(len);\n if complete {\n break;\n }\n }\n }\n pub fn next(&mut self) -> Result {\n loop {\n let mut begin = self.pos;\n while begin < self.buf.len() && (self.buf[begin] <= 0x20) {\n begin += 1;\n }\n let mut end = begin;\n while end < self.buf.len() && (self.buf[end] > 0x20) {\n end += 1;\n }\n if begin != self.buf.len() {\n self.pos = end;\n return str::from_utf8(&self.buf[begin..end]).unwrap().parse::();\n } else {\n self.update_buf();\n }\n }\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n#[doc = \" https://github.com/hatoo/competitive-rust-snippets\"]\nconst BIG_STACK_SIZE: bool = true;\n#[allow(dead_code)]\nfn main() {\n use std::thread;\n if BIG_STACK_SIZE {\n thread::Builder::new()\n .stack_size(32 * 1024 * 1024)\n .name(\"solve\".into())\n .spawn(solve)\n .unwrap()\n .join()\n .unwrap();\n } else {\n solve();\n }\n}\nfn solve() {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n input!{\n n:usize,\n a:[usize;n]\n }\n let mut tot = 0;\n for i in 1..n {\n let x = i-1;\n let y = i;\n match (a[x],a[y]) {\n (1,2) | (2,1) => {\n if tot != -1 {\n tot += 3\n }\n },\n (2,3) | (3,2) => {\n tot = -1\n },\n (1,3) | (3,1) => {\n if tot != -1 {\n tot += 4\n }\n },\n _ => {\n\n }\n }\n }\n if tot == -1 {\n writeln!(out,\"Infinite\");\n return\n }\n for i in 2..n {\n match (a[i-2],a[i-1],a[i]) {\n (3,1,2) => {\n tot -= 1;\n },\n _ => {}\n }\n }\n writeln!(out,\"Finite\");\n writeln!(out,\"{}\",tot);\n}", "lang_cluster": "Rust", "tags": ["geometry"], "code_uid": "6f54b1989e6711c7a7bf2eaa4d749ccb", "src_uid": "6c8f028f655cc77b05ed89a668273702", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1156/problem/A\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::io::Write;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n// Input macros.\n// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_line {\n ($t:tt) => {\n {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim_right().parse::<$t>().unwrap()\n }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\n// ===\n\nfn main() {\n input! {\n n: usize,\n a: [usize1; n]\n };\n\n let INF = 1000000000i64;\n let table = vec![\n vec![-INF, 3, 4],\n vec![3, -INF, -INF],\n vec![4, -INF, -INF],\n ];\n\n let mut points = 0i64;\n for i in 1..n {\n points += table[a[i-1]][a[i]];\n if i >= 2 && a[i-2] == 2 && a[i-1] == 0 && a[i] == 1 {\n points -= 1;\n }\n }\n if points <= -1 {\n println!(\"Infinite\");\n } else {\n println!(\"Finite\");\n println!(\"{}\", points);\n }\n}\n", "lang_cluster": "Rust", "tags": ["geometry"], "code_uid": "2f632863f12d7f7899204202f7134032", "src_uid": "6c8f028f655cc77b05ed89a668273702", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\ntype I = usize;\n\nfn main() {\n input!{\n n: usize,\n aa: [usize; n],\n }\n\n let mut ans: u64 = 0;\n for i in 1..n {\n let a1 = aa[i-1];\n let a2 = aa[i];\n let mut a = [a1, a2];\n a.sort();\n\n if a[0] != 1 {\n return println!(\"{}\", \"Infinite\");\n }\n\n if a[1] == 2 {\n if a2 == 2 && i>=2 && aa[i-2] == 3 {\n ans += 2;\n } else {\n ans += 3;\n }\n } else {\n ans += 4;\n }\n }\n println!(\"{}\", \"Finite\");\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["geometry"], "code_uid": "31ca5cde48c1d125bda997f85ebf645d", "src_uid": "6c8f028f655cc77b05ed89a668273702", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n\n ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\ntype I = usize;\n\nfn main() {\n input!{\n n: usize,\n aa: [usize; n],\n }\n\n let mut ans: u64 = 0;\n for i in 1..n {\n let a1 = aa[i-1];\n let a2 = aa[i];\n let mut a = [a1, a2];\n a.sort();\n\n if a[0] != 1 {\n return println!(\"{}\", \"Infinite\");\n }\n\n if a[1] == 2 {\n if a2 == 2 && i>=2 && aa[i-2] == 3 {\n ans += 2;\n } else {\n ans += 3;\n }\n } else {\n ans += 4;\n }\n }\n println!(\"{}\", \"Finite\");\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["geometry"], "code_uid": "d429845bfcbe45e4cb439b7ca7e2b7a7", "src_uid": "6c8f028f655cc77b05ed89a668273702", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports, unused_macros)]\n\nuse std::fmt::Debug;\nuse std::str::FromStr;\n\nfn read_stdin() -> String {\n let mut s = String::new();\n std::io::stdin()\n .read_line(&mut s)\n .expect(\"cannot read stdin\");\n s.trim().to_string()\n}\n\nfn read() -> T\nwhere\n T: FromStr,\n ::Err: Debug,\n{\n read_stdin().parse::().unwrap()\n}\n\nfn read_usize() -> usize {\n read::()\n}\n\nfn read_2() -> (A, B)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n (a, b)\n}\n\nfn read_3() -> (A, B, C)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n (a, b, c)\n}\n\nfn read_4() -> (A, B, C, D)\nwhere\n A: FromStr,\n ::Err: Debug,\n B: FromStr,\n ::Err: Debug,\n C: FromStr,\n ::Err: Debug,\n D: FromStr,\n ::Err: Debug,\n{\n let s = read_stdin();\n let mut s = s.split_whitespace();\n let a = s.next().unwrap().parse::().unwrap();\n let b = s.next().unwrap().parse::().unwrap();\n let c = s.next().unwrap().parse::().unwrap();\n let d = s.next().unwrap().parse::().unwrap();\n (a, b, c, d)\n}\n\nfn read_multiple() -> Vec\nwhere\n ::Err: Debug,\n{\n read_stdin()\n .split_whitespace()\n .map(|x| x.parse::().expect(\"cannot parse stdin\"))\n .collect()\n}\n\n/// NOTE: sort iter beforehand if required\nfn count(iter: &mut impl Iterator) -> Vec<(T, usize)>\nwhere\n T: std::cmp::Ord,\n{\n let iter = iter.collect::>();\n //iter.sort();\n let (mut v, o, c) =\n iter.into_iter()\n .fold((Vec::new(), None, 0), |(mut v, last, count), item| {\n if let Some(o) = last {\n if item == o {\n (v, Some(o), count + 1)\n } else {\n v.push((o, count));\n (v, Some(item), 1)\n }\n } else {\n (v, Some(item), 1)\n }\n });\n if let Some(i) = o {\n v.push((i, c));\n }\n v\n}\n\nfn partial_sum(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + std::ops::Add + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = *state + x;\n Some(*state)\n })\n}\n\nfn partial_max(v: impl Iterator) -> impl Iterator\nwhere\n T: Default + Ord + Copy,\n{\n v.scan(T::default(), |state, x| {\n *state = max(*state, x);\n Some(*state)\n })\n}\n\nfn partial_min(v: impl Iterator) -> impl Iterator {\n v.scan(std::u64::MAX, |state, x| {\n *state = min(*state, x);\n Some(*state)\n })\n}\n\nfn max_subarray(v: impl Iterator) -> (i64, (usize, usize)) {\n //assert!(v.len() > 0);\n let mut best_sum = 0;\n let (mut best_start, mut best_end) = (0, 0);\n let mut current_sum = 0;\n let mut current_start = 0;\n for (end, val) in v.enumerate() {\n if current_sum <= 0 {\n current_start = end;\n current_sum = val;\n } else {\n current_sum += val;\n }\n if current_sum > best_sum {\n best_sum = current_sum;\n best_start = current_start;\n best_end = end + 1;\n }\n }\n (best_sum, (best_start, best_end))\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n while a != 0 {\n let old_m = a;\n a = b % a;\n b = old_m;\n }\n b\n}\n\n/// returns gcd, and pair (x, y), such that x * a + b * y == gcd\nfn egcd(a: i64, b: i64) -> (i64, i64, i64) {\n if a == 0 {\n (b, 0, 1)\n } else {\n let (g, x, y) = egcd(b % a, a);\n (g, y - (b / a) * x, x)\n }\n}\n\nfn factorize(mut n: u64) -> Vec {\n if n <= 3 {\n return vec![n];\n }\n let mut v = Vec::new();\n while n % 2 == 0 {\n n /= 2;\n v.push(2);\n }\n while n % 3 == 0 {\n n /= 3;\n v.push(3);\n }\n let mut f = 6;\n while (f - 1) * (f - 1) <= n {\n while n % (f - 1) == 0 {\n n /= f - 1;\n v.push(f - 1);\n }\n while n % (f + 1) == 0 {\n n /= f + 1;\n v.push(f + 1);\n }\n f += 6;\n }\n if n > 1 {\n v.push(n);\n }\n v\n}\n\nfn compact_factors(n: u64) -> Vec<(u64, usize)> {\n count(&mut factorize(n).into_iter())\n}\n\nfn all_factors(n: u64) -> Vec {\n if n == 0 {\n return vec![0];\n } else if n == 1 {\n return vec![1];\n }\n let factors = compact_factors(n);\n let mut v = vec![1];\n for (fac, num) in factors {\n let ori = v.clone();\n for i in 1..num + 1 {\n v.append(\n &mut ori\n .clone()\n .into_iter()\n .map(|f| f * fac.pow(i as u32))\n .collect::>(),\n )\n }\n }\n v.sort();\n v\n}\n\nfn abs_diff(a: T, b: T) -> T\nwhere\n T: PartialOrd + std::ops::Sub,\n{\n if a > b {\n a - b\n } else {\n b - a\n }\n}\n\nstruct Permutations {\n inner: Vec,\n state: Vec,\n i: usize,\n start: bool,\n}\n\nimpl Permutations {\n fn new(inner: Vec) -> Self {\n Self {\n state: vec![0; inner.len()],\n i: 0,\n start: true,\n inner,\n }\n }\n}\n\n/*impl From for Permutations\nwhere\n X: IntoIterator,\n{\n fn from(f: X) -> Self {\n Self::new(f.into_iter().collect::>())\n }\n}*/\n\nimpl Iterator for Permutations\nwhere\n T: Clone,\n{\n type Item = Vec;\n fn next(&mut self) -> Option {\n if self.start {\n self.start = false;\n return Some(self.inner.clone());\n }\n while self.i < self.inner.len() {\n if self.state[self.i] < self.i {\n if self.i % 2 == 0 {\n self.inner.swap(0, self.i)\n } else {\n self.inner.swap(self.state[self.i], self.i)\n }\n self.state[self.i] += 1;\n self.i = 0;\n return Some(self.inner.clone());\n } else {\n self.state[self.i] = 0;\n self.i += 1;\n }\n }\n None\n }\n}\n\nuse std::cmp::{max, min, Ord, Ordering};\nuse std::collections::{BinaryHeap, VecDeque};\nuse std::mem::swap;\n\nmacro_rules! max_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nmacro_rules! min_with {\n ($x: expr, $y: expr) => {\n $x = max($x, $y)\n };\n}\n\nfn is_prime(n: u64) -> bool {\n factorize(n).len() == 1\n}\n\nfn combination(n: u64, k: u64, m: u64) -> u64 {\n if n == 0 {\n return 1;\n }\n if k == 0 || k == n {\n return 1;\n }\n let new_k = if n - k < k { n - k } else { k };\n let mut res = 1;\n for i in ((n - new_k) + 1)..=n {\n res *= i;\n res %= m;\n }\n let mut den = 1;\n for i in 1..=(new_k) {\n den *= i;\n den %= m;\n }\n let (_one, inverse, _c) = egcd(den as i64, m as i64);\n let inverse = if inverse < 0 {\n m as i64 + inverse\n } else {\n inverse\n } as u64;\n //println!(\"inv: {} {}\", den, inverse);\n res *= inverse;\n res %= m;\n res\n}\n\nuse std::collections::HashSet;\nuse std::iter::FromIterator;\n\nfn main() -> Result<(), Box> {\n let _n = read_usize();\n let v = read_multiple::();\n let mut points = 0;\n let mut prev2 = 0;\n let mut prev = v[0];\n for a in v.into_iter().skip(1) {\n if prev == 1 {\n if a == 2 {\n points += 3\n } else {\n points += 4;\n }\n } else if prev == 2 {\n if a == 1 {\n points += 3\n } else {\n println!(\"Infinite\");\n return Ok(());\n }\n } else {\n //prv == 3\n if a == 1 {\n points += 4\n } else {\n println!(\"Infinite\");\n return Ok(());\n }\n }\n if prev2 == 3 && prev == 1 && a == 2 {\n points -= 1;\n }\n prev2 = prev;\n prev = a;\n }\n println!(\"Finite\");\n println!(\"{}\", points);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["geometry"], "code_uid": "112d20febd980de5936e90fd1d942740", "src_uid": "6c8f028f655cc77b05ed89a668273702", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut numbers = a_str.split_whitespace()\n .map(|x| x.parse::().expect(\"parse error\"))\n .collect::>();\n let n = numbers[0];\n let pos = numbers[1];\n let l = numbers[2];\n let r = numbers[3];\n\n let mut res = 0;\n\n if l != 1 && r == n {\n res += (pos - l).abs() + 1;\n } else if r != n && l == 1 {\n res += (r - pos).abs() + 1;\n } else if r == n && l == 1{\n res = 0;\n } else {\n if (pos - l).abs() < (r - pos).abs() {\n if l != r {\n res += r - l + (pos - l).abs() + 2;\n } else {\n res += (pos - l).abs() + 2;\n }\n } else {\n if l != r {\n res += r - l + (r - pos).abs() + 2;\n } else {\n res += (r - pos).abs() + 2;\n }\n }\n }\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c30c1d892bc8337f5ba453c56c1802ac", "src_uid": "5deaac7bd3afedee9b10e61997940f78", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n#[allow(unused_macros)]\nmacro_rules ! get { ( $ t : ty ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,* ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; let mut iter = line . split_whitespace ( ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; ( $ t : ty ; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ ( $ t : ty ) ,*; $ n : expr ) => { ( 0 ..$ n ) . map ( | _ | get ! ( $ ( $ t ) ,* ) ) . collect ::< Vec < _ >> ( ) } ; ( $ t : ty ;; ) => { { let mut line : String = String :: new ( ) ; stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; line . split_whitespace ( ) . map ( | t | t . parse ::<$ t > ( ) . unwrap ( ) ) . collect ::< Vec < _ >> ( ) } } ; }\n#[allow(unused_macros)]\nmacro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { println ! ( concat ! ( $ ( stringify ! ( $ a ) , \" = {:?}, \" ) ,* ) , $ ( $ a ) ,* ) ; } }\n\nfn main() {\n let (n, pos, l, r) = get!(isize, isize, isize, isize);\n\n if l == 1 && r == n {\n println!(\"{}\", 0);\n return;\n }\n\n if l == 1 {\n println!(\"{}\", (r - pos).abs() + 1);\n return;\n }\n\n if r == n {\n println!(\"{}\", (l - pos).abs() + 1);\n return;\n }\n\n let ans1 = (l - pos).abs() + 1 + (r - l).abs() + 1;\n let ans2 = (r - pos).abs() + 1 + (r - l).abs() + 1;\n\n println!(\"{}\", min(ans1, ans2));\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "76f8c7a2ff280dd10b1222ac079e7006", "src_uid": "5deaac7bd3afedee9b10e61997940f78", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::min;\n\nfn main() {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let nposlr = input.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n let (n, pos, l, r) = (nposlr[0], nposlr[1], nposlr[2], nposlr[3]);\n\n if l == 1 && r == n {\n println!(\"0\");\n } else if l == 1 {\n println!(\"{}\", (pos - r).abs() + 1);\n } else if r == n {\n println!(\"{}\", (pos - l).abs() + 1);\n } else {\n let min_dist = min((pos - l).abs(), (pos - r).abs());\n println!(\"{}\", min_dist + (r - l).abs() + 2);\n }\n\n\n\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d6e18e2b57e3db43493d96270154f5f5", "src_uid": "5deaac7bd3afedee9b10e61997940f78", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_num() -> usize {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n usize::from_str(input.trim()).unwrap()\n}\n\nfn get_string() -> String {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n input.trim().to_string()\n}\n\nfn main() {\n let n = get_num();\n\n let mut v = vec![0; 10];\n for _ in 0..4 {\n let s = get_string();\n\n for c in s.chars() {\n if c == '.' {\n continue;\n }\n v[c.to_digit(10).unwrap() as usize] += 1;\n }\n }\n\n let mx = v.iter().max().unwrap();\n\n if *mx > 2 * n {\n println!(\"NO\");\n } else {\n println!(\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "46de722632abb62175c440ab97962926", "src_uid": "5fdaf8ee7763cb5815f49c0c38398f16", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read()->Vec{\n let mut line=String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace().map(|x|x.parse::().unwrap()).collect()\n}\nuse std::i32;\nfn main(){\n let vec=read();\n let stairs=i32::abs(vec[0]-vec[1])*vec[3];\n let lift=i32::abs(vec[0]-vec[1])*vec[4]+3*vec[5]+i32::abs(vec[0]-vec[2])*vec[4];\n if lift<=stairs{\n println!(\"YES\");\n }\n else{\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "fd89def58f4925bb3b6843dd9568a5da", "src_uid": "05cffd59b28b9e026ca3203718b2e6ca", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let mut s = s.split_whitespace();\n let x: i32 = s.next().unwrap().parse().unwrap();\n let y: i32 = s.next().unwrap().parse().unwrap();\n let z: i32 = s.next().unwrap().parse().unwrap();\n let t1: i32 = s.next().unwrap().parse().unwrap();\n let t2: i32 = s.next().unwrap().parse().unwrap();\n let t3: i32 = s.next().unwrap().parse().unwrap();\n if (x - y).abs() * t1 < ((x - z).abs() + (x - y).abs()) * t2 + 3 * t3 {\n println!(\"NO\");\n } else {\n println!(\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "39323a465f25a210c729adc6730e1557", "src_uid": "05cffd59b28b9e026ca3203718b2e6ca", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_variables)]\n#![allow(unused_must_use)]\nuse std::io::{self, prelude::*};\n\nfn solve(mut input: FastInput, mut w: W) {\n let n = input.token();\n let k: usize = input.token();\n let mut c = vec![0usize; n];\n for x in c.iter_mut() {\n *x = input.token();\n }\n let a = c.iter().filter(|&&x| x == 0).count();\n\n let first_0 = |a, n, x| x;\n let first_1 = |a, n, x| a - x;\n let second_0 = |a, n, x| a - x;\n let second_1 = |a, n, x| n - a - second_0(a, n, x);\n let increase = |a, n, x| {\n let res = first_1(a, n, x) * second_0(a, n, x);\n (res + res) / n / (n - MOD7::identity())\n };\n let decrease = |a, n, x| {\n let res = first_0(a, n, x) * second_1(a, n, x);\n (res + res) / n / (n - MOD7::identity())\n };\n let same = |a, n, x| {\n let res = a * (a - MOD7::identity())\n + (n - a) * (n - a - MOD7::identity())\n + first_0(a, n, x) * second_0(a, n, x)\n + first_0(a, n, x) * second_0(a, n, x)\n + first_1(a, n, x) * second_1(a, n, x)\n + first_1(a, n, x) * second_1(a, n, x);\n res / n / (n - MOD7::identity())\n };\n\n let into = |x| MOD7::from(x as u32);\n let inc = |x| increase(into(a), into(n), into(x));\n let dec = |x| same(into(a), into(n), into(x));\n let eq = |x| decrease(into(a), into(n), into(x));\n\n let mut init: Matrix = Matrix::new(1, a + 1);\n *init.elem_mut(0, a - c[..a].iter().sum::()) = MOD7::identity();\n\n let mut transition: Matrix = Matrix::new(a + 1, a + 1);\n *transition.elem_mut(0, 0) = dec(0);\n if a > 0 {\n *transition.elem_mut(1, 0) = eq(1);\n *transition.elem_mut(a - 1, a) = inc(a - 1);\n *transition.elem_mut(a, a) = dec(a);\n }\n for i in 1..a {\n *transition.elem_mut(i - 1, i) = inc(i - 1);\n *transition.elem_mut(i, i) = dec(i);\n *transition.elem_mut(i + 1, i) = eq(i + 1);\n }\n let ans = init * binary_power(&transition, k as u64);\n let ans = ans.elem(0, a);\n write!(w, \"{}\\n\", ans);\n}\n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let input = FastInput::from(stdin.lock());\n let writer = io::BufWriter::new(stdout.lock());\n solve(input, writer);\n}\n\ntrait TokenStream {\n fn token(&mut self) -> T;\n}\n\nstruct FastInput {\n stdin: R,\n pos: usize,\n}\n\nimpl From for FastInput {\n fn from(r: R) -> Self {\n FastInput { stdin: r, pos: 0 }\n }\n}\n\nimpl TokenStream for FastInput {\n fn token(&mut self) -> u8 {\n loop {\n if let Ok(buf) = self.stdin.fill_buf() {\n while self.pos < buf.len() {\n self.pos += 1;\n if buf[self.pos - 1] > 32 {\n return buf[self.pos - 1];\n }\n }\n if self.pos == 0 {\n return 0;\n }\n } else {\n return 0;\n }\n self.stdin.consume(self.pos);\n self.pos = 0;\n }\n }\n}\n\nimpl TokenStream> for FastInput {\n fn token(&mut self) -> Vec {\n let mut ans = Vec::new();\n let mut parse_token = false;\n loop {\n if let Ok(buf) = self.stdin.fill_buf() {\n if !parse_token {\n while self.pos < buf.len() && buf[self.pos] <= 32 {\n self.pos += 1;\n }\n }\n while self.pos < buf.len() && buf[self.pos] > 32 {\n parse_token = true;\n ans.push(buf[self.pos]);\n self.pos += 1;\n }\n if self.pos != buf.len() || self.pos == 0 {\n return ans;\n }\n }\n self.stdin.consume(self.pos);\n self.pos = 0;\n }\n }\n}\n\nmacro_rules! impl_token_stream_u {\n ($($t:ident),+) => {$(\n impl TokenStream<$t> for FastInput {\n fn token(&mut self) -> $t {\n let mut ans = 0;\n let mut parse_token = false;\n loop {\n if let Ok(buf) = self.stdin.fill_buf() {\n if !parse_token {\n while self.pos < buf.len() && buf[self.pos] <= 32 {\n self.pos += 1;\n }\n }\n while self.pos < buf.len() && buf[self.pos] > 32 {\n parse_token = true;\n ans = ans * 10 + (buf[self.pos] - b'0') as $t;\n self.pos += 1;\n }\n if self.pos != buf.len() || self.pos == 0 {\n return ans;\n }\n }\n self.stdin.consume(self.pos);\n self.pos = 0;\n }\n }\n }\n )+}\n}\n\npub trait Identity {\n fn identity() -> Self;\n}\n\npub trait SelfIdentity {\n fn self_identity(&self) -> Self;\n}\n\nimpl SelfIdentity for T {\n fn self_identity(&self) -> Self {\n Self::identity()\n }\n}\n\npub trait Inverse {\n fn inverse(self) -> Self;\n}\n\nmacro_rules! define_modular_type {\n ($mod:ident, $value:expr) => {\n #[derive(Copy, Clone, Default, PartialEq)]\n struct $mod(u32);\n\n impl $mod {\n const MOD: u64 = $value;\n }\n\n impl std::fmt::Debug for $mod {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"{:?}\", self.0)\n }\n }\n\n impl std::fmt::Display for $mod {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n\n impl> From for $mod {\n fn from(a: T) -> Self {\n $mod((a.into() % Self::MOD) as u32)\n }\n }\n\n impl Into for $mod {\n fn into(self) -> u32 {\n self.0\n }\n }\n\n impl Identity for $mod {\n fn identity() -> Self {\n 1u32.into()\n }\n }\n\n impl Inverse for $mod {\n fn inverse(self) -> Self {\n let mut t = (Self::default(), Self::identity());\n let mut r = (Self::MOD, self.0 as u64);\n while r.1 != 0 {\n let q = r.0 / r.1;\n t = (t.1, t.0 - t.1 * q.into());\n r = (r.1, r.0 - r.1 * q);\n }\n t.0\n }\n }\n\n impl std::ops::Add for $mod {\n type Output = $mod;\n fn add(self, rhs: $mod) -> Self::Output {\n let mut ret = self.0 + rhs.0;\n if ret >= Self::MOD as u32 {\n ret -= Self::MOD as u32;\n }\n $mod(ret)\n }\n }\n\n impl std::ops::AddAssign for $mod {\n fn add_assign(&mut self, rhs: Self) {\n self.0 += rhs.0;\n if self.0 >= Self::MOD as u32 {\n self.0 -= Self::MOD as u32;\n }\n }\n }\n\n impl std::ops::Neg for $mod {\n type Output = Self;\n fn neg(self) -> Self::Output {\n $mod(Self::MOD as u32 - self.0)\n }\n }\n\n impl std::ops::Sub for $mod {\n type Output = $mod;\n fn sub(self, rhs: Self) -> Self::Output {\n if self.0 < rhs.0 {\n $mod(self.0 + (Self::MOD as u32) - rhs.0)\n } else {\n $mod(self.0 - rhs.0)\n }\n }\n }\n\n impl std::ops::SubAssign for $mod {\n fn sub_assign(&mut self, rhs: Self) {\n if self.0 < rhs.0 {\n self.0 += Self::MOD as u32;\n }\n self.0 -= rhs.0\n }\n }\n\n impl std::ops::Mul for $mod {\n type Output = $mod;\n fn mul(self, rhs: Self) -> Self::Output {\n let a = self.0 as u64;\n let b = rhs.0 as u64;\n let c = a * b % Self::MOD;\n $mod(c as u32)\n }\n }\n\n impl std::ops::MulAssign for $mod {\n fn mul_assign(&mut self, rhs: Self) {\n *self = *self * rhs;\n }\n }\n\n impl std::ops::Div for $mod {\n type Output = Self;\n fn div(self, rhs: Self) -> Self::Output {\n self * rhs.inverse()\n }\n }\n\n impl std::ops::DivAssign for $mod {\n fn div_assign(&mut self, rhs: Self) {\n *self = *self / rhs;\n }\n }\n };\n}\n\nfn gcd(mut a: T, mut b: T) -> T\nwhere\n T: Copy + std::cmp::PartialEq + std::default::Default + std::ops::Rem,\n{\n while b != T::default() {\n let r = a % b;\n a = b;\n b = r;\n }\n a\n}\n\n#[derive(Clone)]\npub struct Matrix {\n data: Vec,\n cols: usize,\n rows: usize,\n}\n\nimpl Matrix\nwhere\n T: std::default::Default + Clone,\n{\n pub fn new(rows: usize, cols: usize) -> Matrix {\n let data = vec![T::default(); cols * rows];\n Matrix {\n data: data,\n cols: cols,\n rows: rows,\n }\n }\n}\n\nimpl Matrix {\n pub fn rows(&self) -> std::slice::Chunks {\n self.data.chunks(self.cols)\n }\n pub fn rows_mut(&mut self) -> std::slice::ChunksMut {\n self.data.chunks_mut(self.cols)\n }\n pub fn elem(&self, row: usize, col: usize) -> &T {\n &self.data[self.cols * row + col]\n }\n pub fn elem_mut(&mut self, row: usize, col: usize) -> &mut T {\n &mut self.data[self.cols * row + col]\n }\n}\n\nimpl std::fmt::Debug for Matrix\nwhere\n T: std::fmt::Debug,\n{\n fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {\n self.rows()\n .try_for_each(|row| fmt.write_fmt(format_args!(\"{:?}\\n\", row)))\n }\n}\n\nimpl SelfIdentity for Matrix\nwhere\n T: Identity + std::default::Default + Clone,\n{\n fn self_identity(&self) -> Self {\n assert_eq!(self.cols, self.rows);\n let mut ret = Matrix::new(self.rows, self.cols);\n for (i, row) in ret.rows_mut().enumerate() {\n row[i] = T::identity();\n }\n ret\n }\n}\n\nimpl std::ops::Add for Matrix\nwhere\n T: Clone + std::default::Default + std::ops::Add,\n{\n type Output = Matrix;\n fn add(self, rhs: Matrix) -> Matrix {\n assert_eq!(self.cols, rhs.cols);\n assert_eq!(self.rows, rhs.rows);\n Matrix {\n data: self\n .data\n .iter()\n .zip(rhs.data)\n .map(|(a, b)| a.clone() + b.clone())\n .collect(),\n rows: self.rows,\n cols: self.cols,\n }\n }\n}\nimpl std::ops::Sub for Matrix\nwhere\n T: Clone + std::default::Default + std::ops::Sub,\n{\n type Output = Matrix;\n fn sub(self, rhs: Matrix) -> Matrix {\n assert_eq!(self.cols, rhs.cols);\n assert_eq!(self.rows, rhs.rows);\n Matrix {\n data: self\n .data\n .iter()\n .zip(rhs.data)\n .map(|(a, b)| a.clone() - b.clone())\n .collect(),\n rows: self.rows,\n cols: self.cols,\n }\n }\n}\nimpl std::ops::Mul for Matrix\nwhere\n T: Clone + std::default::Default + std::ops::AddAssign + std::ops::Mul,\n{\n type Output = Matrix;\n fn mul(self, rhs: Matrix) -> Matrix {\n assert_eq!(self.cols, rhs.rows);\n let mut ret: Matrix = Matrix::new(self.rows, rhs.cols);\n for (ret_row, self_row) in ret.rows_mut().zip(self.rows()) {\n for (rhs_row, self_el) in rhs.rows().zip(self_row) {\n for (ret_el, rhs_el) in ret_row.iter_mut().zip(rhs_row) {\n *ret_el += self_el.clone() * rhs_el.clone();\n }\n }\n }\n ret\n }\n}\n\nfn binary_power(a: &T, mut exp: u64) -> T\nwhere\n T: Clone + std::ops::Mul + SelfIdentity,\n{\n let mut base = a.clone();\n let mut acc = a.self_identity();\n while exp > 1 {\n if (exp & 1) == 1 {\n acc = acc * base.clone();\n }\n exp /= 2;\n base = base.clone() * base.clone();\n }\n if exp == 1 {\n acc = acc * base;\n }\n acc\n}\n\nimpl_token_stream_u!(usize);\ndefine_modular_type!(MOD7, 1_000_000_007);\n", "lang_cluster": "Rust", "tags": ["probabilities", "matrices", "dp", "combinatorics"], "code_uid": "5f1c0d131c0ffb54dfa8277ae8fe5b0c", "src_uid": "77f28d155a632ceaabd9f5a9d846461a", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/* This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. */\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\n\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scanner = Scanner::default();\n let (h, w): (usize, usize) = (scanner.next(), scanner.next());\n let cake: Vec> = (0..h)\n .map(|_| scanner.next::().chars().map(|c| c == '*').collect())\n .collect();\n let (mut i, mut j) = (0, 0);\n let mut berries = if cake[i][j] { 1 } else { 0 };\n while j < w - 1 {\n if i < h - 1 && cake[i + 1][j] {\n i += 1;\n berries += 1;\n } else {\n j += 1;\n if cake[i][j] {\n berries += 1;\n }\n }\n }\n while i < h - 1 {\n i += 1;\n if cake[i][j] {\n berries += 1;\n }\n }\n println!(\"{}\", berries);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation", "shortest paths"], "code_uid": "b37408a4aff403f7ff781736938f7aee", "src_uid": "f985d7a6e7650a9b855a4cef26fd9b0d", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{min,max};\n//const INF: i32 = 0x3f3f3f3f;\n\nstruct Scanner {\n buffer: std::collections::VecDeque\n}\n\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn next(&mut self) -> T {\n while self.buffer.is_empty() {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n self.buffer = input.split_whitespace()\n .map(ToString::to_string).collect();\n }\n let front = self.buffer.pop_front().unwrap();\n front.parse::().ok().unwrap()\n }\n}\n\n\n\nfn main1() {\n let mut scan = Scanner::new();\n let n = scan.next::();\n let t = scan.next::();\n let k = scan.next::();\n let d = scan.next::();\n let t1 = ((n+k-1)/k) * t;\n let t2 = t1 - 1;\n let n2 = (t2/t + (t2-d)/t) * k;\n println!(\"{}\", if n2 >= n { \"YES\" } else { \"NO\" } );\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "fabea71e1649950385f06c992b47ec5c", "src_uid": "32c866d3d394e269724b4930df5e4407", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nfn get_nums() -> Vec {\n\tlet mut input = String::new();\n\n\tio::stdin().read_line(&mut input)\n\t\t.expect(\"\");\n\n\tinput.trim()\n\t\t.split_whitespace()\n\t\t.map(|d| i32::from_str(d).unwrap())\n\t\t.collect::>()\n}\n\nfn get_quad() -> (i32, i32, i32, i32) {\n\tlet v = get_nums();\n\n\t(v[0], v[1], v[2], v[3])\n}\n\nfn main() {\n \tlet (n, t, mut k, d) = get_quad();\n\n \tlet mut t1 = 0;\n \tlet mut c = 0;\n\n \twhile c < n {\n \t\tt1 += t;\n \t\tc += k;\n\t}\n\n\tlet mut t2 = d;\n\tc = 0;\n\tfor _ in 0..d/t {\n\t\tc += k;\n\t}\n\tk *= 2;\n\n\twhile c < n {\n\t\tt2 += t;\n\t\tc += k;\n\t}\n\n\tif t1 > t2 {\n\t\tprintln!(\"YES\");\n\t} else {\n\t\tprintln!(\"NO\");\n\t}\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "aa5dbbf69b177f992c70af1af059cb1a", "src_uid": "32c866d3d394e269724b4930df5e4407", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = input.vi(3);\n let b = input.vi(3);\n if (1..4).all(|n| a[..n].iter().sum::() <= b[..n].iter().sum()) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "5c47fab368bb2d2a125e1b7adf931062", "src_uid": "d54201591f7284da5e9ce18984439f4e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::min;\n\nfn main() {\n let mut required = readline_ints();\n let mut grapes = readline_ints();\n \n for i in 0..3 {\n // i can eat j\n for j in 0..(i+1) {\n let ate = min(grapes[j], required[i]);\n grapes[j] -= ate;\n required[i] -= ate;\n }\n }\n match required[0] + required[1] + required[2] { \n r if r == 0 => println!(\"YES\"),\n _ => println!(\"NO\")\n }\n //println!(\"{:?}\", grapes);\n}\n\nfn readline_ints() -> Vec {\n let mut strs = String::new();\n let _ = io::stdin().read_line(&mut strs);\n strs.split_whitespace().map(|s| s.parse::().unwrap()).collect()\n}", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "1bf35f2376abf4db452680feb5b218f1", "src_uid": "d54201591f7284da5e9ce18984439f4e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n #[cfg(debug_assertions)]\n writeln!(&mut std::io::stderr(), concat!(\"[DEBUG] \", $(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\n#[allow(unused_imports)]\nuse std::io::Write;\n\nfn main() {\n input!{\n x: usize,\n y: usize,\n z: usize,\n a: usize,\n b: usize,\n c: usize,\n }\n\n if a < x {\n return println!(\"{}\", \"NO\");\n }\n if (a-x) + b < y {\n return println!(\"{}\", \"NO\");\n }\n if (a+b+c) < x+y+z {\n return println!(\"{}\", \"NO\");\n }\n println!(\"{}\", \"YES\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "ea3c34c37741a372c4d81fceddfe5a1e", "src_uid": "d54201591f7284da5e9ce18984439f4e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut line=String::new();\n io::stdin().read_line(&mut line).expect(\"Die\");\n let arr:Vec = line.split(\" \").map(|x| x.trim().parse().expect(\"Int\")).collect();\n let (mut i,mut j):(i32,i32)=(arr[1],arr[3]);\n let mut ans=false;\n loop{\n i+=1;\n if i>arr[0]{\n i=1;\n }\n\n j-=1;\n if j<=0{\n j=arr[0];\n }\n if i==j{\n ans=true;\n break;\n }\n else if i==arr[2] || j==arr[4]{\n break;\n }\n }\n\n if ans{\n println!(\"YES\")\n }\n else{\n println!(\"NO\")\n }\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "cab89896fe0b33ba9323917033984c9c", "src_uid": "5b889751f82c9f32f223cdee0c0095e4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub trait Readable {\n type Output;\n fn words_count() -> usize;\n fn read_words(words: &[&str]) -> Result;\n}\n#[macro_export]\nmacro_rules! readable {\n ( $ t : ty , $ words_count : expr , |$ words : ident | $ read_words : expr ) => {\n impl Readable for $t {\n type Output = $t;\n fn words_count() -> usize {\n $words_count\n }\n fn read_words($words: &[&str]) -> Result<$t, String> {\n Ok($read_words)\n }\n }\n };\n}\nreadable!((), 1, |_ss| ());\nreadable!(String, 1, |ss| ss[0].to_string());\nimpl Readable for char {\n type Output = char;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result {\n let chars: Vec = words[0].chars().collect();\n if chars.len() == 1 {\n Ok(chars[0])\n } else {\n Err(format!(\"cannot parse \\\"{}\\\" as a char\", words[0]))\n }\n }\n}\npub struct Chars();\nimpl Readable for Chars {\n type Output = Vec;\n fn words_count() -> usize {\n 1\n }\n fn read_words(words: &[&str]) -> Result, String> {\n Ok(words[0].chars().collect())\n }\n}\nmacro_rules ! impl_readable_for_ints { ( $ ( $ t : ty ) * ) => { $ ( impl Readable for $ t { type Output = Self ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result <$ t , String > { use std :: str :: FromStr ; <$ t >:: from_str ( words [ 0 ] ) . map_err ( | _ | { format ! ( \"cannot parse \\\"{}\\\" as {}\" , words [ 0 ] , stringify ! ( $ t ) ) } ) } } ) * } ; }\nimpl_readable_for_ints ! ( i8 u8 i16 u16 i32 u32 i64 u64 isize usize f32 f64 ) ;\nmacro_rules ! define_one_origin_int_types { ( $ new_t : ident $ int_t : ty ) => { # [ doc = \" Converts 1-origin integer into 0-origin when read from stdin.\" ] # [ doc = \"\" ] # [ doc = \" # Example\" ] # [ doc = \"\" ] # [ doc = \" ```no_run\" ] # [ doc = \" # #[macro_use] extern crate atcoder_snippets;\" ] # [ doc = \" # use atcoder_snippets::read::*;\" ] # [ doc = \" // Stdin: \\\"1\\\"\" ] # [ doc = \" read!(a = usize_);\" ] # [ doc = \" assert_eq!(a, 0);\" ] # [ doc = \" ```\" ] # [ allow ( non_camel_case_types ) ] pub struct $ new_t ( ) ; impl Readable for $ new_t { type Output = $ int_t ; fn words_count ( ) -> usize { 1 } fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { <$ int_t >:: read_words ( words ) . map ( | n | n - 1 ) } } } ; ( $ new_t : ident $ int_t : ty ; $ ( $ inner_new_t : ident $ inner_int_t : ty ) ;* ) => { define_one_origin_int_types ! ( $ new_t $ int_t ) ; define_one_origin_int_types ! ( $ ( $ inner_new_t $ inner_int_t ) ;* ) ; } ; }\ndefine_one_origin_int_types ! ( u8_ u8 ; u16_ u16 ; u32_ u32 ; u64_ u64 ; usize_ usize ) ;\nmacro_rules ! impl_readable_for_tuples { ( $ t : ident $ var : ident ) => ( ) ; ( $ t : ident $ var : ident ; $ ( $ inner_t : ident $ inner_var : ident ) ;* ) => { impl_readable_for_tuples ! ( $ ( $ inner_t $ inner_var ) ;* ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,*> Readable for ( $ t , $ ( $ inner_t ) ,* ) { type Output = ( <$ t >:: Output , $ ( <$ inner_t >:: Output ) ,* ) ; fn words_count ( ) -> usize { let mut n = <$ t >:: words_count ( ) ; $ ( n += <$ inner_t >:: words_count ( ) ; ) * n } # [ allow ( unused_assignments ) ] fn read_words ( words : & [ & str ] ) -> Result < Self :: Output , String > { let mut start = 0 ; let $ var = <$ t >:: read_words ( & words [ start .. start +<$ t >:: words_count ( ) ] ) ?; start += <$ t >:: words_count ( ) ; $ ( let $ inner_var = <$ inner_t >:: read_words ( & words [ start .. start +<$ inner_t >:: words_count ( ) ] ) ?; start += <$ inner_t >:: words_count ( ) ; ) * Ok ( ( $ var , $ ( $ inner_var ) ,* ) ) } } } ; }\nimpl_readable_for_tuples ! ( T5 x5; T4 x4 ; T3 x3 ; T2 x2 ; T1 x1 ) ;\npub trait ReadableFromLine {\n type Output;\n fn read_line(line: &str) -> Result;\n}\nfn split_into_words(line: &str) -> Vec<&str> {\n #[allow(deprecated)]\n line.trim_right_matches('\\n').split_whitespace().collect()\n}\nimpl ReadableFromLine for T {\n type Output = T::Output;\n fn read_line(line: &str) -> Result {\n let words = split_into_words(line);\n if words.len() != T::words_count() {\n return Err(format!(\n \"line \\\"{}\\\" has {} words, expected {}\",\n line,\n words.len(),\n T::words_count()\n ));\n }\n T::read_words(&words)\n }\n}\nimpl ReadableFromLine for Vec {\n type Output = Vec;\n fn read_line(line: &str) -> Result {\n let n = T::words_count();\n let words = split_into_words(line);\n if words.len() % n != 0 {\n return Err(format!(\n \"line \\\"{}\\\" has {} words, expected multiple of {}\",\n line,\n words.len(),\n n\n ));\n }\n let mut result = Vec::new();\n for chunk in words.chunks(n) {\n match T::read_words(chunk) {\n Ok(v) => result.push(v),\n Err(msg) => {\n let flagment_msg = if n == 1 {\n format!(\"word {}\", result.len())\n } else {\n let l = result.len();\n format!(\"words {}-{}\", n * l + 1, (n + 1) * l)\n };\n return Err(format!(\"{} of line \\\"{}\\\": {}\", flagment_msg, line, msg));\n }\n }\n }\n Ok(result)\n }\n}\nimpl ReadableFromLine for (T, Vec) {\n type Output = (T::Output, as ReadableFromLine>::Output);\n fn read_line(line: &str) -> Result {\n let n = T::words_count();\n #[allow(deprecated)]\n let trimmed = line.trim_right_matches('\\n');\n let words_and_rest: Vec<&str> = trimmed.splitn(n + 1, ' ').collect();\n if words_and_rest.len() < n {\n return Err(format!(\n \"line \\\"{}\\\" has {} words, expected at least {}\",\n line,\n words_and_rest.len(),\n n\n ));\n }\n let words = &words_and_rest[..n];\n let empty_str = \"\";\n let rest = words_and_rest.get(n).unwrap_or(&empty_str);\n Ok((T::read_words(words)?, Vec::::read_line(rest)?))\n }\n}\nmacro_rules ! impl_readable_from_line_for_tuples_with_vec { ( $ t : ident $ var : ident ) => ( ) ; ( $ t : ident $ var : ident ; $ ( $ inner_t : ident $ inner_var : ident ) ;+ ) => { impl_readable_from_line_for_tuples_with_vec ! ( $ ( $ inner_t $ inner_var ) ;+ ) ; impl <$ t : Readable , $ ( $ inner_t : Readable ) ,+ , U : Readable > ReadableFromLine for ( $ t , $ ( $ inner_t ) ,+ , Vec < U > ) { type Output = ( $ t :: Output , $ ( $ inner_t :: Output ) ,+ , Vec < U :: Output > ) ; fn read_line ( line : & str ) -> Result < Self :: Output , String > { let mut n = $ t :: words_count ( ) ; $ ( n += $ inner_t :: words_count ( ) ; ) + # [ allow ( deprecated ) ] let trimmed = line . trim_right_matches ( '\\n' ) ; let words_and_rest : Vec <& str > = trimmed . splitn ( n + 1 , ' ' ) . collect ( ) ; if words_and_rest . len ( ) < n { return Err ( format ! ( \"line \\\"{}\\\" has {} words, expected at least {}\" , line , words_and_rest . len ( ) , n ) ) ; } let words = & words_and_rest [ .. n ] ; let empty_str = \"\" ; let rest = words_and_rest . get ( n ) . unwrap_or ( & empty_str ) ; let ( $ var , $ ( $ inner_var ) ,* ) = < ( $ t , $ ( $ inner_t ) ,+ ) >:: read_words ( words ) ?; Ok ( ( $ var , $ ( $ inner_var ) ,* , Vec ::< U >:: read_line ( rest ) ? ) ) } } } ; }\nimpl_readable_from_line_for_tuples_with_vec ! ( T4 t4 ; T3 t3 ; T2 t2 ; T1 t1 ) ;\npub fn read() -> T::Output {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n T::read_line(&line).unwrap()\n}\n#[macro_export]\nmacro_rules ! read { ( ) => { let mut line = String :: new ( ) ; std :: io :: stdin ( ) . read_line ( & mut line ) . unwrap ( ) ; } ; ( $ pat : pat = $ t : ty ) => { let $ pat = read ::<$ t > ( ) ; } ; ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { read ! ( ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) ) ; } ; }\n#[macro_export]\nmacro_rules ! readls { ( $ ( $ pat : pat = $ t : ty ) ,+ ) => { $ ( read ! ( $ pat = $ t ) ; ) * } ; }\npub fn readx() -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result = stdin\n .lock()\n .lines()\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n }).collect();\n result\n}\n#[macro_export]\nmacro_rules ! readx_loop { ( |$ pat : pat = $ t : ty | $ body : expr ) => { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; for line in stdin . lock ( ) . lines ( ) { let line = line . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } ; ( |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readx_loop ! ( | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub fn readn(n: usize) -> Vec {\n use std::io::{self, BufRead};\n let stdin = io::stdin();\n let result: Vec = stdin\n .lock()\n .lines()\n .take(n)\n .map(|line_result| {\n let line = line_result.expect(\"read from stdin failed\");\n T::read_line(&line).unwrap()\n }).collect();\n if result.len() < n {\n panic!(\n \"expected reading {} lines, but only {} lines are read\",\n n,\n result.len()\n );\n }\n result\n}\n#[macro_export]\nmacro_rules ! readn_loop { ( $ n : expr , |$ pat : pat = $ t : ty | $ body : expr ) => { use std :: io :: BufRead ; let stdin = std :: io :: stdin ( ) ; { let mut lock = stdin . lock ( ) ; for _ in 0 ..$ n { let mut line = String :: new ( ) ; lock . read_line ( & mut line ) . expect ( \"read from stdin failed\" ) ; let $ pat = <$ t >:: read_line ( & line ) . unwrap ( ) ; $ body } } } ; ( $ n : expr , |$ ( $ pat : pat = $ t : ty ) ,*| $ body : expr ) => { readn_loop ! ( $ n , | ( $ ( $ pat ) ,* ) = ( $ ( $ t ) ,* ) | $ body ) ; } ; }\npub trait Words {\n fn read(&self) -> T::Output;\n}\nimpl<'a> Words for [&'a str] {\n fn read(&self) -> T::Output {\n T::read_words(self).unwrap()\n }\n}\nimpl<'a> Words for &'a str {\n fn read(&self) -> T::Output {\n T::read_words(&[self]).unwrap()\n }\n}\n\n#[macro_export]\nmacro_rules! dbg {\n ( $ e : expr ) => {{\n use std::io::{self, Write};\n let result = $e;\n writeln!(\n io::stderr(),\n \"{}: {} = {:?}\",\n line!(),\n stringify!($e),\n result\n ).unwrap();\n result\n }};\n}\n\npub fn yn(result: bool) {\n if result {\n println!(\"Yes\");\n } else {\n println!(\"No\");\n }\n}\n#[allow(non_snake_case)]\npub fn YN(result: bool) {\n if result {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\nuse std::iter::{once, repeat};\n\nfn main() {\n read!(n = u16, a = u16_, x = u16_, b = u16_, y = u16_);\n let iter1 = (a..)\n .map(|i| i % n)\n .take_while(|&i| i != x)\n .chain(once(x));\n let iter2 = repeat((0..n).rev()).flatten()\n .skip_while(|&i| i != b)\n .take_while(|&i| i != y)\n .chain(once(y));\n let ans = iter1.zip(iter2).any(|(i, j)| i == j);\n YN(ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "1bdcf8fbf87edde04100941765f83504", "src_uid": "5b889751f82c9f32f223cdee0c0095e4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! parse_line {\n ($($t: ty), +) => {{\n let mut a_line = String::new();\n io::stdin().read_line(&mut a_line).expect(\"read error\");\n let mut a_line_iter = a_line.split_whitespace();\n (\n $(\n a_line_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n }};\n}\n\nfn main() {\n let (n, mut a, x, mut b, y) = parse_line!(i32, i32, i32, i32, i32);\n let mut ok = false;\n loop {\n if a == b {\n ok = true;\n }\n if a == x || b == y {\n break;\n }\n match a == n {\n true => a = 1,\n false => a += 1,\n }\n match b == 1 {\n true => b = n,\n false => b -= 1,\n }\n }\n match ok {\n true => println!(\"YES\"),\n false => println!(\"NO\"),\n }\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "ec407ef8be90d4cb515da1e5d5843c20", "src_uid": "5b889751f82c9f32f223cdee0c0095e4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::collections::{HashSet, HashMap};\nuse std::cmp::{min,max};\nuse std::io;\nuse std::str;\n \nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: vec![], buf_iter: \"\".split_whitespace() }\n }\n fn token(&mut self) -> T {\n loop {\n // If we have another token in this line\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\"); // calls parse::() on the current token and returns it.\n }\n\n // If we do not have another token in the line then\n // we should go to the next line.\n self.buf_str.clear(); // empty out the buffer that holds the current line\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\"); // read a new line into the buffer\n\n // create an iterator over the white space delimited strings of the current line\n self.buf_iter = unsafe { \n let slice = str::from_utf8_unchecked(&self.buf_str); // makes a string from utf8 characters in the current line\n std::mem::transmute(slice.split_whitespace()) // transmutes the memory in place \n }\n }\n }\n}\n \n#[derive(PartialEq)]\nenum Cube {\n Red,\n Blue\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let mut red = scan.token::();\n let mut blue = scan.token::();\n let mut last_cube: Option = None;\n let mut petya = true;\n let mut petya_score: u32 = 0;\n let mut vasya_score: u32 = 0;\n\n if blue < red {\n if blue % 2 != 0 {\n last_cube = Some(Cube::Blue);\n blue -= 1;\n } else {\n last_cube = Some(Cube::Red);\n red -= 1;\n }\n } else if red < blue {\n if red % 2 != 0 {\n last_cube = Some(Cube::Red);\n red -= 1;\n } else {\n last_cube = Some(Cube::Blue);\n blue -= 1;\n }\n }\n\n while red > 0 || blue > 0 {\n let desired_color = {\n if petya {\n match last_cube {\n Some(Cube::Red) => Cube::Red,\n Some(Cube::Blue) => Cube::Blue,\n None => Cube::Red\n }\n } else {\n match last_cube {\n Some(Cube::Red) => Cube::Blue,\n Some(Cube::Blue) => Cube::Red,\n None => Cube::Red\n }\n }\n };\n \n let current_cube = {\n if desired_color == Cube::Red && red > 0 {\n red -= 1;\n Cube::Red\n } else if desired_color == Cube::Blue && blue > 0 {\n blue -=1;\n Cube::Blue\n } else if blue > 0 && red == 0 {\n blue -= 1;\n Cube::Blue\n } else {\n red -= 1;\n Cube::Red\n }\n };\n\n if let Some(last_cube) = last_cube {\n if last_cube == current_cube {\n petya_score += 1;\n } else {\n vasya_score += 1;\n }\n }\n\n last_cube = Some(current_cube);\n\n petya = !petya;\n }\n\n writeln!(out, \"{} {}\", petya_score, vasya_score);\n}\n \nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation", "games"], "code_uid": "97c3d6ec6b7b22d41727ed77c8b0d7f1", "src_uid": "c8378e6fcaab30d15469a55419f38b39", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).unwrap();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n let m = input.i();\n println!(\"{}\", m % (1 << n.min(30)));\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "5d1c460e88b973a707b084336732cf7a", "src_uid": "c649052b549126e600691931b512022f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let n: i64 = readln();\n let m: i64 = readln();\n let ans = if n <= 32 { m % (1i64 << n) } else { m };\n println!(\"{}\", ans);\n}\n\n// --- template ---\n#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::HashSet;\n\npub trait FromLn {\n fn fromln(s: &str) -> Self;\n}\npub fn readln() -> T {\n let mut buf = String::new();\n let _ = ::std::io::stdin().read_line(&mut buf).unwrap();\n T::fromln(buf.trim())\n}\npub fn readlns(n: usize) -> Vec {\n let mut vs = vec![];\n for _ in 0..n {\n vs.push(readln());\n }\n vs\n}\nmacro_rules! fromln_primitives {\n ($($t:ty),*) => { $(\n impl FromLn for $t {\n fn fromln(s: &str) -> $t {\n s.parse().unwrap()\n }\n }\n )* }\n}\nfromln_primitives!(\n String,\n bool,\n f32,\n f64,\n isize,\n i8,\n i16,\n i32,\n i64,\n usize,\n u8,\n u16,\n u32,\n u64\n);\nimpl FromLn for Vec\nwhere\n T: FromLn,\n{\n fn fromln(s: &str) -> Vec {\n s.split_whitespace().map(T::fromln).collect()\n }\n}\nimpl FromLn for Vec {\n fn fromln(s: &str) -> Vec {\n s.chars().collect()\n }\n}\nmacro_rules! fromln_tuple {\n ($($t:ident),*) => {\n impl<$($t),*> FromLn for ($($t),*) where $($t: FromLn),* {\n fn fromln(s: &str) -> ($($t),*) {\n let mut it = s.split_whitespace();\n let t = ($($t::fromln(it.next().unwrap())),*);\n assert_eq!(it.next(), None);\n t\n }\n }\n }\n}\nfromln_tuple!(A, B);\nfromln_tuple!(A, B, C);\nfromln_tuple!(A, B, C, D);\nfromln_tuple!(A, B, C, D, E);\nfromln_tuple!(A, B, C, D, E, F);\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "6dc355e6cc22b62998b3ed22b018b1ab", "src_uid": "c649052b549126e600691931b512022f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let n = readln!(i64);\n let m = readln!(i64);\n if n > 30 {\n println!(\"{}\",m);\n } else {\n println!(\"{}\",m%(1< {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let mut a = input.vi(6);\n a.sort();\n let (x,y) = if a[0] == a[3] {\n (4,5)\n } else if a[1] == a[4] {\n (0,5)\n } else if a[2] == a[5] {\n (0,1)\n } else {\n println!(\"Alien\");\n return;\n };\n if a[x] == a[y] {\n println!(\"Elephant\");\n } else {\n println!(\"Bear\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "47203f998c9107997c3096a02ecdc099", "src_uid": "43308fa25e8578fd9f25328e715d4dd6", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap,HashSet,VecDeque};\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let mut a =readvec!(i32);\n a.sort();\n let mut i1 = 10;\n let mut i2 = 10;\n if a[0] == a[3] {\n i1 = 4;\n i2 = 5;\n } else if a[1] == a[4] {\n i1 = 0;\n i2 = 5;\n } else if a[2] == a[5] {\n i1 = 0;\n i2 = 1;\n } else {\n println!(\"Alien\");\n return;\n }\n if i1 >= a.len() {\n println!(\"Alien\");\n return;\n }\n if a[i1] == a[i2] {\n println!(\"Elephant\");\n } else {\n println!(\"Bear\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "af253c944f815a8ef1d916df14fda992", "src_uid": "43308fa25e8578fd9f25328e715d4dd6", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::collections::HashSet;\n\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nfn bruteforce(n: u64) -> u64 {\n let mut set = HashSet::::new();\n\n for a in 0..=n {\n for b in 0..=(n - a) {\n for c in 0..=(n - a - b) {\n set.insert(4 * a + 9 * b + 49 * c);\n }\n }\n }\n\n set.len() as u64\n}\n\nfn main() {\n let (n,) = parse_line!(u64);\n\n let answer = if n < 11 {\n bruteforce(n)\n } else {\n // The items {0, 4, 8, 9, 12, 13, 16, 17, 18, 20, 21, 22} are always reachable.\n let mut answer = 12u64;\n\n // The range 24 -- (67 + 49(n - 11)) = 49n - 472 is always reachable.\n answer += (49 * n - 472) - 24 + 1;\n\n // Now, the only numbers for which we don't know the answer are those in the range\n // [49n - 471, 49n]. For those, we brute-force the check.\n //\n // Formally, we wonder how many numbers in the range [49n - 471, 49n] can be written in the\n // form 4a + 9b + 49c with a + b + c <= n and a, b, c >= 0.\n //\n // The important observation is that if c <= n - 12, there is no way\n // 4a + 9b + 49c >= 49n - 471. Indeed, we have\n // 4a + 9b + 49c <= 9(n - c) + 49c\n // = 9n + 40c\n // <= 9n + 40(n - 12)\n // <= 49n - 40 * 12\n // < 49n - 471.\n //\n // For this reason, we know that c is in the range n - 11 .. n. This does not leave many\n // cases to check.\n let mut tailset = HashSet::::new();\n for c in (n - 11)..=n {\n for b in 0..=(n - c) {\n for a in 0..=(n - c - b) {\n assert!(a + b + c <= n);\n\n let candidate = 4 * a + 9 * b + 49 * c;\n if candidate >= n * 49 - 471 {\n tailset.insert(candidate);\n } \n }\n } \n }\n\n answer += tailset.len() as u64;\n answer\n };\n\n println!(\"{}\", answer);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "greedy"], "code_uid": "59b9742aa67b4992ca5e9cc0a12978cf", "src_uid": "75ec99318736a8a1b62a8d51efd95355", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn board(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn framed_board(&mut self, r: usize, c: usize, f: u8) -> Vec> {\n\t\tlet mut res = v!([r+2]);\n\t\tres.push( v!([c+2] = f) );\n\t\trep!{[r]\n\t\t\tlet mut t = self.vb();\n\t\t\tassert!(t.len() == c);\n\t\t\tt.reserve(2);\n\t\t\tt.insert(0,f);\n\t\t\tt.push(f);\n\t\t\tres.push(t);\n\t\t}\n\t\tres.push( v!([c+2] = f) );\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n\tfn graph(&mut self, n: usize, m: usize) -> Vec> {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e\n\t}\n\tfn graph_w(&mut self, n: usize, m: usize) -> Vec> where T::Err: Debug {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\tconst A: &[usize] = &[0,4,9,49];\n\n\tlet mut sol = v!([13] = 0_i64);\n\tlet mut dp = v!([49*12+1] = false);\n\tdp[0] = true;\n\tfor n in 1..=12 {\n\t\tfor i in (4..=49*n).rev() {\n\t\t\tfor &a in A {\n\t\t\t\tif i >= a && dp[i-a] {\n\t\t\t\t\tdp[i] = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsol[n] = dp.iter().filter(|&&x| x).count() as i64;\n\t}\n\tlet n = rin.u();\n\tlet sol = sol[n.min(12)] + 49 * (12.max(n as i64) - 12);\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "greedy"], "code_uid": "cbd2fc7fcee484df424f3cf8e79188bb", "src_uid": "75ec99318736a8a1b62a8d51efd95355", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin chmin, chmax ----------\ntrait ChangeMinMax {\n fn chmin(&mut self, x: Self) -> bool;\n fn chmax(&mut self, x: Self) -> bool;\n}\n\nimpl ChangeMinMax for T {\n fn chmin(&mut self, x: Self) -> bool {\n *self > x && {\n *self = x;\n true\n }\n }\n fn chmax(&mut self, x: Self) -> bool {\n *self < x && {\n *self = x;\n true\n }\n }\n}\n// ---------- end chmin, chmax ----------\n// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nfn run() {\n input! {\n n: u64,\n }\n let mul = |a: &[(u64, u64)], b: &[(u64, u64)]| -> Vec<(u64, u64)> {\n let mut c = vec![];\n for a in a.iter() {\n for b in b.iter() {\n c.push((a.0 + b.0, a.1 + b.1 - 1));\n }\n }\n c.sort_unstable();\n c.dedup_by(|a, b| {\n a.0 <= b.1 && {\n b.1.chmax(a.1);\n true\n }\n });\n c\n };\n let mut t = vec![(0, 1)];\n let mut s = vec![(1, 2), (5, 6), (10, 11), (50, 51)];\n let mut n = n;\n while n > 0 {\n if n & 1 == 1 {\n t = mul(&t, &s);\n }\n s = mul(&s, &s);\n n >>= 1;\n }\n let ans = t.iter().fold(0, |s, a| s + a.1 - a.0);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "greedy"], "code_uid": "72302ff77fc24490b4fba10860516371", "src_uid": "75ec99318736a8a1b62a8d51efd95355", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\n \"Could not read line\",\n );\n String::from(&line[..line.len() - 1])\n}\n\nmacro_rules! read_line {\n (Vec<$t: ty>) => {{\n read_line().split_whitespace().map(|token| {\n <$t as std::str::FromStr>::from_str(token).expect(\n &format!(concat!(\"Could not parse {} into \", stringify!($t)), token))\n }).collect::>()\n }};\n ($($t: ty),*) => {{\n let line = read_line();\n let mut iter = line.split_whitespace();\n let result = ($({\n let token = iter.next().expect(\"Not enough tokens\");\n <$t as std::str::FromStr>::from_str(token).expect(\n &format!(concat!(\"Could not parse {} into \", stringify!($t)), token))\n }),*);\n if let Some(token) = iter.next() {\n panic!(\"Unexpected token {}\", token);\n }\n result\n }};\n}\n\nfn main() {\n let (s, f) = read_line!(String, String);\n let s = s.chars().nth(0).unwrap();\n let f = f.chars().nth(0).unwrap();\n let time = read_line!(usize);\n let all = ['v', '<', '^', '>'];\n let s = all.iter().enumerate().find(|x| *x.1 == s).unwrap().0;\n let f = all.iter().enumerate().find(|x| *x.1 == f).unwrap().0;\n let canCw = (s + time) % 4 == f;\n let canCcw = s == (f + time) % 4;\n println!(\n \"{}\",\n match (canCw, canCcw) {\n (false, false) => panic!(\"impossible\"),\n (true, false) => \"cw\",\n (false, true) => \"ccw\",\n (true, true) => \"undefined\",\n }\n );\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6be9b2f2fdfec7e66a22e67a0f167653", "src_uid": "fb99ef80fd21f98674fe85d80a2e5298", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_string() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n input\n}\n\nfn read_int() -> u64 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed\");\n let x = input.trim().parse::().unwrap();\n input.clear();\n x\n}\n\nfn main(){\n let s = read_string();\n let vec: Vec<&str> = s.split(\"\").collect();\n let start_pos_as_char = vec[1].chars().next().unwrap() as u8;\n let end_pos_as_char = vec[3].chars().next().unwrap() as u8;\n let x = read_int();\n let cases = vec![118, 60, 94, 62]; // down left up right\n let sp = cases.iter().position(|&r| r == start_pos_as_char).unwrap();\n let ep = cases.iter().position(|&r| r == end_pos_as_char).unwrap();\n let is_even = ((x % 2) + 2) % 2;\n let result = (((x+sp as u64) % 4) + 4) % 4;\n if is_even == 0{\n println!(\"undefined\");\n } else if (sp < 4) && (cases[result as usize] == end_pos_as_char) || (cases[result as usize] == end_pos_as_char) && (ep == 4){\n println!(\"cw\");\n } else {\n println!(\"ccw\");\n }\n\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d0e7c7162d36b194fa40baa9545f6d05", "src_uid": "fb99ef80fd21f98674fe85d80a2e5298", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(isize);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn modu(x: i32, y: i32) -> i32 {\n let res = x % y;\n if res < 0 { res + y } else { res }\n}\n\nfn main() {\n scanln!(start: String, end: String);\n scanln!(rotations: i32);\n let start = match &start as &str {\n \"^\" => 0i32,\n \">\" => 1i32,\n \"v\" => 2i32,\n \"<\" => 3i32,\n _ => unreachable!()\n };\n let end = match &end as &str {\n \"^\" => 0i32,\n \">\" => 1i32,\n \"v\" => 2i32,\n \"<\" => 3i32,\n _ => unreachable!()\n };\n let cw = modu(start + (rotations % 4), 4);\n let ccw = modu(start - (rotations % 4), 4);\n if cw == end && ccw == end {\n println!(\"undefined\");\n } else if cw == end {\n println!(\"cw\");\n } else if ccw == end {\n println!(\"ccw\");\n } else {\n println!(\"undefined\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d990c2950be5306e45000b8eea92ae3f", "src_uid": "fb99ef80fd21f98674fe85d80a2e5298", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn dir(c: char) -> i32 {\n match c {\n 'v' => 0,\n '<' => 1,\n '^' => 2,\n '>' => 3,\n _ => panic!(\"Invalid character\"),\n }\n}\n\nfn modu(a: i32) -> i32 {\n if a < 0 {\n a % 4 + 4\n } else {\n a % 4\n }\n}\n\nfn main() {\n let mut input = String::new();\n\n std::io::stdin().read_line(&mut input).unwrap();\n\n let mut iter = input.chars();\n\n let start = iter.next().unwrap();\n iter.next().unwrap();\n let end = iter.next().unwrap();\n\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n\n let mut it = input.split_whitespace().map(|x| x.parse::().unwrap());\n\n let n = it.next().unwrap();\n\n if n % 2 == 0 {\n println!(\"undefined\");\n } else if n % 4 == modu(dir(end) - dir(start)) {\n println!(\"cw\");\n } else {\n println!(\"ccw\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2e39c630ba3b63bd9cb23543ae0de8a3", "src_uid": "fb99ef80fd21f98674fe85d80a2e5298", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn read_line() -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"EOF\");\n line.pop();\n return line;\n}\n\nmacro_rules! read_line {\n (Vec<$t: ty>) => {{\n read_line().split_whitespace().map(|token| {\n <$t as std::str::FromStr>::from_str(token).expect(\"Invalid token\")\n }).collect>()\n }};\n ($($t: ty),*) => {{\n let line = read_line();\n let mut iter = line.split_whitespace();\n ($({\n let token = iter.next().expect(\"Too few tokens\");\n <$t as std::str::FromStr>::from_str(token).expect(\"Invalid token\")\n }), *)\n }};\n}\n\nfn spinner_position(c: char) -> i32 {\n match c {\n '^' => 0,\n '>' => 1,\n 'v' => 2,\n '<' => 3,\n _ => -1,\n }\n}\n\nfn main() {\n let (s, t) = read_line!(String, String);\n let n = read_line!(i32) % 4;\n let x = spinner_position(s.chars().nth(0).expect(\"\"));\n let y = spinner_position(t.chars().nth(0).expect(\"\"));\n let d = (y - x + 4) % 4;\n if n % 2 == 0 {\n println!(\"undefined\");\n } else if d == n {\n println!(\"cw\");\n } else if d == 4 - n {\n println!(\"ccw\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d599278e159a4032a769a30eff84287b", "src_uid": "fb99ef80fd21f98674fe85d80a2e5298", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let s: u32 = buffer.trim().parse().expect(\"invalid input\");\n\n println!(\"{}\", 2 * (s / 3) + if s % 3 != 0 { 1 } else { 0 });\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "cddcfcdbb1bb7a160001f4e0b4d5792d", "src_uid": "a993069e35b35ae158d35d6fe166aaef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! https://codeforces.com/problemset/problem/630/I\n//! To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.\n//! The parking lot before the office consists of one line of (2n\u2009-\u20092) parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.\n//! Looking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly n successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.\nuse std::io;\n\nfn main() {\n let mut inp = String::new();\n io::stdin().read_line(&mut inp).unwrap();\n let inp: u64 = inp.trim().parse().unwrap();\n\n let ans: u64 = (9*inp - 3) * binexp(4, inp - 3);\n println!(\"{}\", ans);\n}\n\nfn binexp(mut x: u64, mut y: u64) -> u64 {\n let mut res = 1;\n while y != 0 {\n if y & 1 == 1 {\n res *= x;\n }\n x*=x;\n y>>=1;\n }\n res\n}\n\n\n\n\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "3a33b6ae5f33939ba76025ae3c69de55", "src_uid": "3b02cbb38d0b4ddc1a6467f7647d53a9", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn solve() {\n let mut n: i64 = get();\n let k: i32 = get();\n let mut cnt = 0;\n let mut kk = k;\n while kk > 0 {\n if n == 0 {\n cnt = max(cnt + k - kk - 1, 0);\n break;\n }\n if n % 10 != 0 {\n cnt += 1;\n } else {\n kk -= 1;\n }\n n /= 10;\n }\n println!(\"{}\", cnt);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "308df64897cd05b557e6cfc87ee8d20e", "src_uid": "7a8890417aa48c2b93b559ca118853f9", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{ self, BufRead };\n\nmacro_rules! scan_to_vec {\n ($count:expr, $t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n for _ in 0..$count {\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_to_vec: failed at `handle.read_line`.\");\n result.push(buffer.trim().parse::<$t>()\n .expect(\"scan_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line_to_vec {\n ($t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_line(&mut buffer)\n .expect(\"scan_line_to_vec: failed at `handle.read_line`.\");\n \n for s in chunks.split_whitespace() {\n result.push(s.parse::<$t>()\n .expect(\"scan_line_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line {\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\nfn main() {\n let (n, k) = scan_line!(String usize);\n let mut v = n.into_bytes().iter().map(|x| x - b'0').collect::>();\n let zero_count = v.iter().filter(|x| x == &&0).count();\n\n let mut result = 0;\n while v.len() > 0 {\n let zeroes = v.iter().rev().take_while(|x| **x == 0).count();\n if zeroes as usize >= k { break; }\n let first_nonzero = v.iter().rposition(|&x| x != 0);\n if first_nonzero.is_some() {\n v.remove(first_nonzero.unwrap());\n } else {\n v.pop();\n }\n result += 1;\n }\n\n if v.len() == 0 && zero_count > 0 {\n result -= 1;\n }\n\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "ef13360b179ad3b6908d3aa95f75c813", "src_uid": "7a8890417aa48c2b93b559ca118853f9", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main () {\n use std::io;\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"\");\n let a: Vec = input.trim().split(' ').map(|x| x.parse::().unwrap()).collect();\n if a[0] < 10i32.pow(a[1] as u32) {\n println!(\"{}\", a[0].to_string().len() - 1);\n }\n else if a[0] == 10i32.pow(a[1] as u32) {\n println!(\"0\");\n }\n else {\n let mut t = a[0];\n let mut zeros = 0;\n let mut removed = 0;\n while zeros < a[1] {\n if t % 10 == 0 {\n zeros += 1;\n }\n else {\n removed += 1;\n }\n t = t / 10;\n // println!(\"{} {}\", t, zeros);\n }\n if t == 0 {\n println!(\"{}\", a[0].to_string().len() - 1);\n }\n else {\n println!(\"{}\", removed);\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "c3874681fcc1f16d9045b06f608bdd36", "src_uid": "7a8890417aa48c2b93b559ca118853f9", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let (n, k): (String, usize) = {\n let input = get_line();\n let mut it = input.split_whitespace();\n (\n it.next().unwrap().to_string(),\n it.next().unwrap().parse().unwrap(),\n )\n };\n\n let ans = if let Some((i, _)) = n.bytes().rev().enumerate().filter(|&(i, b)| b == b'0').nth(k - 1) {\n i + 1 - k\n } else {\n n.len() - 1\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "8fac4608405651ebf528b9dad4f44b9f", "src_uid": "7a8890417aa48c2b93b559ca118853f9", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(dead_code)]\nuse std::cmp::*;\nuse std::collections::*;\n\nfn main() {\n let (n, k): (usize, usize) = readln();\n let n: Vec = n.to_string().chars().collect();\n let res0 = n.len() - 1;\n let mut res1 = 0;\n let mut acc = 0;\n for i in (0..n.len()).rev() {\n if acc == k {\n break;\n }\n if n[i] == '0' {\n acc += 1;\n } else {\n res1 += 1;\n }\n }\n\n println!(\"{}\", if acc == k { min(res0, res1) } else { res0 });\n}\n\n\nfn get_line() -> String {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_string()\n}\n\nfn get_chars() -> Vec {\n get_line().chars().collect()\n}\n\nfn readln() -> T {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n T::read(buf.trim_right())\n}\n\ntrait Read {\n fn read(s: &str) -> Self;\n}\n\nmacro_rules! read_impl{\n ($($t:ty)*) => ($(\n impl Read for $t {\n fn read(s: &str) -> $t{\n s.parse().unwrap()\n }\n }\n )*)\n}\nread_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }\n\nimpl Read for Vec {\n fn read(s: &str) -> Self {\n s.split_whitespace().map(T::read).collect()\n }\n}\n\nimpl Read for (A, B) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]))\n }\n}\n\nimpl Read for (A, B, C) {\n fn read(s: &str) -> Self {\n let tokens: Vec<_> = s.split_whitespace().collect();\n (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "1092e15793f91926c9c692db5351d2d1", "src_uid": "7a8890417aa48c2b93b559ca118853f9", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let a = input.i();\n let b = input.i();\n let c = input.i();\n let d = b - a;\n if d == 0 || (c != 0 && d % c == 0 && d / c > 0) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "3eb3a4639111817b59c82b7a4a47ea5b", "src_uid": "9edf42c20ddf22a251b84553d7305a7d", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn solution(input: String) {\n let max_fits = input.trim().len() / 11;\n let possible_fits = input.chars().filter_map(|x| {\n if x == '8' {\n Some(1)\n } else {\n None\n }\n }).sum();\n println!(\"{:?}\", cmp::min(possible_fits, max_fits));\n}\n\npub fn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input);\n input.clear();\n match io::stdin().read_line(&mut input) {\n Ok(n) => {\n solution(input)\n }\n Err(error) => println!(\"error: {}\", error),\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "29be140870ab861d6b7544d512216bc2", "src_uid": "259d01b81bef5536b969247ff2c2d776", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::cmp;\n \nfn main() {\n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_to_string(&mut buffer).unwrap();\n\n let arr : Vec<&str> = buffer.split_whitespace().collect();\n let mut num_8 = 0;\n let mut tot = 0;\n for i in arr[1].chars() {\n let d = i as u8 - '0' as u8;\n if d == 8 {\n num_8 += 1;\n }\n tot += 1;\n }\n\n let mut ans = 0;\n for i in 1..num_8+1 {\n let m = (tot-i)/10;\n use std::cmp;\n let h = cmp::min(m,i);\n ans = cmp::max(h,ans);\n }\n\n println!(\"{}\",ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "57511a7703896bb91e6033cfa7d80786", "src_uid": "259d01b81bef5536b969247ff2c2d776", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut n_str = String::new();\n let mut numbers_str = String::new();\n std::io::stdin().read_line(&mut n_str);\n std::io::stdin().read_line(&mut numbers_str);\n\n let numbers_str = numbers_str.trim();\n\n let n: i32 = n_str.trim().parse().unwrap();\n\n let mut result = n / 11;\n\n let mut has_8_count = 0;\n\n for (_, c) in numbers_str.chars().enumerate(){\n if c == '8'{\n has_8_count += 1;\n }\n }\n\n if has_8_count < result {\n result = has_8_count;\n }\n\n println!(\"{}\", result);\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "3caf17f02d0f61ff1da84e6282ac5a74", "src_uid": "259d01b81bef5536b969247ff2c2d776", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\r\nuse std::{cell::{Cell, RefCell, UnsafeCell}, cmp::{Ordering, Reverse, max, min}, collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque, hash_map::{DefaultHasher, RandomState}}, error::Error, fmt::{Display, Write as FmtWrite}, hash::{BuildHasher, Hash, Hasher}, io::{BufWriter, Read, Stdin, Stdout, Write}, iter::{FromIterator, Peekable}, mem::swap, ops::*, process::exit, rc::Rc, str::{FromStr, from_utf8_unchecked}, time::{Duration, Instant}, convert::{TryInto, TryFrom}, marker::PhantomData};\r\n\r\nconst IO_BUF_SIZE: usize = 1 << 16;\r\ntype Input = Scanner;\r\ntype Output = BufWriter;\r\nfn _init_input() -> Input { Scanner::new(std::io::stdin()) }\r\nfn _init_output() -> Output { BufWriter::with_capacity(IO_BUF_SIZE, std::io::stdout()) }\r\n\r\n#[repr(transparent)] struct Unsync(T);\r\nunsafe impl Sync for Unsync {}\r\n \r\ntype BadLazy = Unsync>>;\r\nimpl BadLazy {\r\n const fn new() -> Self { Self(UnsafeCell::new(None)) }\r\n}\r\n \r\nstatic INPUT: BadLazy = BadLazy::new();\r\nstatic OUTPUT: BadLazy = BadLazy::new();\r\n \r\nfn inp R, R>(f: F) -> R {\r\n unsafe { f((&mut *INPUT.0.get()).get_or_insert_with(_init_input)) }\r\n}\r\nfn out R, R>(f: F) -> R {\r\n unsafe { f((&mut *OUTPUT.0.get()).get_or_insert_with(_init_output)) }\r\n}\r\n\r\nmacro_rules! read {\r\n () => { read() };\r\n ($t: ty) => { read::<$t>() };\r\n ($t: ty, $($tt: ty),*) => { (read::<$t>(), $(read::<$tt>(),)*) };\r\n [$t: ty; $n: expr] => { read_vec::<$t>($n) };\r\n}\r\nmacro_rules! println { \r\n () => { out(|x| { let _ = writeln!(x); }) };\r\n ($exp: expr) => { out(|x| { let _ = writeln!(x, \"{}\", $exp); }) }; \r\n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = writeln!(x, $fmt, $($arg)*); }) }\r\n}\r\nmacro_rules! print { \r\n ($exp: expr) => { out(|x| { let _ = write!(x, \"{}\", $exp); }) }; \r\n ($fmt: expr, $($arg : tt )*) => { out(|x| { let _ = write!(x, $fmt, $($arg)*); }) }\r\n}\r\n\r\nfn out_flush() { out(|x| { let _ = x.flush(); }); }\r\n\r\nfn input_is_eof() -> bool { inp(|x| x.eof()) }\r\nfn read_byte() -> u8 { inp(|x| x.byte()) }\r\nfn read_bytes_no_skip(n: usize) -> Vec { inp(|x| x.bytes_no_skip(n)) }\r\nfn read_bytes(n: usize) -> Vec { inp(|x| x.bytes(n)) }\r\nfn read_bytes2(n: usize, m: usize) -> Vec> { inp(|x| x.bytes2(n, m)) }\r\nfn read_token() -> Vec { inp(|x| x.token_bytes()) }\r\nfn read_token_str() -> String { unsafe { String::from_utf8_unchecked(read_token()) } }\r\nfn read_line() -> Vec { inp(|x| x.line_bytes()) }\r\nfn read_line_str() -> String { unsafe { String::from_utf8_unchecked(read_line()) } }\r\nfn read() -> T { read_token_str().parse::().ok().expect(\"failed parse\") }\r\nfn read_vec(n: usize) -> Vec { (0..n).map(|_| read()).collect() }\r\nfn read_vec2(n: usize, m: usize) -> Vec> { (0..n).map(|_| read_vec(m)).collect() }\r\n\r\nstruct Scanner {\r\n src: R,\r\n _buf: Vec,\r\n _pt: usize, // pointer\r\n _rd: usize, // bytes read\r\n}\r\n\r\n#[allow(dead_code)]\r\nimpl Scanner {\r\n fn new(src: R) -> Scanner {\r\n Scanner { src, _buf: vec![0; IO_BUF_SIZE], _pt: 1, _rd: 1 }\r\n }\r\n \r\n fn _check_buf(&mut self) {\r\n if self._pt == self._rd {\r\n self._rd = self.src.read(&mut self._buf).unwrap_or(0);\r\n self._pt = (self._rd == 0) as usize;\r\n }\r\n }\r\n \r\n // returns true if end of file\r\n fn eof(&mut self) -> bool {\r\n self._check_buf();\r\n self._rd == 0\r\n }\r\n \r\n // filters \\r, returns \\0 if eof\r\n fn byte(&mut self) -> u8 {\r\n loop {\r\n self._check_buf();\r\n if self._rd == 0 { return 0; }\r\n let res = self._buf[self._pt];\r\n self._pt += 1;\r\n if res != b'\\r' { return res; }\r\n }\r\n }\r\n\r\n fn bytes_no_skip(&mut self, n: usize) -> Vec { (0..n).map(|_| self.byte()).collect() }\r\n fn bytes(&mut self, n: usize) -> Vec {\r\n let res = self.bytes_no_skip(n);\r\n self.byte();\r\n res\r\n }\r\n fn bytes2(&mut self, n: usize, m: usize) -> Vec> { (0..n).map(|_| self.bytes(m)).collect() }\r\n \r\n fn token_bytes(&mut self) -> Vec {\r\n let mut res = Vec::new();\r\n let mut c = self.byte();\r\n while c <= b' ' {\r\n if c == b'\\0' { return res; }\r\n c = self.byte();\r\n }\r\n loop {\r\n res.push(c);\r\n c = self.byte();\r\n if c <= b' ' { return res; }\r\n }\r\n }\r\n \r\n fn line_bytes(&mut self) -> Vec {\r\n let mut res = Vec::new();\r\n let mut c = self.byte();\r\n while c != b'\\n' && c != b'\\0' {\r\n res.push(c);\r\n c = self.byte();\r\n }\r\n res\r\n }\r\n}\r\n\r\ntrait JoinToStr { \r\n fn join_to_str(self, sep: &str) -> String;\r\n fn concat_to_str(self) -> String;\r\n}\r\nimpl> JoinToStr for I { \r\n fn join_to_str(mut self, sep: &str) -> String {\r\n match self.next() {\r\n Some(first) => {\r\n let mut res = first.to_string();\r\n while let Some(item) = self.next() {\r\n res.push_str(sep);\r\n res.push_str(&item.to_string());\r\n }\r\n res\r\n }\r\n None => { String::new() }\r\n }\r\n }\r\n \r\n fn concat_to_str(self) -> String {\r\n let mut res = String::new();\r\n for item in self { res.push_str(&item.to_string()); }\r\n res\r\n }\r\n}\r\ntrait AsStr { fn as_str(&self) -> &str; }\r\nimpl AsStr for [u8] { fn as_str(&self) -> &str {std::str::from_utf8(self).expect(\"attempt to convert non-UTF8 byte string.\")} }\r\n\r\nmacro_rules! veci {\r\n ($n:expr , $i:ident : $gen:expr) => {{\r\n let _veci_n = $n;\r\n let mut _veci_list = Vec::with_capacity(_veci_n);\r\n for $i in 0.._veci_n {\r\n _veci_list.push($gen);\r\n }\r\n _veci_list\r\n }};\r\n ($n:expr , $gen:expr) => { veci!($n, _veci_: $gen) }\r\n}\r\n\r\nfn abs_diff + PartialOrd>(x: T, y: T) -> T {\r\n if x < y { y - x } else { x - y }\r\n}\r\n\r\ntrait CommonNumExt {\r\n fn div_ceil(self, b: Self) -> Self;\r\n fn div_floor(self, b: Self) -> Self;\r\n fn gcd(self, b: Self) -> Self;\r\n fn highest_one(self) -> Self;\r\n fn lowest_one(self) -> Self;\r\n fn sig_bits(self) -> u32;\r\n}\r\n\r\nmacro_rules! impl_common_num_ext {\r\n ($($ix:tt = $ux:tt),*) => {\r\n $(\r\n impl CommonNumExt for $ux {\r\n fn div_ceil(self, b: Self) -> Self {\r\n let q = self / b; let r = self % b;\r\n if r != 0 { q + 1 } else { q }\r\n }\r\n fn div_floor(self, b: Self) -> Self { self / b }\r\n fn gcd(self, mut b: Self) -> Self {\r\n let mut a = self;\r\n if a == 0 || b == 0 { return a | b; }\r\n let shift = (a | b).trailing_zeros();\r\n a >>= a.trailing_zeros();\r\n b >>= b.trailing_zeros();\r\n while a != b {\r\n if a > b { a -= b; a >>= a.trailing_zeros(); }\r\n else { b -= a; b >>= b.trailing_zeros(); }\r\n }\r\n a << shift\r\n }\r\n #[inline] fn highest_one(self) -> Self { \r\n if self == 0 { 0 } else { const ONE: $ux = 1; ONE << self.sig_bits() - 1 } \r\n }\r\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\r\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ux>() as u32 * 8 - self.leading_zeros() }\r\n }\r\n\r\n impl CommonNumExt for $ix {\r\n fn div_ceil(self, b: Self) -> Self {\r\n let q = self / b; let r = self % b;\r\n if self ^ b >= 0 && r != 0 { q + 1 } else { q }\r\n }\r\n fn div_floor(self, b: Self) -> Self { \r\n let q = self / b; let r = self % b;\r\n if self ^ b < 0 && r != 0 { q - 1 } else { q }\r\n }\r\n fn gcd(self, b: Self) -> Self {\r\n fn w_abs(x: $ix) -> $ux { (if x.is_negative() { x.wrapping_neg() } else { x }) as _ }\r\n w_abs(self).gcd(w_abs(b)) as _\r\n }\r\n #[inline] fn highest_one(self) -> Self { (self as $ux).highest_one() as _ }\r\n #[inline] fn lowest_one(self) -> Self { self & self.wrapping_neg() }\r\n #[inline] fn sig_bits(self) -> u32 { std::mem::size_of::<$ix>() as u32 * 8 - self.leading_zeros() }\r\n }\r\n )*\r\n }\r\n}\r\nimpl_common_num_ext!(i8 = u8, i16 = u16, i32 = u32, i64 = u64, i128 = u128, isize = usize);\r\n\r\ntrait ChMaxMin {\r\n fn chmax(&mut self, v: T) -> bool;\r\n fn chmin(&mut self, v: T) -> bool;\r\n}\r\nimpl ChMaxMin for Option {\r\n fn chmax(&mut self, v: T) -> bool { if self.is_none() || v > *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\r\n fn chmin(&mut self, v: T) -> bool { if self.is_none() || v < *self.as_ref().unwrap() { *self = Some(v); true } else { false } }\r\n}\r\nimpl ChMaxMin for T {\r\n fn chmax(&mut self, v: T) -> bool { if v > *self { *self = v; true } else { false } }\r\n fn chmin(&mut self, v: T) -> bool { if v < *self { *self = v; true } else { false } }\r\n}\r\n\r\n// * end commons * //\r\n#[macro_use]\r\n#[allow(dead_code)]\r\nmod modint {\r\n use std::{fmt::{Display, Formatter}, marker::PhantomData, mem::swap, ops::*, str::FromStr, cell::Cell};\r\n use crate::ModInt;\r\n \r\n pub trait RemEuclidU32: Copy {\r\n /// Calculates `self` _mod_ `modulus` losslessly.\r\n fn rem_euclid_u32(self, modulus: u32) -> u32;\r\n }\r\n \r\n macro_rules! impl_rem_euclid_u32_for_small_signed {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self as i64).rem_euclid(i64::from(modulus)) as _\r\n }\r\n }\r\n )*\r\n }\r\n }\r\n \r\n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\r\n \r\n impl RemEuclidU32 for i128 {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self.rem_euclid(i128::from(modulus)) as _\r\n }\r\n }\r\n \r\n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n self as u32 % modulus\r\n }\r\n }\r\n )*\r\n }\r\n }\r\n \r\n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\r\n ($($ty:tt),*) => {\r\n $(\r\n impl RemEuclidU32 for $ty {\r\n #[inline]\r\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\r\n (self % (modulus as $ty)) as _\r\n }\r\n }\r\n )*\r\n }\r\n }\r\n \r\n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\r\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\r\n \r\n #[cfg(target_pointer_width = \"32\")]\r\n impl_rem_euclid_u32_for_small_unsigned!(usize);\r\n \r\n #[cfg(target_pointer_width = \"64\")]\r\n impl_rem_euclid_u32_for_large_unsigned!(usize);\r\n #[inline]\r\n pub fn mul_mod_u32(a: u32, b: u32, m: u32) -> u32 {\r\n (a as u64 * b as u64 % m as u64) as u32\r\n }\r\n \r\n // for a, b < m, unspecified otherwise\r\n #[inline]\r\n fn add_mod_raw(a: u32, b: u32, m: u32) -> u32 {\r\n let (r, c) = a.wrapping_sub(m).overflowing_add(b);\r\n if c { r } else { a + b }\r\n }\r\n #[inline]\r\n fn sub_mod_raw(a: u32, b: u32, m: u32) -> u32 {\r\n let (r, c) = a.overflowing_sub(b);\r\n if c { r.wrapping_add(m) } else { r }\r\n }\r\n fn pow_mod_raw(a: u32, mut k: u64, m: u32) -> u32 {\r\n if m == 1 { return 0; }\r\n let mut a = a as u64;\r\n let m = m as u64;\r\n let mut r: u64 = 1;\r\n while k > 0 {\r\n if k & 1 == 1 {\r\n r = r * a % m;\r\n }\r\n k >>= 1;\r\n a = a * a % m;\r\n }\r\n r as u32\r\n }\r\n \r\n /// # Parameters\r\n /// * `b` `1 <= b`\r\n /// # Returns\r\n /// (x, g) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\r\n fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\r\n let a = a.rem_euclid(b);\r\n if a == 0 { return (0, b); }\r\n let mut s = b;\r\n let mut t = a;\r\n let mut m0 = 0;\r\n let mut m1 = 1;\r\n \r\n while t != 0 {\r\n let u = s / t;\r\n s -= t * u;\r\n m0 -= m1 * u;\r\n swap(&mut s, &mut t);\r\n swap(&mut m0, &mut m1);\r\n }\r\n \r\n if m0 < 0 { m0 += b / s; }\r\n (m0, s)\r\n }\r\n \r\n pub trait Modulus: Copy + Eq {\r\n fn get_modulus() -> u32;\r\n fn mul(a: u32, b: u32) -> u32;\r\n }\r\n \r\n #[derive(Clone, Copy, PartialEq, Eq, Hash)]\r\n #[repr(transparent)]\r\n pub struct ModIntBase { \r\n val: u32,\r\n _phantom: PhantomData\r\n }\r\n \r\n impl ModIntBase {\r\n #[inline(always)]\r\n pub fn modulus() -> u32 { M::get_modulus() }\r\n #[inline] pub fn new(val: I) -> Self { Self::raw(val.rem_euclid_u32(Self::modulus())) }\r\n #[inline] pub fn raw(val: u32) -> Self { Self { val, _phantom: PhantomData } }\r\n pub fn inv(self) -> Self { \r\n let (x, gcd) = inv_gcd(self.val.into(), Self::modulus().into());\r\n debug_assert!(gcd == 1, \"the multiplicative inverse {}^-1 mod {} does not exist\", self.val, Self::modulus());\r\n Self::raw(x as u32)\r\n }\r\n #[inline] pub fn val(self) -> u32 { self.val }\r\n #[inline] pub fn pow(self, k: u64) -> Self {\r\n Self::raw(pow_mod_raw(self.val, k, Self::modulus()))\r\n }\r\n pub fn powi(self, k: i64) -> Self { if k < 0 { self.inv().pow(-k as _) } else { self.pow(k as _) } }\r\n pub fn pow_vec(self, n: usize) -> Vec {\r\n let mut res = vec![Self::raw(0); n+1];\r\n res[0] += 1;\r\n for i in 1..=n {\r\n res[i] = res[i-1] * self;\r\n }\r\n res\r\n }\r\n\r\n pub fn invs(a: &[Self]) -> Vec {\r\n let n = a.len();\r\n if n == 0 { return vec![]; }\r\n let mut acc = Self::new(1);\r\n let mut res = Vec::with_capacity(n);\r\n for i in 0..n {\r\n if a[i].val() != 0 { acc *= a[i]; }\r\n res.push(acc);\r\n }\r\n acc = acc.inv();\r\n for i in (1..n).rev() {\r\n res[i] = acc * res[i-1];\r\n if a[i].val() != 0 { acc *= a[i]; }\r\n }\r\n res[0] = acc;\r\n res\r\n }\r\n }\r\n \r\n #[inline]\r\n pub fn mi(val: I) -> ModInt { ModIntBase::new(val) }\r\n #[inline] pub fn mir(v: u32) -> ModInt { ModIntBase::raw(v) }\r\n \r\n impl From for ModIntBase {\r\n #[inline]\r\n fn from(from: V) -> Self { Self::new(from) }\r\n }\r\n impl Default for ModIntBase {\r\n fn default() -> Self { Self::raw(0) }\r\n }\r\n impl FromStr for ModIntBase {\r\n type Err = std::convert::Infallible;\r\n #[inline]\r\n fn from_str(s: &str) -> Result {\r\n Ok(s.parse::()\r\n .map(Self::new)\r\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\r\n }\r\n }\r\n impl Display for ModIntBase {\r\n #[inline]\r\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\r\n self.val.fmt(f)\r\n }\r\n }\r\n impl std::fmt::Debug for ModIntBase {\r\n #[inline]\r\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\r\n std::fmt::Debug::fmt(&self.val, f)\r\n }\r\n }\r\n impl Neg for ModIntBase {\r\n type Output = Self;\r\n \r\n #[inline]\r\n fn neg(self) -> Self::Output {\r\n Self::raw(0) - self\r\n }\r\n }\r\n \r\n impl>, M: Modulus> Add for ModIntBase {\r\n type Output = Self;\r\n #[inline]\r\n fn add(self, rhs: V) -> Self::Output {\r\n Self::raw(add_mod_raw(self.val, rhs.into().val, Self::modulus()))\r\n }\r\n }\r\n impl>, M: Modulus> Sub for ModIntBase {\r\n type Output = Self;\r\n #[inline]\r\n fn sub(self, rhs: V) -> Self::Output {\r\n Self::raw(sub_mod_raw(self.val, rhs.into().val, Self::modulus()))\r\n }\r\n }\r\n impl>, M: Modulus> Mul for ModIntBase {\r\n type Output = Self;\r\n #[inline]\r\n fn mul(self, rhs: V) -> Self::Output {\r\n Self::raw(M::mul(self.val, rhs.into().val))\r\n }\r\n }\r\n impl>, M: Modulus> Div for ModIntBase {\r\n type Output = Self;\r\n #[inline]\r\n fn div(self, rhs: V) -> Self::Output { self * rhs.into().inv() }\r\n }\r\n \r\n impl >, M: Modulus> AddAssign for ModIntBase {\r\n #[inline]\r\n fn add_assign(&mut self, rhs: V) { *self = *self + rhs; }\r\n }\r\n impl >, M: Modulus> SubAssign for ModIntBase {\r\n #[inline]\r\n fn sub_assign(&mut self, rhs: V) { *self = *self - rhs; }\r\n }\r\n impl >, M: Modulus> MulAssign for ModIntBase {\r\n #[inline]\r\n fn mul_assign(&mut self, rhs: V) { *self = *self * rhs; }\r\n }\r\n impl >, M: Modulus> DivAssign for ModIntBase {\r\n #[inline]\r\n fn div_assign(&mut self, rhs: V) { *self = *self / rhs; }\r\n }\r\n \r\n impl std::iter::Sum for ModIntBase {\r\n #[inline] fn sum>(iter: I) -> Self {\r\n iter.fold(Self::raw(0), Add::add)\r\n }\r\n }\r\n impl std::iter::Product for ModIntBase {\r\n #[inline] fn product>(iter: I) -> Self {\r\n iter.fold(1.into(), Mul::mul)\r\n }\r\n }\r\n impl<'a, M: Modulus> std::iter::Sum<&'a Self> for ModIntBase {\r\n #[inline] fn sum>(iter: I) -> ModIntBase {\r\n iter.fold(Self::raw(0), |a, &b| a + b)\r\n }\r\n }\r\n impl<'a, M: Modulus> std::iter::Product<&'a Self> for ModIntBase {\r\n #[inline] fn product>(iter: I) -> ModIntBase {\r\n iter.fold(1.into(), |a, &b| a * b)\r\n }\r\n }\r\n \r\n macro_rules! const_modulus {\r\n ($mint: ident, $name: ident, $modulus: expr) => {\r\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\r\n pub enum $name {}\r\n impl Modulus for $name {\r\n #[inline(always)] fn get_modulus() -> u32 { $modulus }\r\n fn mul(a: u32, b: u32) -> u32 { \r\n mul_mod_u32(a, b, Self::get_modulus())\r\n }\r\n }\r\n pub type $mint = ModIntBase<$name>;\r\n }\r\n }\r\n\r\n #[derive(Debug, Clone, Copy)]\r\n pub struct ModulusCalc {\r\n pub modulus: u32,\r\n pub inv: u64\r\n }\r\n \r\n macro_rules! dynamic_modulus {\r\n ($mint: ident, $name: ident, $modulus: ident) => {\r\n static $modulus: crate::Unsync> = crate::Unsync(Cell::new(ModulusCalc { modulus: 0, inv: 0 }));\r\n #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\r\n pub enum $name {}\r\n impl Modulus for $name {\r\n fn get_modulus() -> u32 { $modulus.0.get().modulus }\r\n fn mul(a: u32, b: u32) -> u32 {\r\n let ModulusCalc { modulus, inv } = $modulus.0.get();\r\n let p = a as u64 * b as u64;\r\n let g = ((p as u128 * inv as u128) >> 64) as u64;\r\n let (r, c) = p.overflowing_sub(g * modulus as u64);\r\n if c { (r as u32).wrapping_add(modulus) } else { r as u32 }\r\n }\r\n }\r\n impl $name {\r\n pub fn set_modulus(val: u32) { \r\n let inv = (1u64.wrapping_neg() / val as u64).wrapping_add(1);\r\n $modulus.0.set(ModulusCalc { modulus: val, inv })\r\n }\r\n }\r\n pub type $mint = ModIntBase<$name>;\r\n }\r\n }\r\n \r\n const_modulus!(ModInt998_244_353, Mod998_244_353, 998_244_353);\r\n const_modulus!(ModInt1_000_000_007, Mod1_000_000_007, 1_000_000_007);\r\n dynamic_modulus!(DynamicModInt, DynamicModulus, DYNAMIC_MODULUS);\r\n}\r\n \r\nuse crate::modint::*;\r\ntype ModInt = ModInt998_244_353;\r\n// type ModInt = ModInt1_000_000_007;\r\n// const_modulus!(ModInt, DefaultModulus, 1_000_000_009);\r\n// type ModInt = DynamicModInt;\r\n\r\npub struct ModFft {\r\n n_inv: ModInt,\r\n w: Vec\r\n}\r\nimpl ModFft {\r\n pub fn primitive_root() -> ModInt { ModInt::raw(3) /* for 998244353 */}\r\n pub fn good_len(deg: usize) -> usize { (deg + 1).next_power_of_two() }\r\n pub fn prepare(arr: &[ModInt], deg: usize) -> Vec { \r\n let n = Self::good_len(deg);\r\n let mut res = Vec::with_capacity(n);\r\n res.extend_from_slice(arr);\r\n res.resize(n, ModInt::raw(0));\r\n res\r\n }\r\n\r\n pub fn new(max_deg: usize) -> Self {\r\n let n = Self::good_len(max_deg);\r\n Self {\r\n n_inv: ModInt::new(n).inv(),\r\n w: ModInt::pow_vec(Self::primitive_root().pow((ModInt::modulus() - 1) as u64 / n as u64), n-1)\r\n }\r\n }\r\n\r\n pub fn transform(&self, a: &mut [ModInt]) { self.transform_impl(a, false) }\r\n pub fn transform_inv(&self, a: &mut [ModInt]) { self.transform_impl(a, true) }\r\n\r\n pub fn fft(&self, a: &[ModInt]) -> Vec { self.fft_deg(a, a.len() - 1) }\r\n pub fn fft_deg(&self, a: &[ModInt], deg: usize) -> Vec { \r\n let mut a = Self::prepare(a, deg);\r\n self.transform(&mut a);\r\n a\r\n }\r\n pub fn fft_inv(&self, a: &[ModInt]) -> Vec { \r\n let mut a = Self::prepare(a, a.len() - 1);\r\n self.transform_inv(&mut a);\r\n a\r\n }\r\n\r\n pub fn max_deg(&self) -> usize { self.w.len() - 1 }\r\n\r\n #[inline] fn transform_impl(&self, a: &mut [ModInt], invert: bool) {\r\n let sz = a.len();\r\n if sz <= 1 { return }\r\n let n = self.w.len();\r\n debug_assert!(sz <= n && sz.is_power_of_two(), \"Array size {} must be <= {} and a power of 2\", sz, n);\r\n let sh = sz.leading_zeros() + 1;\r\n\r\n for i in 0..sz {\r\n let j = i.reverse_bits() >> sh;\r\n if i < j { a.swap(i, j) }\r\n }\r\n\r\n let mut len = 2usize;\r\n let mut ang = (n >> 1) as isize;\r\n if invert { ang = -ang; }\r\n while len <= sz {\r\n let h = len >> 1;\r\n for i in (0..sz).step_by(len) {\r\n let mut k = 0usize;\r\n for j in i..i+h {\r\n let u = a[j];\r\n let v = a[j+h] * self.w[k];\r\n a[j] = u + v;\r\n a[j+h] = u - v;\r\n k = k.wrapping_add(ang as usize) & (n-1);\r\n }\r\n }\r\n len <<= 1;\r\n ang >>= 1;\r\n }\r\n\r\n if invert {\r\n let sz_inv = self.n_inv * (n / sz);\r\n for i in 0..sz { a[i] *= sz_inv; }\r\n }\r\n }\r\n\r\n const NAIVE_THRESHOLD: usize = 60;\r\n fn naive_mul(a: &[ModInt], b: &[ModInt]) -> Vec {\r\n let n = a.len();\r\n let m = b.len();\r\n let mut ans = vec![ModInt::raw(0); n + m - 1];\r\n for i in 0..n { for j in 0..m {\r\n ans[i + j] += a[i] * b[j];\r\n }}\r\n ans\r\n }\r\n\r\n pub fn mul(&self, a: &[ModInt], b: &[ModInt]) -> Vec {\r\n if a.is_empty() || b.is_empty() { return vec![]; }\r\n let deg = a.len() + b.len() - 2;\r\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\r\n if min(a.len(), b.len()) <= Self::NAIVE_THRESHOLD { return Self::naive_mul(a, b); }\r\n let mut a = Self::prepare(a, deg);\r\n let mut b = Self::prepare(b, deg);\r\n self.transform(&mut a);\r\n self.transform(&mut b);\r\n for i in 0..a.len() { a[i] *= b[i]; }\r\n self.transform_inv(&mut a);\r\n a.truncate(deg + 1);\r\n a\r\n }\r\n\r\n pub fn sq(&self, a: &[ModInt]) -> Vec {\r\n if a.is_empty() { return vec![]; }\r\n let deg = a.len() * 2 - 2;\r\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\r\n if a.len() <= Self::NAIVE_THRESHOLD { return Self::naive_mul(a, a); }\r\n let mut a = Self::prepare(a, deg);\r\n self.transform(&mut a);\r\n for i in 0..a.len() { let ai = a[i]; a[i] = ai * ai; }\r\n self.transform_inv(&mut a);\r\n a.truncate(deg + 1);\r\n a\r\n }\r\n\r\n pub fn pow(&self, a: &[ModInt], exp: usize) -> Vec {\r\n if a.is_empty() { return vec![]; }\r\n let deg = (a.len() - 1) * exp;\r\n debug_assert!(deg < self.w.len(), \"FFT capacity {} too small for polynomial of degree {}\", self.w.len(), deg);\r\n let mut a = Self::prepare(a, deg);\r\n self.transform(&mut a);\r\n for i in 0..a.len() { a[i] = a[i].pow(exp as u64) }\r\n self.transform_inv(&mut a);\r\n a.truncate(deg + 1);\r\n a\r\n }\r\n\r\n pub fn product(&self, mut polys: VecDeque>) -> Vec {\r\n while let Some(p) = polys.pop_front() {\r\n if let Some(q) = polys.pop_front() {\r\n polys.push_back(self.mul(&p, &q));\r\n } else { return p; }\r\n }\r\n\r\n vec![ModInt::new(1)]\r\n }\r\n}\r\n\r\n#[allow(non_snake_case, non_upper_case_globals)]\r\nfn main() {\r\n let num_cases: usize = 1;//read();\r\n \r\n for _case_num in 1..=num_cases {\r\n let n = read!(usize);\r\n\t\tlet k = read!(usize);\r\n\t\tlet f = read!(usize);\r\n\t\t\r\n\t\tlet ff = ModFft::new(2*k);\r\n\t\tlet mut dp = vec![mi(1); k+1];\r\n\t\tfor _ in 1..n {\r\n\t\t\tlet sq = ff.sq(&dp);\r\n\t\t\tlet mut sm = sq[k+1..].iter().sum::();\r\n\t\t\tfor i in (0..=k).rev() {\r\n\t\t\t\tdp[i] = sq[i] * (k + 1 - i) + sm;\r\n\t\t\t\tsm += sq[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tdp.resize(f+1, mi(0));\r\n\t\tlet ans = (0..=f).map(|i| dp[i] * dp[f-i]).sum::();\r\n\t\tprintln!(ans);\r\n }\r\n \r\n out_flush();\r\n}", "lang_cluster": "Rust", "tags": ["brute force", "flows", "math", "dp", "fft", "bitmasks", "graphs", "meet-in-the-middle", "trees"], "code_uid": "18645f1eb6d40d3476f713c46cf54dcf", "src_uid": "4b8161259545e44c7d1046be2e4fe014", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "type Mod = ModInt998244353;\n\nfn main() {\n let stdout = std::io::stdout();\n let mut writer = std::io::BufWriter::new(stdout.lock());\n #[allow(unused_macros)] macro_rules! print { ($($tt:tt)*) => {{ use std::io::Write; std::write!(writer, $($tt)*).unwrap(); }}; }\n #[allow(unused_macros)] macro_rules! println { ($($tt:tt)*) => {{ use std::io::Write; std::writeln!(writer, $($tt)*).unwrap(); }}; }\n\n input! {\n n: usize,\n k: usize,\n f: usize\n }\n\n let mut ans = vec![Mod::raw(1); k + 1];\n\n for depth in 1..=n {\n\n ans = convolution(&ans, &ans);\n\n if ans.len() > f + 2 {\n let extra_sum = ans[f+2..].iter().sum::();\n ans[f+1] += extra_sum;\n ans.truncate(f + 2);\n }\n\n\n // for j in 0..=k, ans'[min(i, j)] += ans[i];\n\n if depth < n {\n ans = ans\n .iter()\n .enumerate()\n .rev()\n .scan(Mod::raw(0), |sum, (i, ansi)| {\n let mut ret = if i <= k { *sum + ansi * Mod::from(k - i + 1) } else { Mod::raw(0) };\n *sum += ansi;\n Some(ret)\n })\n .skip_while(|ansi| ansi.val() == 0)\n .collect::>();\n ans.reverse();\n }\n\n }\n println!(\"{}\", if f < ans.len() { ans[f] } else { Mod::raw(0) });\n}\n\n// input macro with modifications (to better align with proconio)\n// based on https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\n\n#[macro_export]\nmacro_rules! input {\n (@lock_stdin $reader:ident) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut $reader = move || -> String {\n unsafe {\n String::from_utf8_unchecked(\n bytes\n .by_ref()\n .map_while(Result::ok)\n .skip_while(|c| c.is_ascii_whitespace())\n .take_while(|c| !c.is_ascii_whitespace())\n .collect()\n )\n }\n };\n };\n\n (@inner $reader:ident) => {};\n (@inner $reader:ident, ) => {};\n\n (@inner $reader:ident, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($reader, $t);\n input!{@inner $reader $($r)*}\n };\n\n (@inner $reader:ident, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($reader, $t);\n input!{@inner $reader $($r)*}\n };\n\n (@inner $reader:ident, $($r:tt)*) => {\n compile_error!(stringify!(unable to read $($r)*))\n };\n\n (line = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_ascii_whitespace();\n let mut next = || { iter.next().unwrap_or_default() };\n input!{@inner next, $($r)*}\n };\n (name = $reader:ident, $($r:tt)*) => {\n input!{@lock_stdin $reader};\n input!{@inner $reader, $($r)*}\n };\n (use $reader:ident, $($r:tt)*) => {\n input!{@inner $reader, $($r)*}\n };\n ($($r:tt)*) => {\n input!{@lock_stdin reader};\n input!{@inner reader, $($r)*};\n };\n}\n\n#[macro_export]\nmacro_rules! read_value {\n ($reader:ident, ( $($t:tt),* )) => {\n ( $(read_value!($reader, $t)),* )\n };\n\n ($reader:ident, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($reader, $t)).collect::>()\n };\n\n ($reader:ident, chars) => {\n read_value!($reader, String).chars().collect::>()\n };\n\n ($reader:ident, bytes) => {\n read_value!($reader, String).into_bytes()\n };\n\n ($reader:ident, usize1) => {\n read_value!($reader, usize) - 1\n };\n\n ($reader:ident, $t:tt) => {\n $reader().parse::<$t>().expect(stringify!(parse error($t)))\n };\n}\n\n//https://github.com/rust-lang-ja/ac-library-rs\n\npub mod convolution {\n macro_rules! modulus {\n ($($name:ident),*) => {\n $(\n #[derive(Copy, Clone, Eq, PartialEq)]\n enum $name {}\n\n impl Modulus for $name {\n const VALUE: u32 = $name as _;\n const HINT_VALUE_IS_PRIME: bool = true;\n\n fn butterfly_cache() -> &'static ::std::thread::LocalKey<::std::cell::RefCell<::std::option::Option<$crate::modint::ButterflyCache>>> {\n thread_local! {\n static BUTTERFLY_CACHE: ::std::cell::RefCell<::std::option::Option<$crate::modint::ButterflyCache<$name>>> = ::std::default::Default::default();\n }\n &BUTTERFLY_CACHE\n }\n }\n )*\n };\n}\n\n use crate::{\n internal_bit, internal_math,\n modint::{ButterflyCache, Modulus, RemEuclidU32, StaticModInt},\n };\n use std::{\n cmp,\n convert::{TryFrom, TryInto as _},\n fmt,\n };\n\n #[allow(clippy::many_single_char_names)]\n pub fn convolution(a: &[StaticModInt], b: &[StaticModInt]) -> Vec>\n where\n M: Modulus,\n {\n if a.is_empty() || b.is_empty() {\n return vec![];\n }\n let (n, m) = (a.len(), b.len());\n\n if cmp::min(n, m) <= 60 {\n let (n, m, a, b) = if n < m { (m, n, b, a) } else { (n, m, a, b) };\n let mut ans = vec![StaticModInt::new(0); n + m - 1];\n for i in 0..n {\n for j in 0..m {\n ans[i + j] += a[i] * b[j];\n }\n }\n return ans;\n }\n\n let (mut a, mut b) = (a.to_owned(), b.to_owned());\n let z = 1 << internal_bit::ceil_pow2((n + m - 1) as _);\n a.resize(z, StaticModInt::raw(0));\n butterfly(&mut a);\n b.resize(z, StaticModInt::raw(0));\n butterfly(&mut b);\n for (a, b) in a.iter_mut().zip(&b) {\n *a *= b;\n }\n butterfly_inv(&mut a);\n a.resize(n + m - 1, StaticModInt::raw(0));\n let iz = StaticModInt::new(z).inv();\n for a in &mut a {\n *a *= iz;\n }\n a\n }\n\n pub fn convolution_raw(a: &[T], b: &[T]) -> Vec\n where\n T: RemEuclidU32 + TryFrom + Clone,\n T::Error: fmt::Debug,\n M: Modulus,\n {\n let a = a.iter().cloned().map(Into::into).collect::>();\n let b = b.iter().cloned().map(Into::into).collect::>();\n convolution::(&a, &b)\n .into_iter()\n .map(|z| {\n z.val()\n .try_into()\n .expect(\"the numeric type is smaller than the modulus\")\n })\n .collect()\n }\n\n #[allow(clippy::many_single_char_names)]\n pub fn convolution_i64(a: &[i64], b: &[i64]) -> Vec {\n const M1: u64 = 754_974_721; // 2^24\n const M2: u64 = 167_772_161; // 2^25\n const M3: u64 = 469_762_049; // 2^26\n const M2M3: u64 = M2 * M3;\n const M1M3: u64 = M1 * M3;\n const M1M2: u64 = M1 * M2;\n const M1M2M3: u64 = M1M2.wrapping_mul(M3);\n\n modulus!(M1, M2, M3);\n\n if a.is_empty() || b.is_empty() {\n return vec![];\n }\n\n let (_, i1) = internal_math::inv_gcd(M2M3 as _, M1 as _);\n let (_, i2) = internal_math::inv_gcd(M1M3 as _, M2 as _);\n let (_, i3) = internal_math::inv_gcd(M1M2 as _, M3 as _);\n\n let c1 = convolution_raw::(a, b);\n let c2 = convolution_raw::(a, b);\n let c3 = convolution_raw::(a, b);\n\n c1.into_iter()\n .zip(c2)\n .zip(c3)\n .map(|((c1, c2), c3)| {\n const OFFSET: &[u64] = &[0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3];\n\n let mut x = [(c1, i1, M1, M2M3), (c2, i2, M2, M1M3), (c3, i3, M3, M1M2)]\n .iter()\n .map(|&(c, i, m1, m2)| {\n c.wrapping_mul(i).rem_euclid(m1 as _).wrapping_mul(m2 as _)\n })\n .fold(0, i64::wrapping_add);\n\n let mut diff = c1 - internal_math::safe_mod(x, M1 as _);\n if diff < 0 {\n diff += M1 as i64;\n }\n x = x.wrapping_sub(OFFSET[diff.rem_euclid(5) as usize] as _);\n x\n })\n .collect()\n }\n\n #[allow(clippy::many_single_char_names)]\n fn butterfly(a: &mut [StaticModInt]) {\n let n = a.len();\n let h = internal_bit::ceil_pow2(n as u32);\n\n M::butterfly_cache().with(|cache| {\n let mut cache = cache.borrow_mut();\n let ButterflyCache { sum_e, .. } = cache.get_or_insert_with(prepare);\n for ph in 1..=h {\n let w = 1 << (ph - 1);\n let p = 1 << (h - ph);\n let mut now = StaticModInt::::new(1);\n for s in 0..w {\n let offset = s << (h - ph + 1);\n for i in 0..p {\n let l = a[i + offset];\n let r = a[i + offset + p] * now;\n a[i + offset] = l + r;\n a[i + offset + p] = l - r;\n }\n now *= sum_e[(!s).trailing_zeros() as usize];\n }\n }\n });\n }\n\n #[allow(clippy::many_single_char_names)]\n fn butterfly_inv(a: &mut [StaticModInt]) {\n let n = a.len();\n let h = internal_bit::ceil_pow2(n as u32);\n\n M::butterfly_cache().with(|cache| {\n let mut cache = cache.borrow_mut();\n let ButterflyCache { sum_ie, .. } = cache.get_or_insert_with(prepare);\n for ph in (1..=h).rev() {\n let w = 1 << (ph - 1);\n let p = 1 << (h - ph);\n let mut inow = StaticModInt::::new(1);\n for s in 0..w {\n let offset = s << (h - ph + 1);\n for i in 0..p {\n let l = a[i + offset];\n let r = a[i + offset + p];\n a[i + offset] = l + r;\n a[i + offset + p] = StaticModInt::new(M::VALUE + l.val() - r.val()) * inow;\n }\n inow *= sum_ie[(!s).trailing_zeros() as usize];\n }\n }\n });\n }\n\n fn prepare() -> ButterflyCache {\n let g = StaticModInt::::raw(internal_math::primitive_root(M::VALUE as i32) as u32);\n let mut es = [StaticModInt::::raw(0); 30]; // es[i]^(2^(2+i)) == 1\n let mut ies = [StaticModInt::::raw(0); 30];\n let cnt2 = (M::VALUE - 1).trailing_zeros() as usize;\n let mut e = g.pow(((M::VALUE - 1) >> cnt2).into());\n let mut ie = e.inv();\n for i in (2..=cnt2).rev() {\n es[i - 2] = e;\n ies[i - 2] = ie;\n e *= e;\n ie *= ie;\n }\n let sum_e = es\n .iter()\n .scan(StaticModInt::new(1), |acc, e| {\n *acc *= e;\n Some(*acc)\n })\n .collect();\n let sum_ie = ies\n .iter()\n .scan(StaticModInt::new(1), |acc, ie| {\n *acc *= ie;\n Some(*acc)\n })\n .collect();\n ButterflyCache { sum_e, sum_ie }\n }\n}\npub mod internal_bit {\n\n #[allow(dead_code)]\n pub(crate) fn ceil_pow2(n: u32) -> u32 {\n 32 - n.saturating_sub(1).leading_zeros()\n }\n}\npub mod internal_math {\n #![allow(dead_code)]\n use std::mem::swap;\n\n pub(crate) fn safe_mod(mut x: i64, m: i64) -> i64 {\n x %= m;\n if x < 0 {\n x += m;\n }\n x\n }\n\n pub(crate) struct Barrett {\n pub(crate) _m: u32,\n pub(crate) im: u64,\n }\n\n impl Barrett {\n pub(crate) fn new(m: u32) -> Barrett {\n Barrett {\n _m: m,\n im: (-1i64 as u64 / m as u64).wrapping_add(1),\n }\n }\n\n pub(crate) fn umod(&self) -> u32 {\n self._m\n }\n\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn mul(&self, a: u32, b: u32) -> u32 {\n mul_mod(a, b, self._m, self.im)\n }\n }\n\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn mul_mod(a: u32, b: u32, m: u32, im: u64) -> u32 {\n let mut z = a as u64;\n z *= b as u64;\n let x = (((z as u128) * (im as u128)) >> 64) as u64;\n let mut v = z.wrapping_sub(x.wrapping_mul(m as u64)) as u32;\n if m <= v {\n v = v.wrapping_add(m);\n }\n v\n }\n\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn pow_mod(x: i64, mut n: i64, m: i32) -> i64 {\n if m == 1 {\n return 0;\n }\n let _m = m as u32;\n let mut r: u64 = 1;\n let mut y: u64 = safe_mod(x, m as i64) as u64;\n while n != 0 {\n if (n & 1) > 0 {\n r = (r * y) % (_m as u64);\n }\n y = (y * y) % (_m as u64);\n n >>= 1;\n }\n r as i64\n }\n\n pub(crate) fn is_prime(n: i32) -> bool {\n let n = n as i64;\n match n {\n _ if n <= 1 => return false,\n 2 | 7 | 61 => return true,\n _ if n % 2 == 0 => return false,\n _ => {}\n }\n let mut d = n - 1;\n while d % 2 == 0 {\n d /= 2;\n }\n for &a in &[2, 7, 61] {\n let mut t = d;\n let mut y = pow_mod(a, t, n as i32);\n while t != n - 1 && y != 1 && y != n - 1 {\n y = y * y % n;\n t <<= 1;\n }\n if y != n - 1 && t % 2 == 0 {\n return false;\n }\n }\n true\n }\n\n #[allow(clippy::many_single_char_names)]\n pub(crate) fn inv_gcd(a: i64, b: i64) -> (i64, i64) {\n let a = safe_mod(a, b);\n if a == 0 {\n return (b, 0);\n }\n\n let mut s = b;\n let mut t = a;\n let mut m0 = 0;\n let mut m1 = 1;\n\n while t != 0 {\n let u = s / t;\n s -= t * u;\n m0 -= m1 * u; // |m1 * u| <= |m1| * s <= b\n\n swap(&mut s, &mut t);\n swap(&mut m0, &mut m1);\n }\n if m0 < 0 {\n m0 += b / s;\n }\n (s, m0)\n }\n\n pub(crate) fn primitive_root(m: i32) -> i32 {\n match m {\n 2 => return 1,\n 167_772_161 => return 3,\n 469_762_049 => return 3,\n 754_974_721 => return 11,\n 998_244_353 => return 3,\n _ => {}\n }\n\n let mut divs = [0; 20];\n divs[0] = 2;\n let mut cnt = 1;\n let mut x = (m - 1) / 2;\n while x % 2 == 0 {\n x /= 2;\n }\n for i in (3..std::i32::MAX).step_by(2) {\n if i as i64 * i as i64 > x as i64 {\n break;\n }\n if x % i == 0 {\n divs[cnt] = i;\n cnt += 1;\n while x % i == 0 {\n x /= i;\n }\n }\n }\n if x > 1 {\n divs[cnt] = x;\n cnt += 1;\n }\n let mut g = 2;\n loop {\n if (0..cnt).all(|i| pow_mod(g, ((m - 1) / divs[i]) as i64, m) != 1) {\n break g as i32;\n }\n g += 1;\n }\n }\n}\npub mod modint {\n\n use crate::internal_math;\n use std::{\n cell::RefCell,\n convert::{Infallible, TryInto as _},\n fmt,\n hash::{Hash, Hasher},\n iter::{Product, Sum},\n marker::PhantomData,\n ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},\n str::FromStr,\n sync::atomic::{self, AtomicU32, AtomicU64},\n thread::LocalKey,\n };\n\n pub type ModInt1000000007 = StaticModInt;\n pub type ModInt998244353 = StaticModInt;\n pub type ModInt = DynamicModInt;\n\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct StaticModInt {\n val: u32,\n phantom: PhantomData M>,\n }\n\n impl StaticModInt {\n #[inline(always)]\n pub fn modulus() -> u32 {\n M::VALUE\n }\n\n #[inline]\n pub fn new(val: T) -> Self {\n Self::raw(val.rem_euclid_u32(M::VALUE))\n }\n\n #[inline]\n pub fn raw(val: u32) -> Self {\n Self {\n val,\n phantom: PhantomData,\n }\n }\n\n #[inline]\n pub fn val(self) -> u32 {\n self.val\n }\n\n #[inline]\n pub fn pow(self, n: u64) -> Self {\n ::pow(self, n)\n }\n\n #[inline]\n pub fn inv(self) -> Self {\n if M::HINT_VALUE_IS_PRIME {\n if self.val() == 0 {\n panic!(\"attempt to divide by zero\");\n }\n debug_assert!(\n internal_math::is_prime(M::VALUE.try_into().unwrap()),\n \"{} is not a prime number\",\n M::VALUE,\n );\n self.pow((M::VALUE - 2).into())\n } else {\n Self::inv_for_non_prime_modulus(self)\n }\n }\n }\n\n impl ModIntBase for StaticModInt {\n #[inline(always)]\n fn modulus() -> u32 {\n Self::modulus()\n }\n\n #[inline]\n fn raw(val: u32) -> Self {\n Self::raw(val)\n }\n\n #[inline]\n fn val(self) -> u32 {\n self.val()\n }\n\n #[inline]\n fn inv(self) -> Self {\n self.inv()\n }\n }\n\n pub trait Modulus: 'static + Copy + Eq {\n const VALUE: u32;\n const HINT_VALUE_IS_PRIME: bool;\n\n fn butterfly_cache() -> &'static LocalKey>>>;\n }\n\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum Mod1000000007 {}\n\n impl Modulus for Mod1000000007 {\n const VALUE: u32 = 1_000_000_007;\n const HINT_VALUE_IS_PRIME: bool = true;\n\n fn butterfly_cache() -> &'static LocalKey>>> {\n thread_local! {\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\n }\n &BUTTERFLY_CACHE\n }\n }\n\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum Mod998244353 {}\n\n impl Modulus for Mod998244353 {\n const VALUE: u32 = 998_244_353;\n const HINT_VALUE_IS_PRIME: bool = true;\n\n fn butterfly_cache() -> &'static LocalKey>>> {\n thread_local! {\n static BUTTERFLY_CACHE: RefCell>> = RefCell::default();\n }\n &BUTTERFLY_CACHE\n }\n }\n\n #[allow(dead_code)]\n pub struct ButterflyCache {\n pub(crate) sum_e: Vec>,\n pub(crate) sum_ie: Vec>,\n }\n\n #[derive(Copy, Clone, Eq, PartialEq)]\n #[repr(transparent)]\n pub struct DynamicModInt {\n val: u32,\n phantom: PhantomData I>,\n }\n\n impl DynamicModInt {\n #[inline]\n pub fn modulus() -> u32 {\n I::companion_barrett().umod()\n }\n\n #[inline]\n pub fn set_modulus(modulus: u32) {\n if modulus == 0 {\n panic!(\"the modulus must not be 0\");\n }\n I::companion_barrett().update(modulus);\n }\n\n #[inline]\n pub fn new(val: T) -> Self {\n ::new(val)\n }\n\n #[inline]\n pub fn raw(val: u32) -> Self {\n Self {\n val,\n phantom: PhantomData,\n }\n }\n\n #[inline]\n pub fn val(self) -> u32 {\n self.val\n }\n\n #[inline]\n pub fn pow(self, n: u64) -> Self {\n ::pow(self, n)\n }\n\n #[inline]\n pub fn inv(self) -> Self {\n Self::inv_for_non_prime_modulus(self)\n }\n }\n\n impl ModIntBase for DynamicModInt {\n #[inline]\n fn modulus() -> u32 {\n Self::modulus()\n }\n\n #[inline]\n fn raw(val: u32) -> Self {\n Self::raw(val)\n }\n\n #[inline]\n fn val(self) -> u32 {\n self.val()\n }\n\n #[inline]\n fn inv(self) -> Self {\n self.inv()\n }\n }\n\n pub trait Id: 'static + Copy + Eq {\n fn companion_barrett() -> &'static Barrett;\n }\n\n #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]\n pub enum DefaultId {}\n\n impl Id for DefaultId {\n fn companion_barrett() -> &'static Barrett {\n static BARRETT: Barrett = Barrett::default();\n &BARRETT\n }\n }\n\n pub struct Barrett {\n m: AtomicU32,\n im: AtomicU64,\n }\n\n impl Barrett {\n #[inline]\n pub const fn new(m: u32) -> Self {\n Self {\n m: AtomicU32::new(m),\n im: AtomicU64::new((-1i64 as u64 / m as u64).wrapping_add(1)),\n }\n }\n\n #[inline]\n const fn default() -> Self {\n Self::new(998_244_353)\n }\n\n #[inline]\n fn update(&self, m: u32) {\n let im = (-1i64 as u64 / m as u64).wrapping_add(1);\n self.m.store(m, atomic::Ordering::SeqCst);\n self.im.store(im, atomic::Ordering::SeqCst);\n }\n\n #[inline]\n fn umod(&self) -> u32 {\n self.m.load(atomic::Ordering::SeqCst)\n }\n\n #[inline]\n fn mul(&self, a: u32, b: u32) -> u32 {\n let m = self.m.load(atomic::Ordering::SeqCst);\n let im = self.im.load(atomic::Ordering::SeqCst);\n internal_math::mul_mod(a, b, m, im)\n }\n }\n\n impl Default for Barrett {\n #[inline]\n fn default() -> Self {\n Self::default()\n }\n }\n\n pub trait ModIntBase:\n Default\n + FromStr\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + From\n + Copy\n + Eq\n + Hash\n + fmt::Display\n + fmt::Debug\n + Neg\n + Add\n + Sub\n + Mul\n + Div\n + AddAssign\n + SubAssign\n + MulAssign\n + DivAssign\n {\n fn modulus() -> u32;\n\n fn raw(val: u32) -> Self;\n\n fn val(self) -> u32;\n\n fn inv(self) -> Self;\n\n #[inline]\n fn new(val: T) -> Self {\n Self::raw(val.rem_euclid_u32(Self::modulus()))\n }\n\n #[inline]\n fn pow(self, mut n: u64) -> Self {\n let mut x = self;\n let mut r = Self::raw(1);\n while n > 0 {\n if n & 1 == 1 {\n r *= x;\n }\n x *= x;\n n >>= 1;\n }\n r\n }\n }\n\n pub trait RemEuclidU32 {\n fn rem_euclid_u32(self, modulus: u32) -> u32;\n }\n\n macro_rules! impl_rem_euclid_u32_for_small_signed {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self as i64).rem_euclid(i64::from(modulus)) as _\n }\n }\n )*\n }\n}\n\n impl_rem_euclid_u32_for_small_signed!(i8, i16, i32, i64, isize);\n\n impl RemEuclidU32 for i128 {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self.rem_euclid(i128::from(modulus)) as _\n }\n }\n\n macro_rules! impl_rem_euclid_u32_for_small_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n self as u32 % modulus\n }\n }\n )*\n }\n}\n\n macro_rules! impl_rem_euclid_u32_for_large_unsigned {\n ($($ty:tt),*) => {\n $(\n impl RemEuclidU32 for $ty {\n #[inline]\n fn rem_euclid_u32(self, modulus: u32) -> u32 {\n (self % (modulus as $ty)) as _\n }\n }\n )*\n }\n}\n\n impl_rem_euclid_u32_for_small_unsigned!(u8, u16, u32);\n impl_rem_euclid_u32_for_large_unsigned!(u64, u128);\n\n #[cfg(target_pointer_width = \"32\")]\n impl_rem_euclid_u32_for_small_unsigned!(usize);\n\n #[cfg(target_pointer_width = \"64\")]\n impl_rem_euclid_u32_for_large_unsigned!(usize);\n\n trait InternalImplementations: ModIntBase {\n #[inline]\n fn inv_for_non_prime_modulus(this: Self) -> Self {\n let (gcd, x) = internal_math::inv_gcd(this.val().into(), Self::modulus().into());\n if gcd != 1 {\n panic!(\"the multiplicative inverse does not exist\");\n }\n Self::new(x)\n }\n\n #[inline]\n fn default_impl() -> Self {\n Self::raw(0)\n }\n\n #[inline]\n fn from_str_impl(s: &str) -> Result {\n Ok(s.parse::()\n .map(Self::new)\n .unwrap_or_else(|_| todo!(\"parsing as an arbitrary precision integer?\")))\n }\n\n #[inline]\n fn hash_impl(this: &Self, state: &mut impl Hasher) {\n this.val().hash(state)\n }\n\n #[inline]\n fn display_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\n fmt::Display::fmt(&this.val(), f)\n }\n\n #[inline]\n fn debug_impl(this: &Self, f: &mut fmt::Formatter) -> fmt::Result {\n fmt::Debug::fmt(&this.val(), f)\n }\n\n #[inline]\n fn neg_impl(this: Self) -> Self {\n Self::sub_impl(Self::raw(0), this)\n }\n\n #[inline]\n fn add_impl(lhs: Self, rhs: Self) -> Self {\n let modulus = Self::modulus();\n let mut val = lhs.val() + rhs.val();\n if val >= modulus {\n val -= modulus;\n }\n Self::raw(val)\n }\n\n #[inline]\n fn sub_impl(lhs: Self, rhs: Self) -> Self {\n let modulus = Self::modulus();\n let mut val = lhs.val().wrapping_sub(rhs.val());\n if val >= modulus {\n val = val.wrapping_add(modulus)\n }\n Self::raw(val)\n }\n\n fn mul_impl(lhs: Self, rhs: Self) -> Self;\n\n #[inline]\n fn div_impl(lhs: Self, rhs: Self) -> Self {\n Self::mul_impl(lhs, rhs.inv())\n }\n }\n\n impl InternalImplementations for StaticModInt {\n #[inline]\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\n Self::raw((u64::from(lhs.val()) * u64::from(rhs.val()) % u64::from(M::VALUE)) as u32)\n }\n }\n\n impl InternalImplementations for DynamicModInt {\n #[inline]\n fn mul_impl(lhs: Self, rhs: Self) -> Self {\n Self::raw(I::companion_barrett().mul(lhs.val, rhs.val))\n }\n }\n\n macro_rules! impl_basic_traits {\n () => {};\n (impl <$generic_param:ident : $generic_param_bound:tt> _ for $self:ty; $($rest:tt)*) => {\n impl <$generic_param: $generic_param_bound> Default for $self {\n #[inline]\n fn default() -> Self {\n Self::default_impl()\n }\n }\n\n impl <$generic_param: $generic_param_bound> FromStr for $self {\n type Err = Infallible;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::from_str_impl(s)\n }\n }\n\n impl<$generic_param: $generic_param_bound, V: RemEuclidU32> From for $self {\n #[inline]\n fn from(from: V) -> Self {\n Self::new(from)\n }\n }\n\n #[allow(clippy::derive_hash_xor_eq)]\n impl<$generic_param: $generic_param_bound> Hash for $self {\n #[inline]\n fn hash(&self, state: &mut H) {\n Self::hash_impl(self, state)\n }\n }\n\n impl<$generic_param: $generic_param_bound> fmt::Display for $self {\n #[inline]\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Self::display_impl(self, f)\n }\n }\n\n impl<$generic_param: $generic_param_bound> fmt::Debug for $self {\n #[inline]\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n Self::debug_impl(self, f)\n }\n }\n\n impl<$generic_param: $generic_param_bound> Neg for $self {\n type Output = $self;\n\n #[inline]\n fn neg(self) -> $self {\n Self::neg_impl(self)\n }\n }\n\n impl<$generic_param: $generic_param_bound> Neg for &'_ $self {\n type Output = $self;\n\n #[inline]\n fn neg(self) -> $self {\n <$self>::neg_impl(*self)\n }\n }\n\n impl_basic_traits!($($rest)*);\n };\n}\n\n impl_basic_traits! {\n impl _ for StaticModInt ;\n impl _ for DynamicModInt;\n }\n\n macro_rules! impl_bin_ops {\n () => {};\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~ <$rhs_ty:ty> -> $output:ty { { $lhs_body:expr } ~ { $rhs_body:expr } } $($rest:tt)*) => {\n impl <$($generic_param: $generic_param_bound),*> Add<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn add(self, rhs: $rhs_ty) -> $output {\n <$output>::add_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Sub<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn sub(self, rhs: $rhs_ty) -> $output {\n <$output>::sub_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Mul<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn mul(self, rhs: $rhs_ty) -> $output {\n <$output>::mul_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> Div<$rhs_ty> for $lhs_ty {\n type Output = $output;\n\n #[inline]\n fn div(self, rhs: $rhs_ty) -> $output {\n <$output>::div_impl(apply($lhs_body, self), apply($rhs_body, rhs))\n }\n }\n\n impl_bin_ops!($($rest)*);\n };\n}\n\n macro_rules! impl_assign_ops {\n () => {};\n (for<$($generic_param:ident : $generic_param_bound:tt),*> <$lhs_ty:ty> ~= <$rhs_ty:ty> { _ ~= { $rhs_body:expr } } $($rest:tt)*) => {\n impl <$($generic_param: $generic_param_bound),*> AddAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn add_assign(&mut self, rhs: $rhs_ty) {\n *self = *self + apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> SubAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn sub_assign(&mut self, rhs: $rhs_ty) {\n *self = *self - apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> MulAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn mul_assign(&mut self, rhs: $rhs_ty) {\n *self = *self * apply($rhs_body, rhs);\n }\n }\n\n impl <$($generic_param: $generic_param_bound),*> DivAssign<$rhs_ty> for $lhs_ty {\n #[inline]\n fn div_assign(&mut self, rhs: $rhs_ty) {\n *self = *self / apply($rhs_body, rhs);\n }\n }\n\n impl_assign_ops!($($rest)*);\n };\n}\n\n #[inline]\n fn apply O, X, O>(f: F, x: X) -> O {\n f(x)\n }\n\n impl_bin_ops! {\n for > ~ > -> StaticModInt { { |x| x } ~ { |x| x } }\n for > ~ <&'_ StaticModInt > -> StaticModInt { { |x| x } ~ { |&x| x } }\n for <&'_ StaticModInt > ~ > -> StaticModInt { { |&x| x } ~ { |x| x } }\n for <&'_ StaticModInt > ~ <&'_ StaticModInt > -> StaticModInt { { |&x| x } ~ { |&x| x } }\n for > ~ > -> DynamicModInt { { |x| x } ~ { |x| x } }\n for > ~ <&'_ DynamicModInt> -> DynamicModInt { { |x| x } ~ { |&x| x } }\n for <&'_ DynamicModInt> ~ > -> DynamicModInt { { |&x| x } ~ { |x| x } }\n for <&'_ DynamicModInt> ~ <&'_ DynamicModInt> -> DynamicModInt { { |&x| x } ~ { |&x| x } }\n\n for > ~ -> StaticModInt { { |x| x } ~ { StaticModInt::::new } }\n for > ~ -> DynamicModInt { { |x| x } ~ { DynamicModInt::::new } }\n }\n\n impl_assign_ops! {\n for > ~= > { _ ~= { |x| x } }\n for > ~= <&'_ StaticModInt > { _ ~= { |&x| x } }\n for > ~= > { _ ~= { |x| x } }\n for > ~= <&'_ DynamicModInt> { _ ~= { |&x| x } }\n\n for > ~= { _ ~= { StaticModInt::::new } }\n for > ~= { _ ~= { DynamicModInt::::new } }\n }\n\n macro_rules! impl_folding {\n () => {};\n (impl<$generic_param:ident : $generic_param_bound:tt> $trait:ident<_> for $self:ty { fn $method:ident(_) -> _ { _($unit:expr, $op:expr) } } $($rest:tt)*) => {\n impl<$generic_param: $generic_param_bound> $trait for $self {\n #[inline]\n fn $method(iter: S) -> Self\n where\n S: Iterator,\n {\n iter.fold($unit, $op)\n }\n }\n\n impl<'a, $generic_param: $generic_param_bound> $trait<&'a Self> for $self {\n #[inline]\n fn $method(iter: S) -> Self\n where\n S: Iterator,\n {\n iter.fold($unit, $op)\n }\n }\n\n impl_folding!($($rest)*);\n };\n}\n\n impl_folding! {\n impl Sum<_> for StaticModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\n impl Product<_> for StaticModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\n impl Sum<_> for DynamicModInt { fn sum(_) -> _ { _(Self::raw(0), Add::add) } }\n impl Product<_> for DynamicModInt { fn product(_) -> _ { _(Self::raw(1), Mul::mul) } }\n }\n}\nuse convolution::*;\nuse modint::*;\n", "lang_cluster": "Rust", "tags": ["brute force", "flows", "math", "dp", "fft", "bitmasks", "graphs", "meet-in-the-middle", "trees"], "code_uid": "355edae91a8b9bb190c3ebd329258268", "src_uid": "4b8161259545e44c7d1046be2e4fe014", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(non_snake_case)]\n\nuse std::cmp::{max, min, Ordering};\nuse std::collections::*;\nuse std::fmt::{Debug, Formatter};\nuse std::io::*;\nuse std::ops::*;\nuse std::*;\n\n// -----------------------------------------------\n// Framework\n// -----------------------------------------------\n\n#[allow(unused_macros)]\nmacro_rules! read {\n ([$t:ty] ; $n:expr) =>\n ((0..$n).map(|_| read!([$t])).collect::>());\n ($($t:ty),+ ; $n:expr) =>\n ((0..$n).map(|_| read!($($t),+)).collect::>());\n ([$t:ty]) =>\n (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::>());\n ($t:ty) =>\n (rl().parse::<$t>().unwrap());\n ($($t:ty),*) => {{\n let buf = rl();\n let mut w = buf.split_whitespace();\n ($(w.next().unwrap().parse::<$t>().unwrap()),*)\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($arg:expr),*) => {\n #[cfg(debug_assertions)]\n {\n let entries = [$(&stringify!([$arg]:), &$arg as &Debug),*];\n stderr().write_fmt(format_args!(\"{:#?}\\n\", entries)).unwrap();\n }\n };\n}\n\n#[allow(dead_code)]\nfn rl() -> String {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim_right().to_owned()\n}\n\ntrait IteratorExt: Iterator + Sized {\n fn vec(self) -> Vec {\n self.collect()\n }\n}\n\nimpl IteratorExt for T {}\n\n// -----------------------------------------------\n// Solution\n// -----------------------------------------------\n\nfn is_vowel(c: char) -> bool {\n match c {\n 'a' | 'i' | 'u' | 'e' | 'o' => true,\n _ => false,\n }\n}\n\npub fn main() {\n let S = rl().chars().vec();\n\n let mut ok = true;\n for i in 0..S.len() {\n if S[i] == 'n' || is_vowel(S[i]) || (i + 1 < S.len() && is_vowel(S[i + 1])) {\n continue;\n }\n\n ok = false;\n break;\n }\n\n println!(\"{}\", if ok { \"YES\" } else { \"NO\" });\n return;\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "6e0381953c20b7746195292d43008ac1", "src_uid": "a83144ba7d4906b7692456f27b0ef7d4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin()\n .read_line(& mut s)\n .expect(\"Deu Ruim\");\n \n let s = s.trim();\n let n = s.len();\n\n let mut res = match &s[n-1..n] {\n \"a\"|\"e\"|\"i\"|\"o\"|\"u\"|\"n\" => true,\n _ => false\n };\n\n for i in 0..n-1 {\n\n match (&s[i..i+1], &s[i+1..i+2]) {\n\n (\"a\",_)|(\"e\",_)|(\"i\",_)|(\"o\",_)|(\"u\", _) => (),\n (\"n\", _) => (),\n (_,\"a\")|(_,\"e\")|(_,\"i\")|(_,\"o\")|(_,\"u\") => (),\n (_, _) => res = false,\n }\n }\n\n match res {\n true => println!(\"YES\", ),\n _ => println!(\"NO\", )\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "a47492716082fab0f76429fbfa172efc", "src_uid": "a83144ba7d4906b7692456f27b0ef7d4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn less(n: u64, m: u64, val: u64) -> u64 {\n let mut ptr = 0;\n for i in 1..=n {\n ptr += std::cmp::min(m, val / i);\n }\n return ptr;\n}\n\nfn solve(writer: &mut std::io::BufWriter) {\n let (n, m, k) = parse_line!(u64, u64, u64);\n let mut l = 0;\n let mut r = n * m + 1;\n while l + 1 < r {\n let mid = (l + r) / 2;\n if less(n, m, mid) < k {\n l = mid;\n }else{\n r = mid;\n }\n }\n writeln!(writer, \"{}\", r).unwrap();\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "binary search"], "code_uid": "f7c4d681c8a7cb580a786601ab8a8c5c", "src_uid": "13a918eca30799b240ceb9de47507a26", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input() -> u8 {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim().parse().unwrap()\n}\n\nfn input_split() -> Vec {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let mut k = input();\n let mut months = input_split();\n months.sort_unstable_by(|a, b| b.cmp(&a));\n\n let mut count = 0;\n\n for month in months {\n if k == 0 {\n break;\n }\n count += 1;\n if month > k {\n break;\n } else {\n k -= month;\n }\n }\n\n if count == 12 && k != 0 {\n print!(\"-1\")\n } else {\n print!(\"{}\", count)\n }\n}", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "e4ecbbaaddbcb7be2dbd797634951a9a", "src_uid": "59dfa7a4988375febc5dccc27aca90a8", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// use rand::Rng;\n\nuse std::collections::*;\nuse std::io;\n\nfn trim_newline(s: &mut String) {\n if s.ends_with('\\n') {\n s.pop();\n if s.ends_with('\\r') {\n s.pop();\n }\n }\n}\nmacro_rules! parse_input {\n ($t:ident) => {{\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n trim_newline(&mut input_line);\n input_line.parse::<$t>().unwrap()\n }};\n}\n\nmacro_rules! split_input {\n ($t:ident) => {{\n parse_input!(String)\n .split(\" \")\n .map(|z| z.parse::<$t>().unwrap())\n .collect::>()\n }};\n}\n\nstruct xorrand {\n state: u64,\n}\n#[allow(dead_code)]\nimpl xorrand {\n fn rand(&mut self) -> u64 {\n let mut x = self.state;\n x ^= x << 13;\n x ^= x >> 7;\n x ^= x << 17;\n self.state = x;\n self.state.wrapping_mul(0x2545F4914F6CDD1Du64)\n }\n\n fn randint(&mut self, start: u64, end: u64) -> u64 {\n return (self.rand() % (end - start)) + start;\n }\n\n fn randfloat(&mut self) -> f64 {\n 1.0 / (self.rand() as f64)\n }\n\n fn new(seed: u64) -> xorrand {\n xorrand { state: seed }\n }\n\n fn newtime() -> xorrand {\n let start = std::time::SystemTime::now();\n let ms = start\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap()\n .as_secs();\n xorrand { state: ms }\n }\n\n fn shuffle(&mut self, tgt: &mut Vec) {\n for i in 0..tgt.len() - 1 {\n let j = self.randint(i as u64, tgt.len() as u64) as usize;\n let c = tgt[j].clone();\n tgt[j] = tgt[i].clone();\n tgt[i] = c;\n }\n }\n}\n\nfn main() {\n let s1 = parse_input!(usize);\n let s2 = parse_input!(String);\n let s2 = s2.as_bytes();\n\n let mut idx = 0;\n while idx < s2.len() {\n if s2[idx] == '0' as u8 {\n break;\n }\n idx += 1;\n }\n if idx < s2.len() {\n idx += 1;\n }\n println!(\"{}\", idx);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ed820011a14df50fd1af7d71e101725e", "src_uid": "54cb2e987f2cc06c02c7638ea879a1ab", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n#![allow(unused_macros)]\n// use proconio::input;\nuse std::cmp::{Ordering::*, Reverse};\nuse std::collections::{BTreeMap, BTreeSet, VecDeque, BinaryHeap};\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\nmacro_rules! answer {\n ($out:ident, $ans:expr) => {\n writeln!($out, \"{}\", $ans)\n };\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let _n: usize = scan.token();\n let s: Vec = scan.token::().bytes().map(|b| b - b'0').map(|x| x as u8).collect();\n let t: Vec = s.iter().scan(1, |cin, &x| {\n let y = (x + *cin) & 1;\n *cin = (x + *cin) >> 1;\n Some(y)\n }).collect();\n answer!(out, s.into_iter().zip(t.into_iter()).filter(|(x, y)| x != y).count())\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Mostly copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse [Scanner]\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\n// aka #![feature(bool_to_option)]\ntrait BoolThen {\n fn then_(self, f: impl FnOnce() -> T) -> Option;\n}\n\nimpl BoolThen for bool {\n fn then_(self, f: impl FnOnce() -> T) -> Option {\n if self {\n Some(f())\n } else {\n None\n }\n }\n}\n\ntrait BoolToYes {\n fn yes(self) -> &'static str;\n}\n\nimpl BoolToYes for bool {\n fn yes(self) -> &'static str {\n match self {\n true => \"Yes\",\n false => \"No\",\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "d3f0d556fdd65c2c8d134879e03997a2", "src_uid": "54cb2e987f2cc06c02c7638ea879a1ab", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\nstruct Prng {\n a: i32,\n b: i32,\n m: i32,\n}\n\nimpl Prng {\n pub fn new(a: i32, b: i32, m: i32) -> Self {\n Self { a: a, b: b, m: m }\n }\n \n pub fn next(&self, r: i32) -> i32 {\n (self.a * r + self.b) % self.m \n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let a: i32 = scan.token();\n let b: i32 = scan.token();\n let m: i32 = scan.token();\n let r0: i32 = scan.token();\n\n let gen = Prng::new(a, b, m);\n let mut slow = r0;\n let mut fast = r0;\n loop {\n slow = gen.next(slow);\n fast = gen.next(gen.next(fast));\n if slow == fast {\n break;\n }\n }\n slow = r0;\n while slow != fast {\n slow = gen.next(slow);\n fast = gen.next(fast);\n }\n let mut period = 0;\n loop {\n slow = gen.next(slow);\n period += 1;\n if slow == fast {\n break;\n }\n }\n writeln!(out, \"{}\", period).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "c901855f21c95688e4be400e1e591a3e", "src_uid": "9137197ee1b781cd5cc77c46f50b9012", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/* This code was written by\nRussell Emerine - linguist,\nmathematician, coder,\nmusician, and metalhead. */\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\n\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scanner = Scanner::default();\n let mut a: usize = scanner.next();\n while a > 9 {\n a = a\n .to_string()\n .chars()\n .map(|c| c.to_string().parse::().unwrap())\n .sum()\n }\n println!(\"{}\", a)\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "e13d20557de1f7a4d89a9b047afb7245", "src_uid": "477a67877367dc68b3bf5143120ff45d", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\r\nuse std::convert::TryInto;\r\n\r\nstruct DigitalRootIt {\r\n cur: Vec\r\n}\r\n\r\nimpl Iterator for DigitalRootIt {\r\n type Item = Vec;\r\n fn next (&mut self) -> Option> {\r\n let mut sum: u64 = self.cur.iter()\r\n .map(|d| *d as u64).sum();\r\n let mut ds = Vec::::new();\r\n while sum > 0 {\r\n ds.push((sum % 10).try_into().unwrap_or(0));\r\n sum /= 10;\r\n }\r\n if ds.is_empty() {\r\n ds.push(0);\r\n }\r\n self.cur = ds;\r\n Some(self.cur.clone())\r\n }\r\n}\r\n\r\ntrait DigitalRootable {\r\n fn digital_rooted(&mut self) -> DigitalRootIt;\r\n}\r\n\r\nimpl DigitalRootable for I \r\n where I: Iterator {\r\n fn digital_rooted(&mut self) -> DigitalRootIt {\r\n let collected = self.collect::>();\r\n DigitalRootIt {cur: collected }\r\n }\r\n}\r\n\r\nfn main() {\r\n let result = std::io::stdin().lock()\r\n .lines().next().unwrap().unwrap()\r\n .chars().map(|c| c.to_digit(10).unwrap_or(0) as u8)\r\n .digital_rooted()\r\n .skip_while(|digits| digits.len() > 1)\r\n .next().unwrap_or(vec![0]);\r\n println!(\"{}\", result.first().unwrap_or(&0));\r\n}\r\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "c22c5ec9b9bac8ee90d5ffbca01a87a5", "src_uid": "477a67877367dc68b3bf5143120ff45d", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nuse std::cmp::*;\n\nfn run() {\n input! {\n n: usize,\n p: [(chars, i32, i32); n],\n }\n let p = p\n .into_iter()\n .map(|p| ((p.0[0] == 'B') as usize, p.1, p.2))\n .collect::>();\n let mut sum = vec![([0, 0], 0, 0)];\n for &(x, y, z) in p.iter() {\n for i in 0..sum.len() {\n let (mut a, mut b, mut c) = sum[i];\n a[x] += 1;\n b += y;\n c += z;\n sum.push((a, b, c));\n }\n }\n let mut now = std::collections::BTreeMap::new();\n now.insert((0, 0, 0), 0);\n for _ in 0..n {\n let mut next = std::collections::BTreeMap::new();\n for ((bit, rem_a, rem_b), v) in now {\n assert!(rem_a == 0 || rem_b == 0);\n let (cnt, _, _) = sum[bit];\n for (i, &(_, a, b)) in p.iter().enumerate() {\n if bit >> i & 1 == 1 {\n continue;\n }\n let p = max(0, a - cnt[0]);\n let q = max(0, b - cnt[1]);\n let add = max(0, max(p - rem_a, q - rem_b));\n let v = v + add;\n let po = next.entry((bit | (1 << i), rem_a + add - p, rem_b + add - q)).or_insert(v);\n *po = std::cmp::min(*po, v);\n }\n }\n now = next;\n }\n let ans = now.into_iter().map(|(_, v)| v).min().unwrap() + n as i32;\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "ca3baa39e9b4531d4f062dcb5acb5e79", "src_uid": "25a77f2b7cb281ff3c7800a20b3e5969", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\nuse std::cmp::*;\nuse std::thread;\nconst INF: i64 = 1i64 << 60;\nfn exec() {\n let mut sc = Scanner::new();\n let n: usize = sc.ne();\n let mut cards = Vec::new();\n for _ in 0..n {\n let c: String = sc.ne();\n let r: i64 = sc.ne();\n let b: i64 = sc.ne();\n let is_r = c == \"R\";\n cards.push((is_r, r, b));\n }\n let sn = 1 << n;\n let rn = n * (n + 1) / 2;\n let mut dp = vec![vec![-INF; rn]; sn];\n dp[0][0] = 0;\n for s in 0..sn {\n let mut rnum = 0;\n let mut bnum = 0;\n for i in 0..n {\n if (s >> i) & 1 == 0 {\n continue;\n }\n if cards[i].0 {\n rnum += 1;\n } else {\n bnum += 1;\n }\n }\n for i in 0..rn {\n // println!(\"{:b}, i: {}, {}\", s, i, dp[s][i]);\n if dp[s][i] == -INF {\n continue;\n }\n for j in 0..n {\n if (s >> j) & 1 == 1 {\n continue;\n }\n let ns = s | (1 << j);\n let ni = min(rnum, cards[j].1) as usize + i;\n dp[ns][ni] = max(dp[ns][ni], dp[s][i] + min(bnum, cards[j].2));\n }\n }\n }\n let rsum = cards.iter().fold(0, |acc, &t| acc + t.1);\n let bsum = cards.iter().fold(0, |acc, &t| acc + t.2);\n let mut ans = INF;\n for i in 0..rn {\n ans = min(ans, max(rsum - i as i64, bsum - dp[sn - 1][i]));\n // println!(\"{}\", ans);\n }\n println!(\"{}\", ans + n as i64);\n}\n\nconst DEFAULT_STACK: usize = 16 * 1024 * 1024;\nfn main() {\n let builder = thread::Builder::new();\n let th = builder.stack_size(DEFAULT_STACK);\n let handle = th.spawn(|| { exec(); }).unwrap();\n let _ = handle.join();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => return None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => {\n panic!(\"parse error: {:?}\",\n str::from_utf8(&self.buf[l..r]).unwrap())\n }\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "b0971d171ed8340adf98299f086c846a", "src_uid": "25a77f2b7cb281ff3c7800a20b3e5969", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\n// ---------- begin chmin, chmax ----------\ntrait ChangeMinMax {\n fn chmin(&mut self, x: Self) -> bool;\n fn chmax(&mut self, x: Self) -> bool;\n}\n\nimpl ChangeMinMax for T {\n fn chmin(&mut self, x: Self) -> bool {\n if *self > x {\n *self = x;\n true\n } else {\n false\n }\n }\n fn chmax(&mut self, x: Self) -> bool {\n if *self < x {\n *self = x;\n true\n } else {\n false\n }\n }\n}\n// ---------- end chmin, chmax ----------\n\nuse std::cmp::*;\n\nfn run() {\n input! {\n n: usize,\n p: [(chars, [i32; 2]); n],\n }\n let mut p = p\n .into_iter()\n .map(|p| ((p.0[0] == 'B') as usize, [p.1[0], p.1[1]]))\n .collect::>();\n let mut need = [0; 2];\n for p in p.iter_mut() {\n let n = n as i32;\n for (need, v) in need.iter_mut().zip(p.1.iter_mut()) {\n *need += max(0, *v - n + 1);\n v.chmin(n - 1);\n }\n }\n let mut sum = vec![[0i32; 2]];\n for &(x, _) in p.iter() {\n for i in 0..sum.len() {\n let mut a = sum[i];\n a[x] += 1;\n sum.push(a);\n }\n }\n let inf = std::i32::MAX / 2;\n let sup = (n - 1) * (n - 1);\n let mut dp = vec![vec![vec![inf; 1 << n]; sup + 1]; 2];\n let abs = (need[1] - need[0]).abs() as usize;\n dp[(need[0] >= need[1]) as usize][min(sup, abs)][0] = 0;\n for bit in 0..(1 << n) {\n let sum = sum[bit];\n for rem in 0..=sup {\n for i in 0..2 {\n let v = dp[i][rem][bit];\n if v == inf {\n continue;\n }\n for (j, &(_, p)) in p.iter().enumerate() {\n let k = bit | (1 << j);\n if k == bit {\n continue;\n }\n let p = [max(0, p[0] - sum[0]), max(0, p[1] - sum[1])];\n if rem as i32 + p[i ^ 1] >= p[i] {\n let x = rem as i32 + p[i ^ 1] - p[i];\n let v = v + p[i ^ 1];\n dp[i][min(x as usize, sup)][k].chmin(v);\n } else {\n let x = p[i] - rem as i32 - p[i ^ 1];\n let v = v + p[i] - rem as i32;\n dp[i ^ 1][min(x as usize, sup)][k].chmin(v);\n }\n }\n }\n }\n }\n let add = need.iter().copied().max().unwrap() + n as i32;\n let ans = add + dp.into_iter().flatten().map(|dp| dp[(1 << n) - 1]).min().unwrap();\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "bitmasks"], "code_uid": "5fbc20b52702c7357d8a14e4a26962ea", "src_uid": "25a77f2b7cb281ff3c7800a20b3e5969", "difficulty": 2400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let n: i32 = scan.token();\n\n let mut pten: i32 = 1;\n let mut m = n;\n while m > 9 {\n m /= 10;\n pten *= 10;\n }\n\n m += 1;\n m *= pten;\n\n writeln!(out, \"{}\", m - n)?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8423150edb58a1dc1d36064293c9d15e", "src_uid": "a3e15c0632e240a0ef6fe43a5ab3cc3e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main(){\n let mut inp = String::new();\n io::stdin().read_line(&mut inp).expect(\"Error while taking input\");\n let num: u32 = inp.trim().parse().expect(\"Number can't be parsed\");\n let ipsize: u32 = inp.trim().len() as u32;\n let magicnum = 10u32.pow(ipsize - 1);\n let nlucky = (num/magicnum + 1) * magicnum;\n println!(\"{}\", nlucky-num);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ee342d581d0314832eca060327cd02a8", "src_uid": "a3e15c0632e240a0ef6fe43a5ab3cc3e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 998_244_353;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\nimpl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt((val % MOD as usize) as u32)\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n assert!(self.0 > 0);\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n k: usize,\n }\n let mut ans = ModInt::zero();\n let pc = Precalc::new(n + k);\n for i in 1..=n {\n let x = n / i - 1;\n let y = k - 1;\n if x >= y {\n ans += pc.comb(x, y);\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "number theory"], "code_uid": "394bd14c4f4df5b1134f4daa85adaceb", "src_uid": "8e8eb64a047cb970a549ee870c3d280d", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, [graph1; $len:expr]) => {{\n let mut g = vec![vec![]; $len];\n let ab = read_value!($next, [(usize1, usize1)]);\n for (a, b) in ab {\n g[a].push(b);\n g[b].push(a);\n }\n g\n }};\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n ($next:expr, usize1) => (read_value!($next, usize) - 1);\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n read_value!($next, [$t; len])\n }};\n ($next:expr, $t:ty) => ($next().parse::<$t>().expect(\"Parse error\"));\n}\n\n#[allow(unused)]\nmacro_rules! debug {\n ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());\n}\n#[allow(unused)]\nmacro_rules! debugln {\n ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());\n}\n\n/// Verified by https://atcoder.jp/contests/arc093/submissions/3968098\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData }\n impl ModInt {\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n pub fn pow(self, mut e: i64) -> Self {\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl>> Add for ModInt {\n type Output = Self;\n fn add(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Sub for ModInt {\n type Output = Self;\n fn sub(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Mul for ModInt {\n type Output = Self;\n fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }\n }\n impl>> AddAssign for ModInt {\n fn add_assign(&mut self, other: T) { *self = *self + other; }\n }\n impl>> SubAssign for ModInt {\n fn sub_assign(&mut self, other: T) { *self = *self - other; }\n }\n impl>> MulAssign for ModInt {\n fn mul_assign(&mut self, other: T) { *self = *self * other; }\n }\n impl Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self { ModInt::new(0) - self }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n let (mut a, mut b, _) = red(self.x, M::m());\n if b < 0 {\n a = -a;\n b = -b;\n }\n write!(f, \"{}/{}\", a, b)\n }\n }\n impl From for ModInt {\n fn from(x: i64) -> Self { Self::new(x) }\n }\n // Finds the simplest fraction x/y congruent to r mod p.\n // The return value (x, y, z) satisfies x = y * r + z * p.\n fn red(r: i64, p: i64) -> (i64, i64, i64) {\n if r.abs() <= 10000 {\n return (r, 1, 0);\n }\n let mut nxt_r = p % r;\n let mut q = p / r;\n if 2 * nxt_r >= r {\n nxt_r -= r;\n q += 1;\n }\n if 2 * nxt_r <= -r {\n nxt_r += r;\n q -= 1;\n }\n let (x, z, y) = red(nxt_r, r);\n (x, y - q * z, z)\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998_244_353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n// Depends on ModInt.rs\nfn fact_init(w: usize) -> (Vec, Vec) {\n let mut fac = vec![ModInt::new(1); w];\n let mut invfac = vec![0.into(); w];\n for i in 1 .. w {\n fac[i] = fac[i - 1] * i as i64;\n }\n invfac[w - 1] = fac[w - 1].inv();\n for i in (0 .. w - 1).rev() {\n invfac[i] = invfac[i + 1] * (i as i64 + 1);\n }\n (fac, invfac)\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n input! {\n n: usize, k: usize,\n }\n let (fac, invfac) = fact_init(500_100);\n let mut tot = ModInt::new(0);\n for b in 1..=n / k {\n tot += fac[n / b - 1] * invfac[n / b - k] * invfac[k - 1];\n }\n puts!(\"{}\\n\", tot);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "number theory"], "code_uid": "36719d71db458ed73df1274660cad3c5", "src_uid": "8e8eb64a047cb970a549ee870c3d280d", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt,$x:expr,$y:expr) => {{\n\t\tlet b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\n// Field (mod prime) {{{\nconst P5: i32 = 998244353;\nconst P6: i64 = P5 as i64;\n#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] struct Field(i32);\n#[allow(dead_code)] impl Field {\n\tfn new>(a: T) -> Self { Self(Self::cv(a)) }\n\tfn new_unchecked(a: i32) -> Self { Self(a) }\n\tfn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n\tfn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n\tfn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n\tfn inv(self) -> Self { self.pow(P5-2) }\n\tfn pow>(self, b: T) -> Self {\n\t\tlet b = b.into(); if b == 0 { Self(1) } else {\n\t\t\tlet mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res\n\t\t}\n\t}\n}\nimpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\nimpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\nimpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\nimpl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}\nimpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\nimpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\nimpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\nimpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\nimpl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }\nuse std::fmt::{Display, Formatter, Result};\nimpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\nimpl Sum for Field { fn sum(i: I) -> Self where I: Iterator { i.fold(Field(0), |a,b| a + b) } }\nimpl<'a> Sum<&'a Self> for Field { fn sum(i: I) -> Self where I: Iterator { i.fold(Field(0), |a,&b| a + b) }}//'\nimpl Product for Field { fn product(i: I) -> Self where I: Iterator { i.fold(Field(1), |a,b| a * b) }}\nimpl<'a> Product<&'a Self> for Field { fn product(i: I) -> Self where I: Iterator { i.fold(Field(1), |a,&b| a * b) }}//'\n//}}}\n// Binomial Coefficient (C(n,r)) {{{\n#[derive(Debug,Clone)]\nstruct Cnr {\n\tn: usize,\n\tf: Box<[Field]>,\n\tfi: Box<[Field]>\n}\n#[allow(dead_code)]\nimpl Cnr {\n\tfn new(n: usize) -> Self {\n\t\tlet mut f = Vec::with_capacity(n+1);\n\t\tf.push(Field(1));\n\t\tfor i in 1..=n {\n\t\t\tf.push(f[i-1] * Field::new(i as i32));\n\t\t}\n\t\tlet mut fi = vec![Field(1); n+1];\n\t\tfi[n] = f[n].inv();\n\t\tfor i in (0..n).rev() {\n\t\t\tfi[i] = fi[i+1] * Field::new(i as i32 + 1);\n\t\t}\n\t\tlet f = f.into_boxed_slice();\n\t\tlet fi = fi.into_boxed_slice();\n\t\tSelf {n, f, fi}\n\t}\n\tfn cnr(&self, n: usize, r: usize) -> Field {\n\t\tif r > n {\n\t\t\tField(0)\n\t\t} else {\n\t\t\tself.f[n] * self.fi[r] * self.fi[n-r]\n\t\t}\n\t}\n}//}}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet z = Cnr::new(500000);\n\tl!(n,k = rin.u());\n\tlet mut sol = Field(0);\n\tfor i in 1.. {\n\t\tlet m = n / i;\n\t\tif m < k {\n\t\t\tbreak;\n\t\t}\n\t\tsol += z.cnr(m-1, k-1);\n\t}\n\twriteln!(rout, \"{}\", sol).ok();\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "number theory"], "code_uid": "4ed3240c6bfc8e0f3ecbb5473267d88c", "src_uid": "8e8eb64a047cb970a549ee870c3d280d", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Write;\n\npub struct Scanner {\n buffer: Vec\n}\n\nimpl Scanner {\n pub fn new() -> Scanner {\n Scanner { buffer: Vec::new() }\n }\n\n pub fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn calculate(n: usize, g: &Vec>, p: &Vec) -> i32 {\n let mut found: [[bool; 6]; 6] = [[false; 6]; 6];\n let mut ans: i32 = 0;\n for u in 0..n {\n for &v in g[u].iter() {\n let u = p[u];\n let v = p[v];\n if !found[u][v] {\n found[u][v] = true;\n found[v][u] = true;\n ans += 1;\n }\n }\n }\n return ans;\n}\n\nfn gen(d: usize, n: usize, g: &Vec>, p: &mut Vec) -> i32 {\n if d == n {\n return calculate(n, g, p);\n }\n let mut ans: i32 = 0;\n for x in 0..6 {\n p[d] = x;\n ans = std::cmp::max(ans, gen(d + 1, n, g, p));\n }\n return ans;\n}\n\nfn main() {\n let stdout = std::io::stdout();\n let mut out = std::io::BufWriter::new(stdout.lock());\n let mut scan = Scanner::new();\n\n let n: usize = scan.next();\n let m: usize = scan.next();\n let mut g: Vec> = vec![vec![]; n];\n for _ in 0..m {\n let u: usize = scan.next();\n let v: usize = scan.next();\n g[u - 1].push(v - 1);\n g[v - 1].push(u - 1);\n }\n let mut p: Vec = vec![0; n];\n let ans = gen(0, n, &g, &mut p);\n writeln!(out, \"{}\", ans).unwrap();\n}", "lang_cluster": "Rust", "tags": ["brute force", "graphs"], "code_uid": "21a166e6df003aa1bb13b18caf3c1d09", "src_uid": "11e6559cfb71b8f6ca88242094b17a2b", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//http://codeforces.com rust 1.19\nuse std::io;use std::cmp;\nfn main(){\n let mut a=String::new();io::stdin().read_line(&mut a);let b:Vec<&str>=a.split_whitespace().collect();\n let c:u64=b[0].parse().unwrap();\n let d:u64=b[1].parse().unwrap();\n if c<1&&d>0{print!(\"Impossible\");return}\n let mut e=c+d-1;\n if d==0{e=c}\n print!(\"{} {}\",cmp::max(c,d),e)\n}", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "0cd1b0b0716334ca33e73b89fafb0cb2", "src_uid": "1e865eda33afe09302bda9077d613763", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//codeforces.com:1.19\nuse std::{io,cmp};\nfn main(){\n let mut z=String::new();io::stdin().read_line(&mut z);let y:Vec<&str>=z.split_whitespace().collect();let a:i32=y[0].parse().unwrap();let b:i32=y[1].parse().unwrap();\n if a==0&&b>0{print!(\"Impossible\");return}\n print!(\"{} {}\",cmp::max(a,b),cmp::max(a+b-1,a+0))\n}", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "5cbae32f4ff106cd97b53955ce4d5c4e", "src_uid": "1e865eda33afe09302bda9077d613763", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//1.25.0 | JDoodle.Com & 1.26 | CodeForces.Com\nuse std::{io,cmp};\n\nfn main() {\n let mut input1 = String::new();\n io::stdin().read_line(&mut input1);\n let input2:Vec<&str> = input1.split_whitespace().collect();\n \n let grown_ups:i32 = input2[0].parse().unwrap();\n let children:i32 = input2[1].parse().unwrap();\n \n if grown_ups < 1 && children > 0 {\n print!(\"Impossible\");\n return\n }\n \n print!(\"{} {}\", cmp::max(grown_ups, children), cmp::max(grown_ups + children - 1, grown_ups + 0))\n}", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "da033da47ba67784779f195bdda35127", "src_uid": "1e865eda33afe09302bda9077d613763", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{io,cmp};fn main(){let mut x=String::new();io::stdin().read_line(&mut x);let y:Vec<&str>=x.split_whitespace().collect();let a:i32=y[0].parse().unwrap();let b:i32=y[1].parse().unwrap();if a<1&&b>0{print!(\"Impossible\");return}print!(\"{} {}\",cmp::max(a,b),cmp::max(a+b-1,a+0))}", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "f802d979c98103c3afad45ba5e079307", "src_uid": "1e865eda33afe09302bda9077d613763", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io::stdin;\nfn main() {\n let mut text = String::new();\n stdin().read_line(&mut text).unwrap();\n text.clear();\n stdin().read_line(&mut text).unwrap();\n let text = text.trim();\n let mut counter = 0;\n for i in spliter(text) {\n let a = find_distinct_lc(i);\n if counter < a {\n counter = a;\n }\n }\n println!(\"{}\", counter);\n}\n\nfn find_distinct_lc(text: &str) -> u8 {\n let mut hash: HashMap = HashMap::new();\n let mut counter = 0;\n for i in text.chars() {\n match hash.get(&i) {\n Some(_) => (),\n _ => {\n hash.insert(i, true);\n counter += 1;\n }\n }\n }\n counter\n}\nfn spliter(text: &str) -> Vec<&str> {\n text.split(char::is_uppercase).collect()\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "7c0b7b4a1acd06a3dc3dfc3e122293e1", "src_uid": "567ce65f87d2fb922b0f7e0957fbada3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::char;\n\n#[allow(non_snake_case)]\nfn charCount(x: &str) -> i32 {\n let mut v: Vec = vec![0; 26];\n let mut res = 0;\n for c in x.bytes() {\n if v[(c-0x61) as usize] == 0 {\n res = res + 1;\n v[(c-0x61) as usize] = 1;\n }\n }\n res\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input.clear();\n io::stdin().read_line(&mut input).unwrap();\n let v: Vec<&str> = input.trim_right().split(char::is_uppercase).collect();\n let mut ans = 0;\n for s in v {\n let t = charCount(s);\n if t > ans {\n ans = t;\n }\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "891bc2e2fcf0d038cdffff7bfd939bf3", "src_uid": "567ce65f87d2fb922b0f7e0957fbada3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let n: usize = get_line().trim().parse().unwrap();\n\n let s = get_line().trim().to_string();\n\n let it = s.split_terminator(char::is_uppercase);\n\n let ans = it.map(|s| {\n s.bytes().fold(vec![false; 26], |mut acc, c| {\n acc[(c - b'a') as usize] = true;\n acc\n }).into_iter().filter(|&b| b).count()\n }).max().unwrap();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "caa61dc6c6334705255eef28191fe019", "src_uid": "567ce65f87d2fb922b0f7e0957fbada3", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let d: usize = scan.next();\n let arr: Vec = scan.next_n(n);\n let total: usize = arr.iter().sum();\n let total2 = total + (n-1)*10;\n if total2 > d {\n println!(\"-1\");\n } else {\n let reminding = d - total2;\n println!(\"{}\", (n-1)*2 + reminding/5);\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "8435539ba04266bf9208a342b92c97f8", "src_uid": "b16f5f5c4eeed2a3700506003e8ea8ea", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let a: Vec = s.trim().split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let d = a[1];\n\n s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let v: Vec = s.trim().split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let mut time_needed: i32 = -10;\n v.iter().for_each(|x| time_needed += x + 10);\n\n if time_needed > d {\n println!(\"-1\");\n return;\n }\n\n println!(\"{}\", v.len()*2 - 2 + ((d - time_needed) / 5) as usize);\n}\n\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "e213ca48287602ab563b30d2506c09e0", "src_uid": "b16f5f5c4eeed2a3700506003e8ea8ea", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n#[allow(unused_imports)]\nuse std::collections::HashMap;\n\n#[allow(unused_macros)]\nmacro_rules! readln {\n () => {{\n use std::io;\n \n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\n#[allow(unused_macros)]\nmacro_rules! readvec {\n ( $t:ty ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n let mut result = Vec::new();\n for elem in input {\n result.push(elem.parse::<$t>().unwrap());\n }\n result\n }}\n}\n\nfn main() {\n let (n,d) = readln!(i32,i32);\n let a = readvec!(i32);\n if a.iter().sum::() + (n-1) * 10 > d {\n println!(\"{}\",-1);\n } else {\n println!(\"{}\",(d-a.iter().sum::())/5);\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "2beb375e686aabc495e7c5c7936b18f0", "src_uid": "b16f5f5c4eeed2a3700506003e8ea8ea", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn solve() -> Vec {\n let mut input = \"\".split_ascii_whitespace();\n let mut read = || loop {\n if let Some(word) = input.next() {\n break word;\n }\n input = {\n let mut input = \"\".to_owned();\n io::stdin().read_line(&mut input).unwrap();\n if input.is_empty() {\n panic!(\"reached EOF\");\n }\n Box::leak(input.into_boxed_str()).split_ascii_whitespace()\n };\n };\n macro_rules! read(($ty:ty) => (read().parse::<$ty>().unwrap()));\n\n let mut rr = vec![\"\".to_string(); 0];\n\n let t = 1;\n for _ in 0..t {\n let n = read!(usize);\n let mut a = vec![0; n];\n for i in 0..n {\n a[i] = read!(usize);\n }\n\n a.sort();\n let mut v = vec![false; n];\n let mut r = 0;\n for i in 0..n {\n if v[i] {\n continue;\n }\n v[i] = true;\n r += 1;\n let mut c = 1;\n for j in (i + 1)..n {\n if !v[j] && a[j] >= c {\n v[j] = true;\n c += 1;\n }\n }\n }\n\n rr.push(format!(\"{}\", r));\n }\n\n rr\n}\n\n#[allow(dead_code)]\nfn main() {\n let output = solve();\n println!(\"{}\", output.join(\"\\n\"));\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "greedy"], "code_uid": "f83ccbf590c842f052b0e41345bfd739", "src_uid": "7c710ae68f27f140e7e03564492f7214", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let reader = io::stdin();\n let numbers: Vec = \n reader.lock() // (0)\n .lines().next().unwrap().unwrap() // (1)\n .split(' ').map(|s| s.trim()) // (2)\n .filter(|s| !s.is_empty()) // (3)\n .map(|s| s.parse().unwrap()) // (4)\n .collect(); // (5)\n \n let l = numbers[0];\n let r = numbers[1];\n \n let mut ans = 0;\n \n let mut num2: i64 = 1;\n for p2 in 0..32 {\n let mut num3: i64 = num2;\n for p3 in 0..20 {\n \tif num3 >= l && num3 <= r {\n \t\tans = ans + 1;\n \t}\n \tnum3 = num3 * 3;\n }\n num2 = num2 * 2;\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e264143b0dda3b042e3ea43998ba6833", "src_uid": "05fac54ed2064b46338bb18f897a4411", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn f(n: i64, l: i64, r: i64, t: i32, w: i32) -> i64 {\n let mut result = 0;\n if(n <= r) {\n if(n >= l) {\n result += 1;\n }\n if(w == 0) {\n result += f(2*n, l, r, t+1, w);\n }\n result += f(3*n, l , r, t, w+1);\n }\n return result;\n}\n\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nfn main() {\n let (a, b) = parse_line!(i64, i64);\n \n\tlet mut cnt = f(1, a, b, 0, 0);\n\tprintln!(\"{}\", cnt);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "db4fdeceea18eef47936594b81837747", "src_uid": "05fac54ed2064b46338bb18f897a4411", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/265/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n let s = buf.trim().to_string();\n buf.clear();\n io::stdin().read_line(&mut buf).unwrap();\n let t = buf.trim().to_string();\n let ss = s.as_bytes();\n\n let mut i = 1;\n for &u in t.as_bytes() {\n if u == ss[i-1] { i += 1; }\n }\n println!(\"{}\", i);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8328e97be45283473f9d21b676b2641a", "src_uid": "f5a907d6d35390b1fb11c8ce247d0252", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// {{{ by shik\n\nuse std::io;\n\n#[allow(dead_code)]\nfn gets() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n}\n\nmacro_rules! R {\n ( $ty:ty, ... ) => {\n gets().split_whitespace().map(|x| x.parse::<$ty>().unwrap()).collect::>()\n };\n ( $($ty:ty),* ) => {{\n let line = gets();\n let mut it = line.split_whitespace();\n ( $(it.next().unwrap().parse::<$ty>().unwrap(),)* )\n }}\n}\n\nmacro_rules! W {\n ( $x:expr ) => {{\n println!(\"{}\", $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} \", $x);\n W!($($xs),*);\n }}\n}\n\nmacro_rules! debug {\n ( $x:expr ) => {{\n println!(\"{} = {:?}\", stringify!($x), $x);\n }};\n ( $x:expr, $($xs:expr),* ) => {{\n print!(\"{} = {:?}, \", stringify!($x), $x);\n debug!($($xs),*);\n }}\n}\n\n// }}}\n\nfn main() {\n let (n, h) = R!(usize, usize);\n let mut dp = vec![vec![0i64; n + 1]; n + 1];\n dp[0][0] = 1;\n for i in 1..n + 1 {\n for j in 1..i + 1 {\n let mut s = 0i64;\n for k in 1..i + 1 {\n let l = k - 1;\n let r = i - k;\n for jl in 0..j {\n for jr in 0..j {\n if jl == j - 1 || jr == j - 1 {\n s += dp[l][jl] * dp[r][jr];\n }\n }\n }\n }\n dp[i][j] = s;\n }\n }\n let ans = (h..n + 1).fold(0i64, |s, i| s + dp[n][i]);\n W!(ans);\n}\n", "lang_cluster": "Rust", "tags": ["divide and conquer", "dp", "combinatorics"], "code_uid": "f262adf90710e14d255877664c2da0e2", "src_uid": "faf12a603d0c27f8be6bf6b02531a931", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\nuse std::thread;\nuse std::collections::BTreeSet;\nfn exec() {\n let mut sc = Scanner::new();\n let s: String = sc.ne();\n let mut m = BTreeSet::new();\n let n = s.len();\n for i in 0..n {\n let mut ss = s[i..n].to_string();\n ss.push_str(&s[0..i]);\n m.insert(ss);\n }\n println!(\"{}\", m.len());\n}\nconst DEFAULT_STACK: usize = 16 * 1024 * 1024;\nfn main() {\n let builder = thread::Builder::new();\n let th = builder.stack_size(DEFAULT_STACK);\n let handle = th.spawn(|| { exec(); }).unwrap();\n let _ = handle.join();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => return None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => panic!(\"parse error\"),\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "191a927aa9a2585dbe4ec6242fc5895e", "src_uid": "8909ac99ed4ab2ee4d681ec864c7831e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let mut n = parse_line!(u64);\n let mut result = 0;\n let mut add = 1;\n while n > 1 {\n result += n / 2 * add;\n add *= 2;\n n = (n + 1) / 2;\n }\n println!(\"{}\", result);\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "bitmasks", "graphs", "implementation"], "code_uid": "a80b4dd357e8d071847832a7c9f5aeee", "src_uid": "a98f0d924ea52cafe0048f213f075891", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn check_row(v: Vec) {\n let mut previous: Option = None;\n let mut one_before: Option = None;\n for (i, c) in v.into_iter().enumerate() {\n match c {\n 0 => {\n one_before = previous;\n previous = Some(i);\n },\n 2 => {\n one_before = Some(i);\n previous = Some(i);\n },\n 1 => (),\n _ => panic!(\"Oops!\"),\n }\n\n if let Some(b) = one_before {\n if i > b + 4 {\n println!(\"YES\");\n std::process::exit(0);\n }\n } else if i >= 4 {\n println!(\"YES\");\n std::process::exit(0);\n }\n }\n}\n\nfn main() {\n let mut grid: Vec = Vec::with_capacity(100);\n\n for _ in 0..10 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n for c in input.trim().chars() {\n match c {\n '.' => grid.push(0),\n 'X' => grid.push(1),\n 'O' => grid.push(2),\n _ => panic!(\"Invalid character\"),\n }\n }\n }\n\n for i in 0..10 {\n let it = (0..100).filter_map(|k| if k / 10 == i {Some(grid[k])} else {None});\n check_row(it.collect());\n\n let it = (0..100).filter_map(|k| if k % 10 == i {Some(grid[k])} else {None});\n check_row(it.collect());\n }\n\n for i in 0..6 {\n check_row((i..10).zip(0..(10 - i)).map(|(i, j)| grid[10 * i + j]).collect());\n check_row((i..10).zip(0..(10 - i)).map(|(i, j)| grid[10 * j + i]).collect());\n check_row((i..10).zip((i..10).rev()).map(|(i, j)| grid[10 * j + i]).collect());\n }\n\n for i in 4..10 {\n check_row((0..i).rev().zip(0..i).map(|(i, j)| grid[10 * i + j]).collect());\n }\n\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "866bdfd3e43860f7869bc38a5debd1ae", "src_uid": "d5541028a2753c758322c440bdbf9ec6", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::prelude::*;\n std::io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace().map(|x| {\n x.parse::().unwrap()\n });\n\n let (mut a, b, c) = (\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n );\n\n let mut ans = -1;\n let mut cnt = 0;\n\n for _ in 0..b + 10 {\n cnt += 1;\n a *= 10;\n let q = a / b;\n if q == c {\n ans = cnt;\n break;\n }\n a -= q * b;\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "b5dccd31cbf1564ad93bf54bb23750f1", "src_uid": "0bc7bf67b96e2898cfd8d129ad486910", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (m, d) = {\n let r = getvec::();\n (r[0], r[1])\n };\n let mut days = match m {\n 4 | 6 | 9 | 11 => 30,\n 2 => 28,\n _ => 31,\n };\n let mi = 8 - d;\n days -= mi;\n let p = match days % 7 == 0 {\n true => days / 7,\n false => days / 7 + 1,\n };\n println!(\"{}\", 1 + p);\n}\n\n#[allow(dead_code)]\nfn next_line() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n input\n}\n\n#[allow(dead_code)]\nfn getnum() -> T {\n let res = next_line();\n res.trim().parse::().ok().unwrap()\n}\n\n#[allow(dead_code)]\nfn getvec() -> Vec {\n let res = next_line();\n res.split_whitespace().map(|x| x.parse::().ok().unwrap()).collect()\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "1cccf053a044ceefbbe75b234edbe77f", "src_uid": "5b969b6f564df6f71e23d4adfb2ded74", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::*;\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! debug(\n ($($arg:tt)*) => { {\n let r = writeln!(&mut ::std::io::stderr(), $($arg)*);\n r.expect(\"failed printing to stderr\");\n } }\n);\n\nstruct Scanner {\n buffer : std::collections::VecDeque\n}\n\nimpl Scanner {\n\n fn new() -> Scanner {\n Scanner {\n buffer: std::collections::VecDeque::new()\n }\n }\n\n fn process(&mut self) -> String {\n if self.buffer.len() == 0 {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n for word in input.split_whitespace() {\n self.buffer.push_back(word.to_string())\n }\n }\n\n self.buffer.pop_front().unwrap()\n }\n\n fn next(&mut self) -> T {\n self.process().parse::().ok().unwrap()\n }\n\n fn next_char(&mut self) -> char {\n self.process().into_bytes()[0] as char\n }\n}\n\nfn main() {\n let mut sin = Scanner::new();\n let (m, d) : (usize, i32) = (sin.next(), sin.next());\n\n let month_days = vec![31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n let mut days = month_days[m-1];\n\n let mut columns = 1;\n days -= 7 - d + 1;\n\n while days > 7 {\n columns += 1;\n days -= 7;\n }\n\n if days > 0 {\n columns += 1;\n }\n\n println!(\"{}\", columns);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "5eda2c8fe013318789268224a4dded05", "src_uid": "5b969b6f564df6f71e23d4adfb2ded74", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn sumdigits(x: i64) -> usize {\n let mut result = 0usize;\n let mut tmp = x;\n while tmp > 0 {\n result += (tmp % 10) as usize;\n tmp /= 10;\n }\n result\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: u32 = scan.next();\n let b: isize = scan.next();\n let c: isize = scan.next();\n let mut result: Vec = vec![];\n for i in 0usize..=81 {\n let x: i64 = (i.pow(a) as i64) * (b as i64) + (c as i64);\n if x <= 0 {\n continue;\n }\n if x >= 1000000000 {\n break;\n }\n if sumdigits(x) == i {\n result.push(x);\n }\n }\n println!(\"{}\", result.len());\n for &item in &result {\n print!(\"{} \", item);\n }\n if result.len() != 0 {\n println!();\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "e8cefc6611789cb014a7f869884551e9", "src_uid": "e477185b94f93006d7ae84c8f0817009", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn digit_sum(x: i64) -> i64 {\n let mut x = x;\n let mut ans = 0;\n while x > 0 {\n ans += x % 10;\n x /= 10;\n }\n ans\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let a: u32 = scan.token();\n let b: i64 = scan.token();\n let c: i64 = scan.token();\n let mut ans = Vec::new();\n\n for s_x in 1i64..=81i64 {\n let x = b * s_x.pow(a) + c;\n if x >= 1000000000 {\n break;\n }\n if digit_sum(x) == s_x {\n ans.push(x.to_string());\n }\n }\n writeln!(out, \"{}\", ans.len()).ok();\n writeln!(out, \"{}\", ans.join(\" \")).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "bc08acec9cd7d983c9bfa6611f920f64", "src_uid": "e477185b94f93006d7ae84c8f0817009", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\n\nfn main() {\n let (a, b, c) = get!(i64, i64, i64);\n let mut k = vec![];\n for i in 0..100 {\n k.push((b * ((i as i64).pow(a as u32)) + c, i));\n }\n let mut ans = vec![];\n for &(d, e) in &k {\n if d <= 0 {\n continue;\n } else if d > 10_i64.pow(9) {\n continue;\n }\n let f = d\n .to_string()\n .chars()\n .map(|x| x as usize - '0' as usize)\n .fold(0, |a, x| a + x);\n if f == e {\n ans.push(d);\n }\n }\n echo!(ans.len());\n echo!(ans.joinToString(\" \"));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "50f0c62ceabd1aaae5866154fa24000d", "src_uid": "e477185b94f93006d7ae84c8f0817009", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn sumdigits(x: i64) -> usize {\n let mut result = 0usize;\n let mut tmp = x;\n while tmp > 0 {\n result += (tmp % 10) as usize;\n tmp /= 10;\n }\n result\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let a: u32 = scan.next();\n let b: isize = scan.next();\n let c: isize = scan.next();\n let mut result: Vec = vec![];\n for i in 0usize..=81 {\n let x: i64 = (i.pow(a) as i64) * (b as i64) + (c as i64);\n if x <= 0 {\n continue;\n }\n if x >= 1000000000 {\n break;\n }\n if sumdigits(x) == i {\n result.push(x);\n }\n }\n println!(\"{}\", result.len());\n for &item in &result {\n print!(\"{} \", item);\n }\n if result.len() != 0 {\n println!();\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "number theory"], "code_uid": "e8160ed5ac222ec5cde18a4a237a61b6", "src_uid": "e477185b94f93006d7ae84c8f0817009", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut sides: Vec = scan.next_n(3);\n sides.sort();\n let x = sides[2] - sides[1];\n if sides[0] > x {\n println!(\"0\");\n } else {\n println!(\"{}\", x - sides[0] + 1);\n }\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "f5a53d29f10e59dae05a271f94c8e2d6", "src_uid": "3dc56bc08606a39dd9ca40a43c452f09", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::iter::*;\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty; $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt; $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let mut a = input.vi(3);\n a.sort();\n println!(\"{}\", 0.max(a[2] + 1 - a[1] - a[0]));\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "78c9d5e1cab12890e780a0c85d38c618", "src_uid": "3dc56bc08606a39dd9ca40a43c452f09", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::collections::BTreeSet;\n\nfn max(x: &BTreeSet, y: &BTreeSet) -> (BTreeSet, BTreeSet) {\n let mut r: BTreeSet = BTreeSet::new();\n let mut rx: BTreeSet = BTreeSet::new();\n let mut xiter = x.iter();\n let mut yiter = y.iter();\n let mut i: i32 = *(xiter.next().unwrap());\n let mut j: i32 = *(yiter.next().unwrap());\n if i < j {\n while i < j { match xiter.next() {\n Some(x) => i = *x,\n None => { i = -1; break }\n } }\n } else {\n if j < i {\n while j < i { match yiter.next() {\n Some(x) => j = *x,\n None => { j = -1; break }\n } }\n }\n }\n if i != -1 { r.insert(i); }\n if j != -1 { r.insert(j); rx.insert(j); }\n for x in xiter { r.insert(*x); }\n for y in yiter { r.insert(*y); rx.insert(*y); }\n (r, rx)\n}\n\nfn main() {\n let mut l = String::new();\n io::stdin().read_line(&mut l).unwrap();\n let x: Vec = l.trim().split_whitespace().map(|x| x.parse().unwrap()).collect();\n let (_, k) = (x[0], x[1]);\n let mut xs = String::new();\n io::stdin().read_line(&mut xs).unwrap();\n let mut r: BTreeSet = BTreeSet::new();\n r.insert(-1);\n for x in xs.trim().split('Y') {\n let mut rr: BTreeSet = BTreeSet::new();\n let mut rc: BTreeSet = BTreeSet::new();\n rr.insert(-1);\n rc.insert(-1);\n for g in x.split('?') {\n let mut rs: BTreeSet = BTreeSet::new();\n let gl = g.len() as i32;\n rs.insert(gl);\n let (u, ux) = max(&rr, &rs);\n rr = &u | &(rc.iter().map(|x| x + gl + 1).collect());\n rc = &ux | &(rc.iter().map(|x| x + gl + 1).collect());\n }\n r = max(&r, &rr).0;\n }\n if r.contains(&k) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "c517f1ab6688c278a62c346f81fbeb3d", "src_uid": "5bd578d3da5837c259b222336a194d12", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut s: String = String::new();\n io::stdin().read_line(&mut s).unwrap();\n let v: Vec = s.trim()\n .split(' ')\n .map(|n| n.parse().unwrap())\n .collect();\n\n let a = v[0];\n let b = v[1];\n let c = v[2];\n let n = v[3];\n\n let sol = n - a - b + c;\n\n if sol < 1 || c > a || c > b {\n println!(\"-1\");\n } else {\n println!(\"{}\", sol);\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6a97ff37792a5bb298929b26c9da37fc", "src_uid": "959d56affbe2ff5dd999a7e8729f60ce", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io::{self, prelude::*};\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n let a: usize = it.next().unwrap().parse().unwrap();\n let b: usize = it.next().unwrap().parse().unwrap();\n let c: usize = it.next().unwrap().parse().unwrap();\n let n: usize = it.next().unwrap().parse().unwrap();\n\n let ans = c <= a &&\n c <= b &&\n a < n &&\n b < n &&\n a + b - c < n;\n\n if ans {\n println!(\"{}\", n + c - a - b) ;\n } else {\n println!(\"-1\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b1d0a1d9812cc1b242ed949c42ec0107", "src_uid": "959d56affbe2ff5dd999a7e8729f60ce", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 991A\nuse std::cmp::min;\nuse std::io;\n\nfn main() {\n let (a, b, c, n): (u32, u32, u32, u32) = read_two(&io::stdin());\n if a + b - c + 1 > n || c > min(a, b) {\n println!(\"{}\", -1);\n } else {\n println!(\"{}\", n - (a + b - c));\n }\n}\n\nfn read_two(stdin: &io::Stdin) -> (T, T, T, T)\nwhere\n T: std::str::FromStr,\n ::Err: std::fmt::Debug,\n{\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n let mut iter = s.trim().split_whitespace().map(|x| x.parse().unwrap());\n (\n iter.next().unwrap(),\n iter.next().unwrap(),\n iter.next().unwrap(),\n iter.next().unwrap(),\n )\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "13a89fcb4912dbdc7fa0a8693940c530", "src_uid": "959d56affbe2ff5dd999a7e8729f60ce", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io;\nuse std::cmp::{min, max};\nuse std::mem;\nuse std::str::FromStr;\nuse std::cmp::Ordering;\nuse std::collections::BinaryHeap;\n\npub struct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: B) -> Scanner {\n Scanner {\n reader: reader,\n buffer: Vec::new(),\n }\n }\n\n /// Use \"turbofish\" syntax next::() to select data type of next token.\n pub fn next(&mut self) -> T\n where\n T::Err: ::std::fmt::Debug,\n {\n if let Some(front) = self.buffer.pop() {\n front.parse::().expect(&front)\n } else {\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Line not read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n self.next()\n }\n }\n\n pub fn next_vec(&mut self, len: usize) -> Vec\n where\n T::Err: ::std::fmt::Debug,\n {\n (0..len).map(|_| self.next::()).collect::>()\n }\n}\n\n#[derive(Copy, Clone, Eq, PartialEq, Debug)]\nstruct ReverseInt(i64);\n\nimpl Ord for ReverseInt {\n fn cmp(&self, other: &ReverseInt) -> Ordering {\n other.0.cmp(&self.0)\n }\n}\n\nimpl PartialOrd for ReverseInt {\n fn partial_cmp(&self, other: &ReverseInt) -> Option {\n Some(self.cmp(other))\n }\n}\n\nfn main1() {\n let stdin = io::stdin();\n let mut input = Scanner::new(stdin.lock());\n let n: usize = input.next();\n let mut v: Vec = input.next_vec(n);\n v.sort();\n println!(\"{}\", v[n / 2]);\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(main1).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation"], "code_uid": "50bb2147464a8ee18118f91e0db3b9c3", "src_uid": "f03773118cca29ff8d5b4281d39e7c63", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn main() {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"correct input\");\n\n let res = input\n .trim()\n .split(' ')\n .map(|x| x.parse::())\n .map(|x| x.expect(\"expected number\"))\n .fold(0i32, |sum, x| sum + x);\n\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["dsu", "constructive algorithms", "implementation", "brute force"], "code_uid": "19c04293c10d3f3055ffa54f7f4ab6a4", "src_uid": "b6e3f9c9b124ec3ec20eb8fcea075add", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nstatic BIG: i64 = 1e9 as i64 + 7;\nfn _main() {\n let mut scan = Scan::new();\n let mut x: i64 = scan.next();\n let mut y: i64 = scan.next();\n let mut n: i64 = scan.next();\n let mut i = 2i64;\n n = n % 6;\n // I think it would be better to precompute an\n // array with the 6 different possible values\n while i < n + 6 {\n let tmp = y;\n y = (y - x + BIG) % BIG;\n x = tmp;\n i += 1;\n }\n println!(\"{}\", (y + BIG) % BIG);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d1289eef3a102c1b9dd978d43abc6701", "src_uid": "2ff85140e3f19c90e587ce459d64338b", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\n//------------------- Start Field\nconst P5: i32 = 1_000_000_007;\nconst P6: i64 = P5 as i64;\n#[derive(Debug,Clone,Copy)]\nstruct Field(i32);\n#[allow(dead_code)]\nimpl Field {\n fn new>(a: T) -> Self { Self(Self::cv(a)) }\n fn new_unchecked(a: i32) -> Self { Self(a) }\n fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n fn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n}\nimpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\nimpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\nimpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\nimpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\nimpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\nimpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\nimpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\nuse std::fmt::{Display, Formatter, Result};\nimpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n// impl Default for Field { fn default() -> Self { Field(0) }}\nimpl Default for &Field { fn default() -> Self { &Field(0) }}\nimpl PartialEq for Field { fn eq(&self, a: &Self) -> bool { self.0 == a.0 } }\nimpl PartialOrd for Field { fn partial_cmp(&self, a: &Self) -> Option { Some(self.0.cmp(&a.0)) } }\nimpl Eq for Field {}\nimpl Ord for Field { fn cmp(&self, a: &Self) -> Ordering { self.0.cmp(&a.0) } }\nimpl Sum for Field {\n fn sum(i: I) -> Self where I: Iterator {\n i.fold(Field(0), |a,b| a + b) } }\nimpl<'a> Sum<&'a Self> for Field {\n fn sum(i: I) -> Self where I: Iterator {\n i.fold(Field(0), |a,&b| a + b) } }\nimpl Product for Field {\n fn product(i: I) -> Self where I: Iterator {\n i.fold(Field(1), |a,b| a * b) } }\nimpl<'a> Product<&'a Self> for Field {\n fn product(i: I) -> Self where I: Iterator {\n i.fold(Field(1), |a,&b| a * b) }\n}\n//------------------- End Field\n\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let x = Field::new(input.i());\n let y = Field::new(input.i());\n let n = input.u();\n let mut a = vec![x,y];\n for i in 2..6 {\n let res = a[i-1] - a[i-2];\n a.push(res);\n }\n println!(\"{}\", a[(n - 1) % 6]);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "39d5aa6e4e152f1409cebf4eac0f06ab", "src_uid": "2ff85140e3f19c90e587ce459d64338b", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nfn main() {\n let stdin = io::stdin();\n let mut input = String::new();\n\n stdin.lock().read_line(&mut input).unwrap();\n\n let seq = input.trim().as_bytes();\n\n let n = seq.len();\n let mut largest = seq.to_vec();\n for i in 1..2usize.pow(n as u32) {\n let mut subseq = Vec::with_capacity(n);\n for k in 0..n {\n if i >> k & 1 == 1 {\n subseq.push(seq[k])\n }\n }\n if !is_palindrome(&subseq) {\n continue;\n }\n if is_lexicographically_larger(&subseq, &largest) {\n largest = subseq;\n }\n }\n println!(\"{}\", String::from_utf8_lossy(&largest));\n}\n\nfn is_palindrome(seq: &[u8]) -> bool{\n for i in 0..seq.len()/2 {\n if seq[i] != seq[seq.len()-i-1] {\n return false;\n }\n }\n\n true\n}\n\nfn is_lexicographically_larger(a: &[u8], b: &[u8]) -> bool {\n let mut i = 0;\n let mut same = true;\n\n while i < a.len() && i < b.len() {\n if same {\n if a[i] != b[i] {\n same = false;\n }\n }\n\n if !same {\n if a[i] <= b[i] {\n return false;\n }\n }\n i += 1;\n }\n true\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "binary search", "bitmasks", "greedy", "strings", "implementation"], "code_uid": "c13f97a39639219f9e7f518957a78a5a", "src_uid": "9a40e9b122962a1f83b74ddee6246a40", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::collections::{HashSet, HashMap};\nuse std::cmp::{min,max};\nuse std::io;\nuse std::str;\n \nstruct Scanner {\n reader: R,\n buf_str: Vec,\n buf_iter: str::SplitWhitespace<'static>,\n}\nimpl Scanner {\n fn new(reader: R) -> Self {\n Self { reader, buf_str: vec![], buf_iter: \"\".split_whitespace() }\n }\n fn token(&mut self) -> T {\n loop {\n // If we have another token in this line\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\"); // calls parse::() on the current token and returns it.\n }\n\n // If we do not have another token in the line then\n // we should go to the next line.\n self.buf_str.clear(); // empty out the buffer that holds the current line\n self.reader.read_until(b'\\n', &mut self.buf_str).expect(\"Failed read\"); // read a new line into the buffer\n\n // create an iterator over the white space delimited strings of the current line\n self.buf_iter = unsafe { \n let slice = str::from_utf8_unchecked(&self.buf_str); // makes a string from utf8 characters in the current line\n std::mem::transmute(slice.split_whitespace()) // transmutes the memory in place \n }\n }\n }\n}\n \nfn solve(scan: &mut Scanner, out: &mut W) {\n let n = scan.token::();\n let mut top = 0;\n let mut bottom = 0;\n let mut flippable = false;\n for _ in 0..n {\n let t = scan.token::();\n let b = scan.token::();\n if t % 2 != b % 2 { flippable = true; }\n top += t;\n bottom += b;\n }\n let ans = {\n if top % 2 != 0 && bottom % 2 != 0 && flippable {1}\n else if top % 2 == 0 && bottom % 2 == 0 { 0 }\n else { -1 }\n };\n writeln!(out, \"{}\", ans);\n}\n \nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "1e05acd97cc40e97f7f58c2e55f9d1c9", "src_uid": "f9bc04aed2b84c7dd288749ac264bb43", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn find(src: u64, num: u64, n4: usize, n7: usize, result: &mut u64) {\n if num > 10000000000 {\n return;\n }\n if n4 == n7 && num >= src && (num - src) < (*result - src) {\n *result = num;\n }\n find(src, num * 10 + 4, n4 + 1, n7, result);\n find(src, num * 10 + 7, n4, n7 + 1, result);\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: u64 = scan.next();\n let mut result = std::u64::MAX;\n find(n, 0, 0, 0, &mut result);\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "binary search", "bitmasks"], "code_uid": "76eef6f35ee087776115f18d01e5ee3d", "src_uid": "77b5f83cdadf4b0743618a46b646a849", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::{self,*};\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($($v:ident),* = $i:ident.$f:ident $a:tt) => {\n $( let $v = $i.$f$a; )*\n };\n ($($v:ident),*:$t:ty = $i:ident.$f:ident $a:tt) => {\n $( let $v:$t = $i.$f$a; )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n l!(n,m = input.i());\n let sol = if n == 1 {\n 1\n } else if m - 1 >= n - m {\n m - 1\n } else {\n m + 1\n };\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "games", "math", "greedy", "implementation"], "code_uid": "acbe86c3d0329bfbc86454f56c575a31", "src_uid": "f6a80c0f474cae1e201032e1df10e9f7", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn read_line_pair() -> (u64, u64) {\n let vec = read_line_vec();\n return (vec[0], vec[1]);\n}\n\n\nfn get_bp(n: u64, m: u64) -> u64 {\n if n == 1 {\n return 1;\n }\n assert!(m > 0);\n let left = m - 1;\n let right = n - m;\n \n if left == right {\n return left;\n }\n if left < right {\n return m + 1;\n }\n return left;\n}\n\nfn main() {\n let (n, m) = read_line_pair();\n let res = get_bp(n, m);\n \n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "games", "math", "greedy", "implementation"], "code_uid": "eb0e777da742f64300de7736980b3018", "src_uid": "f6a80c0f474cae1e201032e1df10e9f7", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let arr: Vec = scan.next_n(n);\n let n100 = arr.iter().filter(|x| **x == 100).count();\n let n200 = arr.len() - n100;\n let result = n100 % 2 == 0 && n200 % 2 == 0 || n100 >= 2 && n100 % 2 == 0;\n println!(\"{}\", if result { \"YES\" } else { \"NO\" });\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "7a45ff5b3d178a2915a78e8d34a4a21c", "src_uid": "9679acef82356004e47b1118f8fc836a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\nuse std::cmp::Ordering::{*};\n\n// I have no idea what I'm doing\n\nuse std::f64::consts::{PI};\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let n: i64 = scan.token();\n\n if n == 0 {\n return writeln!(out, \"1\");\n }\n\n let is_in = |i, j| i*i + j*j <= n*n;\n // Uncomment for a cool circle in your screen\n // for i in -n..=n {\n // for j in -n..=n {\n // write!(out, \"{}\", if is_in(i.abs(), j.abs()) { '+' }\n // else { '-' })?;\n // write!(out, \" \")?;\n // }\n // writeln!(out)?;\n // }\n\n let mut ans = 0;\n let mut y = n;\n for x in 0..=n {\n if is_in(x, y) {\n ans += 1;\n }\n while !is_in(x, y) {\n y -= 1;\n ans += 1;\n }\n }\n\n writeln!(out, \"{}\", (ans - 1) * 4)?;\n\n\n Ok(())\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "a508bc09280d034dc2f5602316698971", "src_uid": "d87ce09acb8401e910ca6ef3529566f4", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1293/problem/F\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::io::Write;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n// Input macros.\n// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_line {\n ($t:tt) => {\n {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n s.trim_right().parse::<$t>().unwrap()\n }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\n// ===\n\n\nfn generate_primes(upto: usize) -> (Vec, Vec) {\n let mut is_prime = vec![true; upto+1];\n is_prime[0] = false;\n is_prime[1] = false;\n for i in 2..upto+1 {\n if is_prime[i] {\n let mut ii = i * i;\n while ii <= upto {\n is_prime[ii] = false;\n ii += i;\n }\n }\n }\n\n let mut primes = vec![];\n for i in 0..upto+1 {\n if is_prime[i] {\n primes.push(i as i64);\n }\n }\n (primes, is_prime)\n}\n//===\n\nstruct Graph {\n graph: Vec>,\n vec: Vec,\n edges: Vec<(usize, usize, i64)>,\n mark: Vec,\n dcost: Vec,\n}\n\nimpl Graph {\n fn generate_next(&mut self, cnt: i64) -> usize {\n self.vec.push(cnt);\n self.vec.len() - 1\n }\n fn add_edge(&mut self, u: usize, v: usize, len: i64) {\n self.edges.push((u, v, len));\n }\n}\n\nfn dfs(l: usize, r: usize, depth: usize, parent: usize, table: &Vec<(Vec, usize, i64)>, graph: &mut Graph) {\n if l == r {\n if table[l].1 >= 2 {\n let nid = graph.generate_next(table[l].2);\n let mut d = 0;\n\n let pn = table[0].0.len();\n for i in depth..pn {\n d += table[l].0[i];\n }\n graph.add_edge(parent, nid, d);\n }\n return;\n }\n\n if table[l].0[depth] == table[r].0[depth] {\n if table[l].0[depth] == 0 {\n dfs(l, r, depth+1, parent, table, graph);\n } else {\n let nid = graph.generate_next(0);\n graph.add_edge(parent, nid, table[l].0[depth]);\n dfs(l, r, depth+1, nid, table, graph);\n }\n return;\n }\n\n let mut ll = l;\n let mut last_value = 0;\n let mut cparent = parent;\n while ll <= r {\n let mut rr = ll;\n while rr <= r && table[ll].0[depth] == table[rr].0[depth] {\n rr += 1;\n }\n // [ll, rr)\n let add_len = table[ll].0[depth] - last_value;\n assert!(add_len >= 0);\n if add_len == 0 {\n dfs(ll, rr-1, depth+1, parent, table, graph);\n } else {\n let nid = graph.generate_next(0);\n graph.add_edge(cparent, nid, add_len);\n dfs(ll, rr-1, depth+1, nid, table, graph);\n cparent = nid;\n }\n last_value = table[ll].0[depth];\n ll = rr;\n }\n}\n\n\nfn dfs2(now: usize, par: usize, g: &mut Graph) -> (i64, i64) {\n let mut total_mark = g.vec[now];\n let mut total_cost = 0;\n for (to, len) in g.graph[now].clone() {\n if to == par {\n continue;\n }\n let (m, c) = dfs2(to, now, g);\n total_mark += m;\n total_cost += c + m * len;\n }\n g.mark[now] = total_mark;\n g.dcost[now] = total_cost;\n (total_mark, total_cost)\n}\n\nfn dfs3(now: usize, par: usize, g: &mut Graph) -> i64 {\n let mut best = g.dcost[now];\n for (to, len) in g.graph[now].clone() {\n if to == par {\n continue;\n }\n let mark_back = g.mark[to];\n let dcost_back = g.dcost[to];\n let reduce_cost = g.dcost[to] + g.mark[to] * len;\n let reduce_mark = g.mark[to];\n\n\n g.dcost[to] += (g.dcost[now] - reduce_cost) + (g.mark[now] - reduce_mark) * len;\n g.mark[to] += (g.mark[now] - reduce_mark);\n\n best = min(best, dfs3(to, now, g));\n\n g.mark[to] = mark_back;\n g.dcost[to] = dcost_back;\n\n }\n // debug!(now, best);\n best\n}\n\nconst LIMIT: usize = 5000;\n\nfn main() {\n input! {\n n: usize,\n k: [usize; n]\n };\n\n let mut deg = vec![0; LIMIT+1];\n for k in k {\n if k == 0 {\n deg[1] += 1;\n } else {\n deg[k] += 1;\n }\n }\n let (primes, is_prime) = generate_primes(LIMIT+1);\n\n let mut pn = primes.len();\n let mut vec = vec![];\n // let mut edges = vec![];\n\n let mut l = LIMIT;\n while l >= 2 {\n let mut lw = l;\n while !is_prime[lw] {\n lw -= 1;\n }\n\n for num in (lw..=l).rev() {\n let mut ptbl = vec![0; pn];\n for i in 0..pn {\n let mut num = num as i64;\n while num >= primes[i] {\n ptbl[i] += num / primes[i];\n num /= primes[i];\n }\n }\n ptbl.reverse();\n vec.push((ptbl, num, deg[num]));\n }\n l = lw-1;\n }\n vec.push((vec![0; pn], 1, deg[1]));\n vec.sort();\n\n let mut graph = Graph { vec: vec![], edges: vec![], graph: vec![], mark: vec![], dcost: vec![] };\n graph.generate_next(deg[1]);\n\n dfs(0, vec.len()-1, 0, 0, &vec, &mut graph);\n\n let vn = graph.vec.len();\n\n let mut deg = graph.vec.clone();\n let mut g = vec![vec![]; vn];\n for &(u, v, len) in &graph.edges {\n g[u].push((v, len));\n g[v].push((u, len));\n }\n graph.graph = g;\n graph.mark = vec![0; vn];\n graph.dcost = vec![0; vn];\n\n dfs2(0, vn, &mut graph);\n\n // debug!(graph.graph);\n // debug!(graph.vec);\n\n let ans = dfs3(0, vn, &mut graph);\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "trees", "dp", "graphs", "number theory"], "code_uid": "fdae7f024cae1baa40a5423bc9ba8f68", "src_uid": "40002052843ca0357dbd3158b16d59f4", "difficulty": 2700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Read, Write, BufWriter};\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($format:expr) => (write!(out,$format).unwrap());\n ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())\n }\n let s: Vec = get_word().bytes().map(|x| x as i32 - 48).collect();\n let mut mi = 144;\n for mut v in 0 .. 1000000 {\n let mut t = [0; 6];\n for j in 0 .. 6 {\n t[5 - j] = v % 10;\n v /= 10;\n }\n let mut delta = 0;\n for j in 0 .. 3 { delta += t[j]; }\n for j in 3 .. 6 { delta -= t[j]; }\n let mut diff = 0;\n for j in 0 .. 6 {\n diff += if s[j] != t[j] { 1 } else { 0 };\n }\n if delta == 0 {\n mi = min(mi, diff);\n }\n }\n puts!(\"{}\\n\", mi);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "86ca60425e387a777a22a3971d7126a5", "src_uid": "09601fd1742ffdc9f822950f1d3e8494", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nuse std::cmp::{min,max};\n\nfn main() {\n let a = {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n input.trim().chars().map(|k| k.to_digit(10).unwrap()).collect::>()\n };\n\n let la: Vec<_> = a.iter().cloned().take(3).collect();\n let ra: Vec<_> = a.iter().cloned().skip(3).collect();\n\n let l: u32 = a.iter().cloned().take(3).sum();\n let r: u32 = a.iter().cloned().skip(3).sum();\n\n let diff = r as i32 - l as i32;\n\n if diff == 0 {\n println!(\"0\");\n std::process::exit(0);\n }\n\n let (mut up, mut down) = if diff > 0 {\n (ra, la)\n } else {\n (la, ra)\n };\n\n let mut v = Vec::new();\n v.append(&mut up);\n v.append(&mut down);\n\n for a in v.iter_mut().skip(3) {\n *a = 9 - *a;\n }\n\n v.sort();\n\n let diff = diff.abs();\n\n let mut sum = 0u32;\n\n for (i, k) in v.into_iter().rev().enumerate() {\n if sum >= diff as u32 {\n println!(\"{}\", i);\n std::process::exit(0);\n }\n sum += k;\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "cf8227f4d965474dac1a4e92be0783e3", "src_uid": "09601fd1742ffdc9f822950f1d3e8494", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, [ $t:tt ]) => {{\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }};\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused)]\nmacro_rules! debug {\n ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());\n}\n#[allow(unused)]\nmacro_rules! debugln {\n ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());\n}\n\n/// Verified by https://atcoder.jp/contests/arc093/submissions/3968098\nmod mod_int {\n use std::ops::*;\n pub trait Mod: Copy { fn m() -> i64; }\n #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]\n pub struct ModInt { pub x: i64, phantom: ::std::marker::PhantomData }\n impl ModInt {\n // x >= 0\n pub fn new(x: i64) -> Self { ModInt::new_internal(x % M::m()) }\n fn new_internal(x: i64) -> Self {\n ModInt { x: x, phantom: ::std::marker::PhantomData }\n }\n pub fn pow(self, mut e: i64) -> Self {\n debug_assert!(e >= 0);\n let mut sum = ModInt::new_internal(1);\n let mut cur = self;\n while e > 0 {\n if e % 2 != 0 { sum *= cur; }\n cur *= cur;\n e /= 2;\n }\n sum\n }\n #[allow(dead_code)]\n pub fn inv(self) -> Self { self.pow(M::m() - 2) }\n }\n impl>> Add for ModInt {\n type Output = Self;\n fn add(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x + other.x;\n if sum >= M::m() { sum -= M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Sub for ModInt {\n type Output = Self;\n fn sub(self, other: T) -> Self {\n let other = other.into();\n let mut sum = self.x - other.x;\n if sum < 0 { sum += M::m(); }\n ModInt::new_internal(sum)\n }\n }\n impl>> Mul for ModInt {\n type Output = Self;\n fn mul(self, other: T) -> Self { ModInt::new(self.x * other.into().x % M::m()) }\n }\n impl>> AddAssign for ModInt {\n fn add_assign(&mut self, other: T) { *self = *self + other; }\n }\n impl>> SubAssign for ModInt {\n fn sub_assign(&mut self, other: T) { *self = *self - other; }\n }\n impl>> MulAssign for ModInt {\n fn mul_assign(&mut self, other: T) { *self = *self * other; }\n }\n impl Neg for ModInt {\n type Output = Self;\n fn neg(self) -> Self { ModInt::new(0) - self }\n }\n impl ::std::fmt::Display for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n self.x.fmt(f)\n }\n }\n impl ::std::fmt::Debug for ModInt {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n let (mut a, mut b, _) = red(self.x, M::m());\n if b < 0 {\n a = -a;\n b = -b;\n }\n write!(f, \"{}/{}\", a, b)\n }\n }\n impl From for ModInt {\n fn from(x: i64) -> Self { Self::new(x) }\n }\n // Finds the simplest fraction x/y congruent to r mod p.\n // The return value (x, y, z) satisfies x = y * r + z * p.\n fn red(r: i64, p: i64) -> (i64, i64, i64) {\n if r.abs() <= 10000 {\n return (r, 1, 0);\n }\n let mut nxt_r = p % r;\n let mut q = p / r;\n if 2 * nxt_r >= r {\n nxt_r -= r;\n q += 1;\n }\n if 2 * nxt_r <= -r {\n nxt_r += r;\n q -= 1;\n }\n let (x, z, y) = red(nxt_r, r);\n (x, y - q * z, z)\n }\n} // mod mod_int\n\nmacro_rules! define_mod {\n ($struct_name: ident, $modulo: expr) => {\n #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]\n struct $struct_name {}\n impl mod_int::Mod for $struct_name { fn m() -> i64 { $modulo } }\n }\n}\nconst MOD: i64 = 998_244_353;\ndefine_mod!(P, MOD);\ntype ModInt = mod_int::ModInt

;\n\n// Depends on ModInt.rs\nfn fact_init(w: usize) -> (Vec, Vec) {\n let mut fac = vec![ModInt::new(1); w];\n let mut invfac = vec![0.into(); w];\n for i in 1 .. w {\n fac[i] = fac[i - 1] * i as i64;\n }\n invfac[w - 1] = fac[w - 1].inv();\n for i in (0 .. w - 1).rev() {\n invfac[i] = invfac[i + 1] * (i as i64 + 1);\n }\n (fac, invfac)\n}\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($($format:tt)*) => (let _ = write!(out,$($format)*););\n }\n input!(n: usize, k: i64);\n let (fac, invfac) = fact_init(n + 1);\n if k > n as i64 - 1 {\n puts!(\"0\\n\");\n return;\n }\n let k = k as usize;\n if k == 0 {\n puts!(\"{}\\n\", fac[n]);\n return;\n }\n let mut inex = ModInt::new(0);\n // Sur(n, n - k)\n for i in 0..n - k + 1 {\n let sgn = if (n - k + i) % 2 == 0 { 1 } else { MOD - 1 };\n let tmp = ModInt::new(i as i64).pow(n as i64);\n inex += tmp * sgn * fac[n - k] * invfac[i] * invfac[n - k - i];\n }\n puts!(\"{}\\n\", inex * fac[n] * invfac[n - k] * invfac[k] * 2);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "fft"], "code_uid": "56623881e9c0d057fd372897f9a2f58a", "src_uid": "6c1a9aaa7bdd7de97220b8c6d35740cc", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nconst P5: i32 = 1_000_000_007;\nconst P6: i64 = P5 as i64;\n#[derive(Debug,Clone,Copy)]\nstruct Field(i32);\n#[allow(dead_code)]\nimpl Field {\n fn new>(a: T) -> Self { Self(Self::cv(a)) }\n fn new_unchecked(a: i32) -> Self { Self(a) }\n fn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n fn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n fn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n}\nimpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\nimpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\nimpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\nimpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\nimpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\nimpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\nimpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\nuse std::fmt::{Display, Formatter, Result};\nimpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n// impl Default for Field { fn default() -> Self { Field(0) }}\nimpl Default for &Field { fn default() -> Self { &Field(0) }}\nimpl PartialEq for Field { fn eq(&self, a: &Self) -> bool { self.0 == a.0 } }\nimpl PartialOrd for Field { fn partial_cmp(&self, a: &Self) -> Option { Some(self.0.cmp(&a.0)) } }\nimpl Eq for Field {}\nimpl Ord for Field { fn cmp(&self, a: &Self) -> Ordering { self.0.cmp(&a.0) } }\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let tt = input.i();\n let mut t = vec![0; n];\n let mut g = vec![0; n];\n let mut z = vec![0; 4];\n for i in 0..n {\n t[i] = input.i();\n g[i] = input.i();\n z[g[i] as usize] += 1;\n }\n let sumt: i32 = t.iter().sum();\n\n let dp2 = {\n let mut dp2 = HashMap::<(i32,i32,i32),Field>::new();\n let mut dp = HashMap::<(i32,i32,i32,i32,i32),Field>::new();\n for g in 1..4 {\n dp.insert((0,0,0,0,g), Field(1));\n }\n for _i in 0..n {\n let mut d = HashMap::<(i32,i32,i32,i32,i32),Field>::new();\n for ((h,a,b,c,l), y) in dp.into_iter() {\n let mut p = [0,a,b,c];\n let mut pf = [Field(0),Field(a),Field(b),Field(c)];\n for g in 1..4 {\n let gu = g as usize;\n if (h == 0 && g != l) || (h > 0 && g == l) {\n continue;\n }\n p[gu] += 1;\n pf[gu] += Field(1);\n if (1..4).all(|i| p[i] <= z[i]) {\n let key = (h + 1, p[1], p[2], p[3], g);\n let res = y * pf[g as usize] + *d.get(&key).unwrap_or_default();\n d.insert(key, res);\n }\n p[gu] -= 1;\n pf[gu] -= Field(1);\n }\n }\n\n for (&(_,a,b,c,_),&x) in d.iter() {\n let key = (a,b,c);\n let res = *dp2.get(&key).unwrap_or_default();\n dp2.insert(key, res + x);\n }\n dp = d;\n // println!(\"\\n-----------------------: {}\", _i);\n // for ((h,a,b,c,g),x) in dp.iter() {\n // println!(\"{} {} {} {} {}: {}\", h,a,b,c,g,x);\n // }\n }\n dp2\n };\n // eprintln!(\"DP2\");\n // for ((a,b,c),x) in dp2.iter() {\n // println!(\"dp2 {} {} {} : {}\", a,b,c,x);\n // }\n\n let dp1 = {\n let mut st = [0; 3];\n st[2] = 1;\n st[1] = st[2] * (z[2] + 1);\n st[0] = st[1] * (z[1] + 1);\n let st = st;\n let sz = (st[0] * (sumt + 1)) as usize;\n\n let mut aa = vec![Field(0); sz];\n let mut dp = HashSet::::new();\n dp.insert(0);\n aa[0] = Field(1);\n for i in 0..n {\n if g[i] == 3 { continue; }\n\n let mut d = HashSet::::new();\n let mut a = vec![Field(0); sz];\n let x = t[i];\n let g = g[i] as usize;\n for &s in dp.iter() {\n let key = s + (x * st[0]) + st[g];\n d.insert(key);\n a[key as usize] += aa[s as usize];\n }\n for key in d.into_iter() {\n let s = key as usize;\n aa[s] += a[s];\n dp.insert(key);\n }\n }\n let mut dp1 = HashMap::<(i32,i32,i32),Field>::new();\n for s in dp.into_iter() {\n let t = s / st[0];\n let a = s % st[0] / st[1];\n let b = s % st[1] / st[2];\n dp1.insert((t,a,b),aa[s as usize]);\n }\n dp1\n };\n // eprintln!(\"DP1\");\n // for ((a,b,c),x) in dp1.iter() {\n // println!(\"dp1 {} {} {} : {}\", a,b,c,x);\n // }\n\n let dp3 = {\n let mut st = [0; 4];\n st[3] = 1;\n st[0] = st[3] * (z[3] + 1);\n let st = st;\n let sz = (st[0] * (sumt + 1)) as usize;\n\n let mut aa = vec![Field(0); sz];\n let mut dp = HashSet::::new();\n dp.insert(0);\n aa[0] = Field(1);\n for i in 0..n {\n if g[i] != 3 { continue; }\n\n let mut d = HashSet::::new();\n let mut a = vec![Field(0); sz];\n let x = t[i];\n let g = g[i] as usize;\n for &s in dp.iter() {\n let key = s + (x * st[0]) + st[g];\n d.insert(key);\n a[key as usize] += aa[s as usize];\n }\n for key in d.into_iter() {\n let s = key as usize;\n aa[s] += a[s];\n dp.insert(key);\n }\n }\n let mut dp3 = HashMap::<(i32,i32),Field>::new();\n for s in dp.into_iter() {\n let t = s / st[0];\n let c = s % st[0] / st[3];\n dp3.insert((t,c),aa[s as usize]);\n }\n dp3\n };\n // eprintln!(\"DP3\");\n // for ((a,b),x) in dp3.iter() {\n // println!(\"dp3 {} {} : {}\", a,b,x);\n // }\n\n let dp1 = {\n let mut dp = HashMap::<(i32,i32,i32),Field>::new();\n for ((tab,a,b),res1) in dp1 {\n let tc = tt - tab;\n if tc < 0 { continue; }\n for c in 0..=z[3] {\n if let Some(&res2) = dp3.get(&(tc,c)) {\n let res3 = *dp.get(&(a,b,c)).unwrap_or_default();\n dp.insert((a,b,c), res3 + res1*res2);\n }\n }\n }\n dp\n };\n // println!(\"DP1\");\n // println!(\"DP1\");\n // for ((a,b,c),&x) in dp1.iter() {\n // println!(\"dpX {} {} {} : {}\", a,b,c,x);\n // }\n\n let mut sol = Field::new_unchecked(0);\n for a in 0..=z[1] as i32 {\n for b in 0..=z[2] as i32 {\n for c in 0..=z[3] as i32 {\n let x = *dp1.get(&(a,b,c)).unwrap_or_default();\n let y = *dp2.get(&(a,b,c)).unwrap_or_default();\n sol += x * y;\n }\n }\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics", "bitmasks"], "code_uid": "f15ba3cb88972264cf898036ad767cfd", "src_uid": "ac2a37ff4c7e89a345b189e4891bbf56", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rust\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::*;\n#[allow(unused_imports)] use std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! a {\n ($c: tt, $x: expr, $y: expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a>, }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n\n#[allow(dead_code)]\nfn build_counting_hashmap(i: T) -> HashMap\n where T: Iterator {\n let mut m = HashMap::new();\n for k in i {\n let n = 1 + if let Some(&n) = m.get(&k) { n } else { 0 };\n m.insert(k, n);\n }\n m\n}\n\nconst M: i64 = 1_000_000_007;\n\n// fn mul(a: i64, b: i64) -> i64 { a * b % M }\nfn add(a: i64, b: i64) -> i64 {\n let mut x = (a + b) % M;\n if x < 0 { x += M; }\n x\n}\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let tt = input.i();\n let mut t = vec![0; n];\n let mut g = vec![0; n];\n let mut z = vec![0; 4];\n for i in 0..n {\n t[i] = input.i();\n g[i] = input.i();\n z[g[i] as usize] += 1;\n }\n\n let f = |a,b| if a == b { 1 } else { 0 };\n\n let dp1 = {\n let mut dp = HashMap::<(i32,i32,i32,i32),i64>::new();\n dp.insert((0,0,0,0), 1);\n for i in 0..n {\n let mut d = HashMap::<(i32,i32,i32,i32),i64>::new();\n let x = t[i];\n let g = g[i];\n for (&(t,a,b,c), &y) in dp.iter() {\n let key = (t + x, a + f(g, 1), b + f(g, 2), c + f(g, 3));\n let res = *d.get(&key).unwrap_or(&0);\n d.insert(key, add(res, y));\n }\n for (key, y) in d.into_iter() {\n let res = *dp.get(&key).unwrap_or(&0);\n dp.insert(key, add(res, y));\n }\n }\n dp\n };\n // for ((t,a,b,c),x) in dp1.iter() {\n // println!(\"dp1 {} {} {} {} : {}\", t,a,b,c,x);\n // }\n\n let dp2 = {\n let mut dp2 = HashMap::<(i32,i32,i32),i64>::new();\n let mut dp = HashMap::<(i32,i32,i32,i32,i32),i64>::new();\n for g in 1..4 {\n dp.insert((0,0,0,0,g), 1);\n }\n for _i in 0..n {\n let mut d = HashMap::<(i32,i32,i32,i32,i32),i64>::new();\n for ((h,a,b,c,l), y) in dp.into_iter() {\n let mut p = [0,a,b,c];\n for g in 1..4 {\n if (h == 0 && g != l) || (h > 0 && g == l) {\n continue;\n }\n p[g as usize] += 1;\n if (1..4).all(|i| p[i] <= z[i]) {\n let key = (h + 1, p[1], p[2], p[3], g);\n let res = add(y * p[g as usize] as i64, *d.get(&key).unwrap_or(&0));\n d.insert(key, res);\n }\n p[g as usize] -= 1;\n }\n }\n\n for (&(_,a,b,c,_),&x) in d.iter() {\n let key = (a,b,c);\n let res = *dp2.get(&key).unwrap_or(&0);\n dp2.insert(key, add(res, x));\n }\n dp = d;\n // println!(\"\\n-----------------------: {}\", _i);\n // for ((h,a,b,c,g),x) in dp.iter() {\n // println!(\"{} {} {} {} {}: {}\", h,a,b,c,g,x);\n // }\n }\n dp2\n };\n // for ((a,b,c),x) in dp2.iter() {\n // println!(\"dp2 {} {} {} : {}\", a,b,c,x);\n // }\n\n let mut sol: i64 = 0;\n for a in 0..z[1]+1 {\n let a = a as i32;\n for b in 0..z[2]+1 {\n let b = b as i32;\n for c in 0..z[3]+1 {\n let c = c as i32;\n let x = dp1.get(&(tt,a,b,c)).unwrap_or(&0);\n let y = dp2.get(&(a,b,c)).unwrap_or(&0);\n sol = add(sol, x * y);\n }\n }\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["dp", "combinatorics", "bitmasks"], "code_uid": "0b12cea16561d340d521ffc3c389b0fa", "src_uid": "ac2a37ff4c7e89a345b189e4891bbf56", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\n#![allow(unused_macros)]\n#![allow(overflowing_literals)]\n#![allow(unused_must_use)]\n#![allow(non_camel_case_types)]\n\nuse std::collections::*;\nuse std::io::*;\nuse std::cmp::{max, min, Ordering};\nuse std::f64::consts::*;\nuse std::mem::{swap, size_of_val, size_of};\nuse std::fs::File;\nuse std::rc::*;\nuse std::ascii::*;\nuse std::ops::*;\nuse std::num::*;\nuse std::process::*;\n//use std::ptr::*;\nuse std::iter::{once, repeat};\n\nconst INF: i32 = std::i32::MAX;\nconst LINF: i64 = std::i64::MAX;\nconst MOD: usize = 1000000007;\n\nstruct Input {\n\tbuffer: Buf,\n}\n\nimpl Input {\n\tfn read_char(&mut self) -> char {\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\tx[0] as char\n\t}\n\tfn read_line(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] < b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] >= b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n\n\tfn read_word(&mut self) -> String {\n\t\tlet mut v = Vec::new();\n\t\tlet mut x = [255u8];\n\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\twhile x[0] <= b' ' && x[0] != 255u8 {\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\twhile x[0] > b' ' && x[0] != 255u8 {\n\t\t\tv.push(x[0]);\n\t\t\tx[0] = 255u8;\n\t\t\tself.buffer.read(&mut x).expect(\"EOF\");\n\t\t}\n\t\tString::from_utf8(v).unwrap()\n\t}\n}\n\nmacro_rules! read {\n () => {};\n\t($inf:ident, $t:ty) => ($inf.read_word().parse::<$t>().expect(\"Parsing error\"));\n\t($inf:ident, $($t:ty),*) => (($($inf.read_word().parse::<$t>().expect(\"Parsing error\")),*));\n}\nfn gcd(mut a: T, mut b: T) -> T\n\twhere T: ShrAssign + BitAnd + Ord + From + Clone + SubAssign + ShlAssign + Copy\n{\n\tlet one = T::from(1);\n\tlet zero = T::from(0);\n\tlet mut ans = 0;\n\tif a < b {\n\t\tswap(&mut a, &mut b);\n\t}\n\twhile b > zero {\n\t\tif (a & one > zero) && (b & one > zero) {\n\t\t\ta -= b;\n\t\t} else if a & one > zero {\n\t\t\tb >>= one;\n\t\t} else if b & one > zero {\n\t\t\ta >>= one;\n\t\t} else {\n\t\t\tans += 1;\n\t\t\ta >>= one;\n\t\t\tb >>= one;\n\t\t}\n\t\tif a < b {\n\t\t\tswap(&mut a, &mut b);\n\t\t}\n\t}\n\ta <<= ans;\n\ta\n}\n\nfn powmod(mut base: X, mut exp: Y, mm: X) -> X\n\twhere X: Copy + Clone + Mul + Rem + From,\n\t Y: ShrAssign + Copy + Clone + BitAnd + From + Ord\n{\n\tlet mut res = X::from(1);\n\twhile exp > Y::from(0) {\n\t\tif exp & Y::from(1) > Y::from(0) {\n\t\t\tres = res * base % mm;\n\t\t}\n\t\tbase = base * base % mm;\n\t\texp >>= Y::from(1);\n\t}\n\tres\n}\n\nfn main() {\n\tmatch std::env::var(\"home\") {\n\t\tOk(_x) => {\n\t\t\tlet mut inf = Input { buffer: BufReader::new(File::open(\"input.txt\").expect(\"File not found\")) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t\tErr(_e) => {\n\t\t\tlet stdin = stdin();\n\t\t\tlet istr = stdin.lock();\n\t\t\tlet mut inf = Input { buffer: BufReader::new(istr) };\n\t\t\tlet stdout = stdout();\n\t\t\tlet ostr = stdout.lock();\n\t\t\tlet mut ouf = BufWriter::new(ostr);\n\t\t\tsolve(&mut inf, &mut ouf);\n\t\t}\n\t}\n}\n\n\nfn solve(inf: &mut Input, ouf: &mut Output) {\n\tlet n = read!(inf,usize);\n\tlet mut a = vec![0; n];\n\tfor i in 0..n {\n\t\ta[i] = read!(inf,usize);\n\t}\n\ta.sort_unstable();\n\ta.dedup();\n\tlet mut pos = 0;\n\twhile pos < n && a[pos] == 0 {\n\t\tpos += 1;\n\t}\n\twriteln!(ouf, \"{}\", a.len() - pos);\n}\n\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation"], "code_uid": "bd5bbdcee0571e40f3887b2607fe3757", "src_uid": "3b520c15ea9a11b16129da30dcfb5161", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::fs::File;\n\nfn main() {\n let stdin = io::stdin();\n let buf :Box = if cfg!(feature = \"intxt\") {\n eprintln!(\"file mode\");\n let file = File::open(\"in.txt\").unwrap();\n Box::new(io::BufReader::new(file))\n } else {\n eprintln!(\"stdin mode\");\n Box::new(stdin.lock())\n };\n let mut sc = Scanner::new(buf);\n\n let n :i32 = sc.next();\n let mut vec = Vec::new();\n for _ in 0..n {\n let a :i32 = sc.next();\n vec.push(a);\n }\n vec.sort();\n vec.reverse();\n let mut a = vec[0];\n let mut cnt = 1;\n for x in vec {\n if x != a {\n a = x;\n if x > 0 {\n cnt += 1;\n }\n }\n }\n println!(\"{}\", cnt);\n}\n\n\nstruct Scanner {\n reader: B,\n buffer: Vec,\n}\n\nimpl Scanner {\n fn new(reader: B) -> Self {\n Self {\n reader,\n buffer: Vec::new(),\n }\n }\n\n fn next(&mut self) -> T\n where\n T::Err: std::fmt::Debug,\n {\n if let Some(s) = self.buffer.pop() {\n T::from_str(&s).unwrap()\n } else {\n let mut s = String::new();\n let r = self.reader.read_line(&mut s).unwrap();\n assert!(r > 0);\n self.buffer = s.split_whitespace().rev().map(String::from).collect();\n return self.next();\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation"], "code_uid": "dbbf925992ea98165dd6c3bafbcb265d", "src_uid": "3b520c15ea9a11b16129da30dcfb5161", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n use std::io;\n use std::io::prelude::*;\n io::stdin().read_to_string(&mut input).unwrap();\n\n let mut it = input.split_whitespace();\n\n let n: usize = it.next().unwrap().parse().unwrap();\n\n let a: Vec = it.map(|x| x.parse().unwrap()).collect();\n\n let mut set = [false; 601];\n\n for a in a {\n set[a] = true;\n }\n\n let ans = set[1..].iter().filter(|&&x| x).count();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation"], "code_uid": "9f67dc332511a1a71d94705175c35c2f", "src_uid": "3b520c15ea9a11b16129da30dcfb5161", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let (n, m) = parse_line!(usize, usize);\n let l = parse_line_to_vec!(usize);\n let mut result = vec![0; n];\n let mut ok = true;\n for i in 1..m {\n let leader = l[i - 1] - 1;\n let mut diff = (n + l[i] - l[i - 1]) % n;\n if diff == 0 {\n diff = n;\n }\n if result[leader] == 0 {\n result[leader] = diff;\n }else if result[leader] != diff {\n ok = false;\n }\n }\n for i in 0..n {\n if result[i] == 0 {\n continue;\n }\n let mut local = true;\n for j in 0..i {\n local &= result[i] != result[j];\n }\n ok &= local;\n }\n if !ok {\n return println!(\"-1\");\n }\n let mut s = std::collections::HashSet::::new();\n s.extend(result.iter());\n let mut next = 1;\n for i in 0..n {\n if result[i] != 0 {\n continue;\n }\n while s.contains(&next) {\n next += 1;\n }\n result[i] = next;\n next += 1;\n }\n for x in result {\n print!(\"{} \", x);\n }\n println!();\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "783360e16e16b059efa945444d92cf35", "src_uid": "4a7c959ca279d0a9bd9bbf0ce88cf72b", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 998_244_353;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n\nfn gcd(a: usize, b: usize) -> usize {\n if b == 0 {a} else {gcd(b, a % b)}\n}\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let s: Vec = s.trim().chars().map(|c| c.to_digit(10).unwrap() as usize).collect();\n let mut ans = s.iter().fold(ModInt::zero(), |s, a| ModInt(10) * s + ModInt(*a as u32));\n for x in 1..=9 {\n for y in 1..x {\n if gcd(x, y) > 1 {\n continue;\n }\n // \u30ad\u30e3\u30ea\u30fc\u629c\u304d\u3067\u78ba\u5b9a\u3057\u3066\u308b\u6841\u6570\u306e\u7bc4\u56f2\u3067n\u4ee5\u4e0b\u306a\u30890\n // x\u306e\u30ad\u30e3\u30ea\u30fc\u304c\u3044\u304f\u3064\n // y\u306e\u30ad\u30e3\u30ea\u30fc\u304c\u3044\u304f\u3064\n // x\u306e\u51fa\u73fe\n // y\u306e\u51fa\u73fe\n let m = 9 / x;\n let init = vec![vec![vec![vec![vec![ModInt::zero(); 1 << m]; 1 << m]; 9]; 9]; 2];\n let mut now = init.clone();\n let mut next = init.clone();\n now[0][0][0][0][0] = ModInt::one();\n for &digit in s.iter().rev() {\n next.clone_from(&init);\n for (cond, v) in now.iter().enumerate() {\n for (cx, v) in v.iter().enumerate() {\n for (cy, v) in v.iter().enumerate() {\n for (bit_x, v) in v.iter().enumerate() {\n for (bit_y, &v) in v.iter().enumerate() {\n for d in 0..10 {\n let carry_x = (cx + d * x) / 10;\n let carry_y = (cy + d * y) / 10;\n let dx = (cx + d * x) % 10;\n let dy = (cy + d * y) % 10;\n let nx = bit_x | if dx > 0 && dx % x == 0 {1 << (dx / x - 1)} else {0};\n let ny = bit_y | if dy > 0 && dy % y == 0 && dy / y <= m {1 << (dy / y - 1)} else {0};\n if dx < digit {\n next[0][carry_x][carry_y][nx][ny] += v;\n } else if dx > digit {\n next[1][carry_x][carry_y][nx][ny] += v;\n } else {\n next[cond][carry_x][carry_y][nx][ny] += v;\n }\n }\n }\n }\n }\n }\n }\n std::mem::swap(&mut next, &mut now);\n }\n for (i, v) in now[0][0][0].iter().enumerate() {\n for (j, &v) in v.iter().enumerate() {\n let mut ok = false;\n for k in 0..m {\n ok |= ((i >> k) & 1 == 1) && ((j >> k) & 1 == 1);\n }\n if ok && v.0 > 0 {\n ans += v + v;\n }\n }\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "350bd3123b81780bed015186c472cbdd", "src_uid": "b6f2061e2ca174c2385bf4520d232aaf", "difficulty": 2700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut buf = String::new();\n for _i in 0..3 {\n let _ = stdin().read_line(&mut buf);\n buf = buf.trim_end().to_string();\n }\n\n let x = buf.as_bytes();\n let mut ans = true;\n for i in 0..x.len()/ 2 {\n ans = ans && x[i] == x[x.len() - i - 1];\n }\n\n println!(\"{}\", if ans { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "762f0129844ce219c700d223c1ffbb63", "src_uid": "6a5fe5fac8a4e3993dc3423180cdd6a9", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn getline() -> String{\n let mut __ret = String::new();\n std::io::stdin().read_line(&mut __ret).ok();\n return __ret;\n}\n\nfn main() {\n let s = getline();\n let inp:Vec<_> = s.trim().split(' ').collect();\n let mut n: i32 = inp[0].parse().unwrap();\n let k: usize = inp[1].parse().unwrap();\n let mut ans = vec![];\n for i in 2..n-1 {\n while n%i == 0 {\n if ans.len() == k-1 {\n break;\n }\n ans.push(i);\n n /= i;\n }\n }\n if ans.len() == k-1 && n != 1 {\n for e in &ans {\n print!(\"{} \",e);\n }\n println!(\"{}\",n);\n }else{\n println!(\"-1\");\n }\n}", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "f594e055b7d9f813a2a6903a1ca1f55d", "src_uid": "bd0bc809d52e0a17da07ccfd450a4d79", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code)]\n#![allow(unused_imports)]\nuse std::cmp::{min, max};\nuse std::io::{BufWriter, stdin, stdout, Write};\nconst BITS: usize = 19;\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n let n: i32 = scan.next::();\n let m: i32 = scan.next::();\n\n let mut arr: Vec<(i32, i32)> = Vec::new();\n\n for _i in 0..m {\n let a: i32 = scan.next::();\n let b: i32 = scan.next::();\n arr.push((a, b));\n }\n\n arr.sort_by(|a, b| a.1.cmp(&b.1));\n arr.reverse();\n\n let mut total: i32 = 0;\n let mut total_boxes: i32 = 0;\n\n 'outer: for (a, b) in arr.iter() {\n if total_boxes >= n {\n break;\n }\n 'inner: for _i in 0..*a {\n if total_boxes >= n {\n break 'outer;\n }\n total_boxes += 1;\n total += *b;\n }\n }\n\n writeln!(out, \"{}\", total);\n}", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "d7012c0fa9f1177b78bda878620c54b6", "src_uid": "c052d85e402691b05e494b5283d62679", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_imports)]\n#[rustfmt::skip] #[macro_use] mod scanner {use std::io::{stdin, BufReader, Bytes, Error as IoError, Read, Stdin};use std::str::{self, FromStr, Utf8Error};#[derive(Debug)] pub struct Scanner { bytes: Bytes>, buf: Vec, } #[derive(Debug)] pub enum ScanError { Io(IoError), Parse(T::Err, String), NonUtf8(Utf8Error, Vec), } impl Scanner { pub fn stdin() -> Self { Self::new(stdin()) } } impl Scanner { pub fn new(reader: R) -> Self { Self { bytes: BufReader::new(reader).bytes(), buf: Vec::new(), } } #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Result> { assert!(self.buf.is_empty());for b in &mut self.bytes { let b = b.map_err(ScanError::Io)?;if b.is_ascii_whitespace() { if self.buf.is_empty() { continue;} else { break;} } else { self.buf.push(b);} } match str::from_utf8(&self.buf) { Err(err) => Err(ScanError::NonUtf8(err, std::mem::take(&mut self.buf))), Ok(s) => { let ret = s.parse().map_err(|err| ScanError::Parse(err, s.to_owned()));self.buf.clear();ret } } } } #[macro_export] macro_rules! scan { ($scanner:expr) => { $scanner.next().expect(\"failed to read token\") };($scanner:expr, $type:ty) => { $scanner .next::<$type>() .expect(concat!(\"failed to read token of type \", stringify!($type))) };($scanner:expr, $type:ty; $n:expr) => { (0..$n).map(|_| scan!($scanner)).collect::>() };($scanner:expr, $($type:ty),+) => { ($( scan!($scanner, $type), )+) };} }\n#[rustfmt::skip] #[macro_use] mod writer {use std::fmt::Display;use std::io::{stdout, BufWriter, Error as IoError, Stdout, Write};#[derive(Debug)] pub struct Writer { writer: BufWriter, } impl Writer { pub fn stdout() -> Self { Self::new(stdout()) } } impl Writer { pub fn new(writer: W) -> Self { Self { writer: BufWriter::new(writer), } } pub fn write>(&mut self, val: T) -> Result<(), IoError> { val.write_to(&mut self.writer) } pub fn flush(&mut self) -> Result<(), IoError> { self.writer.flush() } } pub trait Writable { fn write_to(self, w: &mut W) -> Result<(), IoError>;} #[non_exhaustive] pub struct Single;impl Writable for T { fn write_to(self, w: &mut W) -> Result<(), IoError> { writeln!(w, \"{}\", self) } } #[non_exhaustive] pub struct Many;impl Writable for I where I: Iterator, I::Item: Display, { fn write_to(mut self, w: &mut W) -> Result<(), IoError> { if let Some(x) = self.next() { write!(w, \"{}\", x)?;} else { return Ok(());} for x in self { write!(w, \" {}\", x)?;} writeln!(w) } } #[non_exhaustive] pub struct Array;impl Writable for &[T] { fn write_to(self, w: &mut W) -> Result<(), IoError> { self.iter().write_to(w) } } }\n#[rustfmt::skip] #[macro_use] mod prefix_sum {use std::ops::{Add, Bound, Range, RangeBounds, Sub};#[derive(Debug, Clone)] pub struct PrefixOp { pref: Vec, inverse: Option, } impl PrefixOp { pub fn len(&self) -> usize { self.pref.len() } pub fn is_empty(&self) -> bool { self.pref.is_empty() } #[track_caller] fn verify_range_bounds>(&self, range: R) -> Range { let start = match range.start_bound() { Bound::Unbounded => 0, Bound::Included(&x) => x, Bound::Excluded(&x) => x + 1, };let end = match range.end_bound() { Bound::Unbounded => self.len(), Bound::Included(&x) => x + 1, Bound::Excluded(&x) => x, };assert!( start < end, \"range inverted: start >= end ({} >= {})\", start, end );assert!( end <= self.len(), \"range out of bounds: end > len ({} > {})\", end, self.len() );Range { start, end } } pub fn query_prefix>(&self, range: R) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);assert!(start == 0, \"query start bound is non-zero: {} > 0\", start);self.pref[end - 1].clone() } } impl PrefixOp { pub fn new(mut arr: Vec, op: F) -> Self where F: Fn(&T, &T) -> T, { for i in 1..arr.len() { arr[i] = op(&arr[i - 1], &arr[i]);} PrefixOp { pref: arr, inverse: None, } } } impl PrefixOp where I: Fn(&T, &T) -> T, { pub fn new_invertible(mut arr: Vec, op: F, inverse: I) -> Self where F: Fn(&T, &T) -> T, { for i in 1..arr.len() { arr[i] = op(&arr[i - 1], &arr[i]);} PrefixOp { pref: arr, inverse: Some(inverse), } } pub fn query>(&self, range: R) -> T where T: Clone, { let Range { start, end } = self.verify_range_bounds(range);if start == 0 { self.pref[end - 1].clone() } else { (self .inverse .as_ref() .expect(\"range query is not supported on non-invertible operation\"))( &self.pref[end - 1], &self.pref[start - 1], ) } } } type NextFn = fn(&T, &T) -> T;pub trait PrefixSums { type Data;fn prefix_sums(self) -> PrefixOp>;} impl PrefixSums for Vec where T: Add + Sub + Clone, { type Data = T;fn prefix_sums(self) -> PrefixOp> { PrefixOp::new_invertible( self, |a, b| a.clone() + b.clone(), |b, a| b.clone() - a.clone(), ) } } }\n#[rustfmt::skip] #[macro_use] mod util { pub trait IntoVec { fn into_vec(self) -> Vec;} #[non_exhaustive] pub struct Owned;impl IntoVec for I where I: Iterator, { fn into_vec(self) -> Vec { self.collect() } } #[non_exhaustive] pub struct Reference;impl<'a, I, T> IntoVec for I where I: Iterator, T: Clone + 'a, { fn into_vec(self) -> Vec { self.cloned().collect() } } pub trait Argmax { fn argmax(self) -> Option;} impl Argmax for I where I: Iterator, I::Item: Ord, { fn argmax(self) -> Option { self.fold((0, None), |(i, mx), next| { if let Some((mx_i, mx_v)) = mx { if next.gt(&mx_v) { (i + 1, Some((i, next))) } else { (i + 1, Some((mx_i, mx_v))) } } else { (i + 1, Some((i, next))) } }) .1 .map(|x| x.0) } } pub trait Sorted { fn sorted(self) -> Self;} impl Sorted for Vec where T: Ord, { fn sorted(mut self) -> Self { self.sort();self } } pub trait Choose { fn choose(self, a: T, b: T) -> T;} impl Choose for bool { fn choose(self, a: T, b: T) -> T { if self { a } else { b } } } #[allow(unused_macros)] macro_rules! p { ( $( $x:expr ),* ) => { #[cfg(any(debug_assertions, debug_print))] { dbg!( $( & $x, )* );} };} }\n#[rustfmt::skip] #[macro_use] mod graph {use std::{convert::TryInto, fmt::Debug};#[derive(Debug, Clone, PartialEq, Eq)] pub struct Graph { adj: Vec>, } pub trait VertexRepr: Clone + Copy { fn from(id: usize) -> Self;fn to_usize(self) -> usize;fn invalid() -> Self;fn is_valid(&self) -> bool;} impl VertexRepr for u32 { fn from(id: usize) -> Self { let id = match id.try_into() { Ok(x) => x, Err(_) => panic!(\"vertex id {} excceds implementation limit\", id), };assert_ne!( id, u32::MAX, \"vertex id {} exceeds implementation limit\", id );id } fn to_usize(self) -> usize { self as usize } fn invalid() -> Self { u32::MAX } fn is_valid(&self) -> bool { *self != u32::MAX } } impl Graph { pub fn empty() -> Self { Graph { adj: Vec::new() } } pub fn with_vertices(n: usize) -> Self { Graph { adj: (0..n).map(|_| Vec::new()).collect(), } } #[track_caller] fn verify_vertex(&self, v: Id) -> Id { assert!(v.is_valid(), \"vertex is invalid\");assert!( v.to_usize() < self.n(), \"vertex {} does not exist\", v.to_usize() );v } pub fn add_vertex(&mut self) -> Id { self.adj.push(Vec::new());Id::from(self.adj.len() - 1) } pub fn add_edge(&mut self, u: Id, v: Id, directed: bool) { let (u, v) = (self.verify_vertex(u), self.verify_vertex(v));if !directed { self.adj[v.to_usize()].push(u);} self.adj[u.to_usize()].push(v);} pub fn adjacent( &self, u: Id, ) -> impl Iterator + DoubleEndedIterator + ExactSizeIterator + '_ { let u = self.verify_vertex(u);self.adj[u.to_usize()].iter().copied() } pub fn n(&self) -> usize { self.adj.len() } pub fn dfs(&self, source: Id, mut state: DfsState) -> DfsState { let s = self.verify_vertex(source).to_usize();let mut stack = Vec::new();if !state.visited[s] { stack.push((s, 0));state.visited[s] = true;state.parent[s] = Id::invalid();state.depth[s] = Id::from(0);} while let Some((cur, child_id)) = stack.last_mut() { if let Some(&child_vid) = self.adj[*cur].get(*child_id) { *child_id += 1;let child = child_vid.to_usize();if !state.visited[child] { state.visited[child] = true;state.parent[child] = Id::from(*cur);state.depth[child] = Id::from(stack.len());stack.push((child, 0));} } else { stack.pop();} } state } } #[non_exhaustive] #[derive(Debug, Clone, PartialEq, Eq)] pub struct DfsState { pub visited: Vec, pub parent: Vec, pub depth: Vec, } impl DfsState { pub fn new(graph: &Graph) -> Self { DfsState { visited: vec![false; graph.n()], parent: vec![Id::invalid(); graph.n()], depth: vec![Id::invalid(); graph.n()], } } } }\n#[rustfmt::skip] #[macro_use] mod number_theory { pub fn gcd(mut a: i64, mut b: i64) -> i64 { while b != 0 { let t = b;b = a % b;a = t;} a.checked_abs().unwrap_or(a) } pub fn egcd(a: i64, b: i64) -> (i64, i64, i64) { if b == 0 { if a >= 0 || a == i64::MIN { (a, 1, 0) } else { (-a, -1, 0) } } else { let (g, s, t) = egcd(b, a % b);(g, t, s - a / b * t) } } pub fn mod_exp(a: i64, mut b: i64, m: i64) -> i64 { assert!(m > 0, \"modulus must be positive: {} <= 0\", m);if b < 0 { return mod_exp( mod_mulinv(a, m), b.checked_neg().expect(\"cannot raise to i64::MIN power\"), m, );} let intermediate_error = \"intermediate value overflowed\";let mut x = 1i64;let mut pwr = a;while b > 0 { if b & 1 > 0 { x = x.checked_mul(pwr).expect(intermediate_error).rem_euclid(m);} pwr = pwr .checked_mul(pwr) .expect(intermediate_error) .rem_euclid(m);b >>= 1;} x } pub fn mod_mulinv(a: i64, m: i64) -> i64 { assert!(m > 0, \"modulus must be positive: {} <= 0\", m);let (g, s, _) = egcd(a, m);assert_eq!( g, 1, \"multiplicative inverse does not exist: {} and {} have gcd {}\", a, m, g );s.rem_euclid(m) } }\n#[rustfmt::skip] #[macro_use] mod segment_tree {use std::{ fmt::{self, Debug, Formatter}, ops::{Bound, Range, RangeBounds}, };pub trait Spec { type Node;type Update: Clone;type Formatter: Format;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node;fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node;fn compose(f: &Self::Update, g: &Self::Update) -> Self::Update;} pub trait EagerSpec { type Node;type Formatter: Format;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node;} impl Spec for T { type Node = T::Node;type Update = ();type Formatter = T::Formatter;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { T::op(a, b) } fn apply(_f: &Self::Update, _a: &Self::Node) -> Self::Node { panic!(\"eager spec does not support range updates\") } fn compose(_f: &Self::Update, _g: &Self::Update) -> Self::Update { panic!(\"eager spec does not support range updates\") } } pub trait Format { type Node;type Input;type Output;fn input(a: Self::Input, i: usize) -> Self::Node;fn output(a: &Self::Node) -> Self::Output;} pub struct SegmentTree { data: Vec, updates: Vec>, needs_update_propagation: bool, } impl SegmentTree { #[track_caller] pub fn new(vals: Vec<::Input>) -> Self { let n = vals.len();let mut data = Vec::with_capacity( n.checked_mul(2) .expect(\"size needed for tree overflowed\") .saturating_sub(1), );data.extend( vals.into_iter() .enumerate() .map(|(i, x)| S::Formatter::input(x, i)) .rev(), );for i in 0..n.saturating_sub(1) { data.push(S::op(&data[2 * i + 1], &data[2 * i]));} data.reverse();let mut updates = Vec::with_capacity(n.saturating_sub(1));updates.resize_with(n.saturating_sub(1), || None);SegmentTree { data, updates, needs_update_propagation: false, } } pub fn len(&self) -> usize { (self.data.len() + 1) / 2 } pub fn is_empty(&self) -> bool { self.data.is_empty() } pub fn height(&self) -> usize { let n = self.len();(0usize.leading_zeros() - n.leading_zeros()) as usize } #[track_caller] pub fn query(&mut self, range: impl RangeBounds) -> ::Output { let Range { start: left, end: right, } = self.verify_range_bounds(range);if self.needs_update_propagation { self.push_updates_to(left + self.len());self.push_updates_to(right + self.len() - 1);} let (mut res_l_owned, mut res_r_owned);let (mut res_l, mut res_r) = (None, None);let (mut l, mut r) = (left + self.len(), right + self.len());while l < r { if l % 2 == 1 { if let Some(prev_res_l) = res_l.take() { res_l_owned = S::op(prev_res_l, &self.data[l - 1]);res_l = Some(&res_l_owned);} else { res_l = Some(&self.data[l - 1]);} l += 1;} if r % 2 == 1 { r -= 1;if let Some(prev_res_r) = res_r { res_r_owned = S::op(&self.data[r - 1], prev_res_r);res_r = Some(&res_r_owned);} else { res_r = Some(&self.data[r - 1]);} } l /= 2;r /= 2;} match (res_l, res_r) { (Some(l), Some(r)) => S::Formatter::output(&S::op(l, r)), (Some(x), None) | (None, Some(x)) => S::Formatter::output(x), (None, None) => unreachable!( \"both left and right results are None - empty query should not have been allowed\" ), } } #[track_caller] fn verify_range_bounds(&self, range: impl RangeBounds) -> Range { let left = match range.start_bound() { Bound::Included(&x) => x, Bound::Excluded(&x) => x + 1, Bound::Unbounded => 0, };let right = match range.end_bound() { Bound::Included(&x) => x + 1, Bound::Excluded(&x) => x, Bound::Unbounded => self.len(), };assert!( left < right, \"range inverted: left >= right ({} >= {})\", left, right );assert!( right <= self.len(), \"range out of bounds: right > n ({} > {})\", right, self.len() );Range { start: left, end: right, } } fn push_updates_to(&mut self, i: usize) { for h in (1..self.height()).rev() { let ip = i >> h;if let Some(upd) = self.updates[ip - 1].take() { self.apply_update_to(2 * ip, &upd);self.apply_update_to(2 * ip + 1, &upd);} } } fn push_updates_to_range(&mut self, range: Range) { let (l, r) = (range.start, range.end - 1);for h in (1..self.height()).rev() { let (lp, rp) = (l >> h, r >> h);for x in lp..=rp { if let Some(upd) = self.updates[x - 1].take() { self.apply_update_to(2 * x, &upd);self.apply_update_to(2 * x + 1, &upd);} } } } fn update_parents_of(&mut self, i: usize) { for h in 1..self.height() { let ip = i >> h;self.data[ip - 1] = S::op(&self.data[2 * ip - 1], &self.data[2 * ip]);if self.needs_update_propagation { if let Some(ref upd) = self.updates[ip - 1] { self.data[ip - 1] = S::apply(upd, &self.data[ip - 1]);} } } } fn update_parents_of_range(&mut self, range: Range) { let (l, r) = (range.start, range.end - 1);for h in 1..self.height() { let (lp, rp) = (l >> h, r >> h);for x in lp..=rp { self.data[x - 1] = S::op(&self.data[2 * x - 1], &self.data[2 * x]);if self.needs_update_propagation { if let Some(ref upd) = self.updates[x - 1] { self.data[x - 1] = S::apply(upd, &self.data[x - 1]);} } } } } fn apply_update_to(&mut self, i: usize, f: &S::Update) { self.data[i - 1] = S::apply(f, &self.data[i - 1]);if i < self.len() { self.updates[i - 1] = match self.updates[i - 1].take() { None => Some(f.clone()), Some(g) => Some(S::compose(&g, f)), };} } #[track_caller] fn verify_index(&self, index: usize) -> usize { assert!( index < self.len(), \"index out of bounds: index >= n ({} >= {})\", index, self.len() );index } #[track_caller] pub fn set(&mut self, index: usize, val: ::Input) { let i = self.verify_index(index) + self.len();if self.needs_update_propagation { self.push_updates_to(i);} self.data[i - 1] = S::Formatter::input(val, i);self.update_parents_of(i) } #[track_caller] pub fn get(&mut self, index: usize) -> ::Output { let i = self.verify_index(index) + self.len();if self.needs_update_propagation { self.push_updates_to(i);} S::Formatter::output(&self.data[i - 1]) } #[track_caller] pub fn update(&mut self, range: impl RangeBounds, update: S::Update) { let Range { start: left, end: right, } = self.verify_range_bounds(range);if self.needs_update_propagation { self.push_updates_to(left + self.len());self.push_updates_to(right + self.len() - 1);} self.needs_update_propagation = true;let (mut l, mut r) = (left + self.len(), right + self.len());while l < r { if l % 2 == 1 { self.apply_update_to(l, &update);l += 1;} if r % 2 == 1 { r -= 1;self.apply_update_to(r, &update);} l /= 2;r /= 2;} self.update_parents_of(left + self.len());self.update_parents_of(right + self.len() - 1);} #[track_caller] pub fn view(&mut self, range: impl RangeBounds, f: impl FnOnce(&[S::Node])) { let Range { start: left, end: right, } = self.verify_range_bounds(range);let range = left + self.len()..right + self.len();if self.needs_update_propagation { self.push_updates_to_range(range.clone());} f(&self.data[range.start - 1..range.end - 1]);} #[track_caller] pub fn view_mut(&mut self, range: impl RangeBounds, f: impl FnOnce(&mut [S::Node])) { let Range { start: left, end: right, } = self.verify_range_bounds(range);let range = left + self.len()..right + self.len();if self.needs_update_propagation { self.push_updates_to_range(range.clone());} f(&mut self.data[range.start - 1..range.end - 1]);self.update_parents_of_range(range);} } impl Debug for SegmentTree where S: Spec, S::Node: Debug, S::Update: Debug, { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct(\"SegmentTree\") .field(\"data\", &self.data) .field(\"updates\", &self.updates) .field(\"needs_update_propagation\", &self.needs_update_propagation) .finish() } } impl Clone for SegmentTree where S: Spec, S::Node: Clone, S::Update: Clone, { fn clone(&self) -> Self { SegmentTree { data: self.data.clone(), updates: self.updates.clone(), needs_update_propagation: self.needs_update_propagation, } } } pub mod ops { use super::{EagerSpec, Format, Spec};use std::{marker::PhantomData, ops::Add};pub struct AsNode(PhantomData);impl Format for AsNode where T: Clone, { type Node = T;type Input = T;type Output = T;fn input(a: Self::Input, _i: usize) -> Self::Node { a } fn output(a: &Self::Node) -> Self::Output { a.clone() } } pub struct Sum(PhantomData);impl EagerSpec for Sum where T: Clone + Add, { type Node = T;type Formatter = AsNode;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { a.clone() + b.clone() } } pub struct Min(PhantomData);impl Spec for Min where T: Clone + Ord, { type Node = T;type Update = T;type Formatter = AsNode;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { Ord::min(a, b).clone() } fn compose(f: &Self::Update, g: &Self::Update) -> Self::Update { Ord::min(f, g).clone() } fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node { Ord::min(f, a).clone() } } pub struct Max(PhantomData);impl Spec for Max where T: Clone + Ord, { type Node = T;type Update = T;type Formatter = AsNode;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { Ord::max(a, b).clone() } fn compose(f: &Self::Update, g: &Self::Update) -> Self::Update { Ord::max(f, g).clone() } fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node { Ord::max(f, a).clone() } } pub struct ValueIndex(PhantomData);impl Format for ValueIndex { type Node = (T, usize);type Input = T;type Output = usize;fn input(a: Self::Input, i: usize) -> Self::Node { (a, i) } fn output(a: &Self::Node) -> Self::Output { a.1 } } pub struct Argmin(PhantomData);impl Spec for Argmin where T: Clone + Ord, { type Node = (T, usize);type Update = T;type Formatter = ValueIndex;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { if a.0 <= b.0 { a.clone() } else { b.clone() } } fn compose(f: &Self::Update, g: &Self::Update) -> Self::Update { Ord::min(f, g).clone() } fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node { (Ord::min(&a.0, f).clone(), a.1) } } pub struct Argmax(PhantomData);impl Spec for Argmax where T: Clone + Ord, { type Node = (T, usize);type Update = T;type Formatter = ValueIndex;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { if a.0 >= b.0 { a.clone() } else { b.clone() } } fn compose(f: &Self::Update, g: &Self::Update) -> Self::Update { Ord::max(f, g).clone() } fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node { (Ord::max(&a.0, f).clone(), a.1) } } pub struct MinAdd(PhantomData);impl Spec for MinAdd where T: Clone + Ord + Add, { type Node = T;type Update = T;type Formatter = AsNode;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { Ord::min(a, b).clone() } fn compose(f: &Self::Update, g: &Self::Update) -> Self::Update { f.clone() + g.clone() } fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node { f.clone() + a.clone() } } pub struct MaxAdd(PhantomData);impl Spec for MaxAdd where T: Clone + Ord + Add, { type Node = T;type Update = T;type Formatter = AsNode;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { Ord::max(a, b).clone() } fn compose(f: &Self::Update, g: &Self::Update) -> Self::Update { f.clone() + g.clone() } fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node { f.clone() + a.clone() } } pub struct SumSet(());impl Spec for SumSet { type Node = (i64, usize);type Update = i64;type Formatter = SumSet;fn op(a: &Self::Node, b: &Self::Node) -> Self::Node { (a.0 + b.0, a.1 + b.1) } fn compose(_f: &Self::Update, g: &Self::Update) -> Self::Update { *g } fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node { (a.1 as i64 * *f, a.1) } } impl Format for SumSet { type Node = (i64, usize);type Input = i64;type Output = i64;fn input(a: Self::Input, _i: usize) -> Self::Node { (a, 1) } fn output(a: &Self::Node) -> Self::Output { a.0 } } } }\n\nuse std::sync::atomic::{AtomicI64, Ordering};\n\nuse graph::{DfsState, Graph};\nuse number_theory::{egcd, gcd, mod_exp, mod_mulinv};\nuse prefix_sum::{PrefixOp, PrefixSums};\nuse scanner::Scanner;\nuse segment_tree::{SegmentTree, Spec};\nuse util::{Argmax, Choose, IntoVec, Sorted};\nuse writer::Writer;\n\nstatic mut MOD: i64 = 0;\n\nfn main() {\n let mut sc = Scanner::stdin();\n let mut wr = Writer::stdout();\n\n let (n, m) = scan!(sc, usize, i64);\n unsafe {\n MOD = m;\n }\n //let mut tree = SegmentTree::::new(vec![0; n + 1]);\n //tree.set(n, 1);\n // suffix[i] = sum of ways to get to i and later fields\n let mut suffix = vec![0; n + 1];\n suffix[n] = 1;\n\n for x in (1..=n).rev() {\n //let mut cnt = tree.query(x..);\n let mut cnt = suffix[x];\n //p!(x, cnt);\n\n for z in 2.. {\n if x * z > n {\n break;\n }\n //let inc = tree.query(x * z..((x + 1) * z).min(n + 1));\n let inc = suffix[x * z] - suffix.get((x + 1) * z).copied().unwrap_or(0);\n p!(x, z, inc);\n cnt = (cnt + inc) % m;\n }\n\n //tree.set(x, cnt);\n p!(x, cnt);\n suffix[x] = (suffix.get(x + 1).copied().unwrap_or(0) + cnt) % m;\n suffix[x - 1] = suffix[x];\n p!(x, suffix[x]);\n }\n\n //wr.write(tree.get(1)).unwrap();\n wr.write((suffix[1] - suffix[2] + m) % m).unwrap();\n}\n\nstruct MySpec;\nimpl Spec for MySpec {\n type Node = i64;\n type Update = ();\n type Formatter = segment_tree::ops::AsNode;\n fn op(a: &Self::Node, b: &Self::Node) -> Self::Node {\n unsafe { (*a + *b) % MOD }\n }\n fn compose(a: &Self::Update, b: &Self::Update) -> Self::Update {\n unreachable!()\n }\n fn apply(f: &Self::Update, a: &Self::Node) -> Self::Node {\n unreachable!()\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "data structures", "number theory"], "code_uid": "3886faeb12e91a7eaf0d910f28c711de", "src_uid": "a524aa54e83fd0223489a19531bf0e79", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\r\n#![allow(unused_imports)]\r\n#![allow(non_upper_case_globals)]\r\n#![allow(non_snake_case)]\r\n#![allow(unused_mut)]\r\n#![allow(unused_variables)]\r\n#![allow(dead_code)]\r\n\r\ntype Vec2 = Vec>;\r\ntype Vec3 = Vec>>;\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! invec {\r\n ( $ t : ty ) => {{\r\n let mut s = String::new();\r\n match std::io::stdin().read_line(&mut s) {\r\n Ok(0) => Vec::<$t>::new(),\r\n Ok(n) => s\r\n .trim()\r\n .split_whitespace()\r\n .map(|s| s.parse::<$t>().unwrap())\r\n .collect::>(),\r\n Err(_) => Vec::<$t>::new(),\r\n }\r\n }};\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! get {\r\n ($t:ty) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.trim().parse::<$t>().unwrap()\r\n }\r\n };\r\n ($($t:ty),*) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n let mut iter = line.split_whitespace();\r\n (\r\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\r\n )\r\n }\r\n };\r\n ($t:ty; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($t)\r\n ).collect::>()\r\n };\r\n ($($t:ty),*; $n:expr) => {\r\n (0..$n).map(|_|\r\n get!($($t),*)\r\n ).collect::>()\r\n };\r\n ($t:ty ;;) => {\r\n {\r\n let mut line: String = String::new();\r\n std::io::stdin().read_line(&mut line).unwrap();\r\n line.split_whitespace()\r\n .map(|t| t.parse::<$t>().unwrap())\r\n .collect::>()\r\n }\r\n };\r\n ($t:ty ;; $n:expr) => {\r\n (0..$n).map(|_| get!($t ;;)).collect::>()\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let mut s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\r\n let mut $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n\r\n ($next:expr, [$t:tt]) => {\r\n {\r\n let len = read_value!($next, usize);\r\n (0..len).map(|_| read_value!($next, $t)).collect::>()\r\n }\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n\r\n#[allow(unused_macros)]\r\n#[cfg(debug_assertions)]\r\nmacro_rules! mydbg {\r\n //($arg:expr) => (dbg!($arg))\r\n //($arg:expr) => (println!(\"{:?}\",$arg));\r\n ($($a:expr),*) => {\r\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\r\n }\r\n}\r\n#[cfg(not(debug_assertions))]\r\nmacro_rules! mydbg {\r\n ($($arg:expr),*) => {};\r\n}\r\n\r\nmacro_rules! echo {\r\n ($($a:expr),*) => {\r\n $(println!(\"{}\",$a))*\r\n }\r\n}\r\n\r\nuse std::cmp::*;\r\nuse std::collections::*;\r\nuse std::ops::{Add, Div, Mul, Rem, Sub};\r\n\r\ntrait SafeRangeContain {\r\n fn safe_contains(&self, x: i64) -> bool;\r\n}\r\n\r\nimpl SafeRangeContain for std::ops::Range {\r\n fn safe_contains(&self, x: i64) -> bool {\r\n if x < 0 {\r\n return false;\r\n }\r\n return self.contains(&(x as usize));\r\n }\r\n}\r\n\r\n#[allow(dead_code)]\r\nstatic INF_I64: i64 = i64::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_I32: i32 = i32::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic INF_USIZE: usize = usize::max_value() / 2;\r\n#[allow(dead_code)]\r\nstatic M_O_D: usize = 1000000007;\r\n#[allow(dead_code)]\r\nstatic PAI: f64 = 3.1415926535897932;\r\n\r\ntrait IteratorExt: Iterator {\r\n fn toVec(self) -> Vec;\r\n}\r\n\r\nimpl IteratorExt for T {\r\n fn toVec(self) -> Vec {\r\n self.collect()\r\n }\r\n}\r\n\r\ntrait CharExt {\r\n fn toNum(&self) -> usize;\r\n fn toAlphabetIndex(&self) -> usize;\r\n fn toNumIndex(&self) -> usize;\r\n}\r\nimpl CharExt for char {\r\n fn toNum(&self) -> usize {\r\n return *self as usize;\r\n }\r\n fn toAlphabetIndex(&self) -> usize {\r\n return self.toNum() - 'a' as usize;\r\n }\r\n fn toNumIndex(&self) -> usize {\r\n return self.toNum() - '0' as usize;\r\n }\r\n}\r\n\r\ntrait VectorExt {\r\n fn joinToString(&self, s: &str) -> String;\r\n}\r\nimpl VectorExt for Vec {\r\n fn joinToString(&self, s: &str) -> String {\r\n return self\r\n .iter()\r\n .map(|x| x.to_string())\r\n .collect::>()\r\n .join(s);\r\n }\r\n}\r\n\r\ntrait StringExt {\r\n fn get_reverse(&self) -> String;\r\n}\r\nimpl StringExt for String {\r\n fn get_reverse(&self) -> String {\r\n self.chars().rev().collect::()\r\n }\r\n}\r\n\r\ntrait UsizeExt {\r\n fn pow(&self, n: usize) -> usize;\r\n}\r\nimpl UsizeExt for usize {\r\n fn pow(&self, n: usize) -> usize {\r\n return ((*self as u64).pow(n as u32)) as usize;\r\n }\r\n}\r\n\r\nfn main() {\r\n solve();\r\n}\r\n\r\nfn solve() {\r\n let mut ans: u64 = 0;\r\n let (N, M) = get!(usize, u64);\r\n \r\n let mut dp = vec![0; N + 5];\r\n dp[N] = 1;\r\n let mut sum = 0;\r\n for i in (1..=N).rev() {\r\n dp[i] += sum;\r\n dp[i] %= M;\r\n\r\n for j in 1..i {\r\n if j * j > i {\r\n break;\r\n }\r\n\r\n let b = i / (j + 1);\r\n let c = i / j;\r\n let d = (dp[i] * (c - b) as u64) % M;\r\n dp[j] += d;\r\n dp[j] %= M;\r\n\r\n if j != i / j {\r\n let a = i / j;\r\n if a == i {\r\n continue;\r\n }\r\n let b = i / (a + 1);\r\n let c = i / a;\r\n let d = (dp[i] * (c - b) as u64) % M;\r\n dp[a] += d;\r\n dp[a] %= M;\r\n }\r\n }\r\n\r\n sum += dp[i];\r\n sum %= M;\r\n }\r\n let ans = dp[1] % M;\r\n\r\n echo!(ans);\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "data structures", "number theory"], "code_uid": "d74f9986ebcd9f8a06580e07189cdfa7", "src_uid": "a524aa54e83fd0223489a19531bf0e79", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{ self, BufRead };\nuse std::collections::*;\n\nmacro_rules! scan_line {\n () => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n buffer\n });\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\nfn main() {\n let (ax, ay, bx, by, cx, cy) = scan_line!(i64 i64 i64 i64 i64 i64);\n\n let d1 = (ax - bx)*(ax - bx) + (ay - by)*(ay - by);\n let d2 = (bx - cx)*(bx - cx) + (by - cy)*(by - cy);\n let area = ax*(by - cy) + bx*(cy - ay) + cx*(ay - by);\n\n if d1 == d2 && area != 0 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "8837723ffe70334e6c15e3253dbb8203", "src_uid": "05ec6ec3e9ffcc0e856dc0d461e6eeab", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::iter::FromIterator;\n\n#[allow(dead_code)]\nstruct Source {\n chars: Box>,\n}\n\n#[allow(dead_code)]\nimpl Source {\n fn next_chr(&mut self) -> char {\n self.chars\n .by_ref()\n .skip_while(|c| char::is_whitespace(*c))\n .next()\n .expect(\"eof\")\n }\n\n fn next_str(&mut self) -> String {\n let it = self\n .chars\n .by_ref()\n .skip_while(|c| char::is_whitespace(*c))\n .take_while(|c| !char::is_whitespace(*c));\n let s = String::from_iter(it);\n if s.is_empty() {\n panic!(\"eof\")\n } else {\n s\n }\n }\n\n fn from_stdin() -> Self {\n let mut data = String::new();\n io::stdin().read_to_string(&mut data).expect(\"Input error\");\n Self::from_str(&data)\n }\n\n fn from_str(s: &str) -> Self {\n let data = String::from(s);\n let chars = data.chars().collect::>().into_iter();\n Source {\n chars: Box::new(chars),\n }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n ($src:expr; $($elem:tt)*) => {\n input_inner!($src, $($elem)*)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($src:expr) => {};\n ($src:expr,) => {};\n ($src:expr, $var:ident : mut $ty:tt $($rest:tt)*) => {\n let mut $var = parse!($src, $ty);\n input_inner!($src $($rest)*)\n };\n ($src:expr, $var:ident : $ty:tt $($rest:tt)*) => {\n let $var = parse!($src, $ty);\n input_inner!($src $($rest)*)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse {\n ($src:expr, ( $($ty:tt),* )) => {\n ( $(parse!($src,$ty)),* )\n };\n ($src:expr, char) => {\n $src.next_chr()\n };\n ($src:expr, [ $ty:tt; $len:expr ]) => {\n (0..$len).map(|_| parse!($src,$ty)).collect::>()\n };\n ($src:expr, $ty:tt) => {\n parse_str!($src,$ty)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_str {\n ($src:expr, chars) => {\n $src.next_str().chars().collect::>()\n };\n ($src:expr, $ty:ty) => {\n $src.next_str().parse::<$ty>().expect(\"Parse error\")\n };\n}\n\nuse std::cmp::min;\n\nfn max_height(pos: usize, height: usize, restriction: &[(usize, usize, usize)]) -> usize {\n restriction.iter().fold(height, |cur, (l, r, h)| {\n if *l <= pos && pos <= *r {\n min(cur, *h)\n } else {\n cur\n }\n })\n}\n\nfn main() {\n let mut src = Source::from_stdin();\n input! { src;\n n: usize, h: usize, m: usize,\n r: [(usize,usize,usize); m]\n }\n\n let res: usize = (1..=n)\n .map(|pos| {\n let h = max_height(pos, h, &r);\n h * h\n })\n .sum();\n\n println!(\"{}\", res)\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "398748af4921a8734e09aeb4f1b39026", "src_uid": "f22b6dab443f63fb8d2d288b702f20ad", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! parse_line {\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n io::stdin().read_line(&mut a_str).unwrap();\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n })\n}\n\nfn main() {\n let (mut r, mut g, mut b) = parse_line!(u64, u64, u64);\n if r > g {\n std::mem::swap(&mut r, &mut g)\n }\n if g > b {\n std::mem::swap(&mut g, &mut b)\n }\n let s = r + g + b;\n let v = r + g;\n println!(\"{:?}\", if s / 3 < v { s / 3 } else { v });\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "546f98af98d771778e13d555da170533", "src_uid": "bae7cbcde19114451b8712d6361d2b01", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use self::algebra::*;\nuse self::matrix::Matrix;\nuse self::mod_int::ModInt;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::f64::consts::PI;\nuse std::io::*;\nuse std::str::*;\nuse std::string::*;\n\nmacro_rules! read {\n (($($t:tt),*)) => {\n ( $(read!($t)),* )\n };\n ([[$t:tt; $len1:expr]; $len2:expr]) => {\n (0..$len2).map(|_| read!([$t; $len1])).collect::>()\n };\n\n ([$t:tt; $len:expr]) => {\n (0..$len).map(|_| read!($t)).collect::>()\n };\n\n (chars) => {\n read!(String).chars().collect::>()\n };\n\n (usize1) => {\n read!(usize) - 1\n };\n\n ($t:ty) => {{\n let stdin = stdin();\n let stdin = stdin.lock();\n let token: String = stdin\n .bytes()\n .map(|c| c.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n\n token.parse::<$t>().unwrap()\n }};\n}\n\nmacro_rules! input {\n (mut $name:ident: $t:tt, $($r:tt)*) => {\n let mut $name = read!($t);\n input!($($r)*);\n };\n\n (mut $name:ident: $t:tt) => {\n let mut $name = read!($t);\n };\n\n ($name:ident: $t:tt, $($r:tt)*) => {\n let $name = read!($t);\n input!($($r)*);\n };\n\n ($name:ident: $t:tt) => {\n let $name = read!($t);\n };\n}\n\nmacro_rules! min {\n ($a:expr $(,)*) => {{\n $a\n }};\n ($a:expr, $b:expr $(,)*) => {{\n std::cmp::min($a, $b)\n }};\n ($a:expr, $($rest:expr),+ $(,)*) => {{\n std::cmp::min($a, min!($($rest),+))\n }};\n}\n\nmacro_rules! chmin {\n ($base:expr, $($cmps:expr),+ $(,)*) => {{\n let cmp_min = min!($($cmps),+);\n if $base > cmp_min {\n $base = cmp_min;\n true\n } else {\n false\n }\n }};\n}\n\nmacro_rules! max {\n ($a:expr $(,)*) => {{\n $a\n }};\n ($a:expr, $b:expr $(,)*) => {{\n std::cmp::max($a, $b)\n }};\n ($a:expr, $($rest:expr),+ $(,)*) => {{\n std::cmp::max($a, max!($($rest),+))\n }};\n}\n\nmacro_rules! chmax {\n ($base:expr, $($cmps:expr),+ $(,)*) => {{\n let cmp_max = max!($($cmps),+);\n if $base < cmp_max {\n $base = cmp_max;\n true\n } else {\n false\n }\n }};\n}\n\n#[derive(Eq, PartialEq, Clone, Debug)]\npub struct Rev(pub T);\n\nimpl PartialOrd for Rev {\n fn partial_cmp(&self, other: &Rev) -> Option {\n other.0.partial_cmp(&self.0)\n }\n}\n\nimpl Ord for Rev {\n fn cmp(&self, other: &Rev) -> std::cmp::Ordering {\n other.0.cmp(&self.0)\n }\n}\n\nstruct IO(R, std::io::BufWriter);\n\nimpl IO {\n pub fn new(r: R, w: W) -> Self {\n IO(r, std::io::BufWriter::new(w))\n }\n\n pub fn write(&mut self, s: S) {\n use std::io::Write;\n self.1.write(s.to_string().as_bytes()).unwrap();\n }\n\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let s: String = self\n .0\n .by_ref()\n .bytes()\n .map(|b| b.unwrap() as char)\n .skip_while(|c| c.is_whitespace())\n .take_while(|c| !c.is_whitespace())\n .collect();\n\n return s.parse::().ok().unwrap();\n }\n\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n\nfn prime_factorization(n: i64) -> HashMap {\n let mut n = n;\n let mut res = HashMap::new();\n let mut i = 2;\n while i * i <= n {\n while n % i == 0 {\n n /= i;\n let count = res.entry(i).or_insert(0);\n *count += 1;\n }\n i += 1;\n }\n\n if n > 1 {\n res.insert(n, 1);\n }\n\n return res;\n}\n\nstruct Combination {\n MOD: i64,\n fac: Vec,\n fac_inv: Vec,\n}\n\nimpl Combination {\n pub fn new(n: i64) -> Self {\n let MOD: i64 = 1_000_000_007;\n let mut fac: Vec = vec![0; n as usize + 1];\n let mut fac_inv: Vec = vec![0; n as usize + 1];\n\n let get_inverse = |mut n: i64| -> i64 {\n let (mut res, mut p) = (1, MOD - 2);\n\n while p != 0 {\n if p & 1 == 1 {\n res = (res * n) % MOD;\n }\n n = (n * n) % MOD;\n p >>= 1;\n }\n\n return res;\n };\n\n fac[0] = 1;\n\n for i in 1..n + 1 {\n fac[i as usize] = (fac[i as usize - 1] * i) % MOD;\n }\n\n for i in 0..n + 1 {\n fac_inv[i as usize] = get_inverse(fac[i as usize]);\n }\n\n Combination {\n MOD: MOD,\n fac: fac,\n fac_inv: fac_inv,\n }\n }\n\n fn nCr(&self, n: i64, r: i64) -> i64 {\n if n < r {\n return 0;\n }\n\n let a: i64 = self.fac[n as usize];\n let b: i64 = self.fac_inv[(n - r) as usize];\n let c: i64 = self.fac_inv[r as usize];\n let bc: i64 = (b * c) % self.MOD;\n\n return (a * bc) % self.MOD;\n }\n\n fn nPr(&self, n: i64, r: i64) -> i64 {\n if n < r {\n return 0;\n }\n\n let a: i64 = self.fac[n as usize];\n let b: i64 = self.fac_inv[(n - r) as usize];\n\n return (a * b) % self.MOD;\n }\n\n fn nHr(&self, n: i64, r: i64) -> i64 {\n if n == 0 && r == 0 {\n return 1;\n }\n\n return self.nCr(n + r - 1, r);\n }\n}\n\n#[derive(Copy, Clone, Eq, PartialEq)]\nstruct Edge {\n to: usize,\n cost: i64,\n}\n\nfn dijkstra(graph: &Vec>, s: &usize) -> Vec {\n use std::collections::BinaryHeap;\n let mut dist = vec![1e18 as i64; graph.len()];\n let mut heap = BinaryHeap::new();\n dist[*s] = 0;\n heap.push(Rev((0, *s)));\n while let Some(Rev((cost, v))) = heap.pop() {\n if dist[v] < cost {\n continue;\n }\n\n for e in &graph[v] {\n if dist[e.to] <= dist[v] + e.cost {\n continue;\n }\n dist[e.to] = dist[v] + e.cost;\n heap.push(Rev((dist[e.to], e.to)));\n }\n }\n return dist;\n}\n\nstruct LCA {\n par: Vec>>,\n dist: Vec,\n}\n\nimpl LCA {\n pub fn new(graph: &Vec>, root: usize) -> LCA {\n let V = graph.len();\n let mut K = 1;\n\n while (1 << K) < V {\n K += 1;\n }\n\n let mut par = vec![vec![None; V]; K];\n let mut dist = vec![-1; V];\n let graph = graph.to_vec();\n\n fn dfs(\n v: usize,\n p: Option,\n d: i64,\n graph: &Vec>,\n par: &mut Vec>>,\n dist: &mut Vec,\n ) {\n par[0][v] = p;\n dist[v] = d;\n for &to in &graph[v] {\n match p {\n Some(p) => {\n if to != p {\n dfs(to, Some(v), d + 1, graph, par, dist)\n }\n }\n None => dfs(to, Some(v), d + 1, graph, par, dist),\n }\n }\n }\n\n dfs(root, None, 0, &graph, &mut par, &mut dist);\n\n for k in 0..K - 1 {\n for v in 0..V {\n match par[k][v] {\n Some(x) => par[k + 1][v] = par[k][x],\n None => (),\n }\n }\n }\n\n LCA {\n par: par,\n dist: dist,\n }\n }\n\n pub fn query(&self, u: usize, v: usize) -> usize {\n let mut u = u;\n let mut v = v;\n if self.dist[u] < self.dist[v] {\n return self.query(v, u);\n }\n\n let K = self.par.len();\n for k in 0..K {\n if ((self.dist[u] - self.dist[v]) >> k & 1) == 1 {\n u = self.par[k][u].unwrap();\n }\n }\n\n if u == v {\n return u;\n }\n\n for k in (0..K - 1).rev() {\n if self.par[k][u] != self.par[k][v] {\n u = self.par[k][u].unwrap();\n v = self.par[k][v].unwrap();\n }\n }\n\n return self.par[0][u].unwrap();\n }\n}\n\nstruct Doubling {\n N: usize,\n LOG: usize,\n next: Vec>>,\n}\n\nimpl Doubling {\n pub fn new(vec: &Vec, lim: &usize) -> Doubling {\n let N = vec.len();\n let lim = *lim;\n let mut LOG = 1;\n while (1 << LOG) < 2 * lim {\n LOG += 1;\n }\n\n let mut next = vec![vec![None; N]; LOG];\n\n for i in 0..N {\n next[0][i] = Some(vec[i]);\n }\n\n for k in 0..LOG - 1 {\n for i in 0..N {\n match next[k][i] {\n Some(x) => next[k + 1][i] = next[k][x],\n None => (),\n }\n }\n }\n\n Doubling {\n N: N,\n LOG: LOG,\n next: next,\n }\n }\n\n pub fn query(&self, i: usize, n: usize) -> usize {\n let mut i = i;\n for k in (0..self.LOG).rev() {\n if (n >> k) & 1 == 1 {\n i = self.next[k][i].unwrap();\n }\n }\n return i;\n }\n}\n\nstruct UnionFind {\n par: Vec,\n}\n\nimpl UnionFind {\n pub fn new(n: usize) -> UnionFind {\n UnionFind { par: vec![-1; n] }\n }\n\n pub fn root(&mut self, x: usize) -> usize {\n if self.par[x] < 0 {\n return x;\n } else {\n let a = self.par[x] as usize;\n self.par[x] = self.root(a) as i32;\n return self.par[x] as usize;\n }\n }\n\n pub fn same(&mut self, x: usize, y: usize) -> bool {\n self.root(x) == self.root(y)\n }\n\n pub fn merge(&mut self, x: usize, y: usize) -> bool {\n let mut x = self.root(x);\n let mut y = self.root(y);\n if x == y {\n return false;\n } else {\n if self.par[x] > self.par[y] {\n std::mem::swap(&mut x, &mut y);\n }\n self.par[x] += self.par[y];\n self.par[y] = x as i32;\n return true;\n }\n }\n\n pub fn size(&mut self, x: usize) -> i64 {\n let a = self.root(x);\n return -self.par[a] as i64;\n }\n}\n\npub mod algebra {\n pub trait Monoid {\n fn id() -> Self;\n fn op(&self, rhs: &Self) -> Self;\n }\n\n #[derive(Clone, Debug)]\n pub struct Min(i64);\n\n #[derive(Clone, Debug)]\n pub struct RangeUpdate(i64);\n\n #[derive(Clone, Debug)]\n pub struct RangeAdd(i64);\n\n #[derive(Clone, Debug)]\n pub struct Sum(i64);\n\n impl Monoid for Sum {\n fn id() -> Self {\n Sum(0)\n }\n\n fn op(&self, rhs: &Self) -> Self {\n Sum(self.0 + rhs.0)\n }\n }\n\n impl Monoid for Min {\n fn id() -> Self {\n Min(std::i32::MAX as i64)\n }\n\n fn op(&self, rhs: &Self) -> Self {\n Min(std::cmp::min(self.0, (*rhs).0))\n }\n }\n\n pub trait Operator {\n type T;\n fn id() -> Self;\n fn op(&self, rhs: &Self) -> Self;\n fn act(&self, tar: &Self::T, x: usize) -> Self::T;\n }\n\n impl Operator for RangeUpdate {\n type T = Min;\n fn id() -> Self {\n RangeUpdate(0)\n }\n\n fn op(&self, rhs: &Self) -> Self {\n (*rhs).clone()\n }\n\n fn act(&self, tar: &Self::T, x: usize) -> Self::T {\n Min(self.0)\n }\n }\n\n impl Operator for RangeAdd {\n type T = Sum;\n fn id() -> Self {\n RangeAdd(0)\n }\n\n fn op(&self, rhs: &Self) -> Self {\n RangeAdd(self.0 + rhs.0)\n }\n\n // Sum(tar.0 + self.0 * x as i64)\n fn act(&self, tar: &Self::T, x: usize) -> Self::T {\n Sum(tar.0 + self.0 * x as i64)\n }\n }\n\n pub trait Zero {\n fn zero() -> Self;\n }\n\n impl Zero for usize {\n fn zero() -> Self {\n 0usize\n }\n }\n\n pub trait One {\n fn one() -> Self;\n }\n\n impl One for usize {\n fn one() -> Self {\n 1usize\n }\n }\n}\n\nstruct LazySegTree> {\n dat: Vec,\n lzy: Vec,\n need_update: Vec,\n size: usize,\n}\n\nimpl + Clone> LazySegTree {\n pub fn new(vec: Vec) -> LazySegTree {\n let n = vec.len();\n let mut sz = 1;\n while sz < n {\n sz <<= 1;\n }\n let mut dat = vec![M::id(); sz << 1];\n for i in 0..n {\n dat[i + sz] = vec[i].clone();\n }\n for k in (1..sz).rev() {\n dat[k] = dat[k << 1].op(&dat[(k << 1) + 1]);\n }\n\n return LazySegTree {\n dat: dat,\n lzy: vec![O::id(); sz << 1],\n need_update: vec![false; sz << 1],\n size: sz,\n };\n }\n\n pub fn eval(&mut self, l: usize, r: usize, k: usize) {\n if !self.need_update[k] {\n return;\n }\n self.dat[k] = self.lzy[k].act(&self.dat[k], r - l);\n if (k << 1) < self.dat.len() {\n self.lzy[k << 1] = self.lzy[k << 1].op(&self.lzy[k]);\n self.lzy[(k << 1) + 1] = self.lzy[(k << 1) + 1].op(&self.lzy[k]);\n self.need_update[k << 1] = true;\n self.need_update[(k << 1) + 1] = true;\n }\n self.lzy[k] = O::id();\n self.need_update[k] = false;\n }\n\n pub fn update(&mut self, a: usize, b: usize, x: O) {\n let sz = self.size;\n self._update(a, b, &x, 0, sz, 1);\n }\n\n pub fn _update(&mut self, a: usize, b: usize, x: &O, l: usize, r: usize, k: usize) {\n self.eval(l, r, k);\n if b <= l || r <= a {\n return;\n } else if a <= l && r <= b {\n self.lzy[k] = self.lzy[k].op(x);\n self.need_update[k] = true;\n self.eval(l, r, k);\n } else {\n let mid = (l + r) >> 1;\n self._update(a, b, x, l, mid, k << 1);\n self._update(a, b, x, mid, r, (k << 1) + 1);\n self.dat[k] = self.dat[k << 1].op(&self.dat[(k << 1) + 1]);\n }\n }\n\n pub fn query(&mut self, a: usize, b: usize) -> M {\n let sz = self.size;\n return self._query(a, b, 0, sz, 1);\n }\n\n pub fn _query(&mut self, a: usize, b: usize, l: usize, r: usize, k: usize) -> M {\n self.eval(l, r, k);\n if b <= l || r <= a {\n return M::id();\n } else if a <= l && r <= b {\n return self.dat[k].clone();\n } else {\n let mid = (l + r) >> 1;\n let vl = self._query(a, b, l, mid, k << 1);\n let vr = self._query(a, b, mid, r, (k << 1) + 1);\n return vl.op(&vr);\n }\n }\n}\n\nstruct SegTree {\n dat: Vec,\n size: usize,\n}\n\nimpl SegTree {\n pub fn new(n: usize) -> SegTree {\n let mut sz = 1;\n while sz < n {\n sz <<= 1;\n }\n\n SegTree:: {\n dat: vec![M::id(); sz * 2],\n size: sz,\n }\n }\n\n pub fn update(&mut self, k: usize, val: M) {\n let mut k = k + self.size;\n self.dat[k] = val;\n while k > 0 {\n k = k >> 1;\n self.dat[k] = self.dat[k << 1].op(&self.dat[(k << 1) + 1]);\n }\n }\n\n pub fn query(&self, a: usize, b: usize) -> M {\n let mut lx = M::id();\n let mut rx = M::id();\n let mut l = a + self.size;\n let mut r = b + self.size;\n while l < r {\n if (l & 1) == 1 {\n lx = lx.op(&self.dat[l]);\n l += 1;\n }\n\n if (r & 1) == 1 {\n r -= 1;\n rx = self.dat[r].op(&rx);\n }\n\n l >>= 1;\n r >>= 1;\n }\n\n return lx.op(&rx);\n }\n}\n\nfn decode(v: Vec) -> Vec<(char, usize)> {\n let mut res = Vec::new();\n let mut now = v[0];\n let mut cnt = 1;\n\n for i in 1..v.len() {\n if v[i] == now {\n cnt += 1;\n } else {\n res.push((now, cnt));\n cnt = 1;\n now = v[i];\n }\n }\n res.push((now, cnt));\n\n return res;\n}\n\npub mod mod_int {\n use super::algebra::{One, Zero};\n use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};\n\n type Num = usize;\n\n const MOD: usize = 1e9 as usize + 7;\n\n #[derive(Clone, Copy)]\n pub struct ModInt(pub T);\n\n impl Add> for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> ModInt {\n self + rhs.0\n }\n }\n\n impl Add for ModInt {\n type Output = ModInt;\n fn add(self, mut rhs: Num) -> ModInt {\n if rhs >= MOD {\n rhs %= MOD;\n }\n let mut t = rhs + self.0;\n if t >= MOD {\n t = t - MOD;\n }\n ModInt(t)\n }\n }\n\n impl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: Num) -> ModInt {\n let rhs = if rhs >= MOD { rhs % MOD } else { rhs };\n let value = if self.0 < rhs { self.0 + MOD } else { self.0 };\n ModInt(value - rhs)\n }\n }\n\n impl Sub> for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> ModInt {\n self - rhs.0\n }\n }\n\n impl AddAssign for ModInt {\n fn add_assign(&mut self, other: Num) {\n *self = *self + other;\n }\n }\n\n impl AddAssign> for ModInt {\n fn add_assign(&mut self, other: ModInt) {\n *self = *self + other;\n }\n }\n\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, other: Num) {\n *self = *self - other;\n }\n }\n\n impl SubAssign> for ModInt {\n fn sub_assign(&mut self, other: ModInt) {\n *self = *self - other;\n }\n }\n\n impl Div for ModInt {\n type Output = ModInt;\n fn div(self, mut rhs: Num) -> ModInt {\n if rhs >= MOD {\n rhs %= MOD;\n }\n self * ModInt(rhs).pow(MOD - 2)\n }\n }\n\n impl Div> for ModInt {\n type Output = ModInt;\n fn div(self, rhs: ModInt) -> ModInt {\n self / rhs.0\n }\n }\n\n impl DivAssign for ModInt {\n fn div_assign(&mut self, rhs: Num) {\n *self = *self / rhs\n }\n }\n\n impl DivAssign> for ModInt {\n fn div_assign(&mut self, rhs: ModInt) {\n *self = *self / rhs\n }\n }\n\n impl Mul> for ModInt {\n type Output = ModInt;\n\n fn mul(self, rhs: ModInt) -> ModInt {\n self * rhs.0\n }\n }\n\n impl Mul for ModInt {\n type Output = ModInt;\n\n fn mul(self, mut rhs: Num) -> ModInt {\n if rhs >= MOD {\n rhs %= MOD;\n }\n let t = (self.0 * rhs) % MOD;\n ModInt(t)\n }\n }\n\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: Num) {\n *self = *self * rhs;\n }\n }\n\n impl MulAssign> for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n }\n\n impl ModInt {\n pub fn pow(self, e: Num) -> ModInt {\n let mut result = ModInt(1);\n let mut cur = self;\n let mut e = e;\n while e > 0 {\n if e & 1 == 1 {\n result *= cur;\n }\n e >>= 1;\n cur *= cur;\n }\n result\n }\n }\n\n impl Zero for ModInt {\n fn zero() -> Self {\n ModInt(0)\n }\n }\n\n impl One for ModInt {\n fn one() -> Self {\n ModInt(1)\n }\n }\n}\n\nstruct Eratosthenes {\n n: usize,\n prime: Vec,\n}\n\nimpl Eratosthenes {\n pub fn new(n: usize) -> Eratosthenes {\n let mut prime = vec![true; n + 1];\n prime[0] = false;\n prime[1] = false;\n let mut i = 2;\n while i * i <= n {\n if prime[i] {\n let mut p = i * 2;\n while p <= n {\n prime[p] = false;\n p += i;\n }\n }\n i += 1;\n }\n\n Eratosthenes { n: n, prime: prime }\n }\n}\n\npub mod matrix {\n use super::algebra::{One, Zero};\n use std::ops::{Add, Mul};\n\n #[derive(Clone)]\n pub struct Matrix(pub Vec>);\n\n impl + Mul + Clone + Copy + One + Zero> Matrix {\n pub fn mul(&mut self, rhs: &Matrix) -> Matrix {\n let n = self.0.len();\n let m = rhs.0[0].len();\n let p = self.0[0].len();\n let mut res = vec![vec![T::zero(); m]; n];\n for i in 0..n {\n for j in 0..m {\n for k in 0..p {\n res[i][j] = res[i][j] + self.0[i][k] * rhs.0[k][j]\n }\n }\n }\n\n return Matrix(res);\n }\n\n // pub fn update(&mut self) -> Vec> {\n // let m = self.mat.len();\n // let mut res = vec![vec![T::zero(); m]; m];\n // for i in 0..m {\n // for j in 0..m {\n // for k in 0..m {\n // res[i][j] = res[i][j] + self.mat[i][k] * self.mat[k][j];\n // }\n // }\n // }\n // return res;\n // }\n\n pub fn pow(&mut self, k: usize) -> Matrix {\n let n = self.0.len();\n let mut k = k;\n let mut res = Matrix(vec![vec![T::zero(); n]; n]);\n let mut b = (*self).clone();\n for i in 0..n {\n res.0[i][i] = T::one();\n }\n\n while k > 0 {\n if k & 1 == 1 {\n res = b.mul(&res);\n }\n b = b.mul(&b.clone());\n k >>= 1;\n }\n\n return res;\n }\n }\n}\n\n#[derive(Clone, Copy)]\nstruct Alpha(i64);\n\nimpl Monoid for Alpha {\n fn id() -> Self {\n Alpha(0i64)\n }\n\n fn op(&self, rhs: &Self) -> Self {\n Alpha(self.0 | rhs.0)\n }\n}\n\npub trait BinarySearch {\n fn lower_bound(&self, x: T) -> usize;\n fn upper_bound(&self, x: T) -> usize;\n}\n\nimpl BinarySearch for [T] {\n fn lower_bound(&self, x: T) -> usize {\n let mut ok = self.len() as i32;\n let mut ng = -1i32;\n while ok - ng > 1 {\n let mid = ((ok + ng) / 2);\n match self[mid as usize].cmp(&x) {\n Ordering::Greater | Ordering::Equal => {\n ok = mid;\n }\n Ordering::Less => {\n ng = mid;\n }\n }\n }\n return ok as usize;\n }\n\n fn upper_bound(&self, x: T) -> usize {\n let mut ok = self.len() as i32;\n let mut ng = -1i32;\n while ok - ng > 1 {\n let mid = ((ok + ng) / 2);\n match self[mid as usize].cmp(&x) {\n Ordering::Greater => {\n ok = mid;\n }\n Ordering::Equal | Ordering::Less => {\n ng = mid;\n }\n }\n }\n return ok as usize;\n }\n}\n\nfn solve() {\n input! {\n n: usize,\n k: usize,\n d: usize\n }\n\n let mut dp = vec![vec![ModInt(0); 2]; 110];\n dp[0][0] += 1;\n\n for i in 1..=n {\n for j in 1..=k {\n if i < j {\n continue;\n }\n if j < d {\n dp[i][0] = dp[i][0] + dp[i - j][0];\n dp[i][1] = dp[i][1] + dp[i - j][1];\n } else {\n dp[i][1] = dp[i][1] + dp[i - j][0];\n dp[i][1] = dp[i][1] + dp[i - j][1];\n }\n }\n }\n println!(\"{}\", dp[n][1].0);\n}\n\nfn main() {\n // input! {\n // t: usize\n // }\n\n let mut t = 1;\n for _ in 0..t {\n solve();\n }\n}", "lang_cluster": "Rust", "tags": ["dp", "implementation", "trees"], "code_uid": "5f993026b0d9f5e990f7d870747661e7", "src_uid": "894a58c9bba5eba11b843c5c5ca0025d", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() -> io::Result<()> {\n let m: i64 = 1000000007;\n let mut input = String::new();\n io::stdin().read_to_string(&mut input)?;\n let mut ws = input.split_whitespace();\n let n: usize = ws.next().unwrap().parse().unwrap();\n let k: usize = ws.next().unwrap().parse().unwrap();\n let d: usize = ws.next().unwrap().parse().unwrap();\n let mut v0 = vec![1];\n for i in 1..n + 1 {\n let mut s: i64 = 0;\n for j in 1..k + 1 {\n if i >= j {\n s += v0[i - j];\n }\n }\n v0.push(s % m);\n }\n let mut v1 = vec![0];\n for i in 1..n + 1 {\n let mut s: i64 = 0;\n for j in 1..d {\n if i >= j {\n s += v1[i - j];\n }\n }\n for j in d..k + 1 {\n if i >= j {\n s += v0[i - j];\n }\n }\n v1.push(s % m);\n }\n println!(\"{}\", v1[n]);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["dp", "implementation", "trees"], "code_uid": "6c4111133c14bcc5ce3abe95d60ce2ca", "src_uid": "894a58c9bba5eba11b843c5c5ca0025d", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let k: usize = scan.next();\n let d: usize = scan.next();\n let mut dp = [[0usize; 2]; 128];\n dp[0][0] = 1;\n for i in 1..=n {\n for j in 1..=k {\n if i < j {\n continue;\n }\n if j < d {\n dp[i][0] = (dp[i][0] + dp[i - j][0]) % 1000000007;\n dp[i][1] = (dp[i][1] + dp[i - j][1]) % 1000000007;\n } else {\n dp[i][1] = (dp[i][1] + dp[i - j][0]) % 1000000007;\n dp[i][1] = (dp[i][1] + dp[i - j][1]) % 1000000007;\n }\n }\n }\n println!(\"{}\", dp[n][1]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["dp", "implementation", "trees"], "code_uid": "da205713108f7c953afa95359512940a", "src_uid": "894a58c9bba5eba11b843c5c5ca0025d", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let evolutions = [\"vaporeon\", \"jolteon\", \"flareon\", \"espeon\", \"umbreon\", \"leafeon\", \"glaceon\", \"sylveon\"];\n \n let mut entry = String::new();\n stdin().read_line(&mut entry).unwrap();\n let len:usize = entry.trim().parse().unwrap();\n entry.clear();\n stdin().read_line(&mut entry).unwrap();\n let name = entry.trim();\n let mut coord:Vec<(char, usize)> = vec!();\n for (i, c) in name.chars().enumerate(){\n if c != '.' {\n coord.push((c, i));\n }\n }\n for ev in evolutions.iter() {\n if len == ev.len(){\n let mut is_it = true;\n let chars :Vec = ev.chars().collect();\n for i in &coord{\n if i.0 != chars[i.1] {\n is_it = false;\n break;\n }\n }\n if is_it {\n println!(\"{}\", ev);\n break;\n }\n }\n }\n}\n\n\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "5a6453ad118f9492cf51bdf4ce4856db", "src_uid": "ec3d15ff198d1e4ab9fd04dd3b12e6c0", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\n\n// I have no idea what I'm doing\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n\nfn is_match(pat: &str, text: &str) -> bool {\n pat.len() == text.len() &&\n pat.chars().zip(text.chars())\n .all(|(p, t)| p == '.' || t == p)\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let pool: Vec<_> = \"vaporeon jolteon flareon espeon umbreon leafeon glaceon and sylveon\"\n .split_ascii_whitespace()\n .collect();\n\n let _n: usize = scan.token();\n let s: String = scan.token();\n\n writeln!(out, \"{}\", pool.into_iter().filter(|t| is_match(&s, t)).next().unwrap())?;\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "5d120b2f2bf2dca118cfa921e398bbb9", "src_uid": "ec3d15ff198d1e4ab9fd04dd3b12e6c0", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nuse std::collections::HashMap;\n\nfn main() {\n let k = {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n it.next();\n it.next().unwrap()\n };\n\n let mut hm: HashMap = HashMap::new();\n\n let mut s = String::new();\n stdin().read_line(&mut s).unwrap();\n let s = s.trim();\n for c in s.as_bytes() {\n let cnt = hm.entry(*c).or_insert(0);\n *cnt += 1;\n }\n\n let l = hm.values().max().unwrap();\n if k < *l {\n println!(\"NO\");\n } else {\n println!(\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "05982df2b6d7613509c8b0d4768a99df", "src_uid": "ceb3807aaffef60bcdbcc9a17a1391be", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io;\nuse std::collections::HashMap;\n\nfn main() {\n if let Err(e) = run() {\n println!(\"{}\", e);\n }\n}\n\nfn run() -> Result<(), Box> {\n let mut s = String::new();\n io::stdin().read_line(&mut s)?;\n let s: Vec<&str> = s.trim().split(\" \").collect();\n let _: i32 = s[0].parse()?;\n let k: i32 = s[1].parse()?;\n let mut s = String::new();\n io::stdin().read_line(&mut s)?;\n let mut m = HashMap::new();\n for b in s.trim().as_bytes() {\n match m.get(b).cloned() {\n Some(x) => m.insert(b, x + 1),\n _ => m.insert(b, 1)\n };\n }\n for (_, x) in &m {\n if *x > k {\n println!(\"NO\");\n return Ok(())\n }\n }\n println!(\"YES\");\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "2c110c6ce0b975a18810da68e484cb9c", "src_uid": "ceb3807aaffef60bcdbcc9a17a1391be", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1118/problem/D2\n//\n#![allow(unused_imports)]\nuse std::io::*;\nuse std::io::Write;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($iter:expr, [ next / $t:tt ]) => {\n {\n let len = read_value!($iter, usize);\n (0..len).map(|_| read_value!($iter, $t)).collect::>()\n }\n };\n\n ($iter:expr, switch) => {\n {\n let ty = read_value!($iter, i32);\n if ty == 1 {\n vec![ty, read_value!($iter, i32), read_value!($iter, i32)]\n } else if ty == 2 {\n vec![ty, read_value!($iter, i32)]\n } else {\n vec![ty, read_value!($iter, i32)]\n }\n }\n };\n\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! dvec {\n ($t:expr ; $len:expr) => {\n vec![$t; $len]\n };\n\n ($t:expr ; $len:expr, $($rest:expr),*) => {\n vec![dvec!($t; $($rest),*); $len]\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! ifv {\n ($t:expr, $a:expr, $b: expr) => {\n if $t { $a } else { $b }\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! fill {\n ($t:expr, $v:expr) => {\n for i in 0..$t.len() {\n $t[i] = $v;\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! join {\n ($t:expr, $glue:expr) => {\n $t.into_iter().map(|w| w.to_string()).collect::>().join($glue)\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\nfn isok(days: usize, a: &Vec) -> i64 {\n let n = a.len();\n let mut total = 0;\n let mut cup = 0;\n let mut fr = 0;\n while fr < n {\n for i in 0..days {\n if fr == n {\n break;\n }\n total += max(0, a[fr]-cup);\n fr += 1;\n }\n cup += 1;\n }\n total\n}\n\nfn main() {\n input! {\n n: usize, m: i64,\n mut a: [i64; n]\n };\n a.sort();\n a.reverse();\n\n let mut sum = 0;\n for i in 0..n {\n sum += a[i];\n }\n if sum < m {\n println!(\"-1\");\n return;\n }\n\n let mut ng = 0;\n let mut ok = n;\n while ok - ng > 1 {\n let med = (ok + ng) / 2;\n if isok(med, &a) >= m {\n ok = med;\n } else {\n ng = med;\n }\n }\n println!(\"{}\", ok);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "de79da95ea7c03f3c41eba218ac14644", "src_uid": "acb8a57c8cfdb849a55fa65aff86628d", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n m: i64,\n a: [i64; n],\n }\n if a.iter().fold(0, |s, a| s + *a) < m {\n println!(\"-1\");\n return;\n }\n let mut a = a;\n a.sort();\n a.reverse();\n let mut ok = n;\n let mut ng = 0;\n while ok - ng > 1 {\n let mid = (ok + ng) / 2;\n let mut sum = 0;\n let mut sub = 0;\n for a in a.chunks(mid) {\n for a in a.iter() {\n sum += std::cmp::max(0, *a - sub);\n }\n sub += 1;\n }\n if sum >= m {\n ok = mid;\n } else {\n ng = mid;\n }\n }\n println!(\"{}\", ok);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "a77c2b89012eabc0d6c47d122eb92d11", "src_uid": "acb8a57c8cfdb849a55fa65aff86628d", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::cmp::*;\n\nfn main() {\n let (n, k) = {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n (it.next().unwrap(), it.next().unwrap())\n };\n\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let it = input.split_whitespace().map(|k| k.parse::().unwrap());\n\n let mut ac = 0;\n let mut bc = 0;\n\n for (i, a) in it.enumerate() {\n ac += a;\n bc += min(ac, 8);\n ac -= min(ac, 8);\n if k <= bc {\n println!(\"{}\", i + 1);\n std::process::exit(0);\n }\n }\n\n println!(\"-1\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3e5d8068323c2b6eb7cf31c38d38f49b", "src_uid": "24695b6a2aa573e90f0fe661b0c0bd3a", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n }\n let ans = if n == m {\n 0\n } else if m <= 1 {\n 1\n } else if m <= n / 2 {\n m\n } else {\n n - m\n };\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "25a0d6d3846dafd2a31c658214c0b018", "src_uid": "c05d0a9cabe04d8fb48c76d2ce033648", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> Vec {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n return buf.trim().split(\" \").map(|x| { x.parse::().unwrap() }).collect();\n}\n\nfn main() {\n let line = read_line();\n let (n, x) = (line[0], line[1]);\n let arr = read_line();\n let count_lt = arr.iter().filter(|e| { **e < x }).count() as i64;\n let has_eq = arr.iter().filter(|e| { **e == x }).count() == 1;\n let result = (x - count_lt) + (if has_eq { 1 } else { 0 });\n println!(\"{}\", result);\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "3d70a3e31fb4bacb866ab0f090ebe88a", "src_uid": "21f579ba807face432a7664091581cd8", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec(s: String) -> Vec\n where T: FromStr,\n ::Err: std::fmt::Debug,\n{\n s.split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nfn main() {\n let (n, x): (usize, usize) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let v: Vec = get_line().split_whitespace().map(|k| k.parse().unwrap())\n .filter(|&k: &usize| k <= x).collect();\n\n let ans = v.into_iter().fold(x, |acc, i| {\n if i == x {\n acc + 1\n } else {\n acc - 1\n }\n });\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "79cd8ba92d303d1e17aa43a3928a2bdf", "src_uid": "21f579ba807face432a7664091581cd8", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::FromStr;\nuse std::fmt;\nuse std::io;\n\nconst MODULO: u64 = 1000000007;\n\nfn main() {\n let n: u64 = read();\n let mut k = 0;\n\n for i in 2..(n+1) {\n if i%2 == 0 {\n k = (3 * (k + 1)) % MODULO;\n } else {\n k = (3 * (k - 1)) % MODULO;\n }\n }\n\n println!(\"{}\", k);\n}\n\nfn read_line() -> String {\n let mut pre_n = String::new();\n io::stdin().read_line(&mut pre_n).unwrap();\n pre_n\n}\n\nfn read() -> T\n where ::Err: fmt::Debug\n{\n read_line().trim().parse().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "dp"], "code_uid": "6811e5f63b22e63bca4c1565645fa302", "src_uid": "77627cc366a22e38da412c3231ac91a8", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n}\n\nfn mult(m1: &[[u64; 4]; 4], m2: &[[u64; 4]; 4]) -> [[u64; 4]; 4] {\n let mut result = [[0u64; 4]; 4];\n for i in 0..4 {\n for j in 0..4 {\n let mut sum = 0u64;\n for k in 0..4 {\n sum = (sum + m1[i][k] * m2[k][j]) % 1000000007;\n }\n result[i][j] = sum;\n }\n }\n result\n}\n\nfn exp(m: &[[u64; 4]; 4], mut e: u64) -> [[u64; 4]; 4] {\n let mut m2 = m.clone();\n let mut result = [[0u64; 4]; 4];\n result[0][0] = 1;\n result[1][1] = 1;\n result[2][2] = 1;\n result[3][3] = 1;\n while e > 0 {\n if e & 1 == 1 {\n result = mult(&result, &m2);\n }\n e >>= 1;\n m2 = mult(&m2, &m2);\n }\n result\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: u64 = scan.next();\n let mat: [[u64; 4]; 4] = [[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0]];\n let result = exp(&mat, n);\n println!(\"{}\", result[0][0]);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "dp"], "code_uid": "820b8e00027068bde3bd6f058e8278d7", "src_uid": "77627cc366a22e38da412c3231ac91a8", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn input(read_file: bool) -> String {\n if read_file {\n let mut file = std::fs::File::open(\"sample.txt\").unwrap();\n let mut buf = String::new();\n file.read_to_string(&mut buf).unwrap();\n buf\n } else {\n let mut buf = String::new();\n std::io::stdin().read_to_string(&mut buf).unwrap();\n buf.trim_end().to_owned()\n }\n}\n\nfn solve(ws: &mut std::str::SplitWhitespace) {\n let n: usize = ws.next().unwrap().parse().unwrap();\n const MOD: i64 = 1_000_000_007;\n\n let mut nd = 1;\n let mut na = 0;\n\n for i in 0..n {\n let d = na * 3 % MOD;\n let a = (nd + na * 2) % MOD;\n nd = d;\n na = a;\n }\n\n println!(\"{}\", nd);\n}\n\nfn main() {\n const READ_FROM_FILE: bool = false;\n\n let s = input(READ_FROM_FILE);\n let mut ws = s.split_whitespace();\n\n // let t = ws.next().unwrap().parse().unwrap();\n // for _ in 0..t {}\n solve(&mut ws);\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "dp"], "code_uid": "d5d585394a3de42225af5a1c1ff9e3fd", "src_uid": "77627cc366a22e38da412c3231ac91a8", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let (a, b) = parse_line!(u64, u64);\n let mut pos = 0;\n let mut count = 0;\n while pos != a * b {\n let closest_a = (pos / a + 1) * a;\n let closest_b = (pos / b + 1) * b;\n if closest_a < closest_b {\n count += closest_a - pos;\n pos = closest_a;\n }else if closest_b < closest_a {\n pos = closest_b;\n }else if closest_a == closest_b {\n if a > b {\n count += closest_a - pos;\n }\n pos = closest_a;\n }\n }\n if count * 2 == a * b {\n println!(\"Equal\");\n }else if count * 2 > a * b {\n println!(\"Dasha\");\n }else{\n println!(\"Masha\");\n }\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "99e1dbb59d6fe59427cac33be314e00e", "src_uid": "06eb66df61ff5d61d678bbb3bb6553cc", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nconst N: i64 = 998_244_353;\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let s = get_line().trim().to_string();\n\n let names = vec![\n \"Danil\",\n \"Olya\",\n \"Slava\",\n \"Ann\",\n \"Nikita\",\n ];\n\n let count = names.into_iter()\n .map(|name| s.split(name).count() - 1)\n .sum::();\n\n if count == 1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "9774d7e66e9b223c296ec2e202bf1ff4", "src_uid": "db2dc7500ff4d84dcc1a37aebd2b3710", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! m {\n\t($c:tt,$x:expr,$y:expr) => {{\n\t\tlet b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}\n\t}};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! vec_dim {\n\t([$d:expr]$($s:tt)+) => {vec![vec_dim!($($s)+);$d]}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\n// Field (mod prime) {{{\nmod field {\n\tuse std::ops::*;\n\tconst P5: i32 = 1_000_000_007;\n\tconst P6: i64 = P5 as i64;\n\t#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(i32);\n\t#[allow(dead_code)] impl Field {\n\t\tpub fn new>(a: T) -> Self { Self(Self::cv(a)) }\n\t\tpub unsafe fn new_unchecked(a: i32) -> Self { Self(a) }\n\t\tfn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n\t\tfn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n\t\tfn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n\t\tpub fn inv(self) -> Self { self.pow(P5-2) }\n\t\tpub fn pow>(self, b: T) -> Self {\n\t\t\tlet b = b.into(); if b == 0 { Self(1) } else {\n\t\t\t\tlet mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res\n\t\t\t}\n\t\t}\n\t}\n\timpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\n\timpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\n\timpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\n\timpl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}\n\timpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\n\timpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\n\timpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\n\timpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\n\timpl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }\n\tuse std::fmt::{Display, Formatter, Result};\n\timpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n}\nuse field::Field as Z;\n//}}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\tlet z0 = Z::new(0);\n\n\tl!(r,g = rin.u());\n\tlet mut dp = vec![z0; r+1];\n\tdp[r] = Z::new(1);\n\tlet mut sum = dp[r];\n\tlet mut sol = sum;\n\tlet mut rg = 0;\n\tfor n in 1.. {\n\t\tif sum == z0 {\n\t\t\tbreak;\n\t\t}\n\t\tsol = sum;\n\t\tlet mut dp1 = vec![z0; r+1];\n\t\tsum = z0;\n\t\tfor i in 0..=r {\n\t\t\tif r + g < rg + i { break; }\n\t\t\tlet j = r + g - rg - i;\n\t\t\tif j > g { continue; }\n\t\t\tif dp[i] == z0 { continue; }\n\t\t\tsum += dp[i];\n\t\t\tif j >= n {\n\t\t\t\tdp1[i] += dp[i];\n\t\t\t}\n\t\t\tif i >= n {\n\t\t\t\tdp1[i - n] += dp[i];\n\t\t\t}\n\t\t}\n\t\trg += n;\n\t\tdp = dp1;\n\t}\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "833afdec2c85a397967405ada62d09a4", "src_uid": "34b6286350e3531c1fbda6b0c184addc", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\nuse std::collections::HashMap;\n\nfn get_num() -> usize{\n let mut input = String::new();\n\n io::stdin().read_line(&mut input)\n .expect(\"\");\n\n usize::from_str(input.trim()).unwrap()\n}\n\nfn main() {\n let n = get_num();\n\n let mut m = HashMap::new();\n m.insert(0, (0, 0));\n m.insert(1, (0, 1));\n m.insert(2, (0, 2));\n m.insert(3, (0, 2));\n m.insert(4, (0, 2));\n m.insert(5, (0, 2));\n m.insert(6, (1, 2));\n m.insert(7, (2, 2));\n\n if n < 8 {\n let r = m.get(&n).unwrap();\n println!(\"{} {}\", r.0, r.1);\n } else {\n let r = m.get(&(n%7)).unwrap();\n println!(\"{} {}\", (n/7) * 2 + r.0, (n/7) * 2 + r.1);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "brute force"], "code_uid": "339239a64533e747df4808e066464ec4", "src_uid": "8152daefb04dfa3e1a53f0a501544c35", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::iter::*;\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty; $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt; $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.i();\n let a = n / 7 * 2;\n let b = n % 7;\n println!(\"{} {}\", a + (b-5).max(0).min(2), a + b.min(2));\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "brute force"], "code_uid": "d0a67cff908503197a5f995375e4c689", "src_uid": "8152daefb04dfa3e1a53f0a501544c35", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min, Ordering};\n#[allow(unused_imports)]\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n#[allow(unused_imports)]\nuse std::iter::FromIterator;\n#[allow(unused_imports)]\nuse std::io::stdin;\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! debug {\n ($($a:expr),*) => {\n println!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n\n// https://github.com/bluss/permutohedron\npub trait LexicalPermutation {\n /// Return `true` if the slice was permuted, `false` if it is already\n /// at the last ordered permutation.\n fn next_permutation(&mut self) -> bool;\n /// Return `true` if the slice was permuted, `false` if it is already\n /// at the first ordered permutation.\n fn prev_permutation(&mut self) -> bool;\n}\n\nimpl LexicalPermutation for [T]\nwhere\n T: Ord,\n{\n /// Original author in Rust: Thomas Backman \n fn next_permutation(&mut self) -> bool {\n // These cases only have 1 permutation each, so we can't do anything.\n if self.len() < 2 {\n return false;\n }\n\n // Step 1: Identify the longest, rightmost weakly decreasing part of the vector\n let mut i = self.len() - 1;\n while i > 0 && self[i - 1] >= self[i] {\n i -= 1;\n }\n\n // If that is the entire vector, this is the last-ordered permutation.\n if i == 0 {\n return false;\n }\n\n // Step 2: Find the rightmost element larger than the pivot (i-1)\n let mut j = self.len() - 1;\n while j >= i && self[j] <= self[i - 1] {\n j -= 1;\n }\n\n // Step 3: Swap that element with the pivot\n self.swap(j, i - 1);\n\n // Step 4: Reverse the (previously) weakly decreasing part\n self[i..].reverse();\n\n true\n }\n\n fn prev_permutation(&mut self) -> bool {\n // These cases only have 1 permutation each, so we can't do anything.\n if self.len() < 2 {\n return false;\n }\n\n // Step 1: Identify the longest, rightmost weakly increasing part of the vector\n let mut i = self.len() - 1;\n while i > 0 && self[i - 1] <= self[i] {\n i -= 1;\n }\n\n // If that is the entire vector, this is the first-ordered permutation.\n if i == 0 {\n return false;\n }\n\n // Step 2: Reverse the weakly increasing part\n self[i..].reverse();\n\n // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)\n let mut j = self.len() - 1;\n while j >= i && self[j - 1] < self[i - 1] {\n j -= 1;\n }\n\n // Step 4: Swap that element with the pivot\n self.swap(i - 1, j);\n\n true\n }\n}\n\nfn main() {\n let mut v = get!(usize;;);\n\n v.sort();\n\n if v[0] == 1 {\n println!(\"YES\");\n return;\n }\n\n while {\n let a = v[0];\n let b = v[1];\n let c = v[2];\n\n let t0 = 0;\n let t1 = 1;\n\n let mut t2 = 0;\n\n for t in 2..2000 {\n if !((t - t0) % a == 0 || (t - t1) % b == 0) {\n t2 = t;\n break;\n }\n }\n\n if (0..2000).all(|t| {\n (t >= t0 && (t - t0) % a == 0) || (t >= t1 && (t - t1) % b == 0)\n || (t >= t2 && (t - t2) % c == 0)\n }) {\n println!(\"YES\");\n return;\n }\n\n v.next_permutation()\n } {}\n\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms"], "code_uid": "554615e1c2e639f45779f0d85d1939d5", "src_uid": "df48af9f5e68cb6efc1214f7138accf9", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::*;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok();\n return ret;\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = std::string::String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\nfn parse(s: &str) -> T { s.parse::().ok().unwrap() }\n\n#[allow(dead_code)]\nfn get() -> T { parse(&get_word()) }\n\nfn main() {\n let k: i64 = get();\n let a: i64 = get();\n let b: i64 = get();\n let aq = a / k;\n let bq = b / k;\n let res: i64 = if (aq == 0 && b % k != 0) || (bq == 0 && a % k != 0) {\n -1\n } else {\n a / k + b / k\n };\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "a261ec573a6df86e34a966204cf4017e", "src_uid": "6e3b8193d1ca1a1d449dc7a4ad45b8f2", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{ self, BufRead };\nuse std::collections::*;\n\nmacro_rules! scan_line {\n () => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n buffer\n });\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\nfn main() {\n let (n, k, t) = scan_line!(i64 i64 i64);\n\n if t <= k {\n println!(\"{}\", t);\n } else if t <= n {\n println!(\"{}\", k);\n } else {\n let d = k - (t - n);\n println!(\"{}\", d);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "bfd13cb710dbe3162bf8074dae841708", "src_uid": "7e614526109a2052bfe7934381e7f6c2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let (n, k, t) = {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let ans = if t < k {\n (t - 1) % k + 1\n } else if t > n {\n n + k - t\n } else {\n k\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "19039d8a2346866289cc2e7e4a8685c8", "src_uid": "7e614526109a2052bfe7934381e7f6c2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() \n{\n let mut n =String::new();\n let mut opt = String::new();\n io::stdin().read_line(&mut n);\n io::stdin().read_line(&mut opt);\n\n let n:usize = n.trim().parse().expect(\"\");\n let mut ans = 0;\n for i in 0..n\n {\n if opt.chars().nth(i) == Some('-')\n {\n ans-=1;\n if ans<0\n {\n ans=0;\n }\n }\n else\n {\n ans+=1;\n }\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "4ffe0f0c84286be6f98e5e435401d7df", "src_uid": "a593016e4992f695be7c7cd3c920d1ed", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn board(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn framed_board(&mut self, r: usize, c: usize, f: u8) -> Vec> {\n\t\tlet mut res = v!([r+2]);\n\t\tres.push( v!([c+2] = f) );\n\t\trep!{[r]\n\t\t\tlet mut t = self.vb();\n\t\t\tassert!(t.len() == c);\n\t\t\tt.reserve(2);\n\t\t\tt.insert(0,f);\n\t\t\tt.push(f);\n\t\t\tres.push(t);\n\t\t}\n\t\tres.push( v!([c+2] = f) );\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n\tfn graph(&mut self, n: usize, m: usize) -> Vec> {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e\n\t}\n\tfn graph_w(&mut self, n: usize, m: usize) -> Vec> where T::Err: Debug {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tl!(n,m,i,j,a,b = rin.i());\n\tlet mut sol = None;\n\tfor &(x,y) in [(1,1), (1,m), (n,1), (n,m)].iter() {\n\t\tif (x - i) % a == 0 && (y - j) % b == 0 {\n\t\t\tlet xx = (x - i).abs() / a;\n\t\t\tlet yy = (y - j).abs() / b;\n\t\t\tlet mx = xx > 0 || a < n;\n\t\t\tlet my = yy > 0 || b < m;\n\t\t\tif (xx == 0 && yy == 0) || (mx && my && (xx ^ yy) & 1 == 0) {\n\t\t\t\tlet res = xx.max(yy).min(sol.unwrap_or(1000000000));\n\t\t\t\tsol.replace(res);\n\t\t\t}\n\t\t}\n\t}\n\tif let Some(ans) = sol {\n\t\twriteln!(rout, \"{}\", ans).ok();\n\t} else {\n\t\twriteln!(rout, \"Poor Inna and pony!\").ok();\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "576bca145e5dc06e6e4affd6d5fb89fe", "src_uid": "51155e9bfa90e0ff29d049cedc3e1862", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! scanln {\n () => ({\n let mut buffer = String::new();\n ::std::io::stdin().read_line(&mut buffer).expect(\"Unable to read line\");\n buffer\n });\n ($($t: ty),+) => ({\n scanln!($($t),+, |c: char| c.is_whitespace())\n });\n ($($t: ty),+, $sp: expr) => ({\n let mut buffer = scanln!();\n let mut iter = buffer.split($sp);\n ($(iter.next().unwrap().parse::<$t>().expect(\"Unable to parse token\")),+)\n });\n}\n\nfn main() {\n const MOD: u64 = 1000000009;\n let mut dp = vec![[[[[0u64; 2]; 32]; 32]; 32]; 1001].into_boxed_slice();\n let (n, h) = scanln!(usize, usize);\n dp[0][0][0][0][0] = 1;\n\n for i in 1..=n {\n for a in 0..=(h + 1) {\n for b in a..=(h + 1) {\n for c in b..=(h + 1) {\n for y in 0..2 {\n dp[(i - 1) as usize][a][b][c][y] %= MOD;\n let val = dp[(i - 1) as usize][a][b][c][y];\n let ta = if a + 1 > h { h + 1 } else { a + 1 };\n let tb = if b + 1 > h { h + 1 } else { b + 1 };\n let tc = if c + 1 > h { h + 1 } else { c + 1 };\n dp[i][ta][tb][tc][y] += val;\n if y == 0 {\n dp[i][1][tb][tc][(ta > h) as usize] += val;\n dp[i][1][ta][tc][(tb > h) as usize] += val;\n dp[i][1][ta][tb][(tc > h) as usize] += val;\n } else {\n dp[i][tb][tc][h + 1][(ta > h) as usize] += val;\n dp[i][ta][tc][h + 1][(tb > h) as usize] += val;\n dp[i][ta][tb][h + 1][(tc > h) as usize] += val;\n }\n }\n }\n }\n }\n }\n\n let mut res = 0;\n\n for a in 0..=(h + 1) {\n for b in a..=(h + 1) {\n for c in b..=(h + 1) {\n for y in 0..2 {\n if (a < h) || (b < h) || (c < h) || (y == 0) {\n res += dp[n][a][b][c][y];\n }\n }\n }\n }\n }\n\n println!(\"{}\", res % MOD);\n}", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "69086fa32bba81e52337e404959512c8", "src_uid": "9fe9658db35076c0bddc8b7ddce11013", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::io::{ BufWriter, stdin, stdout, Write, Stdout };\n \n#[derive(Default)]\nstruct Scanner {\n buffer: Vec\n}\nimpl Scanner {\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nconst DIG: [&'static str; 10] = [\n \"O-|-OOOO\",\n \"O-|O-OOO\",\n \"O-|OO-OO\",\n \"O-|OOO-O\",\n \"O-|OOOO-\",\n \"-O|-OOOO\",\n \"-O|O-OOO\",\n \"-O|OO-OO\",\n \"-O|OOO-O\",\n \"-O|OOOO-\",\n];\n\nfn main() {\n let out = &mut BufWriter::new(stdout());\n let mut n: usize = (Scanner::default()).next();\n let mut nums = vec![];\n if n == 0 {\n writeln!(out, \"{}\", DIG[0]).ok();\n return;\n }\n while n != 0 {\n nums.push(n % 10);\n n = n/10;\n }\n nums.iter().for_each(|d| {\n writeln!(out, \"{}\", DIG[*d]).ok();\n });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "11a4a886b070a65def05e56bf0ff54d9", "src_uid": "c2e3aced0bc76b6484360563355d23a7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: v!([]), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = v!([8]);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn board(&mut self, r: usize, c: Option) -> Vec> {\n\t\tlet mut res = v!([r]);\n\t\tlet c = c.unwrap_or(0);\n\t\trep!{[r]\n\t\t\tlet t = self.vb();\n\t\t\tassert!(c == 0 || t.len() == c);\n\t\t\tres.push(t);\n\t\t}\n\t\tres\n\t}\n\tfn framed_board(&mut self, r: usize, c: usize, f: u8) -> Vec> {\n\t\tlet mut res = v!([r+2]);\n\t\tres.push( v!([c+2] = f) );\n\t\trep!{[r]\n\t\t\tlet mut t = self.vb();\n\t\t\tassert!(t.len() == c);\n\t\t\tt.reserve(2);\n\t\t\tt.insert(0,f);\n\t\t\tt.push(f);\n\t\t\tres.push(t);\n\t\t}\n\t\tres.push( v!([c+2] = f) );\n\t\tres\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n\tfn graph(&mut self, n: usize, m: usize) -> Vec> {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); e[a].push(b); e[b].push(a); } e\n\t}\n\tfn graph_w(&mut self, n: usize, m: usize) -> Vec> where T::Err: Debug {\n\t\tlet mut e = v!([n][]); rep!{[m] l!(a,b = self.u()-1); let c: T = self.p(); e[a].push((b,c)); e[b].push((a,c)); } e\n\t}\n}\n//------------------- End rusT }}}\n\n// Field (mod prime) {{{\nmod field {\n\tuse std::ops::*;\n\t#[allow(dead_code)] pub const Z0: Field = Field(0);\n\t#[allow(dead_code)] pub const Z1: Field = Field(1);\n\tconst P5: i32 = 1_000_000_007;\n\tconst P6: i64 = P5 as i64;\n\t#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(i32);\n\t#[allow(dead_code)] impl Field {\n\t\tpub fn new>(a: T) -> Self { Self(Self::cv(a)) }\n\t\tpub fn new_unchecked(a: i32) -> Self { Self(a) }\n\t\tfn hi(mut a: i32) -> i32 { if a >= P5 { a -= P5; } a }\n\t\tfn lo(mut a: i32) -> i32 { if a < 0 { a += P5; } a }\n\t\tfn cv>(a: T) -> i32 { Self::lo((a.into() % P6) as i32) }\n\t\tpub fn inv(self) -> Self { self.pow(P5-2) }\n\t\tpub fn pow>(self, b: T) -> Self {\n\t\t\tlet b = b.into(); if b == 0 { Self(1) } else {\n\t\t\t\tlet mut res = self.pow(b/2); res *= res; if b % 2 == 1 {res *= self;} res\n\t\t\t}\n\t\t}\n\t}\n\timpl Add for Field { type Output = Self; fn add(self, a: Self) -> Self::Output { Self(Self::hi(self.0 + a.0)) }}\n\timpl Sub for Field { type Output = Self; fn sub(self, a: Self) -> Self::Output { Self(Self::lo(self.0 - a.0)) }}\n\timpl Mul for Field { type Output = Self; fn mul(self, a: Self) -> Self::Output { Self(Self::cv(self.0 as i64 * a.0 as i64)) }}\n\timpl Div for Field { type Output = Self; fn div(self, a: Self) -> Self::Output { self * a.inv() }}\n\timpl Neg for Field { type Output = Self; fn neg(self) -> Self::Output { Self(Self::lo(-self.0)) }}\n\timpl AddAssign for Field { fn add_assign(&mut self, a: Self) { *self = *self + a; } }\n\timpl SubAssign for Field { fn sub_assign(&mut self, a: Self) { *self = *self - a; } }\n\timpl MulAssign for Field { fn mul_assign(&mut self, a: Self) { *self = *self * a; } }\n\timpl DivAssign for Field { fn div_assign(&mut self, a: Self) { *self = *self / a; } }\n\tuse std::fmt::{Display, Formatter, Result};\n\timpl Display for Field { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, \"{}\", self.0) } }\n}\n#[allow(unused_imports)] use field::{Field, Field as Z, Z0, Z1};\n//}}}\n// Square Matrix (Field) {{{\ntype MatT = Field;\nconst MAT_T_0: MatT = Z0;\nconst MAT_T_1: MatT = Z1;\n#[derive(Debug,Clone)] struct Mat { n: usize, a: Vec }\n#[allow(dead_code)] impl Mat {\n\tfn new(n:usize)->Self{Self{n,a:vec![MAT_T_0;n*n]}}\n\tfn diag(n:usize,v:MatT)->Self{let mut m=Self::new(n);let mut p=0;for _ in 0..n{m.a[p]=v;p+=n+1;}m}\n\tfn pow(&self,n:u64)->Self{if n==0{Self::diag(self.n,MAT_T_1)}else{let mut t=self.pow(n/2);t*=t.clone();if n%2==1{t*=self.clone();}t}}\n\tfn range(&self,r:Range,c:Range)->Vec>{if r.startMatT{self.a[r*self.n+c]}\n\tfn at_mut<'a>(&'a mut self,r:usize,c:usize)->&'a mut MatT{&mut self.a[r*self.n+c]}//'\n}\nimpl Mul for Mat{type Output=Self;fn mul(self,o:Self)->Self::Output{assert!(self.n==o.n);let n=self.n;let mut res=Self::new(n);\n\tfor ii in(0..n).map(|i|i*n){for j in 0..n{let mut t=MAT_T_0;let mut kk=j;for k in 0..n{t+=self.a[ii+k]*o.a[kk];kk+=n;}res.a[ii+j]=t;}}res}}\nimpl Add for Mat{type Output=Self;fn add(mut self,o:Self)->Self{self+=o;self}}\nimpl Sub for Mat{type Output=Self;fn sub(mut self,o:Self)->Self{self-=o;self}}\nimpl MulAssign for Mat{fn mul_assign(&mut self,a:Self){*self=self.clone()*a;}}\nimpl AddAssign for Mat{fn add_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x+=y;}} }\nimpl SubAssign for Mat{fn sub_assign(&mut self,o:Self){assert!(self.n==o.n);for(x,y)in self.a.iter_mut().zip(o.a.into_iter()){*x-=y;}} }\nimpl PartialEq for Mat{fn eq(&self,o:&Self)->bool{self.n==o.n&&self.a==o.a}}impl Eq for Mat{}\n// }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet n = rin.l();\n\tlet m = rin.u();\n\tlet mut mat = Mat::new(m);\n\tfor i in 1..m {\n\t\t*mat.at_mut(i,i-1) = Z1;\n\t}\n\t*mat.at_mut(0,0) = Z1;\n\t*mat.at_mut(0,m-1) = Z1;\n\tlet mat = mat.pow(n as u64);\n\tlet sol = mat.at(0,0);\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "dp"], "code_uid": "1f3fc2d4c604e57150c2593e95d99c39", "src_uid": "e7b9eec21d950f5d963ff50619c6f119", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::io::BufRead;\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n\n let input_string = lines.next().unwrap().expect(\"input reading failed\");\n let len = input_string.len();\n let iter = input_string.chars().take(len / 2 + 1);\n let mut reverse = input_string.chars().rev().take(len / 2 + 1);\n let mut palindrome = true;\n let mut same_char = true;\n\n // input string is non-empty\n let my_char = input_string.chars().nth(0).unwrap();\n\n for char_a in iter {\n if char_a != my_char {\n same_char = false;\n }\n\n let char_b = match reverse.next() {\n Some(c) => c,\n None => {\n break;\n }\n };\n\n if char_a != char_b {\n palindrome = false;\n break;\n }\n }\n\n let mut count = len;\n if palindrome {\n if same_char {\n count = 0;\n } else {\n count = len - 1;\n }\n }\n\n println!(\"{}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "3de6f3a3073e6631ad49aa4b5f78f226", "src_uid": "6c85175d334f811617e7030e0403f706", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\n\nstruct Scan {\n buffer: std::collections::VecDeque,\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan {\n buffer: std::collections::VecDeque::new(),\n }\n }\n\n fn next_line(&self) -> String {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n line\n }\n\n fn next(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let line = self.next_line();\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n fn next_n(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.next::()).collect()\n }\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let line = scan.next_line();\n let tline = line.trim();\n let result = 26 + 25 * tline.len();\n println!(\"{}\", result);\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "strings"], "code_uid": "7855705956875f7d652bae284902ecd8", "src_uid": "556684d96d78264ad07c0cdd3b784bc9", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::str::{FromStr};\n\nfn main() {\n let mut r = Read::new();\n let ln = r.many();\n print!(\"{}\", solve(ln[0], ln[1], ln[2]));\n}\n\nfn solve(t: i32, l: i32, r: i32) -> i64 {\n let b = 1000000007;\n let mut f = vec![0;(r + 1) as usize];\n for i in 1..r as i64 + 1 {\n for j in 2..r as i64 / i + 1 {\n f[(i * j) as usize] = (f[i as usize] + i * j * (j - 1) / 2) % b;\n }\n }\n\n f[l as usize..r as usize + 1].iter().fold((0, 1), |(s, p), fi| ((s + p * fi) % b, p * t as i64 % b)).0\n}\n\nstruct Read { s: String }\n\nimpl Read {\n fn new() -> Read {\n Read{s: String::new()}\n }\n\n #[allow(unused_must_use)]\n fn line(&mut self) -> &str {\n self.s.clear();\n std::io::stdin().read_line(&mut self.s);\n self.s.trim()\n }\n \n fn one(&mut self) -> T where ::Err: std::fmt::Debug {\n self.line().parse().unwrap()\n }\n\n fn many(&mut self) -> Vec where ::Err: std::fmt::Debug {\n self.line().split(' ').map(|x| x.parse().unwrap()).collect()\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "greedy", "number theory"], "code_uid": "5f39caaf8f1571453aaf019995f6b2f4", "src_uid": "c9d45dac4a22f8f452d98d05eca2e79b", "difficulty": 1800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io;\nuse std::str::FromStr;\n\nfn get_num() -> usize {\n let mut input = String::new();\n\n io::stdin().read_line(&mut input).expect(\"\");\n\n usize::from_str(input.trim()).unwrap()\n}\n\nfn main() {\n let mut m = HashMap::new();\n\n m.insert(0, \"zero\");\n m.insert(1, \"one\");\n m.insert(2, \"two\");\n m.insert(3, \"three\");\n m.insert(4, \"four\");\n m.insert(5, \"five\");\n m.insert(6, \"six\");\n m.insert(7, \"seven\");\n m.insert(8, \"eight\");\n m.insert(9, \"nine\");\n m.insert(10, \"ten\");\n m.insert(11, \"eleven\");\n m.insert(12, \"twelve\");\n m.insert(13, \"thirteen\");\n m.insert(14, \"fourteen\");\n m.insert(15, \"fifteen\");\n m.insert(16, \"sixteen\");\n m.insert(17, \"seventeen\");\n m.insert(18, \"eighteen\");\n m.insert(19, \"nineteen\");\n m.insert(20, \"twenty\");\n m.insert(30, \"thirty\");\n m.insert(40, \"forty\");\n m.insert(50, \"fifty\");\n m.insert(60, \"sixty\");\n m.insert(70, \"seventy\");\n m.insert(80, \"eighty\");\n m.insert(90, \"ninety\");\n\n let n = get_num();\n\n if n < 20 || m.contains_key(&n) {\n println!(\"{}\", m.get(&n).unwrap());\n } else {\n println!(\n \"{}-{}\",\n m.get(&(n / 10 * 10)).unwrap(),\n m.get(&(n % 10)).unwrap()\n );\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "37eb28f495eb4f89da20ff2aa68468cd", "src_uid": "a49ca177b2f1f9d5341462a38a25d8b7", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n\nfn read_line() -> String {\n let mut input_line = String::new();\n io::stdin().read_line(&mut input_line).unwrap();\n return String::from(input_line.trim());\n}\n\nfn read_line_vec() -> Vec {\n return read_line().split(' ')\n .map(|s| s.parse().unwrap())\n .collect();\n}\n\nfn resolve(n: u32) -> String {\n let s = match n {\n 0 => \"zero\",\n 10 => \"ten\",\n 1 => \"one\",\t\n 11 => \"eleven\",\t \t \n 2 => \"two\",\t\n 12 => \"twelve\",\n 20 => \"twenty\",\n 3 => \"three\",\n 13 => \"thirteen\",\n 30 => \"thirty\",\n 4 => \"four\",\n 14 => \"fourteen\",\n 40 => \"forty\",\n 5 => \"five\",\n 15 => \"fifteen\", \n 50 => \"fifty\",\n 6 => \"six\",\n 16 => \"sixteen\",\n 60 => \"sixty\",\n 7 => \"seven\",\n 17 => \"seventeen\",\t\n 70 => \"seventy\",\n 8 => \"eight\",\n 18 => \"eighteen\",\n 80 => \"eighty\",\n 9 => \"nine\",\n 19 => \"nineteen\",\n 90 => \"ninety\",\n _ => panic!(\"WHAAAAT\")\n };\n return String::from(s);\n}\n\nfn main() {\n let n: u32 = read_line().parse().unwrap();\n if n <= 20 || n % 10 == 0 {\n let s = resolve(n);\n println!(\"{}\", s);\n } else {\n let s2 = resolve(n % 10);\n \n let s1 = resolve(10 * (n / 10));\n println!(\"{}-{}\", s1, s2);\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "bd66b1649c3e76356adfe817bc98bab3", "src_uid": "a49ca177b2f1f9d5341462a38a25d8b7", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\n\nfn main() -> () {\n\n let mut buffer = String::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n handle.read_to_string(&mut buffer).expect(\"stdin\");\n\n let mut arr : Vec<_> = buffer.split_whitespace().map(|x| x.parse::().unwrap() ).collect();\n\n let n = arr[0];\n let m = arr[1];\n\n let max_seats = arr.iter().skip(2).max().unwrap();\n let s = arr.iter().skip(2).sum::();\n let b = (s + m)/n + if (s+m) % n != 0 { 1 } else { 0 };\n\n use std::cmp;\n \n println!(\"{} {}\", cmp::max( max_seats, &b ), max_seats + m );\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "binary search"], "code_uid": "e081fad54811597dbc76df656a058d8a", "src_uid": "78f696bd954c9f0f9bb502e515d85a8d", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n a: [usize; n],\n }\n let max = *a.iter().max().unwrap() + m;\n let mut a = a;\n for _ in 0..m {\n let mut min = (1000000, 0);\n for (i, a) in a.iter().enumerate() {\n min = std::cmp::min(min, (*a, i));\n }\n a[min.1] += 1;\n }\n let min = *a.iter().max().unwrap();\n println!(\"{} {}\", min, max);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "binary search"], "code_uid": "59991f6ef8aa1ec5601a1feecf50e2ec", "src_uid": "78f696bd954c9f0f9bb502e515d85a8d", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::max;\n\nfn main() {\n let stdin = io::stdin();\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n let a: Vec = s.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n s = String::new();\n stdin.read_line(&mut s).unwrap();\n let v: Vec = s.split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n let mut cmax = 0;\n for i in 1..v.len() {\n cmax = max(cmax, v[i-1] - v[i]);\n }\n\n println!(\"{}\", max(cmax - a[1], 0));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "f7eb80f80a8714eb0a2d49340182b738", "src_uid": "411539a86f2e94eb6386bb65c9eb9557", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n a: (u32, u32),\n b: (u32, u32),\n s: chars,\n }\n let mut f = 0;\n f += s[0].to_digit(10).unwrap() * 10 * 60;\n f += s[1].to_digit(10).unwrap() * 60;\n f += s[3].to_digit(10).unwrap() * 10;\n f += s[4].to_digit(10).unwrap();\n assert!((f - 300) % a.0 == 0);\n let start = f;\n let end = start + a.1;\n let mut p = 300;\n let mut ans = 0;\n while p < 24 * 60 {\n let (s, e) = (p, p + b.1);\n let (l, r) = (std::cmp::max(s, start), std::cmp::min(e, end));\n if l < r {\n ans += 1;\n }\n p += b.0;\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "921e2a4cf4d11743269960da61303b0b", "src_uid": "1c4cf1c3cb464a483511a8a61f8685a7", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main(){\n let mut s=String::new();\n io::stdin().read_line(&mut s).expect(\"Something is wrong\");\n let n=&s[0..s.find(' ').unwrap()];\n let mut n:i64=n.trim().parse().unwrap();\n let k=&s[s.find(' ').unwrap()+1..s.len()]; \n let mut k:i64=k.trim().parse().unwrap();\n let mut a:i64=n;\n let mut p:i64=0;\n while a%10==0{\n p+=1;\n a/=10;\n }\n if p>=k{println!(\"{}\",n)}\n else{k=k-p;\n match a%10{\n 1|3|7|9=>{for c in 0..k{n*=10}println!(\"{}\",n)},\n 5=>{while a%5==0{p+=1;a/=5;}if k>=p{for c in 0..p{n*=2}for c in 0..k-p{n*=10}}else{for c in 0..k{n*=2}}println!(\"{}\",n);},\n _=>{while a%2==0{p+=1;a/=2;}if k>=p{for c in 0..p{n*=5}for c in 0..k-p{n*=10}}else{for c in 0..k{n*=5}}println!(\"{}\",n);},\n }\n}\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "4877c3247d7e827d7819c38fd0dce3ed", "src_uid": "73566d4d9f20f7bbf71bc06bc9a4e9f3", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\n// Be careful for n = 10^6. In Codeforces, usize is a 32-bit integer.\nfn sieve(n: i64) -> (Vec, Vec) {\n let mut is_prime = vec![true; (n as usize) + 1];\n is_prime[0] = false;\n is_prime[1] = false;\n let mut primes = Vec::new();\n for i in 2..=n {\n if is_prime[i as usize] {\n primes.push(i);\n let mut j = i * i;\n while j <= n {\n is_prime[j as usize] = false;\n j += i;\n }\n }\n }\n (primes, is_prime)\n}\n\nfn lower_bound(arr: &[i64], target: i64) -> usize {\n let mut lo = 0;\n let mut hi = arr.len();\n while lo < hi {\n let mid = lo + (hi - lo) / 2;\n if arr[mid] >= target {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n lo\n}\n\nfn count_primes(primes: &[i64], lo: i64, hi: i64) -> i64 {\n // How many primes are there in [lo, hi]?\n let lb_1 = lower_bound(primes, lo) as i64;\n let lb_2 = lower_bound(primes, hi + 1) as i64;\n lb_2 - lb_1\n}\n\nfn pred(a: i64, b: i64, k: i64, l: i64, primes: &[i64], is_prime: &[bool]) -> bool {\n // For ALL x in [a, b - l + 1], are there at least k prime numbers in [x, x + l - 1]?\n\n // window: [a, a + l - 1]\n let mut prime_count = count_primes(primes, a, a + l - 1);\n if prime_count < k {\n return false;\n }\n for x in (a + 1)..=(b - l + 1) {\n // for i in 1..(b - l - a + 2) {\n // let x = a + i;\n // window: [x, x + l - 1]\n // previous window: [x - 1, x + l - 2]\n // if x - 1 was prime, remove it\n if is_prime[(x - 1) as usize] {\n prime_count -= 1;\n }\n\n // if x + l - 1 is prime, add it\n if is_prime[(x + l - 1) as usize] {\n prime_count += 1;\n }\n\n if prime_count < k {\n return false;\n }\n }\n true\n}\n\nfn search_l(a: i64, b: i64, k: i64, primes: &[i64], is_prime: &[bool]) -> i64 {\n let mut lo = 1;\n let mut hi = b - a + 2;\n while lo < hi {\n let mid = lo + (hi - lo) / 2;\n if pred(a, b, k, mid, primes, is_prime) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n if lo == b - a + 2 {\n -1\n } else {\n lo\n }\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let a: i64 = scan.token();\n let b: i64 = scan.token();\n let k: i64 = scan.token();\n\n let (primes, is_prime) = sieve(1000005);\n let ans = search_l(a, b, k, &primes, &is_prime);\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "binary search", "number theory"], "code_uid": "8f5af5115ae3ad7df7554abd7519beb6", "src_uid": "3e1751a2990134f2132d743afe02a10e", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\nfn count_bits(n: u64) -> u64 {\n let mut n = n;\n let mut ans = 0;\n while n > 0 {\n ans += 1;\n n >>= 1;\n }\n ans\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u64 = scan.token();\n let k: u64 = scan.token();\n // Maximize the xor-sum of at most k numbers from 1 to n\n // For any bit pattern that represents a positive number, its negation is always less than the number itself.\n // For example, n = 6 = 110 -> neg(n) = 001\n // n ^ neg(n) = 111\n // The answer is num_bits(n) ones, if k >= 2\n if k == 1 {\n writeln!(out, \"{}\", n).ok();\n return;\n }\n let num_bits = count_bits(n);\n let mut ans = 0u64;\n for i in 0..(num_bits) {\n ans = ans | (1 << i);\n }\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n pub fn tokens(&mut self) -> Vec {\n assert!(self.buffer.is_empty());\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n input\n .split_whitespace()\n .map(|x| x.parse().ok().expect(\"Failed parse\"))\n .collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "number theory", "bitmasks"], "code_uid": "47ac34dd4778ec8a9579ce4d4a9afd38", "src_uid": "16bc089f5ef6b68bebe8eda6ead2eab9", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get().parse::().unwrap());\n }\n \n let n = get!();\n let k = get!();\n \n if k == 1 {\n println!(\"{}\", n);\n } else {\n let mut t = n;\n let mut d = 0;\n while t > 0 {\n t >>= 1;\n d += 1;\n }\n let ans = (1i64 << d) - 1;\n println!(\"{}\", ans);\n }\n\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "number theory", "bitmasks"], "code_uid": "2c0fcfbb586d61ec5279346d0ac5c25e", "src_uid": "16bc089f5ef6b68bebe8eda6ead2eab9", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT {{{\nuse std::io::*; use std::str::{self,*}; use std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::{self,*};\n#[allow(unused_imports)] use std::iter::{self,*};\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_imports)] use std::cell::*;\n#[allow(unused_macros)] macro_rules! min {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b < *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! max {\n\t($x:expr,$y:expr) => {{ let b=$y; let a=&mut$x; if b > *a {*a=b; true} else {false} }};\n}\n#[allow(unused_macros)] macro_rules! l {\n\t($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};\n\t($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};\n\t(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};\n\t(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};\n}\n#[allow(unused_macros)] macro_rules! v {\n\t([$d:expr]$($s:tt)+) => {vec![v!($($s)+);$d]};\n\t([]) => {Vec::new()}; ([$e:expr]) => {Vec::with_capacity($e)}; (=$e:expr) => {$e};\n}\n#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }\n#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }\n#[allow(dead_code)] fn writer() -> BufWriter { BufWriter::new(stdout()) }\nstruct WordReaderC {buf: Vec, pos: usize, q: std::io::StdinLock<'static>}//'\n#[allow(dead_code)] impl WordReaderC {\n\tfn new() -> Self {\n\t\tlet r = unsafe {&*Box::into_raw(Box::new(stdin()))};\n\t\tSelf { q: r.lock(), buf: Vec::new(), pos: 0 }\n\t}\n\tfn next_line(&mut self) -> bool {\n\t\tself.buf.clear(); self.pos = 0;\n\t\tself.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0\n\t}\n\tfn is_ws(c: u8) -> bool {\n\t\tc == b' ' || c == b'\\r' || c == b'\\n' || c == b'\\t'\n\t}\n\tfn byte(&mut self) -> Option {\n\t\tif self.pos == self.buf.len() { if !self.next_line() { return None; } }\n\t\tself.pos += 1; Some(self.buf[self.pos - 1])\n\t}\n\tfn vb(&mut self) -> Vec {\n\t\tlet mut s = Vec::with_capacity(8);\n\t\tlet mut f = false;\n\t\tloop {\n\t\t\tif let Some(c) = self.byte() {\n\t\t\t\tif !Self::is_ws(c) {\n\t\t\t\t\ts.push(c);\n\t\t\t\t\tf = true;\n\t\t\t\t} else if f { break; }\n\t\t\t} else { break; }\n\t\t}\n\t\ts\n\t}\n\tfn s(&mut self) -> String { String::from_utf8(self.vb()).expect(\"invalid utf8\") }\n\tfn i(&mut self) -> i32 { self.p() }\n\tfn l(&mut self) -> i64 { self.p() }\n\tfn u(&mut self) -> usize { self.p() }\n\tfn f(&mut self) -> f64 { self.p() }\n\tfn vi(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vl(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn vu(&mut self, n: usize) -> Vec { self.vp(n) }\n\tfn ii(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn iu(&mut self, n: usize) -> impl Iterator { self.ip(n).into_iter() }\n\tfn p(&mut self) -> T where T::Err: Debug {\n\t\tlet w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::().unwrap()\n\t}\n\tfn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n\t\t(0..n).map(|_|self.p()).collect()\n\t}\n\tfn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n\t\tself.vp(n).into_iter()\n\t}\n}\n//------------------- End rusT }}}\n\nfn main() {\n\tlet mut rin = reader();\n\tlet mut rout = writer();\n\n\tlet n = rin.u();\n\tl!(x,y = rin.l());\n\tlet mut dp = v!([n+1]);\n\tdp.push(x);\n\tdp.push(x);\n\tfor i in 2..=n {\n\t\tlet z = dp[i-1] + x;\n\t\tlet ii = i >> 1;\n\t\tdp.push(z);\n\t\tif i & 1 == 0 {\n\t\t\tmin!(dp[i], dp[ii] + y);\n\t\t} else {\n\t\t\tmin!(dp[i], dp[ii].min(dp[ii+1]) + y + x);\n\t\t}\n\t}\n\twriteln!(rout, \"{}\", dp[n]).ok();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "dp"], "code_uid": "59789032c3fa37b06d41b2f18f1773a1", "src_uid": "0f270af00be2a523515d5e7bd66800f6", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::io::{self, BufRead};\nuse std::cmp::*;\nuse std::collections::*;\n\nmacro_rules! scan_to_vec {\n ($count:expr, $t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n\n for _ in 0..$count {\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_to_vec: failed at `handle.read_line`.\");\n result.push(buffer.trim().parse::<$t>()\n .expect(\"scan_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line_to_vec {\n ($t:ty) => ({\n let mut result = Vec::new();\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n handle.read_line(&mut buffer)\n .expect(\"scan_line_to_vec: failed at `handle.read_line`.\");\n \n for s in chunks.split_whitespace() {\n result.push(s.parse::<$t>()\n .expect(\"scan_line_to_vec: failed at `parse::<$t>`.\"));\n }\n result\n })\n}\n\nmacro_rules! scan_line {\n () => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n buffer\n });\n ( $($t:ty)+ ) => ({\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buffer = String::new();\n handle.read_line(&mut buffer)\n .expect(\"scan_line: failed at `handle.read_line`.\");\n let mut chunks = buffer.split_whitespace();\n\n ($(\n {\n chunks.next()\n .expect(\"scan_line: failed at `next`, # of space separated strings not equal to requested #\")\n .parse::<$t>()\n .expect(\"scan_line: failed at `parse::<$t>`.\")\n },\n )+)\n })\n}\n\nfn main() {\n let (n, x, y) = scan_line!(usize u64 u64);\n\n let mut dp : Vec = Vec::with_capacity(n + 1);\n dp.resize(n + 1, 0);\n dp[0] = 0;\n dp[1] = x;\n\n for i in 2..(n+1) {\n let just_add = dp[i-1] + x;\n let just_double = dp[i/2] + y;\n let double_and_add = dp[(i-1)/2] + x + y;\n let double_and_delete = dp[(i+1)/2] + x + y;\n let mut best = min(just_add, min(double_and_add, double_and_delete));\n if i % 2 == 0 {\n best = min(best, just_double);\n }\n dp[i] = best;\n }\n\n println!(\"{}\", dp[n]);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "dp"], "code_uid": "0ecfd0bd09e9f9b6ec2f155d14092250", "src_uid": "0f270af00be2a523515d5e7bd66800f6", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "const INF: i64 = 1_000_000_000i64;\n\nstruct Graph {\n size: usize,\n edge: Vec<(usize, usize, i64, i64)>,\n}\n\nimpl Graph {\n fn new(size: usize) -> Self {\n Graph {\n size: size,\n edge: vec![],\n }\n }\n fn add_edge(&mut self, src: usize, dst: usize, capa: i64, cost: i64) {\n assert!(src < self.size && dst < self.size && src != dst);\n self.edge.push((src, dst, capa, cost));\n }\n fn solve(&self, src: usize, dst: usize, flow: i64) -> Option {\n if src == dst {\n return Some(0);\n }\n let size = self.size;\n let edge = &self.edge;\n let mut deg = vec![0; size];\n for &(a, b, _, _) in edge.iter() {\n deg[a] += 1;\n deg[b] += 1;\n }\n let mut graph: Vec<_> = deg.into_iter().map(|d| Vec::with_capacity(d)).collect();\n for &(a, b, capa, cost) in edge.iter() {\n let x = graph[a].len();\n let y = graph[b].len();\n graph[a].push((b, capa, cost, y));\n graph[b].push((a, 0, -cost, x));\n }\n let mut ans = 0;\n let mut dp = Vec::with_capacity(size);\n let mut elem = Vec::with_capacity(size);\n let mut que = std::collections::VecDeque::new();\n for _ in 0..flow {\n dp.clear();\n dp.resize(size, (INF, src, 0));// \u30b3\u30b9\u30c8\u3001\u89aa\u3001\u89aa\u304b\u3089\u306e\u756a\u53f7\n dp[src] = (0, src, 0);\n elem.clear();\n elem.resize(size, false);\n elem[src] = true;\n que.push_back(src);\n while let Some(v) = que.pop_front() {\n elem[v] = false;\n let (c, _, _) = dp[v];\n for (i, &(u, capa, cost, _)) in graph[v].iter().enumerate() {\n if capa == 0 {\n continue;\n }\n let c = c + cost;\n if c < dp[u].0 {\n dp[u] = (c, v, i);\n if !elem[u] {\n elem[u] = true;\n que.push_back(u);\n }\n }\n }\n }\n if dp[dst].0 == INF {\n return None;\n }\n ans += dp[dst].0;\n let mut pos = dst;\n while pos != src {\n let (_, parent, k) = dp[pos];\n let inv = graph[parent][k].3;\n graph[parent][k].1 -= 1;\n graph[pos][inv].1 += 1;\n pos = parent;\n }\n }\n Some(ans)\n }\n}\n\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n k: usize,\n c: i64,\n d: i64,\n a: [usize1; k],\n e: [(usize1, usize1); m],\n }\n let w = 101;\n let size = n * w + 2;\n let mut graph = Graph::new(size);\n let src = size - 1;\n let dst = src - 1;\n let pos = |a: usize, b: usize| -> usize {\n assert!(a < 101 && b < n);\n a * n + b\n };\n for a in a {\n graph.add_edge(src, pos(0, a), 1, 0);\n }\n for i in 0..w {\n graph.add_edge(pos(i, 0), dst, 50, c * i as i64);\n }\n for (a, b) in e {\n for i in 1..w {\n for j in 1..=k {\n let x = j as i64;\n graph.add_edge(pos(i - 1, a), pos(i, b), 1, d * (2 * x - 1));\n graph.add_edge(pos(i - 1, b), pos(i, a), 1, d * (2 * x - 1));\n }\n }\n }\n for i in 1..w {\n for j in 0..n {\n graph.add_edge(pos(i - 1, j), pos(i, j), 50, 0);\n }\n }\n let ans = graph.solve(src, dst, k as i64).unwrap();\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["flows", "graphs"], "code_uid": "2eea6cdb11d628a923930d9e157cbb0d", "src_uid": "2d0aa75f2e63c4fb8c98742ac8cd821c", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn factorize(n: u64) -> Vec<(u64, u64)> {\n let mut n = n;\n let mut p = 2;\n let mut ans = Vec::new();\n while p * p <= n && n > 1 {\n let mut expo = 0;\n while n % p == 0 {\n expo += 1;\n n /= p;\n }\n if expo > 0 {\n ans.push((p, expo));\n }\n p += 1;\n }\n if n > 1{\n ans.push((n, 1));\n }\n ans\n}\n\n// fn is_power_of_two(n: u64) -> bool {\n// let expo = (n as f64).log2() as u32;\n// 2u64.pow(expo) == n\n// }\n\nfn log2(n: u64) -> u64 {\n (n as f64).log2() as u64\n}\n\nfn find_min_ops(max_expo: u64, factors: &[(u64, u64)]) -> u64 {\n let m = max_expo.next_power_of_two();\n if m == max_expo {\n for (_, expo) in factors {\n if *expo < m {\n return 1 + log2(m);\n }\n }\n return log2(m);\n }\n 1 + log2(m)\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: u64 = scan.token();\n let factors = factorize(n);\n let mut min_n = 1;\n let mut max_expo = 1u64;\n for (p, expo) in &factors {\n min_n *= p;\n max_expo = max_expo.max(*expo);\n }\n if max_expo == 1 {\n writeln!(out, \"{} 0\", min_n).ok();\n return;\n }\n let min_ops = find_min_ops(max_expo, &factors);\n writeln!(out, \"{} {}\", min_n, min_ops).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "fc9f9d296b8bebb4ff08300b12d1e374", "src_uid": "212cda3d9d611cd45332bb10b80f0b56", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let mut n = parse_line!(u64);\n if n == 1 {\n println!(\"1 0\");\n return;\n }\n let mut max: u64 = 0;\n let mut min = std::u64::MAX;\n let mut val: u64 = 1;\n for i in 2..n {\n if i * i > n {\n break;\n }\n if n % i != 0 {\n continue;\n }\n val *= i;\n let mut cnt = 0;\n while n % i == 0 {\n n /= i;\n cnt += 1;\n }\n max = std::cmp::max(max, cnt);\n min = std::cmp::min(min, cnt);\n }\n if n != 1 {\n max = std::cmp::max(max, 1);\n min = std::cmp::min(min, 1);\n val *= n;\n }\n let mult = if max != min || max & (max - 1) != 0 {1} else {0};\n if max & (max - 1) != 0 {\n max <<= 1;\n }\n while max & (max - 1) != 0 {\n max &= max - 1;\n }\n println!(\"{} {}\", val, mult + max.trailing_zeros());\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "number theory"], "code_uid": "4d4a763c503844a018c87aa1ed015ed0", "src_uid": "212cda3d9d611cd45332bb10b80f0b56", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut ss: String = String::new();\n io::stdin().read_line(&mut ss).unwrap();\n let n: u64 = ss.trim().parse().unwrap();\n\n let mut l: u64 = 1;\n let mut r: u64 = n;\n let mut m: u64;\n\n if tryv(n, 1) { println!(\"1\"); return; }\n\n loop {\n // println!(\"l: {}, r: {}\", l, r);\n if l + 1 == r {\n break;\n }\n m = (l + r) / 2;\n // println!(\"m: {}\", m);\n if tryv(n, m) {\n r = m; \n } else {\n l = m;\n } \n }\n\n if tryv(n, l) {\n println!(\"{}\", l);\n } else {\n println!(\"{}\", r);\n }\n return;\n}\n\nfn tryv(nn: u64, k: u64) -> bool {\n // println!(\"n: {}, k: {}\", nn, k);\n // println!(\"=====================\");\n if k == 0 { return false; }\n let mut n = nn;\n let mut v: u64 = 0;\n loop {\n if v >= nn/2 + nn%2{\n return true;\n } else if v + n < nn/2 + nn%2 {\n return false;\n }\n\n if k >= n {\n v += n;\n n = 0;\n } else {\n v += k;\n n -= k;\n }\n \n n -= n/10;\n // println!(\"left: {}, vasya: {}\", n, v);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "binary search"], "code_uid": "39011a4b035cf996e104713ee02bafa8", "src_uid": "db1a50da538fa82038f8db6104d2ab93", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/682/problem/A\n\n#[macro_export]\nmacro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n use std::io;\n let mut __buf = String::new();\n io::stdin().read_line(&mut __buf).unwrap();\n let mut eles = __buf.split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n}\n\npub trait Scan {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator;\n}\n\nmacro_rules! impl_scan_single {\n ($ty:ty) => {\n impl Scan for $ty {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n let next = eles.next().unwrap();\n match next.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }\n }\n }\n }\n}\n\nimpl_scan_single!(u8);\nimpl_scan_single!(u16);\nimpl_scan_single!(u32);\nimpl_scan_single!(u64);\nimpl_scan_single!(usize);\nimpl_scan_single!(i8);\nimpl_scan_single!(i16);\nimpl_scan_single!(i32);\nimpl_scan_single!(i64);\nimpl_scan_single!(f32);\nimpl_scan_single!(f64);\nimpl_scan_single!(isize);\nimpl_scan_single!(String);\n\nconst __IMPL_SCAN_FOR_VEC: () = {\n use std::str::FromStr;\n impl Scan for Vec where T: FromStr {\n fn scan<'a, I>(eles: &mut I) -> Self where I: Iterator {\n eles.map(|str| match str.parse() {\n Ok(res) => res,\n Err(_) => panic!()\n }).collect()\n }\n }\n};\n\n// -----------------------------------------------------------------------------\n\nfn main() {\n scanln!(n: u64, m: u64);\n let (nt, nb) = (n / 5, n % 5);\n let (mt, mb) = (m / 5, m % 5);\n let mut add_to_five = 0;\n for i in 1..6 {\n let nf = nt + if i <= nb { 1 } else { 0 };\n let mf = mt + if i != 5 && 5 - i <= mb { 1 } else { 0 };\n add_to_five += nf * mf;\n }\n println!(\"{}\", add_to_five);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "number theory"], "code_uid": "12603aa9f3a5c33c6e50a452586cf127", "src_uid": "df0879635b59e141c839d9599abd77d2", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\nuse image;\n\nfn main() {\n let img = image::open(\"e.bmp\").unwrap().to_luma();\n let block_size = 15.0625;\n let mut table = vec![vec![false; 64]; 64];\n for iy in 0..64 {\n let y = (block_size * (iy as f64 + 0.5)) as u32;\n let mut is_in = false;\n let mut x = 0;\n for ix in 0..64 {\n let r = (block_size * (ix as f64 + 0.5)) as u32;\n while x < r {\n x += 1;\n if img.get_pixel(x-1, y)[0] < 128 && img.get_pixel(x, y)[0] >= 128 {\n is_in = !is_in;\n }\n }\n table[iy][ix] = is_in;\n }\n }\n\n for y in 0..64 {\n for x in 0..64 {\n print!(\"{}\", if table[y][x] { '1' } else { '0' });\n }\n println!();\n }\n}\n */\n\nuse std::io;\n\nconst IMAGE: [&str; 64] = [\n \"0000000000000000000000000010101111110100000000000000000000000000\",\n \"0000000000000000000000101110101010010111110000000000000000000000\",\n \"0000000000000000000011101000100011010000100100000000000000000000\",\n \"0000000000000000011110101011111000011110101110100000000000000000\",\n \"0000000000000000110000001010000011110000101010110000000000000000\",\n \"0000000000000010011011111011101110100101100010010100000000000000\",\n \"0000000000000111001001000000101000111100110110110110000000000000\",\n \"0000000000011111101101101110111011100001100100100011100000000000\",\n \"0000000000111111111111000010000010001011001101101001110000000000\",\n \"0000000001111111111111111111101111111001111001111111111000000000\",\n \"0000000011111111111111111111111111111111111111111111111100000000\",\n \"0000000111111111111111111111111111111111111111111111111110000000\",\n \"0000000111111111111111111111111111111111111111111111111110000000\",\n \"0000001111111111111111111111111111111111111111111111111111000000\",\n \"0000011111111111111111111111111111111111111111111111111111100000\",\n \"0000011111111111111111111111111111111111111111111111111111100000\",\n \"0000111111111111111111111111111111111111111111111111111111110000\",\n \"0001111111111111111111111111111111111111111111111111111111111000\",\n \"0000011111111111111111111111111111111111111111111111111111111000\",\n \"0000000111111111111000100111111111111110001010111111111111100000\",\n \"0011000001111111110010001111111111111110100000001111111100000000\",\n \"0011110000011111000110100011111111111111101101100101100000001100\",\n \"0111111100000100011100111001111111111101001000110000000001111110\",\n \"0111111111000001001001101100011111111101101111100100001111111110\",\n \"0111111111111011011100000111001111111000100100001110111111111110\",\n \"0111111111000001000111011100011111111010111110100010010111111110\",\n \"1111111111110111010010010001001111110010010000110111000111111111\",\n \"1111111111100010010110111011101111010111011110011100010111111111\",\n \"1111111111101111110111100001001010000101001011110001110111111111\",\n \"1111111111100000100100111011100010101101101001000100100111111111\",\n \"1111111111110110111101101110001011100000111101011111101111111111\",\n \"1111111111100011100100100011101001110111100101110001000111111111\",\n \"1111111111111000001101110110111011000001001101100100010111111111\",\n \"1111111111111101101000010100001010010101101000110110111111111111\",\n \"1111111111110000111101010101011110110100101110011100011111111111\",\n \"1111111111111010010001110001111000100110000100110001111111111111\",\n \"1111111111111111000111000101101101101100101110100100111111111111\",\n \"1111111111111111110001011111100000111111100010001111111111111111\",\n \"0111111111111111100100001111101011111111111000100111111111111110\",\n \"0111111111111111111111111111111000011111111111111111111111111110\",\n \"0111111111111111111111111111010010111111111111111111111111111110\",\n \"0111111111111111111111111101000111111111111111111111111111111110\",\n \"0011111111111111111111111100010001111111111111111111111111111100\",\n \"0011111110011111111111111111110111111111111111111111111111111100\",\n \"0001111111010111111111111111100011111111111111111111101111111000\",\n \"0001111111000100011111111111001011111111111011111010000111111000\",\n \"0001111111010101001010001101011001010010110001100000101111111000\",\n \"0000111111110001100000100000001100011000000101001110111111110000\",\n \"0000011111110100111101111011100111000011101111101011111111100000\",\n \"0000011111111110100100100010111101110110100000100011111111100000\",\n \"0000001111111100001101101000010001010000111010001111111111000000\",\n \"0000000111111111011000111110110101000101100011111111111110000000\",\n \"0000000111111111001110010100011100010111001000111111111110000000\",\n \"0000000011111111100011110001110110111101111011111111111100000000\",\n \"0000000001111111110110000101000000100001011111111111111000000000\",\n \"0000000000111111111111010111101101101011001111111111110000000000\",\n \"0000000000011111111111110000111100001000011111111111100000000000\",\n \"0000000000000111111111111111111110111111111111111110000000000000\",\n \"0000000000000011111111111111111111111111111111111100000000000000\",\n \"0000000000000000111111111111111111111111111111110000000000000000\",\n \"0000000000000000011111111111111111111111111111100000000000000000\",\n \"0000000000000000000011111111111111111111111100000000000000000000\",\n \"0000000000000000000000111111111111111111110000000000000000000000\",\n \"0000000000000000000000000011111111111100000000000000000000000000\",\n];\n\nfn main() {\n let stdin = io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n let coordinates: Vec = line.trim_end().split(' ').map(|s| s.parse().unwrap()).collect();\n let row = coordinates[0];\n let col = coordinates[1];\n let ans = if IMAGE[row].as_bytes()[col] == b'1' { \"IN\" } else { \"OUT\" };\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "geometry", "implementation"], "code_uid": "b2d1a57c5c93d866c7c81e6edca3fabd", "src_uid": "879ac20ae5d3e7f1002afe907d9887df", "difficulty": null, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_parens)]\n#![allow(unused_imports)]\n#![allow(non_upper_case_globals)]\n#![allow(non_snake_case)]\n#![allow(unused_mut)]\n#![allow(unused_variables)]\n#![allow(dead_code)]\n\n#[allow(unused_macros)]\nmacro_rules! invec {\n ( $ t : ty ) => {{\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(0) => Vec::<$t>::new(),\n Ok(n) => s\n .trim()\n .split_whitespace()\n .map(|s| s.parse::<$t>().unwrap())\n .collect::>(),\n Err(_) => Vec::<$t>::new(),\n }\n }};\n}\n\n#[allow(unused_macros)]\nmacro_rules! get {\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n get!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n get!($($t),*)\n ).collect::>()\n };\n ($t:ty ;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty ;; $n:expr) => {\n (0..$n).map(|_| get!($t ;;)).collect::>()\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let mut s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {\n let mut $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\n#[allow(unused_macros)]\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n\n ($next:expr, [$t:tt]) => {\n {\n let len = read_value!($next, usize);\n (0..len).map(|_| read_value!($next, $t)).collect::>()\n }\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n#[allow(unused_macros)]\n#[cfg(debug_assertions)]\nmacro_rules! mydbg {\n //($arg:expr) => (dbg!($arg))\n //($arg:expr) => (println!(\"{:?}\",$arg));\n ($($a:expr),*) => {\n eprintln!(concat!($(stringify!($a), \" = {:?}, \"),*), $($a),*);\n }\n}\n#[cfg(not(debug_assertions))]\nmacro_rules! mydbg {\n ($($arg:expr),*) => {};\n}\n\nmacro_rules! echo {\n ($($a:expr),*) => {\n $(println!(\"{}\",$a))*\n }\n}\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::ops::{Add, Div, Mul, Sub};\n\n#[allow(dead_code)]\nstatic INF_I64: i64 = i64::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_I32: i32 = i32::max_value() / 2;\n#[allow(dead_code)]\nstatic INF_USIZE: usize = usize::max_value() / 2;\n#[allow(dead_code)]\nstatic M_O_D: usize = 1000000007;\n#[allow(dead_code)]\nstatic PAI: f64 = 3.1415926535897932;\n\ntrait IteratorExt: Iterator {\n fn toVec(self) -> Vec;\n}\n\nimpl IteratorExt for T {\n fn toVec(self) -> Vec {\n self.collect()\n }\n}\n\ntrait CharExt {\n fn toNum(&self) -> usize;\n fn toAlphabetIndex(&self) -> usize;\n fn toNumIndex(&self) -> usize;\n}\nimpl CharExt for char {\n fn toNum(&self) -> usize {\n return *self as usize;\n }\n fn toAlphabetIndex(&self) -> usize {\n return self.toNum() - 'a' as usize;\n }\n fn toNumIndex(&self) -> usize {\n return self.toNum() - '0' as usize;\n }\n}\n\ntrait VectorExt {\n fn joinToString(&self, s: &str) -> String;\n}\nimpl VectorExt for Vec {\n fn joinToString(&self, s: &str) -> String {\n return self\n .iter()\n .map(|x| x.to_string())\n .collect::>()\n .join(s);\n }\n}\n\ntrait StringExt {\n fn get_reverse(&self) -> String;\n}\nimpl StringExt for String {\n fn get_reverse(&self) -> String {\n self.chars().rev().collect::()\n }\n}\n\ntrait UsizeExt {\n fn pow(&self, n: usize) -> usize;\n}\nimpl UsizeExt for usize {\n fn pow(&self, n: usize) -> usize {\n return ((*self as u64).pow(n as u32)) as usize;\n }\n}\nmacro_rules ! max { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { { use std :: cmp :: max ; max ( $ x , max ! ( $ ( $ xs ) ,+ ) ) } } ; }\nmacro_rules ! min { ( $ x : expr ) => ( $ x ) ; ( $ x : expr , $ ( $ xs : expr ) ,+ ) => { { use std :: cmp :: min ; min ( $ x , min ! ( $ ( $ xs ) ,+ ) ) } } ; }\n\nfn main() {\n let n = get!(usize);\n let a = invec!(usize);\n let mut ans = 0;\n let mut p = 0;\n let mut dp = vec![vec![INF_USIZE; 3]; n + 5];\n dp[0][0] = 0;\n for i in 0..n {\n dp[i + 1][0] = min!(dp[i][0], dp[i][1], dp[i][2]) + 1;\n if a[i] == 1 {\n dp[i + 1][1] = min(dp[i][2], dp[i][0]);\n } else if a[i] == 2 {\n dp[i + 1][2] = min(dp[i][1], dp[i][0]);\n }\n if a[i] == 3 {\n dp[i + 1][1] = min(dp[i][0], dp[i][2]);\n dp[i + 1][2] = min(dp[i][0], dp[i][1]);\n }\n }\n ans = min!(dp[n][0], dp[n][1], dp[n][2]);\n echo!(ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "b87f3a54fa50596b7bbd4b6602ff77c5", "src_uid": "08f1ba79ced688958695a7cfcfdda035", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\n\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::cmp::{max, min};\n\nfn get_line() -> String {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input\n}\n\nfn get_vec() -> Vec\nwhere T: FromStr,\n ::Err: std::fmt::Debug,\n{\n get_line().split_whitespace().map(|k| k.parse().unwrap()).collect()\n}\n\nconst N: i64 = 998_244_353;\n\nfn extended_euclid(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (d0, x0, y0) = extended_euclid(b, a % b);\n (d0, y0, x0 - a / b * y0)\n }\n}\n\nfn main() {\n let (a, b, c) = {\n let input = get_line();\n let mut it = input.split_whitespace().map(|k| k.parse::().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let mut s = [a, b, c];\n s.sort();\n let (a, b, c) = (s[0], s[1], s[2]);\n\n // Nombres d'ar\u00eates possibles :\n // a * b + b * c + c * a\n // Nombre de combinaisons possibles :\n // 2^nap\n\n let modulo = |a, b| {\n if a % b < 0 {\n a % b + b\n } else {\n a % b\n }\n };\n \n let inv = |x| {\n modulo(extended_euclid(x, N).1, N)\n };\n\n let fact: Vec = (0..5001).scan(1, |state, x| {\n if x != 0 {\n *state = x * *state % N;\n }\n Some(*state)\n }).collect();\n\n let bc = |k, n| {\n fact[n as usize] * inv(fact[(n - k) as usize]) % N * inv(fact[k as usize]) % N\n };\n\n let np = |k, n| {\n fact[n as usize] * inv(fact[(n - k) as usize]) % N\n };\n\n let foo = |a, b| {\n (0..a + 1).map(|i| bc(i, a) * np(i, b) % N).fold(0, |acc, x| (acc + x) % N)\n };\n\n let ans = foo(a, b) * foo(a, c) % N * foo(b, c) % N;\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "402b9d9153dc269b3a5cd9ad4f0ea0ee", "src_uid": "b6dc5533fbf285d5ef4cf60ef6300383", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\n#[allow(unused_imports)]\nuse std::collections::{HashMap, HashSet};\n\nmod util {\n use std::io::stdin;\n use std::str::FromStr;\n use std::fmt::Debug;\n\n #[allow(dead_code)]\n pub fn line() -> String {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn get() -> T\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.trim().parse().unwrap()\n }\n\n #[allow(dead_code)]\n pub fn gets() -> Vec\n where\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse().unwrap())\n .collect()\n }\n\n #[allow(dead_code)]\n pub fn get2() -> (T, U)\n where\n ::Err: Debug,\n ::Err: Debug,\n {\n let mut line: String = String::new();\n stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n iter.next().unwrap().parse().unwrap(),\n iter.next().unwrap().parse().unwrap(),\n )\n }\n}\n\n\nfn gcd(a: usize, b: usize) -> usize {\n if b == 0 { a } else { gcd(b, a % b) }\n}\n\n\nfn lcm(a: usize, b: usize) -> usize {\n a * b / gcd(a, b)\n}\n\n// (gcd, x, y)\nfn extgcd(a: i64, b: i64) -> (i64, i64, i64) {\n if b == 0 {\n (a, 1, 0)\n } else {\n let (gcd, x, y) = extgcd(b, a % b);\n (gcd, y, x - (a / b) * y)\n }\n}\n\nfn mod_pow(x: u64, n: u64, m: u64) -> u64 {\n let mut res = 1;\n let mut x = x;\n let mut n = n;\n while n > 0 {\n if n & 1 == 1 {\n res = (res * x) % m;\n }\n x = (x * x) % m;\n n = n >> 1;\n }\n res\n}\n\n\nfn mod_inverse(a: u64, m: u64) -> u64 {\n let (_, x, y) = extgcd(a as i64, m as i64);\n ((m as i64 + x) as u64 % m) % m\n}\n\nfn fact_table(len: usize, m: u64) -> Vec {\n let mut res = vec![1; len];\n for i in 1..len {\n res[i] = (i as u64 * res[i - 1]) % m;\n }\n res\n}\n\n\n// (a mod p, e when n! = a p^e)\nfn mod_fact(n: u64, p: u64, fact: &Vec) -> (u64, u64) {\n if n == 0 {\n (1, 0)\n } else {\n let (a, b) = mod_fact(n / p, p, fact);\n let e = b + n / p;\n\n if n / p % 2 != 0 {\n (a * (p - fact[(n % p) as usize]) % p, e)\n } else {\n (a * fact[(n % p) as usize] % p, e)\n }\n }\n}\n\nfn mod_comb(n: u64, k: u64, p: u64, fact: &Vec) -> u64 {\n if n < k {\n 0\n } else {\n let (a1, e1) = mod_fact(n, p, fact);\n let (a2, e2) = mod_fact(k, p, fact);\n let (a3, e3) = mod_fact(n - k, p, fact);\n\n if e1 > e2 + e3 {\n 0\n } else {\n a1 * mod_inverse(a2 * a3 % p, p) % p\n }\n }\n}\n\nconst M: u64 = 998244353;\n\nfn between(a: u64, b: u64, fact: &Vec) -> u64 {\n let n = min(a, b);\n let m = max(a, b);\n\n (0..n + 1)\n .map(|k| {\n //let l = mod_comb(n, k, M, fact);\n //let r = (fact[m] * mod_inverse(fact[m - k], M)) % M;\n let l = mod_comb(n, k, M, fact) * mod_comb(m, k, M, fact) % M;\n let r = fact[k as usize];\n l * r % M\n })\n .fold(0, |x, y| (x + y) % M)\n}\n\nfn main() {\n let abc: Vec = util::gets();\n let fact = fact_table(100000, M);\n\n let mut ans = (between(abc[0], abc[1], &fact) * between(abc[1], abc[2], &fact)) % M;\n ans = (ans * between(abc[0], abc[2], &fact)) % M;\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "af023b26155cdfb27c3705e601992d48", "src_uid": "b6dc5533fbf285d5ef4cf60ef6300383", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn sieve(n: u32) -> (Vec, Vec) {\n let n = n as usize;\n let mut is_prime = vec![true; n + 1];\n let mut primes = Vec::new();\n for i in 2..n {\n if is_prime[i] {\n primes.push(i as u32);\n let mut j = i * i;\n while j <= n {\n is_prime[j] = false;\n j += i;\n }\n }\n }\n (primes, is_prime)\n}\n\nfn count_noldbach(n: u32, primes: &[u32], is_prime: &[bool]) -> u32 {\n let num_primes = primes.len();\n let mut count = 0;\n for i in 1..num_primes {\n let noldbach = primes[i - 1] + primes[i] + 1;\n if noldbach > n {\n break;\n }\n if is_prime[noldbach as usize] {\n count += 1;\n }\n }\n count\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let (primes, is_prime) = sieve(1001);\n let n: u32 = scan.token();\n let k: u32 = scan.token();\n let ans = count_noldbach(n, &primes, &is_prime);\n if ans >= k {\n writeln!(out, \"YES\").ok();\n } else {\n writeln!(out, \"NO\").ok();\n }\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "2515280893cfe4fd325f7f5eec0e90af", "src_uid": "afd2b818ed3e2a931da9d682f6ad660d", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin Matrix ----------\nmod matrix {\n use std::ops::*;\n pub trait SemiRing: Add + Mul + Copy {\n fn zero() -> Self;\n fn one() -> Self;\n }\n #[derive(Clone)]\n pub struct SquareMatrix {\n size: usize,\n buf: Box<[R]>,\n }\n #[allow(dead_code)]\n impl SquareMatrix {\n pub fn zero(size: usize) -> Self {\n SquareMatrix {\n size: size,\n buf: vec![R::zero(); size * size].into_boxed_slice(),\n }\n }\n pub fn identity(size: usize) -> Self {\n let mut e = Self::zero(size);\n for i in 0..size {\n e.buf[i * size + i] = R::one();\n }\n e\n }\n pub fn get(&self, x: usize, y: usize) -> &R {\n assert!(x < self.size && y < self.size);\n &self.buf[x * self.size + y]\n }\n pub fn get_mut(&mut self, x: usize, y: usize) -> &mut R {\n assert!(x < self.size && y < self.size);\n &mut self.buf[x * self.size + y]\n }\n pub fn matadd(&self, rhs: &Self) -> Self {\n assert!(self.size == rhs.size);\n let buf: Vec = self\n .buf\n .iter()\n .zip(rhs.buf.iter())\n .map(|p| *p.0 + *p.1)\n .collect();\n SquareMatrix {\n size: self.size,\n buf: buf.into_boxed_slice(),\n }\n }\n pub fn matmul(&self, rhs: &Self) -> Self {\n let size = self.size;\n assert!(size == rhs.size);\n let mut res = Self::zero(size);\n for (x, a) in res.buf.chunks_mut(size).zip(self.buf.chunks(size)) {\n for (a, b) in a.iter().zip(rhs.buf.chunks(size)) {\n for (x, b) in x.iter_mut().zip(b.iter()) {\n *x = *x + *a * *b;\n }\n }\n }\n res\n }\n pub fn mat_pow(&self, mut n: usize) -> Self {\n let size = self.size;\n let mut t = Self::identity(size);\n let mut s = self.clone();\n while n > 0 {\n if n & 1 == 1 {\n t = t.matmul(&s);\n }\n s = s.matmul(&s);\n n >>= 1;\n }\n t\n }\n }\n #[allow(dead_code)]\n impl> SquareMatrix {\n pub fn matsub(&self, rhs: &Self) -> Self {\n assert!(self.size == rhs.size);\n let buf: Vec = self\n .buf\n .iter()\n .zip(rhs.buf.iter())\n .map(|p| *p.0 - *p.1)\n .collect();\n SquareMatrix {\n size: self.size,\n buf: buf.into_boxed_slice(),\n }\n }\n }\n}\n// ---------- end Matrix ----------\n// ---------- begin ModInt ----------\nmod modint {\n\n #[allow(dead_code)]\n pub struct Mod;\n impl Modulo for Mod {\n fn modulo() -> u32 {\n 1_000_000_007\n }\n fn rem() -> u32 {\n 2226617417\n }\n fn ini() -> u64 {\n 582344008\n }\n }\n\n use std::marker::*;\n use std::ops::*;\n\n pub trait Modulo {\n fn modulo() -> u32;\n fn rem() -> u32;\n fn ini() -> u64;\n }\n\n pub struct ModInt(pub u32, PhantomData);\n\n impl Clone for ModInt {\n fn clone(&self) -> Self {\n Self::new_unchecked(self.0)\n }\n }\n\n impl Copy for ModInt {}\n\n impl Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: Self) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n Self::new_unchecked(d)\n }\n }\n\n impl AddAssign for ModInt {\n fn add_assign(&mut self, rhs: Self) {\n *self = *self + rhs;\n }\n }\n\n impl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: Self) -> Self::Output {\n let mut d = T::modulo() + self.0 - rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n ModInt::new_unchecked(d)\n }\n }\n\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: Self) {\n *self = *self - rhs;\n }\n }\n\n impl Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: Self) -> Self::Output {\n ModInt::new_unchecked(Self::reduce(self.0 as u64 * rhs.0 as u64))\n }\n }\n\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: Self) {\n *self = *self * rhs;\n }\n }\n\n impl Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n if self.0 == 0 {\n Self::zero()\n } else {\n Self::new_unchecked(T::modulo() - self.0)\n }\n }\n }\n\n impl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n\n impl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n }\n\n impl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: u64) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: i64) -> ModInt {\n let m = T::modulo() as i64;\n ModInt::new((val % m + m) as u32)\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n fn reduce(x: u64) -> u32 {\n let b = (x as u32 * T::rem()) as u64;\n let t = x + b * T::modulo() as u64;\n let mut c = (t >> 32) as u32;\n if c >= T::modulo() {\n c -= T::modulo();\n }\n c as u32\n }\n fn new_unchecked(d: u32) -> Self {\n Self(d, PhantomData)\n }\n pub fn is_zero(&self) -> bool {\n self.0 == 0\n }\n pub fn new(d: u32) -> Self {\n Self::new_unchecked(Self::reduce(d as u64 * T::ini()))\n }\n pub fn zero() -> Self {\n Self::new(0)\n }\n pub fn one() -> Self {\n Self::new(1)\n }\n pub fn get(&self) -> u32 {\n Self::reduce(self.0 as u64)\n }\n /*\n pub fn pow(&self, mut n: u64) -> Self {\n let mut t = Self::one();\n let mut s = *self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(&self) -> Self {\n assert!(self.0 != 0);\n self.pow(T::modulo() as u64 - 2)\n }\n */\n }\n\n #[allow(dead_code)]\n pub fn mod_pow(r: u64, mut n: u64, m: u64) -> u64 {\n let mut t = 1 % m;\n let mut s = r % m;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s % m;\n }\n s = s * s % m;\n n >>= 1;\n }\n t\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nuse modint::*;\ntype M = ModInt;\n\nuse matrix::*;\ntype Mat = SquareMatrix;\n\nimpl SemiRing for M {\n fn zero() -> Self {\n M::zero()\n }\n fn one() -> Self {\n M::one()\n }\n}\n\nfn run() {\n input! {\n w: [usize; 7],\n }\n // 0: \u7f6e\u3044\u3066ok\n // 1: \u304a\u3044\u305f\u3089\u30c0\u30e1\n let mut mat = vec![];\n for i in 1..=7 {\n let mut m = Mat::zero(1 << 7);\n for j in 0..(1 << i) {\n for k in 0..(1 << (2 * i - 1)) {\n if j & k > 0 {\n continue;\n }\n let mut next = 0;\n for x in 0..i {\n let left = x == 0 || (k >> (i + x - 1)) & 1 == 1;\n let down = k >> x & 1 == 1;\n let right = x == i - 1 || (k >> (i + x)) & 1 == 1;\n if left && down && right {\n next |= 1 << x;\n }\n }\n *m.get_mut(next, j) += M::one();\n }\n }\n mat.push(m);\n let mut m = Mat::zero(1 << 7);\n for j in 0..(1 << i) {\n *m.get_mut(j, j) = M::one();\n }\n mat.push(m);\n }\n let mul = |m: &Mat, b: &[M]| -> Vec {\n let mut res = vec![M::zero(); b.len()];\n for i in 0..b.len() {\n for j in 0..b.len() {\n res[i] += *m.get(i, j) * b[j];\n }\n }\n res\n };\n let mut b = vec![M::zero(); 1 << 7];\n let mut ini = false;\n let mut w = w;\n for (i, (w, mat)) in w.iter_mut().zip(mat.chunks(2)).enumerate().rev() {\n if !ini && *w > 0 {\n *w -= 1;\n ini = true;\n let i = i + 1;\n for k in 0..(1 << (i - 1)) {\n let mut bit = 0;\n for x in 0..i {\n let left = x == 0 || k >> (x - 1) & 1 == 1;\n let down = true;\n let right = x == i - 1 || k >> x & 1 == 1;\n if left && right && down {\n bit |= 1 << x;\n }\n }\n b[bit] += M::one();\n }\n }\n b = mul(&mat[1], &b);\n b = mul(&mat[0].mat_pow(*w), &b);\n }\n let ans = b[0].get();\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["matrices", "dp"], "code_uid": "20defb92505dd513c541a829b1b9bcdb", "src_uid": "a4bda63b95dc14185c47a08652fe41bd", "difficulty": 2700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\n// \u30e2\u30f3\u30b4\u30e1\u30ea\u4e57\u7b97\u3092\u7528\u3044\u308b\n// \u307b\u307cCodeforces\u7528\n// \u7d20\u6570\u306e\u307f\nmod modint {\n\n use std::marker::*;\n use std::ops::*;\n\n pub trait Modulo {\n fn modulo() -> u32;\n fn rem() -> u32;\n fn ini() -> u64;\n }\n\n #[allow(dead_code)]\n pub enum Mod1_000_000_007 {}\n\n impl Modulo for Mod1_000_000_007 {\n fn modulo() -> u32 {\n 1_000_000_007\n }\n fn rem() -> u32 {\n 2226617417\n }\n fn ini() -> u64 {\n 582344008\n }\n }\n\n #[allow(dead_code)]\n pub enum Mod998_244_353 {}\n\n impl Modulo for Mod998_244_353 {\n fn modulo() -> u32 {\n 998_244_353\n }\n fn rem() -> u32 {\n 998244351\n }\n fn ini() -> u64 {\n 932051910\n }\n }\n\n #[allow(dead_code)]\n pub fn generate_umekomi_modulo(p: u32) {\n assert!(p < (1 << 31) && p > 2 && p & 1 == 1 && (2u32..).take_while(|v| v * v <= p).all(|k| p % k != 0));\n let mut t = 1u32;\n let mut s = !p + 1;\n let mut n = !0u32 >> 2;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n let mut ini = (1u64 << 32) % p as u64;\n ini = (ini << 32) % p as u64;\n assert!(t * p == !0);\n println!(\"pub enum Mod{} {{}}\", p);\n println!(\"impl Modulo for Mod_{} {{\", p);\n println!(\" fn modulo() -> u32 {{\");\n println!(\" {}\", p);\n println!(\" }}\");\n println!(\" fn rem() -> u32 {{\");\n println!(\" {}\", t);\n println!(\" }}\");\n println!(\" fn ini() -> u32 {{\");\n println!(\" {}\", ini);\n println!(\" }}\");\n }\n\n pub struct ModInt(pub u32, PhantomData);\n\n impl Clone for ModInt {\n fn clone(&self) -> Self {\n ModInt::build(self.0)\n }\n }\n\n impl Copy for ModInt {}\n\n impl Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: Self) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n Self::build(d)\n }\n }\n\n impl AddAssign for ModInt {\n fn add_assign(&mut self, rhs: Self) {\n *self = *self + rhs;\n }\n }\n\n impl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: Self) -> Self::Output {\n let mut d = T::modulo() + self.0 - rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n Self::build(d)\n }\n }\n\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: Self) {\n *self = *self - rhs;\n }\n }\n\n impl Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: Self) -> Self::Output {\n Self::build(Self::reduce(self.0 as u64 * rhs.0 as u64))\n }\n }\n\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: Self) {\n *self = *self * rhs;\n }\n }\n\n impl Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n if self.0 == 0 {\n Self::zero()\n } else {\n Self::build(T::modulo() - self.0)\n }\n }\n }\n\n impl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.get())\n }\n }\n\n impl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n }\n\n impl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: u64) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: i64) -> ModInt {\n let m = T::modulo() as i64;\n ModInt::new((val % m + m) as u32)\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n fn build(d: u32) -> Self {\n ModInt(d, PhantomData)\n }\n pub fn zero() -> Self {\n Self::build(0)\n }\n pub fn is_zero(&self) -> bool {\n self.0 == 0\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n fn reduce(x: u64) -> u32 {\n let b = (x as u32 * T::rem()) as u64;\n let t = x + b * T::modulo() as u64;\n let mut c = (t >> 32) as u32;\n if c >= T::modulo() {\n c -= T::modulo();\n }\n c as u32\n }\n pub fn new_unchecked(d: u32) -> Self {\n Self::build(Self::reduce(d as u64 * T::ini()))\n }\n pub fn new(d: u32) -> Self {\n Self::new_unchecked(d % T::modulo())\n }\n pub fn one() -> Self {\n Self::new_unchecked(1)\n }\n pub fn get(&self) -> u32 {\n Self::reduce(self.0 as u64)\n }\n pub fn pow(&self, mut n: u64) -> Self {\n let mut t = Self::one();\n let mut s = *self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(&self) -> Self {\n assert!(!self.is_zero());\n self.pow(T::modulo() as u64 - 2)\n }\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\nmod precalc {\n use super::modint::*;\n #[allow(dead_code)]\n pub struct Precalc {\n inv: Vec>,\n fact: Vec>,\n ifact: Vec>,\n }\n #[allow(dead_code)]\n impl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n fact[i] = fact[i - 1] * ModInt::new_unchecked(i as u32);\n }\n ifact[n] = fact[n].inv();\n if n > 0 {\n inv[n] = ifact[n] * fact[n - 1];\n }\n for i in (1..n).rev() {\n ifact[i] = ifact[i + 1] * ModInt::new_unchecked((i + 1) as u32);\n inv[i] = ifact[i] * fact[i - 1];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n assert!(n > 0);\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn perm(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[n - k]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n }\n}\n// ---------- end Precalc ----------\n// ---------- begin Matrix ----------\nmod matrix {\n use std::ops::*;\n pub trait SemiRing: Add + Mul + Copy {\n fn zero() -> Self;\n fn one() -> Self;\n }\n #[derive(Clone)]\n pub struct SquareMatrix {\n size: usize,\n buf: Box<[R]>,\n }\n #[allow(dead_code)]\n impl SquareMatrix {\n pub fn zero(size: usize) -> Self {\n SquareMatrix {\n size: size,\n buf: vec![R::zero(); size * size].into_boxed_slice(),\n }\n }\n pub fn identity(size: usize) -> Self {\n let mut e = Self::zero(size);\n for i in 0..size {\n e.buf[i * size + i] = R::one();\n }\n e\n }\n pub fn get(&self, x: usize, y: usize) -> &R {\n assert!(x < self.size && y < self.size);\n &self.buf[x * self.size + y]\n }\n pub fn get_mut(&mut self, x: usize, y: usize) -> &mut R {\n assert!(x < self.size && y < self.size);\n &mut self.buf[x * self.size + y]\n }\n pub fn matadd(&self, rhs: &Self) -> Self {\n assert!(self.size == rhs.size);\n let buf: Vec = self\n .buf\n .iter()\n .zip(rhs.buf.iter())\n .map(|p| *p.0 + *p.1)\n .collect();\n SquareMatrix {\n size: self.size,\n buf: buf.into_boxed_slice(),\n }\n }\n pub fn matmul(&self, rhs: &Self) -> Self {\n let size = self.size;\n assert!(size == rhs.size);\n let mut res = Self::zero(size);\n for (x, a) in res.buf.chunks_mut(size).zip(self.buf.chunks(size)) {\n for (a, b) in a.iter().zip(rhs.buf.chunks(size)) {\n for (x, b) in x.iter_mut().zip(b.iter()) {\n *x = *x + *a * *b;\n }\n }\n }\n res\n }\n pub fn mat_pow(&self, mut n: usize) -> Self {\n let size = self.size;\n let mut t = Self::identity(size);\n let mut s = self.clone();\n while n > 0 {\n if n & 1 == 1 {\n t = t.matmul(&s);\n }\n s = s.matmul(&s);\n n >>= 1;\n }\n t\n }\n }\n #[allow(dead_code)]\n impl> SquareMatrix {\n pub fn matsub(&self, rhs: &Self) -> Self {\n assert!(self.size == rhs.size);\n let buf: Vec = self\n .buf\n .iter()\n .zip(rhs.buf.iter())\n .map(|p| *p.0 - *p.1)\n .collect();\n SquareMatrix {\n size: self.size,\n buf: buf.into_boxed_slice(),\n }\n }\n }\n}\n// ---------- end Matrix ----------\n// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nuse modint::*;\ntype M = ModInt;\n\nuse matrix::*;\ntype Mat = SquareMatrix;\n\nimpl SemiRing for M {\n fn zero() -> Self {\n M::zero()\n }\n fn one() -> Self {\n M::one()\n }\n}\n\nfn run() {\n input! {\n w: [usize; 7],\n }\n // 0: \u7f6e\u3044\u3066ok\n // 1: \u304a\u3044\u305f\u3089\u30c0\u30e1\n let mut mat = vec![];\n for i in 1..=7 {\n let mut m = Mat::zero(1 << 7);\n for j in 0..(1 << i) {\n for k in 0..(1 << (2 * i - 1)) {\n if j & k > 0 {\n continue;\n }\n let mut next = 0;\n for x in 0..i {\n let left = x == 0 || (k >> (i + x - 1)) & 1 == 1;\n let down = k >> x & 1 == 1;\n let right = x == i - 1 || (k >> (i + x)) & 1 == 1;\n if left && down && right {\n next |= 1 << x;\n }\n }\n *m.get_mut(next, j) += M::one();\n }\n }\n mat.push(m);\n let mut m = Mat::zero(1 << 7);\n for j in 0..(1 << i) {\n *m.get_mut(j, j) = M::one();\n }\n mat.push(m);\n }\n let mul = |m: &Mat, b: &[M]| -> Vec {\n let mut res = vec![M::zero(); b.len()];\n for i in 0..b.len() {\n for j in 0..b.len() {\n res[i] += *m.get(i, j) * b[j];\n }\n }\n res\n };\n let mut b = vec![M::zero(); 1 << 7];\n let mut ini = false;\n let mut w = w;\n for (i, (w, mat)) in w.iter_mut().zip(mat.chunks(2)).enumerate().rev() {\n if !ini && *w > 0 {\n *w -= 1;\n ini = true;\n let i = i + 1;\n for k in 0..(1 << (i - 1)) {\n let mut bit = 0;\n for x in 0..i {\n let left = x == 0 || k >> (x - 1) & 1 == 1;\n let down = true;\n let right = x == i - 1 || k >> x & 1 == 1;\n if left && right && down {\n bit |= 1 << x;\n }\n }\n b[bit] += M::one();\n }\n }\n b = mul(&mat[1], &b);\n b = mul(&mat[0].mat_pow(*w), &b);\n }\n println!(\"{}\", b[0]);\n}\n\nfn main() {\n run();\n}\n\n", "lang_cluster": "Rust", "tags": ["matrices", "dp"], "code_uid": "a8ad2936aef2534b10a47a26572eaa64", "src_uid": "a4bda63b95dc14185c47a08652fe41bd", "difficulty": 2700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nmod modint {\n\n #[allow(dead_code)]\n pub struct Mod;\n impl Modulo for Mod {\n fn modulo() -> u32 {\n 1_000_000_007\n }\n fn rem() -> u32 {\n 2226617417\n }\n fn ini() -> u64 {\n 582344008\n }\n }\n\n use std::marker::*;\n use std::ops::*;\n\n pub trait Modulo {\n fn modulo() -> u32;\n fn rem() -> u32;\n fn ini() -> u64;\n }\n\n pub struct ModInt(pub u32, PhantomData);\n\n impl Clone for ModInt {\n fn clone(&self) -> Self {\n Self::new_unchecked(self.0)\n }\n }\n\n impl Copy for ModInt {}\n\n impl Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: Self) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n Self::new_unchecked(d)\n }\n }\n\n impl AddAssign for ModInt {\n fn add_assign(&mut self, rhs: Self) {\n *self = *self + rhs;\n }\n }\n\n impl Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: Self) -> Self::Output {\n let mut d = T::modulo() + self.0 - rhs.0;\n if d >= T::modulo() {\n d -= T::modulo();\n }\n ModInt::new_unchecked(d)\n }\n }\n\n impl SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: Self) {\n *self = *self - rhs;\n }\n }\n\n impl Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: Self) -> Self::Output {\n ModInt::new_unchecked(Self::reduce(self.0 as u64 * rhs.0 as u64))\n }\n }\n\n impl MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: Self) {\n *self = *self * rhs;\n }\n }\n\n impl Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n if self.0 == 0 {\n Self::zero()\n } else {\n Self::new_unchecked(T::modulo() - self.0)\n }\n }\n }\n\n impl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n }\n\n impl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n }\n\n impl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as usize) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: u64) -> ModInt {\n ModInt::new_unchecked((val % T::modulo() as u64) as u32)\n }\n }\n\n impl From for ModInt {\n fn from(val: i64) -> ModInt {\n let m = T::modulo() as i64;\n ModInt::new((val % m + m) as u32)\n }\n }\n\n #[allow(dead_code)]\n impl ModInt {\n fn reduce(x: u64) -> u32 {\n let b = (x as u32 * T::rem()) as u64;\n let t = x + b * T::modulo() as u64;\n let mut c = (t >> 32) as u32;\n if c >= T::modulo() {\n c -= T::modulo();\n }\n c as u32\n }\n fn new_unchecked(d: u32) -> Self {\n Self(d, PhantomData)\n }\n pub fn is_zero(&self) -> bool {\n self.0 == 0\n }\n pub fn new(d: u32) -> Self {\n Self::new_unchecked(Self::reduce(d as u64 * T::ini()))\n }\n pub fn zero() -> Self {\n Self::new(0)\n }\n pub fn one() -> Self {\n Self::new(1)\n }\n pub fn get(&self) -> u32 {\n Self::reduce(self.0 as u64)\n }\n /*\n pub fn pow(&self, mut n: u64) -> Self {\n let mut t = Self::one();\n let mut s = *self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(&self) -> Self {\n assert!(self.0 != 0);\n self.pow(T::modulo() as u64 - 2)\n }\n */\n }\n\n #[allow(dead_code)]\n pub fn mod_pow(r: u64, mut n: u64, m: u64) -> u64 {\n let mut t = 1 % m;\n let mut s = r % m;\n while n > 0 {\n if n & 1 == 1 {\n t = t * s % m;\n }\n s = s * s % m;\n n >>= 1;\n }\n t\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Matrix ----------\nmod matrix {\n use std::ops::*;\n pub trait SemiRing: Add + Mul + Copy {\n fn zero() -> Self;\n fn one() -> Self;\n }\n #[derive(Clone)]\n pub struct SquareMatrix {\n size: usize,\n buf: Box<[R]>,\n }\n #[allow(dead_code)]\n impl SquareMatrix {\n pub fn zero(size: usize) -> Self {\n SquareMatrix {\n size: size,\n buf: vec![R::zero(); size * size].into_boxed_slice(),\n }\n }\n pub fn identity(size: usize) -> Self {\n let mut e = Self::zero(size);\n for i in 0..size {\n e.buf[i * size + i] = R::one();\n }\n e\n }\n pub fn get(&self, x: usize, y: usize) -> &R {\n assert!(x < self.size && y < self.size);\n &self.buf[x * self.size + y]\n }\n pub fn get_mut(&mut self, x: usize, y: usize) -> &mut R {\n assert!(x < self.size && y < self.size);\n &mut self.buf[x * self.size + y]\n }\n pub fn matadd(&self, rhs: &Self) -> Self {\n assert!(self.size == rhs.size);\n let buf: Vec = self\n .buf\n .iter()\n .zip(rhs.buf.iter())\n .map(|p| *p.0 + *p.1)\n .collect();\n SquareMatrix {\n size: self.size,\n buf: buf.into_boxed_slice(),\n }\n }\n pub fn matmul(&self, rhs: &Self) -> Self {\n let size = self.size;\n assert!(size == rhs.size);\n let mut res = Self::zero(size);\n for (x, a) in res.buf.chunks_mut(size).zip(self.buf.chunks(size)) {\n for (a, b) in a.iter().zip(rhs.buf.chunks(size)) {\n for (x, b) in x.iter_mut().zip(b.iter()) {\n *x = *x + *a * *b;\n }\n }\n }\n res\n }\n pub fn mat_pow(&self, mut n: usize) -> Self {\n let size = self.size;\n let mut t = Self::identity(size);\n let mut s = self.clone();\n while n > 0 {\n if n & 1 == 1 {\n t = t.matmul(&s);\n }\n s = s.matmul(&s);\n n >>= 1;\n }\n t\n }\n }\n #[allow(dead_code)]\n impl> SquareMatrix {\n pub fn matsub(&self, rhs: &Self) -> Self {\n assert!(self.size == rhs.size);\n let buf: Vec = self\n .buf\n .iter()\n .zip(rhs.buf.iter())\n .map(|p| *p.0 - *p.1)\n .collect();\n SquareMatrix {\n size: self.size,\n buf: buf.into_boxed_slice(),\n }\n }\n }\n}\n// ---------- end Matrix ----------\n// ---------- begin input macro ----------\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n// ---------- end input macro ----------\n\nuse modint::*;\ntype M = ModInt;\n\nuse matrix::*;\ntype Mat = SquareMatrix;\n\nimpl SemiRing for M {\n fn zero() -> Self {\n M::zero()\n }\n fn one() -> Self {\n M::one()\n }\n}\n\nfn run() {\n input! {\n w: [usize; 7],\n }\n // 0: \u7f6e\u3044\u3066ok\n // 1: \u304a\u3044\u305f\u3089\u30c0\u30e1\n let mut mat = vec![];\n for i in 1..=7 {\n let mut m = Mat::zero(1 << i);\n for j in 0..(1 << i) {\n for k in 0..(1 << (2 * i - 1)) {\n if j & k > 0 {\n continue;\n }\n let mut next = 0;\n for x in 0..i {\n let left = x == 0 || (k >> (i + x - 1)) & 1 == 1;\n let down = k >> x & 1 == 1;\n let right = x == i - 1 || (k >> (i + x)) & 1 == 1;\n if left && down && right {\n next |= 1 << x;\n }\n }\n *m.get_mut(next, j) += M::one();\n }\n }\n mat.push(m);\n let mut m = Mat::zero(1 << i);\n for j in 0..(1 << i) {\n *m.get_mut(j, j) = M::one();\n }\n mat.push(m);\n }\n let mul = |m: &Mat, b: &[M]| -> Vec {\n let mut res = vec![M::zero(); b.len()];\n for i in 0..b.len() {\n for j in 0..b.len() {\n res[i] += *m.get(i, j) * b[j];\n }\n }\n res\n };\n let mut b = vec![M::zero(); 1 << 7];\n let mut ini = false;\n let mut w = w;\n for (i, (w, mat)) in w.iter_mut().zip(mat.chunks(2)).enumerate().rev() {\n if !ini && *w > 0 {\n *w -= 1;\n ini = true;\n let i = i + 1;\n for k in 0..(1 << (i - 1)) {\n let mut bit = 0;\n for x in 0..i {\n let left = x == 0 || k >> (x - 1) & 1 == 1;\n let down = true;\n let right = x == i - 1 || k >> x & 1 == 1;\n if left && right && down {\n bit |= 1 << x;\n }\n }\n b[bit] += M::one();\n }\n }\n b = mul(&mat[1], &b);\n b = mul(&mat[0].mat_pow(*w), &b);\n b.truncate(1 << i);\n }\n let ans = b[0].get();\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["matrices", "dp"], "code_uid": "284902b39baf88da4393df7f4b83c76d", "src_uid": "a4bda63b95dc14185c47a08652fe41bd", "difficulty": 2700, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//---------- begin SegmentTree Point update Range query ----------\npub trait PURQ {\n type T: Clone;\n fn fold(l: &Self::T, r: &Self::T) -> Self::T;\n fn e() -> Self::T;\n}\n\nstruct SegmentTreePURQ {\n seg: Vec,\n size: usize,\n}\n\n#[allow(dead_code)]\nimpl SegmentTreePURQ {\n fn new(n: usize) -> SegmentTreePURQ {\n let size = n.next_power_of_two();\n SegmentTreePURQ {\n seg: vec![R::e(); 2 * size],\n size: size,\n }\n }\n fn build_by(a: &[R::T]) -> SegmentTreePURQ {\n let size = a.len().next_power_of_two();\n let mut b = vec![R::e(); 2 * size];\n for i in 0..a.len() {\n b[i + size] = a[i].clone();\n }\n let mut seg = SegmentTreePURQ { seg: b, size: size };\n seg.update_all();\n seg\n }\n fn update(&mut self, x: usize, v: R::T) {\n assert!(x < self.size);\n let mut x = x + self.size;\n let a = &mut self.seg;\n a[x] = v;\n x >>= 1;\n while x > 0 {\n a[x] = R::fold(&a[2 * x], &a[2 * x + 1]);\n x >>= 1;\n }\n }\n fn update_tmp(&mut self, x: usize, v: R::T) {\n self.seg[self.size + x] = v;\n }\n fn update_all(&mut self) {\n let a = &mut self.seg;\n for i in (1..self.size).rev() {\n a[i] = R::fold(&a[2 * i], &a[2 * i + 1]);\n }\n }\n fn find(&self, l: usize, r: usize) -> R::T {\n assert!(l <= r && r <= self.size);\n let mut x = R::e();\n let mut y = R::e();\n let mut l = l + self.size;\n let mut r = r + self.size;\n let a = &self.seg;\n while l < r {\n if l & 1 == 1 {\n x = R::fold(&x, &a[l]);\n l += 1;\n }\n if r & 1 == 1 {\n r -= 1;\n y = R::fold(&a[r], &y);\n }\n l >>= 1;\n r >>= 1;\n }\n R::fold(&x, &y)\n }\n}\n//---------- end SegmentTree Point update Range query ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\n// C -> AB -> AAC -> AAAB -> B\n// C -> B \u3068\u3057\u3066\u3044\u3044\n//\n// A -> BB\n// B -> AB\n// AAA -> empty\n//\n// \u53f3\u7aef\u306eA\u306emod 3?\n// \u4e21\u65b9\u64cd\u4f5c\u53ef\u80fd\u306a\u3089\u305d\u3046\u304b\u3082\u77e5\u308c\u3093\u304c\u7247\u65b9\u3060\u3051\u3057\u304b\u52d5\u304b\u305b\u306a\u3044\n//\n// B -> AB -> AAB -> AAAB -> B\n// \u64cd\u4f5c\u53ef\u80fd\u306a\u65b9\u306f\u64cd\u4f5c\u7d9a\u3051\u308b\u3053\u3068\u3067\n// B...BA..A \u307f\u305f\u3044\u306b\u3067\u304d\u308b\n// B\u306e\u6570\u304cT\u4ee5\u4e0b\u304b\u3064mod2\u3067\u7b49\u3057\u3044\u304b\u3064\u53f3\u7aef\u306eA\u306e\u6570\u304c\u4e00\u81f4\n// \u3044\u3084\u53f3\u7aef\u306eA\u3092\u64cd\u4f5c\u3057\u3066B\u306b\u3059\u308b\u3053\u3068\u8003\u3048\u308b\u3068\uff1f\n// \u5dee\u5206/2\u306e\u5206\u3060\u3051B\u306b\u5909\u63db\u3059\u308b\u4f59\u88d5\u3042\u308a\n// AAA -> empty \u3082\u3042\u308b\n//\n// WA\n//\n// B\u304c\u306a\u3044\u5834\u5408\u3068\u304b\n//\n// WA\n//\n//\n//\n\nstruct R;\nimpl PURQ for R {\n // B...BA...A\n // \u3067B\u306e\u6570\u3001A\u306e\u6570\n type T = (usize, usize);\n fn fold(l: &Self::T, r: &Self::T) -> Self::T {\n if r.0 == 0 {\n (l.0, l.1 + r.1)\n } else {\n (l.0 + r.0, r.1)\n }\n }\n fn e() -> Self::T {\n (0, 0)\n }\n}\n\nfn run() {\n input! {\n s: bytes,\n t: bytes,\n q: usize,\n ask: [(usize1, usize, usize1, usize); q],\n }\n let mut seg_s = SegmentTreePURQ::::new(s.len());\n for (i, s) in s.iter().enumerate() {\n if *s == b'A' {\n seg_s.update_tmp(i, (0, 1));\n } else {\n seg_s.update_tmp(i, (1, 0));\n }\n }\n seg_s.update_all();\n let mut seg_t = SegmentTreePURQ::::new(t.len());\n for (i, s) in t.iter().enumerate() {\n if *s == b'A' {\n seg_t.update_tmp(i, (0, 1));\n } else {\n seg_t.update_tmp(i, (1, 0));\n }\n }\n seg_t.update_all();\n let mut out = String::new();\n for (a, b, c, d) in ask {\n let ans = || -> bool {\n let (x, y) = seg_s.find(a, b);\n let (z, w) = seg_t.find(c, d);\n let mut ans = false;\n if x == 0 {\n if z > 0 {\n ans |= y > w && z % 2 == 0;\n } else {\n ans |= y >= w && (y - w) % 3 == 0;\n }\n return ans;\n }\n if z >= x && (z - x) % 2 == 0 && y >= w {\n let d = (z - x) / 2;\n let mut ok = false;\n ok |= (y - w) % 3 == 0;\n ok |= d > 0 && y > w;\n ans |= ok;\n }\n ans\n }();\n if ans {\n out.push('1');\n } else {\n out.push('0');\n }\n }\n println!(\"{}\", out);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "constructive algorithms", "implementation"], "code_uid": "babfa533379cdea1d8177e234132a790", "src_uid": "98e3182f047a7e7b10be7f207b219267", "difficulty": 2500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Read};\nuse std::collections::HashMap;\n\nstruct Node {\n white: bool,\n black: bool,\n left: bool,\n right: bool,\n count: u32,\n}\n\nfn update_tree(tree: &mut Vec, index: usize, l: usize, r: usize, left: usize, right: usize) {\n let mid :usize = (l + r) / 2;\n if tree[index].black && !tree[index].white {\n return;\n }\n if l == left && r == right {\n tree[index].black = true;\n tree[index].white = false;\n tree[index].left = true;\n tree[index].right = true;\n tree[index].count = 1;\n return;\n } else if mid >= right {\n update_tree(tree, index * 2 + 1, l, mid, left, right);\n } else if mid + 1 <= left {\n update_tree(tree, index * 2 + 2, mid + 1, r, left, right);\n } else {\n update_tree(tree, index * 2 + 1, l, mid, left, mid);\n update_tree(tree, index * 2 + 2, mid + 1, r, mid + 1, right);\n }\n tree[index].white = tree[index * 2 + 1].white & tree[index * 2 + 2].white;\n tree[index].black = tree[index * 2 + 1].black & tree[index * 2 + 2].black;\n tree[index].left = tree[index * 2 + 1].left;\n tree[index].right = tree[index * 2 + 2].right;\n if tree[index * 2 + 1].right && tree[index * 2 + 2].left {\n tree[index].count = tree[index * 2 + 1].count + tree[index * 2 + 2].count - 1;\n } else {\n tree[index].count = tree[index * 2 + 1].count + tree[index * 2 + 2].count;\n }\n return;\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut handle = stdin.lock();\n let mut buf :String = String::new();\n\n match handle.read_to_string(&mut buf) {\n Ok(_v) => (),\n Err(e) => panic!(\"{}\", e),\n }\n let lines: Vec<&str> = buf.split(\"\\r\\n\").collect();\n\n let n :usize = lines[0].parse().unwrap();\n\n let mut points = HashMap::new();\n let mut query: Vec<(u32,u32)> = Vec::new();\n\n for i in 1..(n+1) {\n let pair: Vec<&str> = lines[i].split(\" \").collect();\n let l :u32 = pair[0].parse().unwrap();\n let r :u32 = pair[1].parse().unwrap();\n points.insert(l, 0);\n points.insert(r, 0);\n query.push((l,r));\n }\n let mut v :Vec = Vec::new(); \n for (point, _v) in points.iter() {\n v.push(*point);\n }\n v.sort();\n for i in 0..v.len() {\n points.insert(v[i], i);\n }\n let mut tree: Vec = Vec::new();\n for _i in 0..(4*v.len()) {\n tree.push(Node {count: 0, black: false, white: true, left: false, right: false});\n }\n for i in 0..n {\n let l :usize = *points.get(&query[i].0).unwrap();\n let r :usize = *points.get(&query[i].1).unwrap();\n update_tree(&mut tree, 0, 0, v.len() - 2, l, r - 1);\n print!(\"{} \", tree[0].count);\n }\n}", "lang_cluster": "Rust", "tags": ["data structures"], "code_uid": "a339251748d9d3a275daf226920f8a1d", "src_uid": "3979abbe7bad0f3b5cab15c1cba19f6b", "difficulty": 2100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct Scan {\n buffer: std::collections::VecDeque\n}\n\nimpl Scan {\n fn new() -> Scan {\n Scan { buffer: std::collections::VecDeque::new() }\n }\n\n fn next(&mut self)-> T {\n loop {\n if let Some(token) = self.buffer.pop_front() {\n break token.parse::().ok().unwrap();\n }\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).expect(\"Fail to read\");\n self.buffer = line.split_whitespace().map(String::from).collect();\n }\n }\n\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let a: usize = scan.next();\n let b: usize = scan.next();\n println!(\"{}\", (b+1).min(n-a));\n}\n\nfn main() {\n std::thread::Builder::new()\n .stack_size(1<<23).spawn(_main).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "da825fd9eaef280ccb5dc260cce63da2", "src_uid": "51a072916bff600922a77da0c4582180", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nconst s: &[u8] = \"AsBf=V6Y6O8LWOLGSK.E*F@E?ERCGIE?8<>J*@U=DG)>GAYBI@=>C@TAY;YD:8WED>X;O@@DU=P7OBDC;;P@O88D<7*BLBK:65>;=(?/A(;J<*=QAG4-D5;D@Y>+:Q=E<-@S3:B>,EH:Y4:BG=4C-3C>RE=6W:N?W<4:,???D=Q7BBO:G==8N@.?>76=QEY3R9TBY9:D83ACQ8I?5;W:BAI<+9A@T59F<:.>Y61<>?X=/9KA>>/:38*B;8GA?75AA8ACO4G?28SDD71?S;KAR9C7@AN7K@7@A65?(=V:/8EA4:8B-6UBE72=*>5=H?W51>M:OA7<5=J11?W9G:G>3:G@>9H:D@N<*:F<4<4<1C94?>M77E)8,?N==6X@O;P73=4CQ4F@G<+B?;:9R>B<0>H7;=H>9=/>W<>;;:+=7>E:F?L0MAN@V8H?O4GAQ=998<(<.>E=H?L6J=L9):P==CE7U??8N:3=A=6I8YFR6B>V::L=>?T=S9,;N::AT=+28F(:.68?<9*>UAV1CE@;Y9I;L=K;Q:5@/:J@15T@C7H;*A19.DC6Y;;=-<<7C:DE9:JI71?X@?4@:3=B?T<0:L=@95:S=S@)4X?8?-=,5RE05CCB2/>>>@?+:P;M?C;S8M>Q7M?H:-;S?A6=B:?-2WDT6<<*@8>M:68+<,5UA.=E;U5AC3928-;L=0AG6*C24G@.@M82?(?R4>;*=HAG=G6M93A@66AL=A7I>;7X=F=K8=DE84;8<@A57(A/6RBI62D=I;Y73A.:X6B:4B>75FO76>+959-=1=34N@0=I>F9G=A7/:9;M9(<(A*8+DL4L;L=9?-9-=9>=7B:7N=@79=,>E;J:M;Y;T?0?Q4L837C>*>A;.:P39>V9GB09U;<@?J2(;(CC=?8VI;;@L4Q=(?C6M@K7G;2@6:==*>17U;,D+6E>J=)87<<:Q?=8*A.78/><@P;1>)9+9X8P:UB??R7L929QCX6H:)?1;7@)3/*F-R5?E=5L@>6L8LI;4D?,;=:L>P<,78J7/=-DW4J?M7-XP71=<<)?V:U4/DH8N7W=1?Q+=U=-6S;7AL;7?N8B>C8>>J5N>Q:??QAU5T8R=G;J?A?(81:.BT97>R4W>N59HX:J9R8+@13*@F;D8R?R32>HCV7N8XDH6O9H@+7>AF5K>Q?0:R??8(3FE19R>I7>;*CH7O95BQ:L38A?-91=):?=+;-?IS9,>H;=;F?I;S59?6:JQ8U<3;0CF-I@<==>,<2?52;@B>L<)>Y=M5=?K=@7*6-?B>1:FAY9GHCV1J?29IBE9R8A=R>B54DL;S37BW4@DI7T9B?J<(<5;<@4=R7U>5;-A?5U?/9O:08-?18I?L?S7R=M91B;8F:A98M79?R;3>AM6O;*:G?R@X4F=D:U?5;A73<5BL35DC:6=C8N9K:OBN4GA.51?.=T=;D;7G:E;L6L>V=;;0;1>J:M><;Y>(99U?-9>9F;0=G;)>@<(/9G>*:*>/>138B49)A-:/;.;JB<34D-8O;1;<<<I<,?3<9L?@7Q;>;+?)1OGY8Q<95DAO@<9Y?M8F;*;9?=8(@*->/57AH92?*:U=L?R2@?(=-9+B45V@M6;EH8L;*:F>K6,B<=M2PBY8DAS6H0<-;)43CE>N:E?Y4.@>8+@D65>T=);D9KCD<7/BBG;@B(4J<+@K9=45*CT;N42?:>1:/9<98G+8T;8;;8/@;9E7GFA8K8I@A839B:A@V>96B>)=E=9:.;--:F>)6VB38B7S?.@08FAU8?6CAF8:74(FP2PDP4R@N6QB.:M9??-;0>68C;A?E8)A+9Q?Q7Y:4>/<.7X@R9M=K;>A17I:L=S;H:K:0?G85>?;E>.<3;?959WBP:N:2:8==@(?C8>6?>J:S/<4.5T=WV>08@>.;S;5<>=M>M82=7<68E>E?43->O>N,B:6T=O=(7XAX9Q=V:=>38A=1BW3XAS3S@T7;B@6SH;Q@36793A;;Y6)AA9X:FBW5:?J:I;B8L>G9F?)=(=U;+90CW3A=3?W:V:Q=R9S9N>A=9?74K=1>)R:2>07GAL9D=Y93@76/DY5=9N=H9*F-6,=*;2:/52GX4,?1?+<56I@V:-;7C@809K:OCU35>A:(AT=,=4?K:;9U>3-62=*@W:/9QEQ6R(=M;B?,5Q:V>C=S<.A-49@S:N7DAD>T8L?E4G?6@E9V;O4-?,@U9M=H90@Q;7:U;K97=NAM858(>?8,FP3MC56B=X8;<4>081BI3.L?0X28;<26OA?;Q<-=E@B4H>T6/BI7N@F3YC9;2;3>5<*7C:H;A>0=<>53QA.=10<3:F8O@35.=1>O>P@D0(CP79?B*;)=S7*BV7G<)>)=D9P<@<@8Y<+A47F8QAT9S?T9Q<,69>PA>O>-;673::V<,7;7CER7W<(>2>F21C?;3<->.=07Y=*;+BA1=C9=N7C=N>>9Y;B5O?N<(=2:/CC8.L:O9<:79H=<@<;I;<<17M@Y8WBC6AY7/>M<=9H>C;4<1;+B)@L4O6:?O7M:(HH2:<:;,<>;H>O<=;99*=J72BL;78D:I@<4A>3>884G@T:47:BM>A5@=E:9(;K;+9A;=BJ9S?932G@9-:E:TBV5F9TCL;U4X>;BE0RB>76;R>Y>:<,5J?;98>I:6=D;*8*@.BA<;8/7*?8:=:(=U>G64B?;B=B=761=E<+=98Y>AH6J9MAD72@.=E>JH8/C-27<:@K?L6U97P@Q7+;JDU069+8<D1*<+BV8<><;*AX;L/TB,=S;V;6;<=8;*7R?>::?X4MC=;*:N8J;AG*08BE75B:;V5.HH3W?=3>AD;R37H16TD;-NF;9;7XDT7)8,?=E=C<:4MDP:V>T48:E?N9@=?@6>U73<0:Y>-94=8=Q:U6WHJ0?<=?9=Q8);M@V8Y=R<3=@;D8C;+94?T;@<-=;7E>X64D*A*6@3UEH:T?;8XK@I4*CS6<8N>??G9L93EV7(8L::?0:,C027?>@J8D?TA74CKI1R9Y:P;F>29U;0;?;=:ACH78P@K=7;T76AH9.>M8*=K>B6Y9P=>??>X23CY719BCC8):/@3)@S6,;=B7<273>P=2>-3PDY8H7DB?;>9/@,6(B<58@59-AI4UDF9E5I<+E//GE4=);371T>N<:?K3NA8;98>AW7TCH7TB@;8;M7Y?.9*A06H8-E9=N9V9-<0>8:H>F7==U;A:0:O9?>6=(Y8KE8.58@M88@8;:I:28R>CAD;.8>;:,5?B-7O?M43B-+8T4,@(@+6;@?85=EA)=G5W?L4EBV:F8L;/>YB08K8G<;D.5;:H@=@A4K<4C88E7CDP/9@);1@(=R8CCD49AW36A5;R:6:,=8@?71::;CA=<0=66/9-=0?+7=FO705M:IFA>K6U55B(@K/JA@A;4F<4=B=C-;A9>8:>T@@;T9G>M4UAV@R3E>P7Y:U>;B?2;CD60AE8BH>*7J:O@B8:>H<3B65N:O9H==8B?(49AY>6:OA*8Y=7;L;S70;.AA:MAN7L:,78<-=?AB>M:58K9N>A?U7<7;@->J7F=-?=:4:5AK4@@:;YA9;80/@0<6C@4L?P89>(<:9P=@;S8A9;<U;<@X8>97J=09T;+5+JL4R3OGS:N8N>2=:1=IM<>69;W9J>X9/86:>CY936,GP9F9:88E)7<<.:8:(@8-?7T65@C6JBG;4AAV:*8?9IJ6.S?2:X:T?T;+>L;+=W<;=.-*CS=L<89X?E=NAK/5>D9S;9@46>>;;C>>;T>N7?C@3G>=;>@Y8M>T80>F:=?V;J8X7H>8AA84B:4J>B<-7B:@JN37<78FBX3R=QD*5-BV5L83<?9TCG7YT7.>JC6;;939M;N;0?/3>IJ59;:<3?V6U=F9;;0>+>)<9C82G:W:H65OAU1IA*?J8V<*=T;@9-<78TBU65=?B(7S;5A=I846V;CA6BE8J?M5O=<9=A?;;6R>+9VBR62>8;M/:@>E6B;8>G<4;L>2BL4H@P0E>*=O=G>L46BD7*<0=Y@=9Q7X?:>A:,@28R>N3)Q5D=.DH>P8Q:J=G4L@8?R-,DW>,9>@A3NBY=E:U:E:O=H;9@W.V>/=RD-?R3P:9;S?Y=7?A3K=5F53)?:@:R=,=B=9>V5,?*;*E*0H@D9.>X;C?Y//D4>?B52992B175<,:>CB9@>Y3,EK9TQ:U;:@G7Y8,?E>->H4L??7P;D?=7NFJ=(3B@4.>Y9HE>:@;?;:L>P8B=X9U<7CW2UAP4YC(9@:0BF65>F8Q4UEC9091=R?1@G3C>9<4AG:,:O:O?C:*2S@0C487:N;A=9;R9:EU3T>T=9<8V?U9?ES3T77<3@/6T@/@K:H?82(B?:5=T6AAJ3:CC90>C:3?69);285@@96;>:N8S;0<;@(99@-6YC<7E8GEE3->1DG34<M=W3?G38;<79=A,24A*J;5;65CEG6N>K92:BF7:=51>L=Y;V8T=6?O5.>,>H;97+B+6@<0B1=65OB+8C?@3H@KAT;09T5-?D=A9O@Q8>:/8?AB:5BS7I:M?45/@O;Q8VB28W8HB<9+@K6::4>W;O>2:782C@=N8X2BHH4RBK2)=P=)?9<7988C>L?27MD,7MAD9H7A@86T=(;RC*6V>S7W85CM;99B;/:KA2908H?;58=I>M;E;*>4=?=P4,B?=D:-A?3?AX2F@7>98V75J*1*?+=)@S,5XCD>M4)><>T48=V9D?J;>?.=J7E;XB.22A>7HB)8H>=7?@Q7S;RA*5;:U@Q>N4*D7787OA49OC@17B?Q:D<@9=:<:/?F@E5*B59+B)6I;5;H8WD>5??U6NA):):/:4:<@+7Q>C>F<:BK7F<450?.A.83;J=Q6+BM=-3?A.=V7V=<==80>FD20O<.AP87?*<06NDJ5+>S7F6+D;>S;460AB:1=S<<9:?,92:<<5;I94B>::?=)?E9Y9*@K9=AH5J89F;675-HW76:5;/X8+=B8KES7S6DI:28?@?:0BC59>M;?;9>C1F>JBK:S;9:<7J;N9GHC6Q6<1;9;Y<*@R:S@,8I6)>+*;.8.=+83CL;W56?>>C7J=K=<8M@/?V3B2;77;@T?J?<,XG1;Y9O;P>7:H9R7(CC<93F@K;,=I=*:S;3>W=U<7;C79J16CA73?3<)<;1?=927+8X=X6JC)?54I;4)8W>@B=2K;O@>=;6E9T8:G5PAX55;<@26@=+?78><6<(C/63C20J@V:R<4=-K;)=X>N>I5I=E8Y=UB055=>AP9(A)5Y>H7L9DS8.=08N>9;0CN7E9H@A9W7DB<6-@-7-?>;H?H978X=Q<+<0UJ,7K4QBJ6A>1;+?<;Y>98;7;AE768AHO/;>H@I:P<7@Y/GFK<>59;7>R:Y@;7;@.;)9C>H5FCW:W9H:*DK;68R<<9+<*=+;TA(70;V94AA6.?.A/8P5E?.98<<@/:6?O8X9:>B<8;T>T7,?G:P74E<;G61;2>@>39G96=K;C?S:I=63KD*3DF58:9<=CJ;B7PC-9D7SAX4?@H@D8::7<7>,><3P@@7:>Q;P:TE14D=H=L3DC1>M4CF737:2?.=NC4)D)W?C:U;Y8)CL7W:D>180CJ2NB;9J:(;9@V9.<-=SAL4P=G@(4.:-;BA8>291B48X7CE90O=,@-9Y=,?=S34C094=Y=B6>U@Q9GEI/LD50UF(6+BW5M>14R;QY;S9;=<7J9K>-?1;;V:?8Q@?=;9(8T9W<>>.C+:E65=J@H9>=O9K:/=87G=2D;86@44@A,;F=;3:FP55=18==1BA7>;F?LJ6,;5>;CU6*+7U;:;1@Q9;;+>.6L>1<@:J9)DG;<;-;?9?@F=:4O:A<@>M?X;>3.F/>A7X:V;@6,>4>JC74:@N4JB.?I6Q1>*8H8@>N:O;N;NA520@+;A:CDA4L>/?W78;Y59G@8=>810B8@38.:L7H@2@H<)6V>O;BD(1LC1:E56B>>86;8J6@CA8O817*C->O8/;/=97=I;D84DQ5<<:;I>B7+H=S:I0;V9A85E87<M=A=<6A9+@A9PA?50=)?G8+D67M9+9T?F<79*<)>58KC,>W1Q?I:H>0<=3VCH?J7W6M=N=2?6=Y8:>?;77D;>8=859D@B>W:U@E97:C=D7+@79R::>+=A9V=Y>T6Q7SCA8(>R>R35:*FH=A9)9E;Y7Y?R>O;<<*9)BQ;:8,9WP0L?>@192>S:B9NI;J;X=+8(P6KCL6U>R7Y<9>9=191>537KK7,0IA;;P;,8VCJ=<:.AO2L@H=A5<:;@W<4=):M=T8.?49,=6:7>V@-7+=<8I=9=-@U1CCN=T7B:J@Q:44TCL)>D7+8BD-==:,:+7,BO*48>O>M=S8K?@>N7+X;;<29NBG25A->L?+<07L79EB9*5D;><.=L@Q9/6:@1=:(>-9F91?F:0=S8M7M@J>>7V@L6+F>3)B36I<):;?WB>F:B8=8;37V>-<3?66B@D76D05>@6;+9M*7<@M64C*:?:6@R9L<>:/9P=>>.;+:@B(@?/PN:9>);Y?46O>BD*5UA)7E88@U8@?*>X9V9TC-8>;H9>:,A29S:E>@@37?=(6V*7@=/;V;PC=O3;CL7+>>2>FG86BD?:,-AL=?@,9+<5>05N>1T9W:A>98,;>>L:M:88*BJ:K>D9*;F=(:PDX5Y8E?*4@:,E167GQ/XA,9E>0><;Y7H;P8?DF:R:?6H<@6U:O?>;5;U;L=0@8:R6X?J@81(A/9>>S;.=5:8<7;:5WBC@.7;<*9N:/A:>M?B.U@(=W584:/BP50A47K:3A68G@I78;L:)B85/B(:K:C?I=(2;F>59A,;+>C3A49*98A)1=0BS59>>9VB66??P9,2@HP8NM83D/:G4=CAD;D9H;J?R=96,G<2I>1AQ7H=*=48.;9A35.8CFB8=8O?V>>9*A130>O<<6H@/:(?+;C67W<,=B:2;FO9A?2:R=/:Q,;2:O-AJ;F4/EM4E::ED5*>0?/:A>R7C@O1W

-:,EP/0HK7+9:=)@7;240FF3?>OBA7IBX;;3U@VAN5.8E=*?B8W<@9+;/@;?.5W?A;Q8;BT;3:J;W:<8P@Y>R1OB45B>28X:4D@9F6FIN47:T6,C68?@E884=F98D;;:A@866D.2?CS3+G)3C@==,:*>Q2CDJ;M>O;P7@:GA.:85N?W9X?6<:<5:R7RB-8FGR5870;.:G=+@593A(6Y:;@+9@=J@F1/F*5)@.70;8@X@S79<7=U4:E@729A?)>=7X9DBX1G@2@U7/:)?K;6@B:J6DGP/0:3JL4Y7M@:=A;H;S7MA2;Y30G*7N;/>A8=>S<6(9-BF=G9B2WKH3Y>Y8(A=<(6L;)?H8W@=4)A76H@M=K9U7;:-=U<:@R6Q:8F011@E8MG<)<5?=@M3V:L>+?T=43R8LGD2:?X=(;V:C@,4H;(EH8J7H>-9(D+2BCF8B>E=(;3;N?@9=9B?6>J3S=J7;<)79BS;+4QE?5Q37DN4EB069E8TYA:24??64:.?A@C9-BD2B93BR==@57*A>7F=M6E<+8S;A@L9YFI/Q=OBO7>>S=)7+9+B@6T@Y9U<,><>.9U3)B)3?@=A9=K74BS3F<3A=:@7/D@9:=4516OE9AF2L?<9LCC3@CV6-:JB.4V>A>0>42*GM6CBO616PEW978A66B@;C:.D=5OC28-:3;-3EGB?S40?F7/>S5.@T=S@24?8+EL7D=GC82CA=6??J:*=R8G?W9.=2@U4;@O=38>E=7F778BD78)9:=E;1B921D38/?F<3;F8AAD8W=-7@-5W23=EM57:H?D<+93;;CR9S5(AH9(BI8O8G?C:>:-7YA6C;B45?X@O5R>R4/CG8CA=9(?=7+65G;2D7LH845BO:4;;@G7EA6:.4@F54F?87(AD>)?X8Y2N@8=86T@R7-@E>47?=F8.A8?K88=77O<9BV4W;,B.3=>XAB:96:A79E33H=:,<)9D>S:M>>>R,WGA?D4X==<,=P8S?C8X=(=(?A1CER8Q7WE<5+MJ-T;O=4AD9K7J?A:A>F>;8)=<<5I:7CI00J844A0;L8W=V;76;A/:EE)5-9+CJ5SA37C82CU6A@J:K9TB2<,7V=@?U(8U>H=8S4K=7C)8:9(>>+8L?561B+;A;(@=66C<6V9BDU2+=2AV8D;;9H@.=G;3;C5REK5S;9=J92EM4.:AE14F;U>T=?64?*;U:3R?M05C?:P9,A299>,AF738M;F<8;<9W=.B=;,<,6+>O<;8/>@;-8>C>:3>7=<66?W=767A?6WI=3:O@75CAY;4KC@17.=@=5<29@:RB41EA3::N;,>X66<,:.B)98:.<:BG8/>O8P<-@H7A46IH5F=W9,I=;:A>C<:7K>K=@8K=*8YD=8-;=;I?G6YA;7,?J6O=G?U8-?L9/:B:X>A;EA61OB??+6U>64RD5:C=5>A:6998/:JD28:53EK7OA@:=44@:6/D??M7T6YB;4Y5N>>>N9T9IB74Y;:BX9.;M<6BA3:L4@?.:*BNF9+P6J8VCR5T9FW;49MAQ::6?A3AF5T9J=B;3@57E=F3G<8?4?67-?Q9+=(@2:O=P5T;H=+:>DS5V:8A8:U=F8:9H=1:8@7:57*E646BW3@BV5/BX?M/+C78P=.AW6@Y6E:B:7BH7XA):(=7;@<14/GX17C>75BQ5S;K9@?;A*:Y88D-6360F-8U<@9>B22V?W;S9A>+:CBD>(5X8H:)@9KB14=?8?>72A,7G>-;1:U>=>P:/8P:Q@V?K2?CM4,E@4J?+:P8IC+6(85>5@E=?;X?J43?:?49V3YAO@;9K4PCL8L?>;8:H3HH)7A>87+@E?P809M@T9U7K?@;)?P?H91:K91@K5S>N:H>=9W>W;D;C=C7R8)BO;N:8;S;+=3:8P8/@A?+4)<,=Q9>?V>;:,;+6,EK5A@FBG2<:LF=-=B/?36VC-:(97?;;H7BAP;P9,AC0H?G;,?;89>P:/;T9/EG59:+??>80BE2;;A@294AP7,B23-@L9/@>7RAG8V6;BS=X3U<4>>>13JB9;8:/CG/OB@=HR8*=B9+?:-AI1XEH95;*=4<1?T7M:<==?G4IBS6I?3<;:G7P;H;=E2948A@<9B49GI(S;V@/73@X9V6J>V5CAD>E6C8LCW4VD145>4>?:A;/::6O@-?D:;CJ5E;+8,=Q;K(DI4,9C=M=.;C:<<)@*31;DC,@*7M9,?6<::M9BD<2L53HH5?EB34BJ5U=RAA;?8,8U5@BS?G<)90AQ7J:3;C;5?0@W4,C=8I;D7U=U=HAN9+6W;C=9?<75A4465YDI7<9K9WBD79=Q;N?X7,=G9?:BBY9-?Q81<=>37<8C=V6G>0CH1R>>>AA?7I@B2?><60A+;XA)3U=R@-918DFC2S=U@49;@P/7?YDJ4PFE38B-3K=-C)?+593QC(=?:SX:5=W6C0AAA=R35?);->><,7P=(;X<-=->4:(=Y5TE9R:H=E;*?C8X=CKBQ.JI)0I;ICU7W>V:H6=>A>T86B<7+>7>Y>Q6P7XCU:X6/?K58CK8:BP8259GM3BEM45X56A2>,86A7<=5WA>5TD?5P:B@;8*AD4DB4=74=X3@CL=>:(7W>(:3=Q8L>H?G1HB)?D5I6T>*>?6T>Y=W3.EE6==V:2=W?Y9C;>@G6A<=>8:J?D57;F;U;;@M8-=14+BN=K>*;/>O>601DR:C8H?E>09,:T=+;H@B7+;X>2:L9D96H//HDI3XC:=S7WEA6:K=,>(2I?B<8@O57=<<6@P:*8U>Q=9;5:889?.5)T3FCQ7/7CGV:<2QC?2?@A50D?>29M5:(@54.>2<4ED4*6@:BGU31=T<)8(A1=O=;>E813QI103AJ:>AQ2TF1:X4DC;5:9;CX7J:I=R@>9K:9@/=G7W>I8@;J69FQ76DV0BIB20:85;O9+7CH0=-6*@A?-1HA74=H-4M>@;V:69P>?>B<69H7NB)8;:7H=P=,7AAR7T=M?T77@787:C57ATCA8-:4:V>/:R<+;?=U:H:P>4::=1<:83;MCN86;)74?O7SAM=L6CB6BB4U?P31:5)EV;?:*9J?/46B8>O8*=@5,DL:O9T@@99@K:7:I:(I22*=J57>4?B:J;2=K:C;N;V4@D+:5<7C@V8/9H9A>39SQ6DA;:S<.?X;46UCA8>9-80B:8MB<A;K=DB@0+>I;,=S;=?.8484?CA89>Q9,66>R;X:1>P>I=M:C7T>M:X7P@)>A94;@AP2)A58FCT7<3DC*A*2E@K1>;.1<?4XFR67;I@-92?44H;@?1<1:*?V:+:.=G=H8??(<9?.6>:;EL31A58,=*@O;Q8M?Q:O6T>M>DG/X?;@52SA771@6?E:69?80=O?(;B=D53AK:+=(;U<0:3A6>BB8A+E6:89T7/<3A86C?+=674R:Q9J;0:W;79B@:99A777=VAQ7K=2:.:P81??=-97>R>)7)@R9471?R9O>(:IAT3H>=CK6O?H:*76B@3H>L;?<2<7AS:K=07O?4;46L@L=74AA0:K?Q?24)>,=P>K:=8688ADBS5M:?9R:G@F<2290;9U987J<->-A=?S5671?2;T?B2A5(B-9S:1A@8-<-<7=V:==-9W6-G74T?J*9F8H:>N8V8K;M?27?FW-J>MBS5-CC>:96:F=-;G=8<)6BEP0M@,>,5(AR;<:C?=:D9W?X;H1JA:DB5L8Q@G41D*<2;V:>?<3,>O@1>>X3L:TEV971;?RA+<>1DBI>,;:;,9U93AS:I:*==9I)8CA=>J3EF56G;NBF8-:+>66-F-4(5GD>4KGS3VBU7X;8:W@86PT80>K?-7A9T>2A66S=O6C;W<<;C7R@993;?6VC>;3@76R@::B>@0N=V=DCY935@EW0R=S@R4LF,8X6-AP8Q9>BF90B48);,6ED8:*:(9N;ECU7A>I6H?B9B>?6B76BS=M:?>=6EDT:.5-@/6?F;::.?-14B-.8DEH57:P>/:,9VCG:96W7;9@87V8W>Q>+5/LA/1AU7N:*>E?-7R>K=09Y=.=@7B@-8*@6=G8L;P<(8N?G76<8?E;F/?V1NAJ7<@@9Y;.?-:NY:57P;M=F>,;I?T0EG(9440@X:1?X;+88.=SDJ,9E@1?;U7CD?2T?Q>J;V)?*;GP@P9.67@P:W;=>893;9?/45V@8;*;<9ID<.>?E@25NGA64?96CAUA228Y9G71AX@J5X;0<(>L;49S8O?39QEA.I>V<+=K@W9):C>6>48/.9WCW03:BDO6?@5@;8I8E?E9E9+.=84FHR.R@?>98F.5CE=/BAN6K;G;B@P?B8/E-1N?+=@;4=963AQ9E9Y?T4/;=DT;*:U9R@/8)2;V<+;.>YAF:V7V=F9A/<*8+CJ27@A4>73PFF6(:B>.<16KBQ9Q<<>.;963DD8R?N8-83E<1ED*:I62A480A5;?@9VJ8J9H>,:3=4?06@@77-C3;(;(:*@;?K2>CJ0EA;K7D=W@0D6*A+AL3@B2I<.E;;743C7;O8D@W8CA11GACAB59AX40>H;C>S=I9:6AI8Q<59P;9HN1E9F>:A8994@G;*7CCV8:6OA(8P73:5B/6M:>>*:X7>DAA;1>@C;,67B(?(9I>E107A<81@J>G5R?W;99IL4@B=@(=>;K4/8@AM?I:7A@;T7A:U?P:T9,93@A;7:G8MC,9W=K:E:Q<6>+8P7A=UCV8;5RE,96:K75@)=PDCX3JD(22=@=Y73@=92=>A?9W;X5B>O@R:19N@>8M>-AH5::E;UC:6>(>?>F1HC;:G:J4CGH5;;J?.?B3):0DS57E+@F3=EK2P<8=0:C@>8L@/:T<)B*8)6E@5:5B5<36<>G3S?OBF4U:A@(1NL?5<>E5.D25CA<<(8LBS3=>I7,:MA7;9;U5?.7I>Q81=T5UE(9V3;=Q?I?65O;K@Y*>O7T?I8C82@O9J>19:>F,6P=(;7?X75=V:S=4>658?J@F9CD59E/?P=N6JB4;<4H@09)>)>7N5M=R>49B=M==>81.AI9T>+=P8=:G=@=N6N?8BI87:,4<.>R7:;0A.@F9=7(AE6W@<6V@C>F5R<(9J>:?C>?13BB;46;V3.G93J=R:?AF?A9F5-AF36??(94<+A<8:;B:03=5;E=W61@F5Q@47*?-,;M47CD8H=D?F5S>J8+D*9-7CAX<:?(<-4P=Q;H<9;::;;TDF609Q@>B5+?-B?=;2U@P9P;Y@D8(<(@88K@1:K:G;V;K@34Y?G:O==7JD)6;??;65.6I=D<*:,;A@W9K;,9Q=R>8:,:*AP869F?H8FA773?Q8@=/9)BP:4>Q35>N>3?3:U29>,@(>=3*7?5P6+BM<5@03Y?M9HB9.ABU=9<.5UBH;+8MB59C<>?A5X;,>*0AK9=8;GJ4G>?5;9-CC:C@05F?Y9>:4A29(D..7F+3.JL,THT7/74=(@Y=F1G?K=39(+=C;::7>F9V8*D)997G@A;K9-:-;MC+;;8.?*;E8O;0?W;<8+A=78;3DE7-96A/55>+?@:J99:;>H83?MY@I:M:@=C;A7.>P=1AG6M:N?5:G:;9R@1;O8G@W6;?9:JAF9C6OAD9*>)?V844A@A>,<)9@7W?>?E;(8E@:<;:P?6:X1HFX5SA)6Q=W>@7.?-9A>->A9S==U7D?09*>M7QE-6=X9F;X=*8R?W:2P3X>NCK9?6=?3:(;1=9;=;A>SCD3NA)980RE*E60@Q72:T@-6G<,>*;7?DA*=H63>=A>,5@:-K34:?E>.4Q@J=2:O89:A:I?E85>/4/=B=0:B:PAP6/;G@.?C:(;L9@BG2(BM=Q8C;@75A(8>;/DP7O6QA88C)=P4-E07V4)GP7)8WDM26?<=4?R60=M;/;?S8LA01:=H>FA/4?A.;N3,B)8P=D@U65;8M=S@794>M4A:9B2;D7V;@6QJ18O=:4*@;:=><:U9)DX7):):1>(@>929AAT8/;.AO2,@G?@=Y3Q>N:F9>DC5E?07S<293DF;5;29J:0BH9I7(A/;V?43?AL@6:K@H5M=N9978X:B76BV6S?B?S7TA(8D<1;.@75ECL:X=E8+9*EH.GCN0IC*@Y5*BW<15/HA0/AF;DAY9V5D?(=E6J@=<>5L?@<7H5V@4=?:I:/EG/)82C:75BN>B7(7J?C;7>6?X=48V<6:4;,7VDX84:)@9=89=8*BW3*=Y?3:6@K60=Q1UC78K7X=U@*6B<4AL70:8:J?1>-8+R17DE(6H4YCR<;;3<,8A@N75BW2*C:43A,;K>/5+A2=V>H7<H?D1HF<8S7,>=;I?77G<9?+4,I<8D3H94B:;M9P:89*=>:*:SAW3MGR<<8E=;=<<39>/>C=?==B30F0:B7NFO4/@H7L4V>IAD8A>M:5:>;+?/?B;<:M:J9?B;779E@(>Y<19P;7>L88;*78B99Y;K<323B?C;K@86(=1<)?19H7:DK70:V84?>9B7LG3;-;6B/7E?M./FE:;A66S?P1G>0@W8Q=F5W=EB)6O8P@99K76EA9G;);>;Q9M>/=X7O>1;A9B99J>T6:B>;G868R?F<3;/>A;><293C40IT26>F:V:X?B<:>H94>D2N<6>,<8DD:V:89:2;L9<@B:O;M;A:K:N<1@2=9.:*=O;B=0:V?D6@:=A-:N=8:)=C?N9,89BK5(FB1Y@<2KEL;@7?BF3L>D;X:+;N7MA:AI8:?E55D875?N:F:;6B>1?;:S8SAM?;5H?29JAJ3E@350/61C4:C:@:H9?@,?C7,>Y6XAR7/@9=28:>T?28K=S/L@)CX>U8@?<67?93CC6:D8;BF53BJ6LA-27BG=;;O<82*A>??8Y@W9T?I4QC=S=,7N>/3(GP8L6@?-@>3TD-;V;54P@U>B7P=;AS;S;(4/8YE02MAE9@@R74M56EA8=9)AE9V:X6.=?>@=E??7;B,9P;W:,9O9X?W6AFV;B2=AJ<9?F74:>AM:U:M8L>M=?92;<=39/?Y7Q?8;I=X9RK2W)D26B;86A>-I?<6J>(4UCAAL8/9<>A;74SB8:*?P;69.<98U?J7(I?1BB-86A:489HCU*BW31C:73C:;.5O>/=S5Q<3>29Q;9?26L@Y=O9(>R94?Q:3<(6BHX10>,*>W3(@I:C@Y7CBU7.9GCC9L?B9X1NA<>??O2FA<=Q4V@/8-EA9Q2,B@@28V99@<:?<*AK<>=W3L=;;/LB?59I85BN94@14T:(@;V;;;58RGX75=.23G85684DA8>88CL/@EM6.<,?X13L13=A<9;8J8SAK=XY<*=*2VB374?,AL32C+=P6A9K<-DI1PA?BM0C;K??>=?U71;+=J:O:4;Y??8.T:=EK15=-;)?F:7@U3KC88E8(DX9T9,71EP5C@6;B5XBL3R<4EE5X9=9K<3BE7@=J9R?T8TBC2?DDA=5,;WBB7X9I:O=D<-:R9.E>1-UK;==B;KB452;I8F9GF)7F8XCC9W=X56=/:3E@43>)75G:5M;H3SB+=O=)?+4SD)2>*7)D*3S@4;:9E=YCV3/;29/=Q@Y>34C;RE63L?4?D8@>4K<59)8+F167=98WBS3/CB>Q;R46>/=-75@5;8?896=99J:*A67G79H75C@+;;<+8*@7>U02B5:9;Y;V82>RDB9W;B8.=D>55WYAN8U8I=L9/:Y@A;@;W>.9@>K9X;->M7KA,;=5T*1=.:E?-5XF@U8=<@C<5G;*5G8/L06>Q9T>E3(@@<;8HL?O9;4;?V4V@C?<;6?O2EC?:4;B9>AV6U<)?A74I?8:=>@=9;@=K>32B>F@O4B@I63@;AN8T?F1,D;7??=AS8C7/B,4E?2AH0N8@?P=V<>=X9V8/?W;T8)6Y;B@I97=LD*8I4MDX8A34CR:*:C:3F;+,C5CS56=5@U<(8==E72;?DL1QC>1X>T?;9=D9:47)=26?@0>799?A7(A,6=AS:;<;?4;H7+?L6IP8)?UW7ABL88>U?W6D7-AG>39?<>=?7C?+AQ5I;9:1@C>J:M64=,B58B;F7,E86(;89CB10)G,8?5TIA4O@U3.I*7378>;?>4DW8)65BY3DC??V?,4,;B>Y/A>KD8:G9G8UHK21=T9M?*@H1LA;Q?X:U:>9I@-9:=M8=>5=B:)=>>N5=A29,6HCD5JGD7V<2@23O:KAQ7,:0=G?B8->W:S8Q>>9I>+:@C?:N7>:*A8:==;<6>==S;L56=W6)A?;6:9>4?EI6T85DY6(:-A36>B(3XA67/G:1H?D;KC-34:UA=963>W:V@?2<@Y=<8/;V:N>M=.:+8-B5>87(<1>*9T?:<>9.@5:S89F337=N=@8R;7,:07U@J>X7K=D8A?M>F5Y:1?R::>O9X;P>(;<<7C>D9<=A:68F>H99>N=S<3>A?+776BBU9P;8?2/2=?=@-=,(:699@)@N6.;K?0>/53=N?;/5>0@P83AS9/=?==;>AD92;,:*>8;L57W=29OHE(@DP;86.8B<:,Q:?7(@-A:0D?2S9M6Q?;A:5,@L8M<8=1@:9J4(?*AQ7;C19E48A;:N?JJ<+MJ76@67?HB74J;S<25DDE=7I@/;*8K;E=J;(@M9;=E:=:X=:V76?5AN2KA*:U:U>/5C?Q8@AW:T>:4D@4?99X:4AQ/IB99T?U=D5U>W=:=U:?W=QG2>H,5/;>:S>HBU916@>/@;8?9B=687C>9S7N@;>2=581:>>86J?=9B>>8=Q8E;3E04Q7;>8>/;C;->6;8?<6@7N?A@26)8-BO<1?S73DI4U;95GC8AQ:P4N9KDK72<17L=6DT7H>H98C//8C,42B(I6D8BA*9+;BA(:N:6=O9(AY9;4WFI916O=+:IEN8877;GFK2L9SA<9T7P5DH18XAS5V@B6@DO/9A+@D2MC+;D;3@@7(BF3;?(;D;6:8;U8?E?9)B54G47V;E8<;39??9<;=-A+9@?,/.CF93<5>89/@E87@;3O>AB<;@@(0B@7=P6/AJ4XB?9Y=T5RBKB81MC*1JGH<7:S5Y?X(5Q@F76C17V=.AP4M+84;>2:B<5<,8384;,?-:;@A5NA=;=F6L:@;0*@+9L8F:SB>:):O:3?J;;B=04?><,D17BHJ=W9C=R4RBN7XB:S74DF2DD.7R9Q;:<.><;5=H;>77>/:GEO7?>A6O?C95B65+88@A:JA:H:R<<=?8A?U:E?*5E<.@3/3O:.CP50C:8-;RA67?7N@79(>M::A>86T>?5FCA8<;X=<7L>>9W;NDE5G>K2IH(3CDF8.=V9U84?W>29L@G8?<5;@;==,37EM;G6872GC9D55B1;D=2;I9GC>3=56FL@T5+?93Q@KB286<6=98,79@F?2;E=R3*BA?@15B2E:Y?(9Q:A;AF52@@B:(:1=<:C@>:,:>8;H<-7)5=E/><4KA*@E6.78B17XD78:@M870-JJ5@DO4H;>8=>1@Q6ICS;26?7CG23GCC4KCW5T;:=>AG5B=Q8W@G:O=1;/6A>Y=5>58<>D6SEO2V;BAC<38R===L55?CA=7P6YAO@*3D@6?4,@@:B:*C:;57S97DE1P?V?4=7?C5=9A=>=K74A6:+9T?4:*>*;P>N/2CO?P2YGJM9@81BR;L3AD710HM>25T7@;LBC?(4QA06+B*7:7,@;C635@C96EF2EB+6J<6?X7W;D=39N;4?N2X?E<,8J:2AP;LTAS;B44;H>==E?Y:U;:;C3>BGAE5R:Q9-DL;@04BX;B?3@71SA*9:@M8.64>9?.AX418T?E=<;M<,;R=R;3;MB45@9@@T;66:@>?/4M@57WCV8+=(<13>IB4C8X>N9PB.9W6KBT:8=<79@;CX;B66E;8119M=G7,>A@M8,>56B;@@K??7I>/4Q?8;H:9>(;5>H>W6)<;?(;5>G9.9M;-BN7F8F>EAF;,6>:WW:K?V;G=X7R7L<*BM>D2K=.=98EF)8?7<;9.89?;>C>>4P<*;-5SEH60B17N?=<-:W<<=J>.7:8GAJ9XBP8B;17X:V?*:6B*:29/;,:D=O7-@OAG2DAS:?AV5V;(T;V=7<>H31DC:C?T9->/;K9*87@@?:8H@J/5B-9F@0?=52AK7O>W8N75FV65D<5<<78?=?LB>=;H8+;P@A4JAA>22JC)>J91=(=?9I?K3Y2;O>=7N?C6V@+><75=JAU9A8Y:+>:6N@H63?M9VA999?L9V@J95:N90AN7G=:.6AAQ9Y8><0BF1XCF=F9@S3O@?9A:.;K;R@L3Y=Y;X?2@Y3O;D=>BT=66VY.8:@E6P9?EM8=7G=?AE5C>>78B(>O<::A>8:3>BE;02KBD7;<373G*:<7R<9G67E@A?C=N8A?:?:3A?94/?(=Q9W@B:9?D52<+@4<873@R:6:4>+@0:Q9S9095FG8A?L20C46:=*AR:(:,9>;:@4AS4?:/=)A?3QAE;69(A,8X6IF11LBJ6R>H@M5@W?)8V?07,=S2=Q6+BX=:1KA0>SBG;8;R9):9BIA4@8+?CB:9W7L;2AL6(@A=4:+93>R?T985MB/7+EX6P;E?(4@?8><6=+?R52<:?*;(9HCT53=T8T;Q9N?W9*:A@5?TQ6PCX5R:48;CT6MCE:D=:4=>:8WBJ6XA?9*3,H15>?V9H;C:2?87IA+8P;LB?DCM3R=M8G?U>P<572AW4I?P>T?@7U<>:O7R>;@.6@?<3=BA=QP2JBN45>A=9=J8J.5)AM8/=C@3;L4QCW:::15FAQ<=;3@090B34>7D@8?T8L;O7A?2@6;1;>>053DM18AD@@7D:Q@74@DE00@.>OA,80<,=;>P8R:W=47V>:/>:8-R>F:73/CE948;BN;;2WE2A@Y<03.B<87AQ5B?69+C7:O:E<,;5?F6+@A8:L+0/C9=Y=+9Q=I:Q5)AC9D@8@H2S<3G;M:D;R;F>2==:H38(=5:0BI2+D@7)>U@(6B:M>/,8PB+9>907GD6:YO7<M=P>B4XBB8W=:;,B=1/=);WDU.>CFAD9=3KDF:67HAF>>6Y3PBD7TAN90;??<9Y941GG:/:::>:O@B8,81BO:H;O;;71>K:3>58GCC8T>W6WCW;;3@>A?R10G>5:;2D766;*@L8,>B7=E>9;P;R6.?K;*>*@@2YI12??U;W>54C:P@T@U76=9=752?;=V84:S?B82?K@23GB55I@A:EAA4,?:8UB56,8S?K@L9T9D8YE,7D9T@>47>M71CSAL558W@W;F?M:X=S697-=I=Q?=;/9E@H:M;K;/>R//C176GF7R@Q6(=+=-7V?W<;8M?S:@):X=MBE5:=VBL4@A45+GQ42;J>D=P:P6U:1EY9A:?>A:(;S7V;3=M?4:7>(97?77RA05N>-@W24EH8R6Q;2BW6WAH5/D/:C=H3==:A,;U<<8S9I@X3>=6/A*3=?C?9=T=O3FA>87:Q?J6MC88G:W8*A0=985A<;W6-@1;J9W?+5:?-=8A-;68L?98Q<)8QAR6,>7?/6EA69Q9B>56.AG?-3-@,=V:+?=8-7T?*A94-E+;X5;AX8K:1@?997VBK669GC6?S4+>K=W:B;W;7=V@A4?:@DT6N6MB895>272>);R9==T>69;AV9?42@R7;:40C*HC24<2N?;1UB+@I:R?.2A>7AX;0-0C@;/@Q:W:V?5;U9L?@6A@I;,=O5*=B>:7FC>:H<+8X@;6/=9>U6;FJ56;LAS4H@(75AI8*=>55@9<=?N?-4H=FA>779C@*?Y;R9Q7I:>9XD+5,CI3N?;>R=/:A4@R4SA0>:6LBPF?7B>@5/@EN5,;*@-8T>J?J.OJW::2?B.>)63=S?O:E>U:=->G4AA33(GA4.CI2+E66G:WE:7,7.AS:0=R=,5/BK4(>5A.;T;->N5I>=:I=X86;U?*:G;4>W69EA/ID?CV.4DD528FCQ7BE;V=/<2;5:?BE7(=J9I>Y@8H;-<9;WEM3J;.=A0;2;5<6?982=X8N;ICK9F6B@H=Q77B=6Y?6=T4.?L=S93:Q<4@P6U;*@6?I>::*93@D:4;,=S8?94K,-FDR40;K>E:UD53D=O<2;H8.E(;:2TA@:O;?65C(6E@6=K:T?96.;C?D9P@(8N?:9/80?>9OB1;K?E65;O7IBG54BK5QC66X=3A24I:?K;4814?09F@Y7UB@1.B=9H>L7N;6AF8@>0=A8<>39)<.;1A-K=?G:/?*6?@P8/=9:M9C>;5PB7T5)D740C/E:X@V8,D788R@W?I3*=>@J?V7Y:B;B>64/FW8Q5KBQ28H(*GK5;E;79Q?3=57R>Y?(4(B03;CI<;(9->P:C:4AV6+@D9X9R>B=E:L;*BV2.=S97<,H1=R7TG15+@(6S?99V?.G=0<-;P7B;@7/C*93C82B9LB-?1;J=:7+;?U7SAL95>A6>7:5/V?7CT6F=MDN;<:X3:AI9FCL2O0=-<8<972?P=-=V8-9XF;5.?M8N)-8U9;A7:0B,6L:8<;:-@C5@G:;;E9+6KB*8CDV5Y6F<1C05E?4@X6>?N;/;P=G9<>R8OC7.;>FP8,5>?M9+DL66>U3OE88O@6-=D8*F5;E7.<=;.>2:@B.;/3J=-?D93A@66=/?848A+;+AN*75=09ND(95:X8T=H=T>64A;4C29I6UD<7F?M4P@Q:S=18-C,6R?7:D73<)4B?@?<7(8+B4@C1+CY;,=15=:1@8?WD=.H:2?.6XA);KB@1D=I>H8X=*=2<:3+CC7Q?22+@L19/>H?,:479@022D*;)BR6,A@:3828M@,;SDT0-@M3AP76@76QE65W;L;451@E:4(:XC-6F:5>S7QBL739;9CC(9K>XB<6Y:+?H3TFR=A6L8H>W5-C,5+>8<;A(<.7FB4:37S?F9,;Q@(6>>J<4;+@25C<7CI69CY/T:N?O=7=G;:9;=@<;?G8(?/7E;OC;70.<4;,>>;N75:NCL:*89<*@):O:>:T?I5TCJ6JBT9J;=087BU53?O<;9D0:P>E?H6)>C7L@1;5T2UBM9@@?7X5EH51?BU4)>UB95D>?=9<:;O@N28?)=+@==14?@@)8AC6:Y6I<5=0@1;1;+9Y;?;5?J=X;W30@,<1<,=D>>7>?P:2BD4H:UEN6T>14V:JAS8F7V@7?>:K:7PBP9:@M:0;7;S7C;@>SA(8+=P9U966PD@;.;;>B4P>-BS8/;:<3H6G<+=Y9W>S=L3M?6=GE(7L;32S@->C9O??6H@U>;=B4*BO6I:C>R@?:P7E7>4,E2X67B25S=K<882AX7/@H80?K?17<9>9,F+6N@I:*69S94<:C44P>.?H6II>1::B>597B(7D7;-?:2S>B=2=V=J6.GR,MDC999<>X>(:9?P5W;AB+8V:WBJ1+>/:(@Y;22FB@?TBAF;,8+AG4H?B7T<0AK<5<7;,;T@O4=6R7W?P?8:L51CD7M:4BU7H?,9P/RF66;:9J2=M:D9A68B/>13.<4@+=T21AA9UDG4891<9<78/B@8Q9AA?6T=A:T>W4>@89<;-D55H;;EL-C<)=JAU8R;(@@>W6OC;66C=(:*91=D;E=.6I==AQ;S@K1>A*=9;N63C?;O7Y@+;18D:G;YC(9-?H7*=0=?7H=::P@=:;7G;-BG8L9D>B;O;C9*CT3=B7=*:M>49O<17D>I:M?A7IAU:98/0;N1YFX41DK5;BQ6,?=;C:3=@8(9QA19J;Q=C75C5?@6@;:B7V:WCJ,3HE@>4<>LB-6D<9;IV;T6ICN5HBS46=K@<6G7J>O+=W8;=T8Y>?;+<*>F;K72B-6/ANJ4L@D;U?+?,6;?+2VF?9<8;?S@+9=AP2C>1=0;L??2-EE;,?N4E9PD-9K<4<*8+:NG:1KC656=S;4=R=69;<39EAE>R:K=;5T=R;*M64@87(>L7EC+>+21>R?9<=:99(>7@X:27I=*@I;@;)74DA=F3>::?)=(7/?2<3;W=B:E;4@O8K:6@D:7<:;7>@AS0L?*T;7>@8MCA2+HR7G7D@0<;68=.8OBH3>@(?;=<838,FF7I:I3;W:@4@F=8@;18/?N@G;3<);O8>9*@V9KA>:/8EA)4*CT79=.:B9)C=9J>N;64A=0AA8(@>8GBQ7L>E6D=XBF189NA:7BD922EH4OAR=<8B74@5C+6ME+4L;;9*==?Y/BC8:U9;IQ20?@8M:N:R@98T9IHA1M;I>RA7R7><2>150<6=@6=>-D;42AL<<5BU5.F:(CB1SAG8E:.C+4)CXK9,A@6R:DBC44?V9SBE8<:/>T5JE+50A;4BC?4/F)3V=Y?X63?VAY4H96BKR?748.=7CN7E@C9V=W:Q;S?+84@H7M97AY6NCW5S9SAQ8B8YAQ6V:3=1=)?F;:9>8P@S?K4E78G(SM5@@P;0>N8>@N9(CE/A:P?:?=;=;B:T8?=5G,3Q:-:@=+AN94=0/2D1@X;59>@262>V@B898VD=8:<*5*?6D77T:Q?I877W>Q=K7H?A@)6W7G;K:<><@87PA-8F@L6:>4DN8U0S?)>U<6W?F<,@;:>B>V5;DG:>9Q62CL7J9.A4;1:,9:@@*?R57=M:15)<2EN:::A:IDN6K1EE)94@K6Y7(C5<=;P5);?85@=5@49D;@88?6>);@90A::.;.9L;6?V:1@.39AP<39T:/ER7P;QD57DP4/CQ:*2I>DIM248TBW46C<49BG>=5IFB5A;C=S8D?76V=.AO5N>H1@<;AC)3G9R@>9@9(@E=(?S0DFG5XB>1PAH7+D-7/>H?T6U:K8;=1:9D73)C3<)5PCE5BH;F9;<6@::M5XD/7L:HAM7;9SB-3DE576;==VE15-<2?X=@;5<@=R8>:Q0@F5E;X;M7L@Y:(C863<)6)@71=9;4==8/<@6,@-;*>081B<<):?>B6@=?92?DB(3I;(=7=6;3=I64@R;===:K=5:T6TDBB8U?,?T3)BJ:=9N?J;7>+>-6V7O:U=>?;D8W38K9;>T6MFD5(>Q>U;9=EI77<>:*@:8DD@@4I65?C@C7@==7P@X:O?X34?):UA98E9;=3=L8SC/:3:E:UBM23AD4T@18+B0?RY/7ED70?X9B<:CY3MW>J4,C<7L>B65;3><>;I95T/SK99S2HAX8*;X?872:;B49J;/>X:C86GK3A;J>)5CH;:H4Q>P84=XA,1ADP9K@7.MAWEY7W?R4I=4=D:;;Q;N=T9C:(=>;L92;HAV6A;0@N<6;9;@B<6*=-=S7DA;;39,;?=O71C67<::T:,?M5A@5;BA;4@AN:L4J=G=.B/4U:+<6:E;V=V@:48@3:G05/;DFA81A32H>RU>C9(;R6J?1=M;A7XD@4(D66/?X4M?0;N:J:9>S?A@073>R1L?@:G>V?97A<=;H8?H3.CB9=7>B:6;8;NBI7O=WS65<-?S:E8M8:FX5Y>M4V@1<;;B=:9O>N:178CH72?>>:8;:2;I9O9K:V=Y8P:5BE6U5CC9@;;8(:.=@>;:M?O;I7J>J=D=A:,9?=T8(C1;S8I>Y6@?V6/@P?A4E8PGN10AO3CE-:QH<:A(7/>L5J=A8)?5@C8K9:@0>U92:?=U@:9*7Y>J;Q;*=26W>M>(;GAI,MK7995TAN83;HAN8V:;>O?H;R;O4GB8<=6S89BO9SAY7G;0:(;6@J3H?R=4DH23;6@4>Y5CY8+>C:K>W;5?W7V60EE908B@Q5.?L>F7D6BJF19?@9C?;T?K9?07FT96<)<-4:1;,:W<6<7@?6@=H:79G59IE6AB?1K>HDP3@@S:S;G;*=+9>;8:=;V8(C<;=BI5B>W2@?K;N?D:C>E;L=9?A3A=8I5*9@Q@H<)48?V6;AI;Y8+<:@88MC.7J??:25?C3?I8P5.9C=YDA35=P>);7K8K;Q@F8K?<6?@G<-==.8EF:1<=;2:B@/3KC36*=*8EFY=L5H?V;*9O;><>>O9D<:;7==9O:N@A56;FLM.3>,A1=J-P3L:(@,A.2WBA;98;:+=G9W?659D0AP5<;,?37?:3=VBE1FDU8P68E.89.47D96EAQ7M*8=U?R8F5)DX20H76PA/6U>7>W6Y<7;:>:,>N<3>I8>9V=V@179:0?B9J=)=B89>;91=K>-758CF+B31K@Q8*99@9=D5F;T;4>TC74.?S?83->M@J=)25;+G.:;2-@J;+:1AK=;5GB=:1@6;V:3N=T>H.VBJ6UAL9H@S<:91>U=L93=?=.>I50@R4AK@5T70:8?H?92WD18A<.@O:8<*:YA66Y9T<*B@67<5<7=L=.4,>A@<:M5)?VBF2T@A9C>N;AB0769/;R;H;+>(?G8)?I?-5+S8G9PA(9@8*BA8J4HIN:Q8=592>@4SB5:G8-:W?6AX2EA985C:5;;JNA>90;1;IA,8(BA5QGX4R>J9S?L9/BW6Q;(<=9;@E:>>)8E>J:.>8>36J9SC/9G>97-BX7U5>A(74A@@N4LA20@K?1J?<;N?T;E>B1YB5;K6S:MADA)9)?G79>49WAG7*8A7CAW;F=*949UEP:J6R7Q@PR?>6J?L=4;L7:?H;4>44)C97+5;79*<381<*C*:R7E>N4>F=8B7)AG84CN9K;42FC)7/DK>K2P;FBO;R5:A195>G=;6K;BC95X>X3EC7@D7E8>?V<3=361AA@1879Q>Y76=67?A?64>+?>@H76=Y58DG56;;D86M8A:=BM:5=+=7:E<74O>S@:>87L=??2EBAA/60L;>B29263B)6<==>@-6M;Q7R=:=3<8?@8)@D=*6J7/F9/MAF?=7(DH3T?<9@@-=;6?>Y:L>>;A>L6,;*C8;U5J>LBN4=:ED62?BB2N9XGN>-5T?=4,D:75>1>R<9=38C:2?(<49A;9?V;J8U=.C53E9?92G96T>D:H44@)@;<@5O@,83:+AU>E6S=V9T:K?A9:?0<19:?V;@:QCY1A@M;*:?:=DW4?>;7DC=7P:T9=>WH8CB+7EDA4E=JBL7(@L1PC07+?W:T8R?:=C4,E*::7W>T@Y19B>:F:T?57I9)@97D<,;:=31:X?Y:1AQ8L5KAG>C?C78=*9K=<<)7S=A>J79BH81<4;@:C8=:E5DG;5N9=9@=C8GK81I?+:779;Y:>D><90+EE919X@H3W?7AL:56AFW9Y45BO5Y>R:4=YC92>Y;1?W-RGY9>;;=7<;<+?93W=CA=5O8*CG58B>86@8?N1@@,>;8C?M;M>@8C>A6VBF4B55.@O:S@=17@4?;=69M4(BG8TCA9E5>>3;K;1@W@851<18Y@>4W@A,7VF96S8:L1/BS:Q>E:AE+6U8Q7/@D>K6V?F6P;;8H9VAU63@6>X62@R;6;N4.BS<*>C9I?X9?;O:4<8>M50F)0)D>=K9Q9-8=9JC>6YDE53?:?08L:VBX7F:@7;@0<<8*=C=B>D;V;3>4;<7DCS20<0FT24?+:<8T<5D05ME98X5-<,AB8M?<;76;58.(A724BR>563=-/:6@.9*=E17A0=.;.B<9K;=7/CK9H6K@1>Q:C8J@-7Y>OAK0OCR8C?Q2VF/7,@S6(=:?/966@>S9K>399@3=26;D;90?94@DB4/A-;E7.EL2AB=7.K6E@*84;L?N?25693>J28R;O6IA+<(K<,>H6.@I:Y:E92G/;/7)N9*B3:@77?07A@D:S9W?Q4/>>>B):W;W>Q;;87?-7<>7;5:KER4IA+5C:T49X;S::<>?<6:=8:W;5BG;+;K;4>?8J3HGP8;8/C;2,FI5/=D?8:-==8X=:;X;P<+;V>V;PC(/*@>34C<=C9P8OFW1TDL4K=3<<=F=Y<45FBB8>73A4:6?49<>,@<43:/@89O>A<.9:?>8O9Q@1?<:M;9(@>4H?O;.>2:E:.@*:7=37DCO;/;69)E67M89;W84?4H9MB678A/3OA3T9;5?B19/BE5@;?>7:0=1B30M?)>N7D+5A@0;X6Q4@C94:K7(@>:?AL:584BM55:I;I@X<78P=J;,<,>E9F;X:5;+<4@4=-7;AY8/D85R9N?,3FG08)8.<=(6L7ED744:V9H:X979EB17J>FD92?O4CB=:(4+D76CF/:18G9Q9@E*7.3QBY?+;M8LCK6R=5808Y=H;5=>AG:86:A4<4;?6;.=E=09;;4AJ3K=?;W=>C(51>J4JD6=,<56-96B8>;7(<1>P9D><89>I9XBF/;D28Q=A>49=<2=Q5L@8<-=*9G?U9M?C92:A8-H<2L=B>1;E9=K:9T:D@?46>I7B>M+44=7D2,2<8K=3AF:O87=7EP3)7YT42:1;JCK>;6*>7<>8H5I50EE9:?*7W>5B+0C>,BM=5:A8+-:IC?;+:27FA83;B+7:@/>P?(0X?=>B?*7E=T8A:4<0B=7E=@:2>3=SV?*51?GBQ34CB5LB:5X=A:Y92<*A:;8:V8.=PD84I:M;U9W<17OBV8.9BD>1.E84?=T>9;<9OD93R?R;E9::8:5CW?D;R6,:*I4/*B9;S<6??3*B,9R>0;S>*37CJ9J=)=)9,=(CH:3>B:)99=T8C;39Q@R9A>ADE88AR5L<5AD;I728V@083=L:3C7?6@>*>K8S>*9)>(>M;?=A4E67DK9+;+AY:D8KA36?@+4F=M1@I:.>A0GE58PA0>=4S<7)=K@@?>D<7;@AU6F9X9I>2?;:,87==?NR8;BX8:9L:.09+B>95R=W==?R9;;.8-?V:C??;597=+97==?G3EAR<@64J7R@.55YBD:);DH<.B+6F<:1:VAI=@90<=8*F45.:FCI7@:U>A=K8J4JDK>85+DC?(57;@>09)=<=8>?4)GN39@B7T?O=<89:L8C?E=68V?@;R:G6E5MJ<30=CAC7(AM2G9=C:4PGG9L:J7GBK2=B->58Y>8::<7>0=*7K;3<4=R95=1?L5O;X>X<(8UBO9T9S:)>88R=Q:4@0>W5-3K;=?5BX2Q;(?Y19R?,:6?;5O=N?44@?YN9?9;;HA/6H=/?J8A=046FK=S7P?)8L>07+BP>F4LB=41;3:N=HAI9*===J<348F*/J=WD=67AD7*<,<,;F@S:0:X;=9U?P;292>P@735BU4KA)93==7NAW=@8Y@@7/@881AL4E>)8XBL=<4<>U8M?:>O?-7?9P?;<-8J9B?/;M;S?@3,A3=2B:1U;2AD7R?G6ND):*:.9F>O8O>O<09P7::LEP59@>AD-PBS4=@2A*9R9*A02KBS?F7I9AC34-AW:2>B:G::?9A86*=J91=U9;36W;EI7,(EQ6F;V?)=H:D;V6NA(4-IU609Y;;;L=E8HF.9L=L81=R5X5CHS5=C>4C8BHJ87:38.;.AG?A<969:I>>9-@P;PX<<83:TCH77G?/4CL7M8?=S6G;PC.7HBT4E?P75?KB3:<;->23O=FGK/7>8X=+;<=U<54C@>=H5BGX1J>;8XFN4P=T=Y;.21IE7<=X;>92A2:.9568A>=O@W8A:V=,6@=><:=R8F=89L9+=98Q@S9+;1>C7R>U<38,>)?7<7=I4+FJ6X>+9<@*6U;I=>=S8B?/7.B86*;7B+9/>O5)AW;S8Y7V?XB=2D;BC992L=78Y@H6+:RDF61;K>TA96??6KCL8T5V@69=<9>A5??LC=::>M4;7IE126EV7>AK9+;H83??:9;Y:YB<7E9:BK61;AA951AK4;59D>88;BF;U1TAL8*;;CJ92>F;67P;;@K=12C>(=PB66Q?X6R:-A-:C?E:7-;EWA@3CDQ>S5B8G;6E6;X5:73FO:G99R8T:U71JQ57;4B05F7XES7>5.BT95EW9;7=9E:,A.:K;67,=UBT;E;U6@<3=.BD59C07M9??<99;D:P?T/GDS*>S2DBR95;WBK3:AK6N>B;C8RAB9U>P>S0GB28)@9=O6,?V=A9FG>06@P87A8;;.?*5PBR?U3=;4:F?L;JA*2F@.;P=1>Q8(B:6C8F?-?>809PCC:68(;?BL978R?I=<6:D53+;F8WAR:J=*BY58<9:E>U7(EM3@C16J;.9LA89?4W>@BD7@B6:5;8:37CA9??6<>.<7BO)N>6<:9A9BAG5:>5=86AHF6F:>7XD@+6BA94.?9;I:V<2>,6HDE=)5P?K87?L=U>W/+CD;D8;::>RLX9Q@9=)=6E;4A0<3?37/>N:9;S;KA*:/2CFI<)8?A;8.;7@O4D:=32C@99C77*<8;N:X=A5HCP@B/U<,?DB;8J:K=D@S.*G@6T<3:POG7@=O>H8I495:=?T<>7B>=<=6+DE5F@9>V15?C=*BM8L8WC-25E137?O4ND66,?X>9>>@C8V3-:=A?-2@D.AJ3+AB7D>C5G5,@=16BO<5>98H=DAN98=,5?=;C=7.8/BA68=1D>5F95=N><7:D5;H9);B76C259;;2>A88=AL6W5NC58K>7:<@88>>(;W=Q<2=J6B<8@S38=,@PBA7R5==:;,>9B25.<>?.;@8(<48A?RA29T7O<)AE:4=*0=EG;A>385>K<.;+9J;O;WAY6*@E>-9(7.>C?V?K70:MII4V7N=5DU:@8N?W:O:L77=U6;>X?2A+1Q@O:Y?.=09S=L68@6>F7?>T35C?8/JD.K<-<.7@A6F11J:)<@>Q<47I=9@@5V?S@J9F;A8NB.966KD>7T8D7SD?9R?8=T8P?I2NC27NBX>W5.=C8P5=K>6;J6@EA4,A3:J=D4BA29C<8AA>Y7C>?4?A/=V@N62?@:J88>A:F=4<6AM8.;9>N7Q>/:*=M9WBK6(;A9+E-5H?/94?+CJ+>BG;B=?8P:*C.:@7.@9J:KD47>>C67:8=H;.;,B@8A=<73GU38==>U:C)9/C66R?184=XET+AG+27/5T?X6UDA8:;(?D;.;E:W3:B>8F@Q=:5-:8A@@X4K8-A(>96E=YAY3.BJ;)8JEQ1,?B>D>S:?8?@R74?/89?4<36EBB68C(6P:W@53:6=T=R=Q;I7SN94:3?.=D:T=<7FBF9<84BJ9/84E?8*;2>P5;;CA@958U@A?Y53;X?29H=-B+7Y=J664-/GY<,7B9UCE8L4.GH8C5@@)7*BBA./BEM8+?==T72=(>?;,=D8U=;=;89<29?@C9K>3=C90=8:2=T5-9KA>C0.NBR=J;M>,895;:?R5,B<>0:<80@951@M:?5W?7BG:@65BM7?>8=78F:4;SG>8W7P=S<.55>A9A@<(:O?0;4:D08AC(2BCI4O@8=89,;6:1;4B7

E(:.;=8*;D>F5@W;2;C>9<0>15G8VB(4/GA8V>,9.?351@+>M38=>;AB+8D@42T@H>1;G;=:6==*:Y:W9A>-78@E45AC8D@U42?X8W@D89>N7/?@-:T7T>L89C)83:3;E?+6GBG;J92:/>8<@?=627WC99F88)7NAR8D?+5>?<9(;L>L:A6C@D;0?4=F6;=09PA>9C=J;C:IBE;C7H?8>R7C4UCG7+@N8A>6;/?+:?7-:)@E:8@+8HB@:-:3?U8X9W?F6XA79/:B71GM3Y>,;C?N77?U>D3Y;;B869@W9?>)4JA080AK;M:Y?=R80A66:8J;VDS6KA-7R>S;BA;9,3(EF87>C;D55@AH<<8VL71>2B08;C99H0KFV3EAJB,7-44D?4AA1A562?H5,=H?*9XBF7N=0:L;1><7V@H5MBK<:7;=@>G9K??8858@U;E@3=2:1=R2CAI9T>R8L<<>(>N@2969G8-8B>8@G6W7>@T9+;AA-7P>S6-:0G>2U>.>;L>09,<0:.A24SE/7A-0TG?86;V7=:F>?DM/GE476:NA(6?CB7Y@*5-<==YN51AT41BB;HGA29+?64+:F>3EC54?F=Y:,:198>HA.3/B-=G9JAG3Q71AT4*DA9Q<9:A>1:A<7:->,4/L76T;H<)2WCA9IF;01@17;@R6.;4?=A(5OG8/,A3>:91=26W:1AC?26;?2Q6M@/8XAL5C@B84:WAU6*9/AX8J:1B?7FR>S7R@O7)@7=,3@<(<.B35+CG94A2?(.(@LBC9O:E70:-HJ3==M?4=(6(?X8796BS5X@.8TI:89X>6=S7(>A>:4T=6?,:H=D?58I7Q8VD+57GY5(:5??;BAI5J66:->)=C;M;)AM3HB33H>XD-2:DR4:?K>M=03CAS8PAH:W;K9T:K@M8@;I==@0;,8K6JGH1)?JRA);F9:92B5:C2;56BB?>X>2709L>R=94.;TB89O?GH:G:T?V8E:C:O?18J:PA3?J=E1W>1<*9B5J>.=B>16S6TE*:P:=D>3W9X>2@L4T>99?;0?R<397=-D)9T3ND?2B=<<<=Q:UF2317)@QB@<87X:89*;R@Q?W3)=;=M;>:O=P;L@J6N(7<>2X=N2-GA.LC,:F=J7/LQ-P;WB,9G4W=,?+;DEB32<);NC;9,<9>M57@<5=9YAB07I@?5(AV7?8+EV8*:J6H>K@8;D<*=493<;:BB4M9DA8;9=.9D9C@3K?A967A;H?=:J>(929P=.DF4(C/9S=.2AB873?N*?W:.:JD(9K6B?F8(=8?T;S8?;F<+A(2>A6;,>+@+3<:8>G=B6AJ<814A:F?(>V22IG47<9<2@V9)<.9@63GB=-:-6,?9=K7S:2;=?Q;I=*7L?Q@19U?Y;L=D8C>-;M>194?57<89+?=8M;P:9;F;+;3@.:OA=4-HQ4L<.8IC=-HAU7;U:69NB44A@898=Y=K99=<=4;P@S87>B5M:P;A@;3DF.*>1>+>R3GD93EW1;?X54=N?><;8.?O8>CP7D:9;B;A9@=;A9;,62AM==D:+?U7;:>9HE;4N9;<=B.:V;>:A7N?T?I:+?A6A?;=N8-;(7,@2AB8H;*8+?)@Y?51/?M7+CA9V>U93;,:9B37NE(6I7VBU/2@*>3;M@W82=772?L93?6=V42D@5?A4;B6X:V@5:UAG1Q@N95A27.=H;H??8FAI5:9=437@=?Y?K;A;D38C)8/8I<-D(:5>X2@=I:-A*<@@W8(8GAW;0;54UB=9J=K?R8F;0>J?K6L7)?F4BEE5FDK5BCP7A:F9:;F>G=1;@7)K56?H13HK;46N?P=O746BCS7K;IAC:L;-@/MB,?67609IB.:Y;=;O;8;*=(:0,=F?G:;;=;<<1?09U>W6(>;:X37T@=71;=N;D4SCF7A=F6+CR5N>F;W<;:UBO6*=T?J<78=92D=:P?184@7>?1N:.@.6A>X;,D28,6HD2<-9P;*;4>(:Q5C?:=-=Q>Y6+;5>?:)?T9=H3=1LB<:V?313FJ4L?S;::F:3AY;L:7899J?(=G=@6YB/=/8(?76+>>:A8P@=7IE?5X<4:?>=?08E>Y>/5P>R65DC29B?=*;3;39;BN7D9S@KC?0*>48HA58R;.<29S8,FVG6Y@X9G1H?T;9=1@)<89D>=54=LA3<4@I4PAQ6C<2@L8.;8=(6?D@:L=A7388A+<(;.=/:Y?U6(?19K>(?C6B@8U<1>D5I=??M>57B=;;,:I>0A/6RAM:V86=A:>1/JG:057DK;P6?B:>>F;H:C:3W3(-7@H74?K;W<;A>>W3781=*=/>T8S?Y65AP<7:W9L@M6T8DF85L=,;O;L9?=X8VDP6J@U73:5<):TB/=J8:7MB89C;B6>C<4,@17PA-=S8Q?W:F?I6X<9<(:VAX04F9>.61=49?;NAV5K?W;<94=S?J89;L;4@Y-OL86Q@N7455>DC?:D:A7GAP>66F9>C18L:90BQ60:D:5DC1L?D=S9=A:S=N>97F8=@,?=:(=/>(5I>7:J@L5<7VDB8B;@:?C59*<-8R@-?=6Y<>9X;8B143?E9:75A68*<>DR0OIE2JBA8PBK3I;:?Q:V<3:R>G:5@M42BR8F?5>W0(@080C276<;0?:9;B+8D7=;8?P93:*FU3D9@;0<*:HBD:@C;5D6.7E:7U?G<.;G:3AQ59?N6O>-?J83;J1=S75DF4C=;2XJA4(B;<+71@3<=3N<5G35,<09<>G?S9F;C<,:2>-<@AO5::X<-7DCF:08=?I8OA65?CT:E,56=TB83+CT6*7=BV?(:.6:@R9(?4;6:*;UCJP>16+>0?9QBA91>)@;5T;4?I>4;*=<5??P9C8G>F>(?>43B>6WB@8>=*4W@*>8-7A>Q>P;V<==B=Y,L?P;2:Y@07X>?<07-?B=>758@/>D6->-?+88=?(;9(1<,?6:+@51IC+:@JT0E71EY:C=K+HG,9+9Q>OAL9G9C6HANB88A=9=M49=C?O65@(;N>,7;A(:+M?J=Q9O9ND<3E:T:K=IAA8+9@=08R=VAQ8;8Y=D>8T:Q6FET8U4?<.@7959IAG=O99;0=O4/@;BH7+;(;I@?6@?S6>CU5*?;(71B/7C@I=E8N60>W9SC=64B*7T=R;A=V8?D8/YJA702;DD29F<6>P738PBK>A2/B0=?;U2SD.?;32?E<@>G5-=M<;C49><6:=<;7L?D=M9V8R?0AU6DB-4M;I3)D7=@9ABC80?U2M=VD+27EV58:B>*A8D?*:6;*@L95=S3AD><)8J91AC@Q2Q>9;2:=88H<894;,A=<;<)8@:N9/=J<07?>1>*82A/7P>G@.3;B(=T:DB,5,8YD+3F@D=54JFF48=V;K=A>C:E=<0*J10-D09/=*:5>D:H>S;8<837B9;M;F>,:99.@SC93D868@BB@F=>7Q6</=R;T9=?I77A\".as_bytes();\n\nfn count_primes_in_range(lb: u64, ub: u64, small_primes: &Vec) -> u64 {\n let mut is_prime = vec![true; (ub+1-lb) as usize];\n for p in small_primes {\n if p*p <= ub {\n for j in (((p - lb%p) % p)..(is_prime.len() as u64)).step_by(*p as usize) {\n is_prime[j as usize] = false;\n }\n }\n }\n is_prime.iter().filter(|&is_p| *is_p).count() as u64\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let n: u64 = input.trim().parse().unwrap();\n\n let small_prime_limit = cmp::min(cmp::max(n, 2), 200_000_000) as usize;\n let mut is_prime = vec![true; small_prime_limit/2];\n is_prime[0] = false;\n\n for i in 1..(((small_prime_limit+1) as f64).sqrt() as usize / 2) {\n if is_prime[i] {\n for j in ((3*i+1)..(is_prime.len())).step_by(2*i+1) {\n is_prime[j] = false;\n }\n }\n }\n\n let mut small_primes = vec![2];\n for (idx, is_p) in is_prime.iter().enumerate() {\n if *is_p {\n small_primes.push((2*idx + 1) as u64);\n }\n }\n\n let mut prime_pi: Vec = vec![0, 148_933, 283_146, 412_849];\n for i in 0..24997 {\n prime_pi.push(2*prime_pi[i+3] - prime_pi[i+2] + 1000 - s[2*i] as u64 + 40 - (s[2*i+1] as u64 - 40)*50);\n }\n\n let mut res: u64 = 0;\n for p in &small_primes {\n if p*p*p <= n {\n res += 1;\n } else {\n break;\n }\n }\n\n let mut pi_n_on_p = 0;\n\n let pi_sqrt_n = match small_primes.binary_search(&((n as f64).sqrt().floor() as u64)) {\n Ok(i) => i + 1,\n Err(i) => i,\n };\n\n for i in (0..pi_sqrt_n).rev() {\n if n / small_primes[i] <= small_prime_limit as u64 {\n while pi_n_on_p + 1 < small_primes.len() && small_primes[pi_n_on_p + 1] * small_primes[i] <= n {\n pi_n_on_p += 1;\n }\n res += (pi_n_on_p - i) as u64;\n } else {\n let bucket = n / small_primes[i] / 2_000_000;\n res += prime_pi[bucket as usize] +\n count_primes_in_range(\n bucket * 2_000_000 + 1,\n n / small_primes[i],\n &small_primes\n ) - i as u64 - 1;\n }\n }\n\n println!(\"{}\", res);\n\n //for i in 0..25_000 {\n //println!(\"{}\", count_primes_in_range(i*2_000_000+1, (i+1)*2_000_000, &small_primes));\n //}\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "sortings", "data structures", "two pointers", "number theory"], "code_uid": "7b2b49868b16e622a0992d98eb442ba3", "src_uid": "ffb7762f1d60dc3f16e9b27ea0ecdd7d", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn modpow(base: u64, expo: u64, modulo: u64) -> u64 {\n let mut ans = 1;\n let mut base = base;\n let mut expo = expo;\n while expo > 0 {\n if expo % 2 != 0 {\n ans = (ans * base) % modulo;\n }\n base = (base * base) % modulo;\n expo /= 2;\n }\n ans\n}\n\nfn is_primitive(x: u64, p: u64) -> bool {\n for i in 1..p - 1 {\n if modpow(x, i, p) == 1 {\n return false;\n }\n }\n modpow(x, p - 1, p) == 1\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let p: u64 = scan.token();\n let mut ans = 0;\n for x in 1..p {\n if is_primitive(x, p) {\n ans += 1;\n }\n }\n writeln!(out, \"{}\", ans).ok();\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "b7e8aed6e0c6b52275649b9dc595dd99", "src_uid": "3bed682b6813f1ddb54410218c233cff", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::cmp::Ordering::*;\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\nuse std::collections::{BTreeSet, BTreeMap};\n\n// I have no idea what I'm doing\n\nmacro_rules! answer {\n ($out:ident, $ans:expr) => {\n writeln!($out, \"{}\", $ans)\n };\n}\n\nconst M: i64 = 1_000_000_007;\n\nfn fexp(mut x: i64, mut e: i64) -> i64 {\n let mut ans = 1;\n while e > 0 {\n if e & 1 != 0 {\n ans = (ans * x) % M;\n }\n\n x = (x * x) % M;\n e >>= 1;\n }\n ans\n}\n\nstruct DSU {\n p: Vec,\n s: Vec,\n}\n\nimpl DSU {\n fn new(n: usize) -> Self {\n Self {\n p: (0..n).collect(),\n s: vec![1; n],\n }\n }\n\n fn find(&mut self, i: usize) -> usize {\n if self.p[i] != i {\n self.p[i] = self.find(self.p[i]);\n }\n self.p[i]\n }\n\n fn union(&mut self, mut i: usize, mut j: usize) -> usize {\n i = self.find(i);\n j = self.find(j);\n if i == j { return i; }\n let (i, j) = if self.s[i] < self.s[j] { (i, j) } else { (j, i) };\n self.p[i] = j;\n self.s[j] += self.s[i];\n j\n }\n\n fn classes(&mut self) -> impl Iterator {\n let n = self.p.len();\n (0..n).map(|x| self.find(x)).collect::>().into_iter()\n }\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let p: usize = scan.token();\n let k: i64 = scan.token();\n\n match k {\n 0 => { return answer!(out, fexp(p as i64, p as i64 - 1)); }\n 1 => { return answer!(out, fexp(p as i64, p as i64)); }\n _ => {}\n }\n\n let mut dsu = DSU::new(p);\n\n for x in 1..p {\n let y = k * x as i64 % p as i64;\n dsu.union(x, y as usize);\n }\n\n answer!(out, fexp(p as i64, (dsu.classes().count() - 1) as i64))\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "combinatorics", "dsu", "number theory"], "code_uid": "23494fa7361cb76984f05e8e1df35e0a", "src_uid": "580bf65af24fb7f08250ddbc4ca67e0e", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::cmp::Ordering::*;\nuse std::io::{self, BufWriter, Write};\nuse std::str::{self, SplitAsciiWhitespace};\nuse std::collections::{BTreeSet, BTreeMap};\n\n// I have no idea what I'm doing\n\nmacro_rules! answer {\n ($out:ident, $ans:expr) => {\n writeln!($out, \"{}\", $ans)\n };\n}\n\nconst M: i64 = 1_000_000_007;\n\nfn fexp(mut x: i64, mut e: i64) -> i64 {\n let mut ans = 1;\n while e > 0 {\n if e & 1 != 0 {\n ans = (ans * x) % M;\n }\n\n x = (x * x) % M;\n e >>= 1;\n }\n ans\n}\n\nstruct DSU {\n p: Vec,\n s: Vec,\n}\n\nimpl DSU {\n fn new(n: usize) -> Self {\n Self {\n p: (0..n).collect(),\n s: vec![1; n],\n }\n }\n\n fn find(&mut self, i: usize) -> usize {\n if self.p[i] != i {\n self.p[i] = self.find(self.p[i]);\n }\n self.p[i]\n }\n\n fn union(&mut self, mut i: usize, mut j: usize) -> usize {\n i = self.find(i);\n j = self.find(j);\n if i == j { return i; }\n let (i, j) = if self.s[i] < self.s[j] { (i, j) } else { (j, i) };\n self.p[i] = j;\n self.s[j] += self.s[i];\n j\n }\n\n fn classes(&self) -> impl Iterator {\n self.p.iter().collect::>().into_iter()\n }\n}\n\nfn main() -> Result<(), io::Error> {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = UnsafeScanner::new(stdin.lock());\n let mut out = BufWriter::new(stdout.lock());\n\n let p: usize = scan.token();\n let k: i64 = scan.token();\n\n match k {\n 0 => { return answer!(out, fexp(p as i64, p as i64 - 1)); }\n 1 => { return answer!(out, fexp(p as i64, p as i64)); }\n _ => {}\n }\n\n let mut dsu = DSU::new(p);\n\n for x in 1..p {\n // This makes zero sense to me\n // y is in the range [1, p), so why the fuck is it not sufficient to union(x, x * k mod p) for every x in [1, p)????\n // This is so confusing\n let mut y = x as i64;\n for _ in 1..30 {\n y *= k;\n y %= p as i64;\n dsu.union(x, y as usize);\n }\n }\n\n answer!(out, fexp(p as i64, (dsu.classes().count() - 1) as i64))\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// Copied from https://github.com/EbTech/rust-algorithms/blob/master/src/scanner.rs\n/// Same API as Scanner but nearly twice as fast, using horribly unsafe dark arts\n/// **REQUIRES** Rust 1.34 or higher\npub struct UnsafeScanner {\n reader: R,\n buf_str: Vec,\n buf_iter: SplitAsciiWhitespace<'static>,\n}\n\nimpl UnsafeScanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_ascii_whitespace(),\n }\n }\n\n /// This function should be marked unsafe, but noone has time for that in a\n /// programming contest. Use at your own risk!\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buf_iter.next() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n self.buf_str.clear();\n self.reader\n .read_until(b'\\n', &mut self.buf_str)\n .expect(\"Failed read\");\n self.buf_iter = unsafe {\n let slice = str::from_utf8_unchecked(&self.buf_str);\n std::mem::transmute(slice.split_ascii_whitespace())\n }\n }\n }\n\n pub fn pair(&mut self) -> (T, T) {\n (self.token(), self.token())\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "combinatorics", "dsu", "number theory"], "code_uid": "69c35cbe1d779bc96b3b266e9e230e5f", "src_uid": "580bf65af24fb7f08250ddbc4ca67e0e", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn gcd(mut a: i64, mut b: i64) -> i64 {\n while a != 0 {\n b %= a;\n std::mem::swap(&mut a, &mut b);\n }\n b\n}\n\nfn solve() {\n let s: Vec<_> = parse_line!(String).bytes().collect();\n let k = parse_line!(usize);\n let mut ans = k - k % 2;\n for i in 0..s.len() {\n for j in (i + 2..=s.len() + k).step_by(2) {\n let mut ok = true;\n let n = (j - i) / 2;\n for k in i..i + n {\n if k + n >= s.len() {\n break;\n }\n if s[k] != s[k + n] {\n ok = false;\n break;\n }\n }\n if ok {\n ans = std::cmp::max(ans, j - i);\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "8c168da04e17629d79ec1167f45b7074", "src_uid": "bb65667b65ff069a9c0c9e8fe31da8ab", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Stdin};\nuse std::str::{self, FromStr};\nuse std::error::Error;\nuse std::thread;\n\nfn exec() {\n let mut sc = Scanner::new();\n let s: Vec = sc.ne::().into_bytes();\n let mut ok = true;\n let mut next = b'a';\n for &c in &s {\n if c == next {\n next += 1;\n } else if c > next {\n ok = false;\n }\n }\n println!(\"{}\", if ok { \"YES\" } else { \"NO\" });\n}\n\nfn main() {\n const DEFAULT_STACK: usize = 16 * 1024 * 1024;\n let builder = thread::Builder::new();\n let th = builder.stack_size(DEFAULT_STACK);\n let handle = th.spawn(|| { exec(); }).unwrap();\n let _ = handle.join();\n}\n\n#[allow(dead_code)]\nstruct Scanner {\n stdin: Stdin,\n id: usize,\n buf: Vec,\n}\n\n#[allow(dead_code)]\nimpl Scanner {\n fn new() -> Scanner {\n Scanner {\n stdin: io::stdin(),\n id: 0,\n buf: Vec::new(),\n }\n }\n fn next_line(&mut self) -> Option {\n let mut res = String::new();\n match self.stdin.read_line(&mut res) {\n Ok(0) => return None,\n Ok(_) => Some(res),\n Err(why) => panic!(\"error in read_line: {}\", why.description()),\n }\n }\n fn next(&mut self) -> Option {\n while self.buf.len() == 0 {\n self.buf = match self.next_line() {\n Some(r) => {\n self.id = 0;\n r.trim().as_bytes().to_owned()\n }\n None => return None,\n };\n }\n let l = self.id;\n assert!(self.buf[l] != b' ');\n let n = self.buf.len();\n let mut r = l;\n while r < n && self.buf[r] != b' ' {\n r += 1;\n }\n let res = match str::from_utf8(&self.buf[l..r]).ok().unwrap().parse::() {\n Ok(s) => Some(s),\n Err(_) => panic!(\"parse error\"),\n };\n while r < n && self.buf[r] == b' ' {\n r += 1;\n }\n if r == n {\n self.buf.clear();\n } else {\n self.id = r;\n }\n res\n }\n fn ne(&mut self) -> T {\n self.next::().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings", "implementation"], "code_uid": "357152dada3ff90164455a5a70f005fa", "src_uid": "c4551f66a781b174f95865fa254ca972", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#[allow(dead_code)]\nfn scan() -> T\n{\n\tstatic mut BUFFER: Vec = vec![];\n\tloop {\n\t\tif let Some(token) = unsafe { BUFFER.pop() } {\n\t\t\treturn token.parse().ok().unwrap();\n\t\t}\n\t\tlet mut input = String::new();\n\t\tstd::io::stdin().read_line(&mut input).ok();\n\t\tunsafe { BUFFER = input.split_whitespace().rev().map(String::from).collect(); }\n\t}\n}\n\nstruct Comb {\n\tmodu: i64,\n\tfact: Vec,\n\tifact: Vec,\n}\n\nimpl Comb {\n\tfn mpow(&self, mut x: i64, mut y: i64) -> i64\n\t{\n\t\tlet mut ans = 1;\n\t\twhile y > 0 {\n\t\t\tif y&1 == 1 {\n\t\t\t\tans = ans*x % self.modu;\n\t\t\t}\n\t\t\tx = x*x % self.modu;\n\t\t\ty >>= 1;\n\t\t}\n\t\tans\n\t}\n\n\tfn inv(&self, x: i64) -> i64 { self.mpow(x, self.modu-2) }\n\n\tfn new(modu: i64, size: usize) -> Self\n\t{\n\t\tassert!(size > 1);\n\t\tlet mut tmp = Self { modu, fact: vec![0; size], ifact: vec![0; size] };\n\t\ttmp.fact[0] = 1;\n\t\tfor i in 1..size {\n\t\t\ttmp.fact[i] = tmp.fact[i-1] * i as i64 % modu;\n\t\t}\n\t\ttmp.ifact[size-1] = tmp.inv(tmp.fact[size-1]);\n\t\tfor i in (1..size).rev() {\n\t\t\ttmp.ifact[i-1] = tmp.ifact[i] * i as i64 % modu;\n\t\t}\n\t\ttmp\n\t}\n\n\tfn C(&self, n: i64, r: i64) -> i64\n\t{\n\t\tif 0 <= r && r <= n {\n\t\t\tself.fact[n as usize] * self.ifact[r as usize] % self.modu * self.ifact[(n-r) as usize] % self.modu\n\t\t} else {\n\t\t\t0\n\t\t}\n\t}\n\n}\n\nfn main()\n{\n\tlet n = scan::();\n\tlet modu = scan::();\n\tlet cb = Comb::new(modu, n as usize + 10);\n\n\tlet mut ans = 0i64;\n\tfor a in 0..=n {\n\t\tlet b = n-a;\n let kooft_step = cb.inv(b) * (n-1) % modu;\n let mut kooft = cb.mpow(b, a);\n\t\tlet mut s = 0i64;\n\t\tfor c in 0..=std::cmp::min(a, b) {\n\t\t\ts += cb.C(b-1, c-1) * cb.C(a, c) % modu * kooft % modu;\n kooft = kooft * kooft_step % modu;\n\t\t}\n\t\ts %= modu;\n\t\tans += s * cb.C(n, a) % modu * cb.fact[b as usize] % modu;\n\t}\n\tans %= modu;\n\tprintln!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "math", "dp", "combinatorics", "fft"], "code_uid": "4882953ccf5f88ae00dfb3b175a6d76a", "src_uid": "2d5a5055aaf34f4d300cfdf7c21748c3", "difficulty": 3200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max,min};\n\ntype GenError = Box;\ntype GenResult = Result;\n\nstruct Reader {\n\n}\n\nimpl Reader{\n #[allow(unused)]\n fn read_string() -> GenResult {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string)?;\n Ok(string.trim().to_string())\n }\n\n #[allow(unused)]\n fn read_tokens() -> GenResult> {\n let mut string: String = String::new();\n std::io::stdin().read_line(&mut string)?;\n let mut v = Vec::new();\n for value in string.split_whitespace() {\n v.push(value.to_string());\n }\n Ok(v)\n }\n}\n\nfn main() {\n\n let tokens = Reader::read_tokens().unwrap();\n let n: i32 = tokens[0].parse().unwrap();\n let m: i32 = tokens[1].parse().unwrap();\n let k: i32 = tokens[2].parse().unwrap();\n\n let mut ans = 1000000;\n let mut index = 1;\n for value in Reader::read_tokens().unwrap() {\n let value : i32 = value.parse().unwrap();\n if value > 0 && value <= k {\n if 10 * (index - m).abs() < ans {\n ans = 10 * (index - m).abs();\n }\n }\n index += 1;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "490084c2e5f5cb3a5562aaeebfbdc60f", "src_uid": "57860e9a5342a29257ce506063d37624", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io::*;\nuse std::cmp::*;\n\nfn main() {\n let mut buf = String::new();\n stdin().read_to_string(&mut buf).ok().unwrap();\n let mut cin = buf.split_whitespace().map(|s| s.parse::().ok().unwrap());\n\n let l1 = cin.next().unwrap();\n let r1 = cin.next().unwrap();\n let l2 = cin.next().unwrap();\n let r2 = cin.next().unwrap();\n let k = cin.next().unwrap();\n\n let r = min(r1, r2);\n let l = max(l1, l2);\n\n println!(\"{}\", max(0, r - l + 1 - if l <= k && k <= r { 1 } else { 0 } ));\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "134d3c969008af26507e5836c8af6a1a", "src_uid": "9a74b3b0e9f3a351f2136842e9565a82", "difficulty": 1100, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::*;\n\nconst INF: i64 = 2000000000;\nfn main() {\n let (n, m, k) = {\n let r = getvec::();\n (r[0], r[1], r[2])\n };\n let num = m - n;\n let l_n = k;\n let r_n = n - k + 1;\n let mut lb = 0i64;\n let mut ub = INF;\n while ub - lb > 1i64 {\n let mid = (ub + lb) / 2;\n let r = calc(max(1i64, mid - r_n + 1), mid);\n let l = calc(max(1i64, mid - l_n + 1), mid);\n let res = r + l - mid;\n if res <= num {\n lb = mid;\n } else {\n ub = mid;\n }\n }\n println!(\"{}\", lb + 1);\n}\n\nfn calc(l: i64, r: i64) -> i64 {\n let n = r - l + 1;\n let res = n * (l + r);\n res / 2\n}\n\n#[allow(dead_code)]\nfn next_line() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).unwrap();\n input\n}\n\n#[allow(dead_code)]\nfn getnum() -> T {\n let res = next_line();\n res.trim().parse::().ok().unwrap()\n}\n\n#[allow(dead_code)]\nfn getvec() -> Vec {\n let res = next_line();\n res.split_whitespace().map(|x| x.parse::().ok().unwrap()).collect()\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "binary search"], "code_uid": "d0d8cd036796c664731f030ce4f99863", "src_uid": "da9ddd00f46021e8ee9db4a8deed017c", "difficulty": 1500, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ____ _ _ _ _\n// | _ \\ _ _ ___| |_ ___ _ __ | |_ ___ _ __ ___ _ __ | | __ _| |_ ___\n// | |_) | | | / __| __| / __| '_ \\ | __/ _ \\ '_ ` _ \\| '_ \\| |/ _` | __/ _ \\\n// | _ <| |_| \\__ \\ |_ | (__| |_) | | || __/ | | | | | |_) | | (_| | || __/\n// |_| \\_\\\\__,_|___/\\__| \\___| .__/___\\__\\___|_| |_| |_| .__/|_|\\__,_|\\__\\___|\n// |_| |_____| |_|\n\n// _ _ _ _____ ___\n// _ __ ___ __ _ _ __ | |_ __ _/ / |___ / / _ \\\n// | '_ ` _ \\ / _` | '_ \\| __/ _` | | | |_ \\| | | |\n// | | | | | | (_| | | | | || (_| | | |___) | |_| |\n// |_| |_| |_|\\__,_|_| |_|\\__\\__,_|_|_|____/ \\___/\n\n//https://github.com/manta1130/Competitive_Programming_Template_Rust\n\n#[macro_use]\nmod input {\n\n use std;\n use std::io;\n\n const SPLIT_DELIMITER: char = ' ';\n\n #[macro_export]\n #[allow(unused_macros)]\n macro_rules! input {\n ( $($x:expr ),*) => {\n {\n let temp_str = input_line_str();\n let mut split_result_iter = temp_str.split_whitespace();\n $(\n let buf_split_result = split_result_iter.next();\n let buf_split_result = buf_split_result.unwrap();\n ($x) = buf_split_result.parse().unwrap();\n )*\n }\n };\n }\n\n #[allow(dead_code)]\n pub fn input_line_str() -> String {\n let mut s = String::new();\n io::stdin().read_line(&mut s).unwrap();\n s.trim().to_string()\n }\n\n #[allow(dead_code)]\n pub fn p(t: T)\n where\n T: std::fmt::Display,\n {\n println!(\"{}\", t);\n }\n\n #[allow(dead_code)]\n pub fn input_vector2d(line: usize) -> Vec>\n where\n T: std::str::FromStr,\n {\n let mut v: Vec> = Vec::new();\n\n for _ in 0..line {\n let vec_line = input_vector();\n v.push(vec_line);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector() -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v: Vec = Vec::new();\n\n let s = input_line_str();\n let split_result = s.split(SPLIT_DELIMITER);\n for z in split_result {\n let buf = match z.parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n #[allow(dead_code)]\n pub fn input_vector_row(n: usize) -> Vec\n where\n T: std::str::FromStr,\n {\n let mut v = Vec::with_capacity(n);\n for _ in 0..n {\n let buf = match input_line_str().parse() {\n Ok(r) => r,\n Err(_) => panic!(\"Parse Error\"),\n };\n v.push(buf);\n }\n v\n }\n\n pub trait ToCharVec {\n fn to_charvec(&self) -> Vec;\n }\n\n impl ToCharVec for String {\n fn to_charvec(&self) -> Vec {\n self.to_string().chars().collect::>()\n }\n }\n}\n\n\nuse input::*;\n\nfn main() {\n let (a1, a2, k1, k2, mut n): (isize, isize, isize, isize, isize);\n input!(a1);\n input!(a2);\n input!(k1);\n input!(k2);\n input!(n);\n\n let min = std::cmp::max(0, n - a1 * (k1-1) - a2 * (k2-1));\n let mut max = 0;\n if k2 < k1 {\n max += std::cmp::min(a2, n / k2);\n n -= k2*max;\n max += std::cmp::min(a1, n / k1);\n } else {\n max += std::cmp::min(a1, n / k1);\n n -= k1*max;\n max += std::cmp::min(a2, n / k2);\n }\n println!(\"{} {}\", min, max);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "13d1e11cbf9ef7d0aae4cb47bde10997", "src_uid": "2be8e0b8ad4d3de2930576c0209e8b91", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// Try Codeforces\n// author: Leonardone @ NEETSDKASU\n\nfn main() {\n let mut stdin = String::new();\n std::io::Read::read_to_string(\n &mut std::io::stdin(),\n &mut stdin).unwrap();\n let mut stdin = stdin.split_whitespace();\n let mut get = || stdin.next().unwrap();\n macro_rules! get {\n () => (get().parse::().unwrap());\n ($t:ty) => (get().parse::<$t>().unwrap());\n }\n \n let x = get!();\n let y = get!();\n \n if y == 0 || (y == 1 && x > 0) || x < y - 1 {\n println!(\"No\");\n return;\n }\n \n let d = x - (y - 1);\n \n if d % 2 != 0 {\n println!(\"No\");\n return;\n }\n \n println!(\"Yes\");\n \n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "40134022bbd873b353dc3b65817085e0", "src_uid": "1527171297a0b9c5adf356a549f313b9", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin chmin, chmax ----------\r\npub trait ChangeMinMax {\r\n fn chmin(&mut self, x: Self) -> bool;\r\n fn chmax(&mut self, x: Self) -> bool;\r\n}\r\n\r\nimpl ChangeMinMax for T {\r\n fn chmin(&mut self, x: Self) -> bool {\r\n *self > x && {\r\n *self = x;\r\n true\r\n }\r\n }\r\n fn chmax(&mut self, x: Self) -> bool {\r\n *self < x && {\r\n *self = x;\r\n true\r\n }\r\n }\r\n}\r\n// ---------- end chmin, chmax ----------\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nuse std::collections::*;\r\nuse std::io::Write;\r\n\r\ntype Map = BTreeMap;\r\n\r\n// \u4e0b\u306e\u6841\u304b\u3089dp\u3063\u307d\u304f?\r\n// +\u304c\u3044\u304f\u3064\u3001-\u304c\u3044\u304f\u3064\u3001\u66ab\u5b9acarry\u304c\u3044\u304f\u3064\r\n// \u3053\u306e\u66421\u3092\u5e7e\u3064\u3067\u5408\u308f\u305b\u3089\u308c\u308b\u304b\u7684\u306a\r\n// MLE\r\n// \u306a\u3093\u304b\u72b6\u614b\u591a\u3044\u3063\u307d\u3044\u304c\r\n//\r\n//\r\n\r\nconst INF: i32 = 100000;\r\n\r\nfn run() {\r\n input!(s: bytes);\r\n let m = 300;\r\n let geta = m / 9 + 1;\r\n let mut dp = vec![vec![vec![INF; m + 1]; m + 1]; 2 * geta + 1];\r\n dp[geta] = vec![vec![0; m + 1]; m + 1];\r\n for &s in s.iter().rev() {\r\n let s = (s - b'0') as i32;\r\n let mut next = vec![vec![vec![INF; m + 1]; m + 1]; 2 * geta + 1];\r\n for (carry, dp) in dp.iter().enumerate() {\r\n for (add, dp) in dp.iter().enumerate() {\r\n for (sub, dp) in dp.iter().enumerate() {\r\n if *dp == INF {\r\n continue;\r\n }\r\n let carry = carry as i32 - geta as i32;\r\n let d = add as i32 - sub as i32 + carry;\r\n if d.rem_euclid(10) != s {\r\n continue;\r\n }\r\n let carry = (d.div_euclid(10) + geta as i32) as usize;\r\n next[carry][add][sub].chmin(*dp + (add + sub) as i32);\r\n }\r\n }\r\n }\r\n dp = next;\r\n for dp in dp.iter_mut() {\r\n for i in (0..m).rev() {\r\n for j in (0..m).rev() {\r\n dp[i][j] = dp[i][j].min(dp[i + 1][j]).min(dp[i][j + 1]);\r\n }\r\n }\r\n }\r\n }\r\n let mut ans = INF;\r\n for (carry, dp) in dp.iter().enumerate() {\r\n for (add, dp) in dp.iter().enumerate() {\r\n for (sub, dp) in dp.iter().enumerate() {\r\n let carry = carry as i32 - geta as i32;\r\n let add = add as i32;\r\n let sub = sub as i32;\r\n let mut v = *dp;\r\n if carry == 0 {\r\n } else if carry > 0 && sub >= carry {\r\n v += carry;\r\n } else if carry < 0 && add >= -carry {\r\n v += -carry;\r\n } else {\r\n v += INF;\r\n }\r\n ans.chmin(v);\r\n }\r\n }\r\n }\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "shortest paths"], "code_uid": "afdb8118dafe6f848d15e8914f341b4e", "src_uid": "1961e7c9120ff652b15cad5dd5ca0907", "difficulty": 2900, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::{Write, BufWriter};\n// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n let mut next = || { iter.next().unwrap() };\n input_inner!{next, $($r)*}\n };\n ($($r:tt)*) => {\n let stdin = std::io::stdin();\n let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));\n let mut next = move || -> String{\n bytes\n .by_ref()\n .map(|r|r.unwrap() as char)\n .skip_while(|c|c.is_whitespace())\n .take_while(|c|!c.is_whitespace())\n .collect()\n };\n input_inner!{next, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($next:expr) => {};\n ($next:expr, ) => {};\n\n ($next:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($next, $t);\n input_inner!{$next $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($next:expr, ( $($t:tt),* )) => {\n ( $(read_value!($next, $t)),* )\n };\n\n ($next:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($next, $t)).collect::>()\n };\n\n ($next:expr, chars) => {\n read_value!($next, String).chars().collect::>()\n };\n\n ($next:expr, usize1) => {\n read_value!($next, usize) - 1\n };\n\n ($next:expr, $t:ty) => {\n $next().parse::<$t>().expect(\"Parse error\")\n };\n}\n\nconst LINF: i64 = 1 << 58;\n\nfn solve() {\n let out = std::io::stdout();\n let mut out = BufWriter::new(out.lock());\n macro_rules! puts {\n ($format:expr) => (write!(out,$format).unwrap());\n ($format:expr, $($args:expr),+) => (write!(out,$format,$($args),*).unwrap())\n }\n input!{\n n: usize,\n a: [[i32; n]; n],\n }\n let ni = n as i32;\n let mut pos = vec![0; n * n];\n for i in 0 .. n {\n for j in 0 .. n {\n pos[a[i][j] as usize - 1] = i * n + j;\n }\n }\n let mut kn = vec![vec![LINF >> 32; n * n]; n * n];\n let mut rk = vec![vec![LINF >> 32; n * n]; n * n];\n let mut bs = vec![vec![LINF >> 32; n * n]; n * n];\n for i in 0 .. n {\n for j in 0 .. n {\n for &(dx, dy)\n in &[(-2, -1), (-2, 1), (2, -1), (2, 1),\n (1, 2), (-1, 2), (1, -2), (-1, -2)] {\n let nx = i as i32 + dx;\n let ny = j as i32 + dy;\n if nx < 0 || nx >= ni || ny < 0 || ny >= ni { continue; }\n let v = (nx * ni + ny) as usize;\n kn[i * n + j][v] = 1;\n }\n for dx in -ni .. ni {\n let dy = dx;\n let nx = i as i32 + dx;\n let ny = j as i32 + dy;\n if nx < 0 || nx >= ni || ny < 0 || ny >= ni { continue; }\n let v = (nx * ni + ny) as usize;\n bs[i * n + j][v] = 1;\n }\n for dx in -ni .. ni {\n let dy = -dx;\n let nx = i as i32 + dx;\n let ny = j as i32 + dy;\n if nx < 0 || nx >= ni || ny < 0 || ny >= ni { continue; }\n let v = (nx * ni + ny) as usize;\n bs[i * n + j][v] = 1;\n }\n for u in 0 .. n {\n rk[i * n + j][u * n + j] = 1;\n rk[i * n + j][i * n + u] = 1;\n }\n kn[i * n + j][i * n + j] = 0;\n rk[i * n + j][i * n + j] = 0;\n bs[i * n + j][i * n + j] = 0;\n }\n }\n let mut dist = vec![vec![LINF; 3 * n * n]; 3 * n * n];\n for i in 0 .. n * n {\n for j in 0 .. n * n {\n dist[i][j] = kn[i][j] << 32;\n dist[n * n + i][n * n + j] = rk[i][j] << 32;\n dist[2 * n * n + i][2 * n * n + j] = bs[i][j] << 32;\n }\n for j in 0 .. 3 {\n for k in 0 .. 3 {\n if j != k {\n dist[j * n * n + i][k * n * n + i] = 1 << 32 | 1;\n }\n }\n }\n }\n for k in 0 .. 3 * n * n {\n for i in 0 .. 3 * n * n {\n for j in 0 .. 3 * n * n {\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n }\n }\n }\n // eprintln!(\"dist = {:?}\", dist);\n let mut dp = vec![[LINF; 3]; n * n];\n dp[0] = [0; 3];\n for i in 0 .. n * n - 1 {\n let src = pos[i];\n let dst = pos[i + 1];\n for j in 0 .. 3 {\n for k in 0 .. 3 {\n let cost: i64 = dist[j * n * n + src][k * n * n + dst];\n //eprintln!(\"{} -> {}\", j * n * n + src, k * n * n + dst);\n //eprintln!(\"src = {}, dst = {}, cost = {}\", src, dst, cost);\n dp[i + 1][k] = min(dp[i + 1][k], cost + dp[i][j]);\n }\n }\n //eprintln!(\"dp[{}] = {:?}\", i + 1, dp[i + 1]);\n }\n let mut mi = LINF;\n for i in 0 .. 3 { mi = min(mi, dp[n * n - 1][i]); }\n puts!(\"{} {}\\n\", mi >> 32, mi as i32);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "dp", "shortest paths"], "code_uid": "788955abbc1d193129394d067c020f86", "src_uid": "5fe44b6cd804e0766a0e993eca1846cd", "difficulty": 2200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn f(n: i64, i: i64) -> i64 {\n if i == 0 {\n return 0;\n }\n let bin_n = format!(\"{:b}\", n);\n let bin_len = bin_n.len();\n let len: i64 = 2_i64.pow(bin_len as u32) - 1;\n if i == len / 2 + 1{\n return n / 2 + n % 2;\n }else if i < len / 2 + 1{\n return f(n / 2, i);\n }\n return n / 2 + n % 2 + f(n / 2, i - (len / 2 + 1));\n}\nfn main() {\n let s = std::io::stdin();\n let mut sc = Scanner { stdin: s.lock() };\n let n: i64 = sc.read();\n let l: i64 = sc.read();\n let r: i64 = sc.read();\n let res = f(n, r) - f(n, l - 1);\n println!(\"{}\", res);\n}\n\n//snippet from kenkoooo\npub struct Scanner {\n stdin: R,\n}\n\nimpl Scanner {\n pub fn read(&mut self) -> T {\n use std::io::Read;\n let buf = self.stdin\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b' ' || b == b'\\n' || b == b'\\r')\n .take_while(|&b| b != b' ' && b != b'\\n' && b != b'\\r')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn read_line(&mut self) -> String {\n use std::io::Read;\n let buf = self.stdin\n .by_ref()\n .bytes()\n .map(|b| b.unwrap())\n .skip_while(|&b| b == b'\\n' || b == b'\\r')\n .take_while(|&b| b != b'\\n' && b != b'\\r')\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error.\")\n }\n pub fn vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n\n pub fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "divide and conquer", "constructive algorithms"], "code_uid": "34127c964892d12dfd42369902bb821a", "src_uid": "3ac61b1f8deee7911b1055c243f5eb6a", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn is_leap(y: i64) -> bool {\n y % 400 == 0 || y % 4 == 0 && y % 100 != 0\n}\n\nfn parse_date() -> i64 {\n let s = parse_line!(String);\n let mut it = s.split(':');\n let y: i64 = it.next().unwrap().parse().unwrap();\n let m: i64 = it.next().unwrap().parse().unwrap();\n let d: i64 = it.next().unwrap().parse().unwrap();\n let mut result = d;\n for i in 0..y {\n result += 365;\n if is_leap(i) {\n result += 1;\n }\n }\n let days = [31, 28 + if is_leap(y) {1} else {0}, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n for i in 0..m - 1 {\n result += days[i as usize];\n }\n return result;\n}\n\nfn solve() {\n let from = parse_date();\n let to = parse_date();\n println!(\"{}\", (from - to).abs());\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "6a23206a5d3ada90db4cabaebd38d884", "src_uid": "bdf99d78dc291758fa09ec133fff1e9c", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nmacro_rules! readln {\n () => {{\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n }};\n ( $t:ty ) => {{\n let input = readln!();\n input.parse::<$t>().unwrap()\n }};\n ( $( $t:ty ),+ ) => {{\n let input = readln!();\n let mut input = input.split_whitespace();\n (\n $(\n input.next().unwrap().parse::<$t>().unwrap(),\n )+\n )\n }}\n}\n\nfn main() {\n let (width, height, count) = readln!(i32, i32, i32);\n\n let mut result = 0;\n for i in 0..count {\n let curr_width = width - 4 * i;\n let curr_height = height - 4 * i;\n\n result += 2 * (curr_width + curr_height - 2);\n }\n\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "0e5e9e30acd9a7b1d7802f04bbdc32be", "src_uid": "2c98d59917337cb321d76f72a1b3c057", "difficulty": 800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_variables, dead_code, non_snake_case, unused_macros)]\nuse std::io::{stdin, Read, StdinLock};\nuse std::str::FromStr;\nuse std::fmt::*;\nuse std::str::*;\nuse std::cmp::*;\nuse std::collections::*;\nuse std::iter::FromIterator;\nfn getline() -> String {\n let mut res = String::new();\n std::io::stdin().read_line(&mut res).ok();\n res\n}\nmacro_rules ! readl { ( $ t : ty ) => { { let s = getline ( ) ; s . trim ( ) . parse ::<$ t > ( ) . unwrap ( ) } } ; ( $ ( $ t : ty ) ,+ ) => { { let s = getline ( ) ; let mut iter = s . trim ( ) . split ( ' ' ) ; ( $ ( iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) , ) * ) } } ; }\nmacro_rules ! readlvec { ( $ t : ty ) => { { let s = getline ( ) ; let iter = s . trim ( ) . split ( ' ' ) ; iter . map ( | x | x . parse ( ) . unwrap ( ) ) . collect ::< Vec <$ t >> ( ) } } }\nmacro_rules ! mvec { ( $ v : expr , $ s : expr ) => { vec ! [ $ v ; $ s ] } ; ( $ v : expr , $ s : expr , $ ( $ t : expr ) ,* ) => { vec ! [ mvec ! ( $ v , $ ( $ t ) ,* ) ; $ s ] } ; }\nmacro_rules ! debug { ( $ x : expr ) => { println ! ( \"{}: {:?}\" , stringify ! ( $ x ) , $ x ) } }\nfn printiter<'a, T>(v: &'a T)\nwhere\n &'a T: std::iter::IntoIterator,\n <&'a T as std::iter::IntoIterator>::Item: std::fmt::Display,\n{\n for (i, e) in v.into_iter().enumerate() {\n if i != 0 {\n print!(\" \");\n }\n print!(\"{}\", e);\n }\n println!(\"\");\n}\nstruct ContestPrinter {\n s: String,\n}\nimpl ContestPrinter {\n fn new() -> ContestPrinter {\n ContestPrinter { s: String::new() }\n }\n fn print(&mut self, x: T)\n where\n T: std::fmt::Display,\n {\n self.s.push_str(format!(\"{}\", x).as_str());\n }\n fn println(&mut self, x: T)\n where\n T: std::fmt::Display,\n {\n self.s.push_str(format!(\"{}\\n\", x).as_str());\n }\n}\nimpl std::ops::Drop for ContestPrinter {\n fn drop(&mut self) {\n print!(\"{}\", self.s);\n }\n}\nstatic MOD: i64 = 1e9 as i64 + 7;\nfn is_max_i64(num: i64) -> bool {\n if num == i64::max_value() {\n true\n } else {\n false\n }\n}\n\nfn bfs(graph: &Vec>, start: usize) -> Vec {\n let mut visited: Vec = vec![-1; graph.len()];\n let mut prev: Vec = vec![0; graph.len()];\n prev[start] = usize::max_value();\n let mut q: VecDeque = VecDeque::new();\n visited[start] = 0;\n q.push_back(start);\n while !q.is_empty() {\n let &c_idx = q.front().unwrap();\n let c_cost = visited[c_idx];\n for n_idx in graph[c_idx].iter() {\n let c = visited[*n_idx];\n if c < 0 {\n let n_cost = c_cost + 1;\n visited[*n_idx] = n_cost;\n prev[*n_idx] = c_idx;\n q.push_back(*n_idx);\n }\n }\n q.pop_front();\n }\n prev\n}\n\nfn get_path(prev: Vec, goal: usize) -> Vec {\n let mut path = Vec::new();\n let mut c = goal;\n while c != usize::max_value() {\n path.push(c);\n c = prev[c];\n }\n path\n}\n\nfn main() {\n let mut pr = ContestPrinter::new();\n /*let (N, M, S, T) = readl!(usize, usize, usize, usize);\n let mut g: Vec> = vec![Vec::new(); N];\n for i in 0..M {\n let (a, b) = readl!(usize, usize);\n g[a-1].push(b-1);\n g[b-1].push(a-1);\n }\n\n let path = bfs(&g, S-1);\n let p_nodes = get_path(path, T-1);\n let p_set: HashSet = HashSet::from_iter(p_nodes.iter().cloned());\n let num = p_nodes.len();\n let mut ans = 0;\n for i in 0..N {\n ans += N - num;\n let mut cnt = 0;\n let on = p_set.contains(&i);\n for j in 0..g[i].len() {\n let idx = g[i][j];\n if on & !p_set.contains(&idx) {\n cnt += 1;\n }\n }\n ans -= cnt;\n }\n\n pr.println(ans);*/\n let N = readl!(usize);\n let s = readl!(String);\n\n let mut ans = 0;\n for i in 1..N/2+1 {\n let pr = &s[0..i];\n let co = &s[i..i+i];\n if pr == co { ans = i-1; };\n }\n\n pr.println(N - ans);\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "a7a586022f1dd0251ddfc371bc1487dd", "src_uid": "ed8725e4717c82fa7cfa56178057bca3", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::*;\n#[allow(unused_imports)]\nuse std::collections::*;\nuse std::io::Read;\n#[allow(dead_code)]\nfn getline() -> String {\n let mut ret = String::new();\n std::io::stdin().read_line(&mut ret).ok().unwrap();\n ret\n}\nfn get_word() -> String {\n let mut stdin = std::io::stdin();\n let mut u8b: [u8; 1] = [0];\n loop {\n let mut buf: Vec = Vec::with_capacity(16);\n loop {\n let res = stdin.read(&mut u8b);\n if res.unwrap_or(0) == 0 || u8b[0] <= b' ' {\n break;\n } else {\n buf.push(u8b[0]);\n }\n }\n if buf.len() >= 1 {\n let ret = String::from_utf8(buf).unwrap();\n return ret;\n }\n }\n}\n\n#[allow(dead_code)]\nfn get() -> T { get_word().parse().ok().unwrap() }\n\nfn solve() {\n let n: usize = get();\n let k = get();\n let m: i64 = get();\n let mut t: Vec = (0 .. k).map(|_| get()).collect();\n t.sort();\n let tsum: i64 = t.iter().sum();\n let mut ma = 0;\n for comp in 0 .. n + 1 {\n let rem = m - comp as i64 * tsum;\n if rem < 0 {\n break;\n }\n let mut remtask = Vec::new();\n for _ in 0 .. n - comp {\n remtask.append(&mut t.clone());\n }\n remtask.sort();\n let mut tot = 0;\n let mut pos = 0;\n while pos < remtask.len() {\n tot += remtask[pos];\n if tot > rem {\n break;\n }\n pos += 1;\n }\n ma = max(ma, comp * (t.len() + 1) + pos);\n }\n println!(\"{}\", ma);\n}\n\nfn main() {\n // In order to avoid potential stack overflow, spawn a new thread.\n let stack_size = 104_857_600; // 100 MB\n let thd = std::thread::Builder::new().stack_size(stack_size);\n thd.spawn(|| solve()).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "b97fc0c3086b068970f0bd0ea0ccd2cd", "src_uid": "d659e92a410c1bc836be64fc1c0db160", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// ---------- begin chmin, chmax ----------\r\npub trait ChangeMinMax {\r\n fn chmin(&mut self, x: Self) -> bool;\r\n fn chmax(&mut self, x: Self) -> bool;\r\n}\r\n\r\nimpl ChangeMinMax for T {\r\n fn chmin(&mut self, x: Self) -> bool {\r\n *self > x && {\r\n *self = x;\r\n true\r\n }\r\n }\r\n fn chmax(&mut self, x: Self) -> bool {\r\n *self < x && {\r\n *self = x;\r\n true\r\n }\r\n }\r\n}\r\n// ---------- end chmin, chmax ----------\r\n// ---------- begin input macro ----------\r\n// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8\r\nmacro_rules! input {\r\n (source = $s:expr, $($r:tt)*) => {\r\n let mut iter = $s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n ($($r:tt)*) => {\r\n let s = {\r\n use std::io::Read;\r\n let mut s = String::new();\r\n std::io::stdin().read_to_string(&mut s).unwrap();\r\n s\r\n };\r\n let mut iter = s.split_whitespace();\r\n input_inner!{iter, $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! input_inner {\r\n ($iter:expr) => {};\r\n ($iter:expr, ) => {};\r\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\r\n let $var = read_value!($iter, $t);\r\n input_inner!{$iter $($r)*}\r\n };\r\n}\r\n\r\nmacro_rules! read_value {\r\n ($iter:expr, ( $($t:tt),* )) => {\r\n ( $(read_value!($iter, $t)),* )\r\n };\r\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\r\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\r\n };\r\n ($iter:expr, chars) => {\r\n read_value!($iter, String).chars().collect::>()\r\n };\r\n ($iter:expr, bytes) => {\r\n read_value!($iter, String).bytes().collect::>()\r\n };\r\n ($iter:expr, usize1) => {\r\n read_value!($iter, usize) - 1\r\n };\r\n ($iter:expr, $t:ty) => {\r\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\r\n };\r\n}\r\n// ---------- end input macro ----------\r\n\r\nuse std::collections::*;\r\n\r\ntype Map = BTreeMap;\r\ntype Set = BTreeSet;\r\ntype Deque = VecDeque;\r\n\r\n// \u30a2\u30ea\u30b9\u3068\u30dc\u30d6\u304c\u30b2\u30fc\u30e0\u3092\u3059\u308b\r\n// \u30a2\u30ea\u30b9\u306fN\u500b\u306e\u5b9d\u3092\u6301\u3063\u3066\u3044\u308b\u3002\r\n// i\u500b\u76ee\u306e\u5b9d\u306b\u306f A_i \u679a\u306e\u30b3\u30a4\u30f3\u304c\u5165\u3063\u3066\u3044\u308b\r\n// \u307e\u305fM\u500b\u306e\u9375\u304c\u3042\u308b\r\n// j\u500b\u76ee\u306e\u9375\u306e\u5024\u6bb5\u306f\u30b3\u30a4\u30f3B_j\u679a\u3067\u3042\u308b\r\n//\r\n// \u6700\u521d\u3001\u30a2\u30ea\u30b9\u306f\u5b9d\u306e\u3044\u304f\u3064\u304b\u306b\u9320\u3092\u3064\u3051\u308b\r\n// j\u756a\u76ee\u306e\u9320\u306fj\u756a\u76ee\u306e\u9375\u3067\u306e\u307f\u958b\u304f\u3053\u3068\u304c\u3067\u304d\u308b\r\n// i\u756a\u76ee\u306e\u5b9d\u306bj\u756a\u76ee\u306e\u9320\u3092\u3064\u3051\u308b\u306e\u306b\u304b\u304b\u308b\u30b3\u30b9\u30c8\u306f C_{i, j} \u3067\u3042\u308b\r\n//\r\n// \u9320\u3092\u3064\u3051\u7d42\u308f\u3063\u305f\u5f8c\u3001\u30dc\u30d6\u306f\u3044\u304f\u3064\u304b\u9375\u3092\u30a2\u30ea\u30b9\u304b\u3089\u8cb7\u3063\u3066\u5b9d\u3092\u958b\u3051\u308b\r\n// (\u5b9d\u304b\u3089\u624b\u306b\u5165\u3063\u305f\u30b3\u30a4\u30f3) - (\u9375\u3092\u8cb7\u3046\u306e\u306b\u4f7f\u3063\u305f\u30b3\u30a4\u30f3) > 0\r\n// \u3092\u6e80\u305f\u3059\u6642\u3001\u30dc\u30d6\u306e\u52dd\u3061\u3068\u306a\u308b\r\n//\r\n// \u30a2\u30ea\u30b9\u306f\u30dc\u30d6\u304c\u52dd\u3066\u306a\u3044\u3088\u3046\u306b\u9320\u3092\u3064\u3051\u308b\u6642\u3001\u6700\u5c0f\u30b3\u30b9\u30c8\u3092\u6c42\u3081\u3088\r\n// \u4e0d\u53ef\u80fd\u306a\u3089-1\u3092\u51fa\u529b\u305b\u3088\r\n//\r\n// 1 <= N, M <= 6\r\n// 1 <= A_i, B_j <= 4\r\n// 1 <= C_{i, j} <= 10^7\r\n//\r\n//\r\n// \u30e1\u30e2\r\n// sum b < sum a \u306a\u3089-1\r\n// \u305d\u3046\u3067\u306a\u3044\u306a\u3089\u9320\u3092\u5168\u90e8\u3064\u3051\u308c\u3070\u3068\u308a\u3042\u3048\u305a\u306f\u52dd\u3066\u308b\r\n// \u611a\u76f4\u89e3\u3063\u3066\u306a\u3093\u3060\uff1f\r\n// \u9320\u3092\u5168\u63a2\u7d22\r\n// \u305d\u306e\u5f8c\u9375\u306e\u8cb7\u3044\u65b9\u3092\u5168\u63a2\u7d22\r\n// \u30b3\u30b9\u30c8\u3092\u8a08\u7b97\u3057\u3066\u5229\u5f97\u306e\u6700\u5927\u5024\u3092\u8a08\u7b97\u3001\u7b54\u3048\u306e\u66f4\u65b0\r\n// \u3053\u308c\u3067\u3044\u3044\r\n// \u8a08\u7b97\u91cf O(2^(NM) * 2^(M) * N) \u304f\u3089\u3044\uff1f\r\n// \u5f53\u7136\u9593\u306b\u5408\u308f\u3093\r\n// \u9375\u306f\u5168\u63a2\u7d22\u305b\u305a\u3068\u3082\u30d5\u30ed\u30fc\u3067\u89e3\u3051\u308b\r\n// \u9375\u3001\u5b9d\u3067\u305d\u308c\u305e\u308c\u9802\u70b9\u3092\u4f5c\u308b\r\n// src -> \u9375i \u306bb_i\r\n// \u9375j -> \u5b9di \u306b\u9320\u304c\u3064\u3044\u3066\u308b\u306a\u3089inf\r\n// \u5b9di -> dst \u306ba_i\r\n// \u3092\u5f35\u3063\u3066\u30d5\u30ed\u30fc\u3092\u6d41\u3059\r\n// sum a_i > (\u6d41\u91cf)\r\n// \u306a\u3089\u30dc\u30d6\u306e\u52dd\u3061\r\n// \u3053\u308c\u3067\u3082\u307e\u3060\u9593\u306b\u5408\u308f\u306a\u3044\r\n// \r\n// \u30dc\u30d6\u306f\u9375\u3092\u8cb7\u308f\u306a\u3044\u3053\u3068\u3067\u5e38\u306b0\u3092\u9054\u6210\u3067\u304d\u308b\r\n// \u30a2\u30ea\u30b9\u306f\u30dc\u30d6\u306e\u6700\u9069\u6226\u7565\u304c\u3053\u308c\u306b\u306a\u308b\u3088\u3046\u306b\u3057\u305f\u3044\r\n// \u3064\u307e\u308a\u30ab\u30c3\u30c8\u304c\u5e38\u306b\u5b9d->dst \u306e\u3068\u3053\u308d\u306b\u306a\u308b\u3088\u3046\u306b\u3057\u305f\u3044\r\n// N, M, A, B \u304c\u5c0f\u3055\u3044\u306e\u3067\u3053\u308c\u3092\u305d\u306e\u307e\u307edp\u306b\u3059\u308b\r\n// \u5b9d\u306b\u3064\u3044\u3066\u30eb\u30fc\u30d7\u3092\u56de\u3057\u3064\u3064\u8fba\u3092\u5f35\u3063\u3066\u6d41\u91cf\u3092\u5168\u90e8\u8a66\u3059\r\n// \u8fba\u3092\u6e80\u305f\u3057\u305f\u3089\u6b21\u3078\r\n// \u307f\u305f\u3044\u306a\r\n\r\nfn run() {\r\n input! {\r\n n: usize,\r\n m: usize,\r\n a: [i32; n],\r\n b: [i32; m],\r\n c: [[i32; m]; n],\r\n }\r\n let mut memo = Map::new();\r\n memo.insert(b, 0);\r\n for (a, c) in a.into_iter().zip(c) {\r\n let mut dp = Map::new();\r\n for (b, v) in memo.into_iter() {\r\n dp.insert((a, b), v);\r\n }\r\n for (i, c) in c.into_iter().enumerate() {\r\n let mut next = dp.clone();\r\n for ((a, b), v) in dp {\r\n let v = v + c;\r\n for k in 1..=b[i].min(a) {\r\n let mut b = b.clone();\r\n b[i] -= k;\r\n let a = a - k;\r\n next.entry((a, b)).or_insert(v).chmin(v);\r\n }\r\n }\r\n dp = next;\r\n }\r\n memo = Map::new();\r\n for ((a, b), v) in dp {\r\n if a == 0 {\r\n memo.entry(b).or_insert(v).chmin(v);\r\n }\r\n }\r\n }\r\n let ans = memo.values().min().cloned().unwrap_or(-1);\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "flows", "dp", "bitmasks"], "code_uid": "9018a0ed053eaf758ac80d4ff9ab488b", "src_uid": "4dc5dc78bda59c1ec6dd8acd6f1d7333", "difficulty": 3200, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn gcd(a: u64, b: u64) -> u64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn run() {\n input! {\n n: usize,\n p: [usize1; n],\n }\n let mut q = p.clone();\n q.sort();\n q.dedup();\n if q.len() < n {\n println!(\"-1\");\n return;\n }\n let mut a = vec![];\n let mut used = vec![false; n];\n for i in 0..n {\n if used[i] {\n continue;\n }\n used[i] = true;\n let mut k = p[i];\n let mut c = 1;\n while k != i {\n used[k] = true;\n c += 1;\n k = p[k];\n }\n if c % 2 == 0 {\n a.push(c / 2);\n } else {\n a.push(c);\n }\n }\n a.sort();\n let ans = a.iter().fold(1, |s, a| s / gcd(s, *a) * *a);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math"], "code_uid": "6f666f7214dc3c23d41002567b0949f2", "src_uid": "149221131a978298ac56b58438df46c9", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn can(m: usize, a: &[usize], p: &[(usize, usize)]) -> bool {\n let mut last = m;\n let mut free = 0;\n let mut rem = vec![];\n rem.extend_from_slice(a);\n for &(d, t) in p.iter().rev() {\n if d > m {\n continue;\n }\n if last > d {\n free += last - d;\n last = d;\n }\n while rem[t] > 0 && last > 0 {\n rem[t] -= 1;\n last -= 1;\n }\n }\n free += last;\n 2 * rem.into_iter().fold(0, |s, a| s + a) <= free\n}\n\nfn run() {\n input! {\n n: usize,\n m: usize,\n a: [usize; n],\n p: [(usize, usize1); m],\n }\n let mut p = p;\n p.sort_by_key(|p| p.0);\n let mut ng = 0;\n let mut ok = 400_000;\n while ok - ng > 1 {\n let m = (ok + ng) / 2;\n if can(m, &a, &p) {\n ok = m;\n } else {\n ng = m;\n }\n }\n println!(\"{}\", ok);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "binary search"], "code_uid": "80c1301f4634868da050546da610b5e0", "src_uid": "2eb101dcfcc487fe6e44c9b4c0e4024d", "difficulty": 2000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nfn solve() {\n let (al, ar) = parse_line!(i32, i32);\n let (bl, br) = parse_line!(i32, i32);\n let mut ok = false;\n ok |= br >= al - 1 && br <= (al + 1) * 2;\n ok |= bl >= ar - 1 && bl <= (ar + 1) * 2;\n println!(\"{}\", if ok {\"YES\"} else {\"NO\"})\n}\n\nfn main() {\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve();\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "2f6ee04a152a52a1464258653271657b", "src_uid": "36b7478e162be6e985613b2dad0974dd", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//spnauti-rusT\nuse std::io::*;\nuse std::str::*;\nuse std::fmt::Debug;\n#[allow(unused_imports)] use std::cmp::Ordering::{self,*};\n#[allow(unused_imports)] use std::ops::*;\n#[allow(unused_imports)] use std::iter::*;\n#[allow(unused_imports)] use std::collections::*;\n#[allow(unused_macros)]\nmacro_rules! m {\n ($c:tt, $x:expr, $y:expr) => {{\n let b = $y; let a = &mut $x;\n if b $c *a { *a = b; true } else { false }\n }};\n}\n#[allow(unused_macros)]\nmacro_rules! l {\n ($i:ident . $e:tt : $t:ty; $($a:ident),*) => {\n $( let $a: $t = $i.$e(); )*\n };\n ($i:ident . $e:tt; $($a:ident),*) => {\n $( let $a = $i.$e(); )*\n };\n}\nstruct WordReader<'a> { it : SplitAsciiWhitespace<'a> }\n#[allow(dead_code)]\nimpl<'a> WordReader<'a> {\n fn new(b: &mut String, mut r: T) -> WordReader {\n b.clear();\n r.read_to_string(b).ok();\n WordReader { it: b.split_ascii_whitespace() }\n }\n fn from_stdin(b: &mut String) -> WordReader {\n WordReader::new(b, stdin())\n }\n fn sl(&mut self) -> &str { self.it.next().unwrap() }\n fn bs(&mut self) -> &[u8] { self.sl().as_bytes() }\n fn s(&mut self) -> String { String::from(self.sl()) }\n fn i(&mut self) -> i32 { self.p() }\n fn f(&mut self) -> f64 { self.p() }\n fn u(&mut self) -> usize { self.p() }\n fn sk(&mut self, n: usize) { self.it.nth(n - 1); }\n fn ii(&mut self, n: usize) -> impl Iterator {\n self.ip(n).into_iter()\n }\n fn vi(&mut self, n: usize) -> Vec {\n self.vp::(n)\n }\n fn p(&mut self) -> T where T::Err: Debug {\n self.sl().parse::().unwrap()\n }\n fn ip(&mut self, n: usize) -> impl Iterator where T::Err: Debug {\n self.vp(n).into_iter()\n }\n fn vp(&mut self, n: usize) -> Vec where T::Err: Debug {\n (0..n).map(|_| self.p()).collect()\n }\n}\n//------------------- End rusT\n\nfn main() {\n let mut bin = String::new();\n let mut input = WordReader::from_stdin(&mut bin);\n\n let n = input.u();\n let a = input.i();\n let a = a - 1;\n let mut d = vec![Vec::new(); n];\n for (i,t) in input.ii(n).enumerate() {\n let i = i as i32;\n d[(i-a).abs() as usize].push(t);\n }\n let sol: i32 = d.into_iter().map(|a| {\n let l = a.len() as i32;\n let s = a.into_iter().sum();\n if s == l { s } else { 0 }\n }).sum();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "835c845d2e2ea054d8fd92ded54f5164", "src_uid": "4840d571d4ce6e1096bb678b6c100ae5", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut text = String::new();\n std::io::stdin().read_line(&mut text).unwrap();\n let val: u64 = text.trim().parse().unwrap();\n let mut i = 1;\n let value = loop {\n if summation(i) >= val {\n break i;\n }\n i += 1;\n };\n println!(\"{}\", val - summation(value - 1))\n}\nfn summation(i: u64) -> u64 {\n (i * (i + 1)) / 2\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "066a8b95164cfe69e657326adec5f1f8", "src_uid": "1db5631847085815461c617854b08ee5", "difficulty": 1000, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\nuse std::collections::HashSet;\n\nfn parse_problem(mut input: B) -> io::Result> {\n let mut buffer = String::new();\n input.read_line(&mut buffer)?;\n buffer.truncate(buffer.trim_end().len());\n let mut positions = Vec::new();\n let mut curr = (0, 0);\n for c in buffer.chars() {\n let next = match c {\n 'L' => Ok((curr.0 - 1, curr.1)),\n 'U' => Ok((curr.0, curr.1 + 1)),\n 'R' => Ok((curr.0 + 1, curr.1)),\n 'D' => Ok((curr.0, curr.1 - 1)),\n _ => Err(io::Error::new(io::ErrorKind::InvalidInput, \"bad input\")),\n }?;\n positions.push(curr);\n curr = next;\n }\n positions.push(curr);\n Ok(positions)\n}\n\nfn main() -> io::Result<()> {\n let positions = parse_problem(io::stdin().lock())?;\n let mut seen_positions = HashSet::new();\n let mut last_position = (0, 0);\n for pos in positions.iter().skip(1) {\n if !seen_positions.insert(*pos) {\n println!(\"BUG\");\n return Ok(())\n }\n seen_positions.insert((last_position.0 + 1, last_position.1));\n seen_positions.insert((last_position.0 - 1, last_position.1));\n seen_positions.insert((last_position.0, last_position.1 + 1));\n seen_positions.insert((last_position.0, last_position.1 - 1));\n last_position = *pos;\n }\n println!(\"OK\");\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "graphs"], "code_uid": "c4993f6e8e1454de2279233e26f8fb92", "src_uid": "bb7805cc9d1cc907b64371b209c564b3", "difficulty": 1400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! parse_line {\n ($t: ty) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let a_str = a_str.trim();\n a_str.parse::<$t>().expect(\"parse error\")\n });\n ($($t: ty),+) => ({\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n let mut a_iter = a_str.split_whitespace();\n (\n $(\n a_iter.next().unwrap().parse::<$t>().expect(\"parse error\"),\n )+\n )\n })\n}\n\n#[allow(unused_macros)]\nmacro_rules! parse_line_to_vec {\n ($t: ty) => {{\n let mut a_str = String::new();\n std::io::stdin().read_line(&mut a_str).expect(\"read error\");\n (a_str\n .split_whitespace()\n .map(|x| x.parse::<$t>().unwrap())\n .collect::>())\n }};\n}\n\nuse std::io::Write;\n\nfn solve(writer: &mut std::io::BufWriter) {\n let ss: Vec = parse_line!(String).bytes().collect();\n let b = ss.iter().filter(|c| **c == b'B').count() as u64;\n let s = ss.iter().filter(|c| **c == b'S').count() as u64;\n let c = ss.iter().filter(|c| **c == b'C').count() as u64;\n let (nb, ns, nc) = parse_line!(u64, u64, u64);\n let (pb, ps, pc) = parse_line!(u64, u64, u64);\n let r = parse_line!(u64);\n let mut l = 0;\n let mut u = 10000000000000;\n while u - l > 1 {\n let m = (l + u) / 2;\n let need =\n if b * m <= nb {0} else {pb * (b * m - nb)} +\n if s * m <= ns {0} else {ps * (s * m - ns)} +\n if c * m <= nc {0} else {pc * (c * m - nc)};\n if need <= r {\n l = m;\n }else{\n u = m;\n }\n }\n writeln!(writer, \"{}\", l).unwrap();\n}\n\nfn main() {\n let mut writer = std::io::BufWriter::new(std::io::stdout());\n let tests = 1; // parse_line!(usize);\n for _ in 0..tests {\n solve(&mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "binary search"], "code_uid": "4db68d85e2197aab4224fd79073e2efa", "src_uid": "8126a4232188ae7de8e5a7aedea1a97e", "difficulty": 1600, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, bytes) => {\n read_value!($iter, String).bytes().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n//\n\nfn run() {\n input! {\n n: usize,\n q: usize,\n op: [(bytes, bytes); q],\n }\n let mut p = vec![];\n for (a, b) in op {\n let a = (a[1] - b'a') as usize * 6 + (a[0] - b'a') as usize;\n let b = (b[0] - b'a') as usize;\n p.push((a, b));\n }\n let mut ok = vec![false; 6];\n ok[0] = true;\n for _ in 2..=n {\n let mut next = vec![false; ok.len() * 6];\n for (i, _) in ok.iter().enumerate().filter(|p| *p.1) {\n for &(a, b) in p.iter() {\n if i % 6 == b {\n next[(i / 6) * 36 + a] = true;\n }\n }\n }\n ok = next;\n }\n let ans = ok.into_iter().filter(|p| *p).count();\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "strings", "dp", "brute force"], "code_uid": "4421289456cf83dbd64507a1cdcdf177", "src_uid": "c42abec29bfd17de3f43385fa6bea534", "difficulty": 1300, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\n\nfn calcu_size(ix: i32, iy: i32, n: i32, second: i32) -> i64 {\n let mut total = 0i64;\n // middle\n let lefty: i32 = cmp::max(iy - second, 1);\n let righty: i32 = cmp::min(iy + second, n);\n\n total += (righty - lefty) as i64 + 1;\n\n // upper\n for i in 0..cmp::min(second, ix - 1) {\n let _row = ix - i - 1;\n let lefty = cmp::max(iy - second + i + 1, 1);\n let righty = cmp::min(iy + second - i - 1, n);\n total += (righty - lefty) as i64 + 1;\n }\n\n // lower\n for i in 0..cmp::min(second, n - ix) {\n let _row = ix + i + 1;\n let lefty = cmp::max(iy - second + i + 1, 1);\n let righty = cmp::min(iy + second - i - 1, n);\n total += (righty - lefty) as i64 + 1;\n }\n\n return total;\n}\n\nfn main() {\n let mut input_str = String::new();\n std::io::stdin().read_line(&mut input_str).expect(\"read error\");\n let mut iter = input_str.split_whitespace();\n let n: i32 = iter.next().unwrap().parse().unwrap();\n let x: i32 = iter.next().unwrap().parse().unwrap();\n let y: i32 = iter.next().unwrap().parse().unwrap();\n let c: i32 = iter.next().unwrap().parse().unwrap();\n\n let mut left = -1;\n let mut right = 2 * (((2.0 * (c as f64)).sqrt() as i32) + 1);\n while left != right - 1 {\n let mid = (left + right) >> 1;\n if calcu_size(x, y, n, mid) < c as i64 {\n left = mid;\n } else {\n right = mid;\n }\n }\n println!(\"{}\", right);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation", "binary search"], "code_uid": "793df68999485198705c07e529ec6147", "src_uid": "232c5206ee7c1903556c3625e0b0efc6", "difficulty": 1800, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\nconst MOD: u32 = 1_000_000_007;\n\n#[derive(Clone, Copy)]\nstruct ModInt(u32);\n\nimpl std::ops::Add for ModInt {\n type Output = ModInt;\n fn add(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl std::ops::Sub for ModInt {\n type Output = ModInt;\n fn sub(self, rhs: ModInt) -> Self::Output {\n let mut d = self.0 + MOD - rhs.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n}\n\nimpl std::ops::SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl std::ops::Mul for ModInt {\n type Output = ModInt;\n fn mul(self, rhs: ModInt) -> Self::Output {\n ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)\n }\n}\n\nimpl std::ops::MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl std::ops::Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> Self::Output {\n ModInt(if self.0 == 0 {0} else {MOD - self.0})\n }\n}\n\nimpl std::fmt::Display for ModInt {\n fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nimpl std::str::FromStr for ModInt {\n type Err = std::num::ParseIntError;\n fn from_str(s: &str) -> Result {\n let val = s.parse::()?;\n Ok(ModInt::new(val))\n }\n}\n\nimpl From for ModInt {\n fn from(val: usize) -> ModInt {\n ModInt((val % MOD as usize) as u32)\n }\n}\n\n#[allow(dead_code)]\nimpl ModInt {\n pub fn new(n: u32) -> ModInt {\n ModInt(n % MOD)\n }\n pub fn zero() -> ModInt {\n ModInt(0)\n }\n pub fn one() -> ModInt {\n ModInt(1)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::one();\n let mut s = self;\n while n > 0 {\n if n & 1 == 1 {\n t *= s;\n }\n s *= s;\n n >>= 1;\n }\n t\n }\n pub fn inv(self) -> ModInt {\n assert!(self.0 > 0);\n self.pow(MOD - 2)\n }\n}\n// ---------- end ModInt ----------\n// ---------- begin Precalc ----------\n#[allow(dead_code)]\nstruct Precalc {\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n}\n\n#[allow(dead_code)]\nimpl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt::one(); n + 1];\n let mut fact = vec![ModInt::one(); n + 1];\n let mut ifact = vec![ModInt::one(); n + 1];\n for i in 2..(n + 1) {\n inv[i] = -inv[MOD as usize % i] * ModInt(MOD / i as u32);\n fact[i] = fact[i - 1] * ModInt(i as u32);\n ifact[i] = ifact[i - 1] * inv[i];\n }\n Precalc {\n inv: inv,\n fact: fact,\n ifact: ifact,\n }\n }\n pub fn inv(&self, n: usize) -> ModInt {\n self.inv[n]\n }\n pub fn fact(&self, n: usize) -> ModInt {\n self.fact[n]\n }\n pub fn ifact(&self, n: usize) -> ModInt {\n self.ifact[n]\n }\n pub fn comb(&self, n: usize, k: usize) -> ModInt {\n if k > n {\n return ModInt::zero();\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n}\n// ---------- end Precalc ----------\n// ---------- begin Aho-Corasick ----------\nconst F: usize = 2;\n\nfn convert(s: Vec) -> Vec {\n let mut a = Vec::with_capacity(s.len());\n for c in s {\n let k = c.to_digit(10).unwrap() as usize;\n a.push(k);\n }\n a\n}\n\nstruct ACTrieNode {\n elem: bool,\n fail: usize,\n depth: usize,\n next: [usize; F],\n}\n\nimpl ACTrieNode {\n fn new() -> ACTrieNode {\n ACTrieNode {\n elem: false,\n fail: 0,\n depth: 0,\n next: [0; F],\n }\n }\n}\n\nstruct AhoCorasick {\n node: Vec,\n}\n\n#[allow(dead_code)]\nimpl AhoCorasick {\n fn new() -> Self {\n let root = ACTrieNode::new();\n AhoCorasick {\n node: vec![root],\n }\n }\n fn insert(&mut self, s: &Vec) -> usize {\n let node = &mut self.node;\n let mut v = 0;\n for &k in s {\n if node[v].next[k] == 0 {\n node[v].next[k] = node.len();\n let mut t = ACTrieNode::new();\n t.depth = node[v].depth + 1;\n node.push(t);\n }\n v = node[v].next[k];\n }\n node[v].elem = true;\n v\n }\n fn build(&mut self) {\n let mut q = std::collections::VecDeque::new();\n let node = &mut self.node;\n for i in 0..F {\n if node[0].next[i] != 0 {\n q.push_back(node[0].next[i]);\n }\n }\n while let Some(v) = q.pop_front() {\n for i in 0..F {\n let u = node[v].next[i];\n if u == 0 {\n continue;\n }\n let mut fail = node[v].fail;\n while fail > 0 && node[fail].next[i] == 0 {\n fail = node[fail].fail;\n }\n let f = node[fail].next[i];\n node[u].fail = f;\n q.push_back(u);\n }\n }\n }\n fn next(&self, v: usize, k: usize) -> usize {\n self.node[v].next[k]\n }\n fn trans(&self, mut v: usize, k: usize) -> usize {\n let node = &self.node;\n while v > 0 && node[v].next[k] == 0 {\n v = node[v].fail;\n }\n node[v].next[k]\n }\n fn elem(&self, k: usize) -> bool {\n self.node[k].elem\n }\n fn fail(&self, k: usize) -> usize {\n self.node[k].fail\n }\n fn depth(&self, k: usize) -> usize {\n self.node[k].depth\n }\n fn get_size(&self) -> usize {\n self.node.len()\n }\n}\n// ---------- end Aho-Corasick ----------\n// ---------- begin Matrix ----------\n#[allow(dead_code)]\nmod matrix {\n use std::ops::{Add, Mul};\n pub trait SemiRing: Add + Mul + Copy {\n fn zero() -> Self;\n fn one() -> Self;\n }\n pub const SIZE: usize = 102;\n #[derive(Clone)]\n pub struct SquareMatrix {\n buf: [[T; SIZE]; SIZE],\n }\n impl SquareMatrix {\n pub fn zero() -> Self {\n let z = T::zero();\n SquareMatrix {\n buf: [[z; SIZE]; SIZE],\n }\n }\n pub fn identity() -> Self {\n let mut m = Self::zero();\n for i in 0..SIZE {\n m.buf[i][i] = T::one();\n }\n m\n }\n pub fn set_at(&mut self, i: usize, j: usize, v: T) {\n self.buf[i][j] = v;\n }\n pub fn get_at(&self, i: usize, j: usize) -> T {\n self.buf[i][j]\n }\n pub fn matmul(&self, rhs: &Self) -> Self {\n let mut res = Self::zero();\n for (x, a) in res.buf.iter_mut().zip(self.buf.iter()) {\n for (a, b) in a.iter().zip(rhs.buf.iter()) {\n for (x, b) in x.iter_mut().zip(b.iter()) {\n *x = *x + *a * *b;\n }\n }\n }\n res\n }\n pub fn matadd(&self, rhs: &Self) -> Self {\n let mut c = Self::zero();\n for (c, (a, b)) in c.buf.iter_mut().zip(self.buf.iter().zip(rhs.buf.iter())) {\n for (c, (a, b)) in c.iter_mut().zip(a.iter().zip(b.iter())) {\n *c = *a + *b;\n }\n }\n c\n }\n pub fn matpow(&self, mut n: usize) -> Self {\n let mut t = Self::identity();\n let mut s = self.clone();\n while n > 0 {\n if n & 1 == 1 {\n t = t.matmul(&s);\n }\n s = s.matmul(&s);\n n >>= 1;\n }\n t\n }\n }\n}\n// ---------- end Matrix ----------\n//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nuse matrix::*;\n\nimpl SemiRing for ModInt {\n fn zero() -> Self {\n ModInt::zero()\n }\n fn one() -> Self {\n ModInt::one()\n }\n}\n\nfn run() {\n input! {\n n: usize,\n x: usize,\n s: chars,\n }\n let s = convert(s);\n let mut aho = AhoCorasick::new();\n aho.insert(&s);\n aho.build();\n type M = SquareMatrix;\n let mut zero = M::identity();\n zero.set_at(n + 1, n + 1, ModInt(2));\n for i in 0..=n {\n let v = aho.trans(i, 0);\n let u = zero.get_at(v, i);\n zero.set_at(v, i, u + ModInt::one());\n if v == n {\n let u = zero.get_at(n + 1, i);\n zero.set_at(n + 1, i, u + ModInt::one());\n }\n }\n let mut one = M::identity();\n one.set_at(n + 1, n + 1, ModInt(2));\n for i in 0..=n {\n let v = aho.trans(i, 1);\n let u = one.get_at(v, i);\n one.set_at(v, i, u + ModInt::one());\n if v == n {\n let u = one.get_at(n + 1, i);\n one.set_at(n + 1, i, u + ModInt::one());\n }\n }\n let mut dp = vec![];\n dp.push(zero);\n dp.push(one);\n for i in 2..=x {\n let v = dp[i - 2].matmul(&dp[i - 1]);\n dp.push(v);\n }\n let ans = dp[x].get_at(n + 1, 0);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["matrices", "dp", "combinatorics"], "code_uid": "7f6d51c31df8a63bff1a65928f8fdd37", "src_uid": "52c6aa73ff4460799402c646c6263630", "difficulty": 2400, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 \u3088\u308a\nmacro_rules! input {\n (source = $s:expr, $($r:tt)*) => {\n let mut iter = $s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n ($($r:tt)*) => {\n let s = {\n use std::io::Read;\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s\n };\n let mut iter = s.split_whitespace();\n input_inner!{iter, $($r)*}\n };\n}\n\nmacro_rules! input_inner {\n ($iter:expr) => {};\n ($iter:expr, ) => {};\n ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {\n let $var = read_value!($iter, $t);\n input_inner!{$iter $($r)*}\n };\n}\n\nmacro_rules! read_value {\n ($iter:expr, ( $($t:tt),* )) => {\n ( $(read_value!($iter, $t)),* )\n };\n ($iter:expr, [ $t:tt ; $len:expr ]) => {\n (0..$len).map(|_| read_value!($iter, $t)).collect::>()\n };\n ($iter:expr, chars) => {\n read_value!($iter, String).chars().collect::>()\n };\n ($iter:expr, usize1) => {\n read_value!($iter, usize) - 1\n };\n ($iter:expr, $t:ty) => {\n $iter.next().unwrap().parse::<$t>().expect(\"Parse error\")\n };\n}\n\n// \u3053\u3053\u307e\u3067\n\nfn run() {\n input! {\n n: i64,\n p: i64,\n }\n for k in 1..50 {\n let v = n - p * k;\n if v < 0 {\n break;\n }\n let c = v.count_ones() as i64;\n if c <= k && k <= v {\n println!(\"{}\", k);\n return;\n }\n }\n println!(\"-1\");\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "bitmasks"], "code_uid": "6ab16cbd1e8a295700633046c3054bf4", "src_uid": "9e86d87ce5a75c6a982894af84eb4ba8", "difficulty": 1600, "exec_outcome": "PASSED"}