Problem:
Score : 900 points

Problem Statement

There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.

You have two pieces, initially placed on square A and B, respectively.
You will be asked to process Q queries of the following kind, in the order received:

Given an integer x_i, move one of the two pieces of your choice to square x_i.

Here, it takes you one second to move a piece one square.
That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.

Your objective is to process all the queries in the shortest possible time.

You may only move the pieces in response to queries, and you may not move both pieces at the same time.
Also, it is not allowed to rearrange the order in which queries are given.
It is, however, allowed to have both pieces in the same square at the same time.

Constraints

1 ≤ N, Q ≤ 200,000

1 ≤ A, B ≤ N

1 ≤ x_i ≤ N

Input

Input is given from Standard Input in the following format:

N Q A B
x_1 x_2 ... x_Q

Output

Let the shortest possible time to process all the queries be X seconds. Print X.

Sample Input 1

8 3 1 8
3 5 1

Sample Output 1

7

All the queries can be processed in seven seconds, by:

moving the piece at square 1 to 3

moving the piece at square 8 to 5

moving the piece at square 3 to 1

Sample Input 2

9 2 1 9
5 1

Sample Output 2

4

The piece at square 9 should be moved first.

Sample Input 3

9 2 1 9
5 9

Sample Output 3

4

The piece at square 1 should be moved first.

Sample Input 4

11 16 8 1
1 1 5 1 11 4 5 2 5 3 3 3 5 5 6 7

Sample Output 4

21

Solution in Rust (1.15.1) (judge verdict: Accepted)

// use std::ops::{Index, IndexMut};
// use std::cmp::{Ordering, min, max};
// use std::collections::{BinaryHeap, BTreeMap};
// use std::collections::btree_map::Entry::{Occupied, Vacant};
// use std::clone::Clone;

fn getline() -> String{
    let mut res = String::new();
    std::io::stdin().read_line(&mut res).ok();
    res
}

macro_rules! readl {
    ($t: ty) => {
        {
            let s = getline();
            s.trim().parse::<$t>().unwrap()
        }
    };
    ($( $t: ty),+ ) => {
        {
            let s = getline();
            let mut iter = s.trim().split(' ');
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*) 
        }
    };
}

macro_rules! readlvec {
    ($t: ty) => {
        {
            let s = getline();
            let iter = s.trim().split(' ');
            iter.map(|x| x.parse().unwrap()).collect::<Vec<$t>>()
        }
    }
}

macro_rules! debug {
    ($x: expr) => {
        println!("{}: {:?}", stringify!($x), $x)
    }
}

fn printiter<'a, T>(v: &'a T)
where
    &'a T: std::iter::IntoIterator, 
    <&'a T as std::iter::IntoIterator>::Item: std::fmt::Display {
    for (i,e) in v.into_iter().enumerate() {
        if i != 0 {
            print!(" ");
        }
        print!("{}", e);
    }
    println!("");
}

struct ContestPrinter {
    s: String,
}

impl ContestPrinter {
    fn new() -> ContestPrinter {
        ContestPrinter {
            s: String::new(),
        }
    }

    fn print<T>(&mut self, x: T)
        where T: std::fmt::Display {
        self.s.push_str(format!("{}", x).as_str());
    }

    fn println<T>(&mut self, x: T)
        where T: std::fmt::Display {
        self.s.push_str(format!("{}\n", x).as_str());
    }
}

impl std::ops::Drop for ContestPrinter {
    fn drop(&mut self) {
        print!("{}", self.s);
    }
}

trait Monoid {
    fn unity() -> Self;
    fn op(&self, &Self) -> Self;
}

#[derive(Clone, Debug)]
struct SegmentTree<T: Monoid + std::clone::Clone> {
    dat: Vec<T>,
    length: usize,
}

impl<T: Monoid + std::clone::Clone> SegmentTree<T> {
    fn new(n: usize) -> SegmentTree<T> {
        let mut len = 1;
        while len < n {
            len <<= 1;
        }
        SegmentTree {
            dat: vec![T::unity(); len*2],
            length: n,
        }
    }

    fn len(&self) -> usize {
        self.length
    }

    fn update(&mut self, i: usize, val: T) {
        assert!(i < self.len());
        let mut p = self.dat.len()/2-1+i;
        self.dat[p] = val;
        while p != 0 {
            p = (p-1)/2;
            self.dat[p] = self.dat[2*p+1].op(&self.dat[2*p+2]);
        }
    }

    fn query(&self, l: usize, r: usize) -> T {
        self.query_(l, r, 0, 0, self.dat.len()/2)
    }

    fn get(&self, ind: usize) -> T {
        self.dat[self.dat.len()/2+ind-1].clone()
    }

    fn query_(&self, l: usize, r: usize, i: usize, a: usize, b: usize) -> T {
        if l <= a && b <= r {
            self.dat[i].clone()
        } else if !(r <= a || b <= l) {
            let retl = self.query_(l, r, i*2+1, a, (a+b)/2);
            let retr = self.query_(l, r, i*2+2, (a+b)/2, b);
            retl.op(&retr)
        } else {
            T::unity()
        }
    }

    // fn debug(&self) {
    //     printvec(&self.dat);
    // }
    fn get_dat(&self) -> &[T] {
        &self.dat[self.dat.len()/2-1..self.dat.len()-1]
    }
}

impl Monoid for i64 {
    fn unity() -> Self {
        1_000_000_000_000_000
    }

    fn op(&self, x: &Self) -> Self {
        std::cmp::min(*self, *x)
    }
}

fn main() {
    let mut printer = ContestPrinter::new();
    let (n, q, a, b) = readl!(usize, usize, i64, i64);
    let a = a-1;
    let b = b-1;
    let x: Vec<_> = readlvec!(i64).into_iter().map(|x| x-1).collect();;
    let mut segl = SegmentTree::new(n);
    let mut segr = SegmentTree::new(n);
    segl.update(a as usize, (x[0]-b).abs() + n as i64 - a);
    segr.update(a as usize, (x[0]-b).abs() + a);
    segl.update(b as usize, (x[0]-a).abs() + n as i64 - b);
    segr.update(b as usize, (x[0]-a).abs() + b);
    let mut add = 0;
    for i in 1..q {
        // debug!(add);
        // debug!(segl.get_dat());
        // debug!(segr.get_dat());
        let tmp = std::cmp::min(segl.query(0, x[i] as usize) - (n as i64 - x[i]),
                                segr.query(x[i] as usize, n)- x[i])+add;
        add += (x[i]-x[i-1]).abs();
        let mi = std::cmp::min(tmp, segr.get(x[i-1] as usize) - x[i-1] + add);
        segl.update(x[i-1] as usize, mi - add + n as i64 - x[i-1]);
        segr.update(x[i-1] as usize, mi - add + x[i-1]);
    }
    // debug!(segl.get_dat());
    // debug!(segr.get_dat());
    let mut ans = i64::unity();
    for i in 0..n {
        ans = std::cmp::min(ans, segr.get(i)-(i as i64));
    }
    // debug!(ans);
    // debug!(add);
    ans += add;
    printer.println(ans);
}