Problem:


Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0



Sample input:
2 5
10 12 1 2 14


Sample output:
5

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n = n//a
    count += 1
  if a**count == n:
    return count
  else:
    return count+1

#############
# Main Code #
#############

N,M = IL()
X = IL()

X.sort()
D = []

for i in range(M-1):
  D.append(X[i+1]-X[i])
  
D.sort()

if N>=M:
  PE(0)

P(sum(D[:M-N]))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
x = input().split()

if n >= m:
  	print(0)
else:
  for i in range(m):
    x[i] = int(x[i])
  x.sort()
  ans = x[-1] - x[0]
  #print(ans)
  b = []
  for i in range(m-1):
  	b.append(x[i+1]-x[i])
  b.sort()
  #print(b)
  for i in range(1,n):
    #print(i,b[-i])
    ans -= b[-i]
  print(ans)

Submission status: Accepted

Solution code:
from itertools import *

n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
dis=[]
for i in range(1,m):
    dis.append(x[i]-x[i-1])
dis.sort()

if n>=m:
    print(0)
else:
    for i in range(n-1):
        dis.pop(-1)
    print(sum(dis))

Submission status: Accepted

Solution code:
import numpy as np

n, _ = map(int, input().split())
x = np.array(list(map(int, input().split())))

x.sort()
dist = x.max() - x.min()
x = np.diff(x)
x.sort()

ans = dist - x[::-1][:n - 1].sum()

print(ans)

Submission status: Accepted

Solution code:
import sys
# from collections import deque
# import bisect
# import math
# import itertools
# from queue import deque
# from math import gcd

INF = float('inf')
mod = 10**9+7
eps = 10**-7


def inp(): return int(sys.stdin.readline())


def inp_list(): return list(map(int, sys.stdin.readline().split()))


def lcm(x, y): return (x * y) // gcd(x, y)


N, M = inp_list()
X = inp_list()
X.sort()
# print(X)

if N >= M:
    print(0)
    exit()

d = [X[i + 1] - X[i] for i in range(M - 1)]
# for i in range(M - 1): d.append(X[i + 1] - X[i])
# print(d)
d.sort()
ans = sum(d[: M - 1 - (N - 1)])
# ans = 0
# for i in range(M - 1 -  (N - 1)):
    # ans += d[i]
print(ans)

Submission status: Accepted

Solution code:
import sys
# from collections import deque
# import bisect
# import math
# import itertools
# from queue import deque
# from math import gcd

INF = float('inf')
mod = 10**9+7
eps = 10**-7


def inp(): return int(sys.stdin.readline())


def inp_list(): return list(map(int, sys.stdin.readline().split()))


def lcm(x, y): return (x * y) // gcd(x, y)


N, M = inp_list()
X = inp_list()
X.sort()
# print(X)

if N >= M:
    print(0)
    exit()

d = [X[i + 1] - X[i] for i in range(M - 1)]
# for i in range(M - 1): d.append(X[i + 1] - X[i])
# print(d)
d.sort()
# ans = sum(d[: - (N - 1)])
ans = 0
for i in range(M - 1 -  (N - 1)):
    ans += d[i]
print(ans)

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=1
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def main():
	#a = int(input())
	n, m = tin()
	al = lin()
	#s = input()
	al.sort()
	diff_al = [abs(vj-vi) for vi, vj in zip(al, al[1:])]
	#pa(al)
	#pa(diff_al)
	diff_al.sort()
	#pa(diff_al)
	if n == 1:
		ret = sum(diff_al)
	else:
		ret = sum(diff_al[:-(n-1)])
	print(ret)
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
L = sorted(map(int, input().split()))
d = [L[i + 1] - L[i] for i in range(m - 1)]
d.sort(reverse=True)
print(sum(d[(n - 1):]))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
L = sorted(map(int, input().split()))
d = [0] * (m - 1)
for i in range(1, m):
    d[i - 1] = abs(L[i] - L[i - 1])
