Problem:
Leapfrog

Problem Statement

N 個のマスが円状に並んでいる。マスは時計回りに 1,\ 2,\ ... ,\ N と番号が振られている。各 i (1 ≤ i ≤ N−1) について、i 番目のマスと i+1 番目のマスは隣り合う。また、N 番目のマスと 1 番目のマスは隣り合う。

これらのうち M 個のマスには、互いに区別できない駒が 1 個ずつ置かれている。はじめ、x_1,\ x_2,\ ... ,\ x_M 番目のマスに駒が置かれている。次の操作を何回か行い、y_1,\ y_2,\ ... ,\ y_M 番目のマスに駒が置かれているようにしたい。

時計回りまたは反時計回りに連続する 3 個のマスを選び、順に A,\ B,\ C とおく。A と B にそれぞれ駒があり C に駒がないならば、A の駒を C へ移動する。

y_1,\ y_2,\ ... ,\ y_M 番目のマスに駒が置かれているようにできるか判定せよ。できるならば、必要な操作の回数の最小値を求めよ。

Constraints

3 ≤ N ≤ 3,000

1 ≤ M ≤ N

1 ≤ x_1<x_2< ... <x_M ≤ N

1 ≤ y_1<y_2< ... <y_M ≤ N

Input Format

入力は以下の形式で標準入力から与えられる。

N M
x_1 x_2 ... x_M
y_1 y_2 ... y_M

Output Format

y_1,\ y_2,\ ... ,\ y_M 番目のマスに駒が置かれているようにできるならば、必要な操作の回数の最小値を一行に出力せよ。できないならば、代わりに -1 を一行に出力せよ。

Sample Input 1

7 2
1 2
5 6

Sample Output 1

3

次のように 3 回の操作を行えばよい。

2 番目のマスの駒を 7 番目のマスへ移動する。

1 番目のマスの駒を 6 番目のマスへ移動する。

7 番目のマスの駒を 5 番目のマスへ移動する。

Sample Input 2

3 1
1
2

Sample Output 2

-1

Sample Input 3

2999 3
1 2 3
2 3 4

Sample Output 3

4491004

Solution in Rust (judge verdict: Accepted)

extern crate core;

use std::fmt;
use std::cmp::{Ordering, min, max};
use std::fmt::{Display, Error, Formatter};
use std::ops::{Index, IndexMut};
use std::collections::VecDeque;

