use std::io::*; mod fenwick_tree { use std::ops::*; pub struct FenwickTree { data: Vec, identity: T, operation: F, } impl T> FenwickTree { pub fn new(size: usize, id: T, op: F) -> FenwickTree { FenwickTree { data: vec![id; size + 1], identity: id, operation: op, } } pub fn query(&self, i: usize) -> T { let mut res = self.identity; let mut idx = i as isize - 1; while idx >= 0 { res = (self.operation)(res, self.data[idx as usize]); idx = (idx & (idx + 1)) - 1; } res } pub fn update(&mut self, i: usize, x: T) { let mut idx = i; while idx < self.data.len() { self.data[idx] = (self.operation)(self.data[idx], x); idx |= idx + 1; } } } } fn main() { let mut s: String = String::new(); std::io::stdin().read_to_string(&mut s).ok(); let mut itr = s.trim().split_whitespace(); let n: usize = itr.next().unwrap().parse().unwrap(); let k: usize = itr.next().unwrap().parse().unwrap(); let a: Vec = (0..n) .map(|_| itr.next().unwrap().parse().unwrap()) .collect(); let mut b = a.clone(); b.sort(); b.dedup(); let mut c = std::collections::HashMap::new(); for i in 0..b.len() { c.insert(b[i], i); } let mut set: Vec> = vec![Vec::new(); k]; for i in 0..n { set[i % k].push(c[&a[i]]); } let mut ans = 0; for i in 0..set.len() { let mut bit = fenwick_tree::FenwickTree::new(1010, 0, |a, b| a + b); for j in 0..set[i].len() { ans += j - bit.query(set[i][j]); bit.update(set[i][j], 1); } set[i].sort(); } let mut ok = true; for i in 0..set[0].len() { for j in 0..set.len() - 1 { if set[j + 1].len() <= i { break; } if set[j][i] > set[j + 1][i] { ok = false; break; } } if !ok { break; } } if ok { println!("{}", ans); } else { println!("-1"); } }