d = sorted(d, reverse=True)[(n - 1):]
print(sum(d))

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
X = sorted(list(map(int,input().split())))

dX = [X[i+1]-X[i] for i in range(M-1)]
dX.sort()
p = N - 1
print(sum(dX[:-p]) if p != 0 else sum(dX))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
x = list(map(int,input().split()))
x.sort()
l = x[-1] - x[0]
y = []
for i in range(m-1):
  y.append(x[i+1]-x[i])
y.sort(reverse=True)
print(l-sum(y[:(n-1)]))

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
X=sorted([int(i)for i in input().split()])
print(sum(sorted([X[i+1]-X[i]for i in range(M-1)])[:max(M-N,0)]))

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import copy
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

N, M = getNM()
X = getList()
X. sort()
Xalta = []
for i in range(M - 1):
    Xalta.append(-1 * abs(X[i + 1] - X[i]))
heapq.heapify(Xalta)

for i in range(N - 1):
    if len(Xalta) > 0:
        heapq.heappop(Xalta)
print(sum(Xalta) * -1)

Submission status: Accepted

Solution code:
m, n = map(int, input().split())
a = [int(x) for x in input().split()]
a.sort()
b = [a[i+1]-a[i] for i in range(n-1)]
b.sort(reverse=True)

print(a[-1]-a[0]-sum(b[:min([m-1, n-1])]))

Submission status: Accepted

Solution code:
# coding: utf-8
import re
import math
from collections import defaultdict
from collections import deque
from fractions import Fraction
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
#@lru_cache(maxsize=None)
readline=sys.stdin.readline
sys.setrecursionlimit(2000000)
#import numpy as np
alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_pow(a,b):#aはbの累乗数か
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def get_facs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def get_primes(n,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def pm(x):
    return x//abs(x)
def inputintlist():
    return list(map(int,input().split()))
######################################################################################################
def main():
    N,M=inputintlist()
    X=inputintlist()
    X.sort()
    if N>=M:
        print(0)
    else:
        kukan=[]
        for a in range(M-1):
            kukan.append(X[a+1]-X[a])
        kukan.sort()
        kukan.reverse()
        ans=X[-1]-X[0]
        ans-=sum(kukan[:N-1])
        print(ans)
main()

Submission status: Accepted

Solution code:
def main():
    N, M = [int(v) for v in input().split(' ')]
    X = sorted([int(v) for v in input().split(' ')])

    if N >= M:
        print(0)
        return

    l = []
    x0 = X[0]
    for x in X[1:]:
        dx = x - x0
        l.append(dx)
        x0 = x

    sl = sorted(l)

    count = 0
    for v in sl[0:M - N]:
        count += v
    print(count)


main()

Submission status: Accepted

Solution code:
import sys
#from collections import defaultdict, deque, Counter
#import bisect
#import heapq
#import math
#from itertools import accumulate
#from itertools import permutations as perm
#from itertools import combinations as comb
#from itertools import combinations_with_replacement as combr
#from fractions import gcd
#import numpy as np

stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)
MIN = -10 ** 9
MOD = 10 ** 9 + 7
INF = float("inf")
IINF = 10 ** 18

def main():
    #n = int(stdin.readline().rstrip())
    n,m = map(int, stdin.readline().rstrip().split())
    x = list(map(int, stdin.readline().rstrip().split()))
    #numbers = [[int(c) for c in l.strip().split()] for l in sys.stdin]
    #word = [stdin.readline().rstrip() for _ in range(n)]
    #number = [[int(c) for c in stdin.readline().rstrip()] for _ in range(n)]
    #zeros = [[0] * w for i in range(h)]
    if n>m:
        print(0)
        exit()
    spl = n-1
    sa = [0]*(m-1)
    x.sort()
    for i in range(m-1):
        sa[i] = x[i+1] - x[i]
    sa.sort()
    i = m-n
    print(sum(sa[:i]))