fn show<T: Display>(vec: &Vec<T>) {
    if vec.is_empty() {
        println!("[]");
    }else {
        print!("[{}", vec[0]);
        for i in 1 .. vec.len() {
            print!(", {}", vec[i]);
        }
        println!("]");
    }
}
fn show_ring_reader<T: Display>(ring: &RingReader<T>) {
    if ring.size == 0 {
        println!("[]");
    }else {
        print!("[{}", ring[0]);
        for i in 1 .. ring.size {
            print!(", {}", ring[i]);
        }
        println!("]");
    }
}
fn show_ring_vector<T: Display>(ring: &RingVector<T>) {
    if ring.size == 0 {
        println!("[]");
    }else {
        print!("[{}", ring[0]);
        for i in 1 .. ring.size {
            print!(", {}", ring[i]);
        }
        println!("]");
    }

}
macro_rules! read_line{
    () => {{
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).ok();
        line
    }};
    (delimiter: ' ') => {
        read_line!().split_whitespace().map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (delimiter: $p:expr) => {
        read_line!().split($p).map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (' ') => {
        read_line!(delimiter: ' ')
    };
    ($delimiter:expr) => {
        read_line!(delimiter: $delimiter)
    };
    (' '; $ty:ty) => {
        read_line!().split_whitespace().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
    ($delimiter:expr; $ty:ty) => {
        read_line!($delimiter).into_iter().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
}
macro_rules! let_all {
    ($($n:ident:$t:ty),*) => {
        let line = read_line!(delimiter: ' ');
        let mut iter = line.iter();
        $(let $n:$t = iter.next().unwrap().parse().ok().unwrap();)*
    };
}

struct RingVector<T> {
    vec: Vec<T>,
    size: usize
}
impl <T> RingVector<T> {
    fn new(vector: Vec<T>) -> RingVector<T> {
        let size = vector.len();
        RingVector{vec: vector, size: size}
    }
}
impl <T> Index<usize> for RingVector<T> {
    type Output = T;
    fn index(&self, index: usize) -> &Self::Output {
        &self.vec[(index % self.size) % self.size]
    }
}
impl <T> IndexMut<usize> for RingVector<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.vec[(index % self.size) % self.size]
    }
}

fn reversed<T: Copy>(vec: &Vec<T>) -> Vec<T> {
    let mut rev = Vec::with_capacity(vec.len());
    for v in vec.iter().rev() {
        rev.push(*v);
    }
    rev
}
fn main(){
    let_all!(n: usize, m: usize);
    if n == m {
        println!("0");
        return
    }
    let mut before = RingVector::<usize>::new(vec![0; n]);
    let mut after = RingVector::<usize>::new(vec![0; n]);
    for x in read_line!(' '; usize) {
        before[x - 1] = 1;
    }
    for y in read_line!(' '; usize) {
        after[y - 1] = 1;
    }
    for i in 0 .. n {
        if before[i] == 0 {
            for j in 1 .. n {
                if before[n + i - j] == 1 {
                    before[n + i - j] += before[n + i - j + 1]
                }
            }
            break
        }
    }
    for i in 0 .. n {
        if after[i] == 0 {
            for j in 1 .. n {
                if after[n + i - j] == 1 {
                    after[n + i - j] += after[n + i - j + 1]
                }
            }
            break
        }
    }
    let mut before_state = Vec::new();
    let mut after_state = Vec::new();
    for i in 0 .. n {
        if before[i] == 0 {
            if before[i + 1] % 2 == 0 {
                before_state.push(State::E{position: i})
            }
        }else if before[i] % 2 == 0 {
            before_state.push(State::PP{position: i})
        }else if before[i + n - 1] == 0 {
            before_state.push(State::EP{position: i})
        }
        if after[i] == 0 {
            if after[i + 1] % 2 == 0 {
                after_state.push(State::E{position: i})
            }
        }else if after[i] % 2 == 0 {
            after_state.push(State::PP{position: i})
        }else if after[i + n - 1] == 0 {
            after_state.push(State::EP{position: i})
        }
    }
    let before = RingReader::new(&before_state);
    let b_rev = reversed(&before_state);
    let before_rev = RingReader::new(&b_rev);
    let after = RingReader::new(&after_state);
    let a_rev = reversed(&after_state);
    let after_rev = RingReader::new(&a_rev);
    let clockwise = solve(&before, &after, n, false);
    let counter_clockwise = solve(&before_rev, &after_rev, n, true);
    if clockwise == -1 || counter_clockwise == -1 {
        println!("{}", max(clockwise, counter_clockwise));
    }else {
        println!("{}", min(clockwise, counter_clockwise));
    }
}
fn abs(value: i32) -> i32 {
    if value > 0 {
        value
    }else {
        -value
    }
}
#[derive(Copy, Clone)]
enum State {
    E{position: usize}, EP{position: usize}, PP{position: usize}
}
impl Display for State {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match self {
            &State::E{position: p} => write!(f, "E({})", p),
            &State::PP{position: p} => write!(f, "PP({})", p),
            &State::EP{position: p} => write!(f, "EP({})", p),
        }
    }
}
impl State {
    fn is_pp(&self) -> bool {
        match self {
            &State::PP {position:_} => true,
            _ => false
        }
    }
    fn is_ep(&self) -> bool {
        match self {
            &State::EP {position:_} => true,
            _ => false
        }
    }
    fn is_e(&self) -> bool {
        match self {
            &State::E {position:_} => true,
            _ => false
        }
    }
    fn is_same_type(&self, other: &Self) -> bool {
        match (self, other) {
            (&State::PP{position:_}, &State::PP{position:_}) => true,
            (&State::EP{position:_}, &State::EP{position:_}) => true,
            (&State::E{position:_}, &State::E{position:_}) => true,
            _ => false
        }
    }
    fn pos(&self) -> usize {
        match self {
            &State::PP{position: p} => p,
            &State::EP{position: p} => p,
            &State::E{position: p} => p,
        }
    }
}
struct RingReader<'a, T: 'a> {
    origin: usize,
    vec: &'a Vec<T>,
    size: usize,
}
impl <'a, T> RingReader<'a, T> {
    fn new(vec: &Vec<T>) -> RingReader<T> {
        RingReader {origin: 0, vec: vec, size: vec.len()}
    }
    fn shift(&mut self, new_origin: usize) {
        self.origin = new_origin;
    }
    fn shifted(&self, new_origin: usize) -> RingReader<T> {
        RingReader{origin: new_origin, vec: &self.vec, size: self.size}
    }
}
impl <'a, T> Index<usize> for RingReader<'a, T> {
    type Output = T;
    fn index(&self, index: usize) -> &Self::Output {
        &self.vec[((self.origin + index) % self.vec.len() + self.vec.len()) % self.vec.len()]
    }
}
fn can_make_by_position(before: &RingReader<State>, after: &RingReader<State>) -> bool {
    if !before[0].is_same_type(&after[0]) {
        false
    }else {
        let mut b = 0;
        let mut a = 0;
        while b < before.size && a < after.size {
            if !before[b].is_same_type(&after[a]) {
               return false
            }
            b += 1;
            a += 1;
            while b < before.size && before[b].is_pp() {
                b += 1;
            }
            while a < after.size && after[a].is_pp() {
                a += 1;
            }
        }
        a == b
    }
}
fn can_make_by_accumulate(before: &RingReader<State>, after: &RingReader<State>) -> bool {
    if before.size != after.size {
        false
    }else {
        let mut be = 0;
        let mut bep = 0;
        let mut bpp = 0;
        let mut ae = 0;
        let mut aep = 0;
        let mut app = 0;
        for i in 0 .. before.size {
            match before[i] {
                State::E{position:_} => be += 1,
                State::EP {position:_} => bep += 1,
                State::PP {position:_} => bpp += 1,
            }
            match after[i] {
                State::E{position:_} => ae += 1,
                State::EP {position:_} => aep += 1,
                State::PP {position:_} => app += 1,
            }
        }
        be == ae && bep == aep && bpp == app
    }
}
fn solve(before: &RingReader<State>, after: &RingReader<State>, length: usize, is_counter_clock_wise: bool) -> i32 {
    if !can_make_by_accumulate(&before, &after) {
        return -1
    }
    let mut start = 0;
    for i in 0 .. before.size {
        if !before[i].is_pp() {
            start = i;
            break
        }
    }
    let before = before.shifted(start);
    //show_ring_reader(&before);
    //show_ring_reader(&after);
    let mut min_cost = std::i32::MAX;
    for i in 0 .. after.size {
        if can_make_by_position(&before, &after.shifted(i)) {
            let after = after.shifted(i);
            let distance = if !is_counter_clock_wise {
                ((length + after[0].pos() - before[0].pos()) % length) as i32
            }else {
                ((length + before[0].pos() - after[0].pos()) % length) as i32
            };
            if distance % 2 == 1 {
                continue;
            }
            let mut pp_count = 0 as i32;
            let mut temp_cost = 0;
            let mut deque = VecDeque::with_capacity(before.size);
            for i in 0 .. before.size {
                match before[i] {
                    State::PP {position:_} if pp_count * 2 < distance => {
                        temp_cost += deque.len() as i32;
                        pp_count += 1;
                    },
                    _ => deque.push_back(before[i]),
                }
            }
            if pp_count * 2 < distance {
                if pp_count != 0 {
                    temp_cost += (distance / 2 - pp_count) * deque.len() as i32;
                }else {
                    continue
                }
            }
            for _ in 0 .. pp_count {
                deque.push_back(State::PP {position: 0});
            }
            let mut before_no_pp_count = 0;
            let mut after_no_pp_count = 0;
            for i in 0 .. after.size {
                if after[i].is_pp() {
                    while let Some(f) = deque.pop_front() {
                        if f.is_pp() {
                            break
                        }else {
                            before_no_pp_count += 1;
                        }
                    }
                    temp_cost += abs(before_no_pp_count as i32 - after_no_pp_count as i32);
                }else {
                    after_no_pp_count += 1;
                }
            }
            if min_cost > temp_cost {
                min_cost = temp_cost;
            }
        }
    }
    if min_cost == std::i32::MAX {
        -1
    }else{
        min_cost
    }
}