#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MOD1 1000000007
#define MOD2 998244353
#define LIMIT1 200002
#define LIMIT2 500002
typedef long long ll;
typedef long double ld;
typedef const void cv;
#define rep(i,n) for((i)=0;(i)<(n);(i)++)
#define per(i,n) for((i)=(n)-1;(i)>=0;(i)--)
#define max(a,b) ((a)>(b) ? (a) : (b))
#define min(a,b) ((a)<(b) ? (a) : (b))
#define zt(a,b) (max((a),(b))-min((a),(b)))
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll nPr(int n,int r){ll i,result=1;rep(i,r){result*=(ll)(n-i);}return result;}
ll nCr(int n,int r){ll i,result=1;if(n<r) return 0;rep(i,min(r,n-r)){result*=(ll)(n-i);result/=(ll)(i+1);}return result;}
#define nHr(n,r) nCr((int)((n)+(r)+1),(int)(r))
#define sankaku(x) (((x)*((x)+1))/2)
int dx[8]={1,0,-1,0,1,-1,-1,1};
int dy[8]={0,1,0,-1,1,1,-1,-1};
int upint(const void *a, const void *b) { return *(int *)a < *(int *)b ? -1 : *(int *)a > *(int *)b ? 1 : 0; }
int downint(const void *a, const void *b) { return *(int *)a < *(int *)b ? 1 : *(int *)a > *(int *)b ? -1 : 0; }
int upchar(const void* left, const void* right) {return strcmp((char *)left,(char *)right);}
int downchar(const void* left, const void* right) {return strcmp((char *)right,(char *)left);}
ll modpow(ll a, ll n, ll mod) {
    ll res = 1;
    while (n > 0) {
        if (n & 1){
            res *= a; if(mod>=1) res %= mod;
        }
        a *= a; if(mod>=1) a %= mod;
        n >>= 1;
    }
    return res;
}
void initialize(){

}
int main(void){
  initialize();
  ll n,m,i,j,k,result=0;
  int a[LIMIT2]={0};
  char s[LIMIT1];
  char t[LIMIT1];

  scanf("%s",s);
  scanf("%s",t);
  n = strlen(s);
  m = strlen(t);
  if(strncmp(s,t,n)==0&&n+1==m) printf("Yes");
  else printf("No");

  return 0;
}


#include<stdio.h>
int main()
{
	char s[20], t[20];
	scanf("%s%s", s, t);
	int i;
	for (i = 0; s[i] != '\0'; i++)
	{
		if (s[i] != t[i])
		{
			printf("No\n");
			return 0;
		}
	}
	if (t[i + 1] != '\0')
		printf("No\n");
	else
		printf("Yes\n");
	return 0;
}


#include<stdio.h>
int main(){
    char s[11], t[11];
    scanf("%s%s",s,t);
    int ans = 0;
    int i;
    for(i = 0; s[i]; i++)
        if(s[i] == t[i])
            ans ++;
    if(i == ans){
        printf("Yes");
    }
    else{
        printf("No");
    }
    printf("\n");
    return 0;
}


#include <stdio.h>
#include <string.h>

int main() {
    char s[10],t[11];
    scanf("%s",s);
    scanf("%s",t);
    for(int i = 0;i < strlen(s);i++) {
        if(s[i] != t[i]) {
            printf("No");
            return 0;
        }
    }
    printf("Yes");
    return 0;
}


int main(void) {
	// your code goes here
	int	S,T,Z;
	scanf("%d",&S,&T,&Z);
	if(S+Z==T)
	printf("Yes");
	else
	printf("No");
	return 0;
}


int main(void) {
	// your code goes here
	int	S,T;
	scanf("%d",&S,&T);
	if(S+1==T)
	printf("Yes");
	else
	printf("No");
	return 0;
}


function Main(input){
  input = input.split("\n");
  console.log(input[0]==input[1].slice(0,input[1].length-1)?"Yes":"No")

}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