main()

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
if N>=M:
    X=[int(i) for i in input().split()]
    print(0)
else:
    X=[int(i) for i in input().split()]
    a=sorted(X)
    d=[]
    for i in range(M-1):
        d.append(a[i+1]-a[i])
    k=sorted(d)
    print(sum(k[:M-N]))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = [int(x) for x in input().split()]
X.sort(reverse=True)
X_diff = []
for i in range(len(X)-1):
    X_diff.append(X[i] - X[i+1])
X_diff.sort()
if N < M:
    print(sum(X_diff[:M-N]))
else:
    print(0)

Submission status: Accepted

Solution code:
# Python3 (3.4.3)
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# function
# -------------------------------------------------------------


# -------------------------------------------------------------
# main
# -------------------------------------------------------------
N,M = map(int,input().split())
X = list(map(int,input().split()))

if N >= M:
    print(0)
else:
    X.sort()
    D = []
    for i in range(M-1):
        D.append(X[i+1]-X[i])
    D.sort()
    print(sum(D[0:M-N]))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())

if n >= m:
    print(0)
    exit()
    
lis = list(map(int, input().split()))
lis.sort()

res = []
for i in range(m - 1):
    res.append(lis[i + 1] - lis[i])
res.sort()

l = len(res)
k = n - 1

print(sum(res[:l - k]))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
k = sorted(list(map(int, input().split())))

if n >= m:
    print(0)
    exit()
dis = []
for i in range(m-1):
    dis.append(k[i+1] - k[i])

dis.sort()
dis.reverse()
sub = 0
#print(dis)
for i in range(n-1):
    sub += dis[i]
    
print(sum(dis) - sub)

Submission status: Accepted

Solution code:
import itertools
import math
import fractions
import functools
import copy
n, m = map(int, input().split())
x  = list(map(int, input().split()))

sub = []
x.sort()
for i in range(m-1):
    sub.append(abs(x[i]-x[i+1]))

sub.sort(reverse=True)
if n >= m:
    print(0)
    quit()
for i in range(n-1):
    sub[i] = 0
print(sum(sub))

Submission status: Accepted

Solution code:
import sys
from heapq import heappush, heappop
def input(): return sys.stdin.readline().strip()


def main():
    N, M = map(int, input().split())
    X = list(map(int, input().split()))
    if M <= N:
        print(0)
        return
    X.sort(reverse=True)
    diff = []
    pre = X.pop()
    for i in range(M - 1):
        cur = X.pop()
        heappush(diff, cur - pre)
        pre = cur
    ans = 0
    for _ in range(M - N):
        ans += heappop(diff)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
x = list(map(int, input().split()))
if n >= m:
    print(0)
    exit()
x.sort()
l = []
for i in range(m - 1):
    l.append(x[i + 1] - x[i])
l.sort()
print(sum(l[: m - n]))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
Xm = list(map(int, input().split()))
if n >= m:
    print(0)
else:
    Xm.sort()
    check = [Xm[i+1] - Xm[i] for i in range(m-1)]
    check.sort(reverse=True)
    print(sum(check) - sum(check[:n-1]))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
Xm = list(map(int, input().split()))
Xm.sort()
check = [Xm[i+1] - Xm[i] for i in range(m-1)]
check.sort()
print(sum(check[:max(m-n, 0)]))

Submission status: Accepted

Solution code:
# coding: utf-8
# hello worldと表示する
#dpでできないかな？
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,m=MI()
lis=LI()
if n>=m:
    print(0)
    sys.exit()
lis.sort()
dis=[]
for i in range(m-1):
    dis.append(lis[i+1]-lis[i])
ans=0
dis.sort()
for i in range(m-n):
    ans+=dis[i]
print(ans)

Submission status: Accepted

Solution code:
N, M = map(int, input().split(' '))
if N >= M:
    print(0)
else:
    points = sorted(tuple(map(int, input().split(' '))))
    distances = sorted([abs(p1 - p2) for p1, p2 in zip(points, points[1:])], reverse=True)
    print(sum(distances[N - 1:]))

