//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // fn run() { input! { n: usize, s: [String; n], m: usize, x: usize, d: usize, } let mut s: Vec<(usize, String)> = s.into_iter().enumerate().collect(); s.sort_by(|a, b| a.1.cmp(&b.1)); let mut map = vec![0; n]; for i in 0..n { map[s[i].0] = i; } let mut lcp = vec![0; n - 1]; for i in 1..n { let mut len = 0u64; for (a, b) in s[i - 1].1.chars().zip(s[i].1.chars()) { if a != b { break; } len += 1; } lcp[i - 1] = len; } let mut table = vec![]; table.push(lcp); for i in 1.. { if (1 << i) > n { break; } let mut dp = vec![0; n - 1 - (1 << i) + 1]; for (j, dp) in dp.iter_mut().enumerate() { *dp = std::cmp::min(table[i - 1][j], table[i - 1][j + (1 << (i - 1))]); } table.push(dp); } let mut x = x; let mut sum = 0; for _ in 0..m { let mut i = x / (n - 1) + 1; let mut j = x % (n - 1) + 1; if i > j { std::mem::swap(&mut i, &mut j); } else { j += 1; } let l = std::cmp::min(map[i - 1], map[j - 1]); let r = map[i - 1] + map[j - 1] - l; let diff = r - l; let k = 8 * std::mem::size_of::() - diff.leading_zeros() as usize - 1; sum += std::cmp::min(table[k][l], table[k][r - (1 << k)]); x = (x + d) % (n * (n - 1)); } println!("{}", sum); } fn main() { run(); }