function main(lines) {
    const input = lines.split('\n')
    const S = input[0]
    const T = input[1].split('')
    const beforeT = T.slice(0,T.length-1).join('')

    if(S.length + 1 === T.length && S === beforeT){
        console.log('Yes')
    } else {
        console.log('No')
    }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


fs = require('fs');
input = fs.readFileSync('/dev/stdin', 'utf8');
tmp = input.split("\n");
reg = new RegExp("^" + tmp[0] + "[a-z]+$");
if(tmp[1].match(reg)) r='Yes'; else r='No';
console.log(r);


const main = stdin => {
  const [A, B, C, K] = stdin.trim().split(' ').reduce((acc, value) => {
    acc.push(parseInt(value))
    return acc
  }, [])

  if (A >= K) {
    console.log(K)
  } else if (B >= K - A) {
    console.log(A)
  } else {
    console.log(A - (K - A - B))
  }
}

// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))


let input = require("fs").readFileSync("/dev/stdin", "utf8")

function main() {
    const [S,T] = load(2,1,String)
    return T.startsWith(S) && T.length === S.length + 1
}

/*

入力値を読み込む
load(rows = 1, cols = 1, type = Number)

TruthyならYes, FalsyならNo
yesno(boolean) => String

数列の和
array_sum(numbers) => Number

対無限ループ安全装置
inifinite_loop_preventer(max = 1e5)

配列の中から最大値を返す
array_max(numbers, initial_value = null) => Number

配列の中から最小値を返す
array_min(numbers, initial_value = null) => Number

オブジェクトのスナップショットをconsole.logする
log_obj(value)

nを素因数分解
math_prime_factors(n) => { 素数: n乗 }

2次元配列を作る
new_array_2d(x_len, y_len = 0, init_value = 0) => [[]]

最大公約数
gcd(a, b) => Number

最小公倍数
lcm(a,b) => Number

*/

// console.time()
let inputs = input.split(/[\s\n]/)
let inifinite_loop_prevent_counter = 0
let result = main()
if(result === undefined) {
    console.warn("result is undefined")
} else {
    console.log(result)
}
// console.timeEnd()

// 入力値を読み込む
function load(rows = 1, cols = 1, type = Number) {
    const length = rows * cols
    let result = inputs.splice(0, length)

    if(type !== String) result = result.map(type)
    if(cols > 1) {
        const arrays = new Array(cols)
        for(let col = 0; col < cols; col++) {
            arrays[col] = new Array()
            for(let row = 0; row < rows; row++) {
                arrays[col].push(result[row * cols + col])
            }
        }
        result = arrays
    }

    return result
}

// TruthyならYes, FalsyならNo
function yesno(value) {
    return value ? 'Yes' : 'No'
}

// 数列の和
function array_sum(numbers) {
    return numbers.reduce((acc, cur) => acc + cur, 0)
}

// 対無限ループ安全装置
function inifinite_loop_preventer(max = 1e5) {
    inifinite_loop_prevent_counter++
    if(inifinite_loop_prevent_counter >= max) {
        throw new Error("Infinite loop")
    }
}

// 配列の中から最大値を返す
function array_max(numbers, initial_value = null) {
    let result = (initial_value === null) ? numbers[0] : initial_value
    for(const n of numbers) if(n > result) result = n
    return result
}

// 配列の中から最小値を返す
function array_min(numbers, initial_value = null) {
    let result = (initial_value === null) ? numbers[0] : initial_value
    for(const n of numbers) if(n < result) result = n
    return result
}

// オブジェクトのスナップショットをconsole.logする
function log_obj(value) {
    console.log(JSON.parse(JSON.stringify(value)))
}

// 素因数分解 { 素数: n乗 }
function math_prime_factors(n) {
    const result = {}

    for(let i = 2; i * i <= n; i++) {
        if(n % i === 0) {
            n /= i
            result[i] = 1

            while(n % i === 0) {
                n /= i
                result[i]++
            }
        }
    }

    if(n > 1) result[n] = 1

    return result
}

// 2次元配列を作る
function new_array_2d(x_len, y_len = 0, init_value = 0) {

    const array = new Array()
    for(let i = 0; i < x_len; i++) {
        const y = y_len ? new Array(y_len).fill(init_value) : new Array()
        array.push(y)
    }

    return array
}

// 最大公約数
function gcd(a, b) {
    if(b === 0) return a
    return gcd(b, a % b)
}

// 最小公倍数
function lcm(a,b) {
    const g = (n, m) => m ? g(m, n % m) : n
    return a * b / g(a, b)
}


"use strict"

const Main =(input)=> {
	let input = input.split("\n");
	if(input[0] === input[1].substring(0, input[1].length - 1)){
    	console.log('Yes');
    } else {
      	console.log('No');
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main

import (
	"fmt"
	"strings"
)

func main() {
	var s, t string
	fmt.Scanf("%s", &s)
	fmt.Scanf("%s", &t)
	if strings.HasPrefix(t, s) {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


package main

import (
  "os"
  "fmt"
  "io/ioutil"
  "strings"
)

var (
  S string
  T string
)

func scan() {
  all, err := ioutil.ReadAll(os.Stdin)
  if err != nil {
    panic(err)
  }

  st := strings.Split(string(all), "\n")
  S = st[0]
  T = st[1]
}

func test() {
  Td := T[:len(T)-1]
  if S == Td {
    fmt.Println("Yes")
  } else {
    fmt.Println("No")
  }
}

func main() {
  scan()
  test()
}


package main

import (
	"fmt"
)

func main() {
	var s string
	var t string

	fmt.Scan(&s)
	fmt.Scan(&t)

	if s == t[0:len(s)] {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	var s, t string
	_, _ = fmt.Scanf("%s", &s)
	_, _ = fmt.Scanf("%t", &t)

	fmt.Println(answer167A(s, t))
}

func answer167A(s string, t string) string {
	tLength := utf8.RuneCountInString(t)

	if t[:tLength-1] == s {
		return "Yes"
	}
	return "No"
}


package main

import "fmt"

func main() {
	var a, b, c, k int
	fmt.Scanf("%d %d %d %d", &a, &b, &c, &k)
	if a >= k {
		fmt.Println(k)
	} else if a+b >= k {
		fmt.Println(a)
	} else {
		fmt.Println(a - (k - a - b))
	}
}


package main

import "fmt"

func main() {
	var s, t string
	fmt.Scan(&s, &t)
	if t == s[0:len(t)] {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


s = gets.chomp
t = gets.chomp.chop
if s == t
  puts "Yes"
else
  puts "No"
end


S = gets.chomp
T = gets.chomp.chop
puts(T==S ? 'Yes' : 'No')


S = $stdin.gets.strip
T = $stdin.gets.strip
SLen = S.length
TLen = T.length
if 1 <= SLen && SLen <= 10 && TLen == SLen + 1 && T.start_with?(S)
  puts "Yes"
else
  puts "No"
end


first = gets
second = gets
slice = second.slice(0..-2)
puts first == slice ? 'Yes' : 'No'


a = gets
puts a


puts gets.chomp==gets.chomp.chop ?'Yes':'No'


extern crate proconio;

use proconio::*;
use proconio::marker::Chars;

fn main() {
    input! {
        s: Chars,
        t: Chars,
    }
    let n = s.len();
    for i in 0..n {
        if s[i] != t[i] {
            println!("No");
            return;
        }
    }
    println!("Yes");
}


fn main() {
  proconio::input! {
    s: String,
    t: String,
  };
  let ans = if s.len() + 1 == t.len() && s == t[0..s.len()] { "Yes" } else { "No" };
  println!("{}", ans);
}


use proconio::input;

fn main() {
    input! {
        s: String,
        t: String,
    };

    if t.starts_with(&s) {
        println!("Yes");
    } else {
        println!("No");
    }
}


use proconio::input;

fn main() {
    input! {
        s: String,
        t: String
    }

    solve(&s, &t);
}

fn solve(s: &String, t: &String) {
    if s.eq(&t[..t.len()]) {
        println!("Yes");
    } else {
        println!("No");
    }
}


use proconio::input;
use proconio::marker::Chars;

fn main() {
	input! {
		s: Chars,
		t: Chars,
	}
	for i in 0..s.len() - 1 {
		if s[i] == t[i] {
			continue;
		} else {
			println!("No");
			return;
		}
	}
	println!("Yes");
}


fn main() {
    let (k, s) = read();
    let s = solve(&k, &s);
    write(s);
}

fn read() -> (String, String) {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();

    let mut t = String::new();
    std::io::stdin().read_line(&mut t).ok();

    (s, t)
}

fn write(b: bool) {
    println!("{}", if b {"Yes"} else {"No"});
}

fn solve(s: &str, t: &str) -> bool {
    s == &t[0..(t.len() - 2)]
}


let S = readLine()!
let T = readLine()!
let index = T.endIndex
if(S == T[T.startIndex..<T.index(before: index)]){
  print("Yes")
}else{
  print("No")
}


let str1 = readLine()!
    let str2 = readLine()!

    let charArr = str2.map{($0)}
    var str: String = ""

    var s: Int = 0

    for i in 0 ..< charArr.count {

      str += String(charArr[i])

      if str == str1 {

        s += 1
        break
      }

    }

    if s == 1 {
      print("Yes")
    } else {
      print("No")
    }


let s = readLine()!
let t = readLine()!
let prefix = t.prefix(s.count)
print(s == prefix ? "Yes" : "No")


import Foundation

let input_line: String = readLine()!
let split: [String] = input_line.components(separatedBy: " ")

let S = String(input_line)
let T = String(input_line)

if (String("T").dropLast()=="S"){
    print("Yes")
}else{
    print("No")
}


import Foundation

let input_line: String = readLine()!
let split: [String] = input_line.components(separatedBy: " ")

let S = String(input_line)
let T = String(input_line)
var x = String(input_line)

if (String("T").dropLast()=="S"){
    print("Yes")
}else{
    print("No")
}


import Foundation

let input_line: String = readLine()!
let split: [String] = input_line.components(separatedBy: " ")

let S = String(input_line)
let T = String(input_line)
var x = String(input_line)

if ("T"=="S"+"x"){
    print("Yes")
}else{
    print("No")
}


"use strict";
const Main = (input) =>{
   let xs = input.trim().split('\n');
   let X = xs[0].split('');
   let Y = xs[1].split('');
   Y.pop();
   let count = 0
   for(let i=0; i<Y.length; i++){
     if(X[i]==Y[i]){
   	  count++;
     }
   }
   if(X.length==count){
     console.log('Yes');
   }else{
     console.log('No');
   }

}
Main(require('fs').readFileSync('/dev/stdin','utf8'));


function Main(input) {
    let s = input.split("\n");
    let r = RegExp(s[0] + '[a-z]');
    (/[a-z]{0,10}/.test(s[0]) && r.test(s[1])) ? console.log('Yes') : console.log('No');
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


import * as fs from 'fs';

const input = fs.readFileSync('/dev/stdin', 'utf8').split('\n');
const s = input[0];
const t = input[1];
console.log(s == t.slice(0, -1) ? 'Yes' : 'No');


import { isRegExp } from "util";

class AtCoder {
  // 入力系
  input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);
  input_i=-1;

  n(){
    this.input_i++;
    return Number(this.input[this.input_i]);
  }
  nn(n:number):number[]{
    const a=[];
    for(let i=0;i<n;i++){
      a.push(this.n());
    }
    return a;
  }
  s(){
    this.input_i++;
    return String(this.input[this.input_i]);
  }
  ss(n:number):string[]{
    const a=[];
    for(let i=0;i<n;i++){
      a.push(this.s());
    }
    return a;
  }

  // コンソール
  o(...a:any){
    console.log(...a);
  }

  // Math
  abs(a:number){
    return Math.abs(a);
  }
  min(...a:number[]){
    return Math.min(...a);
  }
  max(...a:number[]){
    return Math.max(...a);
  }
  floor(a:number){
    return Math.floor(a);
  }
  ceil(a:number){
    return Math.ceil(a);
  }
  round(a:number){
    return Math.round(a);
  }

  // ソート
  asc(ar:number[]){
    const t=[...ar];
    ar.sort((a,b)=>{return a-b});
  }
  desc(ar:number[]){
    const t=[...ar];
    ar.sort((a,b)=>{return b-a});
  }

  // 自作
  gcd(...arr:number[]):number{
    for(let i=0;i<arr.length-1;i++){
      let [x,y]=[arr[i],arr[i+1]];
      while(y){
        [x,y]=[y,x%y];
      }
      arr[i+1]=x;
    }
    return arr[arr.length-1];
  };
  lcm(...arr:number[]):number{
    for(let i=0;i<arr.length-1;i++){
      let [x,y]=[arr[i],arr[i+1]];
      while(y){
        [x,y]=[y,x%y];
      }
      arr[i+1]=arr[i]*arr[i+1]/x;
    }
    return arr[arr.length-1];
  };
  isPrime(n:number):boolean{
    if(n < 2) return false;
    const suq=Math.sqrt(n);
    for(let i=2;i<=suq;i++){
      if(n%i==0){
        return false;
      }
    }return true;
  };
  deduplicate(a:any[]):any[]{
    return Array.from(new Set(a));
  };
  f(roop:number, callback:any){
    for(let i=0;i<roop;i++){
      callback(i);
    }
  };
  Yes(){
    console.log('Yes');
  }
  No(){
    console.log('No');
  }
  YES(){
    console.log('YES');
  }
  NO(){
    console.log('NO');
  }
}
const m = () => {
  const o = new AtCoder();
  let s = o.s()
  let a = o.s()
  if(a.slice(0, a.length) == s) {
    o.Yes()
  }else{
    o.No()
  }
}
m();


    // inputに入力データ全体が入る
    function Main(inputString: string) {
        // 1行目がinput[0], 2行目がinput[1], …に入る
		let arrInputString = inputString.trim().split("\n");
		let a = arrInputString[0]
		let b = arrInputString[1]
		// StartWithする
		let isStartWith = b.startsWith(a)

		// lengthが+1か比較する
		let isPlusOne = (b.length - a.length == 1)
		// 最後の文字が英数字か確認する
		const regex = RegExp('^[A-Za-z0-9]*$');
		let isAlphanumeric = regex.test(b)

		//出力

    	if(isStartWith && isPlusOne && isAlphanumeric){
			console.log('Yes')
		}else {
			console.log('No')
		};
    }
    //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
	//Main(require("fs").readFileSync("/dev/stdin", "utf8"));


    // inputに入力データ全体が入る
    function Main(inputString: string) {
        // 1行目がinput[0], 2行目がinput[1], …に入る
		let arrInputString = inputString.trim().split("\n");
		let a = arrInputString[0]
		let b = arrInputString[1]
		// StartWithする
		let isStartWith = b.startsWith(a)

		// lengthが+1か比較する
		let isPlusOne = (b.length - a.length == 1)
		// 最後の文字が英数字か確認する
		const regex = RegExp('^[A-Za-z0-9]*$');
		let isAlphanumeric = regex.test(b)

		//出力

    	console.log(isStartWith && isPlusOne && isAlphanumeric);
    }
    //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
	//Main(require("fs").readFileSync("/dev/stdin", "utf8"));


def main():
    N, M, *X = map(int, open(0).read().split())
    X = sorted(set(X))
    D = [j - i for i, j in zip(X, X[1:])]
    D.sort()
    print(0 if M <= N else sum(D[:M - N]))
    return

main()


n, m, *x = map(int, open(0).read().split())
if n >= m:
  print(0)
  quit()
x = sorted(set(x))
lst = [j - i for i, j in zip(x, x[1:])]
lst.sort(reverse=1)
s = sum(lst[n - 1:])
print(s)


# ABC117C - Streamline
def main():
    N, M, *X = map(int, open(0).read().split())
    X = sorted(set(X))
    dist = [j - i for i, j in zip(X, X[1:])]
    dist.sort(reverse=1)
    ans = sum(dist[N - 1 :])
    print(ans)

if __name__ == "__main__":
    main()


n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))
d = []
if m==1:
    print(0)
elif n>=m:
    print(1)
elif n<m:
    for i in range(m-1):
        d.append(x[i+1] - x[i])
    print(sum(sorted(d)[:m-n]))


n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))
d = []
if n>=m or m==1:
    print(1)
elif n<m:
    for i in range(m-1):
        d.append(x[i+1] - x[i])
    print(sum(sorted(d)[:m-n]))


n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))
d = []
if n>=m or n==1:
    print(1)
elif n<m:
    for i in range(m-1):
        d.append(x[i+1] - x[i])
    print(sum(sorted(d)[:-(n-1)]))


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int m = in.readInt();

            n = Math.min(n, m);

            int[] x = in.readIntArray(m);
            Arrays.sort(x);

            int[] diff = new int[m - 1];
            for (int i = 0; i < m - 1; i++) {
                diff[i] = x[i + 1] - x[i];
            }
            Arrays.sort(diff);

            long ans = 0;
            for (int i = 0; i < m - n; i++) {
                ans += diff[i];
            }

            out.printLine(ans);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int[] readIntArray(int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = readInt();
            }
            return array;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void printLine(long i) {
            writer.println(i);
        }

    }
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {
		FastScanner scan = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt();
		int m = scan.nextInt();

		int[] a = new int[m];
		int i;
		for(i = 0; i < m; i++)
			a[i] = scan.nextInt();
		if(n >= m) {
			System.out.println(0);
			return;
		}
		Arrays.sort(a);

		int[] sub = new int[m - 1];
		for(i = 0; i < m - 1; i++)
			sub[i] = a[i + 1] - a[i];

		Arrays.sort(sub);

		long sum = 0;
		for(i = 0; i < (m - 1) - (n - 1); i++)
			sum += sub[i];

		out.print(sum);

		out.close();
	}
	static public long gcd(long a, long b) {
		if(b == 0)
			return a;

		return gcd(b, a % b);
	}
}
class cal{
	long mod;

	cal(long x){
		this.mod = x;
	}
	long mpow(long x, long n) {
		if(n == 0)
			return 1;
		if(n % 2 == 0) {
			long root = mpow(x, n / 2);
			return root * root % mod;
		}else {
			return x * mpow(x, n - 1) % mod;
		}
	}

	long mcomb(long a, long b) {
		if(b > a - b)
			return mcomb(a, a - b);
		long m = 1;
		long d = 1;
		long i;
		for(i = 0; i < b; i++) {
			m *= (a - i);
			m %= mod;
			d *= (i + 1);
			d %= mod;
		}
		long ans = m * mpow(d, mod - 2) % mod;

		return ans;
	}
}
class unionFind{
	int[] par;
	int[] size;

