#[allow(unused_imports)] use std::cmp::*; #[allow(unused_imports)] use std::collections::*; use std::io::*; #[allow(dead_code)] fn getline() -> String { let mut ret = String::new(); std::io::stdin().read_line(&mut ret).ok(); return ret; } fn get_word() -> String { let mut stdin = std::io::stdin(); let mut u8b: [u8; 1] = [0]; loop { let mut buf: Vec = Vec::with_capacity(16); loop { let res = stdin.read(&mut u8b); if res.is_err() || u8b[0] <= ' ' as u8 { break; } else { buf.push(u8b[0]); } } if buf.len() >= 1 { let ret = std::string::String::from_utf8(buf).unwrap(); return ret; } } } fn parse(s: &str) -> T { s.parse::().ok().unwrap() } #[allow(dead_code)] fn get() -> T { parse(&get_word()) } fn try_sort(a: &mut [i32], k: usize, start: usize) -> i32 { let n = a.len(); if start >= n { return 0; } let steps = (n - start - 1) / k + 1; let mut cnt = 0; for i in (0 .. steps).rev() { for j in 0 .. i { let ind1 = start + j * k; let ind2 = start + (j + 1) * k; if a[ind1] > a[ind2] { let t = a[ind1]; a[ind1] = a[ind2]; a[ind2] = t; cnt += 1; } } } return cnt; } fn main() { let n: usize = get(); let k: usize = get(); let mut a: Vec = vec![0; n]; for i in 0 .. n { a[i] = get(); } let mut cnt = 0; for i in 0 .. k { cnt += try_sort(&mut a, k, i); } let mut is_sorted = true; for i in 0 .. (n - 1) { if a[i] > a[i + 1] { is_sorted = false; } } println!("{}", if is_sorted { cnt } else { -1 }); }