Submission status: Accepted

Solution code:
n, m = [int(i) for i in input().split()]
x = sorted([int(i) for i in input().split()])
a = list(reversed(sorted([x[i+1] - x[i] for i in range(m-1)])))
print(sum(a[n-1:]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# sys.stdin.readline()
import numpy as np

import math

n,m = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
B = [-A[i]+A[i+1] for i in range(m-1)]
B.sort()
print(sum(B[0:max(m-n,0)]))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())

if (M <= N):
    print(0)
else:
    Xs = list(map(int, input().split()))
    Xs.sort()
    W = Xs[-1] - Xs[0]
    Ds = [Xs[i+1]-Xs[i] for i in range(M-1)]
    Ds.sort(reverse=True)

    gaps = 0
    for i in range(N-1):
        gaps += Ds[i]

    print(W-gaps)

Submission status: Accepted

Solution code:
import heapq
n,m = map(int,input().split())
x_input = sorted(list(map(int,input().split())))

cost_li = []
for i in range(m-1):
    heapq.heappush(cost_li,-(x_input[i+1]-x_input[i]))

for i in range(n-1):
    if len(cost_li)==0:
        print(0);exit()
    heapq.heappop(cost_li)

print(-sum(cost_li))

Submission status: Accepted

Solution code:
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))

n,m = iim()
X = iil()
X.sort()

dif = []
for i in range(1,m):
    dif.append(X[i]-X[i-1])

dif.sort(reverse=True)
#print(dif)
#print(X[-1],X[0],sum(dif[:n-1]))
print(X[-1]-X[0]-sum(dif[:n-1]))

Submission status: Accepted

Solution code:
n,m = map(int, input().split())
T = list(map(int, input().split()))

if n >= m:
    print(0)
    exit()

T.sort()
diff = []
for i in range(1,m):
    diff.append(T[i]-T[i-1])
diff.sort(reverse=True)
print(sum(diff[n-1:]))

Submission status: Accepted

Solution code:

"""
全探索は無理なオーダー
N個のこま，
M - N回の移動が必要
−＞間の距離の長いのを移動しないように配置すれば良い
"""
N, M = map(int, input().split())
X = list(map(int, input().split()))
X.sort()
if N >= M:
    print(0)
    exit()

dist = [X[i+1] - X[i] for i in range(M-1)]
dist.sort(reverse=True)

count = sum(dist)
for i in range(N-1):
    count -= dist[i]

print(count)

Submission status: Accepted

Solution code:
import heapq

N,M = (int(x) for x in input().split())
X = list(map(int, input().split()))
if N >= M:
    print('0')
else:
    heapq.heapify(X)
    t1 = heapq.heappop(X)
    diff = []
    for i in range(M-1):
        t2 = heapq.heappop(X)
        diff.append(t2-t1)
        t1 = t2
    heapq.heapify(diff)
    ans = 0
    for i in range(M-N):
        ans += heapq.heappop(diff)
    print(ans)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
if n >= m:
    print(0)
    exit()
l = list(map(int, input().split()))
l.sort()
t = l[0]
a = []
for i in l[1:]:
    a.append(i-t)
    t = i
a.sort(reverse=True)
print(sum(a[n-1:]))

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = 10**18
# ----------------------------------------------------------- #

n, m = Is()
X = LI()
X.sort()
D = []
for i in range(1, m):
    D.append(X[i]-X[i-1])
D.sort(reverse=True)
print(X[-1]-X[0]-sum(D[:n-1]))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N, M = map(int, input().split())
    X = list(map(int, input().split()))
    X.sort()

    dist = []
    for i in range(1, M):
        dist.append(X[i] - X[i - 1])

    dist.sort(reverse=True)

    if N >= M:
        print(0)
    else:
        # N - 1個の開いた区間が出てくる
        ans = sum(dist[N - 1 :])
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed May 13 13:45:08 2020