	unionFind(int x){
		this.par = new int[x + 1];
		this.size = new int[x + 1];

		int i;
		for(i = 0; i <= x; i++)
			this.par[i] = i;
		Arrays.fill(this.size, 1);
	}

	int root(int x) {
		int r = x;
		while (r != this.par[r]) {
	        r = this.par[r];
	      }

		return r;
	}

	void union(int x, int y) {
		int rx = root(x);
		int ry = root(y);
		if(rx == ry)
			return;

		if(this.size[rx] < this.size[ry]) {
			this.size[ry] += this.size[rx];
			this.par[rx] = ry;
		}else {
			this.size[rx] += this.size[ry];
			this.par[ry] = rx;
		}
	}

	int size(int x) {
		return this.size[root(x)];
	}

	boolean same(int x, int y) {
		int rx = root(x);
		int ry = root(y);

		return rx == ry;
	}
}
class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double nextDouble() { return Double.parseDouble(next());}
}


import java.io.*;
import java.util.*;

public class Main {

	public static void main(String[] args) {
        hayami saori = new hayami();
		int ans = 0;
		int N = saori.saori_hayami();
		int M = saori.saori_hayami();
		int[] X = new int[M];
		for(int i=0; i<M; i++){
			X[i] = saori.saori_hayami();
		}
		Arrays.sort(X);
		int[] diff = new int[M-1];
		for(int i=0; i<M-1; i++){
			diff[i] = X[i+1] - X[i];
		}
		Arrays.sort(diff);
		if(N>=M){
			ans = 0;
		}else{
			for(int i=0; i<M-N; i++){
				ans += diff[i];
			}
		}
		System.out.println(ans);

	}

}

class hayami implements Closeable {
	private final InputStream in = System.in;
	private final byte[] hayami = new byte[1024];
	private int Hayami = 0;
	private int saori = 0;
	private boolean HayamiSaori() {
		if (Hayami < saori) {
			return true;
		}else{
			Hayami = 0;
			try {
				saori = in.read(hayami);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (saori <= 0) {
				return false;
			}
		}
		return true;
	}
	private int SaoriHayami() {
		if (HayamiSaori()) {
            return hayami[Hayami++];
         }else{
             return -1;
         }
	}
	private static boolean hayami_saori(int hayami) {
		return 33 <= hayami && hayami <= 126;
	}
	public boolean hayamisaori() {
		while(HayamiSaori() && !hayami_saori(hayami[Hayami])) Hayami++; return HayamiSaori();
	}
	public String nextHayami() {
		if (!hayamisaori()) throw new NoSuchElementException();
		StringBuilder hayamin = new StringBuilder();
		int saori = SaoriHayami();
		while(hayami_saori(saori)) {
			hayamin.appendCodePoint(saori);
			saori = SaoriHayami();
		}
		return hayamin.toString();
	}
	public long saorihayami() {//nextLong
		if (!hayamisaori()) throw new NoSuchElementException();
		long hayami = 0;
		boolean misao = false;
		int saori = SaoriHayami();
		if (saori == '-') {
			misao = true;
			saori = SaoriHayami();
		}
		if (saori < '0' || '9' < saori) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= saori && saori <= '9') {
				hayami *= 10;
				hayami += saori - '0';
			}else if(saori == -1 || !hayami_saori(saori)){
				return misao ? -hayami : hayami;
			}else{
				throw new NumberFormatException();
			}
			saori = SaoriHayami();
		}
	}
	public int saori_hayami() {//nextInt
		long hayami = saorihayami();
		if (hayami < Integer.MIN_VALUE || hayami > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) hayami;
	}
	public double Hayamin() { //nextDouble
		return Double.parseDouble(nextHayami());
	}
	public void close() {
		try {
			in.close();
		} catch (IOException e) {
		}
    }

}


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < m; i++) {
            list.add(sc.nextInt());
        }
        Collections.sort(list);
        ArrayList<Integer> list2 = new ArrayList<>();
        for (int i = 1; i < m; i++) {
            list2.add(Math.abs(list.get(i -1) - list.get(i)));
        }
        if(list2.size() == 0) {
            System.out.println(0);
            return;
        }
        Collections.sort(list2);
        int ans = 0;
        for (int i = 0; i <= n; i++) {
            ans += list2.get(i);
        }
        System.out.println(ans);
    }
}


/*
 * Click `Run` to execute the snippet below!
 */

import java.io.*;
import java.util.*;

/*
 * To execute Java, please define "static void main" on a class
 * named Solution.
 *
 * If you need more classes, simply define them inline.
 */

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt(), M = sc.nextInt();
    int arr[] = new int[M];
    for(int i = 0; i<M; i++){
      arr[i] = sc.nextInt();
    }
    Arrays.sort(arr);
    int dif[] = new int[M-1];
    for(int i = 0; i<M-1; i++){
      dif[i] = arr[i+1] - arr[i];
    }
    Arrays.sort(dif);
    int ans = arr[M-1] - arr[0];
    for(int i = M-2; i>M-2-N+1; i--){
      //System.out.println(dif[i]);
      ans -= dif[i];
    }
    System.out.println(ans);
  }
}


import java.util.Arrays;
import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc =new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();

		int[]ar = new int[M];
		for(int i =0; i<M; i++) {
			ar[i]= sc.nextInt();

		}
		Arrays.sort(ar);

	int[]dis = new int[M-1];
	for(int i =0; i<dis.length; i++) {
		dis[i] = Math.abs(ar[i]-ar[i+2]);
	}
	Arrays.sort(dis);

	int count = 0;
	for(int i =0; i<dis.length-N+1; i++) {
		count += dis[i+1];
	}
	System.out.println(count);

}
}


