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::io::*;
use std::str::FromStr;

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

#[allow(dead_code)]
#[derive(Clone)]
struct Node {
    v: i64,
}

#[allow(dead_code)]
impl Node {
    fn new(v: i64) -> Node {
        Node { v: v }
    }
    fn default_value() -> Node {
        Node { v: 1 << 40 }
    }
}
#[allow(dead_code)]
fn merge(left: &Node, right: &Node) -> Node {
    if left.v < right.v {
        left.clone()
    } else {
        right.clone()
    }
}
// add op
#[allow(dead_code)]
fn resolve_delay(lhs: &Node, rhs: &Node) -> Node {
    Node::new(lhs.v + rhs.v)
}

#[allow(dead_code)]
#[derive(Clone)]
struct DelaySegmentTree {
    n: usize,
    max_depth: usize,
    data: Vec<Node>,
    delay_data: Vec<Node>,
    updated: Vec<bool>,
}
#[allow(dead_code)]
impl DelaySegmentTree {
    fn new(n: usize) -> DelaySegmentTree {
        let mut max_depth = 0;
        while (1 << max_depth) < n {
            max_depth += 1;
        }
        DelaySegmentTree {
            n: n,
            max_depth: max_depth,
            data: vec![Node::default_value(); 1 << (max_depth + 1)],
            delay_data: vec![Node::default_value(); 1 << (max_depth + 1)],
            updated: vec![false; 1 << (max_depth + 1)],
        }
    }
    // [left, right)
    fn range_op(&mut self, left: usize, right: usize, value: Node) {
        if right <= left || self.n <= left {
            return;
        }
        // assert!(left < right);
        // assert!(right <= self.n);
        self.in_range_op(value, 0, 1, left, right);
    }
    // [left, right)
    fn get(&mut self, left: usize, right: usize) -> Node {
        if right <= left || self.n <= left {
            return Node::new(1 << 40);
        }
        self.in_get(0, 1, left, right)
    }
    // private
    fn in_range_op(&mut self, value: Node, depth: usize, node: usize, left: usize, right: usize) {
        let width = 1 << (self.max_depth - depth);
        let index = node - (1 << depth);
        let node_left = index * width;
        let node_mid = node_left + (width >> 1);
        self.divide(node);
        if right - left == width && left == node_left {
            self.updated[node] = true;
            self.delay_data[node] = value;
            self.divide(node);
        } else {
            if right <= node_mid {
                self.in_range_op(value, depth + 1, node * 2, left, right);
                self.divide(node * 2 + 1);
            } else if node_mid <= left {
                self.divide(node * 2);
                self.in_range_op(value, depth + 1, node * 2 + 1, left, right);
            } else {
                self.in_range_op(value.clone(), depth + 1, node * 2, left, node_mid);
                self.in_range_op(value, depth + 1, node * 2 + 1, node_mid, right);
            }
            self.data[node] = merge(&self.data[node * 2], &self.data[node * 2 + 1]);
        }
    }
    fn in_get(&mut self, depth: usize, node: usize, left: usize, right: usize) -> Node {
        let width = 1 << (self.max_depth - depth);
        let index = node - (1 << depth);
        let node_left = index * width;
        let node_mid = node_left + (width >> 1);
        self.divide(node);
        if right - left == width && left == node_left {
            return self.data[node].clone();
        } else if right <= node_mid {
            return self.in_get(depth + 1, node * 2, left, right);
        } else if node_mid <= left {
            return self.in_get(depth + 1, node * 2 + 1, left, right);
        }
        merge(
            &self.in_get(depth + 1, node * 2, left, node_mid),
            &self.in_get(depth + 1, node * 2 + 1, node_mid, right),
        )
    }
    fn divide(&mut self, node: usize) {
        if !self.updated[node] {
            return;
        }
        if node < (1 << self.max_depth) {
            for i in 0..2 {
                if self.updated[node * 2 + i] {
                    self.delay_data[node * 2 + i] =
                        resolve_delay(&self.delay_data[node * 2 + i], &self.delay_data[node]);
                } else {
                    self.delay_data[node * 2 + i] = self.delay_data[node].clone();
                    self.updated[node * 2 + i] = true;
                }
            }
        }
        self.updated[node] = false;
        self.data[node] = resolve_delay(&self.data[node], &self.delay_data[node]);
    }
}

fn set_value(stree: &mut Vec<DelaySegmentTree>, index: usize, v: i64) {
    let n = stree[0].n;
    for &(i, start) in [(0, 0), (1, n - 1)].iter() {
        let d = (start as i64 - index as i64).abs();
        let prev = stree[i].get(index, index + 1).v - d;
        stree[i].range_op(index, index + 1, Node::new(v - prev));
    }
}

fn get_value(
    stree: &mut Vec<DelaySegmentTree>,
    lr: usize,
    left: usize,
    right: usize,
    next_pos: i64,
) -> i64 {
    let n = stree[0].n;
    let lr_value = [0, n - 1];
    stree[lr].get(left, right).v - (lr_value[lr] as i64 - next_pos).abs()
}

fn main() {
    let n = read::<usize>();
    let q = read::<usize>();
    let a = read::<i64>() - 1;
    let b = read::<i64>() - 1;
    let mut xseq = vec![0; q];
    for i in 0..q {
        xseq[i] = read::<i64>() - 1;
    }
    let mut index = 0;
    while index < q && (a == xseq[index] || b == xseq[index]) {
        index += 1;
    }
    if index == q {
        println!("0");
        return;
    }
    let mut stree = vec![DelaySegmentTree::new(n); 2];
    set_value(&mut stree, a as usize, (xseq[index] - b).abs());
    set_value(&mut stree, b as usize, (xseq[index] - a).abs());

    for i in index + 1..q {
        let prev_pos = xseq[i - 1];
        let next_pos = xseq[i];
        if prev_pos == next_pos {
            continue;
        }
        let mut best = 1 << 40;
        best = std::cmp::min(
            best,
            get_value(&mut stree, 1, 0, next_pos as usize, next_pos),
        );
        best = std::cmp::min(
            best,
            get_value(&mut stree, 0, next_pos as usize, n, next_pos),
        );
        set_value(&mut stree, prev_pos as usize, best);
        for j in 0..2 {
            stree[j].range_op(0, prev_pos as usize, Node::new((next_pos - prev_pos).abs()));
            stree[j].range_op(
                prev_pos as usize + 1,
                n,
                Node::new((next_pos - prev_pos).abs()),
            );
        }
        set_value(&mut stree, next_pos as usize, 1 << 40);
    }
    let mut ans = 1 << 40;
    for i in 0..n {
        ans = std::cmp::min(ans, stree[0].get(i, i + 1).v - i as i64);
    }
    println!("{}", ans);
}