@author: shinba
"""
import sys
n,m = map(int,input().split())

X = list(map(int,input().split()))

if n >= m:
    print(0)
    sys.exit()

sub = []
X.sort()

for i in range(m-1):
    sub.append(X[i+1]-X[i])

sub.sort()

for i in range(n-1):
    sub.pop()

print(sum(sub))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, m = mi()
    X = lmi()
    X.sort()
    if m <= n:
        print(0)
    else:
        diff = [X[i] - X[i-1] for i in range(1, m)]
        diff.sort()
        print(sum(diff[:m-n]))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
X=sorted(list(map(int,input().split())))

if N >= M:
  print(0)
  exit()
D=[0]*(M-1)
for i in range(1,M):
  D[i-1] = X[i]-X[i-1]
D.sort()
D.reverse()
D_pass=0
for i in range(N-1):
  D_pass+=D[i]
print(X[-1]-X[0]-D_pass)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import collections
import itertools as it
import math
#import numpy as np
 
#  = input()
#  = int(input())
n, m  = map(int, input().split())
x  = list(map(int, input().split()))
#  = [int(input()) for i in range(N)]
#
# c = collections.Counter()

x.sort()
q = [x1 - x2 for x1, x2 in zip(x[1:], x[:-1])]
q = sorted(q)[::-1]

print(sum(q[n-1:]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

N, M = map(int, input().split())
X = sorted(list(map(int, input().split())))

D = {}

for i in range(M-1):
    D[(X[i],X[i+1])] = X[i+1] - X[i]

s_D = sorted(D.items(), key=lambda x:x[1])[::-1]
A = s_D[N-1:]
ans = 0
for a in A:
    ans += a[1]
print(ans)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(map(int, input().split()))
X.sort()

if N >= M:
    print(0)
else:
    sub = [0]*(M-1)
    for i in range(M-1):
        sub[i] = X[i+1]-X[i]
    sub.sort()

    ans = 0
    for i in range(M-N):
        ans += sub[i]
    print(ans)

Submission status: Accepted

Solution code:
n, m = list(map(int, input().split()))
#n, m = list(map(int, input().split()))
x = list(map(int, input().split()))
# abc = [int(input()) for i in range(5)]
# n = int(input())
# n, m = list(map(int, input().split()))
if n >= m:
    print(0)
else:
    x.sort()
    ans = x[-1]-x[0]
    p = []
    for i in range(m-1):
        p.append(x[i+1]-x[i])
    p.sort(reverse=True)
    for i in range(n-1):
        ans -= p[i]
    print(ans)

Submission status: Accepted

Solution code:
n, m=map(int, input().split())
x=list(map(int, input().split()))

if n>=m:#全ての座標にコマを置ける
    print(0)
else:
    x.sort()
    dif=[]
    for i in range(m-1):#座標間距離を求める
        dif.append(x[i+1]-x[i])
    
    dif.sort()
    
    S=sum(dif)
    remove=0
    
    for j in range(1, n):#(コマの数-1)だけ長い区間を除く
        remove+=dif[-j]

    print(S-remove)

Submission status: Accepted

Solution code:
n, m=map(int, input().split())
x=list(map(int, input().split()))

if n>=m:
    print(0)
else:
    x.sort()
    dif=[]
    for i in range(m-1):
        dif.append(x[i+1]-x[i])
    
    dif.sort()
    S=sum(dif)
    remove=0
    
    for j in range(1, n):
        remove+=dif[-j]

    print(S-remove)

Submission status: Accepted

Solution code:
N, M = [int(i) for i in input().split()]
X = [int(i) for i in input().split()]

if N >= M:
    print(0)
    exit()
    
X.sort()
L = []
for i in range(1,M):
    L.append(X[i]-X[i-1])
    
L.sort(reverse=True)

tmp = 0

for i in range(N-1):
    tmp += L[i]
    
print(X[-1]-X[0]-tmp)