#include <cstdio>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	int pn = 1;
	if (ci - cn + 16 > cm) {
		if ((ct = getcha()) == '-') { pn = -1; ct = getcha(); }
		A = ct - '0';
		while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
	else {
		if ((ct = *ci++) == '-') { pn = -1; ct = *ci++; }
		A = ct - '0';
		while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
}

int main() {

	int N = getint(), M = getint();
	bool X[200010] = {};
	rep(i, M) X[getint() + 100000] = true;

	int mae = -1;
	int sa[200010] = {};
	rep(i, 200001) {
		if (X[i]) {
			if (mae != -1) {
				sa[i - mae]++;
			}
			mae = i;
		}
	}

	int kotae = 0;
	rep(i, 200001) {
		if (M <= N) break;
		int k = M - N >= sa[i] ? sa[i] : M - N;
		kotae += i * k;
		M -= k;
	}

	printf("%d", kotae);

	Would you please return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	int pn = 1;
	if (ci - cn + 16 > cm) {
		if ((ct = getcha()) == '-') { pn = -1; ct = getcha(); }
		A = ct - '0';
		while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
	else {
		if ((ct = *ci++) == '-') { pn = -1; ct = *ci++; }
		A = ct - '0';
		while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	int N = getint(), M = getint();
	bool X[200010] = {};
	rep(i, M) X[getint() + 100000] = true;

	int mae = -1;
	int sa[200010] = {};
	rep(i, 200001) {
		if (X[i]) {
			if (mae != -1) {
				sa[i - mae]++;
			}
			mae = i;
		}
	}

	int kotae = 0;
	rep(i, 200001) {
		if (M <= N) break;
		int k = min(M - N, sa[i]);
		kotae += i * k;
		M -= k;
	}

	co(kotae);

	Would you please return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	int pn = 1;
	if (ci - cn + 16 > cm) {
		if ((ct = getcha()) == '-') { pn = -1; ct = getcha(); }
		A = ct - '0';
		while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
	else {
		if ((ct = *ci++) == '-') { pn = -1; ct = *ci++; }
		A = ct - '0';
		while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';;
		return pn * A;
	}
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	int N = getint(), M = getint();
	bool X[200010] = {};
	rep(i, M) X[getint() + 100000] = true;

	int mae = -1;
	int sa[200010] = {};
	rep(i, 200001) {
		if (X[i]) {
			if (mae != -1) {
				sa[i - mae]++;
			}
			mae = i;
		}
	}

	int kotae = 0;
	rep(i, 200001) {
		while (M > N && sa[i]) {
			sa[i]--;
			kotae += i;
			M--;
		}
	}

	co(kotae);

	Would you please return 0;
}


//Author: Fuadul Hasan(fuadul202@gmail.com)
#include<bits/stdc++.h>
using namespace std;

#define ll long long
const int N   = 2e5 + 5;

int main(){

	int n,k;
	cin>>n>>k;
	int a[n];

	for(int i=0;i<k;i++){
		cin>>a[i];
	}

	sort(a,a+k);
	std::vector<int> v;
	for(int i=1;i<k;i++){
		v.push_back(a[i]-a[i-1]);
	}
	sort(v.begin(),v.end());
	ll sum = 0;
	for(int i=(v.size() - n);i>=0;i--){
		//cout<<v[i]<<" ";
		sum += (ll)v[i];
	}//cout<<endl;
	cout<<sum<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

/* エイリアス */
#define ll long long
#define ld long double
#define vi vector<int>
#define vll vector<ll>
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vpi vector<pii>
#define vpll vector<pll>
#define endl '\n'

#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define em emplace
#define mp make_pair

/* 関数マクロ */
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define rep2(i, n, m) for (ll i = n; i <= m; ++i)
#define rep3(i, n, m) for (ll i = n; i >= m; --i)
#define all(v) v.begin(), v.end()
#define si(v) int(v.size())
#define UNIQUE(v) sort(all(v)), v.erase(unique(all(v)),v.end())

/* 定数 */
const ll mod = 1e9 + 7;
const ll infll = (1LL << 62) - 1;
const ll inf = (1LL << 30) - 1;

/* その他 */
template<class S, class T> inline bool chmax(S &a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class S, class T> inline bool chmin(S &a, T b) { if (a > b) { a = b; return 1; } return 0; }
template<class T> using pq = priority_queue<T>;
template<class T> using pqg = priority_queue<T, vector<T>, greater<T>>;

signed main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cout << fixed << setprecision(15);

  int n, m; cin >> n >> m;
  vll a(m);

  rep(i, m) cin >> a[i];
  sort(all(a));

  vll dis(m-1);
  rep(i, m-1) {
    dis[i] = a[i+1] - a[i];
  }

  sort(all(dis));
  ll ans = 0;

  rep(i, min(si(dis),n+1)) {
    ans += dis[i];
  }

  cout << ans << endl;
}


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;
#define chmax(x,y) x = max(x,y);
#define chmin(x,y) x = min(x,y);
const int di[] = {-1, 0, 1, 0};
const int dj[] = {0, -1, 0, 1};
const int INF = 1001001001;

int main() {
    int n, m;
    cin >> n >> m;
    vector<int> x(m);
    rep(i,m) cin >> x[i];
    sort(x.begin(), x.end());
    priority_queue<int> q;
    rep(i,m-1) {
        int a = x[i+1] - x[i];
        q.push(a);
    }
    rep(i,n-1) {
        q.pop();
    }
    int ans = 0;
    while (!q.empty()) {
        ans += q.top();
        q.pop();
    }
    cout << ans << endl;
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<inttypes.h>
#include<string.h>

typedef int32_t i32;
typedef int64_t i64;

static i64 read_int(void){int prev='\0';int c=getchar();while(!('0'<=c && c<='9')){prev=c;c=getchar();}i64 res=0;while('0'<=c && c<='9'){res=10*res+c-'0';c=getchar();}return prev=='-'?-res:res;}

typedef i32  radix_type;

#define RADIX_WIDTH 9
const uint32_t radix_type_max = 18;
const uint32_t radix_type_begin = 0;
const uint32_t radix_width = RADIX_WIDTH;
const uint32_t radix_mask = (1 << RADIX_WIDTH) - 1;
#undef RADIX_WIDTH

static inline uint32_t radix_get_bit (radix_type v, uint32_t shift) {
  return v >> shift & radix_mask;
}

void radix_sort (radix_type *a, uint32_t n) {
  radix_type * const array = (radix_type *) calloc (4 * n, sizeof (radix_type));
  radix_type **bucket = (radix_type **) calloc (1 << radix_width, sizeof (radix_type *));
  uint32_t *len = (uint32_t *) calloc (2 << radix_width, sizeof (uint32_t));
  uint32_t *max_len = len + (1 << radix_width);
  for (uint32_t shift = radix_type_begin; shift < radix_type_max; shift += radix_width) {
    radix_type *p = array;
    memset (len, 0, sizeof (uint32_t) << (radix_width + 1));
    for (uint32_t i = 0; i < n; ++i) {
      uint32_t bit = radix_get_bit (a[i], shift);
      if (len[bit] == max_len[bit]) {
	for (uint32_t j = 0; j < len[bit]; ++j) {
	  p[j] = bucket[bit][j];
	}
	max_len[bit] = 2 * max_len[bit] + 1;
	bucket[bit] = p;
	p += max_len[bit];
      }
      bucket[bit][len[bit]++] = a[i];
    }
    for (uint32_t bit = 0, i = 0; bit < (1 << radix_width); ++bit) {
      for (uint32_t j = 0; j < len[bit]; ++j, ++i) {
	a[i] = bucket[bit][j];
      }
    }
  }
  free (array);
  free (bucket);
  free (len);
}

void run (void) {
  i32 n = read_int();
  i32 m = read_int();
  i32 *x = (i32 *) calloc (m, sizeof (i32));
  for (i32 i = 0; i < m; ++i) {
    x[i] = read_int() + 100000;
  }
  radix_sort (x, m);
  for (i32 i = 0; i < m - 1; ++i) {
    x[i] = x[i + 1] - x[i];
  }
  radix_sort (x, m - 1);
  i32 ans = 0;
  for (i32 i = 0; i < m - n; ++i) {
    ans += x[i];
  }
  printf("%" PRIi32 "\n", ans);
}

int main (void) {
  run();
  return 0;
}


#include <stdio.h>

int main(){

	int N;
	int M;
	int ary[100000]={0};
	int bucket_1[200001]={0};
	int margin[99999]={0};
	int bucket_2[200000]={0};
	int i,j,k;
	int notpass=0;

	scanf("%d %d",&N,&M);
	for(i=0;i<M;i++)
		scanf("%d",&ary[i]);

	if(M<=N){
	   printf("%d\n",0);
	   return 0;
	}

	///////// BucketSort_1 //////////
	for(i=0;i<M;i++)
		bucket_1[ary[i]+100000]=1;
	for(j=0,i=0;i<M;j++)
		if(bucket_1[j]!=0){
			ary[i]=j-100000;
			i++;
		}

	for(i=0;i<M-1;i++)
	    margin[i]=ary[i+1]-ary[i];

	///////// BucketSort_2 //////////
	for(i=0;i<M-1;i++)
		bucket_2[margin[i]-1]+=1;
	for(i=0,j=0;i<M-1;j++)
		if(bucket_2[j]!=0){
			for(k=0;k<bucket_2[j];k++){
				margin[i]=j+1;
				i++;
			}
		}

	for(i=M-2;M-N-1<i;i--)
	   notpass+=margin[i];

	printf("%d\n",ary[M-1]-ary[0]-notpass);

	return 0;

}


#include <stdio.h>
#define X 100000

int main(){

	int N;
	int M;
	int ary[X]={0};
	int bucket_1[2*X+1]={0};
	int margin[X-1]={0};
	int bucket_2[2*X]={0};
	int i,j,k;
	int notpass=0;

	scanf("%d %d",&N,&M);
	for(i=0;i<M;i++)
		scanf("%d",&ary[i]);

	if(M<=N){
	   printf("%d\n",0);
	   return 0;
	}

	///////// BucketSort_1 //////////
	for(i=0;i<M;i++)
		bucket_1[ary[i]+100000]=1;
	for(i=0,j=0;i<M;j++)
		if(bucket_1[j]!=0){
			ary[i]=j-100000;
			i++;
		}

	for(i=0;i<M-1;i++)
	    margin[i]=ary[i+1]-ary[i];

	///////// BucketSort_2 //////////
	for(i=0;i<M-1;i++)
		bucket_2[margin[i]-1]+=1;
	for(i=0,j=0;i<M-1;j++)
		if(bucket_2[j]!=0){
			for(k=0;k<bucket_2[j];k++){
				margin[i]=j+1;
				i++;
			}
		}

	for(i=M-2;M-N-1<i;i--)
	   notpass+=margin[i];

	printf("%d\n",ary[M-1]-ary[0]-notpass);

	return 0;

}


#include <stdio.h>
#include <stdlib.h>

long long cmp( const void *p, const void *q ) {
  return *(long long*)p - *(long long*)q;
}

int main(void){
  long long n,m,x[100005],L[100005];
  scanf("%lld%lld",&n,&m);
  for(int i=0;i<m;i++){
    scanf("%lld",&x[i]);
  }
  if(n>=m){
    printf("0\n");
    return 0;
  }
  qsort(x, m, sizeof(long long),cmp);
  if(n==1){
    printf("%lld\n",x[m-1]-x[0]);
    return 0;
  }
  for(int i=0;i<m-1;i++){
    L[i]=x[i+1]-x[i];
  }
  qsort(L, m, sizeof(long long),cmp);
 long long k=x[m-1]-x[0];
  for(int i=m-2;i>=m-n;i--){
    k-=L[i];
  }
  printf("%lld",k);

  return 0;
}


#include <stdio.h>
#include <stdlib.h>

long long cmp( const void *p, const void *q ) {
  return *(long long*)p - *(long long*)q;
}

int main(void){
  long long n,m,x[100005],L[100005];
  scanf("%lld%lld",&n,&m);
  for(int i=0;i<m;i++){
    scanf("%lld",&x[i]);
  }
  if(n>=m){
    printf("0\n");
    return 0;
  }
  qsort(x, m, sizeof(long long),cmp);
  if(n==1){
    printf("%lld\n",x[m-1]-x[0]);
    return 0;
  }
  for(int i=0;i<m;i++){
    L[i]=x[i+1]-x[i];
  }
  qsort(L, m, sizeof(long long),cmp);
 long long k=x[m-1]-x[0];
  for(int i=n-1;i>=1;i--){
    k-=L[i];
  }
  printf("%lld",k);

  return 0;
}


#include<stdio.h>

int main(){
  int N,M;
  scanf("%d%d",&N,&M);

  int s[M];
  for (int i=0;i<M;i++){
  scanf("%d",&s[i]);
  }
  for (int i=0;i<=M;i++){
    for (int j=i+1;j<=M;j++){
      if(s[i]>s[j]){
        int tmp =0;
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
      }
    }
  }

  int d[M-1];
  for (int i=0;i<M-1;i++){
    d[i]= s[i+1]-s[i];
  }

  for (int i=0;i<=M;i++){
    for (int j=i+1;j<=M;j++){
      if(d[i]>d[j]){
        int tmp = 0;
        tmp = d[i];
        d[i]=d[j];
        d[j]= tmp;
      }
    }
  }
  int ans=0;
  for (int i=0;i<M-N-1;i++){
    ans+=d[i];
  }

  printf("%d",ans);

  return 0;
}


function Main(input) {
  input = input.split("\n");
  input[0] = input[0].split(" ");
  input[1] = input[1].split(" ");
  var N=parseInt(input[0][0]);
  var M=parseInt(input[0][1]);
  var path=Math.max(M-N,0);
  if(path===0){
    console.log(0);
    return;
  }
  (function(){for(var i=0;i<M;i++){
    input[1][i]=parseInt(input[1][i]);
  }})();
  var Xs=input[1];

  var x_axis=[];
  var delta=[];
  (function(){for(var j=0;j<200001;j++){
    x_axis[j]=0;
    delta[j]=0;
  }})();
  (function(){for(var k=0;k<M;k++){
    x_axis[Xs[k]+100000]++;
  }})();
  (function(){
    var counter=0;
    var i=0;
    while(x_axis[i]===0){
      i++;
    }
    for(i=i+1;i<200001;i++){
      if(x_axis[i]===0){
        counter++;
        continue;
      }
      delta[counter+1]++;
      counter=0;
    }
  })();

  (function(){
    var counter=0;
    var deltax=0;
    for(var i=0;i<path;i++){
      while(delta[deltax]===0){
        deltax++;
      }
      delta[deltax]--;
      counter+=deltax;
      deltax=0;
    }
    console.log(counter);
  })();
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


/**
 *
 * @param {string} input
 */
function main(input) {
  var inputList = input.split("\n");
  var nm = inputList[0].split(" ");
  var n = Number(nm[0]);
  var m = Number(nm[1]);
  var tmpList = inputList[1].split(" ");

  var xList = [];
  for(i=0; i<tmpList.length; i++){
    xList.push(Number(tmpList[i]));
  }

  // 座標ソート
  xList.sort(up);
  // 間の差
  var subList = [];
  for(i=0; i<xList.length-1; i++){
    var sub = Number(xList[i+1]) - Number(xList[i]);
    subList.push(sub);
  }

  // 差のソート昇順
  subList.sort(up);
  var sum = 0;
  for(i=0; i<subList.length-(n-1); i++){
    sum += subList[i];
  }

  console.log(sum);
}

function up(a, b){
  if(a<b){
    return -1;
  }else if(b<a){
    return 1;
  }else{
    return 0;
  }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
    const args = input.split('\n');
    const Args = args[0].split(' ')
  	const N = parseInt(Args[0], 10)
    const M = parseInt(Args[1], 10)
    const L = args[1].split(' ').map(Number).sort(A)
  	var S = B(L,N)

    if(N>=M){
    	console.log(0)
    }else{
    	 console.log(S)
    }

}

var A = (a,b)=>{
  if( a > b ) return -1;
        if( a < b ) return 1;
        return 0;
}

var B = (l,n)=>{
    var a = []
    var s = 0
  	for(var i =0;i<l.length-1;i++){
    	a[i] = l[i] - l[i+1]
    }
    a.sort(A)
    for(var j = n-1;j<a.length;j++){
    	s += a[j]
    }
  	return s
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input = require("fs").readFileSync("/dev/stdin", "utf8")
;(input => {
    const rows = input.split('\n')
    const N = rows[0].split(' ').map(Number)[0]
    const M = rows[0].split(' ').map(Number)[1]
    const X = rows[1].split(' ').map(Number)

    X.sort((a, b) => a < b ? -1 : 1)

    const dp = []
    for (var i = 0; i < M - 1; i++) {
        dp[i] = X[i + 1] - X[i]
    }

    dp.sort((a, b) => a < b ? -1 : 1)
    dp.splice(dp.length - (N - 1), N - 1)

    console.log(dp.length ? dp.reduce((a, b) => a + b) : 0)

})(input)


const input = require("fs").readFileSync("/dev/stdin", "utf8")
;(input => {
    const rows = input.split('\n')
    const N = rows[0].split(' ').map(Number)[0]
    const M = rows[0].split(' ').map(Number)[1]
    const X = rows[1].split(' ').map(Number)

    X.sort((a, b) => a < b ? -1 : 1)

    const dp = []
    for (var i = 0; i < M - 1; i++) {
        dp[i] = X[i + 1] - X[i]
    }

    dp.sort((a, b) => a < b ? 1 : -1)
    dp.splice(0, N - 1)
    console.log(dp.length ? dp.reduce((a, b) => a + b) : 0)

})(input)


const input = require('fs').readFileSync('/dev/stdin', 'utf8');

console.log(input);


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	nm := nextIntArray()
	n, m := nm[0], nm[1]
	if n >= m {
		fmt.Println(0)
		return
	}
	x := nextIntArray()
	sort.Ints(x)
	for i := 1; i < m; i++ {
		x[i-1] -= x[i]
	}
	for i := 0; i < m; i++ {
		if x[i] < 0 {
			x[i] = -x[i]
		}
	}
	x = x[:len(x)-1]
	sort.Ints(x)
	cnt := 0
	for _, v := range x[:m-n] {
		cnt += v
	}
	fmt.Println(cnt)

}

func lcm(a, b int64) int64 {
	return (a / gcd(a, b)) * b
}

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

const size = 1000000

var reader = bufio.NewReaderSize(os.Stdin, size)

func nextLine() string {
	var line, buffer []byte
	isPrefix := true
	var err error
	for isPrefix {
		line, isPrefix, err = reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
	}
	return string(buffer)
}
func nextStringArray() []string {
	return strings.Split(nextLine(), " ")
}
func nextInt() int {
	n, _ := strconv.Atoi(nextLine())
	return n
}

func nextIntArray() []int {
	s := strings.Split(nextLine(), " ")
	n := len(s)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i], _ = strconv.Atoi(s[i])
	}
	return a
}

func min(i, j int) int {
	if i > j {
		return j
	}
	return i
}

func max(i, j int) int {
	if i < j {
		return j
	}
	return i
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)

func init() {
	scanner.Split(bufio.ScanWords)
}

func ScanInt() int {
	scanner.Scan()
	t := scanner.Text()
	n, _ := strconv.Atoi(t)
	return n
}

func main() {
	n, m := ScanInt(), ScanInt()
	if n >= m {
		fmt.Println(0)
		return
	}
	xs := make([]int, m)
	for i := 0; i < m; i++ {
		xs[i] = ScanInt()
	}
	sort.Ints(xs)
	ds := make([]int, m-1)
	for i := 0; i < m-1; i++ {
		ds[i] = xs[i+1] - xs[i]
	}
	ret := 0
	sort.Ints(ds)
	for i := 0; i < m-1-(n-1); i++ {
		ret += ds[i]
	}
	fmt.Println(ret)
}


package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
	"strconv"
)

func main() {
	sc := NewScanner(os.Stdin)
	N := sc.NextInt()
	M := sc.NextInt()
	v := make([]int, M)
	for i := 0; i < M; i++ {
		v[i] = sc.NextInt()
	}
	sv := sort.IntSlice(v)
	sort.Sort(sv)
	d := make([]int, M-1)
	for i := 0; i < M-1; i++ {
		d[i] = sv[i+1] - sv[i]
	}
	sd := sort.IntSlice(d)
	sort.Sort(sd)
	ans := 0
	for i := 0; i < M-N; i++ {
		ans += sd[i]
	}
	fmt.Println(ans)
}

func lcm(x, y int) int {
	x, y = max(x, y), min(x, y)
	if y == 0 {
		return x
	}
	return lcm(y, x%y)
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

// scanner
type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner(r io.Reader) *Scanner {
	rdr := bufio.NewReaderSize(r, 1024)
	return &Scanner{r: rdr}
}

func (s *Scanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		line, isp, err := s.r.ReadLine()
		if err != nil {
			os.Exit(1)
		}
		s.buf = append(s.buf, line...)
		if !isp {
			break
		}
	}
}

func (s *Scanner) NextInt() int {
	i, err := strconv.Atoi(s.Next())
	if err != nil {
		os.Exit(1)
	}
	return i
}

func (s *Scanner) NextFloat64() float64 {
	i, err := strconv.ParseFloat(s.Next(), 64)
	if err != nil {
		os.Exit(1)
	}
	return i
}

func (s *Scanner) Next() string {
	s.Pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	next := string(s.buf[start:s.p])
	s.p++
	return next
}

func (s *Scanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner((os.Stdin))

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	l := nextLine()
	i, e := strconv.Atoi(l)
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	sc.Split(bufio.ScanWords)
	N, M, X := nextInt(), nextInt(), []int{}
	for i := 0; i < M; i++ {
		X = append(X, nextInt())
	}

	fmt.Printf("%d\n", ABC117C(N, X))
}

// ABC117C ...
func ABC117C(N int, X []int) int {
	sort.Ints(X)

	if N == 1 {
		return X[len(X)-1] - X[0] + 1
	}

	dists := []int{}
	for i := 0; i < len(X)-1; i++ {
		dists = append(dists, X[i+1]-X[i])
	}
	sort.Ints(dists)

	res := 0
	for i := 0; i < len(dists)-N+1; i++ {
		res += dists[i]
	}

	return res
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner((os.Stdin))

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	l := nextLine()
	i, e := strconv.Atoi(l)
	if e != nil {
		panic(e)
	}
	return i
}

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

func main() {
	sc.Split(bufio.ScanWords)
	N, M, X := nextInt(), nextInt(), []int{}
	for i := 0; i < M; i++ {
		X = append(X, nextInt())
	}

	fmt.Printf("%d\n", ABC117C(N, X))
}

// ABC117C ...
func ABC117C(N int, X []int) int {
	sort.Ints(X)

	if N == 1 {
		return X[len(X)-1] - X[0] + 1
	}

	div := [][]int{X}
	for d := 0; d < N-1; d++ {
		// select longest range
		var t []int
		max, maxIndex := -1, 0
		for i := 0; i < len(div); i++ {
			if max < len(div[i]) {
				max = len(div[i])
				maxIndex = i
			}
		}

		if max == 1 {
			break
		}

		t = div[maxIndex]

		l, r := t[0], t[len(t)-1]
		llist, rlist := []int{l}, []int{r}
		for i := 1; i < len(t)-1; i++ {
			if abs(t[i]-l) < abs(t[i]-r) {
				llist = append(llist, t[i])
				l = t[i]
			} else {
				rlist = append(rlist, t[i])
				sort.Ints(rlist)
				r = rlist[0]
			}
		}

		newdiv := [][]int{llist, rlist}
		for i := 0; i < len(div)-1; i++ {
			if i == maxIndex {
				continue
			}
			newdiv = append(newdiv, div[i])
		}
		div = newdiv
	}

	// count res
	res := 0
	for _, d := range div {
		res += d[len(d)-1] - d[0]
	}

	return res
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func Scan() string {
	sc.Scan()
	return sc.Text()
}
func iScan() int {
	n, _ := strconv.Atoi(Scan())
	return n
}
func fScan() float64 {
	n, _ := strconv.ParseFloat(Scan(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func SScan(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scan()
	}
	return a
}
func iSScan(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = iScan()
	}
	return a
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func sum(a []int) int {
	x := 0
	for _, v := range a {
		x += v
	}
	return x
}

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n := iScan()
	m := iScan()
	x := iSScan(m)
	sort.Ints(x)
	y := make([]int, m-1)
	for i := 0; i < m-1; i++ {
		y[i] = x[i+1] - x[i]
	}
	sort.Sort(sort.Reverse(sort.IntSlice(y)))
	ans := sum(y)
	if len(y) > 0 {
		ans -= sum(y[:n-1])
	}
	fmt.Println(ans)
}


N, M = gets.split.map(&:to_i)
X = gets.split.map(&:to_i)
distance = Array.new(M-1, 0)
ans = 0

if N < M
  X.sort!
  (M-1).times do |i|
    distance[i] = X[i+1] - X[i]
  end
  distance.sort!
  ans = distance[0, M-N].inject(:+)
end

puts ans


N, M = gets.split.map(&:to_i)
X = gets.split.map(&:to_i).sort!

if N >= M
  puts 0
else
  d = []
  1.step(M-1) {|i| d << X[i] - X[i-1] }
  d.sort!.pop(N-1)
  puts d.inject(:+)
end


N, M = gets.split.map(&:to_i)
x = gets.split.map(&:to_i).sort

if N >= M
  puts 0
  exit
end

diff = []
0.upto(M-2) do |i|
  diff << x[i + 1] - x[i]
end

p diff.sort[0..-N].inject(:+)


n,m = gets.chomp.split(' ').map(&:to_i)
arr = gets.chomp.split(' ').map(&:to_i).sort.reverse
ans = 0
intervals = []
i = 1
while i < arr.size
  intervals << arr[i-1] - arr[i]
  i += 1
end
intervals.sort!
puts intervals[0..(m-n-1)].sum


N, M = gets.chomp.split().map(&:to_i)
X = gets.chomp.split().map(&:to_i).sort

X_pad = []
(M-1).times do |i|
  X_pad << X[i+1] - X[i]
end

X_pad.sort!
ans = 0
ans += X_pad[...-(N-1)].sum
puts ans


N, M = gets.chomp.split().map(&:to_i)
X = gets.chomp.split().map(&:to_i).sort

X_pad = X.map.with_index(1) { |x, i| X[i] - x if X[i] }.compact
l = X[-1] - X[0]
exc_x = X_pad.empty? ? 0 : X_pad.sort[-(N-1)..].sum
puts l - exc_x


/*------------------------------------------------------------------*/
/*------------------------- begin template -------------------------*/
/*------------------------------------------------------------------*/

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, i64_) => {
        $parser.fast_i64()
    };
    ($parser:ident, usize_) => {
        $parser.fast_i64() as usize
    };
    ($parser:ident, usize1_) => {
        ($parser.fast_i64() - 1) as usize
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

use std::io;
use std::io::BufRead;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    pub reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R: BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len, complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len - 1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.parse::<T>();
            } else {
                self.update_buf();
            }
        }
    }
    pub fn fast_i64(&mut self) -> i64 {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            if begin == self.buf.len() {
                self.update_buf();
                continue;
            }
            let mut res = 0;
            let (is_positive, mut end) = match self.buf[begin] {
                b'+' => (true, begin + 1),
                b'-' => (false, begin + 1),
                _ => (true, begin),
            };
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                res = res * 10 + (self.buf[end] as i64 - '0' as i64);
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return if is_positive { res } else { -res };
            } else {
                self.update_buf();
            }
        }
    }
}

