{"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut w = String::new();\n io::stdin()\n .read_line(&mut w)\n .expect(\"Read error\");\n \n let w: isize = w.trim().parse().expect(\"Parse error\");\n \n let mut i = 1;\n while i < w && (i % 2 == 1 || (w - i) % 2 == 1) {\n i += 1;\n }\n\n if i < w {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "6b88bc2fcb8eeace99839710612b419a", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut v = String::new();\n std::io::stdin().read_line(&mut v);\n let v = v.trim();\n let result = v.parse::();\n let num:u32;\n match result {\n Ok(v)=> num = v,\n Err(e)=> panic!(\"failed to parse {}\",e)\n }\n if num <= 3\n {\n println!(\"NO\");\n return;\n }\n if num % 2 == 0\n {\n println!(\"YES\")\n } else {\n println!(\"NO\");\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "c5d6c63de874b3a1e22c468505a25362", "src_uid": "230a3c4d7090401e5fa3c6b9d994cdf2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n\n let line = buf.trim_end();\n\n if line.len() < 7 {\n println!(\"NO\");\n return;\n }\n\n for index in 0..(line.len() - 7 + 1) {\n let substr: String = line.chars().skip(index).take(7).collect();\n\n if substr == \"0000000\" || substr == \"1111111\" {\n println!(\"YES\");\n return;\n }\n }\n\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "05a6ecbd28e0c96c28810433fceb30e6", "src_uid": "ed9a763362abc6ed40356731f1036b38", "difficulty": 900.0, "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}\npub fn solution_of_p96a(input: &mut Read, out: &mut Write) {\n let mut scanner = Scanner::new(input);\n let s = scanner.next::();\n if s.contains(\"0000000\") || s.contains(\"1111111\") {\n write!(out, \"YES\\n\").ok();\n } else {\n write!(out, \"NO\\n\").ok();\n }\n}\n\nfn main() {\n solution_of_p96a(&mut stdin(), &mut stdout());\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "86abe8f40123663ef257edf49240debd", "src_uid": "ed9a763362abc6ed40356731f1036b38", "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;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n\n let numbers = get_numbers(&input);\n let M = numbers[0];\n let N = numbers[1];\n println!(\"{}\", cover(M, N));\n}\n\nfn cover(cols: u8, rows: u8) -> u8 {\n // start with laying them flat\n let flat = ((cols - (cols % 2)) / 2) * rows;\n \n let tall = if cols % 2 == 1 {\n // there is a leftover column, place dominos tall\n rows / 2\n } else {\n 0\n };\n\n flat + tall\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"], "code_uid": "5a03f072204425fe734ae2e2005ab5c5", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_rules! input_list {\n ($var:ident, $type:ty, $ch:expr) => {\n let mut $var: Vec<$type> = Vec::new();\n let mut temp = String::new();\n std::io::stdin().read_line(&mut temp).unwrap();\n let temp_list: Vec<&str> = temp.split($ch).collect();\n for num in temp_list {\n $var.push(num.trim().parse::<$type>().unwrap());\n }\n }\n}\n\nfn main() {\n input_list!(size, i32, ' ');\n let dominoes_needed = (size[0] * size[1])/2;\n println!(\"{}\", dominoes_needed);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "28f47acb9bddbaf9837a11a92942de01", "src_uid": "e840e7bfe83764bee6186fcf92a1b5cd", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\n/**fn main() {\n \n let mut input = String::new();\n println!(\"Say something: \");\n \n match io::stdin().read_line(&mut input){\n Ok(_) =>{\n println!(\"You typed {}\",input);\n },\n Err(e) => println!(\"Error: {}\",e)\n }\n}*/\nfn contar(line: &str) -> (isize, isize) {\n let mut x = 0;\n let mut y = 0;\n for i in line.chars(){\n match i {\n 'Q' => x+=9,\n 'R' => x+=5,\n 'B' => x+=3,\n 'N' => x+=3,\n 'P' => x+=1,\n 'q' => y+=9,\n 'r' => y+=5,\n 'b' => y+=3,\n 'n' => y+=3,\n 'p' => y+=1,\n _ => x = x,\n }\n }\n (x,y)\n}\n\nfn main(){\n let mut pw = 0;\n let mut pb = 0;\n for _ in 0..8 {\n let mut input = String::new();\n //println!(\"Say something: \");\n \n match io::stdin().read_line(&mut input){\n Ok(_) =>{\n let (xx,yy) = contar(&input);\n pw += xx;\n pb += yy;\n //println!(\"You typed {}\",input);\n },\n Err(e) => println!(\"Error: {}\",e)\n }\n\t}\n let res = pw-pb;\n /*match res {\n Ok(value) if value<0 => println!(\"Black\"),\n Ok(value) if value>0 => println!(\"White\"),\n Ok(value) if value==0 => println!(\"Draw\"),\n Err(_) => println!(\"an error occurred\"),\n \n\t}*/\n if res<0{\n println!(\"Black\");\n\t} else if res>0{\n println!(\"White\");\n\t}else{\n println!(\"Draw\");\n\t}\n //println!(\"{} y {}\",pw,pb);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "c1f7fb6cb044821bce544ccafad1270d", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::iter::Iterator;\n\nfn conteo(input: String) -> i32 {\n let mut c :i32 = 0;\n\n for i in input.chars() {\n match i {\n 'Q' => c += 9,\n 'R' => c += 5,\n 'B' | 'N' => c += 3,\n 'P' => c += 1,\n 'q' => c -= 9,\n 'r' => c -= 5,\n 'b' | 'n' => c -= 3,\n 'p' => c -= 1,\n _ => (),\n }\n }\n\n return c;\n}\n\nfn main() {\n let mut comando = String::new();\n let mut res :i32 = 0;\n\n for _i in 0..8 {\n \n match io::stdin().read_line(&mut comando) {\n Ok(_n) => {\n let iter = comando.chars().filter(|&x| x != '.');\n res += conteo(iter.collect::());\n }\n Err(error) => println!(\"error: {}\", error),\n }\n \n comando = String::new(); \n }\n\n if res > 0 {\n println!(\"White\")\n }\n else if res < 0 {\n println!(\"Black\")\n }\n else{\n println!(\"Draw\")\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "095d027e97392abd256b5f9c2eef77ed", "src_uid": "44bed0ca7a8fb42fb72c1584d39a4442", "difficulty": 900.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 = 100006;\nconst INF:i64 = std::i64::MAX;\nconst MOD:i64 = 1e9 as i64 + 7;\n\n\nfn main() {\n input!{n:usize, a:[usize;3]};\n\n let mut dp = vec![-1;n+1];\n dp[0] = 0;\n\n for i in 0..n+1 {\n for j in 0..3 {\n if i < a[j] { continue; }\n if dp[i-a[j]] == -1 { continue; }\n dp[i] = max(dp[i], dp[i-a[j]]+1);\n }\n }\n //debug!(dp);\n\n println!(\"{}\", dp[n]);\n}\n\n/*\n\n長さ n のリボンを a,b,c のいずれかの長さにする。\nこのとき、最大のリボンの数を求める。\n\ndp[i] := 長さ i のリボンを切れる最大の数\ndp[i] = max(dp[i-a[j]]+1, j=0,1,2)\n\n\n\n*/", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "80241c78dec82beabb5e8df94bd35bf4", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300.0, "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\nfn read_params() -> (usize, Vec) {\n let line = read_line();\n let mut input = line.trim().split_whitespace().map(|x| x.parse::().unwrap());\n let n = input.next().unwrap();\n let mut sizes: Vec = input.collect();\n\n sizes.sort();\n if sizes.len() == 3 {\n if sizes[2] % sizes[0] == 0 || sizes[2] % sizes[1] == 0 {\n sizes.pop();\n }\n }\n if sizes.len() > 1 {\n if sizes[1] % sizes[0] == 0 {\n sizes.remove(1);\n }\n }\n\n (n, sizes)\n}\n\nfn calculate_max_cuts(n: usize, sizes: &[usize]) -> usize {\n if n % sizes.first().unwrap() == 0 {\n return n / sizes.first().unwrap();\n }\n\n let mut counts: Vec = vec![0; n + 1];\n for i in 1..counts.len() {\n for x in sizes.iter().cloned() {\n let value = if x > i {\n 0\n } else if x == i {\n 1\n } else if counts[i - x] == 0 {\n 0\n } else {\n counts[i - x] + 1\n };\n counts[i] = std::cmp::max(value, counts[i]);\n }\n }\n\n *counts.last().unwrap()\n}\n\nfn main() {\n let (n, sizes) = read_params();\n println!(\"{}\", calculate_max_cuts(n, &sizes));\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "a5029a2558d551a7c4aad4ca217b1a3c", "src_uid": "062a171cc3ea717ea95ede9d7a1c3a43", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nconst M: u64 = 998244353;\n\nfn pow(n: u64, p: u64) -> u64 {\n let mut q = p;\n let mut r = n;\n let mut result = 1;\n while q > 0 { \n if q % 2 == 1 { \n result = result * r % M;\n } \n r = r * r % M;\n q >>= 1;\n }\n result\n}\n\nfn inv(n: u64) -> u64 {\n pow(n, M - 2)\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n let n: usize = lines.next().unwrap().unwrap().parse().unwrap();\n let mut cs: Vec = vec![0, 0];\n let mut x: u64 = 0;\n for i in 0..n {\n let p = i % 2;\n let q = (i + 1) % 2;\n x = (cs[q] + q as u64) % M;\n cs[p] = (cs[p] + x) % M;\n }\n let d = pow(2, n as u64);\n println!(\"{}\", x * inv(d) % M);\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "bc630931fdd1a73beb09d67e67c9bdd9", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600.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\ntype Vec2 = Vec>;\ntype Vec3 = Vec>>;\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 = 998244353;\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\n let mut dp = vec![ModInt::new(0); N + 10];\n\n dp[0] = ModInt::new(1);\n\n let mut e = vec![ModInt::new(0); N + 2];\n let mut o = vec![ModInt::new(0); N + 2];\n\n for i in 0..N + 1 {\n if i % 2 == 0 {\n dp[i] = dp[i] + o[i];\n e[i + 1] = e[i] + dp[i];\n o[i + 1] = o[i];\n } else {\n dp[i] = dp[i] + e[i];\n o[i + 1] = o[i] + dp[i];\n e[i + 1] = e[i];\n }\n }\n\n mydbg!(dp[N]);\n let mut ans = ModInt::new(1) / ModInt::new(2).pow(N as i64);\n ans = ans * dp[N];\n echo!(ans.to_string());\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "911a7074d7556ccf25620d8428871f74", "src_uid": "cec37432956bb0a1ce62a0188fe2d805", "difficulty": 1600.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\n\n#[derive(Copy, Clone, Debug)]\nstruct Pair {\n i : usize,\n cost : i64\n}\nimpl PartialOrd for Pair {\n fn partial_cmp(&self, other : &Pair) -> Option {\n Some(self.cost.cmp(&other.cost))\n }\n}\n\nimpl Ord for Pair {\n fn cmp(&self, other : &Pair) -> Ordering {\n self.partial_cmp(other).unwrap()\n }\n}\n\nimpl PartialEq for Pair {\n fn eq(&self, other : &Pair) -> bool {\n self.cost == other.cost\n }\n}\nimpl Eq for Pair {}\n\nfn main() {\n let stdin = stdin();\n let mut s = stdin.lock();\n let (n, m) = scan!(s, i64, i64);\n let mut possible = false;\n\n let mut scale = m;\n while scale <= n {\n if 2*scale >= n {\n possible = true;\n break;\n }\n scale += m;\n }\n\n if possible {\n println!(\"{}\", scale);\n } else {\n println!(\"-1\");\n }\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a9c6f67b0f7245618f5e20ec63be0d64", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "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,m) = readln!(i32,i32);\n let (mn,mx) = ((n+1)/2,n);\n let qmin = (mn+m-1)/m;\n let vmin = qmin*m;\n if vmin >= mn && vmin <= mx {\n println!(\"{}\",vmin);\n } else {\n println!(\"-1\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "23d516567f48231805b4badaa2e2f36b", "src_uid": "0fa526ebc0b4fa3a5866c7c5b3a4656f", "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 zeros_factorial(n: u64) -> u64 {\n let mut ans = 0;\n let mut n = n;\n while n > 0 {\n ans += n / 5;\n n /= 5;\n }\n ans\n}\n\nfn search(m: u64) -> u64 {\n let mut lo = 0;\n let mut hi = 500000; // zeros_factorial(n) >= n / 5\n while lo < hi {\n let mid = lo + (hi - lo) / 2;\n if zeros_factorial(mid) >= m {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n lo\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let m: u64 = scan.token();\n let n = search(m);\n if zeros_factorial(n) == m {\n writeln!(out, \"5\").ok();\n for i in 0..5 {\n write!(out, \"{} \", n + i).ok();\n }\n writeln!(out).ok();\n } else {\n writeln!(out, \"0\").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", "constructive algorithms", "number theory"], "code_uid": "3e6d2415a95cf12a4020e114b98c5a35", "src_uid": "c27ecc6e4755b21f95a6b1b657ef0744", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n// let mut user_count = 0;\n// let mut size = 0;\n\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 mut id = 0;\n let mut array: [i32; 4] = [0; 4];\n\n for token in input_text.split_whitespace(){\n match token.parse::() {\n Ok(i) => {\n array[id] = i;\n id = id + 1;\n },\n Err(..) => {},\n };\n }\n\n array.sort();\n if (array[2] < (array[0] + array[1]) || array[3] < (array[1] + array[2])) {\n println!(\"TRIANGLE\");\n return;\n };\n\n if (array[2] == (array[0] + array[1]) || array[3] == (array[1] + array[2])) {\n println!(\"SEGMENT\");\n return;\n };\n\n println!(\"IMPOSSIBLE\");\n\n}", "lang_cluster": "Rust", "tags": ["brute force", "geometry"], "code_uid": "6139c64b3b699e6c55c1454da743fe31", "src_uid": "8f5df9a41e6e100aa65b9fc1d26e447a", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "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 last_odd_number_less_than_number(n: i32) -> i32 {\n let mut i = n;\n while i > 0 {\n if i % 2 == 1 {\n return i;\n }\n i -= 1;\n }\n 0\n}\n\nfn get_result(input: &u32) -> String {\n let base: i32 = 2;\n let num_of_players: i32 = base.pow(*input);\n last_odd_number_less_than_number(num_of_players)\n .to_string()\n}\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n let n = scan.next::();\n let contents: Vec = (0..n).map(|_| scan.next()).collect();\n for content in contents {\n writeln!(out, \"{}\", get_result(&content)).ok();\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e9024af3f19dc2b60a9664b7519c382a", "src_uid": "d5e66e34601cad6d78c3f02898fa09f4", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(warnings, unused)]\nuse std::cmp::Ordering;\nuse std::io::Write;\n\nuse std::cmp;\nuse std::cmp::min;\nuse std::collections::BTreeMap;\nuse std::process;\nuse std::cmp::Ord;\nuse std::collections::HashMap;\nuse std::collections::HashSet;\nuse std::collections::VecDeque;\nuse std::collections::BTreeSet;\nuse std::mem;\nuse std::collections::BinaryHeap;\nuse std::hash::{Hash, Hasher};\n\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\n .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 std::str::from_utf8(&buf).unwrap()\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\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 VecDeque{\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}\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\nstruct MultiSet {\n set: BTreeSet,\n map: HashMap\n}\n\nimpl MultiSet {\n fn new() -> MultiSet {\n MultiSet{\n set: BTreeSet::new(), map: HashMap::new()\n }\n }\n fn len(& self)->usize{\n return self.set.len();\n }\n fn contains(& self, i:&T)->bool{\n if self.set.contains(i){\n return true;\n }\n else{\n return false\n }\n }\n \n\n ///重複許可挿入\n fn insert(&mut self, i:T) -> Option\n {\n if let Some(_i) = self.set.get(&i) {\n //setにある\n *self.map.entry(i).or_insert(0) += 1;\n }else{\n //setにない\n self.set.insert(i);\n *self.map.entry(i).or_insert(0) += 1;\n }\n return Some(i);\n }\n\n ///1つ削除\n fn remove(&mut self, e:&T) -> Option\n {\n if let Some(_e) = self.set.get(e) {\n //setにある\n *self.map.entry(*e).or_insert(0) -= 1;\n if self.map[&e]==0 {\n //なくなった\n self.set.take(e);\n }\n return Some(*e);\n }else{\n //setにない\n return None;\n }\n }\n\n ///最小値の取得\n fn get_min(&self) -> Option\n {\n if let Some(&m) = self.set.iter().nth(0) {\n return Some(m);\n }else{\n return None;\n }\n }\n\n ///最大値の取得\n fn get_max(&self) -> Option\n {\n if let Some(&m) = self.set.iter().last() {\n return Some(m);\n }else{\n return None;\n }\n }\n}\nfn invs(max:usize)->(Vec, Vec){\n let mut fac = vec![0;max+1];\n let mut ifac = vec![0;max+1];\n fac[0] = 1;\n ifac[0] = 1;\n for i in 0..max{\n\n fac[i+1] = ((fac[i] as u64 * (i+1) as u64)%MODu as u64) as usize;\n ifac[i+1] = ((ifac[i] as u64 * modpow(i+1, MODu - 2) as u64)%MODu as u64) as usize;\n }\n (fac, ifac)\n}\nfn modpow(x:usize, n:usize) -> usize{\n let mut ans = 1;\n let mut n = n as usize;\n let mut x = x;\n while(n != 0){\n if (n&1 == 1){ans = (ans as u64*x as u64%MODu as u64) as usize;}\n x = (((x%MODu) as u64*(x%MODu) as u64)%MODu as u64) as usize;\n n = n>>1;\n }\n ans\n}\nfn comb(a:usize, b:usize, fac:&Vec, ifac:&Vec)->usize{\n let mut a = a;\n let mut b = b;\n if a == 0 && b == 0{return 1;}\n if a,\n rank:Vec,\n size:Vec,\n size_edge:Vec,\n}\nimpl union_find{\n fn new(n:usize) -> union_find{\n let mut par = vec![0;n];\n for i in 0..n{\n par[i] = i;\n }\n union_find{\n par:par,\n rank:vec![0;n],\n size:vec![1;n],\n size_edge:vec![0;n],\n }\n }\n fn find(&mut self, x:usize) ->usize{\n if(self.par[x] == x){\n x\n }\n else{\n let p = self.par[x];\n let res = self.find(p);\n self.par[x] = res;\n res\n }\n }\n fn same(&mut self, a:usize, b:usize)->bool{\n self.find(a) == self.find(b)\n }\n fn unite(&mut self, a:usize, b:usize){\n let x = self.find(a);\n let y = self.find(b);\n if x != y{\n if (self.rank[x] < self.rank[y]){\n self.par[x] = y;\n self.size[y] += self.size[x];\n self.size_edge[y] += self.size_edge[x];\n self.size_edge[y] += 1;\n }\n else{\n self.par[y] = x;\n self.size[x] += self.size[y];\n self.size_edge[x] += self.size_edge[y];\n self.size_edge[x] += 1;\n if(self.rank[x] == self.rank[y]){ self.rank[x]+=1;}\n }\n\n }\n else{\n self.size_edge[x] += 1;\n }\n }\n fn check_size(&mut self, a:usize) -> usize{\n let x = self.find(a);\n let s = self.size[x];\n s\n }\n}\n\n\nstruct segment_tree{\n n: usize,\n dat: Vec,\n op:Op,\n e:I,\n}\nimpl segment_tree\n \n \n where Op: Fn(I, I) -> I, I:Copy{\n \n pub fn new(n_:usize, op: Op, e:I)->Self{\n let mut n = 1;\n while(n0){\n k = (k-1)/2;\n self.dat[k] = (self.op)(self.dat[k*2 + 1], self.dat[k*2+2]);\n }\n }\n \n pub fn query_sub(&self, a:usize, b:usize, k:usize, l:usize, r:usize) -> I{\n if r<=a || b<=l{return self.e;}\n if a<=l && r<=b{return self.dat[k];}\n else{\n let mut vl = self.query_sub(a, b, k*2+1, l, (l+r)/2);\n let mut vr = self.query_sub(a, b, k*2+2, (l+r)/2, r);\n return (self.op)(vl, vr);\n }\n }\n pub fn query(&self, a:usize, b:usize)->I{\n return self.query_sub(a, b, 0, 0, self.n);\n }\n }\n \n\n\n\nstruct rolling_hash{\n base1:u64,\n base2:u64,\n mod1:u64,\n mod2:u64,\n hash1:Vec,\n hash2:Vec,\n power1:Vec,\n power2:Vec\n}\n\nimpl rolling_hash{\n fn new(S:&Vec)->rolling_hash{\n let mut n = S.len();\n let mut base1 = 1007;\n let mut base2 = 2009;\n let mut mod1 = 1000000007;\n let mut mod2 = 1000000009;\n let mut hash1 = vec![0;n+1];\n let mut hash2 = vec![0;n+1];\n let mut power1 = vec![1;n+1];\n let mut power2 = vec![1;n+1];\n\n for i in 0..n{\n hash1[i+1] = (hash1[i] * base1 + S[i])%mod1;\n hash2[i+1] = (hash2[i] * base2 + S[i])%mod2;\n power1[i+1] = (power1[i] * base1)%mod1;\n power2[i+1] = (power2[i] * base2)%mod2;\n }\n\n return rolling_hash{\n hash1:hash1,\n hash2:hash2,\n power1:power1,\n power2:power2,\n base1:base1,\n base2:base2,\n mod1:mod1,\n mod2:mod2\n }\n }\n // [l, r) \n fn get(&self, l:usize, r:usize)->(u64, u64){\n let mut res1 = self.hash1[r] as i64 - self.hash1[l] as i64 * self.power1[r-l] as i64%self.mod1 as i64;\n if (res1<0) {res1+= self.mod1 as i64;}\n let mut res2 = self.hash2[r] as i64 - self.hash2[l] as i64 * self.power2[r-l] as i64%self.mod2 as i64;\n if (res2<0) {res2+= self.mod2 as i64;}\n return (res1 as u64, res2 as u64);\n }\n}\nfn base_number(x:u64, n:u64)->Vec{\n let mut x = x;\n let mut n = n;\n let mut r = 1;\n let mut q = x;\n let mut res = vec![];\n while(q>=n){\n r = q%n;\n res.push(r);\n q = q/n;\n }\n r = q%n;\n res.push(r);\n res.reverse();\n return res\n}\npub struct point_set_range_max {\n xss: Vec>,\n h: usize,\n w: usize,\n initial: i64,\n }\n\n impl point_set_range_max {\n pub fn new(h: usize, w: usize, initial: i64) -> Self {\n let H = w.next_power_of_two();\n let W = h.next_power_of_two();\n Self {\n xss: vec![vec![initial; 2 * W]; 2 * H],\n h:H,\n w:W,\n initial,\n }\n }\n fn update(&mut self, x: usize, y: usize) {\n if x >= self.w && y >= self.h {\n return;\n }\n let s = if x < self.w {\n std::cmp::max(self.xss[y][2 * x + 0], self.xss[y][2 * x + 1])\n } else {\n self.initial\n };\n let t = if y < self.h {\n std::cmp::max(self.xss[2 * y + 0][x], self.xss[2 * y + 1][x])\n } else {\n self.initial\n };\n let r = std::cmp::max(s, t);\n self.xss[y][x] = r;\n }\n pub fn set(&mut self, x: usize, y: usize, v: i64) {\n self.xss[y + self.h][x + self.w] = v;\n let mut x = x + self.w;\n while x > 0 {\n let mut y = y + self.h;\n while y > 0 {\n self.update(x, y);\n y >>= 1;\n }\n x >>= 1;\n }\n }\n pub fn query(&mut self, l: usize, r: usize, u: usize, d: usize) -> i64 {\n let mut l = l + self.w;\n let mut r = r + self.w;\n let mut res = self.initial;\n while l < r {\n if l & 1 != 0 {\n let mut u = u + self.h;\n let mut d = d + self.h;\n while u < d {\n if u & 1 != 0 {\n res = std::cmp::max(res, self.xss[u][l]);\n u += 1;\n }\n if d & 1 != 0 {\n d -= 1;\n res = std::cmp::max(res, self.xss[d][l]);\n }\n u >>= 1;\n d >>= 1;\n }\n l += 1;\n }\n if r & 1 != 0 {\n r -= 1;\n let mut u = u + self.h;\n let mut d = d + self.h;\n while u < d {\n if u & 1 != 0 {\n res = std::cmp::max(res, self.xss[u][r]);\n u += 1;\n }\n if d & 1 != 0 {\n d -= 1;\n res = std::cmp::max(res, self.xss[d][r]);\n }\n u >>= 1;\n d >>= 1;\n }\n }\n l >>= 1;\n r >>= 1;\n }\n res\n }\n }\n\npub struct point_set_range_sum_bool {\n xss: Vec>,\n h: usize,\n w: usize,\n initial: bool,\n }\n \n impl point_set_range_sum_bool {\n pub fn new(h: usize, w: usize, initial: bool) -> Self {\n let H = w.next_power_of_two();\n let W = h.next_power_of_two();\n Self {\n xss: vec![vec![initial; 2 * W]; 2 * H],\n h:H,\n w:W,\n initial,\n }\n }\n fn update(&mut self, x: usize, y: usize) {\n if x >= self.w && y >= self.h {\n return;\n }\n let s = if x < self.w {\n self.xss[y][2 * x + 0] | self.xss[y][2 * x + 1]\n } else {\n self.initial\n };\n let t = if y < self.h {\n self.xss[2 * y + 0][x] | self.xss[2 * y + 1][x]\n } else {\n self.initial\n };\n let r = s | t;\n self.xss[y][x] = r;\n }\n pub fn set(&mut self, x: usize, y: usize, v: bool) {\n self.xss[y + self.h][x + self.w] = v;\n let mut x = x + self.w;\n while x > 0 {\n let mut y = y + self.h;\n while y > 0 {\n self.update(x, y);\n y >>= 1;\n }\n x >>= 1;\n }\n }\n pub fn query(&mut self, l: usize, r: usize, u: usize, d: usize) -> bool {\n let mut l = l + self.w;\n let mut r = r + self.w;\n let mut res = self.initial;\n while l < r {\n if l & 1 != 0 {\n let mut u = u + self.h;\n let mut d = d + self.h;\n while u < d {\n if u & 1 != 0 {\n res = res | self.xss[u][l];\n u += 1;\n }\n if d & 1 != 0 {\n d -= 1;\n res = res | self.xss[d][l];\n }\n u >>= 1;\n d >>= 1;\n }\n l += 1;\n }\n if r & 1 != 0 {\n r -= 1;\n let mut u = u + self.h;\n let mut d = d + self.h;\n while u < d {\n if u & 1 != 0 {\n res = res | self.xss[u][r];\n u += 1;\n }\n if d & 1 != 0 {\n d -= 1;\n res = res | self.xss[d][r];\n }\n u >>= 1;\n d >>= 1;\n }\n }\n l >>= 1;\n r >>= 1;\n }\n res\n }\n }\n\n//最大公約数\nfn gcd(a:usize, b:usize)->usize{\n if b==0{return a;}\n return gcd(b, a%b);\n}\nenum Node {\n Operator {\n nxt0: Box,\n nxt1: Box,\n }, \n Number {\n lazy:i64,\n cnt:i64\n }, \n}\nfn dijkstra(s:usize, g:&Vec>)->Vec{\n let mut dist = vec![INF;g.len()];\n dist[s] = 0;\n let mut h = BinaryHeap::new();\n h.push((0, s));\n while(h.len() != 0){\n let mut t = h.pop().unwrap();\n let mut d = t.0 * -1;\n let mut v = t.1;\n if dist[v]d+dd{\n dist[n] = d+dd;\n h.push((dist[n]*-1, n));\n }\n }\n }\n return dist;\n}\nfn safe_mod(x:i64, m:i64)->i64{\n let mut x = x;\n let mut m = m;\n x%=m;\n if x<0{\n x+=m;\n }\n return x;\n}\nfn pow_mod(x: i64, mut n: i64, m: i64) -> 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}\nfn is_prime(n: i64) -> 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 i64);\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}\nfn prime_factor(n:i64)->HashMap{\n let mut res = HashMap::new();\n let mut n = n;\n for i in 2..n{\n if i*i>n{break;}\n while(n%i==0){\n *res.entry(i).or_insert(0)+=1;\n n/=i;\n }\n }\n if n != 1{\n res.insert(n, 1);\n }\n res\n}\nfn solve(){\n let sssss = std::io::stdin();\n let mut sc = Scanner { stdin: sssss.lock() };\n let out = std::io::stdout();\n let mut out = std::io::BufWriter::new(out.lock());\n let mut test:usize = sc.read();\n for _ in 0..test{\n let mut i:i64 = sc.read();\n\n writeln!(out, \"{}\", (1<(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}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 = 998_244_353;\n\tconst P6: i64 = P5 as i64;\n\t#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Default)] pub struct Field(pub 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\tconst N: usize = 500;\n\n\tl!(mut f,fi = v!([N+1] = Z1));\n\tfor i in 2..N {\n\t\tf[i] = f[i-1] * Z::new(i as i32);\n\t\tfi[i] = f[i].inv();\n\t}\n\tlet cnr = |n,r| -> Z {\n\t\tif r > n {\n\t\t\tZ0\n\t\t} else {\n\t\t\tf[n] * fi[n-r] * fi[r]\n\t\t}\n\t};\n\tlet mut p = v!([N+1][N+1]);\n\tfor i in 0..=N {\n\t\tlet x = Z::new(i as i32);\n\t\tlet mut y = Z1;\n\t\tlet p = &mut p[i];\n\t\trp!{[N+1]\n\t\t\tp.push(y);\n\t\t\ty *= x;\n\t\t}\n\t}\n\n\tl!(n,x = rin.u());\n\tlet mut dp = v!([x+1][n+1] = Z0);\n\tlet mut s = Z0;\n\tfor i in 1..=x {\n\t\tdp[i][1] = Z1;\n\t\tfor j in 2..=n.min(i) {\n\t\t\tlet mut res = Z0;\n\t\t\tfor k in 1..=j {\n\t\t\t\tres += dp[i-j+1][k] * p[j-1][j-k] * cnr(j-1,k-1);\n\t\t\t}\n\t\t\tdp[i][j] = res;\n\t\t}\n\t\ts += dp[i][n];\n\t}\n\ts *= Z::new(n as i32);\n\tlet ans = p[x][n] - s;\n\twriteln!(rout, \"{}\", ans).unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "2cf94331e78dad75176683c144898017", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100.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\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 P = 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: &mut|dp, i, j| {\n match dp.D[i][j].get() {\n Some(x) => x,\n None => {\n let res = if j < i { P[j][i] - P[j-1][i] } else {\n (2..=i).map(|k| (dp.f)(dp, k, j-(i-1)) * mc.C(i, k) * P[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": "48e21bd77c99bde74ca53dca56c7dd61", "src_uid": "1908d1c8c6b122a4c6633a7af094f17f", "difficulty": 2100.0, "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() as usize;\n let t = input.i();\n let mut a = input.ab();\n\n for _ in 0..t {\n let mut b = a.clone();\n for i in (0..n-1).rev() {\n if a[i] == b'B' && a[i + 1] == b'G' {\n b[i] = b'G';\n b[i + 1] = b'B';\n }\n }\n a = b;\n }\n println!(\"{}\", String::from_utf8(a).unwrap());\n}\n\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "4a38b3d23f59218bebf397a581dd0459", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let (num,turns,mut list)=input();\n for _ in 0..turns{\n let mut ii=1;\n while ii 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() -> (i32,i32,Vec){\n let inp=read();\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}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation", "shortest paths", "graph matchings"], "code_uid": "bdd931cf9b881218540fb12152bf07af", "src_uid": "964ed316c6e6715120039b0219cc653a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin ModInt ----------\r\n// モンゴメリ乗算を用いる\r\n// ほぼCodeforces用\r\n// 注意\r\n// new_unchecked は値xが 0 <= x < modulo であることを仮定\r\n// ModInt の中身は正規化された値で持ってるので直接読んだり書いたりするとぶっ壊れる\r\n// 奇素数のみ\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 = 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\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\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\nfn run() {\r\n input! {\r\n h: u64,\r\n w: u64,\r\n k: u64,\r\n r: u64,\r\n c: u64,\r\n a: (u64, u64),\r\n b: (u64, u64),\r\n }\r\n let mut a = a;\r\n let mut b = b;\r\n if a.1 > b.1 {\r\n std::mem::swap(&mut a, &mut b);\r\n }\r\n if a.0 > b.0 {\r\n a.0 = h + 1 - (a.0 + r - 1);\r\n b.0 = h + 1 - (b.0 + r - 1);\r\n }\r\n let mut cnt = h * w;\r\n if a == b {\r\n } else {\r\n cnt -= r * c;\r\n }\r\n let ans = M::from(k).pow(cnt);\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n run();\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a46f58e734c13609c3d4df7358ec37bc", "src_uid": "3478e6a4ff2415508fd517413d40c13a", "difficulty": 2200.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 s: Vec = sc.ne::().into_bytes();\n let k: usize = sc.ne();\n let mut div = 1i64;\n for _ in 0..k {\n div *= 10;\n }\n let n = s.len();\n let mut mi = 100;\n for i in 0..(1 << n) {\n let mut a = Vec::new();\n for j in 0..n {\n if (1 << j) & i != 0 {\n a.push(s[j] - b'0');\n }\n }\n if a.is_empty() {\n continue;\n }\n if a.len() > 1 && a[0] == 0 {\n continue;\n }\n let score = n - (i as usize).count_ones() as usize;\n let mut val = 0i64;\n for j in 0..a.len() {\n val *= 10;\n val += a[j] as i64;\n }\n if val % div == 0 {\n mi = std::cmp::min(mi, score);\n }\n }\n println!(\"{}\", mi);\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": ["brute force", "greedy"], "code_uid": "6ffa827d951cb310c75f199dfe5fd46a", "src_uid": "7a8890417aa48c2b93b559ca118853f9", "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 _main() {\n let mut scan = Scan::new();\n let s: usize = scan.next();\n let v1: usize = scan.next();\n let v2: usize = scan.next();\n let t1: usize = scan.next();\n let t2: usize = scan.next();\n let score1 = s * v1 + 2 * t1;\n let score2 = s * v2 + 2 * t2;\n if score1 == score2 {\n println!(\"Friendship\");\n } else {\n println!(\"{}\", if score1 < score2 { \"First\" } else { \"Second\" });\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"], "code_uid": "5c4c742142694218fa64e9386e855ccc", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input)\n .expect(\"Failed to read line\");\n let input = input.trim().split(\" \").collect::>();\n\n let s = str_to_int(input[0]);\n let v1 = str_to_int(input[1]);\n let v2 = str_to_int(input[2]);\n let t1 = str_to_int(input[3]);\n let t2 = str_to_int(input[4]);\n\n let cli1 = s*v1 + 2*t1;\n let cli2 = s*v2 + 2*t2;\n\n if cli1 < cli2 {\n println!(\"First\");\n } else if cli1 > cli2 {\n println!(\"Second\");\n } else {\n println!(\"Friendship\");\n }\n}\n\nfn str_to_int(a:&str) -> i32 {\n a.parse::().unwrap()\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "541fc37c5abcf03f657ec998ec848aff", "src_uid": "10226b8efe9e3c473239d747b911a1ef", "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_interesting(x: usize) -> bool {\n let mut aux = x;\n let mut dsum = 0usize;\n while aux > 0 {\n dsum += aux % 10;\n aux /= 10;\n }\n dsum % 4 == 0\n}\n\nfn _main() {\n let mut scan = Scan::new();\n let mut a: usize = scan.next();\n while !is_interesting(a) {\n a += 1;\n }\n println!(\"{}\", a);\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": "b648867301c7e7bce9986171b612f7c1", "src_uid": "bb6fb9516b2c55d1ee47a30d423562d7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn sum_dig(n: i32) -> i32 {\n let mut x = n;\n let mut s = 0;\n while x > 0 {\n s += x % 10;\n x /= 10;\n }\n s\n}\n\nfn main() {\n let mut buf = String::new();\n let _ = stdin().read_line(&mut buf).unwrap();\n let n = buf.trim().trim_end().parse::().unwrap();\n let mut i = n;\n loop {\n if sum_dig(i) % 4 == 0 {\n println!(\"{}\", i);\n break;\n }\n i += 1;\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6aef083480a7baf3cda1e94dc5a6ec56", "src_uid": "bb6fb9516b2c55d1ee47a30d423562d7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut n = String::new();\n std::io::stdin().read_line(&mut n);\n let n: i32 = n.trim().parse().unwrap();\n // 1 2 3 4 5\n if n % 5 == 0 {\n println!(\"{:?}\", n / 5);\n } else {\n println!(\"{:?}\", n / 5 + 1);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "2fef2c61858c643b9b917ee8eb78fcd9", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused)]\nuse std::io;\n\n#[macro_export]\nmacro_rules! dbg {\n ($expr:expr) => {\n match $expr {\n expr => {\n eprintln!(\"{}: {} = {:#?}\", line!(), stringify!($expr), &expr);\n expr\n }\n }\n };\n ($l:literal, $expr:expr) => {\n match $expr {\n expr => {\n eprintln!(concat!(line!(), \": \",\n stringify!($expr), \" = \", $l), &expr);\n ($l, expr)\n }\n }\n }\n}\n\n#[macro_export]\nmacro_rules! ternary { ($condition: expr, $_true: expr, $_false: expr) => { if $condition { $_true } else { $_false } };}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"\");\n let x: u32 = input.trim().parse().expect(\"\");\n println!(\"{}\", x / 5 + ternary!(x % 5 > 0, 1, 0));\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "28020a99d228eade2f392b68d9a910b9", "src_uid": "4b3d65b1b593829e92c852be213922b6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/337/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\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let mut f: Vec =\n line\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n f.sort();\n\n let mut minima = 999;\n\n let iter = f.windows(n as usize);\n\n for x in iter {\n minima = std::cmp::min(minima, x.last().unwrap() - x[0]);\n }\n\n println!(\"{}\", minima);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "92b5bb8d657891d9ef2c9fd20ef9b56a", "src_uid": "7830aabb0663e645d54004063746e47f", "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 line = line.trim();\n let v: Vec = line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect();\n\n let n = v[0] as usize;\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n let line = line.trim();\n let mut v: Vec = line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect();\n \n v.sort();\n let mut ret = std::i32::MAX;\n for i in 0..v.len() - n + 1 {\n let tmp = v[i + n - 1] - v[i];\n ret = std::cmp::min(tmp, ret);\n }\n println!(\"{:?}\", ret);\n\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "e9a037fb1cd15e377bc3c5d8bcccd28f", "src_uid": "7830aabb0663e645d54004063746e47f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_macros)]\nmacro_rules! scan {\n () => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n };\n (;;$n:expr) => {\n (0..$n).map(|_| scan!()).collect::>()\n };\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 {\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(|_| scan!($t;;)).collect::>()\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n scan!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n scan!($($t),*)\n ).collect::>()\n };\n}\n\nfn main() {\n let (w1, h1, w2, h2) = scan!(i64, i64, i64, i64);\n println!(\"{}\", w1 + 2 * h1 + 4 + w2 + 2 * h2 + w1 - w2);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "cf6e19e5e1d506283b3ce70d3bd230b2", "src_uid": "b5d44e0041053c996938aadd1b3865f6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut sin = String::new();\n std::io::stdin().read_line(&mut sin).expect(\"read error\");\n let vi32: Vec = sin.split_whitespace().map(|c| c.parse().unwrap()).collect();\n let (w1, h1, w2, h2) = (vi32[0], vi32[1], vi32[2], vi32[3]);\n let ret = (h1 + h2) * 2 + (w1 + w2) + 4 + if w1 > w2 { w1 - w2 } else { 0 };\n println!(\"{}\", ret);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "12070d31959892957bd0ff530cfadaff", "src_uid": "b5d44e0041053c996938aadd1b3865f6", "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).unwrap();\n let mut x = text.trim().parse::().unwrap();\n let mut xx = 0;\n while x > 0 {\n let d = x % 10;\n x = x / 10;\n if d == 7 || d == 4 {\n xx = xx + 1;\n }\n }\n if xx == 0 {\n println!(\"NO\");\n return;\n }\n while xx > 0 {\n let d = xx % 10;\n xx = xx / 10;\n if d != 4 && d != 7 {\n println!(\"NO\");\n return;\n }\n }\n println!(\"YES\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "45cc7854ac31400acccf2c0e5ad44162", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "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 ans = 0;\n for i in buf.trim_end().chars() {\n if i == '4' || i == '7' {\n ans += 1;\n };\n }\n println!(\"{}\", if ans == 4 || ans == 7 { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6062b8185e79d0b154ebc2bd34c54af5", "src_uid": "33b73fd9e7f19894ea08e98b790d07f1", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros, non_snake_case)]\nuse std::cmp::{max, min, Ordering};\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\n\nfn run() {\n let stdin = std::io::stdin();\n let mut sc = Scanner::new(stdin.lock());\n let mut n: usize = sc.read();\n let k: usize = sc.read();\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\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 struct Scanner {\n reader: R,\n}\n\nimpl Scanner {\n pub fn new(r: R) -> Scanner {\n Scanner { reader: r }\n }\n}\n\nfn is_whitespace(b: u8) -> bool {\n b == b' ' || b == b'\\n' || b == b'\\r' || b == b'\\t'\n}\n\nimpl Scanner {\n pub fn read(&mut self) -> T {\n let buf = std::io::Read::bytes(self.reader.by_ref())\n .map(|b| b.expect(\"Read failed\"))\n .skip_while(|&b| is_whitespace(b))\n .take_while(|&b| !is_whitespace(b))\n .collect::>();\n unsafe { std::str::from_utf8_unchecked(&buf) }\n .parse()\n .ok()\n .expect(\"Parse error\")\n }\n\n pub fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read()).collect()\n }\n\n pub fn read_chars(&mut self) -> Vec {\n self.read::().chars().collect()\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#[allow(unused)] // This is defined for read! macro\nfn readln() -> String {\n let mut line = String::new();\n ::std::io::stdin()\n .read_line(&mut line)\n .unwrap_or_else(|e| panic!(\"{}\", e));\n line\n}\n//}}}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1a50a856df789827f4f08e90effa758e", "src_uid": "064162604284ce252b88050b4174ba55", "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 arr : Vec = s.split_whitespace().map(|s| s.parse().unwrap()).collect();\n let (mut n, k) = (arr[0], arr[1]);\n for _i in 0..k {\n if n % 10 == 0 {\n n /= 10;\n } else {\n n -= 1;\n }\n }\n println!(\"{}\", n);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7c2870e9c4c0513c423d21a699b27944", "src_uid": "064162604284ce252b88050b4174ba55", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\npub fn main() {\n let mut nums: Vec = {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n buf.trim()\n .split_whitespace()\n .map(str::parse)\n .map(Result::unwrap)\n .collect()\n };\n nums.sort();\n println!(\"{}\", nums[2] - nums[1] + nums[1] - nums[0]);\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "8ff39742f1b282d1edcbd7aa5293f17c", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "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)\n .expect(\"Failed to read line\");\n\n let split_input : Vec<&str> = input.as_str().split(' ').collect();\n let a : i32 = split_input[0].trim().parse().expect(\"en\"); \n let b : i32 = split_input[1].trim().parse().expect(\"en\"); \n let c : i32 = split_input[2].trim().parse().expect(\"en\"); \n let mut minimum: i32 = 300;\n for i in 1..100 {\n if (a - i).abs() + (b - i).abs() + (c - i).abs() < minimum {\n minimum = (a - i).abs() + (b - i).abs() + (c - i).abs();\n }\n }\n println!(\"{}\", minimum);\n}\n", "lang_cluster": "Rust", "tags": ["math", "sortings", "implementation"], "code_uid": "654baaa0525aea68a941ac4f8594d868", "src_uid": "7bffa6e8d2d21bbb3b7f4aec109b3319", "difficulty": 800.0, "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 determine_b(v: &[u16]) -> Option {\n let sum: u16 = v.iter().sum();\n if sum % 5 == 0 && sum != 0 {\n Some(sum / 5)\n } else {\n None\n }\n}\n\nfn print(res: Option) {\n match res {\n Some(val) => print!(\"{}\", val),\n None => print!(\"-1\"),\n }\n}\n\nfn main() {\n print(determine_b(&input_split()))\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f40855336a71fb583430558a0b16ecb5", "src_uid": "af1ec6a6fc1f2360506fc8a34e3dcd20", "difficulty": 1100.0, "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 a.sort();\n a.dedup();\n if a.len() % 2 == 0 {\n println!(\"CHAT WITH HER!\");\n } else {\n println!(\"IGNORE HIM!\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "86d1fea0cc3ba052ee39e8f1ef32f4bd", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// author: zkmrgirish\n// date: 10 Apr, Friday\n\n#[allow(unused_imports)]\nuse std::cmp::{max, min};\nuse std::collections::HashSet;\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\n let username: String = scan.next();\n let mut set = HashSet::new();\n\n for x in username.chars() {\n set.insert(x);\n }\n\n writeln!(\n out,\n \"{}\",\n if set.len() % 2 == 0 {\n \"CHAT WITH HER!\"\n } else {\n \"IGNORE HIM!\"\n }\n )\n .ok();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "d6d9dfca0567dfe2bf90ad02d126039c", "src_uid": "a8c14667b94b40da087501fd4bdd7818", "difficulty": 800.0, "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\nuse std::cmp;\n\n#[allow(unused_must_use)]\nfn run(mut reader: Scanner, mut writer: W) {\n let total_number_of_trips: i32 = reader.next();\n let number_of_trips_with_special_ticket: i32 = reader.next();\n let one_trip_price: i32 = reader.next();\n let special_ticket_price: i32 = reader.next();\n\n let number_of_special_tickets_bought: i32 = total_number_of_trips / number_of_trips_with_special_ticket;\n let mut total_cost: i32 = number_of_special_tickets_bought * special_ticket_price;\n let remaining_trips_needed: i32 = total_number_of_trips % number_of_trips_with_special_ticket;\n if remaining_trips_needed > 0 {\n total_cost += cmp::min(remaining_trips_needed * one_trip_price, special_ticket_price);\n }\n\n total_cost = cmp::min(total_cost, total_number_of_trips * one_trip_price);\n\n writeln!(writer, \"{}\", total_cost);\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": ["implementation"], "code_uid": "7510f4a83a732df90b1abe9b7728b3ad", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200.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 params: Vec = reads(sin);\n\n let n = params[0];\n let m = params[1];\n let a = params[2];\n let b = params[3];\n\n let ans = if a * m < b {\n n * a\n } else {\n let base = n / m;\n let remain = n % m;\n (base * b) + std::cmp::min(remain * a, b)\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f528e626936ce20d05a61284cf2501a5", "src_uid": "faa343ad6028c5a069857a38fa19bb24", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (n, m, z) = {\n let r = getvec::();\n (r[0], r[1], r[2])\n };\n let gc = gcd(n, m);\n let lca = n * m / gc;\n println!(\"{}\", z / lca);\n}\nfn gcd(a: i64, b: i64) -> i64 {\n match b {\n 0i64 => a,\n _ => gcd(b, a % b),\n }\n}\n\n\n#[allow(dead_code)]\nfn next_line() -> String {\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok().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": "7569e6b4de46d075997395fdbdb4d886", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800.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 gcd(a: i64, b: i64) -> i64 { if b == 0 { a } else { gcd(b, a % b) } }\n\nfn main() {\n let mut sc = Scanner::new();\n let m: i64 = sc.cin();\n let n: i64 = sc.cin();\n let z: i64 = sc.cin();\n\n let a = z / (m * n / gcd(m, n));\n println!(\"{}\", a);\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": "fd4335b11de2226aeafc6ca45353ce27", "src_uid": "e7ad55ce26fc8610639323af1de36c2d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\npub fn get_years(weights: Vec) -> u32 {\n let mut years = 0;\n let mut limak = weights[0];\n let mut bob = weights[1];\n\n while limak <= bob {\n years += 1;\n limak *= 3;\n bob *= 2;\n }\n\n years\n}\n\npub fn solution() -> io::Result<()> {\n let mut weights = String::new();\n\n io::stdin().read_line(&mut weights)?;\n let numbers: Vec = weights\n .trim()\n .split(\" \")\n .map(|num| num.parse::().expect(\"Couldn't parse number\"))\n .collect();\n\n println!(\"{}\", get_years(numbers));\n Ok(())\n}\n\nfn main() {\n solution();\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2b141934a19aaf3b4dc164f62ea6184f", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\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}\nfn main() {\n let inp=read();\n let list: Vec<_>=inp.split_whitespace().collect();\n let mut b1=list[0].parse::().expect(\"Failed to parse\");\n let mut b2=list[1].parse::().expect(\"Failed to parse\");\n let mut years=0;\n while b2>=b1{\n b1*=3;\n b2*=2;\n years+=1\n }println!(\"{}\",years);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6ccf078f92247d4836a44d89a008cfb9", "src_uid": "a1583b07a9d093e887f73cc5c29e444a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// http://codeforces.com/problemset/problem/1/A\n\nuse std::io::{self, Read};\n\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_to_string(&mut buffer).unwrap();\n\n let input: Vec<_> = buffer.split_whitespace().collect();\n let n = input[0].parse().unwrap();\n let m = input[1].parse().unwrap();\n let a = input[2].parse().unwrap();\n\n println!(\"{}\", pave(n, m, a));\n}\n\nfn pave(n: u64, m: u64, a: u64) -> u64 {\n //cover n\n let cover_n = if n % a == 0 { n / a } else { (n / a) + 1 };\n let cover_m = if m % a == 0 { m / a } else { (m / a) + 1 };\n\n cover_m * cover_n\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "ffc1fce8e494edc4f8735215bc2a0d0b", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000.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 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!(\"{}\",c*n);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "59509bc0734c8a0220cf033488bab11f", "src_uid": "ef971874d8c4da37581336284b688517", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/520/A\nuse std::io;\nuse std::collections::HashSet;\n\nfn main() {\n io::stdin()\n .read_line(&mut String::new())\n .unwrap();\n\n let mut line = String::new();\n\n io::stdin()\n .read_line(&mut line)\n .unwrap();\n\n let mut line: String = line\n .trim()\n .to_string();\n\n line.make_ascii_lowercase();\n\n let mut letters = HashSet::new();\n\n for ch in line.chars() {\n letters.insert(ch);\n }\n\n let alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n\n let mut flag = true;\n\n for ch in alphabet.chars() {\n match letters.get(&ch) {\n Some(_) => continue,\n None => {\n flag = false;\n break;\n },\n }\n }\n\n if flag {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "d02958c5eb9d6a0ab3fd663518901caa", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashSet;\nuse 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: u32 = read(sin);\n let input: String = read(sin);\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": "da991b794893390ae3a73c6d4b80fe7c", "src_uid": "f13eba0a0fb86e20495d218fc4ad532d", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::BTreeMap;\r\n\r\nfn main() {\r\n let (n,x) : (usize, u128) = input_t();\r\n\r\n if n == x.to_string().len() { println!(\"0\"); return; }\r\n if x.to_string().chars().all(|c| c=='1' || c=='0') { println!(\"-1\"); return; }\r\n let mut memo = BTreeMap::new();\r\n println!(\"{}\", f(0,x,n,&mut memo));\r\n // eprintln!(\"{:?}\", memo);\r\n}\r\n\r\nfn f(c:usize, x:u128,n:usize,memo:&mut BTreeMap) -> usize {\r\n if let Some(&res) = memo.get(&x) { return res; }\r\n let mut t = x;\r\n let mut cnt = 0;\r\n while t!=0 { t/=10;cnt+=1;}\r\n if cnt >= n { return c; }\r\n\r\n // eprintln!(\"{}\", x);\r\n\r\n let mut res = std::usize::MAX >> 4;\r\n for i in 2..10 {\r\n if !x.to_string().chars().collect::>().contains(&((i+b'0') as char)) { continue }\r\n res = res.min(f(c, x*i as u128, n,memo) + 1);\r\n }\r\n\r\n memo.insert(x,res);\r\n res\r\n}\r\n\r\n\r\n#[allow(dead_code)] fn input() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } #[allow(dead_code)] fn input_t() -> (T, U) { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let s = s.trim().split_whitespace().collect::>(); (s[0].parse().ok().unwrap(), s[1].parse().ok().unwrap()) } #[allow(dead_code)] fn input_t3() -> (T1, T2, T3) { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let s = s.trim().split_whitespace().collect::>(); (s[0].parse().ok().unwrap(), s[1].parse().ok().unwrap(), s[2].parse().ok().unwrap()) } #[allow(dead_code)] fn input_t4() -> (T1, T2, T3, T4) { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let s = s.trim().split_whitespace().collect::>(); (s[0].parse().ok().unwrap(), s[1].parse().ok().unwrap(), s[2].parse().ok().unwrap(), s[3].parse().ok().unwrap()) } #[allow(dead_code)] fn input_t5() -> (T1, T2, T3, T4, T5) { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); let s = s.trim().split_whitespace().collect::>(); (s[0].parse().ok().unwrap(), s[1].parse().ok().unwrap(), s[2].parse().ok().unwrap(), s[3].parse().ok().unwrap(), s[4].parse().ok().unwrap()) } #[allow(dead_code)] fn input_vec() -> Vec { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().split_whitespace().map(|s| s.parse().ok().unwrap()).collect() }", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "cdef21ef43bfd5329a5e25c7e221a459", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\r\n\r\nuse std::cmp::*;\r\nuse std::collections::*;\r\nuse std::io::*;\r\nuse std::mem::*;\r\nuse std::str;\r\n\r\nfn main() {\r\n let n: usize = read();\r\n let x: u64 = read();\r\n let target = 10_u64.pow(n as u32 - 1);\r\n let mut seen = HashSet::new();\r\n let mut heap = BinaryHeap::new();\r\n heap.push((len(x), x));\r\n while let Some((score, x)) = heap.pop() {\r\n if !seen.insert(x) {\r\n continue;\r\n }\r\n if x >= target {\r\n println!(\"{}\", n as i32 - score);\r\n return;\r\n }\r\n let has = {\r\n let mut arr = [false; 10];\r\n let mut x = x;\r\n while x > 0 {\r\n arr[(x % 10) as usize] = true;\r\n x /= 10;\r\n }\r\n arr\r\n };\r\n for d in 2..=9 {\r\n if has[d] {\r\n let next = x * d as u64;\r\n heap.push((score - 1 + len(next) - len(x), next));\r\n }\r\n }\r\n }\r\n println!(\"-1\");\r\n}\r\n\r\nfn len(mut x: u64) -> i32 {\r\n let mut ans = 0;\r\n while x > 0 {\r\n x /= 10;\r\n ans += 1;\r\n }\r\n ans\r\n}\r\n\r\npub fn read() -> T {\r\n struct Tokens {\r\n buf: Vec,\r\n iter: str::SplitWhitespace<'static>,\r\n }\r\n static mut TOKENS: Option = None;\r\n\r\n let tokens = unsafe {\r\n TOKENS.get_or_insert_with(|| Tokens {\r\n buf: Vec::new(),\r\n iter: \"\".split_whitespace(),\r\n })\r\n };\r\n loop {\r\n if let Some(token) = tokens.iter.next() {\r\n return token.parse().ok().unwrap();\r\n }\r\n tokens.buf.clear();\r\n stdin().lock().read_until(b'\\n', &mut tokens.buf).unwrap();\r\n tokens.iter = unsafe {\r\n let s = str::from_utf8_unchecked(&tokens.buf);\r\n transmute(s.split_whitespace())\r\n };\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "dfs and similar", "shortest paths", "dp", "data structures"], "code_uid": "9fa82bb24214fb115b3a3a97051c7c98", "src_uid": "cedcc3cee864bf8684148df93804d029", "difficulty": 1700.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::{out, out_line};\nuse std::cmp::min;\nuse crate::math::modular::factorial::Factorial;\nuse crate::math::modular::primitive::ModularType;\n\ntype Mod = ModularType<1000000007>;\n\nfn solve(input: &mut Input, _test_case: usize) {\n let (n, k) = input.read();\n let mut ans = Mod::from(0);\n let factorials = Factorial::new(n);\n for i in 0..=min(k, n) {\n ans += factorials.combinations(n, i);\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 modular {\npub mod factorial {\nuse crate::math::modular::inverse::compute_inverse_up_to;\nuse crate::math::modular::primitive::Modular;\n\npub struct Factorial {\n fact: Vec,\n inverse_fact: Vec,\n}\n\nimpl Factorial\nwhere\n Mod: Modular,\n{\n pub fn new(n: usize) -> Self {\n let mut fact = vec![0.into(); n + 1];\n let mut inverse_fact = vec![0.into(); n + 1];\n let inv = compute_inverse_up_to(n);\n fact[0] = 1.into();\n inverse_fact[0] = 1.into();\n for i in 1..=n {\n fact[i] = fact[i - 1] * i.into();\n inverse_fact[i] = inverse_fact[i - 1] * inv[i];\n }\n Self { fact, inverse_fact }\n }\n\n pub fn combinations(&self, n: usize, k: usize) -> Mod {\n if k > n {\n 0.into()\n } else {\n self.fact[n] * self.inverse_fact[n - k] * self.inverse_fact[k]\n }\n }\n}\n}\npub mod inverse {\nuse crate::math::modular::primitive::Modular;\n\npub fn compute_inverse_up_to(n: usize) -> Vec\nwhere\n Mod: Modular,\n{\n let mut inv: Vec = vec![0.into(); n + 1];\n inv[1] = 1.into();\n for i in 2..=n {\n inv[i] = inv[Mod::MODULO as usize % i] * (Mod::MODULO as usize / i).into();\n inv[i] = -inv[i];\n }\n inv\n}\n}\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 + 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}\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": "4982fe3b92da019947aca6ec1f76a7aa", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "type Mod = ModInt1000000007;\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 let mut precalc = Binom::::new();\n input! {\n n: usize,\n k: usize\n }\n let k = k.min(n);\n let mut ans = Mod::raw(0);\n for i in 0..=k {\n ans += precalc.binom(n, i);\n }\n println!(\"{}\", ans);\n}\n\nstruct Binom {\n len: usize,\n inv: Vec,\n fact: Vec,\n ifact: Vec,\n n: Option,\n nprod: Vec,\n m: Option,\n mprod_n: usize,\n mprod: T\n}\n\n#[allow(dead_code)]\nimpl Binom {\n pub fn new() -> Self {\n assert_eq!(std::mem::size_of::(), 8);\n\n Self {\n len: 1,\n inv: vec![0, 1],\n fact: vec![T::raw(1), T::raw(1)],\n ifact: vec![T::raw(1), T::raw(1)],\n n: None,\n nprod: vec![],\n m: None,\n mprod_n: 0,\n mprod: T::raw(0)\n }\n }\n\n fn ensure(&mut self, idx: usize) {\n if idx > self.len {\n self.inv.reserve(idx - self.len);\n self.fact.reserve(idx - self.len);\n self.ifact.reserve(idx - self.len);\n let m = T::modulus() as usize;\n for i in self.len+1..=idx {\n let inv_i = self.inv[m % i] * (m - m / i) % m;\n self.inv.push(inv_i);\n self.fact.push(self.fact[i - 1] * T::from(i));\n self.ifact.push(self.ifact[i - 1] * T::raw(inv_i as u32));\n }\n self.len = idx;\n }\n }\n\n pub fn binom(&mut self, n: usize, m: usize) -> T {\n if m > n {\n return T::raw(0)\n }\n if m == 0 || m == n {\n return T::raw(1)\n }\n self.ensure(n);\n self.fact[n] * self.ifact[m] * self.ifact[n - m]\n }\n\n pub fn binom_n(&mut self, n: usize, m: usize) -> T {\n if m > n {\n return T::raw(0)\n }\n if m == 0 || m == n {\n return T::raw(1)\n }\n if n >= T::modulus() as usize {\n return self.binom_n(n % T::modulus() as usize, m);\n }\n if self.n != Some(n) {\n self.n = Some(n);\n self.nprod = vec![T::from(n)];\n }\n for i in self.nprod.len()..m {\n self.nprod.push(self.nprod[i - 1] * T::from(n - i));\n }\n self.ensure(m);\n self.nprod[m - 1] * self.ifact[m]\n }\n\n pub fn binom_m(&mut self, n: usize, m: usize) -> T {\n if m > n {\n return T::raw(0)\n }\n if m == 0 || m == n {\n return T::raw(1)\n }\n if n >= T::modulus() as usize {\n return self.binom_m(n % T::modulus() as usize, m);\n }\n if self.m != Some(m) || self.mprod_n > n + m || self.mprod_n + m < n {\n self.m = Some(m);\n self.mprod_n = n;\n self.mprod = ((n-m+1)..=n).map(T::from).product::();\n } else {\n while self.mprod_n < n {\n self.mprod_n += 1;\n self.mprod *= T::from(self.mprod_n);\n self.mprod /= T::from(self.mprod_n - m);\n }\n while self.mprod_n > n {\n self.mprod /= T::from(self.mprod_n);\n self.mprod *= T::from(self.mprod_n - m);\n self.mprod_n -= 1;\n }\n }\n self.ensure(m);\n self.mprod * self.ifact[m]\n }\n\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 ]) => {{\n let len = read_value!($reader, usize);\n read_value!($reader, [ $t ; len])\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 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 modint::*;\n\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "e4e2b1c34e33529a1aa52fead60e2441", "src_uid": "dc7b887afcc2e95c4e90619ceda63071", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let v: Vec = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect()\n };\n\n let min_num = v.iter().min().unwrap();\n if min_num % 2 == 0 {\n println!(\"Malvika\");\n } else {\n println!(\"Akshat\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e4be5d4b59f78fe3b03b30d0195b65cb", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\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\nfn main() {\n let mut scan = Scan::new();\n let a: usize = scan.next();\n let b: usize = scan.next();\n let c = a.min(b);\n println!(\"{}\", if c % 2 == 0 { \"Malvika\" } else { \"Akshat\"});\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b9fd1a30298ad3cfb67ec1bd0a7a5289", "src_uid": "a4b9ce9c9f170a729a97af13e81b5fe4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\n\n\nfn main () {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let mut it = input.split_whitespace();\n let n: i32= it.next().unwrap().parse().unwrap();\n let pos: i32 = it.next().unwrap().parse().unwrap();\n let l: i32 = it.next().unwrap().parse().unwrap();\n let r: i32 = it.next().unwrap().parse().unwrap();\n\n let rl = l != 1;\n let rr = r != n;\n let mut steps = 0;\n\n if rl && rr {\n steps = 2 + (pos - l).abs().min((pos - r).abs()) + (r - l);\n } else if !rl && rr {\n steps = 1 + (pos - r).abs();\n } else if !rr && rl{\n steps = 1 +(pos - l).abs();\n }\n\n println!(\"{}\", steps);\n\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a66de138b70bb6882266596d2d6c9ca4", "src_uid": "5deaac7bd3afedee9b10e61997940f78", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, prelude::*, BufWriter};\r\nuse std::str::FromStr;\r\n\r\ntype M = DynamicModInt;\r\n\r\n#[allow(unused)]\r\nfn solve2(scan: &mut Scanner, out: &mut W) {\r\n let n: usize = scan.next();\r\n M::set_modulus(scan.next());\r\n\r\n let mut dp = vec![M::zero(); n + 1];\r\n dp[1] = M::one();\r\n let mut sum = M::one();\r\n for i in 2..=n {\r\n let root = (i as f64).sqrt() as usize;\r\n for j in 2..=root {\r\n let delta = dp[i / j];\r\n dp[i] += delta;\r\n }\r\n for k in 1..i / root {\r\n let high = i / k;\r\n let low = i / (k + 1) + 1;\r\n if low <= high {\r\n let delta = dp[k] * M::from(high - low + 1);\r\n dp[i] += delta;\r\n }\r\n }\r\n\r\n dp[i] += sum;\r\n sum += dp[i];\r\n }\r\n writeln!(out, \"{}\", dp[n]).ok();\r\n}\r\n\r\nfn solve(scan: &mut Scanner, out: &mut W) {\r\n let n: usize = scan.next();\r\n DynamicModInt::set_modulus(scan.next());\r\n\r\n let mut dp = vec![M::zero(); n + 1];\r\n dp[1] = M::one();\r\n for i in 2..=n {\r\n if i == 2 {\r\n dp[2] = M::two();\r\n } else {\r\n let delta = M::two() * dp[i - 1];\r\n dp[i] += delta;\r\n let delta = dp[1];\r\n dp[i] += delta;\r\n }\r\n for j in (i + i..=n).step_by(i) {\r\n let delta = dp[i] - dp[i - 1];\r\n dp[j] += delta;\r\n }\r\n }\r\n writeln!(out, \"{}\", dp[n]).ok();\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 = BufWriter::new(stdout.lock());\r\n\r\n let tests = 1; // scan.next::();\r\n for _ in 0..tests {\r\n solve(&mut scan, &mut out);\r\n }\r\n}\r\n\r\n// {{{ Scanner\r\npub struct Scanner {\r\n reader: R,\r\n buffer: Vec,\r\n}\r\n\r\nimpl Scanner {\r\n pub fn new(reader: R) -> Self {\r\n Self {\r\n reader,\r\n buffer: vec![],\r\n }\r\n }\r\n\r\n pub fn next(&mut self) -> T {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok().unwrap();\r\n }\r\n let mut line = String::new();\r\n self.reader.read_line(&mut line).unwrap();\r\n self.buffer = line\r\n .split_ascii_whitespace()\r\n .rev()\r\n .map(String::from)\r\n .collect();\r\n }\r\n }\r\n\r\n pub fn next_vec(&mut self, n: usize) -> Vec {\r\n (0..n).map(|_| self.next()).collect()\r\n }\r\n}\r\n// }}}\r\n// {{{ DynamicModInt\r\nuse std::fmt;\r\nuse std::iter::{Product, Sum};\r\nuse std::ops::*;\r\n\r\n#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]\r\npub struct DynamicModInt(pub i32);\r\n\r\nimpl Default for DynamicModInt {\r\n fn default() -> Self {\r\n DynamicModInt(0)\r\n }\r\n}\r\n\r\nimpl fmt::Display for DynamicModInt {\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n write!(f, \"{}\", self.0)\r\n }\r\n}\r\n\r\nimpl DynamicModInt {\r\n pub fn set_modulus(modulus: i32) {\r\n *Self::modulus_ref() = modulus;\r\n }\r\n\r\n pub fn modulus() -> i32 {\r\n *Self::modulus_ref()\r\n }\r\n\r\n fn modulus_ref() -> &'static mut i32 {\r\n static mut MODULES: i32 = 0;\r\n return unsafe { &mut MODULES };\r\n }\r\n\r\n pub fn raw(val: i32) -> Self {\r\n DynamicModInt(val)\r\n }\r\n\r\n #[inline]\r\n fn canon(val: i32) -> Self {\r\n DynamicModInt(if val < 0 { val + Self::modulus() } else { val })\r\n }\r\n\r\n #[inline]\r\n pub fn zero() -> Self {\r\n DynamicModInt(0)\r\n }\r\n\r\n #[inline]\r\n pub fn one() -> Self {\r\n DynamicModInt(1)\r\n }\r\n\r\n #[inline]\r\n pub fn two() -> Self {\r\n DynamicModInt(2)\r\n }\r\n\r\n pub fn pow(self, n: u64) -> Self {\r\n let mut n = n;\r\n let mut res = Self::one();\r\n let mut a = self;\r\n while n > 0 {\r\n if n & 1 == 1 {\r\n res = res * a;\r\n }\r\n a = a * a;\r\n n >>= 1;\r\n }\r\n\r\n res\r\n }\r\n\r\n pub fn inv(self) -> Self {\r\n self.pow(Self::modulus() as u64 - 2)\r\n }\r\n}\r\n\r\nmacro_rules! from_bigger_int {\r\n ($($int:ident)*) => {$(\r\n impl From<$int> for DynamicModInt {\r\n fn from(val: $int) -> Self {\r\n Self::canon((val % Self::modulus() as $int) as i32)\r\n }\r\n }\r\n )*};\r\n}\r\nfrom_bigger_int!(u32 usize i64 u64 i128 u128);\r\n\r\nmacro_rules! from_smaller_int {\r\n ($($int: ident)*) => {$(\r\n impl From<$int> for DynamicModInt {\r\n fn from(val: $int) -> Self {\r\n Self::canon(val as i32 % Self::modulus())\r\n }\r\n }\r\n )*}\r\n}\r\nfrom_smaller_int!(i32 i16 u16 i8 u8);\r\n\r\nimpl Neg for DynamicModInt {\r\n type Output = Self;\r\n fn neg(self) -> Self {\r\n DynamicModInt(if self.0 == 0 {\r\n 0\r\n } else {\r\n Self::modulus() - self.0\r\n })\r\n }\r\n}\r\n\r\nimpl Add for DynamicModInt {\r\n type Output = Self;\r\n fn add(self, other: Self) -> Self {\r\n let s = self.0 + other.0;\r\n let m = Self::modulus();\r\n DynamicModInt(if s >= m { s - m } else { s })\r\n }\r\n}\r\n\r\nimpl Sub for DynamicModInt {\r\n type Output = Self;\r\n fn sub(self, other: Self) -> Self {\r\n Self::canon(self.0 - other.0)\r\n }\r\n}\r\n\r\nimpl Mul for DynamicModInt {\r\n type Output = Self;\r\n fn mul(self, other: Self) -> Self {\r\n let mul: u64 = (self.0 as u64 * other.0 as u64) % Self::modulus() as u64;\r\n DynamicModInt(mul as i32)\r\n }\r\n}\r\n\r\nimpl Div for DynamicModInt {\r\n type Output = Self;\r\n fn div(self, other: Self) -> Self {\r\n self * other.inv()\r\n }\r\n}\r\n\r\nimpl AddAssign for DynamicModInt {\r\n fn add_assign(&mut self, other: Self) {\r\n *self = *self + other;\r\n }\r\n}\r\n\r\nimpl SubAssign for DynamicModInt {\r\n fn sub_assign(&mut self, other: Self) {\r\n *self = *self - other;\r\n }\r\n}\r\n\r\nimpl MulAssign for DynamicModInt {\r\n fn mul_assign(&mut self, other: Self) {\r\n *self = *self * other;\r\n }\r\n}\r\n\r\nimpl DivAssign for DynamicModInt {\r\n fn div_assign(&mut self, other: Self) {\r\n *self = *self / other;\r\n }\r\n}\r\n\r\nimpl Sum for DynamicModInt {\r\n fn sum>(iter: I) -> Self {\r\n iter.fold(Self::zero(), Add::add)\r\n }\r\n}\r\n\r\nimpl Product for DynamicModInt {\r\n fn product>(iter: I) -> Self {\r\n iter.fold(Self::one(), Mul::mul)\r\n }\r\n}\r\n// }}}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "two pointers", "number theory"], "code_uid": "1e773fcb66f7bbd17da3eef615c76f37", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900.0, "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 #[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 #[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 sub_mod_raw(a, m-b, m)\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 let (r, c) = a.overflowing_sub(b);\n if c { r + m } else { r }\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(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]\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": "91e6f353360dcb1f17274728dd67840f", "src_uid": "77443424be253352aaf2b6c89bdd4671", "difficulty": 1900.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;\n\nfn main() {\n let mut first = String::new();\n let mut second = String::new();\n io::stdin().read_line(&mut first).unwrap();\n io::stdin().read_line(&mut second).unwrap();\n let fir: Vec = first.chars().filter(|c| c.is_digit(2)).collect();\n let sec: Vec = second.chars().filter(|c| c.is_digit(2)).collect();\n let mut out = vec!['_'; fir.len()];\n\n for i in 0..fir.len() {\n if fir[i] == sec[i] {\n out[i] = '0';\n } else {\n out[i] = '1';\n }\n }\n\n println!(\"{}\", out.iter().collect::());\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "056d1e2f5449df2de7e62d444e304176", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "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 first = iterator.next().unwrap().unwrap();\n let second = iterator.next().unwrap().unwrap();\n\n let first_vec: Vec = first.chars().collect();\n let second_vec: Vec = second.chars().collect();\n\n let mut result = Vec::new();\n\n for i in 0..first_vec.len() {\n if first_vec[i] != second_vec[i] {\n result.push(\"1\");\n } else {\n result.push(\"0\");\n }\n }\n\n println!(\"{}\", result.join(\"\"));\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6c999049fd1e0a7846042ea34aae56be", "src_uid": "3714b7596a6b48ca5b7a346f60d90549", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::SplitWhitespace;\n\nfn main() {\n let mut input: String = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let mut it_input: SplitWhitespace = input.split_whitespace();\n let n: i32 = it_input.next().unwrap().parse().unwrap();\n let m: i32 = it_input.next().unwrap().parse().unwrap();\n let r: i32 = it_input.next().unwrap().parse().unwrap();\n let mut n_input: String = String::new();\n let mut m_input: String = String::new();\n io::stdin().read_line(&mut n_input).unwrap();\n io::stdin().read_line(&mut m_input).unwrap();\n let mut it_n: SplitWhitespace = n_input.split_whitespace();\n let mut it_m: SplitWhitespace = m_input.split_whitespace();\n let mut n_min: i32 = 1001;\n let mut m_max: i32 = 0;\n for _i in 0..n {\n let a: i32 = it_n.next().unwrap().parse().unwrap();\n if a < n_min {\n n_min = a;\n }\n }\n for _i in 0..m {\n let a: i32 = it_m.next().unwrap().parse().unwrap();\n if a > m_max {\n m_max = a;\n }\n }\n if r / n_min * m_max + r % n_min > r {\n print!(\"{}\", r / n_min * m_max + r % n_min);\n } else {\n print!(\"{}\", r);\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "b89a723fc61831e0732617e6044d380c", "src_uid": "42f25d492bddc12d3d89d39315d63cb9", "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 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 m: usize = scan.next();\n let r: usize = scan.next();\n let buy: usize = scan.next_n::(n).into_iter().min().unwrap();\n let sell: usize = scan.next_n::(m).into_iter().max().unwrap();\n println!(\n \"{}\",\n if buy >= sell {\n r\n } else {\n r % buy + r / buy * sell\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": ["greedy", "implementation"], "code_uid": "2c0e2cb630084cbe9c045f82bf11be5f", "src_uid": "42f25d492bddc12d3d89d39315d63cb9", "difficulty": 800.0, "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 より\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 modint::*;\nuse precalc::*;\n\ntype M = ModInt;\n\nfn run() {\n input! {\n p: u64,\n k: u64,\n }\n let ans = if k == 0 {\n M::from(p).pow(p - 1)\n } else if k == 1 {\n M::from(p).pow(p)\n } else {\n let mut phi = p - 1;\n let mut m = phi;\n for d in 2.. {\n if d * d > m {\n break;\n }\n if m % d == 0 {\n while m % d == 0 {\n m /= d;\n }\n while phi % d == 0 && mod_pow(k, phi / d, p) == 1 {\n phi /= d;\n }\n }\n }\n if m > 1 && mod_pow(k, phi / m, p) == 1 {\n phi /= m;\n }\n M::from(p).pow((p - 1) / phi)\n };\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math", "combinatorics", "dsu", "number theory"], "code_uid": "587d59b41ddde8bd916b54e01203166b", "src_uid": "580bf65af24fb7f08250ddbc4ca67e0e", "difficulty": 1800.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 (_, d) = read!(usize, i64);\n let mut A = read![[i64]];\n A.sort();\n\n let mut l = 0;\n let mut r = 0;\n let mut ma = 0;\n while l < A.len() {\n while r < A.len() && A[r] - A[l] <= d {\n r += 1;\n }\n\n ma = max(ma, r - l);\n l += 1;\n }\n\n println!(\"{}\", A.len() - ma);\n return;\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "4f028d46857b255dc3486dab4ca880e6", "src_uid": "6bcb324c072f796f4d50bafea5f624b2", "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!(u32);\n let m = parse_line!(u32);\n if n > 30 {\n writeln!(writer, \"{}\", m).unwrap();\n }else{\n writeln!(writer, \"{}\", m % (1 << n)).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": "3415023ce4744e679b4f71864564fb33", "src_uid": "c649052b549126e600691931b512022f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::Read;\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!(u64);\n let m = get!(u64);\n \n if n > 63 {\n println!(\"{}\", m);\n } else {\n let x = (1 << n) - 1;\n println!(\"{}\", m & x);\n }\n \n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "b38ebf1fb921e794314fe9ecef5e115e", "src_uid": "c649052b549126e600691931b512022f", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, Write};\nuse std::vec::Vec;\nuse std::string::String;\n\nstruct Point {\n x: i8,\n y: i8,\n}\n\nfn get_line() -> String {\n let mut line: String = String::new();\n io::stdin().read_line(&mut line).expect(\"Failed to get input line\");\n return line.trim().to_string();\n}\n\nfn main() {\n let target: Point = Point{\n x: 2,\n y: 2\n };\n let mut number_one: Point = Point{\n x: 2,\n y: 2,\n };\n for i in 0..5 {\n let line: String = get_line();\n let numbers: Vec = line.split_whitespace().map(\n |n| n.parse().unwrap()\n ).collect();\n for j in 0..5 {\n if numbers[j] == 1 {\n number_one = Point{\n x: (i as i8),\n y: (j as i8),\n };\n }\n }\n }\n let mut result: i8 = 0;\n result += (number_one.x - target.x).abs();\n result += (number_one.y - target.y).abs();\n println!(\"{}\", result);\n\n io::stdout().flush().unwrap();\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ba20a246ee42c089dabab7ef979254a2", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn main() {\n let inp = read_input();\n\n let index = inp.iter().position(|&i| i == 1).unwrap() as i32;\n let ans = (2 - ((index as f64 / 5 as f64).floor()) as i32).abs() + (2 - (index % 5)).abs();\n\n println!(\"{}\", ans);\n}\n\nfn read_input() -> Vec {\n let mut s = String::new();\n std::io::stdin().read_to_string(&mut s).unwrap();\n s.split_whitespace().map(|i| i.parse().unwrap()).collect()\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "396b2050d7974f7cc1eaa2502470b61e", "src_uid": "8ba7cedc3f6ae478a0bb3f902440c8e9", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{BufReader, BufRead};\n\nfn main() -> Result<(), Box> {\n let line = BufReader::new(std::io::stdin())\n .lines()\n .map(Result::unwrap)\n .skip(1)\n .next()\n .unwrap();\n\n let mut days = line.chars();\n let mut location = days.next().unwrap();\n let mut seattle_to_sf = 0;\n let mut sf_to_seattle = 0;\n for day in days {\n match (location, day) {\n | ('S', 'F') => seattle_to_sf += 1,\n | ('F', 'S') => sf_to_seattle += 1,\n | _ => (),\n }\n location = day;\n }\n\n println!(\"{}\", if seattle_to_sf > sf_to_seattle { \"YES\" } else { \"NO\" });\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f9b3ede5730fba2b36132c6f5efe4f9d", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "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 input.clear();\n\n io::stdin().read_line(&mut input)?;\n\n let s = input.trim();\n\n let mut diff = 0;\n\n for i in 0..n - 1 {\n let t = &s[i..i + 2];\n if t == \"SF\" {\n diff += 1;\n } else if t == \"FS\" {\n diff -= 1;\n }\n }\n\n if diff > 0 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "093e2580c6c90067d7ab194d5da55b77", "src_uid": "ab8a2070ea758d118b3c09ee165d9517", "difficulty": 800.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 \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!(i64);\n let m = read!(i64);\n \n let ans = if m == 1 {n-1} else {n * (m-1)};\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "1bfa96042ea012dc60fe92eb9701e6b3", "src_uid": "a91aab4c0618d036c81022232814ef44", "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 s = s.trim().to_string();\n let n = s.len();\n let mut flag = 1; // 0,一般,1,开头, 2,中间\n let mut i = 0;\n while i < n {\n if i+2 < n && s[i..i+3] == String::from(\"WUB\") {\n i += 3;\n if flag == 1 {\n \n } else if flag == 2 {\n \n } else { // flag == 0\n flag = 2;\n print!(\" \");\n }\n }\n else {\n flag = 0;\n print!(\"{}\", s.as_bytes()[i] as char);\n i += 1;\n }\n }\n}", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "ba2841b824839ac3a0d22ffaa3b3c386", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900.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 x: String = read(sin);\n\n let ans: Vec<&str> = x.split(\"WUB\").filter(|x| *x != \"\").collect();\n\n println!(\"{}\", ans.join(\" \"));\n}\n", "lang_cluster": "Rust", "tags": ["strings"], "code_uid": "0e09b22e5320d778e1c9a6d748365ef4", "src_uid": "edede580da1395fe459a480f6a0a548d", "difficulty": 900.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)*) => (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![vec![0; m]; n];\n let mut g = g0;\n for i in 0..n*m {\n let a = i/m;\n let b = i%m;\n hs[a][b] = g;\n g = (g * x + y) % z;\n }\n\n // debug!(n, m, a, b, hs);\n\n let mut min_table = vec![];\n\n // スライド最小値\n use std::collections::VecDeque;\n for i in 0..n {\n let mut q: VecDeque<(usize,usize)> = VecDeque::new();\n let mut row_mins = vec![];\n for j in 0..m {\n let h = hs[i][j];\n\n while q.len() > 0 {\n let (x, y) = *q.back().unwrap();\n if h <= hs[x][y] {\n q.pop_back();\n } else {\n break;\n }\n }\n q.push_back((i, j));\n\n if j < b-1 {\n continue;\n }\n if j >= b {\n let (_,y) = *q.front().unwrap();\n if y == j-b {\n q.pop_front();\n }\n }\n\n // debug!(i, j, q);\n let (x,y) = *q.front().unwrap();\n row_mins.push(hs[x][y]);\n }\n min_table.push(row_mins);\n }\n\n let mut ans = 0;\n for j in 0..m-b+1 {\n let mut q: VecDeque<(usize,usize)> = VecDeque::new();\n for i in 0..n {\n let h = min_table[i][j];\n\n while q.len() > 0 {\n let (x, y) = *q.back().unwrap();\n if h <= min_table[x][y] {\n q.pop_back();\n } else {\n break;\n }\n }\n q.push_back((i, j));\n\n if i < a-1 {\n continue;\n }\n if i >= a {\n let (x,_) = *q.front().unwrap();\n if x == i-a {\n q.pop_front();\n }\n }\n\n let (x,y) = *q.front().unwrap();\n ans += min_table[x][y];\n\n }\n }\n puts!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "ffbebbed2954a71b1d9b844d907b8852", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn sliding_minimum_elements(a: &[u64], l: usize) -> Vec {\n assert!(a.len() >= l && l > 0);\n let mut d = std::collections::VecDeque::<(u64, usize)>::new();\n for (i, &a) in a[..(l - 1)].iter().enumerate() {\n while let Some(p) = d.back() {\n if p.0 >= a {\n d.pop_back();\n } else {\n break;\n }\n }\n d.push_back((a, i));\n }\n let mut b = Vec::with_capacity(a.len() - l + 1);\n for (i, &a) in a[(l - 1)..].iter().enumerate() {\n while let Some(p) = d.back() {\n if p.0 >= a {\n d.pop_back();\n } else {\n break;\n }\n }\n d.push_back((a, i + l - 1));\n if d.front().unwrap().1 < i {\n d.pop_front();\n }\n b.push(d.front().unwrap().0);\n }\n b\n}\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 m: usize = it.next().unwrap().parse().unwrap();\n let a: usize = it.next().unwrap().parse().unwrap();\n let b: 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 h = vec![vec![0; m]; n];\n for i in 0..n {\n for j in 0..m {\n h[i][j] = g;\n g = (g * x + y) % z;\n }\n }\n for h in &mut h {\n *h = sliding_minimum_elements(h, b);\n }\n let mut ans = 0u64;\n for j in 0..(m + 1 - b) {\n let mut c = vec![0; n];\n for i in 0..n {\n c[i] = h[i][j];\n }\n ans += sliding_minimum_elements(&c, a).into_iter().fold(0, |s, a| s + a);\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "data structures"], "code_uid": "a3fa6c6f348e02ddced1ecb68125779f", "src_uid": "4618fbffb2b9d321a6d22c11590a4773", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin Matrix ----------\n\n#[allow(dead_code)]\nmod matrix {\n use std::ops::Add;\n use std::ops::Mul;\n pub trait SemiRing: Add + Mul + Copy {\n fn zero() -> Self;\n fn one() -> Self;\n }\n #[derive(Clone)]\n pub struct SquareMatrix {\n n: usize,\n a: Vec,\n }\n impl SquareMatrix {\n pub fn zero(n: usize) -> Self {\n let z = T::zero();\n SquareMatrix {\n n: n,\n a: vec![z; n * n],\n }\n }\n pub fn identity(n: usize) -> Self {\n let mut m = Self::zero(n);\n for i in 0..n {\n m.a[i * n + i] = T::one();\n }\n m\n }\n pub fn set_at(&mut self, i: usize, j: usize, v: T) {\n debug_assert!(i < self.n && j < self.n);\n self.a[i * self.n + j] = v;\n }\n pub fn get_at(&self, i: usize, j: usize) -> T {\n debug_assert!(i < self.n && j < self.n);\n self.a[i * self.n + j]\n }\n pub fn matmul(l: Self, r: Self) -> Self {\n l * r\n }\n }\n impl Add for SquareMatrix {\n type Output = Self;\n fn add(self, rhs: Self) -> Self {\n debug_assert!(self.n == rhs.n);\n let n = self.n;\n let mut c = Self::zero(n);\n for i in 0..(n * n) {\n c.a[i] = self.a[i] + rhs.a[i];\n }\n c\n }\n }\n impl Mul for SquareMatrix {\n type Output = Self;\n fn mul(self, rhs: Self) -> Self {\n debug_assert!(self.n == rhs.n);\n let n = self.n;\n let mut c = Self::zero(n);\n for i in 0..n {\n for k in 0..n {\n let a = self.a[i * n + k];\n for (x, y) in c.a[(i * n)..((i + 1) * n)].iter_mut().zip(rhs.a[(k * n)..((k + 1) * n)].iter()) {\n *x = *x + a * *y;\n }\n }\n }\n c\n }\n }\n}\n\n// ---------- end Matrix ----------\n// ---------- begin ModInt ----------\n\n//https://github.com/kenkoooo/competitive-programming-rs/blob/master/src/math/mod_int.rs\n//を参考にしています\n#[allow(dead_code)]\nmod modint {\n pub const MOD: u32 = 1000000000 + 7;\n use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};\n #[derive(Clone, Copy)]\n pub struct ModInt(pub T);\n pub type Num = u32;\n impl Add> for ModInt {\n type Output = ModInt;\n fn add(self, other: ModInt) -> ModInt {\n let mut d = self.0 + other.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n }\n impl AddAssign> for ModInt {\n fn add_assign(&mut self, other: ModInt) {\n *self = *self + other;\n }\n }\n impl Sub> for ModInt {\n type Output = ModInt;\n fn sub(self, other: ModInt) -> ModInt {\n let mut d = self.0 + MOD - other.0;\n if d >= MOD {\n d -= MOD;\n }\n ModInt(d)\n }\n }\n impl SubAssign> for ModInt {\n fn sub_assign(&mut self, other: ModInt) {\n *self = *self - other;\n }\n }\n impl Mul> for ModInt {\n type Output = ModInt;\n fn mul(self, other: ModInt) -> ModInt {\n ModInt(((self.0 as u64) * (other.0 as u64) % (MOD as u64)) as u32)\n }\n }\n impl MulAssign> for ModInt {\n fn mul_assign(&mut self, other: ModInt) {\n *self = *self * other;\n }\n }\n impl Div for ModInt {\n type Output = ModInt;\n fn div(self, other: Num) -> ModInt {\n self * ModInt(other).pow(MOD - 2)\n }\n }\n impl Div> for ModInt {\n type Output = ModInt;\n fn div(self, other: ModInt) -> ModInt {\n self * other.pow(MOD - 2)\n }\n }\n impl DivAssign> for ModInt {\n fn div_assign(&mut self, other: ModInt) {\n *self = *self / other;\n }\n }\n impl Neg for ModInt {\n type Output = ModInt;\n fn neg(self) -> ModInt {\n ModInt(if self.0 == 0 { 0 } else { MOD - self.0 })\n }\n }\n impl ModInt {\n pub fn new(v: u32) -> ModInt {\n ModInt(v % MOD)\n }\n pub fn pow(self, mut n: u32) -> ModInt {\n let mut t = ModInt::new(1);\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 }\n pub struct Precalc {\n n: usize,\n inv: Vec>,\n fact: Vec>,\n ifact: Vec>,\n }\n impl Precalc {\n pub fn new(n: usize) -> Precalc {\n let mut inv = vec![ModInt(1); n + 1];\n let mut fact = vec![ModInt(1); n + 1];\n let mut ifact = vec![ModInt(1); n + 1];\n for i in 1..(n + 1) {\n if i > 2 {\n inv[i] = -inv[(MOD as usize) % i] * ModInt(MOD / (i as u32));\n }\n fact[i] = ModInt(i as u32) * fact[i - 1];\n ifact[i] = inv[i] * ifact[i - 1];\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 inv(self, x: usize) -> ModInt {\n self.inv[x]\n }\n pub fn ifact(self, x: usize) -> ModInt {\n self.ifact[x]\n }\n pub fn comb(self, n: usize, k: usize) -> ModInt {\n if !(k <= n) {\n return ModInt(0);\n }\n self.fact[n] * self.ifact[k] * self.ifact[n - k]\n }\n }\n use std;\n impl 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// ---------- end ModInt ----------\n\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\nuse matrix::SquareMatrix;\nuse modint::ModInt;\n\nimpl matrix::SemiRing for ModInt {\n fn one() -> Self {ModInt(1)}\n fn zero() -> Self {ModInt(0)}\n}\n\nfn run() {\n input! {\n n: u64,\n m: usize,\n }\n type M = SquareMatrix>;\n let mut t = M::identity(m);\n let mut s = M::zero(m);\n for i in 1..m {\n s.set_at(i - 1, i , ModInt(1));\n }\n s.set_at(m - 1, 0, ModInt(1));\n s.set_at(m - 1, m - 1, ModInt(1));\n let mut n = n;\n while n > 0 {\n if (n & 1) == 1 {\n t = t * s.clone();\n }\n s = s.clone() * s;\n n >>= 1;\n }\n let ans = t.get_at(m - 1, m - 1);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "dp"], "code_uid": "271738982d53e269a1ffd762e27227bf", "src_uid": "e7b9eec21d950f5d963ff50619c6f119", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::str::FromStr;\nfn read_int() -> usize {\n let stdin = std::io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line).unwrap();\n usize::from_str(&line.trim_end()).unwrap()\n}\n\nfn good_numbers(n: usize) -> usize {\n let mut set = std::collections::HashSet::new();\n for i in 1..=n {\n if i * i > n {\n break;\n }\n set.insert(i * i);\n if i * i * i > n {\n continue;\n }\n set.insert(i * i * i);\n }\n return set.len()\n}\nfn main() {\n let test_cases = read_int();\n\n for _ in 0..test_cases {\n let n = read_int();\n println!(\"{}\", good_numbers(n));\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "9e17f20414a431300c2307cd65a086a4", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#[rustfmt::skip]\n#[allow(unused_imports)]\nuse std::{cmp::*, collections::*, fmt::Debug, io::*, iter::{self, *}, ops::{self, *}, str::{self, *}};\nmacro_rules!v{($(:$t:ty)?=$e:expr)=>{$e$(as$t)?};([$d:expr]$(:$t:ty)?)=>{Vec::$(<$t>::)?with_capacity($d)};([]$(:$t:ty)?)=>{Vec::$(<$t>::)?new()};([$d:expr]$($s:tt)+)=>{vec![v!($($s)+);$d]};}\n#[rustfmt::skip]\nstruct StdinReader { buf: Vec, pos: usize, x: *mut Stdin, q: StdinLock<'static>, }\n#[rustfmt::skip]\n#[allow(dead_code)]\nimpl StdinReader {\n fn new() -> Self { let x = Box::into_raw(Box::new(stdin()));let q = unsafe { &*x }.lock();Self { x, q, buf: v!([]), pos: 0, } }\n fn cache_line(&mut self) -> bool { self.buf.clear();self.pos = 0;self.q.read_until(b'\\n', &mut self.buf).unwrap_or(0) > 0 }\n fn b(&mut self) -> Option { if self.pos == self.buf.len() && !self.cache_line() { return None; }self.pos += 1;Some(self.buf[self.pos - 1]) }\n fn bs(&mut self) -> Vec { let mut s = v!([10]);let mut f = false;while let Some(c) = self.b() { if !c.is_ascii_whitespace() { s.push(c);f = true; } else if f { break; } }s }\n fn p(&mut self) -> T where T::Err: Debug, { let w = self.bs();str::from_utf8(w.as_ref()).unwrap().parse::().unwrap() }\n fn u(&mut self) -> usize { self.p() }\n fn i(&mut self) -> i32 { self.p() }\n}\n#[rustfmt::skip]\nimpl Drop for StdinReader { fn drop(&mut self) { unsafe { Box::from_raw(self.x) }; } }\n#[rustfmt::skip]\nfn stdio() -> (StdinReader, BufWriter) { (StdinReader::new(), BufWriter::new(stdout())) }\n\nfn main() {\n let (mut rin, mut rout) = stdio();\n let n = rin.u();\n let mut t = Vec::with_capacity(n);\n let mut z = vec![0; n];\n (0..n).for_each(|_| t.push(rin.u()));\n let m = *t.iter().max().unwrap();\n let mut h = HashSet::with_capacity(n);\n let (mut f2, mut f3) = (true, true);\n for i in 1..=31622usize {\n let e2 = i.pow(2);\n if e2 > m {\n f2 = false;\n }\n if f2 {\n h.insert(e2);\n }\n\n let e3 = i.pow(3);\n if e3 > m {\n f3 = false;\n }\n if f3 {\n h.insert(i.pow(3));\n }\n\n if !f2 && !f3 {\n break;\n };\n }\n\n for &v in h.iter() {\n for (i, &tt) in t.iter().enumerate() {\n if v <= tt {\n z[i] += 1;\n }\n }\n }\n (0..n).for_each(|i| writeln!(rout, \"{}\", z[i]).unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "a2ce614917f6272d30c030d7f072e3ba", "src_uid": "015afbefe1514a0e18fcb9286c7b6624", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() -> io::Result<()> {\n \n let mut input = String::new();\n\n io::stdin().read_line(&mut input)?;\n let k: usize = input.trim().split(\" \").last().unwrap().parse().unwrap();\n\n input.clear();\n io::stdin().read_line(&mut input)?;\n let scores: Vec = input.trim().split(\" \").map(|s| s.parse().unwrap()).collect();\n let threshold = scores[k - 1];\n\n let mut count = 0;\n for score in scores {\n if (score == 0) || (score < threshold) {\n break;\n }\n count += 1;\n }\n\n println!(\"{}\", count);\n \n return Ok(());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "82a071f66567385533b16b72391b53fd", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "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);\n let line = line.trim();\n let v: Vec = line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect();\n let n = v[1] as usize;\n\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n let line = line.trim();\n let v: Vec = line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect();\n\n let mut ret = 0;\n for i in 0..v.len() {\n if v[i] == 0 {\n break;\n }\n if i >= n && v[i] != v[n - 1] {\n break;\n }\n ret += 1;\n }\n println!(\"{}\", ret);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "12893c9b9df77e4fe8fd2c6824106146", "src_uid": "193ec1226ffe07522caf63e84a7d007f", "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 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": ["strings", "dp"], "code_uid": "faa077e2e1827c60ee6f79475debe4f4", "src_uid": "ae5d21919ecac431ea7507cb1b6dc72b", "difficulty": 1900.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).unwrap();\n let a1: i128 = input.trim().parse().unwrap();\n\n input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let a2: i128 = input.trim().parse().unwrap();\n\n input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let k1: i128 = input.trim().parse().unwrap();\n\n input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let k2: i128 = input.trim().parse().unwrap();\n\n input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let n: i128 = input.trim().parse().unwrap();\n\n if n >= ((a1 * k1) + (a2 * k2)) {\n println!(\"{} {}\", a1 + a2, a1 + a2);\n return;\n }\n\n // Find minimum\n let minimum = if n - (a1 * (k1 - 1)) - (a2 * (k2 - 1)) > 0 {\n n - (a1 * (k1 - 1)) - (a2 * (k2 - 1))\n } else {\n 0\n };\n\n // Find maximum\n let mut maximum: i128 = 0;\n let mut cards_left = n;\n if k1 < k2 {\n cards_left -= a1 * k1;\n maximum += if cards_left >= 0 { a1 + (cards_left / k2) } else { n / k1 };\n } else {\n cards_left -= a2 * k2;\n maximum += if cards_left >= 0 { a2 + (cards_left / k1) } else { n / k2 };\n }\n\n println!(\"{} {}\", minimum, maximum);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "1c412aa5a768f665f5d9ab8310e9c202", "src_uid": "2be8e0b8ad4d3de2930576c0209e8b91", "difficulty": 1000.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\nuse std::cmp::{max, min};\n\nfn run() {\n input! {\n a: i32,\n b: i32,\n x: i32,\n y: i32,\n n: i32,\n }\n let mut f = n;\n let mut g = 0;\n for i in 0..=n {\n if x * a < i || y * b < n - i{\n continue;\n }\n let mut p = 0;\n let mut q = 0;\n if (x - 1) * a < i {\n p += i - (x - 1) * a;\n }\n q += i / x;\n if (y - 1) * b < n - i {\n p += n - i - (y - 1) * b;\n }\n q += (n - i) / y;\n f = min(f, p);\n g = max(g, q);\n }\n println!(\"{} {}\", f, g);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "628632355947997b935e2f0b5febbcff", "src_uid": "2be8e0b8ad4d3de2930576c0209e8b91", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::error::Error;\nuse std::io::{self, Read};\n\nfn main() -> Result<(), Box> {\n let mut stdin = io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line)?;\n let num_str = line.trim();\n let num: u64 = num_str.parse()?;\n let num_nines = num_str.len() - 1;\n let remaining_num = num - (10_u64.pow(num_nines as u32) - 1);\n let rem_digit_sum: u32 = remaining_num.to_string().into_bytes().into_iter().map(|c| (c - b'0') as u32).sum();\n println!(\"{}\", num_nines as u32 * 9 + rem_digit_sum);\n\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "9a636fdc66acfd25d2a26f572ad1a10a", "src_uid": "5c61b4a4728070b9de49d72831cd2329", "difficulty": 1100.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<_> = buffer.split_whitespace().map(|x| x.parse::().unwrap() ).collect();\n let n = arr[0];\n let mut d = 0;\n let mut h = n;\n while h > 0 {\n d += 1;\n h = h / 10;\n }\n use std::cmp;\n let mut a = 0;\n 'outer: for i in 0..d {\n // println!(\"{}\",a);\n let mut r = 0;\n for j in 0..10 {\n let y = j * 10u64.pow(i);\n if a + y <= n {\n r = cmp::max(a + y, r);\n // println!(\"{}\",r);\n }\n }\n a = r;\n }\n let mut b = n - a;\n // println!(\"{} {}\", a, b);\n let mut ans = 0;\n while a > 0 {\n ans += a % 10;\n a = a / 10;\n }\n while b > 0 {\n ans += b % 10;\n b = b / 10;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "2c5069741b0ce3f690abe026d562e150", "src_uid": "5c61b4a4728070b9de49d72831cd2329", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nstruct Reader(Vec, usize);\n\nimpl Reader {\n fn new(r: &mut io::Read) -> Reader {\n let mut b = Vec::new();\n r.read_to_end(&mut b);\n \n Reader(b, 0)\n }\n\n fn read_byte(&mut self) -> u8 {\n self.1 += 1;\n self.0[self.1 - 1]\n }\n\n fn read_string(&mut self) -> String {\n for i in self.1..self.0.len() {\n match self.0[i] {\n b' ' | b'\\t' | b'\\n' | b'\\r' => {}\n _ => { \n self.1 = i;\n break; \n }\n }\n }\n \n let old_pos = self.1;\n for i in self.1..self.0.len() {\n match self.0[i] {\n b' ' | b'\\t' | b'\\n' | b'\\r' => {\n self.1 = i;\n break;\n }\n _ => {}\n } \n }\n String::from_utf8(self.0[old_pos..self.1].to_vec()).unwrap()\n }\n \n fn read_int(&mut self) -> i32 {\n self.read_string().parse().unwrap()\n }\n}\n\npub fn main() {\n let mut r = Reader::new(&mut io::stdin());\n let n = r.read_int();\n let k = r.read_int();\n println!(\"{}\", (2 * n + k - 1) / k + (5 * n + k - 1) / k + (8 * n + k - 1) / k);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "07518716e6a4e85588b2376375586e58", "src_uid": "d259a3a5c38af34b2a15d61157cc0a39", "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, min, max) = parse_line!(usize, usize, i64, i64);\n let t = parse_line_to_vec!(i64);\n let low = t.iter().fold(std::i64::MAX, |x, &y| std::cmp::min(x, y));\n let high = t.iter().fold(std::i64::MIN, |x, &y| std::cmp::max(x, y));\n let mut fail = low < min || high > max;\n fail |= (low != min && high != max && n - m < 2) ||\n ((low != min || high != max) && n - m < 1);\n if fail {\n println!(\"Incorrect\")\n }else{\n println!(\"Correct\")\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": "caa8f1d3d1217e995f402fef699fb338", "src_uid": "99f9cdc85010bd89434f39b78f15b65e", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\nuse std::cmp::{max, min};\nuse 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 #[allow(dead_code)]\n fn read_vec(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.t()).collect()\n }\n\n #[allow(dead_code)]\n fn read_str(&mut self) -> Vec {\n self.t::().into_bytes()\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 let n: usize = scan.t();\n\n let mut res = ModGroup::from_usize(1);\n for _ in 1..n {\n res = res * res * 16;\n }\n res = res * 6;\n\n writeln!(out, \"{}\", res.val)?;\n\n io::Result::Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "868018fee53a5b7206c22c59520c9844", "src_uid": "5144b9b281ea4087d8334d91c3c8bda4", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, dead_code)]\n\nuse std::io;\nuse std::{io::*, io::prelude::*, str};\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 MOD: u64 = 1000_000_007;\n\nfn solve(scan: &mut Scanner, out: &mut BufWriter) -> io::Result<()> {\n let n = scan.next::();\n let mut p = 1;\n for _ in 0..n-1 {\n p = (p * p * 4) % MOD\n }\n p = (p * p * 6) % MOD;\n writeln!(out, \"{}\", p)\n}\n \nfn main() -> io::Result<()> {\n let mut scan = Scanner::default();\n let mut out = &mut BufWriter::new(stdout());\n\n solve(&mut scan, &mut out)?;\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "ed3b7ef4abd1860a0b7203980b164787", "src_uid": "5144b9b281ea4087d8334d91c3c8bda4", "difficulty": 1300.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 sum_1_through_n(n : u64) -> u64 {\n // Do the division before the multiplication\n // so that the result does not overflow sooner.\n if (n % 2) == 0 {\n (n / 2) * (n + 1)\n } else {\n n * ((n + 1) / 2)\n }\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut knw = vec![];\n read_ts(&stdin, &mut knw);\n let k = knw[0];\n let n = knw[1];\n let w = knw[2];\n let needed_amount = k * sum_1_through_n(w);\n if needed_amount > n {\n let x = needed_amount - n;\n println!(\"{}\", x);\n } else {\n println!(\"{}\", 0);\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "667fab44e08c438cc5b590a68602b466", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let v: Vec = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n line.trim().split(\" \").map(|s| s.parse::().unwrap()).collect()\n };\n\n let (first, total, n) = (v[0], v[1], v[2]);\n println!(\"{:?}\",\n std::cmp::max((0..n).fold(0, |total, i| total + first * (i + 1)) - total,\n 0));\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "a180b17e774b133fbbab78696d610c25", "src_uid": "e87d9798107734a885fd8263e1431347", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead};\n\nconst M: u64 = 998244353;\n\nfn pow(n: u64, p: u64) -> u64 {\n let mut q = p;\n let mut r = n;\n let mut result = 1;\n while q > 0 { \n if q % 2 == 1 { \n result = result * r % M;\n } \n r = r * r % M;\n q >>= 1;\n }\n result\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut lines = stdin.lock().lines();\n let xs: Vec = lines.next().unwrap().unwrap().split(' ').map(|x| x.parse().unwrap()).collect();\n let (n, m) = (xs[0], xs[1]);\n if n == 2 || m == 2 {\n println!(\"0\");\n return;\n }\n let mut prods: Vec = vec![0; (m + 1) as usize];\n prods[0] = 1;\n for i in 1..=m {\n prods[i as usize] = i * prods[(i-1) as usize] % M;\n }\n let mut ans: u64 = 0;\n for pivot in (n-1)..=m {\n let n_pairs = pivot - 1;\n let n_cands = (pivot - 2) as usize;\n let choose = (n - 3) as usize;\n let comb = (prods[n_cands] * pow(prods[n_cands - choose], M - 2) % M) * pow(prods[choose], M - 2) % M;\n ans = (ans + (n_pairs * comb % M) * pow(2, choose as u64) % M) % M;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "5a26fc53e1e8f531391583047b8ed0e2", "src_uid": "28d6fc8973a3e0076a21c2ea490dfdba", "difficulty": 1700.0, "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 k: i32 = tokens[1].parse().unwrap();\n\n let mut v = Vec::new();\n for value in Reader::read_tokens().unwrap(){\n v.push(value.parse::().unwrap());\n }\n let mut ans = 0;\n let mut l = 0;\n let mut r = v.len() - 1;\n while l <= r {\n let mut L = l;\n let mut R = r;\n if v[L] <= k {\n L += 1;\n ans += 1;\n }\n if v[R] <= k && R > L {\n R -= 1;\n ans += 1;\n }\n if L == l && R == r{\n break;\n }\n l = L;\n r = R;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "008cbb893913250be3b9fd9789d151e1", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "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 let k = flv[1];\n\n let next_line = lines.next()\n .unwrap() // Option { Some(Result), None }\n .unwrap(); // Result { Ok(String), Err(io::Error) }\n\n let slv: Vec<_> = next_line\n .trim()\n .split(' ')\n .map(|n| {\n n.parse::().unwrap()\n })\n .collect();\n\n let mut cs = 0;\n\n for num in slv.iter() {\n if *num <= k {\n cs += 1;\n } else {\n break;\n }\n }\n\n if cs == n {\n println!(\"{}\", n);\n return;\n }\n\n\n for num in slv.iter().rev() {\n if *num <= k {\n cs += 1;\n } else {\n break;\n }\n }\n\n println!(\"{}\", cs);\n\n // let mut reach: Vec> = vec![];\n // // reach.reserve(n as usize);\n\n // let mut pairs: Vec> = vec![];\n // for l in lines {\n // let lv: Vec = l.unwrap()\n // .trim()\n // .split(' ')\n // .map(|n| n.parse::().unwrap() - 1)\n // .collect();\n // // println!(\"line values: ({}, {})\", lv[0], lv[1]);\n // reach[lv[0] as usize].insert(lv[1]);\n // reach[lv[1] as usize].insert(lv[0]);\n // pairs.push(lv);\n // }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "285884ef3c1b895f5e3dba78762b5688", "src_uid": "ecf0ead308d8a581dd233160a7e38173", "difficulty": 800.0, "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 / 2 * 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": "587cb044b05c03f44d51c58e08b412d1", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400.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 = 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 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 = 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 r += m2;\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": "f5e2a319f03cd0fe722c27e14cd62952", "src_uid": "279f1f7d250a4be6406c6c7bfc818bbf", "difficulty": 2400.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 solution() {\n let mut scanner = Scanner::new();\n let mut s: String = scanner.next();\n let n = s.len();\n let mut ans = 0;\n let mut current = 1;\n for i in 0..n {\n let d = s.chars().next().unwrap().to_digit(10).unwrap() as usize;\n let x = std::cmp::max(d as i32 - 1, 1) as usize;\n ans = std::cmp::max(ans, current * x * 9_usize.pow((n - i - 1) as u32));\n current *= d;\n s = s[1..].to_string();\n }\n ans = std::cmp::max(ans, current);\n println!(\"{}\", ans);\n}\n\nfn main() {\n std::thread::Builder::new().stack_size(50 << 20)\n .spawn(solution).unwrap().join().unwrap();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "number theory"], "code_uid": "93371b823edb8d89c9eadfed80d536c0", "src_uid": "38690bd32e7d0b314f701f138ce19dfb", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut input = String::new();\n\n std::io::stdin().read_line(&mut input);\n\n for ch in input.to_lowercase().chars() {\n match ch {\n 'a' | 'o' | 'y' | 'e' | 'u' | 'i' | '\\n' | '\\r' => {\n continue;\n },\n _ => {\n print!(\".{}\", ch);\n }\n }\n }\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "ef6810efe0d3ef80610449045f61ed7e", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "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\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": "32d1644bd3fca4afa53a03724bb765b8", "src_uid": "db9520e85b3e9186dd3a09ff8d1e8c1b", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/// square root of an int\nfn sqrti(b: u64) -> u64 {\n let n = 2;\n if b < 2 {\n return b\n };\n let n1 = n - 1;\n let n2 = n;\n let n3 = n1;\n let mut c = 1;\n let mut d = (n3 + b) / n2;\n let mut e = (n3 * d + b / d.pow(n1 as u32)) / n2;\n while c != d && c != e {\n c = d;\n d = e;\n e = (n3 * e + b / e.pow(n1 as u32)) / n2;\n }\n if d < e { d }\n else { e }\n}\n\nuse std::ops::Range;\n\n/// iterator that returns `(w, h)` for rectangles of provided area\nstruct Rects {\n area: u64,\n w: u64,\n rw: Range,\n rh: Range,\n}\n\nimpl Rects {\n pub fn new(area: u64) -> Rects {\n let q = sqrti(area);\n Rects { area, rw: 1..q, rh: 1..area, w: q }\n }\n pub fn with_limits(area: u64, rw: Range, rh: Range) -> Rects {\n let q = sqrti(area);\n let maxw = q.min(area / rh.start).min(rw.end);\n let minw = (area / rh.end).max(rw.start);\n Rects { area, rw: minw..maxw, rh, w: maxw }\n }\n}\n\nimpl Iterator for Rects {\n type Item = (u64, u64);\n fn next(&mut self) -> Option<(u64, u64)> {\n while self.w >= self.rw.start {\n let w = self.w;\n self.w -= 1;\n let h = self.area / w;\n if h < self.rh.start || h > self.rh.end || h * w != self.area {\n continue;\n }\n return Some((w, h));\n }\n None\n }\n}\n\nfn solve(a: u64, b: u64) -> Option {\n if a < 1 || b < 1 {\n return None;\n }\n let area = a + b;\n Rects::new(area).flat_map(|(ow, oh)| {\n let perimeter = (ow + oh) * 2;\n Rects::with_limits(a, 1..ow, 1..oh)\n .chain(Rects::with_limits(b, 1..ow, 1..oh))\n .find(|&(iw, ih)| iw <= ow && ih <= oh)\n .and(Some(perimeter))\n }).next()\n}\n\nuse std::io::{stdin, BufRead};\nuse std::process::{exit};\nfn input() -> Result<(u64, u64), String> {\n let std = stdin();\n let mut row = String::new();\n std.lock().read_line(&mut row).map_err(|_|\"Cannot read stdin\")?;\n let words: Vec<&str> = row.trim().split(' ').collect();\n let a: u64 = words[0].parse().map_err(|_|\"Cannot parse input\")?;\n let b: u64 = words[1].parse().map_err(|_|\"Cannot parse input\")?;\n Ok((a, b))\n}\n\nfn main() {\n let rv = input().map(|(a,b)| solve(a, b));\n match rv {\n Ok(Some(perimeter)) => {\n println!(\"{}\", perimeter);\n }\n Ok(None) => {\n eprintln!(\"Error: solution not found\");\n exit(1);\n }\n Err(e) => {\n eprintln!(\"Error: {}\", e);\n exit(1);\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search", "number theory"], "code_uid": "6ca0289b797f9585ad59d9a005ac41c3", "src_uid": "7d0c5f77bca792b6ab4fd4088fe18ff1", "difficulty": 2000.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 input1: String = read(sin);\n let input2: String = read(sin);\n\n let input1 = input1.to_lowercase();\n let input2 = input2.to_lowercase();\n\n if input1 == input2 {\n println!(\"0\");\n } else if input1 < input2 {\n println!(\"-1\");\n } else if input2 < input1 {\n println!(\"1\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "8d08f9ff11d3d49185675f80689fc624", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::Ordering;\nfn main() {\n let data1 = read().to_lowercase();\n let data2 = read().to_lowercase();\n let c = data1.cmp(&data2);\n match c{\n Ordering::Greater => println!(\"1\"),\n Ordering::Less => println!(\"-1\"),\n _ => println!(\"0\"),\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": "d61a8300843759149d207069682a9362", "src_uid": "ffeae332696a901813677bd1033cf01e", "difficulty": 800.0, "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 n = iter.next().unwrap();\n let k = iter.next().unwrap();\n let mut ans = n / k * k;\n while ans <= n {\n ans += k\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "456e085716db97fbda5639fd77b4b566", "src_uid": "75f3835c969c871a609b978e04476542", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/742/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: u32);\n if n == 0 { println!(\"1\"); }\n else {\n println!(\"{}\",\n match n % 4 {\n 1 => 8,\n 2 => 4,\n 3 => 2,\n 0 => 6,\n _ => unreachable!()\n }\n );\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "2453a21e1ccd633f48be4155ed7960ca", "src_uid": "4b51b99d1dea367bf37dc5ead08ca48f", "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 bi(x: i64, n: i64, l0: i64, r0: i64) -> i64 {\n let mut left = l0;\n let mut right = r0;\n\n while right - left > 1 {\n let y = (left + right) / 2;\n if x * x + y * y <= n * n {\n left = y;\n } else {\n right = y;\n }\n }\n return left;\n}\n\nfn main() {\n let mut sc = Scanner::new();\n\n let n: i64 = sc.cin();\n\n if n == 0 {\n println!(\"1\");\n return;\n }\n\n let mut a = 0;\n let mut b = 0;\n\n let mut l0 = 0;\n let mut r0 = n + 1;\n for x in 0..n {\n let y = bi(x, n, l0, r0);\n l0 = max(0, y - 10);\n r0 = min(y + 10, n + 1);\n // trace!((x, y));\n if x < y {\n a += 1;\n } else if x == y {\n b += 1;\n break;\n } else {\n break;\n }\n }\n let ans = 4 * (a * 2 - 1 + b);\n println!(\"{}\", 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 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": ["math"], "code_uid": "750e7cbf1ddc8b8ebb8a9fc2cd138e7a", "src_uid": "d87ce09acb8401e910ca6ef3529566f4", "difficulty": null, "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 mut input = input.split_whitespace().map(|k| k.parse::().unwrap());\n let m = input.next().unwrap();\n let b = input.next().unwrap();\n\n let ans = (0..(m * b + 1)).map(|x| {\n let y = b - (x + m - 1) / m;\n let tmp = (x + 1) * (y + 1) * (x + y) / 2 ;\n tmp\n }).max().unwrap();\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "2f1ae30cab7f823730179069106c197b", "src_uid": "9300f1c07dd36e0cf7e6cb7911df4cf2", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut l = String::new();\n std::io::stdin().read_line(&mut l).unwrap();\n let mut mb = l.split_whitespace().map(|s| s.parse::().unwrap());\n let m = mb.next().unwrap();\n let b = mb.next().unwrap();\n\n let answer: u64 = (0..(b+1)).into_iter().map(|height| {\n let width = m * (b - height);\n\n let height_sum = height * (height+1) / 2;\n let width_sum = width * (width+1) / 2;\n\n height_sum * (width+1) + width_sum * (height+1)\n }).max().unwrap();\n println!(\"{}\", answer);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "20aedeebd4f847c4e5225c800641bcef", "src_uid": "9300f1c07dd36e0cf7e6cb7911df4cf2", "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::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, m) = (line[0], line[1]);\n if m % n != 0 {\n println!(\"-1\");\n return;\n }\n let mut quotient = m / n;\n let mut ans = 0;\n while quotient % 2 == 0 && quotient > 1 {\n quotient /= 2;\n ans += 1;\n }\n while quotient % 3 == 0 && quotient > 1 {\n quotient /= 3;\n ans += 1;\n }\n if quotient > 1 {\n println!(\"-1\");\n return;\n }\n println!(\"{}\", 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": "2ebd06cc3f0c0ab8d6a416780a18e5c6", "src_uid": "3f9980ad292185f63a80bce10705e806", "difficulty": 1000.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::euclid::{gcd, lcm};\nuse crate::math::sieve::{euler_function_up_to, get_all_divisors_for_all_up_to};\nuse crate::{out, out_line};\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 = 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);\n let z = mul((c as u64 / x) as i32, g as i32);\n add(&mut ans, mul(phi[(n - c) / g] as i32, z as i32));\n }\n }\n out_line!(ans);\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\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 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": "f2bf246aa2a426bd682aaaf2a338ab74", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "const MODULUS: usize = 1_000_000_007;\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 }\n let (_, _, phi) = prime_sieve(n);\n let mut divisors = vec![];\n let mut ans = 0;\n for c in 1..=n-2 {\n let sum_ab = n - c;\n divisors.clear();\n for i in 1.. {\n if i * i > sum_ab {\n break;\n }\n if sum_ab % i == 0 {\n divisors.push(i);\n if i * i < sum_ab {\n divisors.push(sum_ab / i);\n }\n }\n }\n for &divisor in divisors.iter() {\n if divisor == sum_ab {\n continue\n }\n let cnt = phi[sum_ab / divisor];\n let lcm = c / c.gcd(divisor) * divisor;\n ans += lcm % MODULUS * cnt % MODULUS;\n ans %= MODULUS;\n }\n }\n println!(\"{}\", ans);\n}\n\ntrait BinaryGCD {\n fn gcd(self, b: Self) -> Self;\n}\n\nmacro_rules! impl_binary_gcd_uint {\n ($($t:ty),*) => {\n $(\n impl BinaryGCD for $t {\n fn gcd(self, mut b: Self) -> Self {\n let mut a = self;\n\n if b == 0 {\n return a\n }\n if a == 0 {\n return b\n }\n let shifts = (a|b).trailing_zeros();\n a >>= a.trailing_zeros();\n b >>= b.trailing_zeros();\n\n loop {\n if a < b {\n std::mem::swap(&mut a, &mut b);\n }\n a -= b;\n if a == 0 {\n return b << shifts\n }\n a >>= a.trailing_zeros();\n }\n }\n }\n )*\n };\n}\n\nimpl_binary_gcd_uint!(u8, u16, u32, u64, usize, u128);\n\nfn prime_sieve(n: usize) -> (Vec, Vec, Vec) {\n let mut primes = vec![];\n let mut min_div = vec![0; n + 1];\n let mut phi = vec![0; n + 1];\n phi[1] = 1;\n for i in 2..=n {\n if min_div[i] == 0 {\n min_div[i] = i;\n phi[i] = i - 1;\n primes.push(i)\n }\n for &p in primes.iter() {\n if i * p > n {\n break\n }\n min_div[i * p] = p;\n if i % p == 0 {\n phi[i * p] = phi[i] * p;\n break\n }\n phi[i * p] = phi[i] * (p - 1);\n }\n }\n (primes, min_div, phi)\n}\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 ]) => {{\n let len = read_value!($reader, usize);\n read_value!($reader, [ $t ; len])\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", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "fad35a6d8b701c3afbb703410851f774", "src_uid": "c3694a6ff95c64bef8cbe8834c3fd6cb", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\n#![allow(dead_code)]\n#![allow(unused_variables)]\nuse std::cmp::*;\nuse std::collections::BTreeSet;\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\nfn transform(x: u64, d: u64) -> u64 {\n if x & (1u64 << 63) != 0 {\n return 0;\n }\n let mut x = (x << 1) | d;\n while x & 1 == 0 {\n x >>= 1;\n }\n let mut y = 0;\n while x != 0 {\n y = (y << 1) | (x & 1);\n x >>= 1;\n }\n\n y\n}\n\nfn solve(io: &mut IO) -> Result<()> {\n let (a, b): (u64, u64) = (io.read(), io.read());\n let mut mp = BTreeSet::::new();\n let mut vis = BTreeSet::::new();\n mp.insert(a);\n\n while let Some(&x) = mp.iter().next() {\n if x == b {\n return writeln!(io.out, \"YES\");\n }\n\n vis.insert(x);\n mp.remove(&x);\n\n for d in 0..=1 {\n let y = transform(x, d);\n if y != 0 && !vis.contains(&y) {\n mp.insert(y);\n }\n }\n }\n return writeln!(io.out, \"NO\");\n}\n\nfn main() -> io::Result<()> {\n let mut io = IO::new();\n\n solve(&mut io)\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "3091eaa7f03e1d18eaeb8f741c4badb3", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000.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 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 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 solve(scanner: &mut Scanner, writer: &mut W) {\n let mut x: i64 = scanner.scan();\n let mut y: i64 = scanner.scan();\n if y % 2 == 0 {\n writeln!(writer, \"{}\", if x == y {\"YES\"} else {\"NO\"}).unwrap();\n return;\n }\n let mut a = Vec::new();\n while x != 0 {\n a.push(x % 2);\n x /= 2;\n }\n let mut b = Vec::new();\n while y != 0 {\n b.push(y % 2);\n y /= 2;\n }\n a.reverse();\n b.reverse();\n let mut result = false;\n let mut aa = vec![a; 3];\n aa[1].push(1);\n aa[1].reverse();\n while let Some(&0) = aa[2].last() {\n aa[2].pop();\n }\n aa[2].reverse();\n for mut a in aa {\n loop {\n for i in 0..b.len() {\n if i + a.len() > b.len() {\n break;\n }\n let mut ok = true;\n for j in 0..a.len() {\n ok &= a[j] == b[i + j];\n }\n for j in 0..i {\n ok &= b[j] == 1;\n }\n for j in i + a.len()..b.len() {\n ok &= b[j] == 1;\n }\n if ok {\n result = true;\n }\n }\n if let Some(1) = a.pop() {\n break;\n }\n while let Some(&0) = a.last() {\n a.pop();\n }\n }\n }\n writeln!(writer, \"{}\", if result {\"YES\"} else {\"NO\"}).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 = 1;\n for _ in 0..tests {\n solve(&mut scanner, &mut writer);\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "constructive algorithms", "math", "bitmasks", "strings", "implementation"], "code_uid": "3f487c785bfce27c50dba61cb47a28c5", "src_uid": "9f39a3c160087beb0efab2e3cb510e89", "difficulty": 2000.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 n: u64,\n }\n if n%2 == 1 {\n println!(\"{}\", 0);\n } else {\n let ans = 1 << (n/2);\n println!(\"{}\", ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "a332afb32554d65ba8a9e54ce8fd1cf3", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_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 length = readln!(usize);\n\n if length % 2 == 0 {\n println!(\"{}\", 1 << (length / 2));\n } else {\n println!(\"0\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "6c79ce2d2c4412e78cff7465085895e7", "src_uid": "4b7ff467ed5907e32fd529fb39b708db", "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 readln!();\n let a = readvec!(i32);\n let last = a[a.len()-1];\n if last == 0 {\n println!(\"UP\");\n } else if last == 15 {\n println!(\"DOWN\");\n } else if a.len() == 1 {\n println!(\"-1\");\n } else if a[a.len()-2] < a[a.len()-1] {\n println!(\"UP\");\n } else if a[a.len()-2] > a[a.len()-1] {\n println!(\"DOWN\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "6daddcc98f9f1fb9cb68f26bca19f5b8", "src_uid": "8330d9fea8d50a79741507b878da0a75", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main()\n{\n\tlet mut s = String::new();\n\tlet mut n = String::new();\n\tio::stdin().read_line(&mut n).unwrap();\n\tlet n = n.trim().parse::().unwrap();\n\tio::stdin().read_line(&mut s).unwrap();\n\ts = s.trim().to_string();\n\tlet val: Vec = s.split(\" \").map(|x: &str| x.parse::().unwrap()).collect();\n\n\tif let Ok(res) = match val[val.len()-1] {\n\t\t0 => Ok(\"UP\"),\n\t\t15 => Ok(\"DOWN\"),\n\t\t_ => if val.len() > 1 {\n\t\t\tmatch val[val.len()-1] - val[val.len()-2] {\n\t\t\t\t1 => Ok(\"UP\"),\n\t\t\t\t-1 => Ok(\"DOWN\"),\n\t\t\t\t_ => Err(\"invalid input\"),\n\t\t\t}\n\t\t} else {\n\t\t\tprint!(\"{}\", -1);\n\t\t\treturn;\n\t\t}\n\t} {\n\t\tprint!(\"{}\", res);\n\t}\n\telse {\n\t\tprint!(\"{}\", \"invalid input\");\n\t}\n\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b575260e19c2730536685afdc54b682e", "src_uid": "8330d9fea8d50a79741507b878da0a75", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "struct FenwickTree {\n val: Vec,\n}\n\nimpl FenwickTree {\n fn new(n: usize) -> Self {\n FenwickTree {\n val: vec![0; n + 1],\n }\n }\n fn add(&mut self, mut x: usize, v: i64) {\n while let Some(p) = self.val.get_mut(x) {\n *p += v;\n x += x & (!x + 1);\n }\n }\n fn sum(&mut self, mut x: usize) -> i64 {\n assert!(x < self.val.len());\n let mut ans = 0;\n while x > 0 {\n ans += self.val[x];\n x -= x & (!x + 1);\n }\n ans\n }\n}\n\nfn sieve(n: usize) -> Vec {\n let mut is_prime = vec![true; n + 1];\n for i in 2.. {\n if i * i > n {\n break;\n }\n if is_prime[i] {\n let mut j = i * i;\n while j <= n {\n is_prime[j] = false;\n j += i;\n }\n }\n }\n let len = is_prime.iter().skip(2).filter(|p| **p).count();\n let mut prime = Vec::with_capacity(len);\n for (i, is_prime) in is_prime.into_iter().enumerate().skip(2) {\n if is_prime {\n prime.push(i as i64);\n }\n }\n prime\n}\n\nstruct PrimeCountSolver {\n query: Vec,\n memo: Vec,\n}\n\nimpl PrimeCountSolver {\n fn new() -> Self {\n PrimeCountSolver {\n query: vec![],\n memo: vec![],\n }\n }\n fn add(&mut self, n: i64) {\n self.query.push(n);\n }\n fn build(&mut self) {\n self.query.sort();\n self.query.dedup();\n let n = self.query.last().map_or(1, |n| *n);\n let mut m = 1;\n while (m + 1) * (m + 1) <= n {\n m += 1;\n }\n let p = sieve(m as usize);\n let bound = (n as f64).cbrt().powi(2) as i64 + 2;\n let mut stack = vec![];\n for &v in self.query.iter() {\n let k = match p.binary_search_by(|&p| (p * p).cmp(&v)) {\n Ok(k) => k + 1,\n Err(k) => k,\n };\n stack.push((v, k));\n }\n let mut query = vec![];\n while let Some((n, k)) = stack.pop() {\n if k == 0 {\n continue;\n }\n let q = p[k - 1];\n if q * q > n {\n let x = match p[..k].binary_search_by(|&p| (p * p).cmp(&n)) {\n Ok(k) => k + 1,\n Err(k) => k,\n };\n stack.push((n, x));\n } else if n <= bound {\n query.push((k, n));\n } else {\n stack.push((n, k - 1));\n stack.push((n / q, k - 1));\n }\n }\n query.sort();\n query.dedup();\n let m = bound as usize;\n let mut bit = FenwickTree::new(m);\n for i in 1..=m {\n bit.add(i, 1);\n }\n let mut is_prime = vec![true; m + 1];\n let mut memo = vec![0; query.len()];\n let mut pos = 0;\n for (i, p) in p.iter().enumerate() {\n let p = *p as usize;\n let mut j = p;\n while j <= m {\n if is_prime[j] {\n bit.add(j, -1);\n }\n is_prime[j] = false;\n j += p;\n }\n while let Some(&(k, n)) = query.get(pos) {\n if k > i + 1 {\n break;\n } else {\n memo[pos] = bit.sum(n as usize);\n pos += 1;\n }\n }\n if pos >= query.len() {\n break;\n }\n }\n self.memo.clear();\n self.memo.resize(self.query.len(), 0);\n let mut stack = vec![];\n for (i, &n) in self.query.iter().enumerate() {\n let k = match p.binary_search_by(|&p| (p * p).cmp(&n)) {\n Ok(k) => k + 1,\n Err(k) => k,\n };\n self.memo[i] += k as i64 - 1;\n stack.push((n, k, 1, i));\n }\n while let Some((n, k, sign, i)) = stack.pop() {\n if k == 0 {\n self.memo[i] += sign * n;\n continue;\n }\n let q = p[k - 1];\n if q * q > n {\n let x = match p[..k].binary_search_by(|p| (p * p).cmp(&n)) {\n Ok(k) => k + 1,\n Err(k) => k,\n };\n self.memo[i] += -sign * (k - x) as i64;\n stack.push((n, x, sign, i));\n } else if n <= bound {\n self.memo[i] += sign * memo[query.binary_search(&(k, n)).unwrap()];\n } else {\n stack.push((n, k - 1, sign, i));\n stack.push((n / q, k - 1, -sign, i));\n }\n }\n }\n fn get(&self, n: i64) -> i64 {\n self.memo[self.query.binary_search(&n).unwrap()]\n }\n}\n\nfn run() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let n: i64 = s.trim().parse().unwrap();\n let p = sieve((n as f64).sqrt() as usize + 2);\n let mut ans = 0i64;\n for p in p.iter() {\n if p.pow(3) <= n {\n ans += 1;\n } else {\n break;\n }\n }\n let mut solver = PrimeCountSolver::new();\n for (i, p) in p.iter().enumerate() {\n if p.pow(2) <= n {\n ans -= i as i64 + 1;\n solver.add(n / *p);\n }\n }\n solver.build();\n for p in p.iter() {\n if p.pow(2) <= n {\n ans += solver.get(n / *p);\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "sortings", "data structures", "two pointers", "number theory"], "code_uid": "a937961db8db3b21eba06aae97af50e3", "src_uid": "ffb7762f1d60dc3f16e9b27ea0ecdd7d", "difficulty": 2400.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 sum = scan.token::();\n let mut s: Vec = Vec::new();\n for n in sum.split('+') {\n s.push(n.parse().unwrap());\n }\n s.sort();\n let mut ans = vector_to_str(&s, \"+\");\n ans.pop();\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": ["sortings", "strings", "implementation", "greedy"], "code_uid": "f410275f2059f3901a5104dbb7bfb2e4", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let mut inp = String::new();\n stdin().read_line(&mut inp).expect(\"msg: &str\");\n let mut inp = inp.trim();\n let mut a: Vec = inp\n .split(\"+\")\n .collect::>()\n .iter()\n .map(|e| e.parse::().unwrap())\n .collect();\n a.sort();\n let a: Vec = a.iter().map(|e| format!(\"{}\", e)).collect();\n println!(\"{}\", a.join(\"+\"));\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "strings", "implementation", "greedy"], "code_uid": "35bd59bac143f6a127e9c7e511d65825", "src_uid": "76c7312733ef9d8278521cf09d3ccbc8", "difficulty": 800.0, "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 if input.s() == input.s().chars().rev().collect::() {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "1d6c17dabb3495df23387dbb43b6ff9c", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "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)] fn strarr() -> Vec {\n let mut inp = String::new();\n stdin().read_line(&mut inp).ok();\n inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).map(|x| x.to_string()).collect() }\n#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{\n let s = strarr(); let mut cnt : usize = 0;\n fn next(cnt: &mut usize, p: &Vec) -> T\n 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 s = strarr(); let mut v = Vec::new();\n for i in 0..$n { v.push(s[i as usize].parse::<$T>().unwrap()); } v\n }}; }\n\n///////////////////////////////////////////////////////////////////////////////\n\nfn main()\n{\n let s = scan!(String);\n let t = scan!(String);\n println!(\"{}\", if s.chars().rev().collect::>() == t.chars().collect::>() { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "33fed4a06f7a14e95dbbe1be79dfb0d7", "src_uid": "35a4be326690b58bf9add547fb63a5a5", "difficulty": 800.0, "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 number = input.trim().parse::().expect(\"NUMBER::Parse to i32 failed!\");\n\n if number % 2 == 0 {\n println!(\"Mahmoud\");\n }else {\n println!(\"Ehab\");\n }\n}", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "f64ad38c9042529ca00b01352465ce50", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "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 println!(\"{}\", [\"Mahmoud\",\"Ehab\"][input.u() % 2]);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "7b27e305f50de547f116d7ab89e633aa", "src_uid": "5e74750f44142624e6da41d4b35beb9a", "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 it.next().unwrap();\n\n let a: Vec = it.map(|x| x.parse().unwrap()).collect();\n\n let ans: i32 = a.into_iter().map(|x| x.abs()).sum();\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "edb6fe9a1f60f18474bcfc423c6a67d4", "src_uid": "4b5d14833f9b51bfd336cc0e661243a5", "difficulty": 800.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: [i32; n],\n }\n let mut ans = 0;\n for a in a {\n ans += a.abs();\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "3ae291c3488f55a34c72ccf2cb615b57", "src_uid": "4b5d14833f9b51bfd336cc0e661243a5", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_int_line () -> i32 {\n let mut num = String::new();\n io::stdin().read_line(&mut num)\n .expect(\"Failed to read line\");\n \n num.trim().parse()\n .expect(\"Not an integer\")\n}\n\nfn main() {\n\n\tread_int_line();\n\n\tlet mut string = String::new();\n\tio::stdin().read_line(&mut string)\n\t\t.expect(\"Failed to read line\");\n\n\n\tlet v: Vec<&str> = string.split(char::is_uppercase).collect();\n\tlet mut maximum: i32 = 0;\n\n\tfor s in v {\n\t\tlet mut vi: Vec = s.trim().chars().collect();\n\t\tvi.sort();\n\t\tvi.dedup();\n\t\tlet temp: i32 = vi.len() as i32;\n\t\tif maximum < temp {\n\t\t\t// println!(\"{:?}, {:?}\", s.trim(), temp);\n\t\t\tmaximum = temp;\n\t\t}\n\t}\n\tprintln!(\"{}\", maximum);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "strings", "implementation"], "code_uid": "72b760a3b1f822a32a2c627434674480", "src_uid": "567ce65f87d2fb922b0f7e0957fbada3", "difficulty": 1000.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)] fn strarr() -> Vec {\n let mut inp = String::new();\n stdin().read_line(&mut inp).ok();\n inp.split(' ').map(|x| x.trim()).filter(|x| x.len() != 0).map(|x| x.to_string()).collect() }\n#[allow(unused)] macro_rules! scan { ($($x:ty), +) => {{\n let s = strarr(); let mut cnt : usize = 0;\n fn next(cnt: &mut usize, p: &Vec) -> T\n 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 s = strarr(); let mut v = Vec::new();\n for i in 0..$n { v.push(s[i as usize].parse::<$T>().unwrap()); } v\n }}; }\n\n///////////////////////////////////////////////////////////////////////////////\n\nfn main()\n{\n let s = scan!(String);\n let c1 = s.chars().filter(|x| x.is_lowercase()).count();\n let c2 = s.chars().nth(0).unwrap().is_lowercase();\n if c1 == 0 || (c1 == 1 && c2 == true) {\n for i in s.chars() {\n print!(\"{}\", if i.is_lowercase() { i.to_uppercase().nth(0).unwrap() } else { i.to_lowercase().nth(0).unwrap() });\n }\n } else {\n print!(\"{}\", s);\n }\n \n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "a041c481e8a4521cba7442101e9f3f21", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000.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 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": "45ce1612d740ae06047d2a4840f478c9", "src_uid": "db0eb44d8cd8f293da407ba3adee10cf", "difficulty": 1000.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 = 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// Binomial Coefficient (C(n,r)) {{{\n#[derive(Debug,Clone)]\nstruct Cnr {\n\tn: usize,\n\tpub f: 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(Z1);\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![Z1; 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\tZ0\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\tl!(n,x,p = rin.u());\n\tlet x = x-1;\n\tlet mut lo = 0;\n\tlet mut hi = n;\n\tl!(mut lo_fix,hi_fix = 0);\n\twhile lo < hi {\n\t\tlet mid = (lo + hi) / 2;\n\t\tif mid == p {\n\t\t\tlo = mid + 1;\n\t\t} else if mid < p {\n\t\t\tlo_fix += 1;\n\t\t\tlo = mid + 1;\n\t\t} else {\n\t\t\thi_fix += 1;\n\t\t\thi = mid;\n\t\t}\n\t}\n\n\tlet f = Cnr::new(n);\n\tlet sol = f.cnr(x, lo_fix) * f.f[lo_fix] * f.cnr(n-1-x, hi_fix) * f.f[hi_fix] * f.f[n - hi_fix - lo_fix - 1];\n\twriteln!(rout, \"{}\", sol).ok();\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "a4c67328e1f8213a63d5b5611318c801", "src_uid": "24e2f10463f440affccc2755f4462d8a", "difficulty": 1500.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\nconst MOD: i64 = 1e9 as i64 + 7;\n\nfn count_needed(n: i64, pos: i64) -> (i64, i64) {\n let mut l = 0;\n let mut r = n;\n\n let mut smaller = 0;\n let mut greater = 0;\n\n while l < r {\n let m = (l + r) / 2;\n if m < pos {\n smaller += 1;\n l = m + 1;\n } else if m > pos {\n greater += 1;\n r = m;\n } else {\n l = m + 1;\n }\n }\n (smaller, greater)\n}\n\nfn factorial(n: i64) -> i64 {\n let mut res = 1;\n for i in 2..=n {\n res = (res * i) % MOD;\n }\n res\n}\n\nfn permutations(n: i64) -> i64 {\n factorial(n)\n}\n\nfn euclid(a: i64, b: i64) -> (i64, i64) {\n if b == 0 {\n (1, 0)\n } else {\n let (x, y) = euclid(b, a % b);\n (y, x - a / b * y)\n }\n}\n\nfn mod_inv(num: i64) -> i64 {\n let mut inv = euclid(num, MOD).0;\n while inv < 0 {\n inv += MOD;\n }\n inv\n}\n\nfn arrangements(n: i64, k: i64) -> i64 {\n factorial(n) * mod_inv(factorial(n - k)) % MOD\n}\n\nfn solve(n: i64, x: i64, pos: i64) -> i64 {\n let (smaller, greater) = count_needed(n, pos);\n if smaller >= x || greater > (n - x) {\n return 0;\n }\n\n arrangements(x - 1, smaller)\n * arrangements(n - x, greater) % MOD\n * permutations(n - 1 - smaller - greater) % MOD\n\n}\n\nfn main() {\n let mut reader = TokenReader::new();\n let n = reader.next();\n let x = reader.next();\n let pos = reader.next();\n\n let res = solve(n, x, pos);\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["binary search", "combinatorics"], "code_uid": "2112b343a181022066c7b16967524b22", "src_uid": "24e2f10463f440affccc2755f4462d8a", "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 count_prime_factors(n: i32) -> i32 {\n let mut count = 0;\n let mut factor = 2;\n let mut n = n;\n while factor * factor <= n {\n let mut expo = 0;\n while n % factor == 0 {\n n /= factor;\n expo += 1;\n }\n if expo >= 1 {\n count += 1;\n }\n factor += 1;\n }\n if n > 1 {\n count += 1;\n }\n count\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: i32 = scan.token();\n let mut ans = 0;\n for i in 1..=n {\n let count = count_prime_factors(i);\n if count == 2 {\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": ["number theory"], "code_uid": "fb0ea88b7076a32d308e774db5bbf496", "src_uid": "356666366625bc5358bc8b97c8d67bd5", "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::*;\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 res = input.bs().iter().fold(0, |a,&x| match (a,x - b'0') {\n (0...2,1) => 2,\n (y@1...2,4) => y - 1,\n _ => -1,\n }) >= 0;\n if res {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy"], "code_uid": "979813ad40dd7ceba1f31c0bd3488bb8", "src_uid": "3153cfddae27fbd817caaf2cb7a6a4b5", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let s = get_input();\n if is_magic_number(s) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n \n}\n\nfn is_magic_number(s: String) -> bool {\n if !s.starts_with(\"1\") {\n false\n } else {\n let mut four_count = 0;\n for c in s.chars() {\n if c == '1' {\n four_count = 0;\n } else if c == '4' {\n four_count += 1;\n if four_count > 2 {\n return false;\n }\n } else {\n return false;\n }\n }\n\n true\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", "greedy"], "code_uid": "98f7029cdb40516b09214c356c1a201b", "src_uid": "3153cfddae27fbd817caaf2cb7a6a4b5", "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;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n let num_squares = get_numbers(&input)[0];\n input.clear();\n io::stdin().read_line(&mut input).unwrap();\n let squares: Vec = input.chars().collect();\n\n let mut numbers = Vec::new();\n let mut n = 0;\n for i in 0..num_squares {\n if squares[i] == 'B' {\n n += 1;\n } else if n > 0 {\n numbers.push(n);\n n = 0;\n }\n }\n if n > 0 {\n numbers.push(n);\n }\n\n if numbers.len() == 0 {\n println!(\"{}\", 0);\n return;\n }\n println!(\"{}\", numbers.len());\n if numbers.len() == 1 {\n println!(\"{}\", numbers[0]);\n return;\n }\n\n for i in 0..(numbers.len()-1) {\n print!(\"{} \", numbers[i])\n }\n println!(\"{}\", numbers[numbers.len()-1]);\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": ["implementation"], "code_uid": "27e6584aed8fc2317e0fca3b711122e6", "src_uid": "e4b3a2707ba080b93a152f4e6e983973", "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 x: [i32; 3],\n a: [i32; 3],\n }\n let mut c = 0;\n for i in 0..3 {\n c += a[i];\n if x[i] > c {\n puts!(\"NO\\n\");\n return;\n }\n c -= x[i];\n }\n puts!(\"YES\\n\");\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": ["brute force", "greedy", "implementation"], "code_uid": "129f132db328b747fbc8941522c7b7a7", "src_uid": "d54201591f7284da5e9ce18984439f4e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "macro_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 (mut x, mut y, mut z) = readln!(i32, i32, i32);\n let (mut a, mut b, mut c) = readln!(i32, i32, i32);\n \n let mut ans = solve(x, y, z, a, b, c);\n println!(\"{}\", [\"YES\", \"NO\"][ans]);\n}\n\nfn solve(x: i32, y: i32, z: i32, a: i32, b: i32, c: i32) -> usize {\n if x > a || x + y > a + b || x + y + z > a + b + c {\n 1\n } else {\n 0\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation"], "code_uid": "f0f91f7599f3dcf1e50e5ebf5e49b659", "src_uid": "d54201591f7284da5e9ce18984439f4e", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\nuse std::io::{self, BufRead};\nfn main() {\n let mut line = \"\".to_string();\n let stdin = io::stdin();\n stdin.lock().read_line(&mut line).unwrap();\n let (_, limit) = if let [Ok(a), Ok(b)] = &line\n .split_whitespace()\n .map(|s| s.parse::())\n .collect::>()[..]\n {\n (*a, *b)\n } else {\n (0, 0)\n };\n line.clear();\n stdin.lock().read_line(&mut line).unwrap();\n if line\n .bytes()\n .fold(&mut HashMap::new(), |map, s| {\n *map.entry(s).or_insert(0) += 1;\n map\n })\n .iter()\n .filter(|(_, &cnt)| cnt > limit)\n .count()\n > 0\n {\n println!(\"NO\");\n } else {\n println!(\"YES\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "ee5e88c1a59edba28cd32db07dc22654", "src_uid": "ceb3807aaffef60bcdbcc9a17a1391be", "difficulty": 900.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, k) = scan_line!(i32 i32);\n let colors = scan_line!();\n let mut color_counts = vec![0; 256];\n\n let mut result = true;\n for c in colors.bytes() {\n color_counts[c as usize] += 1;\n }\n\n for c in color_counts {\n if c > k {\n result = false;\n break;\n }\n }\n\n if result {\n println!(\"YES\")\n } else {\n println!(\"NO\")\n }\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "5fdd80f206afe562585afb0296087d1f", "src_uid": "ceb3807aaffef60bcdbcc9a17a1391be", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::io::BufRead;\n\nfn main() {\n let mut buf = String::new();\n let stdin = io::stdin();\n stdin.read_line(&mut buf).unwrap();\n let n: u32 = buf.trim().parse().unwrap();\n for k in 0..n {\n buf.clear();\n stdin.read_line(&mut buf).unwrap();\n let x: u32 = buf.trim().parse().unwrap();\n let b = x / 7;\n let a = (x % 7) % 3;\n if a == 0 || b >= (3 - a) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n }\n}", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "ffc8b9200047cc585af4761ee86aad7f", "src_uid": "cfd1182be98fb5f0c426f8b68e48d452", "difficulty": 900.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: u64,\n }\n let ans = (n * (n + 1) / 2) % 2;\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "0d110b7d4acb618ccd19ce31fa24316f", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "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: u64 = scan.next();\n let result = (n * (n + 1) / 2) % 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"], "code_uid": "fee6b4d33ab2e6c24c50f8e54e3648ba", "src_uid": "fa163c5b619d3892e33e1fb9c22043a9", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn get_single_number_from_stdin() -> u64 {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n buffer.trim().parse::().expect(\"Not an integer\")\n}\n\nfn main(){\n let mut dollars = get_single_number_from_stdin();\n let denominations = vec![100,20,10,5,1];\n let mut total_bills = 0;\n for denomination in denominations {\n if dollars == 0 {\n break;\n }\n if dollars >= denomination {\n let q = (dollars/denomination) as u64;\n dollars -= denomination * q;\n total_bills += q;\n }else{\n continue;\n }\n }\n print!(\"{}\",total_bills);\n}", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "566e1780b766e692c9049f9e1da6ced3", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "difficulty": 800.0, "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 if money == 0 {\n break;\n }\n }\n println!(\"{}\", bills);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "0e8526a1d376cc5a693f8e7ce8d92240", "src_uid": "8e81ad7110552c20297f08ad3e5f8ddc", "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 a: i64 = read(sin);\n let b: i64 = read(sin);\n let c: i64 = read(sin);\n\n if b == 1 {\n let ans = if a <= c {\n if c == 1 {\n // a == b == c == 1\n a + b + c\n } else {\n (a + b) * c\n }\n } else {\n a * (b + c)\n };\n println!(\"{}\", ans);\n return;\n }\n\n if c == 1 && a != 1 {\n println!(\"{}\", a * (b + c));\n return;\n }\n\n let pre_val = if a == 1 { a + b } else { a * b };\n let ans = if c == 1 { pre_val + c } else { pre_val * c };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "77fd3b7f22c977320c3f26a56b1e1864", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "difficulty": 1000.0, "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 (a, b, c): (u16, u16, u16) = (read_int(), read_int(), read_int());\n \n if a + c == 2 { println!(\"{}\", a + b + c); }\n else if a == 1 || b == 1 || c == 1 {\n if a < c { println!(\"{}\", (a + b) * c); }\n else { println!(\"{}\", a * (b + c)); }\n }\n else { println!(\"{}\", a * b * c); }\n}", "lang_cluster": "Rust", "tags": ["brute force", "math"], "code_uid": "d9f631d2dfb463994f28fbfa01f7b450", "src_uid": "1cad9e4797ca2d80a12276b5a790ef27", "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 let a = input.i();\n let b = input.i();\n println!(\"{}\", (n - a).min(b + 1));\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "d510f0dd8aed27fc6f8683a0a4cfd35e", "src_uid": "51a072916bff600922a77da0c4582180", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let s = std::io::stdin();\n let mut sc = Scanner { stdin: s.lock() };\n let x: usize = sc.read();\n let mut hh: usize = sc.read();\n let mut mm: usize = sc.read();\n let mut result = 24 * 60;\n for h in 0..24 {\n for m in 0..60 {\n if h == 7 || h == 17 || m == 7 || m == 17 || m == 27 || m == 37 || m == 47 || m == 57 {\n let mut cnt = 0;\n let mut tmp_h = h;\n let mut tmp_m = m;\n while tmp_h != hh || tmp_m != mm {\n tmp_m += x;\n if tmp_m >= 60 {\n tmp_h += 1;\n tmp_m %= 60;\n }\n if tmp_h >= 24 {\n tmp_h = 0;\n }\n cnt += 1;\n if cnt > 24 * 60 {\n break;\n }\n }\n \n result = std::cmp::min(result, cnt);\n }\n }\n }\n println!(\"{}\", result);\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\n .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 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", "math", "implementation"], "code_uid": "7741a90644b924b350b67bacd4090e93", "src_uid": "5ecd569e02e0164a5da9ff549fca3ceb", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "// 長さ10^100 な文字列Tがある、最初全部0\r\n// 文字列S が与えられる\r\n// S を T のどこかにxorするみたいなことができる\r\n// 1が二つとなるように操作する時出来上がるTの辞書順最大を求めて\r\n//\r\n// |S| <= 35\r\n//\r\n// なんかサンプル4ですごい数が出てきてる\r\n//\r\n// 不可能な場合って何?\r\n// 0のみ、不可能\r\n// それ以外で不可能な場合は?\r\n// わからん\r\n// 1一つ, 2つ\r\n// 詰めて置けばいい\r\n// 3つ以上?\r\n// 最初の1は確定する\r\n// というの最初を使うと最初の1は確定するし、使わないで得られた答えはスライドさせてより大きくできる\r\n// 残った部分になんかxorしていく感じ\r\n// やれることが前からxorしていくことしかないが\r\n//\r\n// S の最初、最後の0を削っておく\r\n// なんかコンパニオン行列をかけまくって (0, 0, ..., 1) になる最小の数\r\n// みたいな問題になる\r\n// 線形代数ゲー?ようわからん\r\n// S の1文字目の1を削ったやつをs, 単位ベクトルをe_i と置く\r\n// k = |S| - 1 として\r\n//\r\n// s * mat [s, e_1, .., e_{k - 1}] ^n = e_k\r\n//\r\n// となるようなn の最小値、ないならそれ報告\r\n// 離散対数?\r\n// ちょっと間に合わない感\r\n// いや2^18 程度なら間に合ってもいいんじゃ\r\n// 間に合ってもいい気はするがなんか BS-GS に持ち込めない\r\n// 上の前処理すると A は逆行列を持つようになる\r\n//\r\n// s A^n = e_k\r\n// s A^(qx + r) = e_k\r\n// s A^(qx) = e_k A^(-r)\r\n// これはいけそう\r\n//\r\n// ところで、最小性が問題になるが\r\n// まあなんとかなるでしょ多分\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\nfn run(mut s: Vec) -> Option<(usize, usize)> {\r\n s.iter_mut().for_each(|s| *s -= b'0');\r\n let c = s.iter().filter(|s| **s == 1).count();\r\n if c == 0 {\r\n return None;\r\n }\r\n let f = s.iter().position(|s| *s == 1).unwrap();\r\n if c == 1 {\r\n return Some((f, f + 1));\r\n }\r\n let mut s = s;\r\n s.drain(..=f);\r\n while s.last().map_or(false, |c| *c == 0) {\r\n s.pop();\r\n }\r\n let s = s;\r\n let k = s.len();\r\n let mut a = vec![vec![0u8; k]; k];\r\n for (i, s) in s.iter().enumerate() {\r\n a[0][i] = *s;\r\n }\r\n for i in 1..k {\r\n a[i][i - 1] = 1;\r\n }\r\n let inv_a = inverse_matrix(a.clone()).unwrap();\r\n let mut right = vec![0; k];\r\n right[k - 1] = 1u8;\r\n let sq = 1 << (k / 2 + 1);\r\n let mut map = Map::new();\r\n for i in 0..=sq {\r\n map.entry(right.clone()).or_insert(i);\r\n let mut next = vec![0; k];\r\n for (right, inv_a) in right.iter().zip(inv_a.iter()) {\r\n for (next, inv_a) in next.iter_mut().zip(inv_a.iter()) {\r\n *next ^= *right & *inv_a;\r\n }\r\n }\r\n right = next;\r\n }\r\n let mul = |a: &[Vec], b: &[Vec]| -> Vec> {\r\n let mut c = vec![vec![0; k]; k];\r\n for (c, a) in c.iter_mut().zip(a.iter()) {\r\n for (a, b) in a.iter().zip(b.iter()) {\r\n for (c, b) in c.iter_mut().zip(b.iter()) {\r\n *c ^= *a & *b;\r\n }\r\n }\r\n }\r\n c\r\n };\r\n let mut mat = vec![vec![0; k]; k];\r\n for i in 0..k {\r\n mat[i][i] = 1;\r\n }\r\n for i in (0..20).rev() {\r\n mat = mul(&mat, &mat);\r\n if sq >> i & 1 == 1 {\r\n mat = mul(&mat, &a);\r\n }\r\n }\r\n let rad = mat;\r\n let mut mat = vec![vec![0; k]; k];\r\n for i in 0..k {\r\n mat[i][i] = 1;\r\n }\r\n for i in 0..=sq {\r\n let mut b = vec![0; k];\r\n for (s, mat) in s.iter().zip(mat.iter()) {\r\n for (b, mat) in b.iter_mut().zip(mat.iter()) {\r\n *b ^= *s & *mat;\r\n }\r\n }\r\n if let Some(v) = map.get(&b) {\r\n return Some((f, sq * i + v + f + k));\r\n }\r\n mat = mul(&mat, &rad);\r\n }\r\n None\r\n}\r\n\r\nfn inverse_matrix(mut mat: Vec>) -> Option>> {\r\n let n = mat.len();\r\n assert!(mat.iter().all(|mat| mat.len() == n));\r\n for (i, mat) in mat.iter_mut().enumerate() {\r\n mat.resize(2 * n, 0);\r\n mat[n + i] = 1;\r\n }\r\n for i in 0..n {\r\n let x = (i..n).find(|x| mat[*x][i] != 0)?;\r\n mat.swap(i, x);\r\n let a = std::mem::take(&mut mat[i]);\r\n for mat in mat.iter_mut().filter(|mat| !mat.is_empty()) {\r\n let mul = mat[i];\r\n for (mat, a) in mat[i..].iter_mut().zip(a[i..].iter()) {\r\n *mat ^= mul & *a;\r\n }\r\n }\r\n mat[i] = a;\r\n }\r\n Some(mat.iter().map(|a| Vec::from(&a[n..])).collect())\r\n}\r\n\r\nfn main() {\r\n input! {\r\n s: bytes,\r\n }\r\n if let Some((a, b)) = run(s) {\r\n println!(\"{} {}\", a + 1, b + 1);\r\n } else {\r\n println!(\"-1\");\r\n }\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": ["math", "bitmasks", "meet-in-the-middle", "matrices", "number theory"], "code_uid": "4542b5cc5c57ea1a95603351de5ac953", "src_uid": "6bf798edef30db7d0ce2130e40084e6b", "difficulty": 2900.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 (k, p): (usize, usize) = {\n let input = get_line();\n let mut it = input.split_whitespace()\n .map(|x| x.parse().unwrap());\n (\n it.next().unwrap(),\n it.next().unwrap(),\n )\n };\n\n let p = p as u64;\n\n let mul = |a, b| {\n (a * b) % p\n };\n\n let pow10 = |k| {\n let mut ret_val = 1;\n for _ in 0..k {\n ret_val = mul(ret_val, 10);\n }\n ret_val\n };\n\n let mut ans = 0;\n\n for i in (1..).take(k) {\n let s = format!(\"{}\", i);\n let n = s.len() as u64;\n for (ind, d) in s.bytes().enumerate() {\n let d = (d - b'0') as u64;\n let ind = ind as u64;\n ans = (ans + d * pow10(ind)) % p;\n ans = (ans + d * pow10(2 * n - 1 - ind)) % p;\n }\n }\n\n println!(\"{}\", ans);\n}\n\nstruct Solver {\n}\n\nimpl Solver {\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "902ed727f9bd9812dc82ee33018fb593", "src_uid": "00e90909a77ce9e22bb7cbf1285b0609", "difficulty": 1300.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 mult = mir((k * C) as _) * npow[k-1];\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 _) * mult;\n dp[r] += 1;\n a = (a * x + y) % M;\n }\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": "88b719ae6dcd18a12c5bdbf1dcd11e9b", "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 mult = mir(k as _) * npow[k-1];\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 * C) as _) * mult;\n dp[r] += 1;\n a = (a * x + y) % M;\n }\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": "d4270c3e05bc14948fde2c8a6d9fb657", "src_uid": "1d45491e28d24e2b318605cd328d6ecf", "difficulty": 2800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n\tlet mut inp = String::new();\n\tstdin().read_line(&mut inp).unwrap();\n\tlet n:u64 = inp.split_whitespace().nth(0).unwrap().parse().unwrap();\n\tlet k:u64 = inp.split_whitespace().nth(1).unwrap().parse().unwrap();\n\t//dbg!(n, k);\n\n\tlet half;\n\tif n%2 == 0 {\n\t\thalf = n/2;\n\t} else {\n\t\t half = n/2 + 1\n\t}\n\tlet out;\n\tif k <= half {\n\t\tout = k*2 - 1;\n\t} else {\n\t\tout = (k - half)*2\n\t}\n\tprintln!(\"{}\", out);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "e333220c6eb08cf8f2463b3650604f3a", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900.0, "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\nfn main() {\n let (n, mut k) = rt!(u128, u128);\n\n let odds_len = (n+1)/2;\n\n if k <= odds_len {\n println!(\"{}\", k*2-1);\n } else {\n k -= odds_len;\n println!(\"{}\", k*2);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "dcfef99f65951e23a1a8be74de386285", "src_uid": "1f8056884db00ad8294a7cc0be75fe97", "difficulty": 900.0, "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 = 4;\n let mut p = (0..n).map(|_| scan.next::()).collect::>();\n p.sort();\n p.dedup();\n\n writeln!(out, \"{}\", n - p.len()).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "48e44d54703354915b2d5fa23f27ce49", "src_uid": "38c4864937e57b35d3cce272f655e20f", "difficulty": 800.0, "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\nfn 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\nfn main() {\n let stdin = io::stdin();\n let mut v:Vec= vec![];\n read_ts(&stdin, &mut v);\n let mut hs = HashSet::new();\n for i in v {\n hs.insert(i);\n }\n println!(\"{}\", 4 - hs.len());\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "0f3080cc75e738554160ebadf4780233", "src_uid": "38c4864937e57b35d3cce272f655e20f", "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 (n, p) = (v[0] as usize, v[1]);\n Modulo::set_modulus(p);\n\n let mut fact = vec![Modulo::new(1); n + 1];\n for i in 2..fact.len() {\n fact[i] = fact[i - 1] * Modulo::new(i as i64);\n }\n\n let mut ans = Modulo::new(0);\n for l in 1..n + 1 {\n let place_cand = Modulo::new((n + 1 - l) as i64);\n let num_cand = Modulo::new((n + 1 - l) as i64);\n let inner_permutation = fact[l as usize];\n let outer_permutation = fact[(n - l) as usize];\n ans += place_cand * num_cand * inner_permutation * outer_permutation;\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\n#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]\nstruct Modulo(i64);\nstatic mut MODULUS: i64 = 0;\nimpl Modulo {\n fn set_modulus(m: i64) {\n unsafe {\n MODULUS = m;\n }\n }\n fn get_modulus() -> i64 {\n unsafe { MODULUS }\n }\n fn new(x: i64) -> Modulo {\n let m = Modulo::get_modulus();\n if x < 0 {\n Modulo(x % m + m)\n } else if x < m {\n Modulo(x)\n } else {\n Modulo(x % m)\n }\n }\n fn pow(self, p: i64) -> Modulo {\n if p == 0 {\n Modulo(1)\n } else {\n let mut t = self.pow(p / 2);\n t *= t;\n if p & 1 == 1 {\n t *= self;\n }\n t\n }\n }\n fn inv(self) -> Modulo {\n self.pow(Modulo::get_modulus() - 2)\n }\n}\nimpl std::fmt::Display for Modulo {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n self.0.fmt(f)\n }\n}\nimpl std::ops::AddAssign for Modulo {\n fn add_assign(&mut self, other: Modulo) {\n let m = Modulo::get_modulus();\n self.0 += other.0;\n if self.0 >= m {\n self.0 -= m;\n }\n }\n}\nimpl std::ops::MulAssign for Modulo {\n fn mul_assign(&mut self, other: Modulo) {\n let m = Modulo::get_modulus();\n self.0 *= other.0;\n self.0 %= m;\n }\n}\nimpl std::ops::SubAssign for Modulo {\n fn sub_assign(&mut self, other: Modulo) {\n let m = Modulo::get_modulus();\n self.0 += m - other.0;\n if self.0 >= m {\n self.0 -= m;\n }\n }\n}\nmacro_rules! impl_modulo_ops {\n ($imp:ident, $method:ident, $assign_imp:ident, $assign_method:ident) => {\n impl<'a> std::ops::$assign_imp<&'a Modulo> for Modulo {\n fn $assign_method(&mut self, other: &'a Modulo) {\n std::ops::$assign_imp::$assign_method(self, *other);\n }\n }\n impl std::ops::$imp for Modulo {\n type Output = Modulo;\n fn $method(self, other: Modulo) -> Modulo {\n let mut x = self;\n std::ops::$assign_imp::$assign_method(&mut x, other);\n x\n }\n }\n impl<'a> std::ops::$imp for &'a Modulo {\n type Output = Modulo;\n fn $method(self, other: Modulo) -> Modulo {\n std::ops::$imp::$method(*self, other)\n }\n }\n impl<'a> std::ops::$imp<&'a Modulo> for Modulo {\n type Output = Modulo;\n fn $method(self, other: &'a Modulo) -> Modulo {\n std::ops::$imp::$method(self, *other)\n }\n }\n impl<'a, 'b> std::ops::$imp<&'b Modulo> for &'a Modulo {\n type Output = Modulo;\n fn $method(self, other: &'b Modulo) -> Modulo {\n std::ops::$imp::$method(*self, *other)\n }\n }\n impl std::ops::$assign_imp for Modulo {\n fn $assign_method(&mut self, other: i64) {\n std::ops::$assign_imp::$assign_method(self, Modulo::new(other));\n }\n }\n impl<'a> std::ops::$assign_imp<&'a i64> for Modulo {\n fn $assign_method(&mut self, other: &'a i64) {\n std::ops::$assign_imp::$assign_method(self, *other);\n }\n }\n impl std::ops::$imp for Modulo {\n type Output = Modulo;\n fn $method(self, other: i64) -> Modulo {\n let mut x = self;\n std::ops::$assign_imp::$assign_method(&mut x, other);\n x\n }\n }\n impl<'a> std::ops::$imp<&'a i64> for Modulo {\n type Output = Modulo;\n fn $method(self, other: &'a i64) -> Modulo {\n std::ops::$imp::$method(self, *other)\n }\n }\n impl<'a> std::ops::$imp for &'a Modulo {\n type Output = Modulo;\n fn $method(self, other: i64) -> Modulo {\n std::ops::$imp::$method(*self, other)\n }\n }\n impl<'a, 'b> std::ops::$imp<&'b i64> for &'a Modulo {\n type Output = Modulo;\n fn $method(self, other: &'b i64) -> Modulo {\n std::ops::$imp::$method(*self, *other)\n }\n }\n };\n}\nimpl_modulo_ops!(Add, add, AddAssign, add_assign);\nimpl_modulo_ops!(Mul, mul, MulAssign, mul_assign);\nimpl_modulo_ops!(Sub, sub, SubAssign, sub_assign);\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics"], "code_uid": "2ccd8f8a94aafd3915abc6ebc95f8694", "src_uid": "020d5dae7157d937c3f58554c9b155f9", "difficulty": 1600.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: i64 = scan();\n let m: i64 = scan();\n let mut perm = vec![1i64; n as usize + 10];\n for i in 1..n + 1 {\n perm[i as usize] = perm[i as usize - 1] * i % m;\n }\n\n let mut ans = 0i64;\n for k in 1..n + 1 {\n let hoge =\n perm[(n - k) as usize] * (n - k + 1) % m * (n - k + 1) % m * perm[k as usize] % m;\n ans += hoge;\n ans %= m;\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": ["math", "combinatorics"], "code_uid": "ceda77b3813a0658fe1fce68eba31be0", "src_uid": "020d5dae7157d937c3f58554c9b155f9", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": " \nuse std::io::{self};\n\n#[derive(Copy, Clone)]\nstruct Div3 {\n remain0: i64,\n remain1: i64,\n remain2: i64,\n}\n\nfn main() {\n let mut m = vec![Div3{remain0: 0, remain1: 0, remain2: 0}; 10000005].into_boxed_slice();\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"???\");\n\n let x = buffer.trim().split(' ').map(|o| o.parse::().unwrap()).collect::>();\n let d = (x[2] - x[1] + 1) / 3;\n let moder: i64 = 1e9 as i64 + 7;\n\n let mut nums = Div3{\n remain0: d,\n remain1: d,\n remain2: d,\n };\n\n if (x[2] - x[1] + 1) % 3 > 0 {\n let t = {if (x[2] - x[1] + 1) % 3 == 2 {1} else {0}};\n if x[1] % 3 == 0 {\n nums.remain0 = nums.remain0 + 1;\n nums.remain1 = nums.remain1 + t;\n } else if x[1] % 3 == 1 {\n nums.remain1 = nums.remain1 + 1;\n nums.remain2 = nums.remain2 + t;\n } else {\n nums.remain2 = nums.remain2 + 1;\n nums.remain0 = nums.remain0 + t;\n }\n }\n\n m[1] = nums.clone();\n\n for i in 2..x[0]+1 {\n let it = i as usize;\n m[it].remain0 = ((m[it - 1].remain0 * nums.remain0) % moder + (m[it - 1].remain1 * nums.remain2) % moder + (m[it - 1].remain2 * nums.remain1) % moder) % moder;\n m[it].remain1 = ((m[it - 1].remain1 * nums.remain0) % moder + (m[it - 1].remain0 * nums.remain1) % moder + (m[it - 1].remain2 * nums.remain2) % moder) % moder;\n m[it].remain2 = ((m[it - 1].remain2 * nums.remain0) % moder + (m[it - 1].remain1 * nums.remain1) % moder + (m[it - 1].remain0 * nums.remain2) % moder) % moder;\n }\n\n println!(\"{}\", m[x[0] as usize].remain0 % moder);\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "08c76f755895cd07077ff537e62a03aa", "src_uid": "4c4852df62fccb0a19ad8bc41145de61", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::io;\nfn main() {\n let mut line = String::new();\n io::stdin()\n .read_line(&mut line)\n .expect(\"Error!\");\n let x: i32 = line.trim().parse().expect(\"Error!\");\n\n for _ in 0..x {\n let mut res = 0;\n let mut line1 = String::new();\n io::stdin()\n .read_line(&mut line1)\n .expect(\"Error!\");\n let b1 = line1.split_whitespace();\n for i in b1 { \n let _num: i32 = i.parse().expect(\"Error\");\n res += _num;\n } \n let mut line2 = String::new();\n io::stdin()\n .read_line(&mut line2)\n .expect(\"Error!\");\n let b2 = line2.split_whitespace();\n for i in b2 {\n let _num: i32 = i.parse().expect(\"Error\");\n res += _num;\n } \n match res {\n 0 => println!(\"0\"),\n 4 => println!(\"2\"),\n _ => println!(\"1\"),\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b580822f0edc8d82a3ea9a61afcf5f48", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800.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\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);\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\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[1..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);\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\n3\r\n0 0\r\n0 0\r\n1 0\r\n0 1\r\n1 1\r\n1 1\r\noutputCopy\r\n0\r\n1\r\n2\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 impl Write) {\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 c = 0;\r\n for _ in 0..4 {\r\n let a = scan.token::();\r\n c+=a;\r\n }\r\n if c==0 {\r\n writeln!(out, \"{}\", 0).ok();\r\n } else if c==4 {\r\n writeln!(out, \"{}\", 2).ok();\r\n } else {\r\n writeln!(out, \"{}\", 1).ok();\r\n }\r\n\r\n}\r\n\r\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7b777b8c11dda2f45270cd275d32caad", "src_uid": "7336b8becd2438f0439240ee8f9610ec", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\r\nuse std::collections::*;\r\nuse std::error::Error;\r\nuse std::fmt::write;\r\nuse std::hash::Hash;\r\nuse std::io;\r\nuse std::io::prelude::*;\r\nuse std::io::StdinLock;\r\nuse std::io::StdoutLock;\r\nuse std::io::Write;\r\nuse std::io::{stdin, stdout, BufRead, BufWriter};\r\nuse std::ops::Add;\r\n\r\nmacro_rules! fprintvec {\r\n ($dst:expr, $arg:expr) => {{\r\n writeln!(\r\n $dst,\r\n \"{}\",\r\n $arg.iter()\r\n .map(|x| format!(\"{} \", x))\r\n .collect::>()\r\n .join(\"\")\r\n )\r\n .ok();\r\n }};\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 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 = 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 pub fn next_split(&mut self) -> Vec {\r\n loop {\r\n let mut v = Vec::new();\r\n while let Some(token) = self.buf_iter.next() {\r\n v.push(token.parse().ok().expect(\"Failed parse\"));\r\n }\r\n if v.len() > 0 {\r\n return v;\r\n }\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\r\nfn lcm(first: usize, second: usize) -> usize {\r\n first * second / gcd(first, second)\r\n}\r\n\r\nfn gcd(first: usize, second: usize) -> usize {\r\n let mut max = first;\r\n let mut min = second;\r\n if min > max {\r\n let val = max;\r\n max = min;\r\n min = val;\r\n }\r\n\r\n loop {\r\n let res = max % min;\r\n if res == 0 {\r\n return min;\r\n }\r\n\r\n max = min;\r\n min = res;\r\n }\r\n}\r\n\r\nfn main() -> Result<(), Box> {\r\n let stdout = io::stdout();\r\n let lock = stdout.lock();\r\n let stdin = io::stdin();\r\n let mut ow = io::BufWriter::new(lock);\r\n let mut scan = Scanner::new(stdin.lock());\r\n\r\n let n_tests = scan.next::();\r\n\r\n for t_num in 1..=n_tests {\r\n let n = scan.next::();\r\n let m = scan.next_split::();\r\n let mut c = 1;\r\n let v = m[n - 1];\r\n if v == 0 {\r\n writeln!(ow, \"NO\");\r\n continue;\r\n }\r\n let vv = m[v - 1];\r\n if vv == 0 {\r\n writeln!(ow, \"NO\");\r\n continue;\r\n }\r\n writeln!(ow, \"YES\");\r\n // writeln!(ow, \"{}\", st.highest_bit());\r\n }\r\n Ok(())\r\n}\r\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "9a27bd9ef3e8f097a1fd6a8830de2cd0", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#![allow(unused_imports)]\nuse std::cmp::{max, min, Reverse};\nuse std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};\nuse std::io::{self, prelude::*};\nuse std::iter::Rev;\nuse std::ops::{Add, AddAssign, Deref};\nuse std::{num, str};\n\n\nfn solve(scan: &mut Scanner, w: &mut W) {\n let tt: usize = scan.token();\n for _ in 0..tt {\n let n: usize = scan.token();\n // let a: Vec = (0..3).map(|_| scan.token()).collect();\n let mut a = Vec::new();\n a.push(0);\n for _ in 0..3 {\n let ai: usize = scan.token();\n a.push(ai);\n }\n let mut vis = Vec::new();\n vis.resize(4, false);\n let mut now = n;\n loop {\n vis[now] = true;\n now = a[now];\n if vis[now] || now == a[now] {\n break;\n }\n }\n if vis[1] && vis[2] && vis[3] {\n writeln!(w, \"YES\");\n } else {\n writeln!(w, \"NO\");\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 solve(&mut scan, &mut out);\n}\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 {\n reader,\n buf_str: vec![],\n buf_iter: \"\".split_whitespace(),\n }\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\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_whitespace())\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "implementation", "math"], "code_uid": "3310c3d2ed6a49d2f715f7d832ba1ee8", "src_uid": "5cd113a30bbbb93d8620a483d4da0349", "difficulty": 800.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 fn should_flip(c: char) -> bool {\n (\n (c.is_digit(10) && (c as u8 - '0' as u8) % 2 == 1) ||\n (['a', 'e', 'i', 'o', 'u'].iter().find(|&&a| a == c).is_some())\n )\n }\n let flips = read_line()\n .expect(\"should have line\")\n .chars()\n .fold(0, |acc, c| if should_flip(c) { acc + 1 } else { acc });\n println!(\"{}\", flips);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "b77cf72468cc789be41e29c0b57387c4", "src_uid": "b4af2b8a7e9844bf58ad3410c2cb5223", "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 ($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 input! {\n s: chars,\n }\n let c = s.iter().filter(|&&c| {\n if c <= '9' {\n (c as u8 - b'0') % 2 == 1\n } else {\n ['a', 'e', 'i', 'o', 'u'].iter().find(|&&x| x == c).is_some()\n }\n }).count();\n puts!(\"{}\\n\", c);\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": "0e7a7490a38de6a262b9bad29a081da9", "src_uid": "b4af2b8a7e9844bf58ad3410c2cb5223", "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\n let mut vec = Vec::new();\n\n for counter in 0..3 {\n let side = input.next().unwrap().parse::().unwrap();\n vec.push(side);\n }\n\n for i in 0_usize..3_usize {\n for j in i..3_usize {\n if vec[i] > vec[j] {\n vec.swap(i,j);\n }\n }\n }\n\n let mut outcome = i32::default();\n outcome = vec[2] - vec[1] - vec[0] + 1;\n\n if outcome < 0 {\n println!(\"0\");\n } else {\n println!(\"{}\", &outcome);\n }\n\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "f21a68e842be4eeedd2308eb897fe32d", "src_uid": "3dc56bc08606a39dd9ca40a43c452f09", "difficulty": 800.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:i64,\n }\n let mut tot = 0;\n for i in 2..=n-1 {\n tot += i * (i+1);\n }\n writeln!(out,\"{}\",tot);\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp"], "code_uid": "1011e182b474ceb3f1cb8de51617d5ab", "src_uid": "1bd29d7a8793c22e81a1f6fd3991307a", "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\n where 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 w: Vec = get_vec();\n\n w.sort();\n\n let mut ans = None;\n\n for i in 0..2 * n {\n for j in i + 1..2 * n {\n let mut v = w.clone();\n v.remove(j);\n v.remove(i);\n let cur = v.into_iter().fold((0, false), |acc, x| {\n (if acc.1 {\n acc.0 + x\n } else {\n acc.0 - x\n },\n !acc.1)\n }).0;\n\n match ans {\n Some(x) if x <= cur => (),\n _ => ans = Some(cur),\n };\n }\n }\n\n println!(\"{}\", ans.unwrap());\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "3273627a9007d6e7647126c5748ad9a9", "src_uid": "76659c0b7134416452585c391daadb16", "difficulty": 1500.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\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 n = read!(inf,usize) * 2;\n\tlet mut w = vec![0usize; n];\n\tfor i in 0..n {\n\t\tw[i] = read!(inf,usize);\n\t}\n\tw.sort();\n\tlet mut ans = MOD;\n\tfor i in 0..n {\n\t\tfor j in i + 1..n {\n\t\t\tlet mut v = Vec::new();\n\t\t\tfor k in 0..n {\n\t\t\t\tif k != i && k != j {\n\t\t\t\t\tv.push(w[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet mut pos = 0;\n\t\t\tlet mut p = 0;\n\t\t\twhile pos < v.len() {\n\t\t\t\tp += v[pos + 1] - v[pos];\n\t\t\t\tpos += 2;\n\t\t\t}\n\t\t\tans = min(ans, p);\n\t\t}\n\t}\n\twriteln!(ouf, \"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "greedy"], "code_uid": "f12b3ff7ebe903850946824c1ca8e745", "src_uid": "76659c0b7134416452585c391daadb16", "difficulty": 1500.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::numbers::mod_int::ModIntF;\nuse crate::numbers::num_traits::as_index::AsIndex;\nuse crate::numbers::num_traits::zero_one::ZeroOne;\nuse crate::numbers::prime_fft::PrimeFFT;\nuse crate::out_line;\n\nfn solve(input: &mut Input, _test_case: usize) {\n let n = input.read_usize();\n let k = input.read_usize();\n let f = input.read_usize();\n\n type Mod = ModIntF;\n let mut fft = PrimeFFT::new();\n let mut a = vec![Mod::one(); k + 1];\n let mut b = fft.multiply(&a, &a);\n for _ in 1..n {\n let mut tail = b.iter().skip(k + 1).fold(Mod::zero(), |acc, &x| acc + x);\n for i in (0..=k).rev() {\n a[i] = tail + b[i] * Mod::from_index(k - i + 1);\n tail += b[i];\n }\n b = fft.multiply(&a, &a);\n }\n if f < b.len() {\n out_line!(b[f]);\n } else {\n out_line!(0);\n }\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::Single;\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 collections {\npub mod legacy_fill {\n// 1.50\npub trait LegacyFill {\n fn legacy_fill(&mut self, val: T);\n}\n\nimpl LegacyFill for [T] {\n fn legacy_fill(&mut self, val: T) {\n for el in self.iter_mut() {\n *el = val.clone();\n }\n }\n}\n\nimpl LegacyFill for Vec {\n fn legacy_fill(&mut self, val: T) {\n for el in self.iter_mut() {\n *el = val.clone();\n }\n }\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 misc {\npub mod value {\nuse std::hash::Hash;\n\npub trait Value: Copy + Eq + Hash {\n fn val() -> T;\n}\n\npub trait ConstValue: Value {\n const VAL: T;\n}\n\nimpl> Value for V {\n fn val() -> T {\n Self::VAL\n }\n}\n\n#[macro_export]\nmacro_rules! value {\n ($name: ident: $t: ty = $val: expr) => {\n #[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]\n pub struct $name {}\n\n impl $crate::misc::value::ConstValue<$t> for $name {\n const VAL: $t = $val;\n }\n };\n}\n\npub trait DynamicValue: Value {\n //noinspection RsSelfConvention\n fn set_val(t: T);\n}\n\n#[macro_export]\nmacro_rules! dynamic_value {\n ($name: ident: $t: ty) => {\n static mut VAL: Option<$t> = None;\n\n #[derive(Copy, Clone, Eq, PartialEq, Hash)]\n struct $name {}\n\n impl $crate::misc::value::DynamicValue<$t> for $name {\n fn set_val(t: $t) {\n unsafe {\n VAL = Some(t);\n }\n }\n }\n\n impl $crate::misc::value::Value<$t> for $name {\n fn val() -> $t {\n unsafe { VAL.unwrap() }\n }\n }\n };\n ($name: ident: $t: ty = $val: expr) => {\n dynamic_value!($name: $t);\n\n $name::set_val($val);\n };\n}\n}\n}\npub mod numbers {\npub mod gcd {\nuse crate::numbers::num_traits::add_sub::AddSub;\nuse crate::numbers::num_traits::mul_div_rem::{MulDivRem, Multable};\nuse crate::numbers::num_traits::wideable::Wideable;\nuse crate::numbers::num_traits::zero_one::ZeroOne;\nuse std::mem::swap;\n\npub fn extended_gcd(\n a: T,\n b: T,\n) -> (T, T::W, T::W)\nwhere\n T::W: Copy + ZeroOne + AddSub + Multable,\n{\n if a == T::zero() {\n (b, T::W::zero(), T::W::one())\n } else {\n let (d, y, mut x) = extended_gcd(b % a, a);\n x -= T::W::from(b / a) * y;\n (d, x, y)\n }\n}\n\npub fn gcd(mut a: T, mut b: T) -> T {\n while b != T::zero() {\n a %= b;\n swap(&mut a, &mut b);\n }\n a\n}\n\npub fn lcm(a: T, b: T) -> T {\n (a / gcd(a, b)) * b\n}\n}\npub mod mod_int {\nuse crate::io::input::{Input, Readable};\nuse crate::io::output::{Output, Writable};\nuse crate::misc::value::Value;\nuse crate::numbers::gcd::extended_gcd;\nuse crate::numbers::num_traits::add_sub::AddSub;\nuse crate::numbers::num_traits::as_index::AsIndex;\nuse crate::numbers::num_traits::from_u8::FromU8;\nuse crate::numbers::num_traits::invertable::Invertable;\nuse crate::numbers::num_traits::mul_div_rem::{MulDiv, MulDivRem};\nuse crate::numbers::num_traits::wideable::Wideable;\nuse crate::numbers::num_traits::zero_one::ZeroOne;\nuse crate::value;\nuse std::collections::HashMap;\nuse std::fmt::{Display, Formatter};\nuse std::hash::Hash;\nuse std::marker::PhantomData;\nuse std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};\n\npub trait BaseModInt:\n AddSub + MulDiv + Neg + Copy + ZeroOne + PartialEq + Invertable\n{\n type W: AddSub + MulDivRem + Copy + ZeroOne + From;\n type T: AddSub + MulDivRem + Copy + PartialEq + ZeroOne + Wideable + Ord;\n\n fn from(v: Self::T) -> Self;\n fn module() -> Self::T;\n}\n\n#[derive(Copy, Clone, Eq, PartialEq, Hash, Default)]\npub struct ModInt> {\n n: T,\n phantom: PhantomData,\n}\n\nimpl> ModInt {\n pub fn val(&self) -> T {\n self.n\n }\n}\n\nimpl> ModInt {\n unsafe fn unchecked_new(n: T) -> Self {\n debug_assert!(n >= T::zero() && n < V::val());\n Self {\n n,\n phantom: Default::default(),\n }\n }\n\n unsafe fn maybe_subtract_mod(mut n: T) -> T {\n debug_assert!(n < V::val() + V::val() && n >= T::zero());\n if n >= V::val() {\n n -= V::val();\n }\n n\n }\n}\n\nimpl> ModInt {\n pub fn new(n: T) -> Self {\n unsafe { Self::unchecked_new(Self::maybe_subtract_mod(n % (V::val()) + V::val())) }\n }\n}\n\nimpl>\n ModInt\nwhere\n T::W: Copy + ZeroOne + AddSub + MulDivRem,\n{\n pub fn log(&self, alpha: Self) -> T {\n let mut base = HashMap::new();\n let mut exp = T::zero();\n let mut pow = Self::one();\n let mut inv = *self;\n let alpha_inv = alpha.inv().unwrap();\n while exp * exp < Self::module() {\n if inv == Self::one() {\n return exp;\n }\n base.insert(inv, exp);\n exp += T::one();\n pow *= alpha;\n inv *= alpha_inv;\n }\n let step = pow;\n let mut i = T::one();\n loop {\n if let Some(b) = base.get(&pow) {\n break exp * i + *b;\n }\n pow *= step;\n i += T::one();\n }\n }\n}\n\nimpl> ModInt\nwhere\n T::W: MulDivRem,\n{\n pub fn new_from_wide(n: T::W) -> Self {\n unsafe {\n Self::unchecked_new(Self::maybe_subtract_mod(\n T::downcast(n % (V::val()).into()) + V::val(),\n ))\n }\n }\n}\n\nimpl> Invertable\n for ModInt\nwhere\n T::W: Copy + ZeroOne + AddSub + MulDivRem,\n{\n type Output = Self;\n\n fn inv(&self) -> Option {\n let (g, x, _) = extended_gcd(self.n, V::val());\n if g != T::one() {\n None\n } else {\n Some(Self::new_from_wide(x))\n }\n }\n}\n\nimpl> BaseModInt\n for ModInt\nwhere\n T::W: AddSub + MulDivRem + Copy + ZeroOne,\n{\n type W = T::W;\n type T = T;\n\n fn from(v: Self::T) -> Self {\n Self::new(v)\n }\n\n fn module() -> T {\n V::val()\n }\n}\n\nimpl> From for ModInt {\n fn from(n: T) -> Self {\n Self::new(n)\n }\n}\n\nimpl> AddAssign for ModInt {\n fn add_assign(&mut self, rhs: Self) {\n self.n = unsafe { Self::maybe_subtract_mod(self.n + rhs.n) };\n }\n}\n\nimpl> Add for ModInt {\n type Output = Self;\n\n fn add(mut self, rhs: Self) -> Self::Output {\n self += rhs;\n self\n }\n}\n\nimpl> SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: Self) {\n self.n = unsafe { Self::maybe_subtract_mod(self.n + V::val() - rhs.n) };\n }\n}\n\nimpl> Sub for ModInt {\n type Output = Self;\n\n fn sub(mut self, rhs: Self) -> Self::Output {\n self -= rhs;\n self\n }\n}\n\nimpl> MulAssign\n for ModInt\nwhere\n T::W: MulDivRem + Copy,\n{\n fn mul_assign(&mut self, rhs: Self) {\n self.n = T::downcast(T::W::from(self.n) * T::W::from(rhs.n) % T::W::from(V::val()));\n }\n}\n\nimpl> Mul for ModInt\nwhere\n T::W: MulDivRem + Copy,\n{\n type Output = Self;\n\n fn mul(mut self, rhs: Self) -> Self::Output {\n self *= rhs;\n self\n }\n}\n\nimpl> DivAssign\n for ModInt\nwhere\n T::W: AddSub + MulDivRem + Copy + ZeroOne,\n{\n #[allow(clippy::suspicious_op_assign_impl)]\n fn div_assign(&mut self, rhs: Self) {\n *self *= rhs.inv().unwrap();\n }\n}\n\nimpl> Div\n for ModInt\nwhere\n T::W: AddSub + MulDivRem + Copy + ZeroOne,\n{\n type Output = Self;\n\n fn div(mut self, rhs: Self) -> Self::Output {\n self /= rhs;\n self\n }\n}\n\nimpl> Neg for ModInt {\n type Output = Self;\n\n fn neg(mut self) -> Self::Output {\n self.n = unsafe { Self::maybe_subtract_mod(V::val() - self.n) };\n self\n }\n}\n\nimpl> Display for ModInt {\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n ::fmt(&self.n, f)\n }\n}\n\nimpl> Readable\n for ModInt\n{\n fn read(input: &mut Input) -> Self {\n Self::new(T::read(input))\n }\n}\n\nimpl> Writable for ModInt {\n fn write(&self, output: &mut Output) {\n self.n.write(output);\n }\n}\n\nimpl> ZeroOne for ModInt {\n fn zero() -> Self {\n unsafe { Self::unchecked_new(T::zero()) }\n }\n\n fn one() -> Self {\n Self::new(T::one())\n }\n}\n\nimpl> Wideable for ModInt {\n type W = Self;\n\n fn downcast(w: Self::W) -> Self {\n w\n }\n}\n\nimpl> FromU8 for ModInt {\n fn from_u8(n: u8) -> Self {\n Self::new(T::from_u8(n))\n }\n}\n\nimpl<\n T: AddSub + MulDivRem + Copy + PartialEq + Wideable + ZeroOne + Ord + Display + FromU8,\n V: Value,\n > std::fmt::Debug for ModInt\nwhere\n T::W: AddSub + MulDivRem + Copy + ZeroOne,\n{\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n let max = T::from_u8(100);\n if self.n <= max {\n write!(f, \"{}\", self.n)\n } else if self.n >= V::val() - max {\n write!(f, \"-{}\", V::val() - self.n)\n } else {\n let mut denominator = T::one();\n while denominator < max {\n let mut num = T::one();\n while num < max {\n if Self::new(num) / Self::new(denominator) == *self {\n return write!(f, \"{}/{}\", num, denominator);\n }\n if -Self::new(num) / Self::new(denominator) == *self {\n return write!(f, \"-{}/{}\", num, denominator);\n }\n num += T::one();\n }\n denominator += T::one();\n }\n write!(f, \"(?? {} ??)\", self.n)\n }\n }\n}\n\nimpl> AsIndex for ModInt {\n fn from_index(idx: usize) -> Self {\n Self::new(T::from_index(idx))\n }\n\n fn to_index(&self) -> usize {\n self.n.to_index()\n }\n}\n\nvalue!(Val7: i32 = 1_000_000_007);\npub type ModInt7 = ModInt;\n\nvalue!(Val9: i32 = 1_000_000_009);\npub type ModInt9 = ModInt;\n\nvalue!(ValF: i32 = 998_244_353);\npub type ModIntF = ModInt;\n}\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 as_index {\npub trait AsIndex {\n fn from_index(idx: usize) -> Self;\n fn to_index(&self) -> usize;\n}\n\nmacro_rules! from_index_impl {\n ($($t: ident)+) => {$(\n impl AsIndex for $t {\n fn from_index(idx: usize) -> Self {\n idx as $t\n }\n\n fn to_index(&self) -> usize {\n *self as usize\n }\n }\n )+};\n}\n\nfrom_index_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize);\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 invertable {\npub trait Invertable: Sized {\n type Output;\n\n fn inv(&self) -> Option;\n}\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 wideable {\nuse std::convert::From;\n\npub trait Wideable: Sized {\n type W: From;\n\n fn downcast(w: Self::W) -> Self;\n}\n\nmacro_rules! wideable_impl {\n ($($t: ident $w: ident),+) => {$(\n impl Wideable for $t {\n type W = $w;\n\n fn downcast(w: Self::W) -> Self {\n w as $t\n }\n }\n )+};\n}\n\nwideable_impl!(i128 i128, i64 i128, i32 i64, i16 i32, i8 i16, isize isize, u128 u128, u64 u128, u32 u64, u16 u32, u8 u16, usize usize, f64 f64, f32 f64);\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}\npub mod number_ext {\nuse crate::numbers::num_traits::add_sub::AddSub;\nuse crate::numbers::num_traits::from_u8::FromU8;\nuse crate::numbers::num_traits::mul_div_rem::{MulDiv, MulDivRem, Multable};\nuse crate::numbers::num_traits::zero_one::ZeroOne;\n\npub trait Power {\n #[must_use]\n fn power(&self, exp: T) -> Self;\n}\n\nimpl Power for S {\n fn power(&self, exp: T) -> Self {\n if exp == T::zero() {\n S::one()\n } else if exp % (T::one() + T::one()) == T::zero() {\n let res = self.power(exp / (T::one() + T::one()));\n res * res\n } else {\n self.power(exp - T::one()) * (*self)\n }\n }\n}\n\npub trait NumDigs {\n fn num_digs(&self) -> usize;\n}\n\nimpl NumDigs for S {\n fn num_digs(&self) -> usize {\n let mut copy = *self;\n let ten = S::from_u8(10);\n let mut res = 0;\n while copy != S::zero() {\n copy /= ten;\n res += 1;\n }\n res\n }\n}\n}\npub mod prime_fft {\nuse crate::collections::legacy_fill::LegacyFill;\nuse crate::numbers::mod_int::BaseModInt;\nuse crate::numbers::num_traits::zero_one::ZeroOne;\nuse crate::numbers::number_ext::Power;\n\npub struct PrimeFFT {\n root: M,\n reverse_root: M,\n root_power: M::T,\n aa: Vec,\n bb: Vec,\n}\n\nimpl Default for PrimeFFT {\n fn default() -> Self {\n Self::new()\n }\n}\n\nimpl PrimeFFT {\n pub fn new() -> Self {\n let mut exp = M::T::zero();\n let mut root_power = M::T::one();\n while (M::module() - M::T::one()) % (root_power + root_power) == M::T::zero() {\n exp = root_power;\n root_power += root_power;\n }\n let mut i = M::one() + M::one();\n loop {\n if i.power(exp) != M::one() && i.power(root_power) == M::one() {\n break Self {\n root: i,\n reverse_root: i.inv().unwrap(),\n root_power,\n aa: Vec::new(),\n bb: Vec::new(),\n };\n }\n i += M::one();\n }\n }\n\n pub fn multiply_res(&mut self, a: &[M], b: &[M], res: &mut Vec) {\n if a.is_empty() || b.is_empty() {\n res.legacy_fill(M::zero());\n return;\n }\n let res_len = a.len() + b.len() - 1;\n if res_len <= Self::BORDER_LEN {\n res.legacy_fill(M::zero());\n for (i, f) in a.iter().enumerate() {\n for (j, s) in b.iter().enumerate() {\n res[i + j] += (*f) * (*s);\n }\n }\n return;\n }\n let mut size = 1;\n let mut size_t = M::T::one();\n while size < res_len {\n size *= 2;\n size_t += size_t;\n }\n if self.root_power < size_t {\n panic!(\"unsuitable modulo\");\n }\n if self.aa.len() < size {\n let was_len = self.aa.len();\n self.aa[..was_len.min(a.len())].copy_from_slice(&a[..was_len.min(a.len())]);\n self.aa[was_len.min(a.len())..].legacy_fill(M::zero());\n self.aa.extend_from_slice(&a[was_len.min(a.len())..]);\n self.aa.reserve(size - self.aa.len());\n for _ in self.aa.len()..size {\n self.aa.push(M::zero());\n }\n } else {\n self.aa[..a.len()].copy_from_slice(a);\n self.aa[a.len()..size].legacy_fill(M::zero());\n }\n Self::fft(\n &mut self.aa[..size],\n false,\n self.root,\n self.root_power,\n size_t,\n );\n if a == b {\n for i in self.aa[..size].iter_mut() {\n *i *= *i;\n }\n } else {\n if self.bb.len() < size {\n let was_len = self.bb.len();\n self.bb[..was_len.min(b.len())].copy_from_slice(&b[..was_len.min(b.len())]);\n self.bb[was_len.min(b.len())..].legacy_fill(M::zero());\n self.bb.extend_from_slice(&b[was_len.min(b.len())..]);\n self.bb.reserve(size - self.bb.len());\n for _ in self.bb.len()..size {\n self.bb.push(M::zero());\n }\n } else {\n self.bb[..b.len()].copy_from_slice(b);\n self.bb[b.len()..size].legacy_fill(M::zero());\n }\n Self::fft(\n &mut self.bb[..size],\n false,\n self.root,\n self.root_power,\n size_t,\n );\n for (i, j) in self.aa[..size].iter_mut().zip(self.bb[..size].iter()) {\n *i *= *j;\n }\n }\n Self::fft(\n &mut self.aa[..size],\n true,\n self.reverse_root,\n self.root_power,\n size_t,\n );\n if res.len() < res_len {\n let was_len = res.len();\n res.copy_from_slice(&self.aa[..was_len]);\n res.extend_from_slice(&self.aa[was_len..res_len]);\n } else {\n res.copy_from_slice(&self.aa[..res_len]);\n res[res_len..].legacy_fill(M::zero());\n }\n }\n\n pub fn multiply(&mut self, a: &[M], b: &[M]) -> Vec {\n if a.is_empty() || b.is_empty() {\n Vec::new()\n } else {\n let mut res = vec![M::zero(); a.len() + b.len() - 1];\n self.multiply_res(a, b, &mut res);\n res\n }\n }\n\n const BORDER_LEN: usize = 100;\n\n fn fft(a: &mut [M], invert: bool, root: M, root_power: M::T, size_t: M::T) {\n let mut j = 0usize;\n for i in 1..a.len() {\n let mut bit = a.len() >> 1;\n while j >= bit {\n j -= bit;\n bit >>= 1;\n }\n j += bit;\n if i < j {\n a.swap(i, j);\n }\n }\n\n let mut len = 2;\n let mut len_t = M::T::one() + M::T::one();\n while len <= a.len() {\n let mut w_len = root;\n let mut i = len_t;\n while i < root_power {\n w_len *= w_len;\n i += i;\n }\n let half = len >> 1;\n for i in (0..a.len()).step_by(len) {\n let mut w = M::one();\n for j in 0..half {\n let u = a[i + j];\n let v = a[i + j + half] * w;\n a[i + j] = u + v;\n a[i + j + half] = u - v;\n w *= w_len;\n }\n }\n len <<= 1;\n len_t += len_t;\n }\n if invert {\n let inv_size = M::from(size_t).inv().unwrap();\n for i in a {\n *i *= inv_size;\n }\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": ["brute force", "flows", "math", "dp", "fft", "bitmasks", "graphs", "meet-in-the-middle", "trees"], "code_uid": "4c01248a63b3e36e2ba812532059ccea", "src_uid": "4b8161259545e44c7d1046be2e4fe014", "difficulty": 2500.0, "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\nconst MOD: i64 = (7 * 17 * (1 << 23)) + 1;\n\nfn ntt(a: &mut Vec, dir: bool)\n{\n\tlet w = {\n\t\tlet mut v: Vec = vec![if dir { 31 } else { 128805723 }];\n\t\twhile v.last().unwrap() != &1 {\n\t\t\tv.push(v.last().unwrap().pow(2) % MOD);\n\t\t}\n\t\tv.reverse();\n\t\tv\n\t};\n\n\tfn lg(x: usize) -> usize { (usize::BITS - 1 - x.leading_zeros()) as usize }\n\n\tassert!(a.len().is_power_of_two());\n\tlet n = a.len();\n\tlet lgn = lg(n);\n\n\tlet rev = {\n\t\tlet mut v = vec![0];\n\t\tfor x in 1..n {\n\t\t\tv.push(v[x/2]/2 ^ x%2 << lgn-1);\n\t\t}\n\t\tv\n\t};\n\n\tfor i in 0..n {\n\t\tif i > rev[i] {\n\t\t\ta.swap(i, rev[i]);\n\t\t}\n\t}\n\n\tfor len in (1..=lgn).map(|x| 1<) -> Vec\n{\n\tlet mut ans = a.clone();\n\tans.resize(ans.len().next_power_of_two() * 2, 0);\n\tntt(&mut ans, false);\n\tans = ans.into_iter().map(|x| x*x % MOD).collect();\n\tntt(&mut ans, true);\n\tans.resize(a.len(), 0);\n\tans\n}\n\nfn main()\n{\n\tlet (n, k, f): (usize, usize, usize) = (scan(), scan(), scan());\n\n\tlet mut a = vec![vec![0i64; 2*k+1]; n+1];\n\tlet mut a2 = vec![vec![0i64; 2*k+2]; n+1];\n\tlet mut b = a.clone();\n\tlet mut b2 = a2.clone();\n\n\tfor i in 0..a2[0].len() { a2[0][i] = 1; }\n\tfor i in 0..=k { b[0][i] = 1; b2[0][i] = (k+1 - i) as i64; }\n\t\n\tfor i in 1..=n {\n\t\ta[i] = pow2(&b[i-1]);\n\t\tfor j in (0..=2*k).rev() { a2[i][j] = (a[i][j] + a2[i][j+1]) % MOD; }\n\t\tfor j in 0..=k { b[i][j] = ((k-j) as i64 * a[i][j] + a2[i][j]) % MOD; }\n\t\tfor j in (0..=k).rev() { b2[i][j] = (b[i][j] + b2[i][j+1]) % MOD; }\n\t}\n\n\tprintln!(\"{}\", if f < a[n].len() { a[n][f] } else { 0 });\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "flows", "math", "dp", "fft", "bitmasks", "graphs", "meet-in-the-middle", "trees"], "code_uid": "56dcf0fe445dd744c42804cfdbd00970", "src_uid": "4b8161259545e44c7d1046be2e4fe014", "difficulty": 2500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::{max, min};\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: Vec = text\n .trim()\n .split_whitespace()\n .map(|e| e.parse().unwrap())\n .collect();\n let mut v: Vec = vec![];\n for x in 1..(text.len() + 1) {\n let mut value = 0;\n for a in 1..(text.len() + 1) {\n value += (abs(x, a) + abs(1, a) + abs(1, x)) * text[a - 1] * 2\n }\n v.push(value)\n }\n v.sort();\n\n println!(\"{}\", v[0]);\n}\nfn abs(a: usize, b: usize) -> usize {\n max(a, b) - min(a, b)\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "4dc498b5b576bf88783fed58e41c8099", "src_uid": "a5002ddf9e792cb4b4685e630f1e1b8f", "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\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 println!(concat!($(stringify!($a), \"={:?} \"),*), $($a),*);\n }\n}\n\n#[allow(unused_imports)]\nuse std::cmp::{min, max};\n\nfn main() {\n input!{\n n: usize,\n aa: [i64; n],\n }\n let mut ans: i64 = 1 << 32;\n for i in 0i64..n as i64 {\n let mut cost = 0;\n for j in 0i64..n as i64 {\n cost += ((j-i).abs() + j + i) * 2 * aa[j as usize] as i64;\n }\n ans = min(cost, ans);\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "752b1979749a85a240c689eaa5321628", "src_uid": "a5002ddf9e792cb4b4685e630f1e1b8f", "difficulty": 1000.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\nuse std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Neg};\n\nimpl 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 AddAssign for ModInt {\n fn add_assign(&mut self, rhs: ModInt) {\n *self = *self + rhs;\n }\n}\n\nimpl 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 SubAssign for ModInt {\n fn sub_assign(&mut self, rhs: ModInt) {\n *self = *self - rhs;\n }\n}\n\nimpl 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 MulAssign for ModInt {\n fn mul_assign(&mut self, rhs: ModInt) {\n *self = *self * rhs;\n }\n}\n\nimpl 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#[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 mut n: u64 = it.next().unwrap().parse().unwrap();\n let k: usize = it.next().unwrap().parse().unwrap();\n let pc = Precalc::new(50);\n let mut ans = ModInt::one();\n let mut d = 2u64;\n while d * d <= n {\n if n % d == 0 {\n let mut c = 0;\n while n % d == 0 {\n c += 1;\n n /= d;\n }\n let mut dp = vec![ModInt::zero(); c + 1];\n dp[c] = ModInt::one();\n for _ in 0..k {\n let mut next = vec![ModInt::zero(); c + 1];\n for i in 0..=c {\n next[i] += dp[i] * pc.inv(i + 1);\n }\n for i in (0..c).rev() {\n next[i] = next[i] + next[i + 1];\n }\n dp = next;\n }\n let mut s = ModInt::zero();\n let mut f = 1u64;\n for i in 0..=c {\n s += ModInt((f % MOD as u64) as u32) * dp[i];\n f *= d;\n }\n ans *= s;\n }\n d += 1;\n }\n if n > 1 {\n let p = pc.inv(2).pow(k as u32);\n ans *= (ModInt::one() - p) + ModInt((n % MOD as u64) as u32) * p;\n }\n println!(\"{}\", ans.0);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "probabilities", "number theory"], "code_uid": "e75493100f802712d6e8364376a7712d", "src_uid": "dc466d9c24b7dcb37c0e99337b4124d2", "difficulty": 2200.0, "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\nmacro_rules! array {\n ( $t:ty ; $size:expr ) => {\n [<$t>::default(); $size]\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 table: String;\n let mut hands = Vec::::new();\n\n table = stdin.read();\n for i in 0..5 {\n hands.push(stdin.read());\n }\n\n let mut result = false;\n for i in 0..5 {\n if table.bytes().zip(hands[i].bytes()).any(|(x, y)| x == y) {\n result = true;\n break;\n }\n }\n println!(\"{}\", if result { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "2ca8c59c1d3c768f7769032c7482835b", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "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 s = input.s();\n println!(\"{}\", if (0..5).any(|_| {\n let t = input.s();\n s.bytes().zip(t.bytes()).any(|(a,b)| a == b)\n }) {\n \"YES\"\n } else {\n \"NO\"\n });\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "1570c3ca12a0464e1f3cc85a27a9d0b4", "src_uid": "699444eb6366ad12bc77e7ac2602d74b", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nconst days: &[u8] = &[\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 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\nfn user_input() -> Vec\n where ::Err: std::fmt::Debug\n{\n let mut text = String::new();\n std::io::stdin()\n .read_to_string(&mut text);\n text\n .split_whitespace()\n .map(|e| e.parse().unwrap())\n .collect()\n}\n\nfn main() {\n let mut input = user_input::().into_iter();\n let count = input.next().unwrap().to_owned() as usize;\n \n let pattern = input.collect::>();\n let mut matches = false;\n for i in 0..(days.len() - count) {\n if days[i..(i+count)] == pattern[..] {\n matches = true;\n break;\n }\n }\n \n if matches {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "2fa389c1e0e78b4d5620c9d8d416607e", "src_uid": "d60c8895cebcc5d0c6459238edbdb945", "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_leap = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n let leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n let table: Vec = n_leap\n .iter()\n .chain(n_leap.iter())\n .chain(leap.iter())\n .chain(n_leap.iter())\n .chain(n_leap.iter())\n .cloned()\n .collect();\n\n let n = get!(usize);\n let ms = get!(usize;;);\n\n if (0..table.len() - n).any(|i| &table[i..i + n] == &ms[..]) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9320a7b76bc64c1fee2a729ed7220630", "src_uid": "d60c8895cebcc5d0c6459238edbdb945", "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 line\n}\n\nfn main() {\n if read_line().chars().any(|c| \"HQ9\".find(c).is_some()) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7a68088a8b91ea068ca57b48958b846e", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "difficulty": 900.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\n let mut ans = \"NO\";\n for ch in s.chars() {\n match ch {\n 'H' | 'Q' | '9' => {\n ans = \"YES\";\n break;\n }\n _ => {\n continue;\n }\n }\n }\n\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "93a3076d259adf6e8f1565dec9290c81", "src_uid": "1baf894c1c7d5aeea01129c7900d3c12", "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 digit_sum(n: u32) -> u32 {\n let mut ans = 0;\n let mut n = n;\n while n > 0 {\n ans += n % 10;\n n /= 10;\n }\n ans\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n\n let mut k: usize = scan.token();\n let mut num = 0;\n while k > 0 {\n num += 1;\n if digit_sum(num) == 10 {\n k -= 1;\n }\n }\n writeln!(out, \"{}\", num).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", "dp", "binary search", "implementation", "number theory"], "code_uid": "e5e41b5d827ccbf7e1def067c09412a5", "src_uid": "0a98a6a15e553ce11cb468d3330fc86a", "difficulty": 1100.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 b(n: u32) -> bool {\n let mut sum = 0;\n let mut k = n;\n while k > 0 {\n sum += k % 10;\n k /= 10;\n }\n return sum == 10;\n}\n\nfn main() {\n let mut k: u32 = read_line().parse().unwrap();\n let mut i = 0u32;\n while k > 0 {\n i += 1;\n if b(i) {\n k -= 1;\n }\n }\n\n println!(\"{}\", i);\n \n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp", "binary search", "implementation", "number theory"], "code_uid": "dbea9c601df2dba638fc3add6224908d", "src_uid": "0a98a6a15e553ce11cb468d3330fc86a", "difficulty": 1100.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, 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// 同じ値のみを聞き出す戦略\n// 同じ値のみを残せるように聞く戦略\n// 同じ値を残せるように聞く戦略ができるならのみを聞き出すことも可能\n//\n// 同じ値のみを残す\n// a をk 個聞き出せる条件は\n// aを使わないで(k - i) * a を作れないこと\n// 分割統治bitset?\n\nuse std::cmp::*;\n\nfn run() {\n input! {\n n: usize,\n a: [usize; n],\n }\n let mut a = a.into_iter().map(|a| (a, 1)).collect::>();\n a.sort();\n a.dedup_by(|a, b| {\n a.0 == b.0 && {\n b.1 += a.1;\n true\n }\n });\n if a.len() <= 2 {\n println!(\"{}\", n);\n return;\n }\n let w = a.iter().fold(0, |s, a| s + a.0 * a.1);\n let mut dp = vec![vec![0u8; w + 1]; n + 1];\n dp[0][0] = 1;\n for &(a, c) in a.iter() {\n for i in (1..=n).rev() {\n for j in a..=w {\n let mut v = dp[i][j];\n for k in 1..=min(j / a, min(i, c)) {\n v = v.saturating_add(dp[i - k][j - k * a]);\n }\n dp[i][j] = v;\n }\n }\n }\n /*\n for i in 0..=n {\n for j in 0..=w {\n print!(\"{} \", dp[i][j]);\n }\n println!();\n }\n */\n let mut ans = 1;\n for &(a, c) in a.iter() {\n for k in 2..=c {\n if dp[k][k * a] == 1 || dp[n - k][w - k * a] == 1 {\n ans = max(ans, k);\n }\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "90e41586c4cbc8906ff4cec701f223cd", "src_uid": "ccc4b27889598266e8efe73b8aa3666c", "difficulty": 2100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// ---------- begin BitSet ----------\n#[derive(Clone)]\nstruct BitSet {\n size: usize,\n a: Vec,\n}\n\nfn bit_size() -> usize {\n 8 * std::mem::size_of::()\n}\n\nfn quot_rem(n: usize) -> (usize, usize) {\n let w = bit_size();\n (n / w, n % w)\n}\n\n#[allow(dead_code)]\nimpl BitSet {\n fn new(size: usize) -> Self {\n let w = bit_size();\n BitSet {\n size: size,\n a: vec![0; (size + w - 1) / w],\n }\n }\n fn set_at(&mut self, x: usize) {\n assert!(x < self.size);\n let (q, r) = quot_rem(x);\n self.a[q] |= 1 << r;\n }\n fn clear_at(&mut self, x: usize) {\n assert!(x < self.size);\n let (q, r) = quot_rem(x);\n self.a[q] &= !(1 << r);\n }\n fn get_at(&self, x: usize) -> bool {\n if x >= self.size {\n return false;\n }\n let (q, r) = quot_rem(x);\n (self.a[q] >> r) & 1 == 1\n }\n fn any(&self) -> bool {\n self.a.iter().any(|a| *a != 0)\n }\n fn fix(&mut self) {\n let (q, r) = quot_rem(self.size);\n if r != 0 {\n self.a[q] &= (1 << r) - 1;\n }\n }\n fn clear(&mut self) {\n let len = self.a.len();\n self.a.clear();\n self.a.resize(len, 0);\n }\n fn truncate(&mut self, len: usize) {\n if len >= self.size {\n return;\n }\n let w = bit_size();\n self.a.truncate((len + w - 1) / w);\n self.size = len;\n self.fix();\n }\n fn popcnt(&self) -> usize {\n self.a.iter().fold(0, |s, a| s + a.count_ones() as usize)\n }\n fn shift_left(&self, rhs: usize) -> Self {\n let (q, r) = quot_rem(rhs);\n let mut ans = BitSet::new(self.size + rhs);\n if r == 0 {\n for (x, y) in ans.a[q..].iter_mut().zip(self.a.iter()) {\n *x = *y;\n }\n } else {\n let w = bit_size();\n let mut prev = 0;\n for (x, y) in ans.a[q..].iter_mut().zip(self.a.iter()) {\n *x = (*y << r) | (prev >> (w - r));\n prev = *y;\n }\n *ans.a.last_mut().unwrap() |= prev >> (w - r);\n }\n ans.fix();\n ans\n }\n fn shift_right(&self, rhs: usize) -> Self {\n if rhs >= self.size {\n return BitSet::new(1);\n }\n let (q, r) = quot_rem(rhs);\n let mut ans = BitSet::new(self.size - rhs);\n if r == 0 {\n for (x, y) in ans.a.iter_mut().zip(self.a[q..].iter()) {\n *x = *y;\n }\n } else {\n let w = bit_size();\n let mut prev = 0;\n for (x, y) in ans.a.iter_mut().zip(self.a[q..].iter()).rev() {\n *x |= (*y >> r) | (prev << (w - r));\n prev = *y;\n }\n }\n ans.fix();\n ans\n }\n fn bitwise_or(&self, rhs: &Self) -> Self {\n let (x, y) = if self.size >= rhs.size {\n (self, rhs)\n } else {\n (rhs, self)\n };\n let mut a = x.a.clone();\n for (a, y) in a.iter_mut().zip(y.a.iter()) {\n *a |= *y;\n }\n BitSet { size: x.size, a: a }\n }\n fn bitwise_and(&self, rhs: &Self) -> Self {\n let (x, y) = if self.size <= rhs.size {\n (self, rhs)\n } else {\n (rhs, self)\n };\n let mut a = x.a.clone();\n for (a, y) in a.iter_mut().zip(y.a.iter()) {\n *a &= *y;\n }\n BitSet { size: x.size, a: a }\n }\n fn bitwise_xor(&self, rhs: &Self) -> Self {\n let (x, y) = if self.size >= rhs.size {\n (self, rhs)\n } else {\n (rhs, self)\n };\n let mut a = x.a.clone();\n for (a, y) in a.iter_mut().zip(y.a.iter()) {\n *a ^= *y;\n }\n BitSet { size: x.size, a: a }\n }\n fn bitwise_or_assign(&mut self, rhs: &Self) {\n if self.size < rhs.size {\n self.size = rhs.size;\n self.a.resize(rhs.a.len(), 0);\n }\n for (a, b) in self.a.iter_mut().zip(rhs.a.iter()) {\n *a |= *b;\n }\n }\n fn bitwise_and_assign(&mut self, rhs: &Self) {\n if self.size > rhs.size {\n self.size = rhs.size;\n self.a.resize(rhs.a.len(), 0);\n }\n for (a, b) in self.a.iter_mut().zip(rhs.a.iter()) {\n *a &= *b;\n }\n }\n fn bitwise_xor_assign(&mut self, rhs: &Self) {\n if self.size < rhs.size {\n self.size = rhs.size;\n self.a.resize(rhs.a.len(), 0);\n }\n for (a, b) in self.a.iter_mut().zip(rhs.a.iter()) {\n *a ^= *b;\n }\n }\n}\n// ---------- end BitSet ----------\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, 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// 同じ値のみを聞き出す戦略\n// 同じ値のみを残せるように聞く戦略\n// 同じ値を残せるように聞く戦略ができるならのみを聞き出すことも可能\n//\n// 同じ値のみを残す\n// a をk 個聞き出せる条件は\n// aを使わないで(k - i) * a を作れないこと\n// 分割統治bitset?\n\nfn calc(a: &[(usize, usize)], dp: &[BitSet]) -> usize {\n let n = a.len();\n if n == 1 {\n let (a, c) = a[0];\n let mut ans = 1;\n for k in 2..=c {\n let mut ok = true;\n for j in 0..k {\n ok &= !dp[k - j].get_at(a * (k - j));\n }\n if ok {\n ans = k;\n }\n }\n return ans;\n }\n let (l, r) = a.split_at(n / 2);\n let mut p = vec![];\n p.extend_from_slice(dp);\n for &(a, c) in l.iter() {\n for _ in 0..c {\n for i in (1..dp.len()).rev() {\n let mut set = p[i].bitwise_or(&p[i - 1].shift_left(a));\n set.truncate(dp[0].size);\n p[i] = set;\n }\n }\n }\n let a = calc(r, &p);\n let mut p = vec![];\n p.extend_from_slice(dp);\n for &(a, c) in r.iter() {\n for _ in 0..c {\n for i in (1..dp.len()).rev() {\n let mut set = p[i].bitwise_or(&p[i - 1].shift_left(a));\n set.truncate(dp[0].size);\n p[i] = set;\n }\n }\n }\n std::cmp::max(a, calc(l, &p))\n}\n\nfn run() {\n input! {\n n: usize,\n a: [usize; n],\n }\n let mut a = a.into_iter().map(|a| (a, 1)).collect::>();\n a.sort();\n a.dedup_by(|a, b| {\n a.0 == b.0 && {\n b.1 += a.1;\n true\n }\n });\n if a.len() <= 2 {\n println!(\"{}\", n);\n return;\n }\n let w = n * 100;\n let mut dp = vec![BitSet::new(w + 1); n + 1];\n dp[0].set_at(0);\n let ans = calc(&a, &dp);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "a57d6183b7551e3218a4ba90aa1b5a22", "src_uid": "ccc4b27889598266e8efe73b8aa3666c", "difficulty": 2100.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 euclid(a: u64, b: u64) -> u64 {\n if b == 0 {\n a\n } else {\n euclid(b, a % b)\n }\n}\n\nfn main() {\n let (n, k): (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 // ppcm ?\n\n let m: u64 = 10u64.pow(k as u32);\n let g = euclid(n, m);\n let s = n * m / g;\n\n println!(\"{}\", s);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "41460e9801f56ed43be24c1ca7566819", "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\nfn gcd(a: i64, b: i64) -> i64 {\n if b == 0 {\n a\n } else {\n gcd(b, a % b)\n }\n}\n\nfn lcm(a: i64, b: i64) -> i64 {\n a / gcd(a, b) * b\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: i64 = scan.token();\n let k: i64 = scan.token();\n\n let ans = lcm(n, 10i64.pow(k as u32));\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": ["brute force", "math", "number theory"], "code_uid": "9b6c18bf4ea98c14bb7de306e100e211", "src_uid": "73566d4d9f20f7bbf71bc06bc9a4e9f3", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\r\nuse std::cmp::*;\r\n#[allow(unused_imports)]\r\nuse std::collections::*;\r\n#[allow(unused_imports)]\r\nuse std::io;\r\n#[allow(unused_imports)]\r\nuse std::iter::*;\r\n#[allow(unused_imports)]\r\nuse std::mem::*;\r\n#[allow(unused_imports)]\r\nuse std::str::*;\r\n#[allow(unused_imports)]\r\nuse std::usize;\r\n\r\n// vec with some initial value\r\n#[allow(unused_macros)]\r\nmacro_rules! vvec {\r\n ($($x:expr),+; $y:expr; $n:expr) => {{\r\n let mut v = vec![$y; $n];\r\n\r\n let mut it = v.iter_mut();\r\n $(\r\n *it.next().unwrap() = $x;\r\n )+\r\n\r\n v\r\n }}\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! it {\r\n ($x:expr) => {\r\n once($x)\r\n };\r\n ($first:expr,$($x:expr),+) => {\r\n chain(\r\n once($first),\r\n it!($($x),+)\r\n )\r\n }\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! pushed {\r\n ($c:expr, $x:expr) => {{\r\n let mut c = $c;\r\n c.push($x);\r\n c\r\n }};\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! inserted {\r\n ($c:expr, $($x:expr),*) => {{\r\n let mut c = $c;\r\n c.insert($($x),*);\r\n c\r\n }};\r\n}\r\n\r\n#[allow(unused_macros)]\r\nmacro_rules! read_tuple {\r\n ($($t:ty),+) => {{\r\n let mut line = String::new();\r\n io::stdin().read_line(&mut line).unwrap();\r\n\r\n let mut it = line.trim()\r\n .split_whitespace();\r\n\r\n ($(\r\n it.next().unwrap().parse::<$t>().ok().unwrap()\r\n ),+)\r\n }}\r\n}\r\n\r\n#[allow(dead_code)]\r\nfn read() -> T {\r\n let mut line = String::new();\r\n io::stdin().read_line(&mut line).unwrap();\r\n line.trim().to_string().parse().ok().unwrap()\r\n}\r\n\r\n#[allow(dead_code)]\r\nfn read_str() -> Vec {\r\n read::().chars().collect()\r\n}\r\n\r\n#[allow(dead_code)]\r\nfn read_row() -> Vec {\r\n let mut line = String::new();\r\n io::stdin().read_line(&mut line).unwrap();\r\n\r\n line.trim()\r\n .split_whitespace()\r\n .map(|s| s.parse().ok().unwrap())\r\n .collect()\r\n}\r\n\r\n#[allow(dead_code)]\r\nfn read_col(n: usize) -> Vec {\r\n (0..n).map(|_| read()).collect()\r\n}\r\n\r\n#[allow(dead_code)]\r\nfn read_mat(n: usize) -> Vec> {\r\n (0..n).map(|_| read_row()).collect()\r\n}\r\n\r\n#[allow(dead_code)]\r\nfn read_vec R>(n: usize, mut f: F) -> Vec {\r\n (0..n).map(|_| f()).collect()\r\n}\r\n\r\ntrait IterCopyExt<'a, T>: IntoIterator + Sized\r\nwhere\r\n T: 'a + Copy,\r\n{\r\n fn citer(self) -> std::iter::Copied {\r\n self.into_iter().copied()\r\n }\r\n}\r\n\r\nimpl<'a, T, I> IterCopyExt<'a, T> for I\r\nwhere\r\n I: IntoIterator,\r\n T: 'a + Copy,\r\n{\r\n}\r\n\r\nconst B: i32 = 250;\r\nconst C: i32 = 25;\r\n\r\nfn main() {\r\n let n = read::()\r\n .chars()\r\n .map(|c| c.to_digit(10).unwrap() as i32)\r\n .collect::>();\r\n\r\n let dp = n.citer().fold(\r\n (-C..=C)\r\n .map(|t| {\r\n (0..B)\r\n .map(|i| {\r\n if i < t {\r\n vec![i32::MAX; B as usize]\r\n } else {\r\n vec![t; B as usize]\r\n }\r\n })\r\n .collect::>()\r\n })\r\n .collect::>(),\r\n |prev, d| {\r\n // eprintln!(\"{:?}\", prev);\r\n (-C..=C)\r\n .map(|t| {\r\n let d = d + t;\r\n let mut dp = (0..B)\r\n .map(|i| {\r\n let mut v = vec![i32::MAX; B as usize];\r\n\r\n (-C..=C).for_each(|c| {\r\n if i + 10 * c >= d && i + 10 * c < B + d {\r\n let j = i + 10 * c - d;\r\n v[j as usize] = prev[(c + C) as usize][i as usize][j as usize]\r\n .saturating_add(i + j);\r\n }\r\n });\r\n\r\n v\r\n })\r\n .collect::>();\r\n for i in 0..B {\r\n for j in 0..B {\r\n if i > 0 {\r\n dp[i as usize][j as usize] =\r\n min(dp[i as usize][j as usize], dp[i as usize - 1][j as usize]);\r\n }\r\n if j > 0 {\r\n dp[i as usize][j as usize] =\r\n min(dp[i as usize][j as usize], dp[i as usize][j as usize - 1]);\r\n }\r\n }\r\n }\r\n dp\r\n })\r\n .collect::>()\r\n },\r\n );\r\n let ans = dp[0 + C as usize][B as usize - 1][B as usize - 1];\r\n println!(\"{}\", ans);\r\n}\r\n", "lang_cluster": "Rust", "tags": ["greedy", "dp", "shortest paths"], "code_uid": "0549d4f47bc1283c4b18318c7a774e3f", "src_uid": "1961e7c9120ff652b15cad5dd5ca0907", "difficulty": 2900.0, "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// 下の桁からdpっぽく?\r\n// +がいくつ、-がいくつ、暫定carryがいくつ\r\n// この時1を幾つで合わせられるか的な\r\n// MLE\r\n// なんか状態多いっぽいが\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 = 200;\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": "cdb7ae99908d717987aa9b0e41f3d822", "src_uid": "1961e7c9120ff652b15cad5dd5ca0907", "difficulty": 2900.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 : i32 = s.trim().parse().unwrap();\n for i in n+1.. {\n let a = i / 1000;\n let b = i / 100 % 10;\n let c = i / 10 % 10;\n let d = i % 10;\n if a!=b && a!=c && a!=d && b!=c && b!=d && c!=d {\n println!(\"{}\", i);\n ::std::process::exit(0);\n }\n }\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "5008553640bfa9dd2b6200e5938e99f6", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::collections::HashSet;\n\nfn main() {\n let mut year = String::new();\n\n io::stdin()\n .read_line(&mut year)\n .unwrap();\n\n let mut year: i64 = year.trim().parse().unwrap();\n \n loop {\n year += 1;\n\n let name = year.to_string();\n let size = name.len();\n\n let mut characters = HashSet::new();\n\n for ch in name.chars() {\n characters.insert(ch);\n }\n\n if characters.len() == size {\n println!(\"{}\", name);\n break;\n }\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "5c5bfa5d27ffdab5558ebfef89c146c5", "src_uid": "d62dabfbec52675b7ed7b582ad133acd", "difficulty": 800.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\nfn main() {\n let (mut a, mut b): (u64, u64);\n input!(a, b);\n\n while !(a == 0) && !(b == 0) {\n if a >= 2 * b {\n let buf = a / (2 * b);\n a = a - 2 * b * buf;\n } else if b >= 2 * a {\n let buf = b / (2 * a);\n b = b - 2 * a * buf;\n } else {\n break;\n }\n }\n println!(\"{} {}\", a, b);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "6a87b66be50ff5032b65ea0689cf002d", "src_uid": "1f505e430eb930ea2b495ab531274114", "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\nfn brute_force(a: i64, b: i64) -> (i64, i64) {\n let mut a = a;\n let mut b = b;\n while a > 0 && b > 0 {\n if a >= 2 * b {\n a = a % (2 * b);\n } else if b >= 2 * a {\n b = b % (2 * a);\n }\n else {\n return (a, b);\n }\n }\n (a, b)\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let a: i64 = scan.token();\n let b: i64 = scan.token();\n let (a, b) = brute_force(a, b);\n writeln!(out, \"{} {}\", a, b).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": "bdb9a986392ca9b3e1083a3e185f5254", "src_uid": "1f505e430eb930ea2b495ab531274114", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_variables)]\n#![allow(unused_must_use)]\nuse std::io::{self, prelude::*};\nuse std::cmp::min;\n\n\nfn gcd(a: i64, b: i64) -> i64 {\n if b == 0 {\n return a\n }\n return gcd(b, a%b)\n\n}\nfn solve(mut input: FastInput, mut w: W) {\n let a: i64 = input.token();\n let b: i64 = input.token();\n let mut x: i64 = input.token();\n let mut y: i64 = input.token();\n let g = gcd(x,y);\n x = x / g;\n y = y / g;\n write!(w, \"{}\\n\", min(a/x, b/y));\n\n \n}\n \n\nfn main() {\n let stdin = io::stdin();\n let stdout = io::stdout();\n let input = FastInput::from(stdin.lock());\n let output = io::BufWriter::new(stdout.lock());\n solve(input, output)\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 {\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\n\nimpl_token_stream!(i64);", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "aecef191772e9e4ecd41b2b1b08dcba5", "src_uid": "907ac56260e84dbb6d98a271bcb2d62d", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, Read, StdinLock};\nuse std::str::FromStr;\nuse std::iter::FromIterator;\n\n#[allow(unused_macros)]\nmacro_rules! vecs {\n ($init:expr; $($dim:expr);*) => {\n vecs!($($dim);* => $init)\n };\n ($head:expr; $($tail:expr);* => $init:expr) => {\n vec![vecs!($($tail);* => $init); $head]\n };\n ($head:expr => $init:expr) => {\n vec![$init; $head]\n };\n}\n\nfn main() {\n let cin = stdin();\n let mut scan = Scanner::new(cin.lock());\n let n = scan.read::();\n let k = scan.read::();\n let d = scan.read::();\n let mut env = Env {k: k, d: d, memo: vecs![None;n+1;2]};\n env.memo[0][1] = Some(1.into());\n println!(\"{}\", env.need(n));\n}\n\nstruct Env {\n k: usize,\n d: usize,\n memo: Vec>>\n}\n\nimpl Env {\n fn need(&mut self, n: usize) -> Co {\n if let Some(d) = self.memo[n][0] {\n return d;\n }\n let mut sum = Co(0);\n for i in 1..self.k+1 {\n if n>=i {\n if i>=self.d {sum += self.all(n-i);}\n else {sum += self.need(n-i);}\n }\n }\n self.memo[n][0] = Some(sum);\n sum\n }\n\n fn all(&mut self, n: usize) -> Co {\n if let Some(d) = self.memo[n][1] {\n return d;\n }\n let mut sum = Co(0);\n for i in 1..self.k + 1 {\n if n>=i {sum += self.all(n-i);}\n }\n self.memo[n][1] = Some(sum);\n sum\n }\n}\n\n#[allow(dead_code)]\nconst M: i64 = 1_000_000_007;\n\n// region modulo\n#[allow(dead_code)]\nuse std::ops::*;\n\n#[allow(dead_code)]\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub struct Co (pub i64);\n\n#[allow(dead_code)]\nimpl Co {\n pub fn pow(self, mut n: i64) -> Self {\n let mut a = self;\n let mut res = Co(1);\n while n > 0 {\n if n & 1 == 1 {\n res *= a;\n }\n a = a * a;\n n >>= 1;\n }\n res\n }\n}\n\n#[allow(dead_code)]\nimpl std::fmt::Display for Co {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\n#[allow(dead_code)]\nimpl From for Co {\n fn from(value: i32) -> Self {\n Co((value as i64 % M + M) % M)\n }\n}\n#[allow(dead_code)]\nimpl From for Co {\n fn from(value: i64) -> Self {\n Co((value as i64 % M + M) % M)\n }\n}\n#[allow(dead_code)]\nimpl From for Co {\n fn from(value: usize) -> Self {\n Co((value as i64 % M + M) % M)\n }\n}\n#[allow(dead_code)]\nimpl AddAssign for Co {\n fn add_assign(&mut self, other: Self) {\n *self = self.add(other);\n }\n}\n#[allow(dead_code)]\nimpl Add for Co {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n Co::from((self.0).add(other.0))\n }\n}\n#[allow(dead_code)]\nimpl SubAssign for Co {\n fn sub_assign(&mut self, other: Self) {\n *self = self.sub(other);\n }\n}\n#[allow(dead_code)]\nimpl Sub for Co {\n type Output = Self;\n fn sub(self, other: Self) -> Self {\n Co::from((self.0).sub(other.0))\n }\n}\n#[allow(dead_code)]\nimpl MulAssign for Co {\n fn mul_assign(&mut self, other: Self) {\n *self = self.mul(other);\n }\n}\n#[allow(dead_code)]\nimpl Mul for Co {\n type Output = Self;\n fn mul(self, other: Self) -> Self {\n Co::from((self.0).mul(other.0))\n }\n}\n#[allow(dead_code)]\nimpl DivAssign for Co {\n fn div_assign(&mut self, other: Self) {\n *self = self.div(other);\n }\n}\n#[allow(dead_code)]\nimpl Div for Co {\n type Output = Self;\n fn div(self, rhs: Self) -> Self {\n self * rhs.pow((M - 2) as i64)\n }\n}\n// endregion\n\n// region template\n#[allow(dead_code)]\nfn iu(i: isize) -> usize { i as usize }\n\n#[allow(dead_code)]\nfn ui(i: usize) -> isize { i as isize }\n\n#[allow(dead_code, deprecated)]\nfn join(slice: &[T], sep: &str) -> String {\n let strings = slice.iter().map(|t| format!(\"{}\", t)).collect::>();\n strings.connect(sep)\n}\n\n#[allow(dead_code)]\nfn arr<'a, S, T>(n: usize, mut f: S) -> Vec where S: FnMut(usize) -> T + 'a {\n (0..n).map(|i| f(i)).collect::>()\n}\n\n#[allow(dead_code)]\nfn alt(v: Vec) -> T where T: FromIterator {\n v.into_iter().collect::()\n}\n\n#[allow(dead_code)]\nfn dup(v: &[S]) -> T where T: FromIterator, S: Clone {\n v.iter().cloned().collect::()\n}\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\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 fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n\n fn readn(&mut self, n: usize) -> Vec {\n (0..n).map(|_| self.read::()).collect()\n }\n\n fn chars(&mut self) -> Vec {\n self.read::().chars().collect()\n }\n}\n// endregion", "lang_cluster": "Rust", "tags": ["dp", "implementation", "trees"], "code_uid": "88ea57e6d4a4f4f685e65d0f4625771e", "src_uid": "894a58c9bba5eba11b843c5c5ca0025d", "difficulty": 1600.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::io::{stdin, stdout, BufWriter, Write};\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#[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 let out = stdout();\n let mut out = BufWriter::new(out.lock());\n\n input!{\n a:usize,\n b:usize,\n c:usize,\n d:usize,\n e:usize,\n f:usize,\n }\n\n let mut maxcost = 0;\n for i in 0..d+1 {\n let mut cost = 0;\n if a < i {\n continue;\n }\n cost += e*i;\n\n let rest = d-i;\n let mut j = min(min(b,c),rest);\n\n cost += f*j;\n\n chmax!(maxcost, cost);\n }\n println!(\"{}\", maxcost);\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "brute force"], "code_uid": "ff505c8ce79df5511b0be655b08e16a7", "src_uid": "84d9e7e9c9541d997e6573edb421ae0a", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\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 main() {\n let (n, t, k, d) = {\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 )\n };\n\n let t1 = (n - 1) / k + 1;\n\n let ta = d / t;\n\n if t1 > ta + 1 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "24abc9ec731c3419dd0a25528af5ae71", "src_uid": "32c866d3d394e269724b4930df5e4407", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/799/problem/A\n\nfn single_oven_time(n: u32, t: u32, k: u32) -> u64 {\n let mut cakes = 0;\n let mut time = 0;\n while cakes < n {\n cakes += k;\n time += t as u64;\n }\n time\n}\n\nfn double_oven_time(n: u32, t: u32, k: u32, d: u32) -> u64 {\n let mut has_oven = false;\n let mut cakes = 0;\n let mut time = 0u64;\n while cakes < n {\n time += 1;\n if time % (t as u64) == 0 { cakes += k; }\n if let (n, false) = time.overflowing_sub(d as u64) {\n if n % (t as u64) == 0 && has_oven { cakes += k; }\n }\n if time == d as u64 { has_oven = true; }\n }\n time\n}\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 n = ns.next().unwrap();\n let t = ns.next().unwrap();\n let k = ns.next().unwrap();\n let d = ns.next().unwrap();\n if double_oven_time(n, t, k, d) < single_oven_time(n, t, k) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "fb3fec68e1e6563aec74a2f81d446f05", "src_uid": "32c866d3d394e269724b4930df5e4407", "difficulty": 1100.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}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "23818fb60cc2085a26c3a1153a2359c8", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input() -> (u8, u8, u8) {\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], buf[2])\n}\n\nfn gcd(x: u8, n: u8) -> u8 {\n if n == 0 {\n return x;\n }\n gcd(n, x % n)\n}\n\nfn main() {\n let (a, b, mut n) = input();\n let mut simons_turn = true;\n\n loop {\n let x = if simons_turn { a } else { b };\n let gcd = gcd(x, n);\n\n if gcd <= n {\n simons_turn = !simons_turn;\n n -= gcd;\n } else {\n break;\n }\n }\n\n println!(\"{}\", if simons_turn { 1 } else { 0 });\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f2d3e5677d586f019b9ee0fa414b73a5", "src_uid": "0bd6fbb6b0a2e7e5f080a70553149ac2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/// Codeforces Round #663 (Div. 2)\n/// https://codeforces.com/contest/1391/problem/C\n\nuse std::io::{self, BufWriter, Read, Write};\n\nfn main() {\n let stdout = io::stdout();\n let mut output = BufWriter::new(stdout.lock());\n let mut stdin = io::stdin();\n let mut input_string = String::new();\n stdin.read_to_string(&mut input_string).unwrap();\n let mut input_iter = input_string.split_whitespace();\n\n macro_rules! read(() => (input_iter.next().unwrap().parse().unwrap()));\n macro_rules! println(( $( $x:expr ),* ) => (writeln!(output, $( $x, )*).unwrap()));\n\n let n: usize = read!();\n let modulo = 1_000_000_007;\n let mut solution: u64 = 1;\n let mut power_of_2: u64 = 1;\n\n for i in 2..(n + 1) {\n solution = (solution * i as u64) % modulo;\n power_of_2 = (power_of_2 * 2) % modulo;\n }\n\n if solution < power_of_2 {\n solution += modulo;\n }\n\n solution = (solution - power_of_2) % modulo;\n\n println!(\"{}\", solution);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "830021a0aad97106214732da107ee618", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::Read;\n\nfn read() -> T {\n let token: String = std::io::stdin()\n .bytes()\n .map(|c| c.ok().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\nmod mint {\n use std::ops::{Add, BitAnd, Div, Mul, Rem, Shr, Sub};\n\n #[derive(Copy, Clone)]\n pub struct Mint {\n x: T,\n mo: T,\n }\n impl Mint\n where\n T: Copy,\n {\n pub fn new(x: T, mo: T) -> Mint {\n Mint { x, mo }\n }\n }\n impl Mint\n where\n T: Copy,\n {\n pub fn val(&self) -> T {\n self.x\n }\n pub fn mo(&self) -> T {\n self.mo\n }\n }\n impl Add for Mint\n where\n T: Copy,\n T: Add,\n T: Rem,\n {\n type Output = Mint;\n fn add(self, rhs: T) -> Mint {\n Mint::new((self.val() + rhs % self.mo()) % self.mo(), self.mo())\n }\n }\n impl Add> for Mint\n where\n T: Copy,\n Mint: Add>,\n {\n type Output = Mint;\n fn add(self, rhs: Mint) -> Mint {\n self + rhs.val()\n }\n }\n impl Sub for Mint\n where\n T: Copy,\n T: Add,\n T: Sub,\n T: Rem,\n {\n type Output = Mint;\n fn sub(self, rhs: T) -> Mint {\n Mint::new(\n (self.val() + self.mo() - rhs % self.mo()) % self.mo(),\n self.mo(),\n )\n }\n }\n impl Sub> for Mint\n where\n T: Copy,\n Mint: Sub>,\n {\n type Output = Mint;\n fn sub(self, rhs: Mint) -> Mint {\n self - rhs.val()\n }\n }\n impl Mul for Mint\n where\n T: Copy,\n T: Mul,\n T: Rem,\n {\n type Output = Mint;\n fn mul(self, rhs: T) -> Mint {\n Mint::new((self.val() * rhs % self.mo()) % self.mo(), self.mo())\n }\n }\n impl Mul> for Mint\n where\n T: Copy,\n Mint: Mul>,\n {\n type Output = Mint;\n fn mul(self, rhs: Mint) -> Mint {\n self * rhs.val()\n }\n }\n\n impl Mint\n where\n T: Copy,\n T: Sub,\n T: Div,\n T: PartialOrd,\n T: PartialEq,\n T: BitAnd,\n T: Shr,\n Mint: Mul>,\n {\n pub fn pow(self, y: T) -> Mint {\n let one = self.mo() / self.mo();\n let zero = self.mo() - self.mo();\n let mut res = Mint::one(self.mo());\n let mut base = self;\n let mut exp = y;\n while exp > zero {\n if (exp & one) == one {\n res = res * base;\n }\n base = base * base;\n exp = exp >> one;\n }\n res\n }\n }\n impl Div for Mint\n where\n T: Copy,\n T: Sub,\n T: Div,\n T: PartialOrd,\n T: PartialEq,\n T: BitAnd,\n T: Shr,\n Mint: Mul>,\n {\n type Output = Mint;\n fn div(self, rhs: T) -> Mint {\n let one = self.mo() / self.mo();\n self * Mint::new(rhs, self.mo()).pow(self.mo() - one - one)\n }\n }\n impl Div> for Mint\n where\n T: Copy,\n Mint: Div>,\n {\n type Output = Mint;\n fn div(self, rhs: Mint) -> Mint {\n self / rhs.val()\n }\n }\n impl Mint\n where\n T: Copy,\n T: Div,\n Mint: Div>,\n {\n pub fn inv(self) -> Mint {\n Mint::one(self.mo()) / self\n }\n }\n impl std::fmt::Display for Mint\n where\n T: Copy + std::fmt::Display,\n {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n write!(f, \"{}\", self.val())\n }\n }\n impl Mint\n where\n T: Copy,\n T: Sub,\n {\n pub fn zero(mo: T) -> Mint {\n Mint { x: mo - mo, mo }\n }\n }\n impl Mint\n where\n T: Copy,\n T: Div,\n {\n pub fn one(mo: T) -> Mint {\n Mint { x: mo / mo, mo }\n }\n }\n}\n\nuse mint::Mint;\n\nfn factorials(n: usize, mo: u64) -> (Vec>, Vec>) {\n let mut fac = vec![Mint::new(0, mo); n];\n let mut fac_inv = vec![Mint::new(0, mo); n];\n fac[0] = Mint::new(1, mo);\n for i in 1..n {\n fac[i] = fac[i - 1] * (i as u64);\n }\n fac_inv[n - 1] = fac[n - 1].inv();\n for i in (0..n - 1).rev() {\n fac_inv[i] = fac_inv[i + 1] * ((i + 1) as u64);\n }\n (fac, fac_inv)\n}\n\nfn main() {\n let n: usize = read();\n let mo = 1000000007;\n let (fac, _) = factorials(n + 1, mo);\n let mut ans = fac[n];\n ans = ans - Mint::new(2, mo).pow(n as u64 - 1);\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graphs"], "code_uid": "487dbf63c7547a92da0b3781411e5011", "src_uid": "3dc1ee09016a25421ae371fa8005fce1", "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 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..200 {\n for dadd in 0..100 {\n let ay = ay + aadd;\n let dy = dy + dadd;\n let mut l: i64 = -1;\n let mut r: i64 = 10001;\n if !resolve(hy + r, ay, dy, hm, am, dm) {\n continue;\n }\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 if cost < ans {\n ans = cost;\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", "implementation", "binary search"], "code_uid": "325314933cf66d18d879550d51d1b88d", "src_uid": "bf8a133154745e64a547de6f31ddc884", "difficulty": 1800.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 k: i64 = sc.ne();\n let a: i64 = sc.ne();\n let b: i64 = sc.ne();\n let aw = a / k;\n let bw = b / k;\n let mut ok = true;\n if aw == 0 && bw == 0 {\n ok = false;\n } else if aw == 0 {\n ok = b % k == 0;\n } else if bw == 0 {\n ok = a % k == 0;\n }\n if ok {\n println!(\"{}\", aw + bw);\n } else {\n println!(\"-1\");\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": ["math"], "code_uid": "a9f72ebe93ec88575ce05e03ba4fac88", "src_uid": "6e3b8193d1ca1a1d449dc7a4ad45b8f2", "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\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 より\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: u64,\n }\n if m > n as u64 - 1 {\n println!(\"0\");\n return;\n }\n let m = m as usize;\n let pc = Precalc::new(n + m);\n if m == 0 {\n println!(\"{}\", pc.fact(n));\n return;\n }\n let mut ans = ModInt::zero();\n let mut sign = ModInt::one();\n for i in (1..=(n - m)).rev() {\n ans += sign * pc.comb(n - m, i) * ModInt::from(i).pow(n as u32);\n sign = -sign;\n }\n ans *= pc.comb(n, n - m) * ModInt(2);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "fft"], "code_uid": "6c7fe22ee12dc4ca5fcee7bc57d01caa", "src_uid": "6c1a9aaa7bdd7de97220b8c6d35740cc", "difficulty": 2300.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 より\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}\nfn run() {\n input! {\n n: usize,\n m: u64,\n }\n if m > n as u64 - 1 {\n println!(\"0\");\n return;\n }\n let m = m as usize;\n let pc = Precalc::new(n + m);\n if m == 0 {\n println!(\"{}\", pc.fact(n));\n return;\n }\n let mut ans = ModInt::zero();\n let mut sign = ModInt::one();\n for i in (1..=(n - m)).rev() {\n ans += sign * pc.comb(n - m, i) * ModInt::from(i).pow(n as u32);\n sign = -sign;\n }\n ans *= pc.comb(n, n - m) * ModInt(2);\n println!(\"{}\", ans);\n}\nfn main() {\n run();\n}", "lang_cluster": "Rust", "tags": ["math", "combinatorics", "fft"], "code_uid": "a1a1d10fcdf455045d63fb29d4d81cc6", "src_uid": "6c1a9aaa7bdd7de97220b8c6d35740cc", "difficulty": 2300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/732/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 k = words[0];\n let r = words[1];\n\n for i in 1..=9 {\n if i*k%10 == r || i*k%10 == 0 {\n println!(\"{}\", i);\n break;\n }\n }\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "constructive algorithms", "implementation"], "code_uid": "24bb0499b4985e19040b2895796e8e35", "src_uid": "18cd1cd809df4744bb7bcd7cad94e2d3", "difficulty": 800.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 l: u64,\n }\n let mut dp = vec![1u64; n + 1];\n for i in 2..=n {\n dp[i] = dp[i - 1] + dp[i - 2];\n }\n let mut ans = vec![];\n let mut l = l - 1;\n let mut s = 1;\n while s <= n {\n if dp[n - s] > l {\n ans.push(s);\n s += 1;\n } else {\n l -= dp[n - s];\n ans.push(s + 1);\n ans.push(s);\n s += 2;\n }\n }\n let mut s = String::new();\n for a in ans {\n s.push_str(&format!(\"{} \", a));\n }\n s.pop();\n println!(\"{}\", s);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "math", "combinatorics", "binary search", "greedy", "implementation"], "code_uid": "2bc2bb06b22704823f1b43ccbb7e494b", "src_uid": "e03c6d3bb8cf9119530668765691a346", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main() {\n let mut n = String::new();\n io::stdin().read_line(&mut n).expect(\"failed to read\");\n let n :u64 = n.trim().parse().expect(\"failed to parse\");\n let counter:u64 = n/2520;\n println!(\"{}\", counter);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "ba877165177e90443766fba961732784", "src_uid": "8551308e5ff435e0fc507b89a912408a", "difficulty": 1100.0, "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 let info: Vec = (0..2).map(|_| scanner.next()).collect();\n let arr: Vec = scanner.next::().chars().collect();\n let mut dp = vec![false; arr.len()];\n dp[0] = true;\n dp[arr.len() - 1] = true;\n\n let mut count = 1;\n let mut current_pos = info[1];\n\n while !dp[std::cmp::min(current_pos, arr.len() - 1)] {\n dp[current_pos] = true;\n match arr[current_pos] {\n '1' => {\n current_pos += info[1];\n count += 1;\n }\n '0' => current_pos -= 1,\n _ => (),\n }\n }\n if current_pos >= arr.len() - 1 {\n println!(\"{}\", count);\n } else {\n println!(\"-1\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "greedy", "dp", "implementation"], "code_uid": "938657a3fbb11c86d84190d122a3f24c", "src_uid": "c08d2ecdfc66cd07fbbd461b1f069c9e", "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 n: i64 = sc.ne();\n let m: usize = 100;\n let inf = 1e18 as i64 * 2;\n let mut dp = vec![inf; m];\n dp[0] = 1;\n dp[1] = 2;\n for i in 2..m {\n dp[i] = dp[i - 1] + dp[i - 2];\n if dp[i] > inf {\n break;\n }\n }\n let pos = dp.iter().position(|&x| x > n).unwrap();\n // for i in 0..m {\n // println!(\"{} {}\", i, dp[i]);\n // }\n println!(\"{}\", pos - 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", "greedy", "constructive algorithms", "combinatorics"], "code_uid": "12ca7ed7c05e8c1ea934b2457094ebfa", "src_uid": "3d3432b4f7c6a3b901161fa24b415b14", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(dead_code, unused_macros, unused_imports)]\nuse std::collections::*;\nuse std::io;\nuse std::io::Write;\nmacro_rules! fprintln {\n ($dst:expr) => (\n $dst.write(\"\\n\".as_bytes()).unwrap();\n );\n ($dst:expr, $($arg:tt)*) => ( {\n $dst.write_fmt(format_args!($($arg)*)).unwrap();\n $dst.write(\"\\n\".as_bytes()).unwrap();\n }\n );\n}\n\nmacro_rules! fprintvec {\n ($dst:expr, $arg:expr) => {{\n fprintln!(\n $dst,\n \"{}\",\n $arg.iter()\n .map(|x| format!(\"{}\", x))\n .collect::>()\n .join(\" \")\n );\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 input_line\n .trim_end_matches(\"\\n\")\n .trim_end_matches(\"\\r\")\n .parse::<$t>()\n .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 depth(t: i64, k: i64, start: i64) -> i64 {\n let v;\n let t = t % (2 * k);\n if t <= k {\n v = t;\n } else {\n v = k - (t - k);\n }\n v + start\n}\n\nfn slow(depths: &Vec, k: i64, l: i64) -> bool {\n let mut valid = (0..=2 * k).collect::>();\n for p in depths.iter() {\n let mut next = HashSet::new();\n for z in valid.iter() {\n for x in 1..=(2 * k) {\n if depth(z + x, k, *p) <= l {\n next.insert((z + x) % (2 * k));\n } else {\n break;\n }\n }\n }\n valid = next;\n }\n valid.len() > 0\n}\n\nfn main() {\n let stdout = io::stdout();\n let lock = stdout.lock();\n let mut w = io::BufWriter::new(lock);\n let num_tests = parse_input!(usize);\n // let num_tests = 1;\n for _ in 0..num_tests {\n let limits = split_input!(i64);\n let n = limits[0];\n let k = limits[1];\n let l = limits[2];\n let vals = split_input!(i64);\n let mut start = -k;\n let mut valid = true;\n // for (p, &d) in vals.iter().enumerate() {\n // if d > l {\n // valid = false;\n // break;\n // }\n // if d + k <= l {\n // start = -k;\n // } else {\n // let nt = start + 1;\n // let bad = (l - d) + 1;\n // let good = -bad;\n // if nt >= bad {\n // valid = false;\n // break;\n // }\n // start = std::cmp::max(nt, good);\n // }\n // dbg!(start);\n // }\n valid = slow(&vals, k, l);\n if valid {\n fprintln!(w, \"YES\");\n } else {\n fprintln!(w, \"NO\");\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "dp"], "code_uid": "ea61bbd25ec357eba2d56fbf47c43207", "src_uid": "4941b0a365f86b2e2cf686cdf5d532f8", "difficulty": 1900.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(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 found(d: Vec, k: u16, limit: u16) -> bool {\n if d.is_empty() {\n return true;\n }\n let p = (0..k).chain((1..k + 1).rev()).collect::>();\n for start in 0..p.len() {\n if d.iter()\n .enumerate()\n .map(|(i, di)| di + p[(i + start) % p.len()])\n .all(|di| di <= limit)\n {\n return true;\n }\n }\n false\n}\n\nfn main() -> Result<(), Box> {\n for _ in 0..read_usize() {\n let (_n, k, l) = read_3::();\n let d = read_multiple();\n let mut dead = false;\n let mut gap = Vec::new();\n for di in d {\n if k + di <= l {\n if !found(gap, k, l) {\n dead = true\n }\n gap = Vec::new();\n } else {\n gap.push(di)\n }\n }\n if !found(gap, k, l) {\n dead = true\n }\n if dead {\n println!(\"No\")\n } else {\n println!(\"Yes\")\n }\n }\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "greedy", "dp"], "code_uid": "5fd0c75de5c827a32500a779d7792110", "src_uid": "4941b0a365f86b2e2cf686cdf5d532f8", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn is_palindrome(x: &str) -> bool {\n if x.len() <= 1 {\n return true;\n }\n let b = x.as_bytes();\n let mut index = 0;\n while index < (x.len() / 2) {\n if b[index] != b[x.len() - index - 1] {\n return false;\n }\n index = index + 1;\n }\n true\n}\n\nfn is_quasi_palindrome(x: &str) -> bool {\n let mut k = String::from(x);\n let mut count = 0;\n while count < 10 {\n if is_palindrome(k.as_str()) {\n return true;\n }\n k = String::from(\"0\") + &k;\n count = count + 1;\n }\n false\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"io error\");\n\n match is_quasi_palindrome(input.trim_right()) {\n true => println!(\"YES\"),\n false => println!(\"NO\"),\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "1f4e6b2827243c2305f9d579398ab50c", "src_uid": "d82278932881e3aa997086c909f29051", "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::*;\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.i();\n let a = input.i();\n let b = input.i();\n println!(\"{}\", ((a - 1 + b) % n + n) % n + 1);\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d1614154a77e75644cb61d1b114ea95c", "src_uid": "cd0e90042a6aca647465f1d51e6dffc4", "difficulty": 1000.0, "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 mut ans = 0;\r\n for i in 1..=n {\r\n ans += modpow(m, i as i64);\r\n ans %= MOD;\r\n }\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 let mut dp = vec![0; n];\r\n let mut f = 1;\r\n for i in 0..n {\r\n if p[i + 1] {\r\n f *= (i + 1) as i64;\r\n f = f.min(m + 1);\r\n }\r\n dp[i] = m / f % MOD;\r\n if i > 0 {\r\n dp[i] *= dp[i - 1];\r\n dp[i] %= MOD;\r\n }\r\n ans += MOD - dp[i];\r\n ans %= MOD;\r\n }\r\n println!(\"{}\", ans);\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": "18e4c658dd7ba0d730b0eb7dc3602be3", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "use std::collections::VecDeque;\nuse std::fmt::{Display, Formatter};\nuse std::io::{Read, stdin};\nuse std::marker::PhantomData;\nuse std::ops::{Add, Mul, Range, RangeBounds, Sub};\n\nfn main() {\n let mut scan = Scanner::default();\n\n let n = scan.next_usize();\n let m = scan.next_usize();\n\n let mut sum = M::<998244353>(0);\n let mut prod = M::<998244353>(1);\n\n let mut pos_factor = 1;\n for i in 1..=n {\n if is_prime(i) {\n pos_factor *= i;\n }\n let pos_count = m / pos_factor;\n if pos_count == 0 { break; }\n prod = prod * M(pos_count);\n sum = sum + prod;\n }\n\n let mut total = M(0);\n for i in 1..=n {\n total = total + M(m).pow(M(i));\n }\n let amb = total - sum;\n\n println!(\"{}\", amb);\n}\n\n\nstruct PrimeIterator {\n primes: Vec\n}\n\nfn primes() -> PrimeIterator {\n PrimeIterator{ primes: Vec::new() }\n}\n\nimpl Iterator for PrimeIterator {\n type Item = usize;\n\n fn next(&mut self) -> Option {\n for i in self.primes.last().map(|x| *x + 1).unwrap_or(2).. {\n if self.primes.iter().all(|prime| i % prime != 0) {\n self.primes.push(i);\n return Some(i)\n }\n }\n unreachable!()\n }\n}\n\nfn firstfac(x: usize) -> usize {\n if x % 2 == 0 {\n return 2;\n };\n for n in (1..).map(|m| 2 * m + 1).take_while(|m| m * m <= x) {\n if x % n == 0 {\n return n;\n };\n }\n x\n}\n\npub fn is_prime(n: usize) -> bool {\n if n <= 1 { return false }\n firstfac(n) == n\n}\n\n#[derive(Clone, Copy)]\nstruct M(usize);\n\nimpl Add for M

{\n type Output = M

;\n\n #[inline(always)]\n fn add(self, rhs: Self) -> Self::Output {\n let mut v = self.0 + rhs.0;\n if v >= P {\n v -= P\n }\n M(v)\n }\n}\n\nimpl Sub for M

{\n type Output = M

;\n\n #[inline(always)]\n fn sub(self, rhs: Self) -> Self::Output {\n let mut v = self.0.wrapping_sub(rhs.0);\n if v >= P {\n v = v.wrapping_add(P)\n }\n M(v)\n }\n}\n\nimpl Mul for M

{\n type Output = M

;\n\n #[inline(always)]\n fn mul(self, rhs: Self) -> Self::Output {\n M(((self.0 as u128 * rhs.0 as u128) % P as u128) as usize)\n }\n}\n\n\nimpl Display for M

{\n #[inline(always)]\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n Display::fmt(&self.0, f)\n }\n}\n\nimpl M

{\n #[inline(always)]\n pub fn pow(mut self, n: Self) -> Self {\n let mut n = n.0;\n let mut res: Self = Self(1);\n while n > 0 {\n if n % 2 == 1 { res = res * self }\n self = self * self;\n n /= 2;\n }\n\n res\n }\n\n #[inline(always)]\n pub fn inv(self) -> Self {\n self.pow(M(P - 2))\n }\n}\n\n\n#[derive(Default)]\nstruct Scanner {\n buffer: Vec,\n}\nimpl Scanner {\n fn next_usize(&mut self) -> usize {\n self.next()\n }\n\n fn next_string(&mut self) -> String {\n self.next()\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 stdin().read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n\n fn iter(&mut self) -> ScannerIter {\n ScannerIter {\n phantom: Default::default(),\n scanner: self,\n }\n }\n}\n\nstruct ScannerIter<'a, T: std::str::FromStr> {\n phantom: PhantomData,\n scanner: &'a mut Scanner,\n}\n\nimpl<'a, T: std::str::FromStr> Iterator for ScannerIter<'a, T> {\n type Item = T;\n\n fn next(&mut self) -> Option {\n Some(self.scanner.next())\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "number theory"], "code_uid": "45adbc9855c8281164b2926ba5b331ea", "src_uid": "0fdd91ed33431848614075ebe9d2ee68", "difficulty": 1900.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: u64,\n }\n if n <= 2 {\n println!(\"1\");\n return;\n }\n let mut m = 4;\n let mut d = 1;\n while m + 1 < n {\n m = 2 * (m + 1) - d;\n d ^= 1;\n }\n if m == n || m + 1 == n {\n println!(\"1\");\n } else {\n println!(\"0\");\n }\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp"], "code_uid": "2f78d2683d5f4267ff4a020fca1ace44", "src_uid": "821409c1b9bdcd18c4dcf35dc5116501", "difficulty": 2400.0, "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: u16 = read_int();\n for &divisor in &[4, 7, 47, 74, 444, 447, 474, 477, 744, 747, 777] {\n if divisor > n { break; }\n if n % divisor == 0 {\n println!(\"YES\");\n std::process::exit(0);\n }\n }\n println!(\"NO\");\n}", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "5197229abc41c5c017ea8476ec7b1232", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "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\n if permute()\n .into_iter()\n .any(|n| s.trim().parse::().unwrap() % n == 0)\n {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n\nfn permute() -> Vec {\n let arr: [usize; 2] = [4, 7];\n let mut vec = vec![4, 7];\n\n let mut from = 0;\n let mut to = vec.len();\n 'outer: loop {\n for n in arr.iter() {\n for i in from..to {\n let cur = cat(*n, vec[i]);\n if cur < 1000 {\n vec.push(cat(*n, vec[i]));\n } else {\n break 'outer;\n }\n }\n }\n from = to;\n to = vec.len();\n }\n vec\n}\n\nfn cat(left: usize, right: usize) -> usize {\n let right_f = right as f64;\n let mult_left_by: usize = 10_usize.pow(right_f.log10() as u32 + 1_u32);\n (left * mult_left_by) + right\n}", "lang_cluster": "Rust", "tags": ["brute force", "number theory"], "code_uid": "2e9b38ef47b5d1164e5c1f0ff3eedf8b", "src_uid": "78cf8bc7660dbd0602bf6e499bc6bb0d", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() {\n let mut arr: [i16; 101] = [0; 101];\n let mut inp = String::with_capacity(500);\n for _ in 1..3 {\n stdin().read_line(&mut inp).unwrap();\n }\n let mut inp = inp.split_whitespace();\n let _ = inp.next().unwrap();\n let mut i: usize;\n for num in inp {\n i = num.parse().unwrap();\n arr[i] += 1;\n }\n let mut max = arr[0];\n i = 1;\n while i < arr.len() {\n if arr[i] > max {\n max = arr[i];\n }\n i += 1;\n }\n println!(\"{}\",max);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7478f422ba96aba6add51e8f42461dbc", "src_uid": "f30329023e84b4c50b1b118dc98ae73c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports, unused_macros, dead_code)]\n\nmacro_rules! min {\n (.. $x:expr) => {{\n let mut it = $x.iter();\n it.next().map(|z| it.fold(z, |x, y| min!(x, y)))\n }};\n ($x:expr) => ($x);\n ($x:expr, $($ys:expr),*) => {{\n let t = min!($($ys),*);\n if $x < t { $x } else { t }\n }}\n}\nmacro_rules! max {\n (.. $x:expr) => {{\n let mut it = $x.iter();\n it.next().map(|z| it.fold(z, |x, y| max!(x, y)))\n }};\n ($x:expr) => ($x);\n ($x:expr, $($ys:expr),*) => {{\n let t = max!($($ys),*);\n if $x > t { $x } else { t }\n }}\n}\n\n\nmacro_rules! ewriteln {\n ($($args:expr),*) => { let _ = writeln!(&mut std::io::stderr(), $($args),*); };\n}\nmacro_rules! trace {\n ($x:expr) => { ewriteln!(\">>> {} = {:?}\", stringify!($x), $x) };\n ($($xs:expr),*) => { trace!(($($xs),*)) }\n}\nmacro_rules! put {\n (.. $x:expr) => {{\n let mut it = $x.iter();\n if let Some(x) = it.next() { print!(\"{}\", x); }\n for x in it { print!(\" {}\", x); }\n println!(\"\");\n }};\n ($x:expr) => { println!(\"{}\", $x) };\n ($x:expr, $($xs:expr),*) => { print!(\"{} \", $x); put!($($xs),*) }\n}\n\nconst M: i64 = 1_000_000_007;\n\nfn primes(x: i64) -> Vec {\n let mut x = x;\n let mut ret = vec![];\n for p in 2..x+1 {\n if x % p == 0 {\n ret.push(p);\n while x % p == 0 { x /= p; }\n if x == 1 { break }\n }\n if p * p > x && x > 1 {\n ret.push(x);\n break;\n }\n }\n return ret;\n}\n\nfn pow(p: i64, count: i64) -> i64 {\n if count == 0 {\n 1\n } else {\n let a = pow((p * p) % M, count / 2) % M;\n if count % 2 == 0 {\n a\n } else {\n (a * p) % M\n }\n }\n}\n\nfn main() {\n let mut sc = Scanner::new();\n let x: i64 = sc.cin();\n let n: i64 = sc.cin();\n let ps = primes(x);\n let mut ans = 1;\n // trace!(&ps);\n for &p in ps.iter() {\n let mut count = 0;\n let mut z = n;\n while z >= p {\n count += z / p;\n z /= p;\n }\n // trace!(p, count, pow(p%M,count));\n ans *= pow(p % M, count);\n ans %= M;\n }\n put!(ans);\n}\n\nuse std::io::{self, Write};\nuse std::str::FromStr;\nuse std::collections::VecDeque;\n\nstruct Scanner { stdin: io::Stdin, buffer: VecDeque, }\nimpl Scanner {\n fn new() -> Self { Scanner { stdin: io::stdin(), buffer: VecDeque::new() } }\n fn cin(&mut self) -> T {\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 self.buffer.pop_front().unwrap().parse::().ok().unwrap()\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "f8c375b588503c59a872698f5b5fbfc0", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\n\nconst MODULO: u128 = 1000000007;\n\nfn delta_greater(a: usize, b: usize, c: usize) -> bool {\n if a > b {\n return (a - b) > c;\n } else {\n return (b - a) > c;\n }\n}\n\nfn sqrt_int(x: usize) -> usize {\n if x == 0 {\n return 0;\n }\n let mut value: usize = x + 2;\n let mut value1: usize = x;\n while delta_greater(value, value1, 1) {\n value = value1;\n value1 = (value + (x / value)) / 2;\n }\n value1 = (value1 + (x / value1)) / 2;\n return value1;\n}\n\nfn get_power_value(base: u128, power: u128) -> u128 {\n let mut value: u128 = 1;\n let mut z: u128 = base;\n let mut power_of_2: u128 = 1;\n let mut power_tmp: u128 = power;\n for _ in 0..127 {\n if (power_tmp & 1) != 0 {\n value *= z;\n value %= MODULO;\n }\n\n z *= z;\n z %= MODULO;\n\n power_of_2 <<= 1;\n power_tmp >>= 1;\n if power_of_2 > power {\n break;\n }\n }\n return value;\n}\n\nfn get_prime_divider_power(value: u128, divider: u128) -> u128 {\n let mut power: u128 = 0;\n let mut divider_tmp: u128 = divider;\n while divider_tmp <= value {\n power += value / divider_tmp;\n divider_tmp *= divider;\n }\n return power;\n}\n\nfn func_g1_mod(n: u128, p: u128) -> u128 {\n let power: u128 = get_prime_divider_power(n, p);\n return get_power_value(p, power);\n}\n\nfn func_f1_mod(x: usize, n: u128) -> u128 {\n let mut value: u128 = 1;\n\n let mut x_tmp: usize = x;\n for i in 2..(sqrt_int(x) + 1) {\n if (x_tmp % i) == 0 {\n value *= func_g1_mod(n, i as u128);\n value %= MODULO;\n }\n while (x_tmp % i) == 0 {\n x_tmp /= i;\n }\n }\n if x_tmp > 1 {\n value *= func_g1_mod(n, x_tmp as u128);\n value %= MODULO;\n }\n\n return value;\n}\n\n#[cfg(test)]\nmod tests {\n use super::{func_f1_mod, get_power_value, sqrt_int};\n\n #[test]\n fn test_a1() {\n assert_eq!(sqrt_int(0), 0);\n assert_eq!(sqrt_int(1), 1);\n assert_eq!(sqrt_int(2), 1);\n assert_eq!(sqrt_int(3), 1);\n assert_eq!(sqrt_int(4), 2);\n assert_eq!(sqrt_int(5), 2);\n assert_eq!(sqrt_int(6), 2);\n assert_eq!(sqrt_int(7), 2);\n assert_eq!(sqrt_int(8), 2);\n assert_eq!(sqrt_int(9), 3);\n assert_eq!(sqrt_int(10), 3);\n }\n\n #[test]\n fn test_b1() {\n assert_eq!(get_power_value(0, 1), 0);\n assert_eq!(get_power_value(0, 2), 0);\n assert_eq!(get_power_value(0, 3), 0);\n assert_eq!(get_power_value(1, 0), 1);\n assert_eq!(get_power_value(1, 1), 1);\n assert_eq!(get_power_value(1, 2), 1);\n assert_eq!(get_power_value(1, 3), 1);\n assert_eq!(get_power_value(2, 0), 1);\n assert_eq!(get_power_value(2, 1), 2);\n assert_eq!(get_power_value(2, 2), 4);\n assert_eq!(get_power_value(2, 3), 8);\n assert_eq!(get_power_value(3, 0), 1);\n assert_eq!(get_power_value(3, 1), 3);\n assert_eq!(get_power_value(3, 2), 9);\n assert_eq!(get_power_value(3, 3), 27);\n }\n\n #[test]\n fn test_c1() {\n assert_eq!(func_f1_mod(10, 2), 2);\n }\n #[test]\n fn test_c2() {\n assert_eq!(func_f1_mod(20190929, 1605), 363165664);\n }\n #[test]\n fn test_c3() {\n assert_eq!(func_f1_mod(947, 987654321987654321), 593574252);\n }\n}\n\nfn read_usize_u128_pair(stdin_lock: &mut std::io::StdinLock) -> (usize, u128) {\n let mut line1: String = String::new();\n stdin_lock.read_line(&mut line1).unwrap();\n let mut line1_values = line1.trim().split(\" \");\n let value1: usize = line1_values.next().unwrap().parse::().unwrap();\n let value2: u128 = line1_values.next().unwrap().parse::().unwrap();\n return (value1, value2);\n}\n\nfn main() {\n let stdin: std::io::Stdin = std::io::stdin();\n let mut stdin_lock: std::io::StdinLock = stdin.lock();\n\n let (x, n): (usize, u128) = read_usize_u128_pair(&mut stdin_lock);\n\n let func_value: u128 = func_f1_mod(x, n);\n\n println!(\"{}\", func_value);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "b051c73d24fd25cd5a7c1bf51207abf1", "src_uid": "04610fbaa746c083dda30e21fa6e1a0c", "difficulty": 1700.0, "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 \n let n: usize = input.next();\n let mut a: Vec = input.iter().take(n).collect();\n a.sort();\n let mut cur = Vec::new();\n let mut ans = 0usize;\n for x in a {\n if !cur.iter().any(|&y| x % y == 0) {\n cur.push(x);\n ans += 1;\n }\n }\n puts!(\"{}\\n\", ans);\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", "implementation"], "code_uid": "77808bc050b5f32c8ca5e2a8d0e35781", "src_uid": "63d9b7416aa96129c57d20ec6145e0cd", "difficulty": 800.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::*;\n\nfn main() {\n let n: usize;\n input!(n);\n let mut v = input_vector::();\n v.sort();\n let mut flag = vec![false; n];\n let mut ans = 0;\n for i in 0..n {\n if flag[i] {\n continue;\n }\n ans += 1;\n flag[i] = true;\n for j in i + 1..n {\n if v[j] % v[i] == 0 {\n flag[j] = true;\n }\n }\n }\n p(ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "greedy", "implementation"], "code_uid": "be856c3e92989a787b85d0e0dc45b34b", "src_uid": "63d9b7416aa96129c57d20ec6145e0cd", "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 t = read::();\n for _ in 0..t {\n let v = read_vec::();\n let a = read_vec::()\n .iter()\n .map(|&x| x - 1)\n .collect::>();\n let (n, k, d) = (v[0], v[1], v[2]);\n let mut count = vec![0; k];\n let mut current_using = HashSet::new();\n for i in 0..d {\n count[a[i]] += 1;\n current_using.insert(a[i]);\n }\n let mut ans = current_using.len();\n\n for i in d..n {\n count[a[i - d]] -= 1;\n if count[a[i - d]] == 0 {\n current_using.remove(&a[i - d]);\n }\n count[a[i]] += 1;\n current_using.insert(a[i]);\n ans = min(ans, current_using.len());\n }\n println!(\"{}\", ans);\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": ["implementation"], "code_uid": "2bab2d7122ac88bac045b06a87761f36", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::Ordering;\nuse std::collections::*;\nuse std::io::prelude::*;\nfn main() {\n let mut buf = String::new();\n let stdin = std::io::stdin();\n let mut handle = stdin.lock();\n handle.read_to_string(&mut buf).unwrap();\n let mut entries = buf.split_whitespace();\n let num_cases: usize = entries.next().unwrap().parse().unwrap();\n for _ in 0..num_cases {\n let n: usize = entries.next().unwrap().parse().unwrap();\n let k: usize = entries.next().unwrap().parse().unwrap();\n\n let d: usize = entries.next().unwrap().parse().unwrap();\n let mut a = Vec::with_capacity(n);\n for _ in 0..n {\n let ai: usize = entries.next().unwrap().parse().unwrap();\n a.push(ai);\n }\n let res = solve(&mut a, d, k);\n println!(\"{}\", res);\n }\n}\n\nfn solve(a: &mut [usize], d: usize, k: usize) -> usize {\n let k = k + 1;\n let mut cache = vec![0; k];\n for i in 0..d {\n cache[a[i]] += 1;\n }\n let mut res = find_min(a, &mut cache, d);\n for i in d..a.len() {\n cache[a[i]] += 1;\n cache[a[i - d]] -= 1;\n let new_res = find_min(a, &mut cache, d);\n if new_res < res {\n res = new_res\n }\n }\n res\n // for i in d..a.len() {\n // let a_to_inc = a[i];\n // let a_to_inc_in_index = indexes.binary_search(a_to_inc).unwrap();\n // if (a_to_inc_in_index > 0) {\n // let mut next_entry = a_to_inc_in_index - 1;\n // while (cache[next_entry] == cache[a_to_inc_in_index]) && (next_entry > 0) {\n // next_entry -= 1;\n // }\n // cache[a_to_inc_in_index] += 1;\n // indexes.swap(a_to_inc_in_index, next_entry);\n // }\n\n // let a_to_dec = a[i - d];\n // let a_to_dec_in_index = indexes.binary_search(a_to_dec).unwrap();\n // if (a_to_dec_in_index < a.len() - 1) {\n // let mut next_entry = a_to_dec_in_index + 1;\n // while (cache[next_entry] == cache[a_to_dec_in_index]) && (next_entry < a.len() - 1) {\n // next_entry += 1;\n // }\n // cache[a_to_dec_in_index] += 1;\n // indexes.swap(a_to_dec_in_index, next_entry);\n // }\n // }\n}\n\nfn find_min(a: &mut [usize], cache: &mut [usize], d: usize) -> usize {\n let mut indexes: Vec = (0..cache.len()).into_iter().collect();\n indexes.sort_by(|i, j| match cache[*i] as isize - cache[*j] as isize {\n x if x < 0 => Ordering::Greater,\n x if x == 0 => Ordering::Equal,\n _ => Ordering::Less,\n });\n let mut score = 0;\n let mut i = 0;\n while score < d {\n score += cache[indexes[i]];\n i += 1;\n }\n i\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n // #[test]\n // fn test1() {\n // assert_eq!(solve(&mut [1, 2, 1, 2, 1], 2, 2), 2);\n // }\n\n #[test]\n fn test2() {\n assert_eq!(solve(&mut [10, 8, 6, 4], 4, 10), 4);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1314952f1f83216805ad76cc16369751", "src_uid": "56da4ec7cd849c4330d188d8c9bd6094", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main() {\n let mut buf = String::new();\n // pass nubmer of chars\n io::stdin().read_line(&mut buf).unwrap();\n io::stdin().read_line(&mut buf).unwrap();\n let v: u32 = buf.split_whitespace()\n .map(|word| {\n word.chars()\n .map(|c| if c.is_uppercase() {1} else {0})\n .sum()\n })\n .max().unwrap();\n println!(\"{}\", v);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8d6f8717fdd8b5e1dc06f3acc272d644", "src_uid": "d3929a9acf1633475ab16f5dfbead13c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let mut x = String::new();\n std::io::stdin().read_line(&mut x).unwrap();\n let x: u8 = x.trim().parse().unwrap();\n\n let (a, category) = match x % 4 {\n 0 => (1, 'A'),\n 1 => (0, 'A'),\n 2 => (1, 'B'),\n 3 => (2, 'A'),\n _ => unreachable!()\n };\n\n println!(\"{} {}\", a, category);\n}", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "80cf32d4a16382c317be6cec9dd57946", "src_uid": "488e809bd0c55531b0b47f577996627e", "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 x = input.u();\n let a = [3,0,2,1];\n let mut soli = 0;\n let mut sola = a[x % 4];\n for i in 1..=2 {\n let x = x + i;\n if m!(<,sola,a[x % 4]) {\n soli = i;\n }\n }\n println!(\"{} {}\", soli, (sola + b'A') as char);\n}\n\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "4c733d9fab1b2d99682f9f51d2603ac7", "src_uid": "488e809bd0c55531b0b47f577996627e", "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, 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 f(i: usize, k: u64, ll: &Vec) -> char {\n let mut i = i;\n let mut k = k;\n\n loop {\n if i == 0 {\n let f0 = \"What are you doing at the end of the world? Are you busy? Will you save us?\";\n return if f0.len() as u64 > k {\n f0.chars().nth(k as usize).unwrap()\n } else {\n '.'\n };\n } else {\n if k < 34 {\n let s1 = \"What are you doing while sending \\\"\";\n return s1.chars().nth(k as usize).unwrap();\n } else if k < 34 + ll[i - 1] {\n // f(i - 1, k - 34, ll)\n i -= 1;\n k -= 34;\n } else if k < 34 + ll[i - 1] + 32 {\n let s2 = \"\\\"? Are you busy? Will you send \\\"\";\n return s2.chars().nth((k - 34 - ll[i - 1]) as usize).unwrap();\n } else if k < 34 + ll[i - 1] + 32 + ll[i - 1] {\n // f(i - 1, k - 34 - ll[i - 1] - 32, ll)\n k -= 34 + ll[i - 1] + 32;\n i -= 1;\n } else if k < 34 + ll[i - 1] + 32 + ll[i - 1] + 2 {\n let s3 = \"\\\"?\";\n return s3.chars()\n .nth((k - 34 - ll[i - 1] - 32 - ll[i - 1]) as usize)\n .unwrap();\n } else {\n return '.';\n }\n }\n }\n\n}\n\nfn main() {\n let k_max: u64 = 1000000000000000000;\n\n let mut ll = Vec::new();\n ll.push(75u64);\n let mut n = 0;\n for i in 1..100001 {\n n = ll[i - 1] * 2 + 68;\n ll.push(n);\n if n > k_max {\n break;\n }\n }\n while ll.len() < 100001 {\n ll.push(n);\n }\n\n let mut ans = Vec::new();\n\n let n = get!(usize);\n\n for _ in 0..n {\n let (n, k) = get!(usize, u64);\n ans.push(f(n, k - 1, &ll));\n }\n\n println!(\"{}\", ans.into_iter().collect::());\n}\n", "lang_cluster": "Rust", "tags": ["math", "binary search", "combinatorics"], "code_uid": "dff3fa5898eb614f14e6a654c7bf5acc", "src_uid": "da09a893a33f2bf8fd00e321e16ab149", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let n:i64 = {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line);\n line.trim().parse().unwrap()\n };\n\n if n % 2 == 0 {\n println!(\"{:?}\", n / 2);\n } else {\n println!(\"{:?}\", n / 2 - n); \n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "ca8c43deeb9dd5f64d2bd54860ff02e1", "src_uid": "689e7876048ee4eb7479e838c981f068", "difficulty": 800.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()[0];\n println!(\"{}\", ((s+1)/2)*(1-2*(s%2)));\n}\n// min, max\n// HashSet, insert, contains\n// Vec, len, sort\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "9eaf3d4ea64372440ad30946eb1c77c3", "src_uid": "689e7876048ee4eb7479e838c981f068", "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::*;\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: usize = get();\n let m: usize = get();\n let k: usize = get();\n println!(\"{} {} {}\",\n (k - 1) / (2 * m) + 1,\n ((k - 1) % (2 * m)) / 2 + 1,\n if k % 2 == 1 { \"L\" } else { \"R\" });\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "21a1fb2af96249bb8f855a62bb42d1a7", "src_uid": "d6929926b44c2d5b1a8e6b7f965ca1bb", "difficulty": 800.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 nm = parse_line();\n let (n, m) = (nm[0], nm[1]);\n if n > m {\n println!(\"0\");\n return\n }\n let a = parse_line();\n let mut counts = a.iter().fold(vec![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 as usize];\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);\n //println!(\"{:?}\", nums);\n //println!(\"{}\", index); \n println!(\"{}\", counts[index] / nums[index]);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "binary search"], "code_uid": "9dcbc16f1492b82ca4c5813b51909057", "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 nm = parse_line();\n let (n, m) = (nm[0], nm[1]);\n if n > m {\n println!(\"0\");\n return\n }\n let a = parse_line();\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 as usize];\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": "c3a10604c7d644fb0d9746c35c4ffceb", "src_uid": "b7ef696a11ff96f2e9c31becc2ff50fe", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/problemset/problem/520/B\nuse std::io;\nuse std::collections::VecDeque;\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 mut distance = [1<<30;1000005];\n distance[n as usize] = 0;\n\n let mut q = VecDeque::::new();\n q.push_back(n);\n\n while !q.is_empty() {\n let u = q.pop_front().unwrap();\n let v = (2*u) as usize;\n let x = (u-1) as usize;\n\n\n if distance[v] == 1<<30 && (v as i64) < 2*m {\n distance[v] = distance[u as usize] + 1;\n q.push_back(v as i64);\n }\n\n if distance[x] == 1<<30 && x > 0 {\n distance[x] = distance[u as usize] + 1;\n q.push_back(u-1);\n }\n }\n println!(\"{}\", distance[m as usize]);\n}\n\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "88a1d3d58c2c91226f27fb0f5775cba1", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400.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 use std::collections::VecDeque;\n let a: usize = input.p();\n let b: usize = input.p();\n let mut dist = vec![-1; 20000];\n {\n let mut q = VecDeque::new();\n q.push_back(a as i32);\n dist[a] = 0;\n while let Some(p) = q.pop_front() {\n let d = dist[p as usize] + 1;\n let mut push = |q: &mut VecDeque<_>, p: i32, d: i32| {\n if let Some(x @ &mut -1) = dist.get_mut(p as usize) {\n *x = d;\n q.push_back(p);\n }\n };\n push(&mut q, 2 * p, d);\n push(&mut q, p - 1, d);\n }\n }\n println!(\"{}\", dist[b]);\n}\n\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "shortest paths", "math", "graphs", "greedy", "implementation"], "code_uid": "6e7df2c4e0d78557868716d84cf2bc10", "src_uid": "861f8edd2813d6d3a5ff7193a804486f", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nfn main() {\n let (mut h, m) = parse();\n let e = h;\n while reverse_number(h) > 59 || (reverse_number(h) <= m && h == e) {\n h += 1;\n }\n\n if h >= 24 {\n println!(\"00:00\")\n } else {\n print_it(h, reverse_number(h));\n }\n}\n\nfn parse() -> (usize, usize) {\n let mut entry = String::new();\n let mut hours = String::new();\n let mut minutes = String::new();\n let mut b = false;\n stdin().read_line(&mut entry).unwrap();\n\n for i in entry.trim().chars() {\n if i == ':' {\n b = true;\n } else if b {\n minutes.push(i);\n } else {\n hours.push(i);\n };\n }\n (hours.parse().unwrap(), minutes.parse().unwrap())\n}\n\nfn reverse_number(val: usize) -> usize {\n ((val % 10) * 10) + ((val - (val % 10)) / 10)\n}\n\nfn print_it(a: usize, b: usize) {\n let hours: String;\n let minutes: String;\n\n if a < 10 {\n hours = format!(\"0{}\", a);\n } else {\n hours = format!(\"{}\", a);\n };\n if b < 10 {\n minutes = format!(\"0{}\", b);\n } else {\n minutes = format!(\"{}\", b);\n };\n println!(\"{}:{}\", hours, minutes);\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "3064745a3b9c29661e97bae47d963c2b", "src_uid": "158eae916daa3e0162d4eac0426fa87f", "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 _main() {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let mut m: usize = scan.next();\n let circle = n * (n + 1) / 2;\n m %= circle;\n for i in 1..n {\n if i <= m {\n m -= i;\n } else {\n break;\n }\n }\n println!(\"{}\", m);\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": "3547c60e317bd7395e7e1fba1e3bd3d2", "src_uid": "5dd5ee90606d37cae5926eb8b8d250bb", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\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 h(par: &mut Vec, d: &mut Vec, i: i32) -> i32 {\n if i == 1 {\n return -1;\n }\n let p = par[i as usize - 2];\n if d[i as usize - 2] == 0 {\n d[i as usize - 2] = h(par, d, p) + 1\n }\n d[i as usize - 2]\n}\n\nfn main() {\n let v = read_line_of_integers();\n let (a, b) = (cmp::min(v[0], v[1]), cmp::max(v[0], v[1]));\n if a + v[2] <= b {\n println!(\"{}\", 2 * (a + v[2]));\n } else {\n println!(\"{}\", 2 * b + ((v[2] - (b - a)) / 2) * 2);\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "1612ac7839cfe5fa7048954ea02ad2c0", "src_uid": "e8148140e61baffd0878376ac5f3857c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp;\n\nfn read_line() -> String {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"Input error\");\n buffer\n}\n\nfn string_to_integer_iterator(string: String) -> Vec {\n string.split(' ')\n .map(|s| s.trim())\n .filter(|s| !s.is_empty())\n .map(|s| s.parse().unwrap()).collect()\n}\n\nfn main() {\n let vector = string_to_integer_iterator(read_line());\n let min = cmp::min(vector[0], vector[1]);\n let max = cmp::max(vector[0], vector[1]);\n let poten_max = min + vector[2];\n\n let result = (poten_max + cmp::min(poten_max, max)) >> 1 << 1;\n\n println!(\"{}\", result);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "2f72b4bf0b099201f6fefd549778c468", "src_uid": "e8148140e61baffd0878376ac5f3857c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub fn main() {\n let mut input = io::Input::new();\n\n let _n = input.next::();\n let s = input.next::();\n\n let mut count = 0;\n\n for xxx in s.split(|c| c != 'x') {\n if xxx.len() > 2 {\n count += xxx.len() - 2;\n }\n }\n\n println!(\"{}\", count);\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": ["greedy", "strings"], "code_uid": "fb3a248a4e0152ab338bf742de8b6478", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "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::{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: usize = get();\n let s: Vec<_> = get_word().chars().collect();\n let mut tot = 0;\n let mut cur = 0;\n for i in 0 .. n + 1 {\n if i == n || s[i] != 'x' {\n tot += max(0, cur - 2);\n cur = 0;\n } else {\n cur += 1;\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": ["greedy", "strings"], "code_uid": "3f7cfe297e8eef0a55a306e3a85775da", "src_uid": "8de14db41d0acee116bd5d8079cb2b02", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/266/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.clear();\n io::stdin().read_line(&mut buf).unwrap();\n let rocks = buf.trim().as_bytes();\n let mut last = rocks[0];\n let mut remove = 0;\n for &rock in &rocks[1..] {\n if rock == last { remove += 1; }\n else { last = rock; }\n }\n println!(\"{}\", remove);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "04e4c8cf4d7d06ed6401560f6fe56d14", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "/*\n Implementation - https://codeforces.com/problemset/problem/1030/A\n Completed: 2/7/20 21:20\n*/\n\nuse std::io;\n\nfn main() {\n let mut first_input = String::new();\n io::stdin().read_line(&mut first_input).unwrap();\n\n let mut last_input = String::new();\n io::stdin().read_line(&mut last_input).unwrap();\n\n let mut byte: &u8 = &0;\n let mut out_value = 0;\n\n for letter in last_input.as_bytes() {\n if letter == byte {\n out_value += 1;\n }\n byte = letter;\n }\n\n println!(\"{}\", out_value);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "5b85dc4ef15913e64466a84b7270a42c", "src_uid": "d561436e2ddc9074b98ebbe49b9e27b8", "difficulty": 800.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\n// 長さ3までしかなさそう\n// 1~3までをそれぞれ数えられればいい\n// 長さ1\n// gcd > 1 なペアの数\n// 長さ2\n// gcd = 1 で最小素因数の積がN 以下なもの\n// 長さ3\n// 最小素因数の積がNを超えるやつ\n// どう数える\n// 1\n// 包除原理でいけるはず\n// 2, 3\n// 最小素因数で分類すればなんとかなる?\n// 2 * p > N な素数は削除しておく\n// 互いに素の条件を扱えてなかった...\n// 最小素因数の積がNを超えてるなら互いに素になる\n// 超えないなら?\n// 事前にメモっておけばいい感じか?\n// ややこしい\n// 最小素因数が異なるかつ積がN以下かつ互いに素じゃないペアの数\n\nfn run() {\n input! {\n n: usize,\n }\n let mut factor = (0..=n).collect::>();\n let mut mobius = vec![1i8; n + 1];\n let mut prime = vec![];\n let mut cnt = vec![];\n for i in 2..=n {\n if i == factor[i] {\n prime.push(i);\n let mut c = 0;\n for j in 1..=(n / i) {\n let p = &mut factor[j * i];\n if i <= *p {\n *p = i;\n c += 1;\n }\n mobius[j * i] *= -1;\n }\n cnt.push(c);\n let pp = i.saturating_mul(i);\n for j in 1..=(n / pp) {\n mobius[j * pp] = 0;\n }\n }\n }\n while prime.last().map_or(false, |p| 2 * *p > n) {\n prime.pop();\n cnt.pop();\n }\n let mut all = cnt.iter().sum::();\n all = all * (all - 1) / 2;\n let mut ans = 0i64;\n for (i, mobius) in mobius.iter().enumerate().skip(2) {\n let s = *mobius as i64;\n if s != 0 {\n let cnt = (n / i) as i64;\n all += s * cnt * (cnt - 1) / 2;\n ans -= cnt * (cnt - 1) / 2 * s;\n }\n }\n let mut sum = 0;\n let mut x = 0;\n let mut two = 0;\n for (i, (c, p)) in cnt.iter().zip(prime.iter()).enumerate() {\n while x < i && *p * prime[x] <= n {\n two += cnt[x];\n x += 1;\n }\n while x > 0 && *p * prime[x - 1] > n {\n x -= 1;\n two -= cnt[x];\n }\n ans += (sum - two) * *c * 3;\n all -= (sum - two) * *c;\n sum += *c;\n }\n ans += 2 * all;\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "number theory"], "code_uid": "3bac886cd8e00a988ba086541f5ea34c", "src_uid": "bb1bd5d8bab7d79e514281230d484996", "difficulty": 2700.0, "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 const EOF: i32 = -1;\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 Scanner::::EOF;\n }\n }\n \n let ch = self.buffer[self.position];\n self.position += 1;\n \n ch as i32\n }\n \n fn read_char_skip_ws(&mut self) -> i32 {\n let mut ch = self.read_char();\n while ch != Scanner::::EOF && Scanner::::SPACES.contains(&ch) {\n ch = self.read_char();\n }\n\n if ch == Scanner::::EOF {\n return Scanner::::EOF;\n }\n\n return ch;\n }\n\n fn read_int(&mut self) -> Option {\n let mut ch = self.read_char_skip_ws();\n if ch == Scanner::::EOF {\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 != Scanner::::EOF && 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, s: &mut String) -> bool {\n let mut ch = self.read_char_skip_ws();\n if ch == Scanner::::EOF {\n return false;\n }\n \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 true;\n }\n}\n\nfn main() {\n let mut stdin = std::io::stdin();\n let mut reader = Scanner::new(&mut stdin);\n\n let n = reader.read_int().unwrap() as i64;\n let k = reader.read_int().unwrap() as i64;\n \n let y = ((-3f64 + ((9 + 8 * (n + k)) as f64).sqrt()) / 2f64) as i64;\n let x = n - y;\n\n println!(\"{}\", x);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "binary search"], "code_uid": "8ed80a96aa9a4834adec59e015a6d625", "src_uid": "17b5ec1c6263ef63c668c2b903db1d77", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/405/problem/A\n\nfn main() {\n use std::io;\n let mut buf = String::new();\n let mut rows: Vec = Vec::with_capacity(100);\n let cols: Vec;\n io::stdin().read_line(&mut buf).unwrap();\n let n = buf.trim().parse::().unwrap();\n buf.clear();\n io::stdin().read_line(&mut buf).unwrap();\n cols = buf.split(\" \")\n .map(|str| str.trim().parse::().unwrap())\n .collect();\n for i in 1..101 {\n let mut row = 0;\n for j in 0..(n as usize) {\n if cols[j] >= i {\n row += 1;\n }\n } \n rows.push(row);\n }\n let mut res: Vec = Vec::with_capacity(n as usize);\n for i in 1..(n as usize + 1) {\n let mut col = 0;\n for j in 0..100 {\n if rows[j] >= i as u32 {\n col += 1;\n }\n }\n res.push(col);\n }\n res.reverse();\n for i in 0..n as usize {\n if i != 0 { print!(\" \"); }\n print!(\"{}\", res[i]);\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "b5580f790df6bd8cf5f08c817bf2124b", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900.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\n let _first = iterator.next().unwrap().unwrap();\n let second = iterator.next().unwrap().unwrap();\n\n let mut numbers: Vec = second\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n\n numbers.sort();\n\n let strings: Vec = numbers\n .iter()\n .map(|s| s.to_string())\n .collect();\n println!(\"{}\", strings.join(\" \"));\n}", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "8b365d59042b78884a3c0429a84c8a18", "src_uid": "ae20712265d4adf293e75d016b4b82d8", "difficulty": 900.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 v: Vec = get_word().bytes().collect();\n let mut ok = true;\n let mut used = [false; 26];\n let n = v.len();\n for i in 0 .. n {\n let idx = (v[i] - b'a') as usize;\n for j in 0 .. idx {\n if !used[j] {\n ok = false;\n }\n }\n used[idx] = true;\n }\n println!(\"{}\", if ok { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings", "implementation"], "code_uid": "64d686da9f9723ddc7583f11762e6510", "src_uid": "c4551f66a781b174f95865fa254ca972", "difficulty": 1100.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\nuse std::io::Write;\r\n\r\n// 電源をon にするもの固定すると\r\n// 2つ飛ばしは無理\r\n// 3つ以上連続する部分は左からor右から単調に操作しなければならない\r\n// 最後に置いた空白でDP?\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]: 最後の空白がa, b個置いた\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 + 1) {\r\n for j in 0..=(n + 1) {\r\n let way = dp[i][j];\r\n if way.is_zero() {\r\n continue;\r\n }\r\n for k in 1.. {\r\n if i + k + 1 > n + 1 {\r\n break;\r\n }\r\n if k > 1 {\r\n dp[i + k + 1][j + k] += pow[k - 1] * way * pc.comb(j + k, j);\r\n } else {\r\n dp[i + k + 1][j + k] += way * pc.comb(j + k, j);\r\n }\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": "6a7362f6f51d1cb891da84ddc10db330", "src_uid": "4f0e0d1deef0761a46b64de3eb98e774", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str;\n\nfn count_divisors(n: i64) -> i64 {\n let mut n = n;\n let mut d = 2;\n let mut ans = 1;\n while d * d <= n && n > 1 {\n let mut expo = 0;\n while n % d == 0 {\n n /= d;\n expo += 1;\n }\n ans *= expo + 1;\n d += 1;\n }\n if n > 1 {\n ans *= 2;\n }\n ans\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let b: i64 = scan.token();\n let ans = count_divisors(b);\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": "2a29b5f07a6e563db64b6418e1f5f8b2", "src_uid": "7fc9e7d7e25ab97d8ebc10ed8ae38fd1", "difficulty": 1200.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};\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, m) = scan.pair::();\n\n if n == 1 {\n return answer!(out, 1);\n }\n \n answer!(out, if m-1 < n-m {\n m+1 \n } else {\n m-1\n })\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": ["constructive algorithms", "games", "math", "greedy", "implementation"], "code_uid": "31aa53d673bf236f72c5510fd2ea15c3", "src_uid": "f6a80c0f474cae1e201032e1df10e9f7", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\nuse std::io;\n\nfn read() -> i32 {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n let n: i32 = line.trim().parse().unwrap();\n n\n}\n\nfn main() {\n let mut n = read();\n if n >= 0 {\n println!(\"{}\", n);\n } else {\n n = -n;\n let last_digit = n % 10;\n let before_last_digit = (n / 10) % 10;\n let n_without_last_two_digits = n / 100;\n let ans = -(n_without_last_two_digits * 10 + min(last_digit, before_last_digit));\n println!(\"{}\", ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "29b08ddca9f1f7575f4455f8ad074463", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 2018-10-12 10:25\nfn main() {\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 if n >= 0 {\n println!(\"{:?}\", n);\n } else {\n let x = n / 10;\n let y = n % 10 + n / 100 * 10;\n println!(\"{:?}\", std::cmp::max(x, y));\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "number theory"], "code_uid": "c5d424f29e56c0b9c8aa812cafa261c9", "src_uid": "4b0a8798a6d53351226d4f06e3356b1e", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::cmp::{\n min,\n max\n};\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 (nodes, edges) = readln!(i64, i64);\n\n let (min_isolated, max_isolated) = if edges == 0 {\n (nodes, nodes)\n } else {\n (\n if nodes % 2 == 0 {\n max(0, ((nodes + 1) / 2 - edges) * 2)\n } else {\n max(0, ((nodes + 1) / 2 - edges) * 2 - 1)\n },\n nodes - ((1.0 + (8.0 * edges as f64 + 1.0).sqrt()) / 2.0).ceil() as i64\n )\n };\n\n\n println!(\"{} {}\", min_isolated, max_isolated);\n}", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "debe87228c1c825a49801071fef73bfe", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused)] use std::io::*;\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}\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\nfn bin_search bool>(first: i64, last: i64, func: T) -> i64 {\n let mut l = first;\n let mut r = last;\n let dir = func(l);\n\n while l + 1 < r {\n let mid = (l + r) / 2;\n if func(mid) == dir {\n l = mid;\n } else {\n r = mid;\n }\n }\n\n return l\n}\n\nfn main() {\n let (nodes, edges) = scan!(i64, i64);\n let min_graph_size = bin_search(0, nodes + 1, |n| n * (n - 1) / 2 < edges) + 1;\n\n let min_single = if edges == 0 {\n nodes\n } else if 2 * edges >= nodes {\n 0\n } else {\n nodes - 2 * edges\n };\n\n let max_single = if edges == 0 {\n nodes\n } else {\n nodes - min_graph_size\n };\n\n println!(\"{} {}\", min_single, max_single);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "graphs"], "code_uid": "2eaed6fb391ccbba960bd89ec7122bb4", "src_uid": "daf0dd781bf403f7c1bb668925caa64d", "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\n println!(\"{}\", (1..1 + (input.i().min(input.i()) as i64))\n .product::());\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "f97050fe5c01e5dd6452e6a6b663893f", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\nuse std::io;\n\nfn factorial(n: u32) -> u32 {\n (1..=n).fold(1, |acc, x| acc * x)\n}\n\nfn main() {\n let mut line = String::new();\n io::stdin().read_line(&mut line).unwrap();\n let numbers: Vec = line\n .split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n let a = numbers[0];\n let b = numbers[1];\n let ans = factorial(min(a, b));\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "dce934661d9e139c7b2c098c47ff5ed5", "src_uid": "7bf30ceb24b66d91382e97767f9feeb6", "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() {\nlet (n,k) = readln!(i64,i64);\nprintln!(\"{}\",if (n/k)%2 == 0 { \"NO\" } else { \"YES\" });\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "42984ff66638efc9a1ef8b7cb0101244", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\n\nfn main() { \n let stdin = stdin();\n let mut s = String::new();\n stdin.read_line(&mut s).unwrap();\n let vec = s.split_whitespace().map(|x| x.parse::().expect(\"number parse error\")).collect::>();\n if (vec[0] / vec[1])&1 > 0 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "games"], "code_uid": "5cf0193175d393a035d55b79b1c6ead8", "src_uid": "05fd61dd0b1f50f154eec85d8cfaad50", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// https://codeforces.com/contest/1271/problem/E\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 exp(upto: usize, k: usize) {\n let mut cnt = vec![0; upto];\n for w in 1..upto {\n let mut ww = w;\n loop {\n cnt[ww] += 1;\n if ww == 1 {\n break;\n }\n if ww % 2 == 0 {\n ww /= 2;\n } else {\n ww -= 1;\n }\n }\n }\n let mut up = 0;\n for w in (1..upto).rev() {\n if cnt[w] > up {\n up = cnt[w];\n // debug!(w, up);\n }\n }\n for w in (1..upto).rev() {\n if cnt[w] >= k {\n println!(\"{}\", w);\n break;\n }\n }\n}\n\nfn main() {\n input! {\n n: i64, k: i64\n };\n\n if n <= 100 {\n exp((n+1) as usize, k as usize);\n return;\n }\n\n let mut ans = -1;\n let mut tbl = vec![(n, 1), (n-1, ifv!(n % 2 == 0, 1, 2)), (n-2, ifv!(n % 2 == 0, 2, 1))];\n loop {\n // debug!(tbl);\n for &(f, l) in &tbl {\n if k <= l {\n ans = f;\n break;\n }\n }\n if tbl[0].0 <= 1 {\n break;\n }\n if ans != -1 {\n break;\n }\n\n\n let mut ntbl: Vec<(i64, i64)> = vec![];\n let tn = tbl.len();\n for nex in 0..4 {\n let to = tbl[0].0 / 2 - nex;\n let mut add = 1;\n\n // find 2*to\n {\n let mut f2 = false;\n for f in 0..tn {\n if tbl[f].0 == 2*to {\n add += tbl[f].1;\n f2 = true;\n break;\n }\n }\n if !f2 {\n for f in 0..nex {\n if ntbl[f as usize].0 == 2*to {\n add += ntbl[f as usize].1;\n f2 = true;\n break;\n }\n }\n }\n\n if !f2 {\n for f in (0..tn).rev() {\n if tbl[f].0 % 2 == 0 {\n add += tbl[f].1;\n break;\n }\n }\n }\n }\n\n // find to+1\n if to % 2 == 0 {\n // we already have that one...\n if nex >= 1 {\n add += ntbl[(nex-1) as usize].1;\n } else {\n for f in (0..tn).rev() {\n if tbl[f].0 % 2 == 1 {\n add += tbl[f].1;\n break;\n }\n }\n }\n }\n ntbl.push((to, add));\n }\n tbl = ntbl;\n }\n\n // exp((n+1) as usize);\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "binary search", "dp", "combinatorics"], "code_uid": "8ccc6835da056fe3737eee1cb3538144", "src_uid": "783c4b3179c558369f94f4a16ac562d4", "difficulty": 2100.0, "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 ans = min(ans, 10 * (index - m).abs());\n }\n index += 1;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "616acaf9bb2df9225beb625e83e3d903", "src_uid": "57860e9a5342a29257ce506063d37624", "difficulty": 800.0, "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}\n\nfn main() {\n let mut scan = Scanner::default();\n let n = scan.next::();\n let mut a = vec![0; n];\n for i in 0..n {\n a[i] = scan.next::();\n }\n let mut b = vec![0; n];\n for i in 0..n {\n b[i] = scan.next::();\n }\n let mut num_a = 0;\n let mut num_b = 0;\n for i in 0..n {\n if a[i] == 1 && b[i] == 0 {\n num_a += 1;\n } else if a[i] == 0 && b[i] == 1 {\n num_b += 1;\n }\n }\n let ans = {\n if num_a == 0 {\n -1\n } else {\n let mut x = 1;\n while num_a * x <= num_b {\n x += 1;\n }\n x\n }\n };\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "8f434d686ef7266cf713240640f3784e", "src_uid": "b62338bff0cbb4df4e5e27e1a3ffaa07", "difficulty": 900.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 m:usize = read();\n let mut p:Vec<(usize,usize,i64,usize)> = (0..m).map(|i| (read::()-1,read::()-1,read(),i)).collect();\n\n let mut v = vec![];\n\n let mut f = vec![false;m];\n let mut c = vec![0;m];\n for i in 0..m { c[i] = p[i].2; }\n\n for i in 0..n {\n // examがあれば実行\n let mut idx = m;\n for j in 0..m {\n if p[j].1 == i {\n idx = j;\n }\n }\n if idx != m {\n if c[idx] == 0 {\n v.push(m+1);\n continue;\n } else {\n println!(\"-1\");\n return;\n }\n }\n // 可能なタスクの中で締め切りの近いものを求める\n let mut idx = m;\n let mut dead = n;\n for j in 0..m {\n if !f[j] && p[j].0 <= i && i < p[j].1 {\n if dead > p[j].1 {\n dead = p[j].1;\n idx = j;\n }\n }\n }\n\n // 可能なタスクがない場合は休む\n if idx == m {\n v.push(0);\n continue;\n }\n\n // タスクを実行\n v.push(idx+1);\n c[idx] -= 1;\n if c[idx] == 0 {\n f[idx] = true;\n }\n\n }\n\n for e in v {print!(\"{} \", e);} println!();\n\n //}\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "54c3350b958b9845bca6895d605e3bb9", "src_uid": "02d8d403eb60ae77756ff96f71b662d3", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)]\r\nuse std::cmp::{max, min};\r\nuse std::io::{stdin, stdout, BufWriter, Write};\r\n\r\n// code from https://codeforces.com/blog/entry/67391, modified by rkm0959\r\n\r\n#[derive(Default)]\r\nstruct UnkScanner {\r\n buffer: Vec,\r\n}\r\n\r\nimpl UnkScanner {\r\n fn next(&mut self) -> Option {\r\n loop {\r\n if let Some(token) = self.buffer.pop() {\r\n return token.parse().ok();\r\n }\r\n let mut input = String::new();\r\n match stdin().read_line(&mut input) {\r\n Ok(0) => return None,\r\n Err(_) => return None,\r\n _ => self.buffer = input.split_whitespace().rev().map(String::from).collect(),\r\n }\r\n }\r\n }\r\n}\r\n\r\n/*\r\n\r\nn even\r\nfirst \"all common\" at t\r\nfor all t+1 ~ k-1, even number gets it (not n)\r\n-> kills at t as well, sice\r\n\r\nn odd\r\nfirst \"all common\" at t\r\nall common or even gets it for each k\r\n\r\n*/\r\n\r\nfn exp(mut x: i64, mut y: i64, md: i64) -> i64 {\r\n let mut ret: i64 = 1;\r\n while y > 0 {\r\n if y % 2 == 1 {\r\n ret = (ret * x) % md;\r\n }\r\n x = (x * x) % md;\r\n y = y / 2;\r\n }\r\n return ret;\r\n}\r\n\r\nfn main() {\r\n let mut scan = UnkScanner::default();\r\n let out = &mut BufWriter::new(stdout());\r\n let tc: usize = scan.next::().expect(\"\");\r\n let md: i64 = 1_000_000_007;\r\n for _ in 0..tc {\r\n let n = scan.next::().expect(\"\");\r\n let k = scan.next::().expect(\"\");\r\n if k == 0 {\r\n writeln!(out, \"1\").ok();\r\n continue;\r\n }\r\n if n % 2 == 0 {\r\n let mut ans: i64 = 0;\r\n let v1 = exp(2, n - 1, md) - 1;\r\n let v2 = exp(2, n, md);\r\n for i in 0..k {\r\n // i+1 ~ k-1 2^(n-1) - 1\r\n // 0, ... i-1 ~ 2^n\r\n let add: i64 = (exp(v2, i, md) * exp(v1, k - i - 1, md)) % md;\r\n ans += add;\r\n if ans >= md {\r\n ans -= md;\r\n }\r\n }\r\n let add = exp(v1, k, md);\r\n ans += add;\r\n if ans >= md {\r\n ans -= md;\r\n }\r\n writeln!(out, \"{}\", ans).ok();\r\n } else {\r\n let v1 = exp(2, n - 1, md) + 1;\r\n let ans = exp(v1, k, md);\r\n writeln!(out, \"{}\", ans).ok();\r\n }\r\n }\r\n return;\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "24145afccdbc202b46504083788b4416", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\r\n\r\nconst N : usize = 200006;\r\nconst P : u64 = 1000000007;\r\ntype Farr = [[u64; 4]; N];\r\ntype Garr = [u64; N];\r\n\r\nfn preprocess(f : &mut Farr, g : &mut Garr) {\r\n f[0][2] = 1;\r\n g[0] = 1;\r\n for i in 0..N-1 {\r\n f[i+1][3] = f[i][2];\r\n f[i+1][2] = f[i][3];\r\n f[i+1][1] = ((f[i][0] + f[i][1]) % P + f[i][3]) % P;\r\n f[i+1][0] = ((f[i][0] + f[i][1]) % P + f[i][2]) % P;\r\n g[i+1] = (g[i] + g[i]) % P;\r\n }\r\n\r\n}\r\n\r\nfn solve(f : &Farr, g : &Garr) {\r\n let mut a_str = String::new();\r\n io::stdin().read_line(&mut a_str).expect(\"read error\");\r\n let vec = a_str.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\r\n let n = vec[0] as usize;\r\n let k = vec[1] as usize;\r\n let mut win : u64 = 0;\r\n let mut tie : u64 = 1;\r\n for _ in 0..k {\r\n win = (win * g[n] % P + tie * f[n][2]) % P;\r\n tie = ((f[n][0] + f[n][3]) % P * tie) % P;\r\n }\r\n let ans = (win + tie) % P;\r\n println!(\"{}\", ans);\r\n}\r\n\r\nfn main() {\r\n let mut str = String::new();\r\n io::stdin().read_line(&mut str).expect(\"read error\");\r\n let mut f : Farr = [[0u64; 4]; N];\r\n let mut g : Garr = [0u64; N];\r\n preprocess(&mut f, &mut g);\r\n if let Some(s) = str.split_whitespace().next() {\r\n let tests = s.parse::().unwrap();\r\n for _ in 0..tests {\r\n solve(&f, &g);\r\n }\r\n }\r\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "bitmasks", "matrices"], "code_uid": "6ab952e597c2c497f3da2a258a8fa96a", "src_uid": "02f5fe43ea60939dd4a53299b5fa0881", "difficulty": 1700.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 mut 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 if i == '4' {\n c.push_str(\"223\");\n } else if i == '6' {\n c.push_str(\"53\");\n } else if i == '8' {\n c.push_str(\"7222\");\n } else if i == '9' {\n c.push_str(\"2337\");\n } else {\n c.push(i);\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": "8f0ce6051eb57b560941fb527527795f", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "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 _main() {\n let mut scan = Scan::new();\n let _: usize = scan.next();\n let num: String = scan.next();\n let mut cnt = [0usize; 10];\n for c in num.chars() {\n match c {\n '2' => {\n cnt[2] += 1;\n }\n '3' => {\n cnt[3] += 1;\n }\n '4' => {\n cnt[2] += 2;\n cnt[3] += 1;\n }\n '5' => {\n cnt[5] += 1;\n }\n '6' => {\n cnt[3] += 1;\n cnt[5] += 1;\n }\n '7' => {\n cnt[7] += 1;\n }\n '8' => {\n cnt[2] += 3;\n cnt[7] += 1;\n }\n '9' => {\n cnt[2] += 1;\n cnt[3] += 2;\n cnt[7] += 1;\n }\n _ => {}\n }\n }\n for i in (2..10).rev() {\n for _ in 0..cnt[i] {\n print!(\"{}\", i);\n }\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": ["math", "sortings", "greedy"], "code_uid": "b73440d5c35efbe0bedc2ea1666e6778", "src_uid": "60dbfc7a65702ae8bd4a587db1e06398", "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 is_prime(x: usize) -> bool {\n for i in 2..=((x as f64).sqrt() as usize) {\n if x % i == 0 {\n return false;\n }\n }\n return true;\n}\n\nfn next_prime(x: usize) -> usize {\n let mut aux = x + 1;\n while !is_prime(aux) {\n aux += 1;\n }\n aux\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 = next_prime(n) == m;\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"], "code_uid": "3e4c5d9f17e510622983f7cfdb613dd4", "src_uid": "9d52ff51d747bb59aa463b6358258865", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// A. Chess Placing http://codeforces.com/contest/985/problem/A\n\nfn main() {\n let stdin = std::io::stdin();\n let mut buf = String::new();\n stdin.read_line(&mut buf).unwrap(); // discard\n buf.clear();\n stdin.read_line(&mut buf).unwrap();\n let mut arr: Vec = buf.split_whitespace()\n .map(|s| s.parse().unwrap())\n .collect();\n arr[..].sort_unstable();\n let f = |mut m: i32| {\n let mut total = 0;\n for n in &arr {\n total += (n - m).abs();\n m += 2;\n }\n total\n };\n let ans: i32 = vec![1, 2].into_iter().map(f).min().unwrap();\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "1dc8c56bdb34f8693c653e75b7e8d1c4", "src_uid": "0efe9afd8e6be9e00f7949be93f0ca1a", "difficulty": 1100.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: usize = sc.next();\n let mut ps: Vec = sc.next_vec(n / 2);\n ps.sort();\n\n let mut acc_b = 0;\n let mut acc_w = 0;\n for i in 0..n / 2 {\n acc_b += (ps[i] - 1 - i as i64 * 2).abs();\n acc_w += (ps[i] - 1 - i as i64 * 2 - 1).abs();\n }\n\n println!(\"{}\", acc_b.min(acc_w));\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": "0ade5aa0feefd2f570dae67746f8c0c2", "src_uid": "0efe9afd8e6be9e00f7949be93f0ca1a", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\n let (n, l): (usize, i64) = readln();\n let c: Vec = readln();\n\n let mut rest: i64 = l;\n let mut answer = i64::max_value();\n let mut used: i64 = 0;\n while rest > 0 {\n let over_cost = (0..n).filter(|x| rest <= (1i64 << x)).map(|x| c[x]).min();\n if let Some(over_cost) = over_cost {\n answer = min(answer, used + over_cost);\n }\n let last_idx = (0..n).filter(|x| rest >= (1i64 << x)).last().unwrap();\n let cost = (0..last_idx + 1)\n .map(|x| (1i64 << (last_idx - x)) * c[x])\n .min()\n .unwrap();\n let last_pow = (0..36).filter(|x| rest >= (1i64 << x)).last().unwrap();\n used += cost * 1i64 << (last_pow - last_idx);\n rest -= 1i64 << last_pow;\n }\n answer = min(answer, used);\n println!(\"{}\", answer);\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": ["greedy", "dp", "bitmasks"], "code_uid": "421765f8a6564f49bc0693dd7878d541", "src_uid": "04ca137d0383c03944e3ce1c502c635b", "difficulty": 1600.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\n\n#[derive(Copy, Clone, Debug)]\nstruct Pair {\n i : usize,\n cost : i64\n}\nimpl PartialOrd for Pair {\n fn partial_cmp(&self, other : &Pair) -> Option {\n Some(self.cost.cmp(&other.cost))\n }\n}\n\nimpl Ord for Pair {\n fn cmp(&self, other : &Pair) -> Ordering {\n self.partial_cmp(other).unwrap()\n }\n}\n\nimpl PartialEq for Pair {\n fn eq(&self, other : &Pair) -> bool {\n self.cost == other.cost\n }\n}\nimpl Eq for Pair {}\n\nfn main() {\n let stdin = stdin();\n let mut s = stdin.lock();\n let (n, k) = scan!(s, usize, i64);\n let mut remaining = 4*60 - k;\n let mut count = 0;\n \n for i in 1..(n+1) {\n if remaining >= 5*i.num() {\n count += 1;\n remaining -= 5*i.num();\n } else {\n break;\n }\n }\n \n println!(\"{}\", count);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "fe263bf16b5b14c9988136b8d2c9ddff", "src_uid": "41e554bc323857be7b8483ee358a35e2", "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)\n .expect(\"Failed to read line\");\n\n let split_input : Vec<&str> = input.as_str().split(' ').collect();\n let n : i32 = split_input[0].trim().parse().expect(\"en\"); \n let k : i32 = split_input[1].trim().parse().expect(\"en\"); \n let m : i32 = 240 - k; // left time\n let mut sum : i32 = 0;\n let mut counter : i32 = 0;\n for i in 1 .. (n + 1) {\n if sum + i * 5 > m {\n break;\n } else {\n sum += i * 5;\n counter += 1;\n }\n }\n println!(\"{}\", counter);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation", "binary search"], "code_uid": "26b08c776981bc13e22fb9f8103b36f0", "src_uid": "41e554bc323857be7b8483ee358a35e2", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead, Write};\n\nfn solve(mut input: I, mut output: O) {\n let from = read_time(&mut input);\n let to = read_time(&mut input);\n let from_minutes = from.0 * 60 + from.1;\n let to_minutes = to.0 * 60 + to.1;\n let mid_minutes = (to_minutes + from_minutes) / 2;\n let mid = (mid_minutes / 60, mid_minutes % 60);\n writeln!(output, \"{:02}:{:02}\", mid.0, mid.1).unwrap();\n}\n\nfn read_time(mut input: I) -> (i32, i32) {\n let mut time = String::new();\n input.read_line(&mut time).unwrap();\n let time: Vec = time.split(':').map(|x| x.trim().parse().unwrap()).collect();\n (time[0], time[1])\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn example1() {\n assert_eq!(solve(\"10:00\\n11:00\\n\"), \"10:30\\n\");\n }\n\n #[test]\n fn example2() {\n assert_eq!(solve(\"11:10\\n11:12\\n\"), \"11:11\\n\");\n }\n\n #[test]\n fn example3() {\n assert_eq!(solve(\"01:02\\n03:02\\n\"), \"02:02\\n\");\n }\n\n fn solve(input: &str) -> String {\n let mut output = Vec::new();\n super::solve(input.as_bytes(), &mut output);\n String::from_utf8(output).unwrap()\n }\n}\n\nfn main() {\n let input = io::stdin();\n let input = input.lock();\n let output = io::stdout();\n let output = output.lock();\n solve(input, output)\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "3acbf8fb34d100ea118080ba02634e96", "src_uid": "f7a32a8325ce97c4c50ce3a5c282ec50", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[derive(Debug, Eq, PartialEq, Clone, Copy)]\nstruct Time {\n h: u16,\n m: u16\n}\n\nfn parse_time(s: &str) -> Option::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 s = read_stdin().chars().collect::>();\n let t = read_stdin().chars().collect::>();\n let mut front = Vec::new();\n let mut pointer = 0;\n for c in t.iter() {\n while s[pointer] != *c {\n pointer += 1;\n }\n front.push(pointer);\n pointer += 1;\n }\n let mut back = Vec::new();\n let mut pointer = s.len() - 1;\n for c in t.iter().rev() {\n while s[pointer] != *c {\n pointer -= 1;\n }\n back.push(pointer);\n if pointer > 0 {\n pointer -= 1;\n }\n }\n back.reverse();\n //println!(\"{:?}\", front);\n //println!(\"{:?}\", back);\n let mut res = s.len() - front.last().unwrap() - 1;\n // println!(\"{} {}\", res, back[0]);\n res = max(res, back[0]);\n for (f, b) in front.into_iter().zip(back.into_iter().skip(1)) {\n //println!(\"{} {}\", b, f);\n res = max(res, b - f - 1)\n }\n println!(\"{}\", res);\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "28849069ccc80d252e61dc6ffdf3eb2a", "src_uid": "0fd33e1bdfd6c91feb3bf00a2461603f", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\nuse std::collections;\nuse std::io;\n\nstruct Input {\n buffer: collections::VecDeque,\n}\n\nimpl Input {\n fn new() -> Input {\n Input {\n buffer: collections::VecDeque::new(),\n }\n }\n\n fn next(&mut self) -> T {\n while self.buffer.len() == 0 {\n let mut line = String::new();\n std::io::stdin().read_line(&mut line).ok();\n for word in line.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 input = Input::new();\n let rook_str: String = input.next();\n let knight_str: String = input.next();\n\n let rook_pos = (\n rook_str.chars().nth(0).unwrap() as i32 - 'a' as i32,\n rook_str.chars().nth(1).unwrap() as i32 - '1' as i32,\n );\n\n let knight_pos = (\n knight_str.chars().nth(0).unwrap() as i32 - 'a' as i32,\n knight_str.chars().nth(1).unwrap() as i32 - '1' as i32,\n );\n\n let mut count = 8 * 8;\n\n for j in 0..8 {\n for k in 0..8 {\n if rook_pos.0 == j || rook_pos.1 == k {\n count -= 1;\n } else if knight_pos.0 == j && knight_pos.1 == k {\n count -= 1;\n } else if (rook_pos.0 - j).abs() == 2 && (rook_pos.1 - k).abs() == 1 {\n count -= 1;\n } else if (rook_pos.0 - j).abs() == 1 && (rook_pos.1 - k).abs() == 2 {\n count -= 1;\n } else if (knight_pos.0 - j).abs() == 2 && (knight_pos.1 - k).abs() == 1 {\n count -= 1;\n } else if (knight_pos.0 - j).abs() == 1 && (knight_pos.1 - k).abs() == 2 {\n count -= 1;\n }\n }\n }\n\n println!(\"{:?}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "implementation"], "code_uid": "f50ebbfd392f5ea4d327f76ec2fb01e8", "src_uid": "073023c6b72ce923df2afd6130719cfc", "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 { 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 k: usize = scan.next();\n let mut arr: Vec = scan.next_n(12);\n arr.sort();\n arr.reverse();\n let mut index = 1;\n let mut acc = arr[0];\n while acc < k && index < 12 {\n acc += arr[index];\n index += 1;\n }\n if acc < k {\n println!(\"-1\");\n } else if k == 0 {\n println!(\"0\");\n } else {\n println!(\"{}\", index);\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": ["sortings", "implementation", "greedy"], "code_uid": "b3358f3f1ba73324c7855ab38f127360", "src_uid": "59dfa7a4988375febc5dccc27aca90a8", "difficulty": 900.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 k = input.i();\n let mut a = input.vp::(12);\n a.sort();\n a.reverse();\n let sol = (|| {\n if k == 0 { return 0; }\n let mut sum = 0;\n for i in 0..12 {\n sum += a[i as usize];\n if sum >= k {\n return i + 1;\n }\n }\n -1\n })();\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation", "greedy"], "code_uid": "3e36cfb8f152ab4fcab4e8757b8e9901", "src_uid": "59dfa7a4988375febc5dccc27aca90a8", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n\tlet mut k = String::new();\n\tio::stdin().read_line(&mut k).unwrap();\n\tlet k: i32 = k.trim().parse().unwrap();\n\n\tlet mut l = String::new();\n\tio::stdin().read_line(&mut l).unwrap();\n\tlet l: i32 = l.trim().parse().unwrap();\n\n\tlet mut m = String::new();\n\tio::stdin().read_line(&mut m).unwrap();\n\tlet m: i32 = m.trim().parse().unwrap();\n\n\tlet mut n = String::new();\n\tio::stdin().read_line(&mut n).unwrap();\n\tlet n: i32 = n.trim().parse().unwrap();\n\n\tlet mut d = String::new();\n\tio::stdin().read_line(&mut d).unwrap();\n\tlet d: i32 = d.trim().parse().unwrap();\n\n\tlet mut ans = 0;\n\tfor i in 1..=d {\n\t\tif i % k == 0 || i % l == 0 || i % m == 0 || i % n == 0 {\n\t\t\tans += 1;\n\t\t}\n\t}\n\n\tprintln!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "2bb228ec77b02bca439637840b44efc8", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "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 k = scan.next::();\n\tlet l = scan.next::();\n\tlet m = scan.next::();\n\tlet n = scan.next::();\n\tlet d = scan.next::();\n\n let res = (1..=d).filter(|x| x % k == 0 || x % l == 0 || x % m == 0 || x % n == 0).count();\n writeln!(out, \"{}\", res).expect(\"fail\");\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms", "implementation"], "code_uid": "cb3ab7ca3cd79fdef9ac4bc45adef34d", "src_uid": "46bfdec9bfc1e91bd2f5022f3d3c8ce7", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::BufRead;\n\nfn read_problem(br: R) -> Vec {\n let mut lines = br.lines();\n\n let node_ct: usize = str::parse(&lines.next().unwrap().unwrap()).unwrap();\n let mut nodes = Vec::::with_capacity(node_ct);\n nodes.extend(lines.next().unwrap().unwrap().split_whitespace()\n .map(str::parse::)\n .map(|n| n.unwrap()-1));\n assert!(nodes.len() == node_ct);\n assert!(lines.next().is_none());\n nodes\n}\n\nfn gcd(mut a: u64, mut b: u64) -> u64 {\n if a == 0 || b == 0 {\n return a | b;\n }\n let shift = (a|b).trailing_zeros();\n a >>= a.trailing_zeros();\n while b != 0 {\n b >>= b.trailing_zeros();\n if a > b {\n std::mem::swap(&mut a, &mut b);\n }\n b -= a;\n }\n return a << shift;\n}\n\nfn solve(nodes: Vec) -> u64 {\n let mut state = nodes.iter().map(|_| false).collect::>();\n let mut solution = 1u64;\n\n // state is (cycle#,index); cycle# starts at 1; 0 is uninitialized\n for start in 0..state.len() {\n if state[start] {\n continue;\n }\n let mut index = start;\n let mut len = 0u64;\n while !state[index] {\n state[index] = true;\n index = nodes[index];\n len += 1;\n }\n if index != start {\n return 0;\n }\n if len&1 == 0 {\n len >>= 1;\n }\n solution = solution/gcd(solution,len) * len;\n }\n\n solution\n}\n\nfn main() {\n let stdin = std::io::stdin();\n let nodes = read_problem(stdin.lock());\n let sol = solve(nodes);\n if sol == 0 {\n println!(\"-1\");\n } else {\n println!(\"{}\", sol);\n }\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "math"], "code_uid": "9d3afa6f2fc62eb49ace1fd1301be4b5", "src_uid": "149221131a978298ac56b58438df46c9", "difficulty": 1600.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 s: chars,\n }\n\n let mut cur = 0i64;\n for i in 0..n {\n if s[i] == '+' {\n cur += 1;\n } else {\n cur = max(cur-1, 0);\n }\n }\n println!(\"{}\", cur);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "bf7cc8ab13ebddbf8e95b3969a52e48c", "src_uid": "a593016e4992f695be7c7cd3c920d1ed", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, Read, StdinLock};\nuse std::str::FromStr;\n#[allow(unused_imports)]\nuse std::cmp;\n\nstruct Scanner<'a> {\n cin : StdinLock<'a>,\n}\n\nimpl<'a> Scanner<'a> {\n fn new(cin : StdinLock<'a>) -> Scanner<'a> {\n Scanner { cin: cin }\n }\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\n fn read(&mut self) -> T {\n self.read1().unwrap()\n }\n}\n\nfn main(){\n\tlet cin = stdin();\n\tlet cin = cin.lock();\n\tlet mut sc = Scanner::new(cin);\n\tlet _ : usize = sc.read();\n let s : String = sc.read();\n let mut ans : usize = 0;\n for i in s.chars() {\n match i {\n '+' => ans += 1,\n '-' => if ans != 0 { ans -= 1; },\n _ => (),\n }\n }\n println!(\"{}\", ans);\n \n\n\n\n}\n\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "5f90815f7198c0e45182e32ae9041f88", "src_uid": "a593016e4992f695be7c7cd3c920d1ed", "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#[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 mut s: chars,\n }\n s.reverse();\n\n let mut ans = 0;\n let mut ones = 0;\n for i in 0..s.len() {\n if s[i] == '1' {\n ones += 1;\n }\n }\n let mut ans = (s.len() + 1) / 2;\n if s.len()%2 == 1 {\n if ones <= 1 {\n ans -= 1;\n }\n }\n puts!(\"{}\\n\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "84c4eb16e20af70d898997e0645bc130", "src_uid": "d8ca1c83b431466eff6054d3b422ab47", "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 a: u64 = sc.ne();\n let b: u64 = sc.ne();\n let mut cnt = 0;\n for i in 0..64 {\n let k = (1 << i) - 1;\n for j in 0..i - 1 {\n let aim = k ^ (1 << j);\n // println!(\"{:b}\", aim);\n if a <= aim && aim <= b {\n cnt += 1;\n }\n }\n }\n println!(\"{}\", cnt);\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": ["brute force", "implementation", "bitmasks"], "code_uid": "5ef100f4c90a88b576f98f425bf052d5", "src_uid": "581f61b1f50313bf4c75833cefd4d022", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn input_sum() -> f32 {\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 .sum()\n}\n\nfn main() {\n print!(\n \"{}\",\n if (input_sum() / 5f32).ceil() + (input_sum() / 10f32).ceil() <= input_sum() {\n \"YES\"\n } else {\n \"NO\"\n }\n )\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "584cfd760caf3238b27da3fe8a84e1e6", "src_uid": "fe6301816dea7d9cea1c3a06a7d1ea7e", "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 n: u64 = input.trim().parse().unwrap();\n\n let bc = n.next_power_of_two().trailing_zeros();\n\n let mut cb = 1;\n let mut ans = 0;\n for _ in 0..bc {\n let t = cb * ((n - 1 + cb) / (cb << 1));\n ans += t;\n cb <<= 1;\n }\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "bitmasks", "graphs", "implementation"], "code_uid": "cb81937bb4585e29471d57961d9939d5", "src_uid": "a98f0d924ea52cafe0048f213f075891", "difficulty": 1900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut kbd = String::new();\n\n io::stdin().read_line(&mut kbd).expect(\"WHY!\");\n\n let kbd:u64 = kbd.trim().parse().expect(\"WHY!\");\n\n if kbd > 0 {\n println!(\"25\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["number theory"], "code_uid": "57b507d9890aa441ae2bc135b27d84d9", "src_uid": "dcaff75492eafaf61d598779d6202c9d", "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,b,s) = readln!(i32,i32,i32);\n println!(\"{}\", if s >= a.abs()+b.abs() && ((s-(a.abs()+b.abs()))%2) == 0 { \"Yes\" } else { \"No\" });\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "39caf1c293f6cfdd9462c779ad1e76d4", "src_uid": "9a955ce0775018ff4e5825700c13ed36", "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 is_prime(n: i64) -> bool {\n let mut d = 2;\n while d * d <= n {\n if n % d == 0 {\n return false;\n }\n d += 1;\n }\n true\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let t: u32 = scan.token();\n for _ in 0..t {\n let a: i64 = scan.token();\n let b: i64 = scan.token();\n if a - b == 1 && is_prime(a + b) {\n writeln!(out, \"YES\").ok();\n } else {\n writeln!(out, \"NO\").ok();\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 solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "b2e0d483c720829f046dd76101a117f6", "src_uid": "5a052e4e6c64333d94c83df890b1183c", "difficulty": 1100.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\n\nfn main() {\n let stdin = stdin();\n let mut s = stdin.lock();\n let (m, s) = scan!(s, usize, i64);\n let mut smallest = vec![0; m];\n let mut largest = vec![0; m];\n let lower_bound = if m == 1 { 0 } else { 1 };\n let upper_bound = (9*m).num();\n\n if s >= lower_bound && s <= upper_bound {\n let mut temp = s;\n for i in 0..m {\n if temp > 9 {\n largest[i] = 9;\n temp -= 9;\n } else {\n largest[i] = temp;\n break;\n }\n }\n\n temp = s;\n for i in (0..m).rev() {\n if temp > 9 {\n smallest[i] = 9;\n temp -= 9;\n } else {\n smallest[i] = temp - 1;\n smallest[0] += 1;\n break;\n }\n }\n\n let mut flag = false;\n for i in 0..m {\n if smallest[i] != 0 || flag {\n flag = true;\n print!(\"{}\", smallest[i]);\n } \n }\n if !flag {\n print!(\"0\");\n }\n print!(\" \");\n\n flag = false;\n for i in 0..m {\n if largest[i] != 0 || flag {\n flag = true;\n print!(\"{}\", largest[i]);\n }\n }\n if !flag {\n print!(\"0\");\n }\n } else {\n println!(\"-1 -1\");\n }\n}", "lang_cluster": "Rust", "tags": ["greedy", "dp", "implementation"], "code_uid": "d6151f0b18d722ffcc23b2e4d26f3788", "src_uid": "75d062cece5a2402920d6706c655cad7", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::collections::HashMap;\n\nfn main() {\n let mut s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let n : i64 = s.trim().parse().unwrap();\n s = String::new();\n std::io::stdin().read_line(&mut s).unwrap();\n let m : i64 = s.trim().parse().unwrap();\n let mut count = 0;\n let mut a = n;\n let mut ispower = true;\n let mut log = 0;\n let mut dp = HashMap::new();\n dp.insert(1,0);\n loop {\n if (m%a!=0) {\n ispower = false;\n break;\n }\n \n count+=1;\n if (m/a().unwrap()\n }).collect::>();\n\n if vec[0] > vec[1] + vec[2] {\n println!(\"+\");\n } else if vec[0] + vec[2] < vec[1] {\n println!(\"-\");\n } else if vec[0] == vec[1] && vec[2] == 0 {\n println!(\"0\");\n } else {\n println!(\"?\");\n }\n}", "lang_cluster": "Rust", "tags": ["greedy"], "code_uid": "5d51ca5c3f7b890de8b4acf9c2e8a084", "src_uid": "66398694a4a142b4a4e709d059aca0fa", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "fn main() {\r\n #![allow(unused_imports, unused_macros)]\r\n prepare_io!(_in_buf, scanner, _out);\r\n macro_rules ! print { ($ ($ arg : tt) *) => (:: std :: write ! (_out , $ ($ arg) *) . expect (\"io error\")) }\r\n macro_rules ! println { ($ ($ arg : tt) *) => (:: std :: writeln ! (_out , $ ($ arg) *) . expect (\"io error\")) }\r\n scan!(scanner, n);\r\n let pt = PrimeTable::new(n as _);\r\n let mut ans = M::zero();\r\n let mut acc = M::zero();\r\n for i in 1..=n {\r\n let c = pt.count_divisors(i as _);\r\n ans = acc + M::from(c);\r\n acc += ans;\r\n }\r\n println!(\"{}\", ans);\r\n}\r\npub type M = mint_basic::MInt998244353;\r\n#[macro_export]\r\nmacro_rules! prepare_io {\r\n ($ in_buf : ident , $ scanner : ident , $ out : ident) => {\r\n use std::io::{stdout, BufWriter, Write as _};\r\n let $in_buf = read_stdin_all_unchecked();\r\n let mut $scanner = Scanner::new(&$in_buf);\r\n let $out = stdout();\r\n let mut $out = BufWriter::new($out.lock());\r\n };\r\n}\r\npub fn echo(\r\n mut writer: impl std::io::Write,\r\n iter: impl IntoIterator,\r\n sep: impl std::fmt::Display,\r\n) -> std::io::Result<()> {\r\n let mut iter = iter.into_iter();\r\n if let Some(item) = iter.next() {\r\n write!(writer, \"{}\", item)?;\r\n }\r\n for item in iter {\r\n write!(writer, \"{}{}\", sep, item)?;\r\n }\r\n writeln!(writer)\r\n}\r\npub fn read_stdin_all_unchecked() -> String {\r\n use std::io::Read as _;\r\n let mut buf = Vec::new();\r\n std::io::stdin().read_to_end(&mut buf).expect(\"io error\");\r\n unsafe { String::from_utf8_unchecked(buf) }\r\n}\r\npub fn read_stdin_line() -> String {\r\n let mut s = String::new();\r\n std::io::stdin().read_line(&mut s).expect(\"io error\");\r\n s\r\n}\r\npub use scanner_impls::{IterScan, MarkedIterScan, Scanner};\r\nmod scanner_impls {\r\n pub trait IterScan: Sized {\r\n type Output;\r\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option;\r\n }\r\n pub trait MarkedIterScan: Sized {\r\n type Output;\r\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option;\r\n }\r\n #[derive(Clone, Debug)]\r\n pub struct Scanner<'a> {\r\n iter: std::str::SplitAsciiWhitespace<'a>,\r\n }\r\n impl<'a> Scanner<'a> {\r\n #[inline]\r\n pub fn new(s: &'a str) -> Self {\r\n let iter = s.split_ascii_whitespace();\r\n Self { iter }\r\n }\r\n #[inline]\r\n pub fn scan(&mut self) -> ::Output\r\n where\r\n T: IterScan,\r\n {\r\n ::scan(&mut self.iter).expect(\"scan error\")\r\n }\r\n #[inline]\r\n pub fn mscan(&mut self, marker: T) -> ::Output\r\n where\r\n T: MarkedIterScan,\r\n {\r\n marker.mscan(&mut self.iter).expect(\"scan error\")\r\n }\r\n #[inline]\r\n pub fn scan_vec(&mut self, size: usize) -> Vec<::Output>\r\n where\r\n T: IterScan,\r\n {\r\n (0..size)\r\n .map(|_| ::scan(&mut self.iter).expect(\"scan error\"))\r\n .collect()\r\n }\r\n #[inline]\r\n pub fn iter<'b, T>(&'b mut self) -> ScannerIter<'a, 'b, T>\r\n where\r\n T: IterScan,\r\n {\r\n ScannerIter {\r\n inner: self,\r\n _marker: std::marker::PhantomData,\r\n }\r\n }\r\n }\r\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 () } }) * } ; }\r\n iter_scan_impls ! (char u8 u16 u32 u64 usize i8 i16 i32 i64 isize f32 f64 u128 i128 String);\r\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) ?,) *)) } } } ; }\r\n iter_scan_tuple_impl!();\r\n iter_scan_tuple_impl!(A);\r\n iter_scan_tuple_impl ! (A B);\r\n iter_scan_tuple_impl ! (A B C);\r\n iter_scan_tuple_impl ! (A B C D);\r\n iter_scan_tuple_impl ! (A B C D E);\r\n iter_scan_tuple_impl ! (A B C D E F);\r\n iter_scan_tuple_impl ! (A B C D E F G);\r\n iter_scan_tuple_impl ! (A B C D E F G H);\r\n iter_scan_tuple_impl ! (A B C D E F G H I);\r\n iter_scan_tuple_impl ! (A B C D E F G H I J);\r\n iter_scan_tuple_impl ! (A B C D E F G H I J K);\r\n pub struct ScannerIter<'a, 'b, T> {\r\n inner: &'b mut Scanner<'a>,\r\n _marker: std::marker::PhantomData T>,\r\n }\r\n impl<'a, 'b, T> Iterator for ScannerIter<'a, 'b, T>\r\n where\r\n T: IterScan,\r\n {\r\n type Item = ::Output;\r\n #[inline]\r\n fn next(&mut self) -> Option {\r\n ::scan(&mut self.inner.iter)\r\n }\r\n }\r\n}\r\npub use marker_impls::{CharWithBase, Chars, CharsWithBase, Collect, SizedCollect, Usize1};\r\nmod marker_impls {\r\n use super::*;\r\n use std::{\r\n iter::{repeat_with, FromIterator},\r\n marker::PhantomData,\r\n };\r\n #[derive(Debug, Copy, Clone)]\r\n pub struct Usize1;\r\n impl IterScan for Usize1 {\r\n type Output = usize;\r\n #[inline]\r\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\r\n ::scan(iter)?.checked_sub(1)\r\n }\r\n }\r\n #[derive(Debug, Copy, Clone)]\r\n pub struct CharWithBase(pub char);\r\n impl MarkedIterScan for CharWithBase {\r\n type Output = usize;\r\n #[inline]\r\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\r\n Some((::scan(iter)? as u8 - self.0 as u8) as usize)\r\n }\r\n }\r\n #[derive(Debug, Copy, Clone)]\r\n pub struct Chars;\r\n impl IterScan for Chars {\r\n type Output = Vec;\r\n #[inline]\r\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\r\n Some(iter.next()?.chars().collect())\r\n }\r\n }\r\n #[derive(Debug, Copy, Clone)]\r\n pub struct CharsWithBase(pub char);\r\n impl MarkedIterScan for CharsWithBase {\r\n type Output = Vec;\r\n #[inline]\r\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\r\n Some(\r\n iter.next()?\r\n .chars()\r\n .map(|c| (c as u8 - self.0 as u8) as usize)\r\n .collect(),\r\n )\r\n }\r\n }\r\n #[derive(Debug, Copy, Clone)]\r\n pub struct Collect::Output>>\r\n where\r\n T: IterScan,\r\n B: FromIterator<::Output>,\r\n {\r\n size: usize,\r\n _marker: PhantomData (T, B)>,\r\n }\r\n impl Collect\r\n where\r\n T: IterScan,\r\n B: FromIterator<::Output>,\r\n {\r\n pub fn new(size: usize) -> Self {\r\n Self {\r\n size,\r\n _marker: PhantomData,\r\n }\r\n }\r\n }\r\n impl MarkedIterScan for Collect\r\n where\r\n T: IterScan,\r\n B: FromIterator<::Output>,\r\n {\r\n type Output = B;\r\n #[inline]\r\n fn mscan<'a, I: Iterator>(self, iter: &mut I) -> Option {\r\n repeat_with(|| ::scan(iter))\r\n .take(self.size)\r\n .collect()\r\n }\r\n }\r\n #[derive(Debug, Copy, Clone)]\r\n pub struct SizedCollect::Output>>\r\n where\r\n T: IterScan,\r\n B: FromIterator<::Output>,\r\n {\r\n _marker: PhantomData (T, B)>,\r\n }\r\n impl IterScan for SizedCollect\r\n where\r\n T: IterScan,\r\n B: FromIterator<::Output>,\r\n {\r\n type Output = B;\r\n #[inline]\r\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\r\n let size = usize::scan(iter)?;\r\n repeat_with(|| ::scan(iter))\r\n .take(size)\r\n .collect()\r\n }\r\n }\r\n}\r\n#[macro_export]\r\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 > () } ; }\r\n#[macro_export]\r\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) *) } ; }\r\npub mod mint_basic {\r\n use super::*;\r\n #[macro_export]\r\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 } }) * } ; }\r\n #[macro_export]\r\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 >;) * } ; }\r\n define_basic_mint32!(\r\n [Modulo998244353, 998_244_353, MInt998244353],\r\n [Modulo1000000007, 1_000_000_007, MInt1000000007],\r\n [Modulo1000000009, 1_000_000_009, MInt1000000009],\r\n [\r\n DynModuloU32,\r\n DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() }),\r\n DynMIntU32\r\n ]\r\n );\r\n thread_local ! (static DYN_MODULUS_U32 : std :: cell :: UnsafeCell < u32 > = std :: cell :: UnsafeCell :: new (1_000_000_007));\r\n impl DynModuloU32 {\r\n pub fn set_mod(m: u32) {\r\n DYN_MODULUS_U32.with(|cell| unsafe { *cell.get() = m })\r\n }\r\n }\r\n thread_local ! (static DYN_MODULUS_U64 : std :: cell :: UnsafeCell < u64 > = std :: cell :: UnsafeCell :: new (1_000_000_007));\r\n define_basic_mintbase!(\r\n DynModuloU64,\r\n DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() }),\r\n u64,\r\n i64,\r\n u128,\r\n [u64, u128, usize],\r\n [i64, i128, isize]\r\n );\r\n impl DynModuloU64 {\r\n pub fn set_mod(m: u64) {\r\n DYN_MODULUS_U64.with(|cell| unsafe { *cell.get() = m })\r\n }\r\n }\r\n pub type DynMIntU64 = MInt;\r\n pub struct Modulo2;\r\n impl MIntBase for Modulo2 {\r\n type Inner = u32;\r\n #[inline]\r\n fn get_mod() -> Self::Inner {\r\n 2\r\n }\r\n #[inline]\r\n fn mod_zero() -> Self::Inner {\r\n 0\r\n }\r\n #[inline]\r\n fn mod_one() -> Self::Inner {\r\n 1\r\n }\r\n #[inline]\r\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner {\r\n x ^ y\r\n }\r\n #[inline]\r\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner {\r\n x ^ y\r\n }\r\n #[inline]\r\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner {\r\n x | y\r\n }\r\n #[inline]\r\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner {\r\n assert_ne!(y, 0);\r\n x\r\n }\r\n #[inline]\r\n fn mod_neg(x: Self::Inner) -> Self::Inner {\r\n x\r\n }\r\n #[inline]\r\n fn mod_inv(x: Self::Inner) -> Self::Inner {\r\n assert_ne!(x, 0);\r\n x\r\n }\r\n #[inline]\r\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\r\n if y == 0 {\r\n 1\r\n } else {\r\n x\r\n }\r\n }\r\n }\r\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 } }) * } ; }\r\n impl_to_mint_base_for_modulo2!(\r\n Modulo2,\r\n u32,\r\n [u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize]\r\n );\r\n pub type MInt2 = MInt;\r\n}\r\n#[repr(transparent)]\r\npub struct MInt\r\nwhere\r\n M: MIntBase,\r\n{\r\n x: M::Inner,\r\n _marker: std::marker::PhantomData M>,\r\n}\r\npub trait MIntBase {\r\n type Inner: Sized + Copy + Eq + std::fmt::Debug + std::hash::Hash;\r\n fn get_mod() -> Self::Inner;\r\n fn mod_zero() -> Self::Inner;\r\n fn mod_one() -> Self::Inner;\r\n fn mod_add(x: Self::Inner, y: Self::Inner) -> Self::Inner;\r\n fn mod_sub(x: Self::Inner, y: Self::Inner) -> Self::Inner;\r\n fn mod_mul(x: Self::Inner, y: Self::Inner) -> Self::Inner;\r\n fn mod_div(x: Self::Inner, y: Self::Inner) -> Self::Inner;\r\n fn mod_neg(x: Self::Inner) -> Self::Inner;\r\n fn mod_inv(x: Self::Inner) -> Self::Inner;\r\n fn mod_pow(x: Self::Inner, y: usize) -> Self::Inner {\r\n let (mut x, mut y, mut z) = (x, y, Self::mod_one());\r\n while y > 0 {\r\n if y & 1 == 1 {\r\n z = Self::mod_mul(z, x);\r\n }\r\n x = Self::mod_mul(x, x);\r\n y >>= 1;\r\n }\r\n z\r\n }\r\n}\r\npub trait MIntConvert::Inner>: MIntBase {\r\n fn from(x: T) -> ::Inner;\r\n fn into(x: ::Inner) -> T;\r\n fn mod_into() -> T;\r\n}\r\nmod mint_base {\r\n use super::*;\r\n use std::{\r\n fmt::{self, Debug, Display},\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 };\r\n impl MInt\r\n where\r\n M: MIntConvert,\r\n {\r\n #[inline]\r\n pub fn new(x: M::Inner) -> Self {\r\n Self::new_unchecked(>::from(x))\r\n }\r\n #[inline]\r\n pub fn inner(self) -> M::Inner {\r\n >::into(self.x)\r\n }\r\n }\r\n impl MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n pub fn new_unchecked(x: M::Inner) -> Self {\r\n Self {\r\n x,\r\n _marker: PhantomData,\r\n }\r\n }\r\n #[inline]\r\n pub fn get_mod() -> M::Inner {\r\n M::get_mod()\r\n }\r\n #[inline]\r\n pub fn pow(self, y: usize) -> Self {\r\n Self::new_unchecked(M::mod_pow(self.x, y))\r\n }\r\n #[inline]\r\n pub fn inv(self) -> Self {\r\n Self::new_unchecked(M::mod_inv(self.x))\r\n }\r\n }\r\n impl Clone for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn clone(&self) -> Self {\r\n Self {\r\n x: Clone::clone(&self.x),\r\n _marker: PhantomData,\r\n }\r\n }\r\n }\r\n impl Copy for MInt where M: MIntBase {}\r\n impl Debug for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\r\n Debug::fmt(&self.x, f)\r\n }\r\n }\r\n impl Default for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn default() -> Self {\r\n ::zero()\r\n }\r\n }\r\n impl PartialEq for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn eq(&self, other: &Self) -> bool {\r\n PartialEq::eq(&self.x, &other.x)\r\n }\r\n }\r\n impl Eq for MInt where M: MIntBase {}\r\n impl Hash for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn hash(&self, state: &mut H) {\r\n Hash::hash(&self.x, state)\r\n }\r\n }\r\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) } }) * } ; }\r\n impl_mint_from!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);\r\n impl Zero for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn zero() -> Self {\r\n Self::new_unchecked(M::mod_zero())\r\n }\r\n }\r\n impl One for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn one() -> Self {\r\n Self::new_unchecked(M::mod_one())\r\n }\r\n }\r\n impl Add for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = Self;\r\n #[inline]\r\n fn add(self, rhs: Self) -> Self::Output {\r\n Self::new_unchecked(M::mod_add(self.x, rhs.x))\r\n }\r\n }\r\n impl Sub for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = Self;\r\n #[inline]\r\n fn sub(self, rhs: Self) -> Self::Output {\r\n Self::new_unchecked(M::mod_sub(self.x, rhs.x))\r\n }\r\n }\r\n impl Mul for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = Self;\r\n #[inline]\r\n fn mul(self, rhs: Self) -> Self::Output {\r\n Self::new_unchecked(M::mod_mul(self.x, rhs.x))\r\n }\r\n }\r\n impl Div for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = Self;\r\n #[inline]\r\n fn div(self, rhs: Self) -> Self::Output {\r\n Self::new_unchecked(M::mod_div(self.x, rhs.x))\r\n }\r\n }\r\n impl Neg for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = Self;\r\n #[inline]\r\n fn neg(self) -> Self::Output {\r\n Self::new_unchecked(M::mod_neg(self.x))\r\n }\r\n }\r\n impl Sum for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn sum>(iter: I) -> Self {\r\n iter.fold(::zero(), Add::add)\r\n }\r\n }\r\n impl Product for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn product>(iter: I) -> Self {\r\n iter.fold(::one(), Mul::mul)\r\n }\r\n }\r\n impl<'a, M: 'a> Sum<&'a MInt> for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn sum>(iter: I) -> Self {\r\n iter.fold(::zero(), Add::add)\r\n }\r\n }\r\n impl<'a, M: 'a> Product<&'a MInt> for MInt\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn product>(iter: I) -> Self {\r\n iter.fold(::one(), Mul::mul)\r\n }\r\n }\r\n impl Display for MInt\r\n where\r\n M: MIntConvert,\r\n M::Inner: Display,\r\n {\r\n fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {\r\n write!(f, \"{}\", self.inner())\r\n }\r\n }\r\n impl FromStr for MInt\r\n where\r\n M: MIntConvert,\r\n M::Inner: FromStr,\r\n {\r\n type Err = ::Err;\r\n #[inline]\r\n fn from_str(s: &str) -> Result {\r\n s.parse::().map(Self::new)\r\n }\r\n }\r\n impl IterScan for MInt\r\n where\r\n M: MIntConvert,\r\n M::Inner: FromStr,\r\n {\r\n type Output = Self;\r\n #[inline]\r\n fn scan<'a, I: Iterator>(iter: &mut I) -> Option {\r\n iter.next()?.parse::>().ok()\r\n }\r\n }\r\n macro_rules! impl_mint_ref_binop {\r\n ($ imp : ident , $ method : ident , $ t : ty) => {\r\n impl $imp<$t> for &$t\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = <$t as $imp<$t>>::Output;\r\n #[inline]\r\n fn $method(self, other: $t) -> <$t as $imp<$t>>::Output {\r\n $imp::$method(*self, other)\r\n }\r\n }\r\n impl $imp<&$t> for $t\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = <$t as $imp<$t>>::Output;\r\n #[inline]\r\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\r\n $imp::$method(self, *other)\r\n }\r\n }\r\n impl $imp<&$t> for &$t\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = <$t as $imp<$t>>::Output;\r\n #[inline]\r\n fn $method(self, other: &$t) -> <$t as $imp<$t>>::Output {\r\n $imp::$method(*self, *other)\r\n }\r\n }\r\n };\r\n }\r\n impl_mint_ref_binop!(Add, add, MInt);\r\n impl_mint_ref_binop!(Sub, sub, MInt);\r\n impl_mint_ref_binop!(Mul, mul, MInt);\r\n impl_mint_ref_binop!(Div, div, MInt);\r\n macro_rules! impl_mint_ref_unop {\r\n ($ imp : ident , $ method : ident , $ t : ty) => {\r\n impl $imp for &$t\r\n where\r\n M: MIntBase,\r\n {\r\n type Output = <$t as $imp>::Output;\r\n #[inline]\r\n fn $method(self) -> <$t as $imp>::Output {\r\n $imp::$method(*self)\r\n }\r\n }\r\n };\r\n }\r\n impl_mint_ref_unop!(Neg, neg, MInt);\r\n macro_rules! impl_mint_ref_op_assign {\r\n ($ imp : ident , $ method : ident , $ t : ty , $ fromimp : ident , $ frommethod : ident) => {\r\n impl $imp<$t> for $t\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn $method(&mut self, rhs: $t) {\r\n *self = $fromimp::$frommethod(*self, rhs);\r\n }\r\n }\r\n impl $imp<&$t> for $t\r\n where\r\n M: MIntBase,\r\n {\r\n #[inline]\r\n fn $method(&mut self, other: &$t) {\r\n $imp::$method(self, *other);\r\n }\r\n }\r\n };\r\n }\r\n impl_mint_ref_op_assign!(AddAssign, add_assign, MInt, Add, add);\r\n impl_mint_ref_op_assign!(SubAssign, sub_assign, MInt, Sub, sub);\r\n impl_mint_ref_op_assign!(MulAssign, mul_assign, MInt, Mul, mul);\r\n impl_mint_ref_op_assign!(DivAssign, div_assign, MInt, Div, div);\r\n}\r\npub trait Zero: Sized {\r\n fn zero() -> Self;\r\n #[inline]\r\n fn is_zero(&self) -> bool\r\n where\r\n Self: PartialEq,\r\n {\r\n self == &Self::zero()\r\n }\r\n #[inline]\r\n fn set_zero(&mut self) {\r\n *self = Self::zero();\r\n }\r\n}\r\npub trait One: Sized {\r\n fn one() -> Self;\r\n #[inline]\r\n fn is_one(&self) -> bool\r\n where\r\n Self: PartialEq,\r\n {\r\n self == &Self::one()\r\n }\r\n #[inline]\r\n fn set_one(&mut self) {\r\n *self = Self::one();\r\n }\r\n}\r\nmacro_rules ! zero_one_impls { ($ ({ $ Trait : ident $ method : ident $ ($ t : ty) *, $ e : expr }) *) => { $ ($ (impl $ Trait for $ t { fn $ method () -> Self { $ e } }) *) * } ; }\r\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. });\r\n#[derive(Clone, Debug)]\r\npub struct PrimeTable {\r\n table: Vec,\r\n}\r\nimpl PrimeTable {\r\n pub fn new(max_n: u32) -> Self {\r\n let mut table = vec![1; (max_n as usize + 1) / 2];\r\n table[0] = 0;\r\n for i in (3..).step_by(2) {\r\n let i2 = i * i;\r\n if i2 > max_n {\r\n break;\r\n }\r\n if table[i as usize >> 1] == 1 {\r\n for j in (i2..=max_n).step_by(i as usize * 2) {\r\n if table[j as usize >> 1] == 1 {\r\n table[j as usize >> 1] = i;\r\n }\r\n }\r\n }\r\n }\r\n PrimeTable { table }\r\n }\r\n pub fn is_prime(&self, n: u32) -> bool {\r\n n == 2 || n % 2 == 1 && self.table[n as usize >> 1] == 1\r\n }\r\n pub fn for_each(&self, mut n: u32, mut f: F)\r\n where\r\n F: FnMut(u32, u32),\r\n {\r\n let k = n.trailing_zeros();\r\n if k > 0 {\r\n f(2, k);\r\n }\r\n n >>= k;\r\n while self.table[n as usize >> 1] > 1 {\r\n let p = self.table[n as usize >> 1];\r\n let mut cnt = 1;\r\n n /= p;\r\n while self.table[n as usize >> 1] == p {\r\n n /= p;\r\n cnt += 1;\r\n }\r\n if n == p {\r\n cnt += 1;\r\n n /= p;\r\n }\r\n f(p, cnt);\r\n }\r\n if n > 1 {\r\n f(n, 1);\r\n }\r\n }\r\n pub fn prime_factors(&self, n: u32) -> Vec<(u32, u32)> {\r\n let mut factors = vec![];\r\n self.for_each(n, |p, c| factors.push((p, c)));\r\n factors\r\n }\r\n pub fn count_divisors(&self, n: u32) -> u32 {\r\n let mut divisor_cnt = 1;\r\n self.for_each(n, |_, cnt| divisor_cnt *= cnt + 1);\r\n divisor_cnt\r\n }\r\n}\r\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "c46a5bdfd631893db56227845780ceb6", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "mod cp {\n use std::io::prelude::*;\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 return content;\n }\n\n pub struct Parser<'a> {\n tokens: std::str::SplitWhitespace<'a>,\n }\n\n impl<'a> Parser<'a> {\n pub fn new(text: &'a str) -> Self {\n Self {\n tokens: text.split_whitespace(),\n }\n }\n\n pub fn read_or_eof(&mut self) -> Option {\n self.next().map(|s| match s.parse() {\n Ok(x) => x,\n Err(_) => panic!(\"cannot parse {:?}\", s),\n })\n }\n\n pub fn read(&mut self) -> T {\n self.read_or_eof::().expect(\"unexpected end-of-file\")\n }\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\n #[macro_export]\n macro_rules! take {\n ($p: expr, $n: expr) => {\n $p.by_ref().take($n).map(|x| x.parse().unwrap())\n };\n ($p: expr, $n: expr, $t: ty) => {\n $p.by_ref().take($n).map(|x| x.parse::<$t>().unwrap())\n };\n }\n\n #[macro_export]\n macro_rules! take_all {\n ($p: expr) => {\n $p.by_ref().map(|x| x.parse().unwrap())\n };\n ($p: expr, $t: ty) => {\n $p.by_ref().map(|x| x.parse::<$t>().unwrap())\n };\n }\n}\n\nuse cp::*;\n\nfn main() {\n let content = stdin_to_string();\n let mut inp = Parser::new(&content);\n\n let mut nd = vec![0i32; 1000001];\n for i in 1..=1000000 {\n for j in (i..=1000000).step_by(i) {\n nd[j] += 1;\n }\n }\n\n let mut f = vec![0i32; 2000001];\n let mut sum = 0i64;\n for i in (2..=2000000).step_by(2) {\n let t = nd[i / 2] as i64 + sum;\n f[i] = (t % 998244353) as i32;\n sum += f[i] as i64;\n }\n let n: usize = inp.read();\n println!(\"{}\", f[n * 2]);\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics"], "code_uid": "6353f24b1047003b162ab40617f399fd", "src_uid": "09be46206a151c237dc9912df7e0f057", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "\nuse std::io;\nuse std::io::BufRead;\n\nconst MAX_SCORE: usize = 600;\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().ok().unwrap();\n\n let mut awarded = [false; MAX_SCORE + 1];\n let mut count = 0;\n input_string.split(\" \").map(|x| x.parse::().unwrap()).filter(|x| *x > 0).for_each(|x| {\n let index = x as usize;\n if !awarded[index] {\n awarded[index] = true;\n count += 1;\n }\n });\n\n println!(\"{}\", count);\n}\n", "lang_cluster": "Rust", "tags": ["sortings", "implementation"], "code_uid": "8d5de97b00d037118594c07d8a977580", "src_uid": "3b520c15ea9a11b16129da30dcfb5161", "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\n\nfn main() {\n let n: i32 = read_line().parse().unwrap();\n let mut vs = read_line_vec();\n\n vs.sort();\n vs.dedup();\n\n for i in 2..vs.len() {\n let pprev = vs[i-2];\n let prev = vs[i-1];\n let me = vs[i];\n\n if me == prev + 1 && pprev + 1 == prev {\n println!(\"YES\");\n return;\n }\n }\n\n println!(\"NO\");\n \n}", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "implementation"], "code_uid": "0870cbc0be10d469dda7b834596eb800", "src_uid": "d6c876a84c7b92141710be5d76536eab", "difficulty": 900.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, 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 a: [usize; n],\n }\n let mut a = a;\n a.sort();\n a.dedup();\n let n = a.len();\n let mut ans = \"NO\";\n for i in 2..n {\n let s = a[i - 2];\n if a[(i - 2)..=i] == [s, s + 1, s + 2] {\n ans = \"YES\";\n }\n }\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "sortings", "implementation"], "code_uid": "848d437ea3c905da4e84e03aa6e9ed67", "src_uid": "d6c876a84c7b92141710be5d76536eab", "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(\"err\");\n let mut n:i64 = buffer.trim().parse().unwrap();\n let mut d = 0;\n for i in 2..=(n as f64).sqrt() as i64 + 1{\n if n % i == 0 {\n d = i; n -= d;\n break;\n }\n }\n println!(\"{}\", \n if d != 0 {\n n/2+1\n } else {\n 1\n }\n );\n}", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "fa9da5ab09ad479d7aa5c3d143b39437", "src_uid": "a1e80ddd97026835a84f91bac8eb21e6", "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\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: i64 = scan.token();\n let m: i64 = scan.token();\n let mut ans: i64 = 0;\n for x in 1..=n {\n // How many multiples of 5 minus x are there in [1, m]?\n ans += (m + x) / 5 - (x + 5) / 5 + 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", "constructive algorithms", "number theory"], "code_uid": "ef83824194c7313bc6b831bd831573dd", "src_uid": "df0879635b59e141c839d9599abd77d2", "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 ($t:ty) => (get().parse::<$t>().unwrap());\n () => (get!(i64));\n }\n \n let n = get!();\n let k = get!();\n let mut ans = 0;\n if n >= k {\n ans = (k - 1) / 2;\n } else if k <= n + (n - 1) {\n let x = k - n;\n ans = (n - x + 1) / 2;\n }\n \n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "f0b5619c5c015675636922ced9f7adfa", "src_uid": "98624ab2fcd2a50a75788a29e04999ad", "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 let a = input.bs().to_vec();\n let b = input.bs().to_vec();\n let mut i = 0;\n for c in b {\n if c == a[i] {\n i += 1;\n }\n }\n println!(\"{}\", i + 1);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "b9e8a4f850acd2ba746e1d912a0f700a", "src_uid": "f5a907d6d35390b1fb11c8ce247d0252", "difficulty": 800.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 main() {\n let stdin = stdin();\n let mut s = stdin.lock();\n let n = scan!(s, usize);\n let max_n = 1000000;\n let mut squares = vec![2*max_n; 2001];\n squares[0] = 0;\n\n let mut i = 1;\n while i*i <= max_n {\n squares[i] = i*i;\n i += 1;\n }\n\n while squares[i] > n {\n i -= 1;\n }\n\n let mut result = 4*i;\n let diff = n - squares[i];\n if diff > 0 {\n if diff > i {\n result += 4;\n } else {\n result += 2; \n }\n }\n \n\n println!(\"{}\", result);\n}", "lang_cluster": "Rust", "tags": ["brute force", "math", "geometry"], "code_uid": "4426c9351c1c967db27034b6ae7f8074", "src_uid": "414cc57550e31d98c1a6a56be6722a12", "difficulty": 1000.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 let now_time = read_string().replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n let sleep_time = read_string().replace(\"\\n\", \"\").replace(\"\\r\", \"\");\n let now_vec: Vec<&str> = now_time.split(\":\").collect();\n let sleep_vec: Vec<&str> = sleep_time.split(\":\").collect();\n let fix = if now_vec[1].parse::().unwrap() < sleep_vec[1].parse::().unwrap() {1} else {0};\n let mut hours = now_vec[0].parse::().unwrap() - (sleep_vec[0].parse::().unwrap()+fix);\n let mut minutes = now_vec[1].parse::().unwrap() - sleep_vec[1].parse::().unwrap();\n if hours < 0{\n hours = 24+hours;\n }\n if minutes < 0{\n minutes = 60+minutes;\n }\n println!(\"{}{}:{}{}\", if hours<10 {\"0\"} else {\"\"}, hours, if minutes<10 {\"0\"} else {\"\"},minutes);\n }", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7e93c786438bacb45e49587c93036385", "src_uid": "595c4a628c261104c8eedad767e85775", "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 get_divisors(n: u64) -> 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 upper_bound(arr: &[u64], target: u64) -> 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 solve(scan: &mut Scanner, out: &mut W) {\n let a: u64 = scan.token();\n let b: u64 = scan.token();\n if a == 0 {\n if b == 0 {\n writeln!(out, \"infinity\").ok();\n } else {\n writeln!(out, \"0\").ok();\n }\n } else {\n if a < b {\n writeln!(out, \"0\").ok();\n } else if a == b {\n writeln!(out, \"infinity\").ok();\n } else {\n // Solve the modular equation a ≡ b (mod x).\n // a = x * k + b, where k is some integer.\n // (a - b) = x * k -> x is a divisor of (a - b)\n // Count divisors of (a - b) such that x > b.\n let divisors = get_divisors(a - b);\n let ub = upper_bound(&divisors, b);\n let ans = divisors.len() - ub;\n writeln!(out, \"{}\", ans).ok();\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 solve(&mut scan, &mut out);\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "b0ed9ad773990d3fd730f4dfce32294a", "src_uid": "6e0715f9239787e085b294139abb2475", "difficulty": 1600.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse io::BufRead;\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 x1: i64 = input.next().unwrap().parse().unwrap();\n let y1: i64 = input.next().unwrap().parse().unwrap();\n let x2: i64 = input.next().unwrap().parse().unwrap();\n let y2: i64 = input.next().unwrap().parse().unwrap();\n let x: i64 = input.next().unwrap().parse().unwrap();\n let y: i64 = input.next().unwrap().parse().unwrap();\n\n if ((x2 - x1) % x != 0) || ((y2 - y1) % y != 0) {\n println!(\"NO\");\n return;\n }\n\n let dx = (x2 - x1) / x;\n let dy = (y2 - y1) / y;\n\n if (dx + dy) % 2 == 0 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation", "number theory"], "code_uid": "cff36b28765ffe32b5a8114c2786655e", "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 line\n}\n\nfn solve(tag: String, pat: String) -> bool {\n\n let mut tag_stm = tag.chars();\n\n for pat_chr in pat.chars() {\n loop {\n match tag_stm.next() {\n Some(tag_chr) => {\n if tag_chr == pat_chr {\n break;\n }\n }\n None => return false\n }\n }\n }\n true\n}\n\nfn main() {\n if solve(read_line().trim().to_string(), \"hello\".to_string()) {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "ea664408f154e954bd286fa8d114585e", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "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 (mut f1, mut f2, mut f3, mut f4, mut f5) = (false, false, false, false, false);\n for c in s.chars() {\n if c == 'h' && !f1 {\n f1 = true;\n } else if c == 'e' && f1 && !f2 {\n f2 = true;\n } else if c == 'l' && f2 && !f3 {\n f3 = true;\n } else if c == 'l' && f3 && !f4 {\n f4 = true;\n } else if c == 'o' && f4 && !f5 {\n f5 = true;\n }\n }\n if f5 {\n println!(\"YES\");\n } else {\n println!(\"NO\");\n }\n}", "lang_cluster": "Rust", "tags": ["greedy", "strings"], "code_uid": "57742ce36f6f704231f63c408939fd6d", "src_uid": "c5d19dc8f2478ee8d9cba8cc2e4cd838", "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(&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 input: Vec = scan.next::().chars().collect();\n let mut changes = 0;\n for i in 0..(input.len() / 2) {\n if input[i] != input[input.len() - i - 1] {\n changes += 1;\n if changes > 1 {\n println!(\"NO\");\n return;\n }\n }\n }\n println!(\n \"{}\",\n if changes == 1 || changes == 0 && input.len() % 2 == 1 {\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": ["brute force", "strings", "constructive algorithms"], "code_uid": "22dd02e844cf88a029ea7af12505366d", "src_uid": "fe74313abcf381f6c5b7b2057adaaa52", "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 = parse_line!(usize);\n let s: Vec = parse_line!(String).bytes().collect();\n let mut counts = std::collections::HashMap::new();\n let mut best = 0;\n let mut result = Vec::new();\n for i in 1..n {\n let cnt = counts.entry(s[i - 1..=i].iter().copied().collect::>()).or_insert(0);\n *cnt += 1;\n if *cnt > best {\n best = *cnt;\n result = s[i - 1..=i].iter().copied().collect::>();\n }\n }\n writeln!(writer, \"{}\", String::from_utf8(result).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": ["strings", "implementation"], "code_uid": "7bfd5f18d34599d9f24772ad4d2ed024", "src_uid": "e78005d4be93dbaa518f3b40cca84ab1", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn read_line() -> String {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n String::from(buffer.trim())\n}\nfn read_number() -> i64 {\n read_line().parse::().unwrap()\n}\nfn read_nums() -> Vec {\n read_line().split(' ').map(|x| x.parse::().unwrap()).collect()\n}\n\nfn main() {\n let mut nums = read_nums();\n nums.sort();\n let least = nums[0];\n let top = nums[1];\n println!(\"{}\", if least >= 3 { least * top - least * top % 2 } else {\n if least == 1 {\n top - [0, 1, 2, 3, 2, 1][(top % 6) as usize]\n } else {\n if top <= 2 {\n 0\n } else if top == 3 || top == 7 {\n least * top - 2\n } else {\n least * top\n }\n }\n });\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "constructive algorithms", "flows", "graph matchings"], "code_uid": "7f17d36a3987674fc3f38a878a3ba94a", "src_uid": "02ce135a4b276d1e9ba6a4ce37f2fe70", "difficulty": 2200.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\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", "bitmasks"], "code_uid": "d8410933498bd3b50de0ff0be9551cc9", "src_uid": "ac2a37ff4c7e89a345b189e4891bbf56", "difficulty": 2100.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!(usize, i32);\n let a: Vec = read_line!(Vec);\n let mut cur = 0;\n let mut b = 0;\n let mut m = -1;\n for i in 0..n {\n cur += a[i];\n b += cmp::min(cur, 8);\n cur -= cmp::min(cur, 8);\n if b >= k {\n m = i as i32 + 1;\n break;\n }\n }\n println!(\"{}\", m);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "f4e2512f82ffe94f4fe4731768456ca5", "src_uid": "24695b6a2aa573e90f0fe661b0c0bd3a", "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! 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 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 = input.u();\n let k = input.i();\n let mut sum1 = 0;\n let mut sum2 = 0;\n for i in 0..n {\n sum1 += input.i();\n let d = sum1.min(8);\n sum1 -= d;\n sum2 += d;\n if sum2 >= k {\n println!(\"{}\", i + 1);\n return;\n }\n }\n println!(\"-1\");\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "e1c90bf316f934a731a97649b246b274", "src_uid": "24695b6a2aa573e90f0fe661b0c0bd3a", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\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 sqrt(x: i32) -> i32 {\n (0..=2000).find(|y| y * y >= x).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 mut rev = false;\n\n let (mut x, mut y) = scan.pair::();\n if x < 0 {\n rev = !rev;\n x = -x;\n }\n if y < 0 {\n rev = !rev;\n y = -y;\n }\n\n let dsq = x*x + y*y;\n\n let d = sqrt(dsq);\n\n if d * d == dsq {\n return answer!(out, \"black\");\n }\n\n answer!(out, match (d & 1 == 1) != rev {\n true => \"black\",\n false => \"white\",\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", "geometry", "constructive algorithms", "implementation"], "code_uid": "84745f51f561bac425db35cc5bf84da0", "src_uid": "8c92aac1bef5822848a136a1328346c6", "difficulty": 1300.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufReader};\nuse std::io::prelude::*;\nuse std::collections::HashMap;\n\nfn insert_dist(dist: i32, c: char, dist_map: &mut HashMap, diff: i32) {\n if dist <= (13 + diff) {\n dist_map.insert(c, (dist - diff).abs());\n } else {\n dist_map.insert(c, 26 + diff - dist);\n }\n}\n\nfn solve(input: &mut dyn Read, output: &mut dyn Write) {\n let mut reader = BufReader::new(input);\n let mut input = String::new();\n let mut dist_a: HashMap = HashMap::new();\n let mut dist_c: HashMap = HashMap::new();\n let mut dist_t: HashMap = HashMap::new();\n let mut dist_g: HashMap = HashMap::new();\n\n for (i, c) in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".chars().enumerate() {\n let dist = i as i32;\n insert_dist(dist, c, &mut dist_a, 0);\n insert_dist(dist, c, &mut dist_c, 2);\n if dist <= 6 {\n dist_t.insert(c, 7 + dist);\n } else {\n dist_t.insert(c, (dist - 19).abs());\n }\n insert_dist(dist, c, &mut dist_g, 6);\n }\n // for c in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".chars() {\n // println!(\"{} {}\", c, dist_t[&c]);\n // }\n \n\n reader.read_line(&mut input).unwrap();\n let n: usize = input.trim().parse().unwrap();\n\n input.clear();\n reader.read_line(&mut input).unwrap();\n let s = input.trim();\n // println!(\"{:?}\", s);\n\n let char_vec: Vec = s.chars().collect();\n let mut min_sum = -1;\n for i in 0..n-3 {\n let sum = dist_a.get(&char_vec[i]).expect(\"has values\") + \n dist_c.get(&char_vec[i + 1]).expect(\"has values\") + \n dist_t.get(&char_vec[i + 2]).expect(\"has values\") + \n dist_g.get(&char_vec[i + 3]).expect(\"has values\");\n\n if min_sum == -1 || sum < min_sum {\n min_sum = sum;\n }\n }\n\n // for c in s.chars() {\n // println!(\"{:?}\", c);\n // }\n\n writeln!(output, \"{}\", min_sum).expect(\"correct output\");\n\n}\n\nfn main() {\n solve(&mut io::stdin(), &mut io::stdout());\n}", "lang_cluster": "Rust", "tags": ["brute force", "strings"], "code_uid": "4fb252210fbd7920bb3068e892144e29", "src_uid": "ee4f88abe4c9fa776abd15c5f3a94543", "difficulty": 1000.0, "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 input = buf\n .split_whitespace()\n .map(|s| s.parse::().unwrap());\n\n // length\n let n = input.next().unwrap();\n // route 1 (+)\n let a = input.next().unwrap();\n let x = input.next().unwrap();\n // route 2 (-)\n let b = input.next().unwrap();\n let y = input.next().unwrap();\n\n println!(\"{}\", match solve(n, a, x, b, y) {\n true => \"YES\",\n false => \"NO\",\n });\n}\n\nfn solve(n: i32, a: i32, x: i32, b: i32, y: i32) -> bool {\n let x = if x < a { x + n } else { x };\n let b = if y > b { b + n } else { b };\n (y .. b + 1).rev().zip(a .. x + 1).any(|(i, j)| i % n == j % n)\n}\n\n#[cfg(test)]\nmod test {\n\n use super::solve;\n #[test]\n fn test1() {\n assert_eq!(solve(5, 1, 4, 3, 2), true);\n }\n #[test]\n fn test2() {\n assert_eq!(solve(10, 2, 1, 9, 10), false);\n }\n #[test]\n fn test3() {\n assert_eq!(solve(82, 9, 11, 15, 79), false);\n }\n #[test]\n fn test4() {\n assert_eq!(solve(47, 15, 45, 28, 38), true);\n }\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "b12a39d101cb7820194fa1f3f7392595", "src_uid": "5b889751f82c9f32f223cdee0c0095e4", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_imports)]\n\nuse std::cmp::*;\nuse std::collections::*;\nuse std::fmt::Debug;\nuse std::io::{empty, Read};\nuse std::str::FromStr;\n\nfn main() {\n let nn = read_vec::();\n let (n, k) = (nn[0], nn[1]);\n\n let first = min(k - 1, n - k);\n let result = first + 3 * n;\n println!(\"{}\", result);\n}\n\n#[allow(dead_code)]\nconst DIV: i64 = 1_000_000_007;\n#[allow(dead_code)]\nconst N: usize = 200000;\n#[allow(dead_code)]\nconst CHARS: usize = 'z' as usize - 'a' as usize + 1;\n\n#[allow(dead_code)]\nfn print_vec(a: &Vec) {\n for i in 0..a.len() {\n if i != 0 {\n print!(\" \");\n }\n print!(\"{:?}\", a[i]);\n }\n println!();\n}\n\n#[allow(dead_code)]\nfn read_line() -> String {\n let mut s = String::with_capacity(N);\n std::io::stdin().read_line(&mut s).unwrap();\n s\n}\n\n#[allow(dead_code)]\nfn read_vec() -> Vec\n where T::Err: Debug\n{\n return read_line()\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n}\n", "lang_cluster": "Rust", "tags": ["math", "constructive algorithms"], "code_uid": "309def4bb4bd722d50a015821861fd24", "src_uid": "24b02afe8d86314ec5f75a00c72af514", "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 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 c = [0u64; 3];\n for s in scan.next::().chars() {\n match s {\n 'B' => {\n c[0] += 1;\n }\n 'S' => {\n c[1] += 1;\n }\n 'C' => {\n c[2] += 1;\n }\n _ => {}\n }\n }\n let n: Vec = scan.next_n(3);\n let p: Vec = scan.next_n(3);\n let r: u64 = scan.next();\n let mut low = 0u64;\n let mut high = 1000000001000u64;\n while low <= high {\n let middle = (low + high) / 2;\n let mut f = 0u64;\n for i in 0..3 {\n if c[i] * middle > n[i] {\n f += (c[i] * middle - n[i]) * p[i];\n }\n }\n if f <= r {\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n println!(\"{}\", low - 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": ["brute force", "binary search"], "code_uid": "dff2d1bc87daf776e9d6fe50f6a24d1f", "src_uid": "8126a4232188ae7de8e5a7aedea1a97e", "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 vec = input.trim().split_whitespace().map(|item| {\n item.parse::().expect(\"item: parse to i32 failed\")\n }).collect::>();\n\n let (mut width, mut height, mut rings) = (vec[0], vec[1], vec[2]);\n\n let mut amount = i32::default();\n\n while rings > 0 {\n amount += (width + height) * 2 - 4;\n width -= 4;\n height -= 4;\n rings -= 1;\n }\n\n println!(\"{}\", amount);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "d3234ea3d43efc5efa74949be5ed543e", "src_uid": "2c98d59917337cb321d76f72a1b3c057", "difficulty": 800.0, "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 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// ---------- 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: 置いてok\n // 1: おいたらダメ\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];\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["matrices", "dp"], "code_uid": "2c3fae2bc3412787f064d9bd548b63d6", "src_uid": "a4bda63b95dc14185c47a08652fe41bd", "difficulty": 2700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//#[derive(Debug)]\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}\nuse std::collections::HashSet;\n\nfn main() {\n let mut scan = Scanner::default();\n let out = &mut BufWriter::new(stdout());\n\n let mut set = HashSet::new();\n let mut n=scan.next::();\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 writeln!(out,\"{}\",set.len()).ok();\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "8c199dcd6e1ec0e800b76598e041e49e", "src_uid": "055fbbde4b9ffd4473e6e716da6da899", "difficulty": 1100.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 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 u32);\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": "7d70cea3e90e93029d577bd880bda245", "src_uid": "698da80c7d24252b57cca4e4f0ca7031", "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 _main() {\n let mut scan = Scan::new();\n let r: i64 = scan.next();\n let x: i64 = scan.next();\n let y: i64 = scan.next();\n let xp: i64 = scan.next();\n let yp: i64 = scan.next();\n let d = (((x - xp) * (x - xp) + (y - yp) * (y - yp)) as f64).sqrt();\n let mut steps = d as i64 / (2 * r);\n if ((steps * 2 * r) as f64) < d {\n steps += 1;\n }\n println!(\"{}\", steps);\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", "geometry"], "code_uid": "3278ea7e526475c1a306169d77ced6ff", "src_uid": "698da80c7d24252b57cca4e4f0ca7031", "difficulty": 1400.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 max_minutes(a : isize, b : isize) -> usize {\n let mut num_minutes = 0;\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 if (m_a == 1) && (m_b == 1) {\n break;\n } else {\n num_minutes = num_minutes + 1;\n if m_a <= m_b {\n m_a = m_a + 1;\n m_b = m_b - 2;\n } else {\n m_a = m_a - 2;\n m_b = m_b + 1;\n }\n }\n }\n num_minutes\n}\n\nfn main() {\n let stdin = io::stdin();\n let mut a_b = vec![];\n read_ts(&stdin, &mut a_b);\n let a = a_b[0];\n let b = a_b[1];\n let result = max_minutes(a, b);\n println!(\"{}\", result);\n}", "lang_cluster": "Rust", "tags": ["math", "greedy", "dp", "implementation"], "code_uid": "8e7d9538f32e9cc26ec4b9684e74d3e5", "src_uid": "ba0f9f5f0ad4786b9274c829be587961", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// fn count_ways(n: usize) -> u32 {\n// let mut dynamic = vec![vec![0u32; 4]; n + 1];\n// dynamic[1] = vec![1u32; 4];\n// *dynamic[1].last_mut().unwrap() = 0;\n \n// for step_count in 2..=n {\n// for vertex_id in 0..=3 {\n// for neighbor_id in (0..=3).filter(|&x| x != vertex_id) {\n// dynamic[step_count][vertex_id] += dynamic[step_count - 1][neighbor_id];\n// dynamic[step_count][vertex_id] %= 1000000007\n// }\n// }\n// }\n// *dynamic.last().unwrap().last().unwrap()\n// }\n\nfn count_ways(n: usize) -> u64 {\n if n == 1 {\n return 0;\n }\n\n let mut count_for_abc: u64 = 1;\n for step_count in 2..n {\n // dbg!(count_for_abc);\n count_for_abc *= 3;\n if step_count % 2 == 0 {\n count_for_abc -= 1;\n } else {\n count_for_abc += 1;\n }\n count_for_abc %= 1000000007;\n }\n // dbg!(count_for_abc);\n (3 * count_for_abc) % 1000000007\n}\n\n\nfn main() {\n let mut buf = String::new();\n std::io::stdin().read_line(&mut buf).unwrap();\n let n = buf.trim().parse::().unwrap();\n println!(\"{}\", count_ways(n));\n}", "lang_cluster": "Rust", "tags": ["math", "matrices", "dp"], "code_uid": "88c9877ccff30ad867ff38ef01dcc808", "src_uid": "77627cc366a22e38da412c3231ac91a8", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{self, BufRead, Read, Stdin};\nuse std::str::FromStr;\n\nstruct InputUtils {\n stream: Stdin,\n buffer: String,\n}\n\nimpl Default for InputUtils {\n fn default() -> Self {\n return Self {\n stream: io::stdin(),\n buffer: String::new(),\n };\n }\n}\n\nimpl Iterator for InputUtils {\n type Item = String;\n\n fn next(&mut self) -> Option {\n match self.stream.lock().lines().next() {\n Some(line) => Some(line.unwrap().trim().to_string()),\n None => None,\n }\n }\n}\n\nimpl InputUtils {\n fn read(&mut self) -> &str {\n self.buffer.clear();\n self.stream\n .lock()\n .read_to_string(&mut self.buffer)\n .expect(\"Failed to read till EOF\");\n return self.buffer.trim();\n }\n\n fn input(&mut self) -> T\n where\n T: FromStr,\n T::Err: std::fmt::Debug,\n {\n return self\n .into_iter()\n .next()\n .unwrap()\n .parse::()\n .expect(\"Failed to parse line to type\");\n }\n\n fn inputs(&mut self, delimiter: Option<&str>) -> Vec\n where\n T: FromStr,\n T::Err: std::fmt::Debug,\n {\n let line = self.into_iter().next().unwrap();\n let parts = match delimiter {\n Some(delim) => line\n .split(delim)\n .map(|part| part.parse::().expect(\"Failed to parse part\"))\n .collect(),\n None => line\n .split_whitespace()\n .map(|part| part.parse::().expect(\"Failed to parse part\"))\n .collect(),\n };\n return parts;\n }\n}\n\nmacro_rules! print_vec {\n ($x:expr, $y:expr) => {\n println!(\n \"{}\",\n $x.iter()\n .map(|x| x.to_string())\n .collect::>()\n .join($y)\n );\n };\n}\n\nfn main() {\n let mut iu = InputUtils::default();\n let modulo: i64 = 1000000007;\n let n: i32 = iu.input();\n let mut a: i64 = 1;\n let mut an: i64;\n let mut other: i64 = 0;\n let mut othern: i64;\n for _ in 0..n {\n an = other % modulo;\n othern = (((3i64 * a) % modulo) + ((2i64 * other) % modulo)) % modulo;\n a = an;\n other = othern;\n }\n println!(\"{}\", a);\n}\n", "lang_cluster": "Rust", "tags": ["math", "matrices", "dp"], "code_uid": "623e07b70c7eb0913ca61bec4da07a00", "src_uid": "77627cc366a22e38da412c3231ac91a8", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn solve(n :i32, x :i32, numbers :&Vec) -> i32 {\n let mut r = 0;\n for elem in numbers.iter() {\n if elem > &x {\n break;\n } else if elem < &x {\n r = r + 1;\n } else {\n r = r - 1;\n }\n }\n x - r\n}\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).expect(\"io error\");\n let arr: Vec = input.trim_right().split_whitespace().map(|x| {\n let r: i32 = x.parse().expect(\"not a number\");\n r\n }).collect();\n let n = arr[0];\n let x = arr[1];\n input.clear();\n io::stdin().read_line(&mut input).expect(\"io error\");\n let mut numbers: Vec = input.trim_right().split_whitespace().map(|x| {\n let r: i32 = x.parse().expect(\"not a number\");\n r\n }).collect();\n numbers.sort();\n println!(\"{}\", solve(n, x, numbers.as_ref()));\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "implementation"], "code_uid": "14487c6b296494173a2e4687c184a036", "src_uid": "21f579ba807face432a7664091581cd8", "difficulty": 1000.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!(i64));\n }\n \n let n = get!(usize);\n let s = get().as_bytes();\n \n let mut i = 0;\n let mut c = 1;\n let mut ans = vec![];\n while i < n {\n ans.push(s[i]);\n i += c;\n c += 1;\n }\n println!(\"{}\", String::from_utf8(ans).unwrap());\n \n }\n ", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "aa6ee3aa5b147859885aef7d08f340bb", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "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 n: usize,\n s: chars,\n }\n let mut i = 0;\n let mut k = 1;\n let mut res = String::new();\n while i < n {\n res.push(s[i]);\n i += k;\n k += 1;\n }\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": ["implementation"], "code_uid": "a0aed31070db30de63df57b2032361d7", "src_uid": "08e8c0c37b223f6aae01d5609facdeaf", "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 (mut weight, mut height) = readln!(i32, i32);\n let (weight1, height1) = readln!(i32, i32);\n let (weight2, height2) = readln!(i32, i32);\n\n while height > 0 {\n weight += height;\n if height1 == height {\n weight = std::cmp::max(0, weight - weight1);\n } else if height2 == height {\n weight = std::cmp::max(0, weight - weight2);\n }\n height -= 1;\n }\n\n println!(\"{}\", weight);\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "7c00d63b0b309c1b408b605901ad73eb", "src_uid": "084a12eb3a708b43b880734f3ee51374", "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 w: i64,\n h: i64,\n u1: i64,\n d1: i64,\n u2: i64,\n d2: i64,\n }\n let mut ans = w;\n let mut height = h;\n while height > 0 {\n ans += height;\n if d1 == height {\n ans -= u1;\n }\n if d2 == height {\n ans -= u2;\n }\n if ans < 0 {\n ans = 0;\n }\n height -= 1;\n }\n println!(\"{}\", ans);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "09208886fa1885c2b20e28667f40dc11", "src_uid": "084a12eb3a708b43b880734f3ee51374", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut x = String::new();\n io::stdin().read_line(&mut x).expect(\"error\");\n let mut i = x.split_whitespace();\n let a:u64 = i.next().unwrap().parse().expect(\"error\");\n let b:usize = i.next().unwrap().parse().expect(\"error\");\n let mut v:Vec = Vec::new();\n for i in 1..(a as f64).sqrt() as u64+1 {\n if a % i == 0 {\n &v.push(i);\n }\n }\n let len = v.len();\n if b <= len {\n println!(\"{}\", v[b-1]);\n } else if v[len-1]*v[len-1] == a && b <= 2*len-1 {\n println!(\"{}\", a/v[2*len-1-b]);\n } else if v[len-1]*v[len-1] < a && b <= 2*len {\n println!(\"{}\", a/v[2*len-b]);\n } else {\n println!(\"-1\");\n }\n\n}\n", "lang_cluster": "Rust", "tags": ["math", "number theory"], "code_uid": "fb034ff6897d2b3e6edefd1b45226d0e", "src_uid": "6ba39b428a2d47b7d199879185797ffb", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp;\nuse std::error::Error;\nuse std::io::{self, Read};\n\nfn main() -> Result<(), Box> {\n let mut stdin = io::stdin();\n let mut line = String::new();\n stdin.read_line(&mut line)?;\n let num_digits: usize = line.trim().parse()?;\n let mut digits = vec![0u8; num_digits];\n stdin.read_exact(&mut digits)?;\n let num_eights = digits.iter().filter(|c| **c == b'8').count();\n println!(\"{}\", cmp::min(num_digits / 11, num_eights));\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "faf4c7f7197827f42b9e375e216e3e84", "src_uid": "259d01b81bef5536b969247ff2c2d776", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::stdin;\nuse std::isize;\nfn main() {\n let (x,y) = parse_input();\n let abs_x = x.abs();\n let abs_y = y.abs();\n let a = abs_x+abs_y;\n if abs_x == x && abs_y == y{\n print(0,a ,a,0)\n }else if abs_x != x && abs_y !=y{\n print(-a,0,0,-a)\n }else if abs_x !=x {\n print(-a,0,0,a)\n }else{\n print(0,-a,a,0)\n }\n}\nfn parse_input()->(isize,isize){\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n let v:Vec = input.trim().split_whitespace().map(|e| e.parse().unwrap()).collect();\n (v[0],v[1])\n}\nfn print(a:isize,b:isize,c:isize,d:isize){\n println!(\"{} {} {} {}\",a,b,c,d)\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "bf98210e42cb660f98787dac2800466f", "src_uid": "e2f15a9d9593eec2e19be3140a847712", "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(&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 mut arr: Vec = scan.next_n(n);\n arr.sort();\n let mut res: usize = 0;\n for i in (0..n).step_by(2) {\n res += arr[i + 1] - arr[i];\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": ["sortings"], "code_uid": "4c419378032e17b79c1f6c2d913dcd48", "src_uid": "55485fe203a114374f0aae93006278d3", "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 main() {\n let mut input = WordReader::from_stdin();\n let n = input.i();\n let mut sum = 0;\n let mut sol = 0;\n for i in 1.. {\n sum += i * (i+1) / 2;\n if sum <= n {\n sol = i;\n } else {\n break;\n }\n }\n println!(\"{}\", sol);\n}\n\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a551e4618a66d029c2fdc1287d21b14e", "src_uid": "873a12edffc57a127fdfb1c65d43bdb0", "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 = readln!(i32);\n let mut sum = 0;\n let mut cur = 0;\n for i in 1.. {\n cur += i;\n sum += cur;\n if sum > n {\n println!(\"{}\",i-1);\n return;\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "9770ab7eca15ff0112c0f33751c0809b", "src_uid": "873a12edffc57a127fdfb1c65d43bdb0", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::{stdin, Read};\nuse std::str::FromStr;\nuse std::num::ParseIntError;\nuse std::ops::*;\nuse std::fmt;\n\nstatic mut TBL: [[Mnum; 1001]; 1001] = [[Mnum(0); 1001]; 1001];\n\nfn main() {\n let mut ws = Words::new();\n macro_rules! pop {($t:ty) => { ws.next().unwrap().parse::<$t>().unwrap() }; ($($t:ty),+) => { ($(pop!($t),)*) } }\n macro_rules! popn { ($n:expr $(,$t:ty)+) => { (0..$n).map(|_| pop!($($t),* )).collect::>() } }\n let (k, pa, pb) = pop!(usize, Mnum, Mnum);\n\n let d = Mnum(inv(pa.0 + pb.0, MBASE));\n let (a, b) = (pa * d, pb * d);\n let c = pa * Mnum(inv(pb.0, MBASE));\n\n for i in (1..k + 1).rev() {\n for j in (0..k + 1).rev() {\n unsafe {\n TBL[i][j] = if i + j >= k { Mnum(i as i64 + j as i64) + c } else { a * TBL[i + 1][j] + b * TBL[i][j + i] };\n }\n }\n }\n print!(\"{}\", unsafe {TBL[1][0]});\n}\n\nfn inv(x: i64, b: i64) -> i64 {\n let mut s = (0, 1, b, x); // (t, t1, r, r1)\n while s.3 != 0 {\n let q = s.2 / s.3;\n s = (s.1, s.0 - q * s.1, s.3, s.2 - q * s.3)\n }\n\n assert!(s.2 <= 1);\n if s.0 < 0 { s.0 + b } else { s.0 }\n}\n\n\nconst MBASE: i64 = 1000000007;\n#[derive(Clone, Copy, Debug)] struct Mnum(i64);\nimpl Add for Mnum {\n type Output = Mnum;\n fn add(self, rhs: Mnum) -> Mnum { Mnum((self.0 + rhs.0) % MBASE) }\n}\n\nimpl Mul for Mnum {\n type Output = Mnum;\n fn mul(self, rhs: Mnum) -> Mnum { Mnum((self.0 * rhs.0) % MBASE) }\n}\n\nimpl FromStr for Mnum {\n type Err = ParseIntError;\n\n fn from_str(s: &str) -> Result {\n Ok(Mnum(i64::from_str(s)?))\n }\n}\n\nimpl fmt::Display for Mnum {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.0)\n }\n}\n\nfn s32(s: String) -> i32 { s.parse().unwrap() }\n\n\nconst SZ: usize = 4096;\nstruct Words {\n buf: [u8; SZ],\n b: usize,\n e: usize\n}\n\nfn is_ws(c: u8) -> bool {\n match c as char {\n '\\r' | '\\n' | ' ' => true,\n _ => false\n }\n}\n\nimpl Words {\n fn new() -> Words { Words { buf: [0; SZ], b: 0, e: 0 } }\n\n fn len(&self) -> usize { self.e - self.b }\n\n fn fill(&mut self) {\n if self.len() <= 0 {\n self.b = 0;\n self.e = stdin().read(&mut self.buf).unwrap_or(0);\n }\n }\n}\n\nimpl Iterator for Words {\n type Item = String;\n fn next(&mut self) -> Option {\n let mut s = String::new();\n let mut ext = false;\n\n loop {\n self.fill();\n if self.len() <= 0 { return if ext { Some(s) } else { None } }\n\n match (self.b..).zip(self.buf[self.b..self.e].iter()).take_while(|&(_, &c)| is_ws(c)).last() {\n None => {},\n Some((i, _)) => {\n self.b = i + 1;\n if ext { return Some(s) }\n }\n }\n\n match (self.b..).zip(self.buf[self.b..self.e].iter()).take_while(|&(_, &c)| !is_ws(c)).last() {\n None => {},\n Some((i, _)) => {\n s.push_str(match String::from_utf8_lossy(&self.buf[self.b..i + 1]) {\n std::borrow::Cow::Borrowed(s) => s,\n _ => panic!(\"\")\n });\n self.b = i + 1;\n if self.len() <= 0 {\n ext = true;\n } else {\n return Some(s);\n }\n }\n }\n }\n }\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "probabilities"], "code_uid": "f87aceb000ccb0b9637d752031ad7b45", "src_uid": "0dc9f5d75143a2bc744480de859188b4", "difficulty": 2200.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 mut a: [usize; 14] = [0; 14];\n for i in 0..14 {\n a[i] = sc.next::();\n }\n let mut max: u64 = 0;\n for i in 0..14 {\n if a[i] == 0 {\n continue;\n }\n let mut b: [usize; 14] = a.clone();\n b[i] = 0;\n for j in 0..14 {\n b[(i + j + 1) % 14] += a[i] / 14 + (if j < a[i] % 14 { 1 } else { 0 });\n }\n\n let mut sum: u64 = 0;\n for j in 0..14 {\n if b[j] % 2 == 0 {\n sum += b[j] as u64;\n }\n }\n max = std::cmp::max(max, sum);\n }\n println!(\"{}\", max);\n}\n\n// 基本的に 14 割った数足す\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": ["brute force", "implementation"], "code_uid": "7df1dca8b0819ceb485064c0a4feb26e", "src_uid": "1ac11153e35509e755ea15f1d57d156b", "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 (a, b): (u64, u64) = {\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 )\n };\n\n let ans = if b - a < 10 {\n (a..b).fold(1, |acc, k| ((k + 1) * acc) % 10)\n } else {\n 0\n };\n\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "ecea4e27348ea098b6bddf231834b6b9", "src_uid": "2ed5a7a6176ed9b0bda1de21aad13d60", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn get_count(n: u32) -> u32 {\n let mut count = 0;\n\n for i in 1..n {\n if n % i == 0 {\n count += 1;\n }\n }\n\n count\n}\n\npub fn solution() -> io::Result<()> {\n let mut number = String::new();\n\n io::stdin().read_line(&mut number)?;\n let number = number.trim().parse::().unwrap();\n\n println!(\"{}\", get_count(number));\n Ok(())\n}\n\nfn main() {\n solution();\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "86f44f03cbda93e7dc8ee21ba28987c3", "src_uid": "89f6c1659e5addbf909eddedb785d894", "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 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\trep!{[rin.u()]\n\t\tlet s = rin.vb();\n\t\tlet n = s.len();\n\t\tlet res = 10 * (s[0] - b'1') as usize + n * (n+1) / 2;\n\t\twriteln!(rout, \"{}\", res).ok();\n\t}\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "ceed3774eff00d7149876d40b8feefc9", "src_uid": "289a55128be89bb86a002d218d31b57f", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nuse std::str::FromStr;\nuse std::num::ParseIntError;\nuse std::ops::Index;\n\nstruct RevBinary {\n data: Vec,\n}\n\nimpl FromStr for RevBinary {\n type Err = ParseIntError;\n\n fn from_str(s: &str) -> Result {\n let i = s.parse::()?;\n\n Ok(RevBinary::new(i))\n }\n}\n\nimpl Index for RevBinary {\n type Output = bool;\n\n fn index(&self, i: usize) -> &Self::Output {\n &self.data[self.data.len() - i - 1]\n }\n}\n\nimpl RevBinary {\n fn new(x : u32) -> RevBinary {\n let mut y = x;\n let mut bin : Vec = Vec::new();\n while y != 0 {\n bin.push(if y % 2 == 1 { true } else { false }); \n y /= 2;\n }\n RevBinary {\n data: bin,\n }\n }\n\n fn size(&self) -> usize {\n self.data.len()\n }\n}\n\nfn process_node(all: &Vec, ind: Vec, depth: usize, k: u32) -> u32 {\n let mut result : u32 = ind.iter().take(k as usize).map(|&x| all[x].size() - depth).sum::() as u32;\n\n let mut new_ind0 : Vec = Vec::new();\n let mut new_ind1 : Vec = Vec::new();\n for i in ind.iter().filter(|&&x| all[x].size() > depth) {\n if all[*i][depth] {\n new_ind1.push(*i);\n } else {\n new_ind0.push(*i);\n } \n }\n if new_ind0.len() >= k as usize {\n result = result.min(process_node(&all, new_ind0, depth + 1, k));\n }\n if new_ind1.len() >= k as usize {\n result = result.min(process_node(&all, new_ind1, depth + 1, k));\n }\n result\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 n = input_iter.next().unwrap().parse::().unwrap();\n let k = input_iter.next().unwrap().parse::().unwrap();\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).expect(\"failed to read input\");\n let mut a = buffer.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n a.sort_by(|a, b| a.size().cmp(&b.size()));\n \n println!(\"{}\", process_node(&a, (0..n).collect::>(), 0, k));\n}", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "d9573d70427c8e16c64073a4bdbd0d73", "src_uid": "ed1a2ae733121af6486568e528fe2d84", "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 s1: Vec = ws.next().unwrap().chars().collect();\n let s2: Vec = ws.next().unwrap().chars().collect();\n\n let mut p1 = 0;\n for c in s1.iter() {\n if *c == '+' {\n p1 += 1;\n } else {\n p1 -= 1;\n }\n }\n\n let mut p2 = 0;\n let mut uc = 0;\n for c in s2.iter() {\n match c {\n '+' => p2 += 1,\n '-' => p2 -= 1,\n _ => uc += 1,\n }\n }\n\n let mut v: Vec = Vec::new();\n for bit in 0..1 << uc {\n let mut p = p2;\n for i in 0..uc {\n if bit >> i & 1 == 1 {\n p += 1;\n } else {\n p -= 1;\n }\n }\n v.push(p);\n }\n\n let mut cnt = 0;\n for x in v.iter() {\n if *x == p1 {\n cnt += 1;\n }\n }\n\n println!(\"{}\", cnt as f64 / v.len() as f64);\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 // let t = ws.next().unwrap().parse().unwrap();\n // for _ in 0..t {}\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "math", "dp", "combinatorics", "bitmasks", "probabilities"], "code_uid": "2516f9950ef6a748c3811464e9bbe5f4", "src_uid": "f7f68a15cfd33f641132fac265bc5299", "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(&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 sent: String = scan.next();\n let received: String = scan.next();\n let mut pos: isize = 0;\n for mov in sent.chars() {\n if mov == '+' {\n pos += 1;\n } else if mov == '-' {\n pos -= 1;\n }\n }\n let mut new_pos: isize = 0;\n let mut unknown: isize = 0;\n for mov in received.chars() {\n if mov == '+' {\n new_pos += 1;\n } else if mov == '-' {\n new_pos -= 1;\n } else {\n unknown += 1;\n }\n }\n let needed = pos - new_pos;\n if needed > unknown {\n println!(\"{:.10}\", 0.0f64);\n } else {\n let total: usize = 2usize.pow(unknown as u32);\n let mut valid = 0isize;\n for i in 0..total {\n if (2 * i.count_ones() as isize - unknown as isize) == needed {\n valid += 1;\n }\n }\n let result = (valid as f64) / (total as f64);\n println!(\"{:.10}\", 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": ["brute force", "math", "dp", "combinatorics", "bitmasks", "probabilities"], "code_uid": "00038a62b08dadcce378d1de6d1a550b", "src_uid": "f7f68a15cfd33f641132fac265bc5299", "difficulty": 1300.0, "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:i64};\n let s = n.to_string();\n\n let mut que = VecDeque::new();\n que.push_back(vec!['4']);\n que.push_back(vec!['7']);\n let mut cnt = 0;\n while !que.is_empty() {\n let mut chs = que.pop_front().unwrap();\n cnt += 1;\n //debug!(chs,cnt);\n if s == chs.iter().cloned().collect::() {\n println!(\"{}\", cnt);\n return();\n }\n //debug!(chs);\n chs.push('4');\n que.push_back(chs.clone());\n chs.pop();\n chs.push('7');\n que.push_back(chs.clone());\n\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation", "combinatorics", "bitmasks"], "code_uid": "d94ad14b35c643c5938aafd35aeb7f4c", "src_uid": "6a10bfe8b3da9c11167e136b3c6fb2a3", "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_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() -> std::io::Result<()> {\n let mut scan = Scan::new();\n let n: usize = scan.next();\n let mut oddeven = false;\n let mut parx = 0usize;\n let mut pary = 0usize;\n for _ in 0..n {\n let x: usize = scan.next();\n let y: usize = scan.next();\n parx = (parx + x) & 1;\n pary = (pary + y) & 1;\n if (x & 1) ^ (y & 1) == 1 {\n oddeven = true;\n }\n }\n if parx == 0 && pary == 0 {\n println!(\"0\");\n } else if n > 1 && oddeven && (parx * pary) == 1 {\n println!(\"1\");\n } else {\n println!(\"-1\");\n }\n Ok(())\n}\n\nfn main() -> std::io::Result<()> {\n std::thread::Builder::new()\n .stack_size(1 << 23)\n .spawn(_main)\n .unwrap()\n .join()\n .unwrap()?;\n Ok(())\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "fb64a2b55c9797e1fa11ea455be360c0", "src_uid": "f9bc04aed2b84c7dd288749ac264bb43", "difficulty": 1200.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\n\n// fn read_int() -> Result {\n// let mut str = String::new();\n// try!(io::stdin().read_line(&mut str).map_err(|e| e.to_string()));\n// str.trim().parse::().map_err(|e|e.to_string())\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": "85e2dec6d7be22276833f79d656b442b", "src_uid": "3ad3b8b700f6f34b3a53fdb63af351a5", "difficulty": 1000.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, 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\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 \n#[allow(non_snake_case, non_upper_case_globals)]\nfn main() {\n let num_cases: usize = 1;//read();\n for _case_num in 1..=num_cases {\n let n = read!(usize);\n let k = read!(usize);\n let mc = ModCombinatorics::new(n-1);\n\n fn c2(n: usize) -> usize {\n n * n.saturating_sub(1) / 2\n }\n let m = c2(n-1);\n\n let mut dp = vec![mi(0); n];\n dp[0] = mi(1);\n for x in 0..k {\n let R = mi(k - x).pow_vec(m);\n for j in (1..n).rev() {\n for i in 0..j {\n let d = dp[i] * R[c2(j) - c2(i)] * mc.C(n-1-i, j-i);\n dp[j] += d;\n }\n }\n //dbg!(&dp);\n }\n\n let ans = dp[n-1];\n println!(ans);\n }\n \n out_flush();\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "graph matchings"], "code_uid": "8b9c8b0ab1b502241f1952c5daf58b23", "src_uid": "b2d7ac8e75cbdb828067aeafd803ac62", "difficulty": 2200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "//! http://codeforces.com/contest/815/problem/E\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\n#[inline]\nfn house_dist(segment: i64) -> i64 {\n (segment + 1) / 2\n}\n\n/// Check whether the k'th placed house has a position <= limit.\nfn is_before(n: i64, k: i64, limit: i64) -> bool {\n use std::collections::BTreeMap;\n let mut l_segs = BTreeMap::new();\n let mut r_segs = BTreeMap::new();\n let mut cross = Some((2, n - 1));\n let mut rem = k;\n\n l_segs.insert(0i64, 0i64);\n r_segs.insert(0i64, 0i64);\n\n while rem > 0 {\n let (&l_max, &l_cnt) = l_segs.iter().rev()\n .next()\n .unwrap();\n let (&r_max, &r_cnt) = r_segs.iter().rev()\n .next()\n .unwrap();\n\n let mut max_seg = match cross {\n Some((lo, hi)) => hi - lo + 1,\n None => i64::min_value()\n };\n max_seg = std::cmp::max(max_seg, l_max);\n max_seg = std::cmp::max(max_seg, r_max);\n\n if house_dist(max_seg) == house_dist(l_max) {\n if l_cnt >= rem { return true; }\n rem -= l_cnt;\n l_segs.remove(&l_max);\n *l_segs.entry((l_max - 1) / 2).or_insert(0) += l_cnt;\n *l_segs.entry(l_max / 2).or_insert(0) += l_cnt;\n } else if match cross {\n None => false,\n Some((lo, hi)) => house_dist(max_seg) == house_dist(hi - lo + 1)\n }\n {\n let (lo, hi) = cross.unwrap();\n let mid = (lo + hi) / 2;\n if rem == 1 { return mid <= limit; }\n rem -= 1;\n\n let (lr, rl) = (mid - 1, mid + 1);\n\n if limit < lr {\n cross = Some((lo, lr));\n *r_segs.entry(hi - rl + 1).or_insert(0) += 1;\n } else if limit >= rl {\n cross = Some((rl, hi));\n *l_segs.entry(lr - lo + 1).or_insert(0) += 1;\n } else {\n cross = None;\n *r_segs.entry(hi - rl + 1).or_insert(0) += 1;\n *l_segs.entry(lr - lo + 1).or_insert(0) += 1;\n }\n } else if house_dist(max_seg) == house_dist(r_max) {\n if r_cnt >= rem { return false; }\n rem -= r_cnt;\n r_segs.remove(&r_max);\n *r_segs.entry((r_max - 1) / 2).or_insert(0) += r_cnt;\n *r_segs.entry(r_max / 2).or_insert(0) += r_cnt;\n }\n }\n\n unreachable!()\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: i64, k: i64);\n\n if k == 1 { putln!(\"1\"); }\n else if k == 2 { putln!(\"{}\", n); }\n else {\n let (mut lo, mut hi) = (2, n - 1);\n let mut ans = hi;\n while lo <= hi {\n let mid = (lo + hi) / 2;\n if is_before(n, k - 2, mid) {\n ans = mid;\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n putln!(\"{}\", ans);\n }\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "binary search", "implementation"], "code_uid": "7763969c5560756fd10e035f54d019ab", "src_uid": "eb311bde6a0e3244d92fafbd4aa1e61f", "difficulty": 2900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let n = buffer.trim().parse::().unwrap();\n let max_iter = factorial(n+1);\n buffer.clear();\n io::stdin().read_line(&mut buffer).unwrap();\n let mut s1: Vec = buffer.split_whitespace().map(|x| x.parse::().unwrap()).collect();\n let mut s1_cards = s1.split_off(1);\n buffer.clear();\n io::stdin().read_line(&mut buffer).unwrap();\n let mut s2: Vec = buffer.split_whitespace().map(|x| x.parse::().unwrap()).collect();\n let mut s2_cards = s2.split_off(1);\n\n let mut counter = 0;\n let mut infinite_game = false;\n while s1_cards.len() > 0 && s2_cards.len() > 0 {\n \n if counter > max_iter {\n infinite_game = true;\n break;\n }\n\n match (s1_cards.remove(0), s2_cards.remove(0)) {\n (x, y) if x > y => {\n s1_cards.push(y);\n s1_cards.push(x);\n },\n (x, y) if x < y => {\n s2_cards.push(x);\n s2_cards.push(y);\n },\n _ => unreachable!()\n }\n counter += 1;\n }\n\n if infinite_game {\n println!(\"{}\", -1);\n } else {\n let winner: u32;\n if s1_cards.len() == 0 {\n winner = 2;\n } else {\n winner = 1;\n }\n println!(\"{} {}\", counter, winner);\n }\n\n}\n\nfn factorial(x: u32) -> u32 {\n (2..x).fold(1, |a, b| {\n a * b\n })\n}\n", "lang_cluster": "Rust", "tags": ["dfs and similar", "brute force", "games"], "code_uid": "f17114fa58df84b2a913baa05998fc79", "src_uid": "f587b1867754e6958c3d7e0fe368ec6e", "difficulty": 1400.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\n#[derive(Clone)]\nstruct DPCell {\n q: u64,\n qa: u64,\n qaq: u64,\n}\n\nfn main() {\n let s = read_line();\n let mut dp = vec![DPCell {q: 0, qa: 0, qaq: 0}; s.len()];\n for (i, c) in s.chars().enumerate() {\n match c {\n 'Q' => {\n if i > 0 {\n dp[i].q = dp[i - 1].q + 1;\n dp[i].qa = dp[i - 1].qa;\n dp[i].qaq = dp[i - 1].qaq + dp[i - 1].qa;\n } else {\n dp[i].q = 1;\n }\n },\n 'A' => {\n if i > 0 {\n dp[i].q = dp[i - 1].q;\n dp[i].qa = dp[i - 1].qa + dp[i - 1].q;\n dp[i].qaq = dp[i - 1].qaq;\n } },\n _ => {\n if i > 0 {\n dp[i] = dp[i - 1].clone();\n }\n }\n }\n }\n println!(\"{}\", dp.last().unwrap().qaq);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "dp"], "code_uid": "107c7a90b26dda2d14fc47d9866acb77", "src_uid": "8aef4947322438664bd8610632fe0947", "difficulty": 800.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(\"\");\n let mut v_a = a_str.trim().chars()\n .map(|x| x.to_digit(10).unwrap() as i32)\n .collect::>();\n\n let mut b_str = String::new();\n io::stdin().read_line(&mut b_str).expect(\"\");\n let mut v_b = b_str.trim().chars()\n .map(|x| x.to_digit(10).unwrap() as i32)\n .collect::>();\n\n\n let x: String= v_b.iter().map(|y| y.to_string()).collect();\n let n_b: i64 = x.parse().unwrap();\n\n let mut res = String::new();\n v_a.sort();\n for i in 0..v_a.len() {\n for j in (i + 1)..v_a.len() {\n let mut t = v_a.clone();\n t.swap(i, j);\n let x: String= t.iter().map(|y| y.to_string()).collect();\n let n_t: i64 = x.parse().unwrap();\n let x: String= v_a.iter().map(|y| y.to_string()).collect();\n let n_a: i64 = x.parse().unwrap();\n if n_a < n_t && n_t <= n_b {\n v_a.swap(i, j);\n }\n }\n }\n res = v_a.iter().map(|x| x.to_string()).collect();\n println!(\"{}\", res);\n}\n", "lang_cluster": "Rust", "tags": ["greedy", "dp"], "code_uid": "a0dd1da83364e855cb81e10f4f4538e3", "src_uid": "bc31a1d4a02a0011eb9f5c754501cd44", "difficulty": 1700.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 input = get_lines()?;\n\tlet s = input.trim();\n\tlet a_count = s.chars().filter(|c| *c == 'a').count();\n\tlet not_a_count = s.len() - a_count;\n\tprint!(\n\t\t\"{}\",\n\t\tif a_count > not_a_count {\n\t\t\ts.len()\n\t\t} else {\n\t\t\ta_count * 2 - 1\n\t\t}\n\t);\n\tOk(())\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "08c82e9c286ea0ca2034c03da3c0c2c2", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn main() {\n let mut si = String::new();\n io::stdin().read_line(&mut si).unwrap();\n let count_a = si.trim().matches(\"a\").collect::>().len(); \n let len = si.trim().len();\n if count_a > len / 2 {\n println!(\"{}\", len);\n } else {\n println!(\"{}\", count_a * 2 - 1);\n }\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "874e39a226acf50d3ece4f09e12c54c0", "src_uid": "84cb9ad2ae3ba7e912920d7feb4f6219", "difficulty": 800.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 mut p:Vec<(i64,i64)> = (0..6).map(|_| (read(), read())).collect();\n //debug!(p);\n\n // 1つ目の黒について\n if p[2].0 <= p[0].0 && p[2].1 <= p[0].1 && p[3].0 >= p[1].0 && p[3].1 >= p[1].1 {\n println!(\"NO\");\n return;\n }\n // 白の上か下が消えるかどうか\n if p[2].0 <= p[0].0 && p[3].0 >= p[1].0 {\n if p[2].1 <= p[0].1 && p[3].1 >= p[0].1 {\n p[0].1 = p[3].1;\n }\n if p[3].1 >= p[1].1 && p[2].1 <= p[1].1 {\n p[1].1 = p[2].1;\n }\n }\n // 白の左か右が消えるかどうか\n if p[2].1 <= p[0].1 && p[3].1 >= p[1].1 {\n if p[2].0 <= p[0].0 && p[3].0 >= p[0].0 {\n p[0].0 = p[3].0;\n }\n if p[3].0 >= p[1].0 && p[2].0 <= p[1].0 {\n p[1].0 = p[2].0;\n }\n }\n //debug!(p[0],p[1]);\n if p[0].0 >= p[1].0 || p[0].1 >= p[1].1 {\n println!(\"NO\");\n return;\n }\n if p[4].0 <= p[0].0 && p[4].1 <= p[0].1 && p[5].0 >= p[1].0 && p[5].1 >= p[1].1 {\n println!(\"NO\");\n return;\n }\n\n println!(\"YES\");\n\n //}\n\n}\n\n/*\n\n\n*/\n", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "cb0f78f93e0085a27cd9689a342babc2", "src_uid": "05c90c1d75d76a522241af6bb6af7781", "difficulty": 1700.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 mut v = s.split_whitespace().map(|x| x.parse::().unwrap()).collect::>();\n v.sort_unstable();\n let (_legs,headbody) : (&[i32], [i32;2]) = {\n if v[0] == v[1] && v[1] == v[2] && v[2] == v[3] \n {(&v[0..4],[v[4],v[5]])}\n else if v[1] == v[2] && v[2] == v[3] && v[3] == v[4] \n {(&v[1..5], [v[0],v[5]])}\n else if v[2] == v[3] && v[3] == v[4] && v[4] == v[5] \n {(&v[2..6], [v[0],v[1]])}\n else \n {(&v[0..0],[-1,-1])}\n };\n println!(\n \"{}\",\n if headbody == [-1,-1] {\"Alien\"}\n else if headbody[0] 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 s = get_string();\n let mut m = HashMap::new();\n\n for i in 0..10 {\n let n = get_string();\n m.insert(n, i);\n }\n\n let v = Vec::from(s);\n for w in v.chunks(10) {\n let mut k = String::new();\n\n for &c in w {\n k.push(c as char);\n }\n\n print!(\"{}\", m.get(&k).unwrap());\n }\n println!();\n}\n", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "cce14eaca767e3aea918a75be7e270c0", "src_uid": "0f4f7ca388dd1b2192436c67f9ac74d9", "difficulty": 900.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "type Res = u64;\n\nfn main() {\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\n let result = solve(k);\n\n println!(\"{}\", result);\n\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 solve(k: Res) -> char {\n // counter for digits\n let mut n: Res = 1;\n // Potential number of the digit we search\n let mut d: Res = 1;\n while n impl Iterator {\n (0..).flat_map(|i| i.to_string().chars().collect::>())\n}\n\nfn main() {\n let stdin = io::stdin();\n let line = stdin.lock().lines().next().expect(\"input\").expect(\"UTF-8\");\n let index: usize = line.parse().expect(\"Numeric value\");\n\n println!(\"{}\", it().skip(index).next().unwrap());\n}\n\n#[test]\nfn vectors() {\n let in_out = [(7, '7'), (21, '5')];\n\n for (i, o) in &in_out {\n assert_eq!(it().skip(*i).next().unwrap(), *o);\n }\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "df3ecd071dcf48c6cc104d3939a8e38b", "src_uid": "1503d761dd4e129fb7c423da390544ff", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust 2021", "source_code": "#[allow(dead_code)]\nfn scan() -> T\n{\n static mut BUFFER: Vec = vec![];\n loop {\n if let Some(token) = unsafe { BUFFER.pop() } {\n return token.parse().ok().unwrap();\n }\n let mut input = String::new();\n std::io::stdin().read_line(&mut input).ok();\n unsafe { BUFFER = input.split_whitespace().rev().map(String::from).collect(); }\n }\n}\n\nfn non_stop(p1: i64, t1: i128, p2: i64, t2: i128, rem: i64, s: i64) -> i128\n{\n let mut t = 0;\n let mut dam = 0;\n while dam < rem {\n if t1 - t%t1 <= t2 - t%t2 {\n t += t1 - t%t1;\n dam += p1 - s;\n } else if t1 - t%t1 >= t2 - t%t2 {\n t += t2 - t%t2;\n dam += p2 - s;\n } else {\n t += t1 - t%t1;\n dam += p1 + p2 - s;\n }\n }\n t\n}\n\nfn main()\n{\n let (p1, t1) = (scan::(), scan::());\n let (p2, t2) = (scan::(), scan::());\n let (h, s) = (scan::(), scan::());\n let mut dp = vec![0i128; (h+1) as usize];\n for rem in 1..=h as usize {\n dp[rem] = non_stop(p1, t1, p2, t2, rem as i64, s); \n for i in 0..=h {\n let mut t = t1 * (i + 1) as i128;\n let mut dam = (p1 - s) * i;\n // 2 is charged before 1\n if t >= t2 {\n let mut cdam = dam;\n cdam += (t / t2 - 1) as i64 * (p2 - s);\n cdam += p1 + p2 - s;\n dp[rem] = dp[rem].min(if cdam as usize > rem { t }\n else { t + dp[rem - cdam as usize] });\n }\n // 1 is charged before 2\n dam += (t / t2) as i64 * (p2 - s);\n t += t2 - t%t2;\n dam += p1 + p2 - s;\n dp[rem] = dp[rem].min(if dam as usize > rem { t }\n else { t + dp[rem - dam as usize] });\n }\n }\n println!(\"{}\", dp[h as usize]);\n}\n", "lang_cluster": "Rust", "tags": ["dp", "binary search"], "code_uid": "7239ef1eea035742fc4336921a3a06b5", "src_uid": "ca9d48e48e69b931236907a9ac262433", "difficulty": 2400.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\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\t\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}\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": "8fac997122c73e66466f1c7f36c2a0c4", "src_uid": "ca9d48e48e69b931236907a9ac262433", "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(&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 // case 1: 1\n // 2: 1 + 1*4 = 5\n // 3: 5 + 2*4 = 13\n // 4: 13 + 3*4\n // ....\n let mut result = 1usize;\n for i in 1..n {\n result += 4 * i;\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": ["math", "dp", "implementation"], "code_uid": "67748125cb50838d64cc7630cead28b3", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[derive(Debug)]\nstruct RhombusIterator{\n current: isize,\n count: isize,\n total: isize,\n}\n\nimpl RhombusIterator{\n pub fn new() ->Self{\n RhombusIterator{\n current: 1,\n count: 0,\n total: 1,\n }\n }\n}\n\nimpl Iterator for RhombusIterator{\n type Item = isize;\n\n fn next(&mut self) -> Option {\n match self.current{\n 1 => {},\n _ => {\n self.total += 2* self.current + (2* self.count);\n self.count += 1;\n },\n }\n self.current +=1;\n Some(self.total)\n }\n}\n\nfn main() -> Result<(), Box> {\n\n //parse\n let mut input = String::new();\n std::io::stdin().read_line(&mut input)?;\n let input: usize = input.trim().parse().expect(\"Invalid input parameter\");\n\n //solve\n let result = solve(input);\n\n //print\n println!(\"{}\", result);\n\n Ok(())\n}\n\n\nfn solve(input: usize) -> isize{\n let iter = RhombusIterator::new();\n iter.skip(input-1).next().expect(\"Could not calc rhombus\")\n}\n\n\n#[cfg(test)]\nmod test{\n use super::solve;\n\n\n #[test]\n fn test1() {\n\n assert_eq!(1, solve(1));\n assert_eq!(5, solve(2));\n assert_eq!(solve(3), 13);\n assert_eq!(25, solve(4));\n assert_eq!(41, solve(5));\n }\n}", "lang_cluster": "Rust", "tags": ["math", "dp", "implementation"], "code_uid": "8e0de16e72ea7606bbbb24e28d1a4aa2", "src_uid": "758d342c1badde6d0b4db81285be780c", "difficulty": 800.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(\"\");\n let mut num = a_str.split_whitespace()\n .map(|x| x.parse::().expect(\"parse error\"))\n .collect::>();\n let mut b_str = String::new();\n io::stdin().read_line(&mut b_str).expect(\"\");\n let mut v = b_str.split_whitespace()\n .map(|x| x.parse::().expect(\"parse error\"))\n .collect::>();\n\n let n = num[0];\n let k = num[1];\n\n let mut res = 0;\n v.sort();\n v.reverse();\n for i in &v {\n if k % i == 0 {\n res = k / i;\n break;\n }\n }\n println!(\"{}\", res);\n\n\n}\n", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "44e740d62b9b130892d2b51ce25cea85", "src_uid": "80520be9916045aca3a7de7bc925af1f", "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: usize = util::get();\n let a: usize = util::get();\n let b: usize = util::get();\n let c: usize = util::get();\n\n let mut dp = vec![vec![100000; 3]; n];\n dp[0][0] = 0;\n\n for i in 1..n {\n dp[i][0] = min(dp[i][0], dp[i - 1][1] + a);\n dp[i][0] = min(dp[i][0], dp[i - 1][2] + b);\n\n dp[i][1] = min(dp[i][1], dp[i - 1][0] + a);\n dp[i][1] = min(dp[i][1], dp[i - 1][2] + c);\n\n dp[i][2] = min(dp[i][2], dp[i - 1][0] + b);\n dp[i][2] = min(dp[i][2], dp[i - 1][1] + c);\n }\n\n println!(\"{}\", dp[n - 1].iter().min().unwrap());\n\n}\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "aa5b2a875a0c1f2d04a4bdadd4b978f2", "src_uid": "6058529f0144c853e9e17ed7c661fc50", "difficulty": 900.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 n: u64 = input.trim().parse().unwrap();\n\n let check = |k| {\n let mut n = n;\n\n let mut v = 0;\n let mut p = 0;\n loop {\n if n < k {\n v += n;\n break;\n }\n n -= k;\n v += k;\n\n let q = n / 10;\n n -= q;\n p += q;\n }\n\n p <= v\n };\n\n let mut low = 0;\n let mut up = (n + 1) / 2;\n\n while low + 1 != up {\n let cur = (low + up) / 2;\n if check(cur) {\n up = cur;\n } else {\n low = cur;\n }\n }\n\n println!(\"{}\", up);\n}\n", "lang_cluster": "Rust", "tags": ["implementation", "binary search"], "code_uid": "e047df290e1e6d6ed2a626b8a1809560", "src_uid": "db1a50da538fa82038f8db6104d2ab93", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "// 991C\nuse std::io;\nfn main() {\n let n: u64 = read_one(&io::stdin());\n let mut min = 0;\n let mut max = n;\n loop {\n let mid = (min + max) / 2;\n if mid == min {\n break;\n }\n if eats_half(n, mid) {\n max = mid;\n } else {\n min = mid;\n }\n }\n println!(\"{}\", max);\n}\n\nfn eats_half(mut n: u64, k: u64) -> bool {\n let original_n = n;\n let mut v = 0;\n while n >= k {\n n -= k;\n v += k;\n n -= n / 10;\n }\n v += n;\n return 2 * v >= original_n;\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": ["implementation", "binary search"], "code_uid": "468685580ed3d6e9ebdbbcc1b28528f9", "src_uid": "db1a50da538fa82038f8db6104d2ab93", "difficulty": 1500.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::cmp::min;\n\nfn get_max_days(a: u32, b: u32, c: u32) -> u32 {\n let full_week_num: u32 = min(a / 3, min(b / 2, c / 2));\n let a_rest: u32 = a - 3 * full_week_num;\n let b_rest: u32 = b - 2 * full_week_num;\n let c_rest: u32 = c - 2 * full_week_num;\n\n let mut extra_days_max: u32 = 0;\n for start_weekday in 0..7 {\n let mut weekday: u32 = start_weekday;\n let mut extra_days: u32 = 0;\n let mut a_rest1: u32 = a_rest;\n let mut b_rest1: u32 = b_rest;\n let mut c_rest1: u32 = c_rest;\n loop {\n if (weekday == 0) || (weekday == 3) || (weekday == 6) {\n if a_rest1 > 0 {\n a_rest1 -= 1;\n } else {\n break;\n }\n } else if (weekday == 1) || (weekday == 5) {\n if b_rest1 > 0 {\n b_rest1 -= 1;\n } else {\n break;\n }\n } else {\n if c_rest1 > 0 {\n c_rest1 -= 1;\n } else {\n break;\n }\n }\n\n extra_days += 1;\n weekday += 1;\n weekday %= 7;\n }\n\n if extra_days > extra_days_max {\n extra_days_max = extra_days;\n }\n }\n\n return 7 * full_week_num + extra_days_max;\n}\n\n#[cfg(test)]\nmod tests {\n use super::get_max_days;\n\n #[test]\n fn test1() {\n assert_eq!(get_max_days(2, 1, 1), 4);\n }\n #[test]\n fn test2() {\n assert_eq!(get_max_days(3, 2, 2), 7);\n }\n #[test]\n fn test3() {\n assert_eq!(get_max_days(1, 100, 1), 3);\n }\n #[test]\n fn test4() {\n assert_eq!(get_max_days(30, 20, 10), 39);\n }\n}\n\nfn read_data() -> (u32, u32, u32) {\n let mut data_str: String = String::new();\n std::io::stdin().read_line(&mut data_str).unwrap();\n\n let data_values: Vec = data_str\n .trim()\n .split(\" \")\n .map(|s| s.parse::().unwrap())\n .collect();\n\n return (data_values[0], data_values[1], data_values[2]);\n}\n\nfn main() {\n let (a, b, c): (u32, u32, u32) = read_data();\n\n let max_days: u32 = get_max_days(a, b, c);\n\n println!(\"{}\", max_days);\n}\n", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "2b053cf58ec991411ed3c0ac7990ae8b", "src_uid": "e17df52cc0615585e4f8f2d31d2daafb", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn raw_input() -> String {\n let mut buf = String::new();\n io::stdin().read_line(&mut buf).unwrap();\n buf.trim().to_string()\n}\n\nfn input_split() -> Vec {\n raw_input()\n .split_whitespace()\n .map(|elem| elem.parse().unwrap())\n .collect()\n}\n\nfn input() -> u16 {\n raw_input().parse().unwrap()\n}\n\nfn main() {\n let mut n = input();\n let days = input_split();\n\n let week_total: u16 = days.iter().sum();\n while n > week_total {\n n -= week_total;\n }\n\n let mut current_day = 0;\n loop {\n if days[current_day] >= n {\n break;\n } else {\n n -= days[current_day];\n }\n current_day += 1;\n }\n\n print!(\"{}\", current_day + 1);\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "ea3542bf160747ab9a96be8f16eff050", "src_uid": "007a779d966e2e9219789d6d9da7002c", "difficulty": 1000.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,\n mem::{replace, swap},\n};\n\nfn main() -> io::Result<()> {\n std::thread::Builder::new()\n .stack_size(64 * 1024 * 1024)\n .spawn(solve)?\n .join()\n .unwrap();\n Ok(())\n}\n\nfn solve() {\n let stdin = io::stdin();\n let mut kin = KInput::new(stdin.lock());\n let stdout = io::stdout();\n let mut out = io::BufWriter::new(stdout.lock());\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 const MOD: i64 = 998244353;\n let (n, k): (i64, i64) = kin.input();\n if k > n {\n outputln!(\"0\");\n return;\n }\n let c = Combination::new(n as usize + 1, MOD);\n let mut ans = 0;\n for i in 1..=n {\n ans += c.comb(n / i - 1, k - 1);\n }\n ans %= MOD;\n outputln!(\"{}\", 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 {\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) * self.inv(self.fact(a - b)) % 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) * self.inv(self.fact(b) * self.fact(a - b) % self.m) % self.m\n } else {\n 0\n }\n }\n pub fn pow(&self, a: i64, b: i64) -> i64 {\n mod_pow(a, b, self.m)\n }\n pub fn inv(&self, x: i64) -> i64 {\n self.pow(x, self.m - 2)\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 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": ["math", "combinatorics", "number theory"], "code_uid": "31706d53b7f649d5c2a0893fbee11bd5", "src_uid": "8e8eb64a047cb970a549ee870c3d280d", "difficulty": 2000.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 < 3 {n*2+1} 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": "14c256864368ae81965989e8fe26a3ab", "src_uid": "d0a8604b78ba19ab769fd1ec90a72e4e", "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\nfn _main() {\n let mut scan = Scan::new();\n let a: usize = scan.next();\n let mut b: usize = scan.next();\n let mut c: usize = scan.next();\n b /= 2;\n c /= 4;\n let n = a.min(b).min(c);\n println!(\"{}\", n * 7);\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": "3ca8e98bbece6426436ebb93a83e1416", "src_uid": "82a4a60eac90765fb62f2a77d2305c01", "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 mut a = input.vi(3);\n let d = input.i();\n a.sort();\n println!(\"{}\", 2 * d - (a[1] - a[0]).min(d) - (a[2] - a[1]).min(d));\n}\n\n", "lang_cluster": "Rust", "tags": ["math"], "code_uid": "b91c9ad4708c5391968dcd9692694b31", "src_uid": "47c07e46517dbc937e2e779ec0d74eb3", "difficulty": 800.0, "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 let n = input();\n println!(\"{}\", (1..n).fold(0, |count, i| count + i * (n - i)) + n);\n}", "lang_cluster": "Rust", "tags": ["math", "implementation"], "code_uid": "e88eca4fa04d8fb4c8f3112e109ac1a0", "src_uid": "6df251ac8bf27427a24bc23d64cb9884", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn main() {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n let n_a: Vec = buffer.split_whitespace().map(|x| x.parse::().unwrap()).collect();\n let (_, a) = (n_a[0], n_a[1] - 1);\n buffer.clear();\n io::stdin().read_line(&mut buffer).unwrap();\n let s: Vec = buffer.split_whitespace().map(|x| x.parse::().unwrap()).collect();\n let i: usize = a;\n let mut d: usize = 1;\n let mut ans: u32 = 0;\n if s[a] == 1 { ans += 1};\n loop {\n let left_idx = i.checked_sub(d);\n let right_idx = i + d;\n\n let left = match left_idx {\n Some(x) => Some(s[x]),\n None => None\n };\n\n let right = match right_idx {\n x if x < s.len() => Some(s[x]),\n _ => None\n };\n\n ans += match (left, right) {\n (Some(1), Some(1)) => 2,\n (None, Some(1)) => 1,\n (Some(1), None) => 1,\n _ => 0\n };\n\n if left.is_none() && right.is_none() {\n break;\n }\n\n d += 1\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["constructive algorithms", "implementation"], "code_uid": "16f1ade5451965971d9b2e0312ae611c", "src_uid": "4840d571d4ce6e1096bb678b6c100ae5", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#![allow(unused_variables)]\n#![allow(unused_must_use)]\n#![allow(dead_code)]\nuse std::io::{self, prelude::*};\n\nfn solve(mut input: FastInput, mut w: W) {\n let n: usize = input.token();\n let mut a = vec![0usize; n];\n for x in a.iter_mut() {\n *x = input.token();\n }\n let min = a.iter().min().unwrap();\n let cnt = a.iter().filter(|&x| x == min).count();\n if cnt > n / 2 {\n write!(w, \"Bob\\n\");\n } else {\n write!(w, \"Alice\\n\");\n }\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\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": ["games"], "code_uid": "6cba9594f446cbe12b7e23272c88accf", "src_uid": "4b9cf82967aa8441e9af3db3101161e9", "difficulty": 2000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::iter::*;\nuse std::str::SplitWhitespace;\nuse std::io::{stdin, BufReader, Stdin};\nuse std::io::prelude::*;\nuse std::collections::hash_map::HashMap;\nuse std::collections::hash_set::HashSet;\nuse std::string::*;\n\nfn main() {\n let mut buf = String::new();\n stdin().read_line(&mut buf);\n let s: usize = vec![\"Danil\", \"Olya\", \"Slava\", \"Ann\", \"Nikita\"]\n .iter()\n .map(|&s| buf.matches(s).count())\n .sum();\n println!(\"{}\", if s == 1 { \"YES\" } else { \"NO\" });\n}", "lang_cluster": "Rust", "tags": ["strings", "implementation"], "code_uid": "e6439a03c745dc10191eca4a2711b644", "src_uid": "db2dc7500ff4d84dcc1a37aebd2b3710", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::{io::stdin, iter};\n\nfn find_smallest(n: usize, l: usize) -> usize {\n let remaining = l - 1;\n let mut res: Vec = iter::repeat(1).take(n - remaining).collect();\n for i in n - remaining..n {\n res.push(res[i - 1] * 2);\n }\n res.iter().sum()\n}\n\nfn find_biggest(n: usize, r: usize) -> usize {\n let remaining = r - 1;\n let mut res: Vec = iter::repeat(2usize.pow(remaining as u32))\n .take(n - remaining)\n .collect();\n for i in n - remaining..n {\n res.push(res[i - 1] / 2);\n }\n res.iter().sum()\n}\n\nfn main() {\n let mut buf = String::new();\n stdin().read_line(&mut buf).unwrap();\n let mut buf = buf\n .trim()\n .split_whitespace()\n .map(|c| c.parse::().unwrap());\n let (n, l, r) = (\n buf.next().unwrap(),\n buf.next().unwrap(),\n buf.next().unwrap(),\n );\n\n println!(\"{} {}\", find_smallest(n, l), find_biggest(n, r));\n}", "lang_cluster": "Rust", "tags": ["math", "greedy"], "code_uid": "f8aef2d936f3d68cf0be05846e12dffa", "src_uid": "ce220726392fb0cacf0ec44a7490084a", "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 factorize(n: i64) -> Vec {\n let mut n = n;\n let mut ans = Vec::new();\n let mut d = 2;\n while d * d <= n {\n while n % d == 0 {\n ans.push(d);\n n /= d;\n }\n d += 1;\n }\n if n > 1 {\n ans.push(n);\n }\n ans\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: i64 = scan.token();\n let k: i64 = scan.token();\n\n let factors = factorize(n);\n let num_factors = factors.len() as i64;\n if num_factors < k {\n writeln!(out, \"-1\").ok();\n return;\n }\n // Choose (k - 1) factors individually.\n // Make the k-th factor the product of the rest of the factors.\n for i in 0..(k - 1) {\n write!(out, \"{} \", factors[i as usize]).ok();\n }\n let mut last_factor = 1;\n for i in (k - 1)..num_factors {\n last_factor *= factors[i as usize];\n }\n writeln!(out, \"{}\", last_factor).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": "75a85f24fe1e9e875fd987f0d757fef6", "src_uid": "bd0bc809d52e0a17da07ccfd450a4d79", "difficulty": 1100.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io::*;\n\nfn main() {\n let mut k = String::new();\n stdin().read_line(&mut k);\n let mut flag = false;\n let mut cnt = 0;\n for x in k.chars() {\n if !flag && x == '1' {\n flag = true;\n }\n if flag && x == '0' {\n cnt += 1;\n }\n }\n if flag && cnt >= 6 {\n println!(\"yes\");\n } else {\n println!(\"no\");\n }\n}", "lang_cluster": "Rust", "tags": ["implementation"], "code_uid": "a6872fc9860084b78ed346cae20294d0", "src_uid": "88364b8d71f2ce2b90bdfaa729eb92ca", "difficulty": 1000.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 ca = read!(String).chars().collect::>();\n\n let mut a = vec![' '; n];\n let mut b = vec![' '; n];\n for i in 0..n {\n a[i] = ca[i];\n b[i] = ca[i + n];\n }\n\n a.sort();\n b.sort();\n let mut t = 0;\n for i in 0..n {\n if a[i] < b[i] {\n t |= 1;\n } else if a[i] > b[i] {\n t |= 2;\n } else {\n t |= 4;\n }\n }\n\n if t < 3 {\n rr.push(\"YES\".to_string());\n } else {\n rr.push(\"NO\".to_string());\n }\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": "5ef1697860d69078f1d8b885415e6abf", "src_uid": "e4419bca9d605dbd63f7884377e28769", "difficulty": 1100.0, "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#[derive(Clone, Debug, Default)]\nstruct Solver {}\n\nimpl Solver {\n fn solve(&mut self, scan: &mut Scanner, out: &mut BufWriter) {\n // 1426e\n let n = scan.u();\n let a = scan.vecu(3);\n let b = scan.vecu(3);\n\n let maxwin = min(a[0], b[1]) + min(a[1], b[2]) + min(a[2], b[0]);\n let tmp = max(max(a[0] + b[1], a[1] + b[2]), a[2] + b[0]);\n let minwin = tmp.saturating_sub(n);\n\n writeln!(out, \"{} {}\", minwin, maxwin).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": ["brute force", "constructive algorithms", "flows", "math", "greedy"], "code_uid": "2d163382b3e7ff596c4f8168169d5767", "src_uid": "e6dc3bc64fc66b6127e2b32cacc06402", "difficulty": 1800.0, "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 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: 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 p = ModInt(m).inv();\n let pc = Precalc::new(k);\n let mut t = vec![ModInt::zero(); k + 1];\n let mut s = vec![p; k + 1];\n t[0] = ModInt::one();\n s[0] = ModInt::one();\n for (i, s) in s.iter_mut().enumerate() {\n *s *= pc.ifact(i);\n }\n while n > 0 {\n if n & 1 == 1 {\n t = multiply(&t, &s);\n t.truncate(k + 1);\n }\n s = multiply(&s, &s);\n s.truncate(k + 1);\n n >>= 1;\n }\n let ans = t[k] * pc.fact(k);\n println!(\"{}\", ans);\n}\n\nfn main() {\n run();\n}\n", "lang_cluster": "Rust", "tags": ["math", "dp", "combinatorics", "probabilities", "number theory"], "code_uid": "d3f4df8f2b95414575b6549305183a96", "src_uid": "e6b3e559b5fd4e05adf9f1cd1b22126b", "difficulty": 2600.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 a: Vec = get_vec();\n\n let sum: u32 = a.iter().cloned().sum();\n\n if sum % 2 != 0 {\n println!(\"NO\");\n return;\n }\n\n for i in 0..6 {\n for j in i + 1..6 {\n for k in j + 1..6 {\n if a[i] + a[j] + a[k] == sum / 2 {\n println!(\"YES\");\n return;\n }\n }\n }\n }\n\n println!(\"NO\");\n}\n", "lang_cluster": "Rust", "tags": ["brute force"], "code_uid": "4d336f74b78fe3b7c4a8e43c194fb529", "src_uid": "2acf686862a34c337d1d2cbc0ac3fd11", "difficulty": 1000.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn read_line() -> String {\n let mut line = String::new();\n match io::stdin().read_line(&mut line) {\n Ok(_) => line.trim().to_string(),\n _ => panic!(\"QQ\"),\n }\n}\n\nfn main() {\n let mut ans: u32 = 1;\n let n = read_line().parse::().unwrap();\n for i in 1..n {\n ans = ans * (i + n - 1) / i;\n }\n println!(\"{}\", ans);\n}\n", "lang_cluster": "Rust", "tags": ["brute force", "implementation"], "code_uid": "18fe221556a2d65169d8b48c11d8e918", "src_uid": "2f650aae9dfeb02533149ced402b60dc", "difficulty": 800.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "#[allow(unused_imports)] use std::{*, io::*, };\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 input!{\n a: (i64, i64),\n b: (i64, i64),\n c: (i64, i64),\n }\n puts!(\n \"{}\",\n if (a.0 - b.0).pow(2) + (a.1 - b.1).pow(2) == (b.0 - c.0).pow(2) + (b.1 - c.1).pow(2) \n && (b.0 - a.0) * (c.1 - b.1) != (b.1 - a.1) * (c.0 - b.0) \n {\"Yes\"} else {\"No\"}\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\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", "lang_cluster": "Rust", "tags": ["math", "geometry"], "code_uid": "873e3435d98fb860f9ea2c35f5b77553", "src_uid": "05ec6ec3e9ffcc0e856dc0d461e6eeab", "difficulty": 1400.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 gcd(a: i64, b: i64) -> i64 {\n if b == 0 {\n return a\n }\n else {\n return gcd(b, a % b);\n }\n}\n\nfn main1() {\n let mut scan = Scanner::new();\n let n = scan.next::();\n let k = scan.next::();\n let a = scan.next::();\n let b = scan.next::();\n let len = n * k;\n \n // all offsets are in [0, k]\n let mut offsets = vec![a+b, max(a,b)-min(a,b)];\n let neg1 = k - offsets[0];\n let neg2 = k - offsets[1];\n offsets.push(neg1);\n offsets.push(neg2);\n \n let mut lo = len;\n let mut hi = 0;\n for offset in offsets {\n for i in 0..n {\n let l = offset + k * i;\n let stops = len / gcd(l, len);\n lo = min(lo, stops);\n hi = max(hi, stops);\n }\n }\n println!(\"{} {}\", lo, hi);\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", "math"], "code_uid": "6b472f82eb1f1cd9d6315e7415bbfd83", "src_uid": "5bb4adff1b332f43144047955eefba0c", "difficulty": 1700.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\n\nfn to_square(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 solve_square1(s1: &Vec<(i32, i32)>, x: i32) -> Option<(i32, i32)> {\n\tif x < s1[0].0 || x > s1[3].0 { return None; }\n\treturn Some((s1[0].1, s1[3].1));\n}\n\nfn solve_square2(s2: &Vec<(i32, i32)>, x: i32) -> Option<(i32, i32)> {\n\tlet x1 = s2[0].0;\n\tlet x2 = s2[3].0;\n\tlet y0 = s2[0].1;\n\tif x < x1 || x > x2 { return None; }\n\tlet d = if x < s2[1].0 {\n\t\tx - x1\n\t} else {\n\t\ts2[3].0 - x\n\t};\n\treturn Some((y0 - d, y0 + d));\n}\n\nfn solve(s1: Vec<(i32, i32)>, s2: Vec<(i32, i32)>) -> bool {\n\tlet mut xs = Vec::new();\n\tfor (x, _) in &s1 { xs.push(x); }\n\tfor (x, _) in &s2 { xs.push(x); }\n\txs.sort();\n\txs.dedup();\n\tfor x in xs {\n\t\tif let Some((lo1, hi1)) = solve_square1(&s1, *x) {\n\t\t\tif let Some((lo2, hi2)) = solve_square2(&s2, *x) {\n\t\t\t\tlet lo = if lo1 < lo2 { lo2 } else { lo1 };\n\t\t\t\tlet hi = if hi1 < hi2 { hi1 } else { hi2 };\n\t\t\t\tif lo <= hi { return true; }\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nfn main() -> io::Result<()> {\n\tlet f = io::stdin();\n\tlet mut line = String::new();\n\tf.read_line(&mut line)?;\n\tlet s1 = to_square(&line);\n\tline.clear();\n\tf.read_line(&mut line)?;\n\tlet s2 = to_square(&line);\n\tprintln!(\"{}\", if solve(s1, s2) { \"YES\" } else { \"NO\" });\n\n\tOk(())\n}\n", "lang_cluster": "Rust", "tags": ["geometry", "implementation"], "code_uid": "3faeef7dea89a41e56a7935705ec4ded", "src_uid": "f6a3dd8b3bab58ff66055c61ddfdf06a", "difficulty": 1600.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 field: Vec> = (0..10).map(|_| parse_line!(String).bytes().collect()).collect();\n let mut ok = false;\n for i in 0..10 {\n for j in 0..10 {\n if i + 5 <= 10 {\n let mut xs = 0;\n let mut os = 0;\n for d in 0..5 {\n if field[i + d][j] == b'X' {\n xs += 1;\n }else if field[i + d][j] == b'O' {\n os += 1;\n }\n }\n if os == 0 && xs >= 4 {\n ok = true;\n }\n }\n if j + 5 <= 10 {\n let mut xs = 0;\n let mut os = 0;\n for d in 0..5 {\n if field[i][j + d] == b'X' {\n xs += 1;\n }else if field[i][j + d] == b'O' {\n os += 1;\n }\n }\n if os == 0 && xs >= 4 {\n ok = true;\n }\n }\n if i + 5 <= 10 && j + 5 <= 10 {\n let mut xs = 0;\n let mut os = 0;\n for d in 0..5 {\n if field[i + d][j + d] == b'X' {\n xs += 1;\n }else if field[i + d][j + d] == b'O' {\n os += 1;\n }\n }\n if os == 0 && xs >= 4 {\n ok = true;\n }\n }\n if i + 5 <= 10 && j >= 4 {\n let mut xs = 0;\n let mut os = 0;\n for d in 0..5 {\n if field[i + d][j - d] == b'X' {\n xs += 1;\n }else if field[i + d][j - d] == b'O' {\n os += 1;\n }\n }\n if os == 0 && xs >= 4 {\n ok = true;\n }\n }\n }\n }\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": ["brute force", "implementation"], "code_uid": "483a44542893177c49a7c7c412a3b6d9", "src_uid": "d5541028a2753c758322c440bdbf9ec6", "difficulty": 1600.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_one(pos: usize, col: usize, c: &Vec) -> usize {\n let mut s = Vec::new();\n let mut result = 0;\n for i in 0..=c.len() {\n let val = if i < pos {c[i]} else if i > pos {c[i - 1]} else {col};\n if s.is_empty() {\n s.push((val, 1));\n }else if s.last().unwrap().0 == val {\n s.last_mut().unwrap().1 += 1;\n }else{\n if s.last().unwrap().1 > 2 {\n result += s.pop().unwrap().1;\n }\n if s.is_empty() {\n s.push((val, 1));\n }else if s.last().unwrap().0 == val {\n s.last_mut().unwrap().1 += 1;\n }else{\n s.push((val, 1));\n }\n }\n }\n if let Some((_col, cnt)) = s.last() {\n if *cnt > 2 {\n result += cnt;\n }\n }\n return if result > 0 {\n result - 1\n }else{\n 0\n }\n}\n\nfn solve() {\n let (n, _k, x) = parse_line!(usize, usize, usize);\n let c = parse_line_to_vec!(usize);\n let mut result = 0;\n for i in 0..=n {\n result = std::cmp::max(result, solve_one(i, x, &c));\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": ["two pointers", "brute force"], "code_uid": "833d78e31f40176f8f4cfb3bd93bc5a9", "src_uid": "d73d9610e3800817a3109314b1e6f88c", "difficulty": 1400.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "pub 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 #[allow(unused_imports)]\n use std::io::{self, BufReader, BufRead, Write, BufWriter};\n let __stdin = io::stdin();\n let __stdout = io::stdout();\n let mut __in = BufReader::with_capacity(4096, __stdin.lock());\n let mut __buf = String::new();\n let mut __out = BufWriter::with_capacity(4096, __stdout.lock());\n\n macro_rules! scanln {\n ($($var:ident : $ty:path),+) => {\n $(let $var: $ty;)+\n {\n __buf.clear();\n __in.read_line(&mut __buf).unwrap();\n let mut eles = __buf.trim().split_whitespace();\n $($var = Scan::scan(&mut eles);)+\n }\n }\n }\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 // -- PLACE SOLUTION BODY BELOW THIS LINE ------------------------------------\n\n scanln!(l: u32, r: u32, x: u32, y: u32, k: u32);\n\n let mut cost = 1;\n let mut exp = k;\n let mut found = false;\n\n while exp <= r && cost <= y {\n if exp >= l && cost >= x {\n found = true;\n break;\n }\n exp += k;\n cost += 1;\n }\n\n putln!(\"{}\", if found { \"YES\" } else { \"NO\" });\n}\n", "lang_cluster": "Rust", "tags": ["two pointers", "brute force"], "code_uid": "9742b8c2d363be47313bf936d8ce44ae", "src_uid": "1110d3671e9f77fd8d66dca6e74d2048", "difficulty": 1200.0, "exec_outcome": "PASSED"} {"lang": "Rust", "source_code": "use std::io;\nfn read_line() -> String {\n let mut buffer = String::new();\n io::stdin().read_line(&mut buffer).unwrap();\n String::from(buffer.trim())\n}\nfn read_number() -> i64 {\n read_line().parse::().unwrap()\n}\nfn read_nums() -> Vec {\n read_line().split(' ').map(|x| x.parse::().unwrap()).collect()\n}\n\nfn main() {\n let nsk = read_nums();\n let (n, s, k) = (nsk[0] as usize, nsk[1] - 1, nsk[2]);\n let candies = read_nums();\n let colors = read_line().chars().collect::>();\n let mut shortest: Vec>> = vec![vec![None; 50 * n + 1]; n];\n for i in 0..n {\n shortest[i][candies[i]] = Some((i as i64 - s as i64).abs());\n }\n for candy_num in 1..(50usize*n+1) {\n for ind in 0..n {\n if let Some(mut dist) = shortest[ind][candy_num] {\n for jnd in 0..n {\n if colors[ind] != colors[jnd] && candies[jnd] > candies[ind] {\n let total_candies = candy_num + candies[jnd];\n let path = dist + (jnd as i64 - ind as i64).abs();\n if let Some(old) = shortest[jnd][total_candies] {\n shortest[jnd][total_candies] = Some(std::cmp::min(old, path));\n } else {\n shortest[jnd][total_candies] = Some(path);\n }\n }\n }\n }\n }\n }\n let mut ans: Option = None;\n for candy_num in k..(50usize*n+1) {\n for ind in 0..n {\n if let Some(mut dist) = shortest[ind][candy_num] {\n ans = Some(\n match ans {\n Some(old_ans) => std::cmp::min(old_ans, dist),\n None => dist,\n }\n );\n }\n }\n }\n println!(\"{}\", ans.unwrap_or(-1));\n}\n", "lang_cluster": "Rust", "tags": ["dp"], "code_uid": "28ec55ff64b90a920ed3a7387b1aa37c", "src_uid": "a95e54a7e38cc0d61b39e4a01a6f8d3f", "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 { 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 n1: usize = scan.next();\n let n2: usize = scan.next();\n let _k1: usize = scan.next();\n let _k2: usize = scan.next();\n println!(\"{}\", if n2>=n1 {\"Second\"} else {\"First\"});\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", "constructive algorithms"], "code_uid": "91b7ff7e681caefc627fa9c91163eeef", "src_uid": "aed24ebab3ed9fd1741eea8e4200f86b", "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 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 if (dgt_indxs[0].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n match num_swaps_for_digits(n, 0, 0, 5, 0) {\n None => (),\n Some(x) => {\n if x < min_num_swaps {\n min_num_swaps = x;\n }\n }\n }\n } \n if (dgt_indxs[2].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n match num_swaps_for_digits(n, 5, 0, 2, 0) {\n None => (),\n Some(x) => {\n if x < min_num_swaps {\n min_num_swaps = x;\n }\n }\n }\n } \n if (dgt_indxs[7].len() >= 1) && (dgt_indxs[5].len() >= 1) {\n match num_swaps_for_digits(n, 5, 0, 7, 0) {\n None => (),\n Some(x) => {\n if x < min_num_swaps {\n min_num_swaps = x;\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": "ad80f0fa8fcf505ec07ec7dd53157231", "src_uid": "ea1c737956f88be94107f2565ca8bbfd", "difficulty": 2100.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 arr: Vec = scan.next_n(4);\n arr.sort();\n if arr[0] + arr[3] == arr[1] + arr[2] || arr[0] + arr[1] + arr[2] == arr[3] {\n println!(\"YES\");\n } else {\n println!(\"NO\");\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", "implementation"], "code_uid": "6dc69081fd130ba709b649844992ae40", "src_uid": "5a623c49cf7effacfb58bc82f8eaff37", "difficulty": 800.0, "exec_outcome": "PASSED"}