#[allow(unused_imports)]
use std::cmp::*;

fn main() {
    input! {
        new_stdin_parser = parser,
    }
    let res = solve(&mut parser);
    print!("{}", res);
}

/*------------------------------------------------------------------*/
/*-------------------------- end template --------------------------*/
/*------------------------------------------------------------------*/

use std::fmt::Write;
fn solve<R: BufRead>(parser: &mut Parser<R>) -> String {
    let mut buf = String::new();
    input! {
        parser = parser,
        n: usize,
        m: usize,
        xs: [i64_; m],
    }
    let mut xs = xs;
    xs.sort();
    let mut ds = vec![];
    for i in 1..m {
        ds.push(xs[i] - xs[i - 1]);
    }
    ds.sort();
    ds.reverse();
    let res = ds.iter().skip(n - 1).sum::<i64>();
    writeln!(buf, "{}", res);
    buf
}


#[macro_use]
mod input {

use std;
use std::io;

const SPLIT_DELIMITER: char = ' ';

#[macro_export]
#[allow(unused_macros)]
macro_rules! input {
    ( $($x:expr ),*) => {
        {
            let temp_str = input_line_str();
            let mut split_result_iter = temp_str.split_whitespace();
                $(
                let buf_split_result = split_result_iter.next();
                let buf_split_result = buf_split_result.unwrap();
                    ($x) = buf_split_result.parse().unwrap();
                )*
        }
    };
}

#[allow(dead_code)]
pub fn input_line_str() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

#[allow(dead_code)]
pub fn p<T>(t: T)
where
    T: std::fmt::Display,
{
    println!("{}", t);
}

#[allow(dead_code)]
pub fn input_vector2d<T>(line: usize) -> Vec<Vec<T>>
where
    T: std::str::FromStr,
{
    let mut v: Vec<Vec<T>> = Vec::new();

    for _ in 0..line {
        let vec_line = input_vector();
        v.push(vec_line);
    }
    v
}

#[allow(dead_code)]
pub fn input_vector<T>() -> Vec<T>
where
    T: std::str::FromStr,
{
    let mut v: Vec<T> = Vec::new();

    let s = input_line_str();
    let split_result = s.split(SPLIT_DELIMITER);
    for z in split_result {
        let buf = match z.parse() {
            Ok(r) => r,
            Err(_) => panic!("Parse Error"),
        };
        v.push(buf);
    }
    v
}

#[allow(dead_code)]
pub fn str2vec(s: &str) -> Vec<char> {
    let mut v: Vec<char> = Vec::new();
    for c in s.chars() {
        v.push(c);
    }
    v
}
}

use input::*;

fn main() {
    let (n, m): (usize, usize);
    input!(n, m);
    let mut v = input_vector::<isize>();

    if n >= m {
        p(0);
        return;
    }

    let mut dist = vec![];

    v.sort();

    let mut sum = v.iter().last().unwrap() - v.iter().next().unwrap();
    for z in 0..m - 1 as usize {
        let buf = (v[z] - v[z + 1]).abs();
        dist.push(buf);
    }
    dist.sort();
    dist.reverse();
    for z in 0..n - 1 {
        sum -= dist[z];
    }
    p(sum);
}


#![allow(unused)]

use std::{cell, cmp, collections, fmt, ops};

use cell::{Cell, RefCell};
use cmp::Ordering::{Equal, Greater, Less};
use collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use fmt::{Debug, Display};

// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        _input_inner!(iter, $($r)*)
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        _input_inner!(iter, $($r)*)
    };
}

macro_rules! _input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = _read_value!($iter, $t);
        _input_inner!($iter $($r)*)
    };
}

macro_rules! _read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(_read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| _read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        _read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        _read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[cfg(feature = "debug")]
macro_rules! d {
    ($($args: tt)*) => { dbg!($($args)*) };
}

#[cfg(not(feature = "debug"))]
macro_rules! d {
    ($($args:tt)*) => {};
}

mod num {
    //
}

macro_rules! vmin {
    ($x: expr, $y: expr) => { cmp::min($x, $y) };
    ($x: expr, $($args: expr),*) => { cmp::min($x, vmin!($($args),*)) };
}

macro_rules! vmax {
    ($x: expr, $y: expr) => { cmp::max($x, $y) };
    ($x: expr, $($args: expr),*) => { cmp::max($x, vmax!($($args),*)) };
}

mod bits {
    pub fn is_high(bits: u64, pos: u64) -> bool {
        bits & (1 << pos) != 0
    }
}

fn main() {
    input!(stones_num: usize, pos_num: usize, pos: [i32; pos_num]);

    if stones_num >= pos_num {
        println!("{}", 0);
        return;
    }

    let mut pos = pos;
    pos.sort();

    let mut pos_intervals = pos.windows(2).map(|w| w[1] - w[0]).collect::<Vec<_>>();
    pos_intervals.sort_by(|d1, d2| d2.cmp(&d1));

    let ans = pos_intervals.iter().skip(stones_num - 1).sum::<i32>();

    println!("{}", ans);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        //
    }
}


use proconio::input;

fn main() {
  input! {
    n: usize,
    m: usize,
    mut ms: [isize;m]
  }

  if m <= n {
    println!("0");
    return
  }

  ms.sort();
  if n == 1 {
    println!("{}", (ms.last().unwrap() - ms.first().unwrap()).abs());
  }

  let mut between: Vec<isize> = vec![0;m-1];
  for i in 0..m-1 {
    let v = ms[i];
    between[i] = (ms[i+1] - ms[i]).abs();
  }
  between.sort();

  for _ in 0..n-1 {
    between.pop();
  }

  println!("{}", between.iter().sum::<isize>());

}


use std::io::*;
use std::str::FromStr;

pub 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")
}

fn main() {
    let n: usize = read();
    let m: usize = read();

    let mut a: Vec<i64> = vec![];

    for i in 0..m {
        a.push(read());
    }
    a.sort();

    let mut b: Vec<i64> = vec![];
    for i in 1..a.len() {
        b.push(a[i] - a[i - 1])
    }

    b.sort();
    if m - n <= 0 {
        println!("{}", 0);
        return;
    }
    b.split_off(m - n);
    println!("{}", b.iter().sum::<i64>());
}


use std::io::*;
use std::str::FromStr;

pub 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")
}

fn main() {
    let n: usize = read();
    let m: usize = read();

    let mut a: Vec<i64> = vec![];

    for i in 0..m {
        a.push(read());
    }
    a.sort();

    let mut b: Vec<i64> = vec![];
    for i in 1..a.len() {
        b.push(a[i] - a[i - 1])
    }

    b.sort();
    b.split_off(m - n);
    println!("{}", b.iter().sum::<i64>());
}


import Foundation

func readWords<T>(_ f: (Substring) -> T) -> [T] {
    return readLine()!.split(separator: " ").map(f)
}

func main() {
    let nm = readWords { Int($0)! }
    let n = nm[0]
    let m = nm[1]

    if n >= m {
        print(0)
        return
    }

    let X = readWords { Int($0)! }.sorted()

    // 区間が得られる。
    // 問題を簡単にしてみる。
    // コマが1つなら答えは X[m-1] - X[0]
    // コマが複数あるなら、訪れない区間ができるのでそのうち一番広い区間を選択すれば良い。
    // コマが2つなら、訪れない区間は1つ。-> 全体から最も広い区間を1つ引く。
    // コマがn個なら、訪れない区間はn-1つ。 -> 全体から広い区間をn-1個引く。

    var distances = (1..<m).map { X[$0] - X[$0-1] }
    distances.sort(by: >)

    print(distances[(n-1)...].reduce(0, +))
}

main()


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    let aryX = readInts().sorted()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    if n >= m {
        print(0)
        return
    }
    var ans = 0
    var ary = [Int](repeating: 0, count: m - 1)
    for i in 1..<m {
        ary[i - 1] = abs(aryX[i] - aryX[i - 1])
    }

    ary.sort(by: >)

    for i in n - 1..<ary.count {
        ans += ary[i]
    }
    print(ans)
}
main()


let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let M = input[1]
let X = readLine()!.split(separator: " ").map { Int($0)! }.sorted()

if N >= X.count {
    print(0)
} else {
    var distances = [Int]()
    for i in stride(from: 0, to: X.count - 1, by: 1) {
        distances.append(abs(X[i] - X[i + 1]))
    }
    print(distances.sorted()[0 ..< distances.count - N + 1].reduce(0, +))
}


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let nm = readInts()
    let (n, m) = (nm[0], nm[1])
    let aryX = readInts().sorted()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    var ans = 0
    var ary = [Int](repeating: 0, count: m - 1)
    var i = 0

    while i < m - 1 && m > 1{
        ary[i] = abs(aryX[i] - aryX[i + 1])
        ans += ary[i]
        i += 1
    }

    ary.sort(by: >)
    if m > 1 {
        for i in 0..<n - 1 {
            ans -= ary[i]
        }
    }
    print(ans)
}
main()


export class Main {
  static main(input: string): string {
    const tmp = input.split("\n");
    const [n, m] = tmp[0].split(" ").map(Number);
    if (n >= m) {
      return "0";
    }
    const xList = tmp[1].split(" ").slice(0, m).map(Number);
    xList.sort((a, b) => a-b);
    const diffList = [];
    for (let i = 0, len xList.length - 1; i < len; i++) {
      diffList.push(xList[i + 1] - xList[i]);
    }
    diffList.sort((a, b) => a-b);
    let tmp = 0;
    for (let i = 0, len = m - n; i < len; i++) {
      tmp += diffList[i];
    }
    return `${tmp}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

let [n, m] = stdin
  .split('\n')[0]
  .split(' ')
  .map(Number)

n = n > m ? m : n

const x = stdin
  .split('\n')[1]
  .split(' ')
  .map(Number)

const ans = () => {
  const sorted = x.sort((a, b) => a - b)

  const diffs = getDiffs(sorted)

  const splitLines = getSplitLines(diffs)

  let count = 0
  for (let i = 0; i < splitLines.length; i++) {
    const begin = splitLines[i]
    const end = i === splitLines.length - 1 ? sorted.length - 1 : splitLines[i + 1] - 1

    count += sorted[end] - sorted[begin]
  }

  console.log(count)
}

const getDiffs = arr => {
  const diffs = []

  for (let i = 1; i < arr.length; i++) {
    const diff = arr[i] - arr[i - 1]

    diffs.push({
      diff,
      index: i,
    })
  }

  return diffs
}

const getSplitLines = diffs => {
  const sDiffs = diffs.sort((a, b) => b.diff - a.diff)

  const splitLines = [0]
  for (let i = 0; i < n - 1; i++) {
    const idx = sDiffs[i].index

    splitLines.push(idx)
  }

  return splitLines
}

ans()


namespace Coder {
  class Scanner {
    private buffer: string = '';
    private stdinQueue: any = [];

    constructor() {
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on(
        'data',
        (chunk): void => {
          this.buffer += chunk;
          while (this.stdinQueue.length > 0) {
            const i = this.buffer.indexOf('\n');
            if (i < 0) {
              break;
            }
            let line = this.buffer.substr(0, i);
            if (line.endsWith('\r')) {
              line = line.slice(0, -1);
            }
            this.buffer = this.buffer.substr(i + 1);
            this.stdinQueue.shift()(line);
          }
        },
      );
    }
    public getLine(): Promise<string> {
      return new Promise((resolve, reject) => {
        const i = this.buffer.indexOf('\n');
        if (i >= 0 && this.stdinQueue.length == 0) {
          let line = this.buffer.substr(0, i);
          if (line.endsWith('\r')) {
            line = line.slice(0, -1);
          }
          this.buffer = this.buffer.substr(i + 1);
          resolve(line);
        } else {
          this.stdinQueue.push(resolve);
        }
      });
    }

    public close(): void {
      process.stdin.pause();
    }
  }

  async function slove() {
    const sc = new Scanner();
    const [n, m] = (await sc.getLine()).split(' ').map((x) => +x);
    const X = (await sc.getLine()).split(' ').map((x) => +x);
    X.sort((a, b) => {
      if (a > b) return 1;
      else return -1;
    });
    if (m === 1) {
      console.log('0');
    } else {
      const d = [];
      for (let i = 0; i < m - 1; i++) {
        d.push(X[i + 1] - X[i]);
      }
      d.sort((a, b) => {
        if (a > b) return 1;
        else return -1;
      }).reverse();
      const sum = (array: any[]) => {
        return array.reduce((prev, current, i, arr) => {
          return prev + current;
        });
      };
      let ans = sum(d);
      for (let i = 0; i < n - 1; i++) {
        ans -= d[i];
      }
      console.log(ans);
    }

    sc.close();
  }

  slove();
}


a = input()
b = input()
c = input()
print(a[0]+b[1]+c[2])


S=[input() for _ in range(3)]

i=0
for s in S:
  print(s[i],end='')
  i+=1


a = input()
b = input()
c = input()
print(a[0],b[1],c[2], sep="")


l=input()
l1=input()
l2=input()
a=l[0],l1[1],l2[2]
print(*a)


a,b=map(int,input().split())
print(abs((a-2)*(b-2)))


s1 = input()
s2 = input()
s3 = input()
print(s1[0]+s1[1]+s1[2])


import java.io.*;

public class Main{
  public static void main(String[] args) {
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String a, b, c;
      String d, e, f;

      a = reader.readLine();
      d = a.substring(0, 1);
      b = reader.readLine();
      e = b.substring(1, 2);
      c = reader.readLine();
      f = c.substring(2);

      System.out.println(d + e + f);

    }
    catch (Exception e) {

    }
  }
}


import java.io.*;
import java.util.*;

public class Main {
    public static final long mod = (long)1e9+7;
    public static final long INF = Long.MAX_VALUE/4;
    public static final int inf = Integer.MAX_VALUE/4;

    static void solve(InputReader in, PrintWriter out){
        char[][] a = new char[3][3];
        for (int i = 0; i < 3; i++) {
            a[i] = in.ns().toCharArray();
        }
        out.print(a[0][0]);
        out.print(a[1][1]);
        out.println(a[2][2]);
    }

    public static void main(String[] args){
        InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        solve(in, out);
        out.close();
    }
    public static class InputReader{
        private BufferedReader br;
        private StringTokenizer st;
        public InputReader(InputStream is){
            br = new BufferedReader(new InputStreamReader(is));
            st = null;
        }
        public String ns(){
            if(st == null || !st.hasMoreTokens()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (Exception e){
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }
        public int ni(){
            return Integer.parseInt(ns());
        }
        public long nl(){
            return Long.parseLong(ns());
        }
        public Double nd(){
            return Double.parseDouble(ns());
        }
        public int[] ni(int n){
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = ni();
            }
            return a;
        }
        public long[] nl(int n){
            long[] a = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = nl();
            }
            return a;
        }
        public double[] nd(int n){
            double[] a = new double[n];
            for (int i = 0; i < n; i++) {
                a[i] = nd();
            }
            return a;
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {

	final static long MOD = 1000000007;
	public static String[] Ws = null;
	public static int wsIndx = 0;
	public static BufferedReader in = null;
	public static void main(String[] args) throws Exception {
		solution(args);
		if(in!=null){
			in.close();
		}
	}

	public static void solution(String[] args) throws Exception{

		String s="";
		for(int i=0;i<3;i++){
			s+=nextString().substring(i,i+1);
		}

		System.out.println(s);

	}
	public static String[] toStringArray(String s) {
		String[] tmp = new String[s.length()];
		char[] c = s.toCharArray();
		for (int i = 0; i < tmp.length; i++) {
			tmp[i] = String.valueOf(c[i]);
		}
		return tmp;
	}

	public static void check() throws Exception{
		if(in == null){
			in = new BufferedReader(new InputStreamReader(System.in));
		}
		if(Ws==null || Ws.length<=wsIndx){
			Ws = in.readLine().split(" ");
			wsIndx=0;
		}
	}
	public static int nextInt()throws Exception{
		check();
		return Integer.parseInt(Ws[wsIndx++]);
	}

	public static long nextLong()throws Exception{
		check();
		return Long.parseLong(Ws[wsIndx++]);
	}

	public static String nextString()throws Exception{
		check();
		return Ws[wsIndx++];
	}

	public static int[] nextInts()throws Exception{
		check();
		int[] tmp = new int[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Integer.parseInt(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static long[] nextLongs()throws Exception{
		check();
		long[] tmp = new long[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Long.parseLong(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static String[] nextStrings()throws Exception{
		check();
		wsIndx=Ws.length;
		return Ws;
	}

}


import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String first_line = scanner.nextLine();
		String second_line = scanner.nextLine();
		String third_line = scanner.nextLine();

        System.out.print(first_line.substring(0,1));
        System.out.print(second_line.substring(1,2));
        System.out.print(third_line.substring(2,3));
    }
}


import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

import sun.security.krb5.Asn1Exception;

public class Main {

	public static void main(String[] args) throws IOException {

		Scanner scan = new Scanner(System.in);

		char a[] = new char[9];

		for (int i = 0; i < 9; i += 3) {
			String input = scan.next();

			a[i] = input.toCharArray()[i];
			a[i + 1] = input.toCharArray()[i + 1];
			a[i + 2] = input.toCharArray()[i + 2];
		}

		String ans = String.valueOf(a[0])
				+ String.valueOf(a[4])
				+ String.valueOf(a[8]);

		System.out.println(ans);

	}

	//***********************以下共通関数************************************************
	/**
	 * 文字列を反転して返す
	 * @param pStr 文字列
	 * @return 反転した文字列
	 */
	public static String myReverse(String pStr) {
		if (pStr.length() < 1) {
			return "";
		}

		StringBuffer sb = new StringBuffer(pStr);
		return sb.reverse().toString();
	}

	/**
	 * 余りを求める。
	 * @param a
	 * @param b
	 * @return 余り。余りがマイナスの時はプラスで返す。
	 */
	public static long myMod(long a, long b) {
		long ret = 0;

		ret = a % b;

		if (ret < 0) {
			ret += b;
		}

		return ret;
	}

	/**
	 * 乗数を求める ※mod対応
	 * @param kisu 基数
	 * @param josu 乗数
	 * @param primeNumMod_0 法 mod値 使わない場合は「0」
	 * @return
	 */
	public static long myPowWithMod(long kisu, long josu, long primeNumMod_0) {

		long ans = 1;

		//乗数が0の場合→1
		if (josu == 0)
			return 1;

		if (primeNumMod_0 == 0) {
			//modを使わないとき

			while (josu > 0) {

				if (josu % 2 == 0) {
					//累乗が偶数の時

					kisu *= kisu;
					josu = josu / 2;
				} else {
					//累乗が奇数の時
					ans *= kisu;
					josu--;
				}
			}

			return ans;

		} else {
			//modを使うとき

			//初めに桁を落とす
			kisu = myMod(kisu, primeNumMod_0);

			while (josu > 0) {

				if (josu % 2 == 0) {
					//累乗が偶数の時

					kisu *= myMod(kisu, primeNumMod_0);
					josu = josu / 2;

				} else {
					//累乗が奇数の時
					ans *= myMod(kisu, primeNumMod_0);
					josu--;

				}
			}

			return myMod(ans, primeNumMod_0);

		}

	}

}


import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

import sun.security.krb5.Asn1Exception;

public class Main {

	public static void main(String[] args) throws IOException {

		Scanner scan = new Scanner(System.in);

		char a[] = new char[9];

		for (int i = 0; i < 9; i++) {
			a[i] = scan.next().toCharArray()[0];
		}

		String ans = String.valueOf(a[0])
				+ String.valueOf(a[4])
				+ String.valueOf(a[8]);

		System.out.println(ans);

	}

	//***********************以下共通関数************************************************
	/**
	 * 文字列を反転して返す
	 * @param pStr 文字列
	 * @return 反転した文字列
	 */
	public static String myReverse(String pStr) {
		if (pStr.length() < 1) {
			return "";
		}

		StringBuffer sb = new StringBuffer(pStr);
		return sb.reverse().toString();
	}

	/**
	 * 余りを求める。
	 * @param a
	 * @param b
	 * @return 余り。余りがマイナスの時はプラスで返す。
	 */
	public static long myMod(long a, long b) {
		long ret = 0;

		ret = a % b;

		if (ret < 0) {
			ret += b;
		}

		return ret;
	}

	/**
	 * 乗数を求める ※mod対応
	 * @param kisu 基数
	 * @param josu 乗数
	 * @param primeNumMod_0 法 mod値 使わない場合は「0」
	 * @return
	 */
	public static long myPowWithMod(long kisu, long josu, long primeNumMod_0) {

		long ans = 1;

		//乗数が0の場合→1
		if (josu == 0)
			return 1;

		if (primeNumMod_0 == 0) {
			//modを使わないとき

			while (josu > 0) {

				if (josu % 2 == 0) {
					//累乗が偶数の時

					kisu *= kisu;
					josu = josu / 2;
				} else {
					//累乗が奇数の時
					ans *= kisu;
					josu--;
				}
			}

			return ans;

		} else {
			//modを使うとき

			//初めに桁を落とす
			kisu = myMod(kisu, primeNumMod_0);

			while (josu > 0) {

				if (josu % 2 == 0) {
					//累乗が偶数の時

					kisu *= myMod(kisu, primeNumMod_0);
					josu = josu / 2;

				} else {
					//累乗が奇数の時
					ans *= myMod(kisu, primeNumMod_0);
					josu--;

				}
			}

			return myMod(ans, primeNumMod_0);

		}

	}

}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
char s1[5], s2[5], s3[5];

int main() {
	while(~scanf("%s %s %s", s1, s2, s3)) {
		printf("%c%c%c\n", s1[0], s2[1], s3[2]);
	}
	return 0;
}


#include<cstdio>

using namespace std;

int main(){
	char s[3][10];
	scanf("%s %s %s", s[0], s[1], s[2]);
	printf("%c%c%c\n", s[0][0], s[1][1], s[2][2]);
	return 0;
}


#include <cstdio>

int main(int argc, char const *argv[]) {
    char a[4];
    char b[4];
    char c[4];
    scanf("%s%s%s", a, b, c);
    printf("%c%c%c\n", a[0], b[1], c[2]);
}


#include <bits/stdc++.h>
using namespace std;

int main() {
  string s;
  for(int i=0;i<3;i++) {
    cin >> s;
    cout << s[i] << endl;
  }
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    string a[3];
    for (int i = 0; i < 3; i++)
        cin >> a[i];
    string b = a[0].at(0);
    b += a[1].at(1);
    b += a[2].at(2);
    cout << b;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main()
{
    string a[3];
    for (int i = 0; i < 3; i++)
        cin << a[i];
    string b = a[0].at(0);
    b += a[1].at(1);
    b += a[2].at(2);
    cout << b;
    return 0;
}


#include<stdio.h>
int main()
{
    char c[4][4];
    int i;
    for (i = 0; i < 3; i++)
        scanf("%s", &c[i]);
    for (i = 0; i < 3; i++)
        printf("%c", c[i][i]);
    printf("\n");
    return 0;
}


#include<stdio.h>

int main(void){
    char c[3][4];
    int i;
    for(i=0;i<3;i++){
        scanf("%s",c[i]);
    }
    printf("%c%c%c\n",c[0][0],c[1][1],c[2][2]);
    return 0;
}


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>

int main() {

    char c1[4];
    char c2[4];
    char c3[4];

    scanf("%s %s %s", c1, c2, c3);

    printf("%c", c1[0]);
    printf("%c", c2[1]);
    printf("%c", c3[2]);

    return 0;

}


#include<stdio.h>
int main()
{
    char A[3][3];
    int i,j, p, q;
    for(i=0; i<3; i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%c", &A[i][j]);
        }
    }

    for(p=0; p<3; p++)
    {
        printf("%c", A[p][p]);
    }

    return 0;

}


#include<bits/stdc++.h>
using namespace std;
int main()
{
  char mat[3][3];
  int i,j;
  for(i=0;i<3;i++)
  {
    for(j=0;j<3;j++)
    {
      cin>>mat[i][j];
    }
  }
  string s ="";
  s=s+mat[0][0]+mat[1][1]+mat[2][2];
  cout<<s;
  return 0;
}


#include<stdio.h>

typedef struct {
	char m_aLetter[4];
}Squares_t;

void DisplayLetter(Squares_t* a_pstSquares);

int main(void) {
	//構造体変数の定義
	Squares_t astSquares[3];

	//変数に文字を入力
	scanf("%s", &astSquares[0].m_aLetter);
	scanf("%s", &astSquares[1].m_aLetter);
	scanf("%s", &astSquares[2].m_aLetter);

	DisplayLetter(&astSquares);

	return 0;
}

/**********
*3行3列に並んだアルファベットの中で左上、中央、右下の3つを順番に表示する関数
*　Squares_t* a_pstSquares　入力される文字の構造体
*/
void DisplayLetter(Squares_t* a_pstSquares) {
	int i;
	printf("\n");
	//並んだアルファベットの中で左上、中央、右下の3つを順番に表示
	for (i = 0; i < 3; i++) {
		printf("%c", a_pstSquares[i].m_aLetter[i]);
	}
	printf("\n");

	return 0;
}


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const L1 = arg[0].split("");
    const L2 = arg[1].split("");
    const L3 = arg[2].split("");

    console.log(L1[0] + L2[1] + L3[2]);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main (input) {
  input = input.split('\n');
  console.log(input[0][0]+input[1][1]+input[2][2]);
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


inp = require('fs').readFileSync('/dev/stdin', 'utf8').split('\n')
s = ''
for (i=0; i<3; i++) {
    s += inp[i][i]
}
console.log(s)


"use strict"

const Main=(input)=>{
  console.log(input)

  const Array=input.trim().split(/\n/)
  const Array1=Array[0].split(/\D/)
  const Array2=Array[1].split(/\D/)
  const Array3=Array[2].split(/\D/)
  const Answer=`${Array1[0]}${Array2[1]}${Array3[2]}`

  console.log(Answer)
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict"

const Main=(input)=>{
  console.log(input)

  const Array=input.trim().split(/\n/)
  const Array1=Array[0].split(/./)
  const Array2=Array[1].split(/./)
  const Array3=Array[2].split(/./)
  const Answer=`${Array1[0]}${Array2[1]}${Array3[2]}`

  console.log(Answer)
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


// inputに入力データ全体が入る
function Main(input) {
    console.log(input[0][0]+input[1][1]+input[2][2])
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func main() {
	sc.Split(bufio.ScanWords)
	c0 := getString()
	c1 := getString()
	c2 := getString()

	out(string(c0[0]) + string(c1[1]) + string(c2[2]))
}


package main

import (
	"fmt"
)

func main() {
	var a, b, c string
	fmt.Scan(&a, &b, &c)
	fmt.Printf("%s%s%s", a[0:1], b[1:2], c[2:3])
}


package main

import (
	. "fmt"
)

// func init() { Println("----------------------------------------") }

func main() {
    var s1, s2, s3 string
    Scanf("%s", &s1)
    Scanf("%s", &s2)
    Scanf("%s", &s3)

    Print(string(s1[0]), string(s2[1]), string(s3[2]))
}


package main

import (
    "os"
    "fmt"
    "bufio"
    "strconv"
)

func main() {
  var c [3][3]int

  scanner := bufio.NewScanner(os.Stdin)
  count := 0
  for scanner.Scan() {
    line := scanner.Text()
    c[count][0], _ = strconv.Atoi(string(line[0]))
    c[count][1], _ = strconv.Atoi(string(line[1]))
    c[count][2], _ = strconv.Atoi(string(line[2]))
    count++
    if count == 3 {
      break
    }
  }
  fmt.Printf("%d%d%d\n", c[0][0], c[1][1], c[2][2])
}


package main

import(
    "fmt"
)

func main() {
    var a,b,c int
    fmt.Scan(&a,&b,&c)
    fmt.Printf("%c%c%c",a[0],b[1],c[2])
}

func abs32(a int) int {
    if a<0{
        return -a
    }
    return a
}

func abs64(a int64) int64 {
    if a<0{
        return -a
    }
    return a
}

func min32(a, b int) int {
    if a >= b {
        return b
    }
    return a
}

func max32(a, b int) int {
    if a >= b {
        return a
    }
    return b
}

func min64(a, b int64) int64 {
    if a >= b {
        return b
    }
    return a
}

func max64(a, b int64) int64 {
    if a >= b {
        return a
    }
    return b
}

func gcd(a, b int64) int64 {
    if a % b == 0 {
        return b
    } else {
        return gcd(b, a%b)
    }
}

func lcm(a, b int64) int64 {
    return a / gcd(a, b) * b
}

func scanNums(len int) (nums []int){
    var num int
    for i:=0; i<len; i++{
        fmt.Scan(&num)
        nums = append(nums,num)
    }
    return
}

func scanNums64(len int) (nums []int64){
    var num int64
    for i:=0; i<len; i++{
        fmt.Scan(&num)
        nums = append(nums,num)
    }
    return
}

func scanString(len int) (str []string){
    var s string
    for i:=0; i<len; i++{
        fmt.Scan(&s)
        str = append(str,s)
    }
    return
}

func scanTwoNums(n,m int) ([][]int){
    Nums := make([][]int, n)
    for i:=0; i<n; i++{
        Nums[i] = make([]int, m)
    }
    return Nums
}


package main

import "fmt"

func main(){
  ls = make([]string, 9)
  for i:=0; i < 9; i++{
    fmt.Scan(&ls[i])
  }
  fmt.Println(ls[0] + ls[3] + ls[8])
}


a,b,c=3.times.map{gets.chomp}
puts a[0] + b[1] + c[2]


s1 = gets
s2 = gets
s3 = gets
puts s1[0]+s2[1]+s3[2]


c = Array.new(3) { gets.chomp.chars }
puts c[0][0] + c[1][1] + c[2][2]


a = gets.chomp.to_s
b = gets.chomp.to_s
c = gets.chomp.to_s

ar1 = [a, a, a]
ar2 = [b, b, b]
ar3 = [c, c, c]

puts ar1.slice(0) && ar2.slice(1) && ar3.slice(2)


c1 = gets.split(" ").map(&:to_s)
c2 = gets.split(" ").map(&:to_s)
c3 = gets.split(" ").map(&:to_s)
puts c1[0] + c2[1] + c3[2]


first = gets.chomp.split("")
second = gets.chomp.split("")
third = gets.chomp.split("")

puts first.fisrt + second[1] + third.last


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        c: [chars;3]
    }
    let v = vec![c[0][0],c[1][1],c[2][2]];
    println!("{}",
        v.into_iter().collect::<String>());
}


fn main(){
    let mut c1 = String::new();
    let mut c2 = String::new();
    let mut c3 = String::new();

    std::io::stdin().read_line(&mut c1);
    std::io::stdin().read_line(&mut c2);
    std::io::stdin().read_line(&mut c3);

    println!("{}{}{}",c1.remove(0),c2.remove(1),c3.remove(2));
}


use std::io;

fn main() {
	let mut v:Vec<char> = Vec::new();
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s:Vec<char> = buf.trim().chars().collect();
	v.push(s[0]);
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s:Vec<char> = buf.trim().chars().collect();
	v.push(s[1]);
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let s:Vec<char> = buf.trim().chars().collect();
	v.push(s[2]);
	for i in v{
		print!("{}", i);
	}
	println!("");
}


#[allow(unused_imports)]
use itertools::Itertools;
#[allow(unused_imports)]
use num::*;
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::collections::*;

fn main() {
  input! {
    grid: [Chars; 3]
  };

  let res = format!("{}{}{}", grid[0][0], grid[1][1], grid[2][2]);
  println!("{}", res);
}


use std::str::FromStr;
use std::fmt::Debug;

fn read_line<T>() -> Vec<T>
    where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()
}

fn main() {

    for i in 0..3 {
        let x:String = read_line();
        println!("{}", x.chars().nth(i).unwrap());
    }
}


fn read_line() -> String {
    let mut in_str = String::new();
    io::stdin().read_line(&mut in_str).unwrap();
    return in_str.trim().to_string();
}

fn main() {

    for i in 0..3 {
        println!("{}", read_line().chars().nth(i).unwrap());
    }
}


var s="";for i in 0..<3{s+=readLine()!.characters.map{String($0)}[i]};print(s)


let rd = 10000//Int(readLine()!)!
func sumDigits(_ num: Int) -> Int {
  var num = num
  var sum = 0
  while num > 0 {
    sum += num%10
    num /= 10
  }
  return sum
}

var min = 100
for i in 1 ... rd/2+1 {
  var j = rd - i
  if sumDigits(i) + sumDigits(j) < min {
    min = sumDigits(i) + sumDigits(j)
  }
}
print(min)


let rd = Int(readLine()!)!
func sumDigits(_ num: Int) -> Int {
  var num = num
  var sum = 0
  while num > 0 {
    sum += num%10
    num /= 10
  }
  return sum
}

var min = 100
for i in 1 ... rd {
  var j = rd - i
  if i + sumDigits(j) < min {
    min = i + sumDigits(j)
  }
}
print(min)


var s="";for i in 0..<3{s+=readLine()!.characters.map{$0}[i]};print(s)


const main = (input) => {
  input = input.split('\n');
  const A = input[0];
  const B = input[1];
  const C = input[2];

  console.log(A[0]+B[1]+C[2]);

}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));