import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.StringTokenizer;

public class B {

	public static void main(String[] args) throws IOException {
		FastScanner scan = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt(), m = scan.nextInt();
		int[] f = new int[n];
		HashSet<Integer>[] adj = new HashSet[n];
		for(int i = 0; i < n; i++) adj[i] = new HashSet<Integer>();
		for(int i = 0; i < n; i++) f[i] = i;
		for(int i = 0; i < m; i++){
			int x = scan.nextInt()-1, y = scan.nextInt()-1;
			adj[y].add(x);
			adj[x].add(y);
		}
		boolean good = true;
		boolean[] v = new boolean[n];
		for(int i = 0; i < n; i++){
			if(!v[i]){
				ArrayDeque<Integer> q = new ArrayDeque<>();
				q.add(i);
				v[i] = true;
				int nodes = 0, edges = 0;
				while(!q.isEmpty()){
					int at = q.poll();
					nodes++;
					edges += adj[at].size();
					for(int j : adj[at]) if(!v[j]){
						v[j] = true;
						q.add(j);
					}
				}
				if(nodes*(nodes+1)/2 > edges) good = false;
			}
		}
		out.println(good?"YES":"NO");
		out.close();
	}

	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner() {
			try	{
				br = new BufferedReader(new InputStreamReader(System.in));
				st = new StringTokenizer(br.readLine());
			} catch (Exception e){e.printStackTrace();}
		}

		public String next() {
			if (st.hasMoreTokens())	return st.nextToken();
			try {st = new StringTokenizer(br.readLine());}
			catch (Exception e) {e.printStackTrace();}
			return st.nextToken();
		}

		public int nextInt() {return Integer.parseInt(next());}

		public long nextLong() {return Long.parseLong(next());}

		public double nextDouble() {return Double.parseDouble(next());}

		public String nextLine() {
			String line = "";
			try {line = br.readLine();}
			catch (Exception e) {e.printStackTrace();}
			return line;
		}

		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for(int i = 0; i < n; i++) a[i] = nextInt();
			return a;
		}

		public long[] nextLongArray(int n){
			long[] a = new long[n];
			for(int i = 0; i < n; i++) a[i] = nextLong();
			return a;
		}

		public double[] nextDoubleArray(int n){
			double[] a = new double[n];
			for(int i = 0; i < n; i++) a[i] = nextDouble();
			return a;
		}

		public char[][] nextGrid(int n, int m){
			char[][] grid = new char[n][m];
			for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
			return grid;
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;

public class B {

	public static void main(String[] args) throws IOException {
		FastScanner scan = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt(), m = scan.nextInt();
		int[] f = new int[n];
		HashSet<Integer>[] adj = new HashSet[n];
		for(int i = 0; i < n; i++) adj[i] = new HashSet<Integer>();
		for(int i = 0; i < n; i++) f[i] = i;
		for(int i = 0; i < m; i++){
			int x = scan.nextInt()-1, y = scan.nextInt()-1;
			adj[y].add(x);
			adj[x].add(y);
		}
		boolean good = true;
		boolean[] v = new boolean[n];
		for(int i = 0; i < n; i++){
			if(!v[i]){
				ArrayDeque<Integer> q = new ArrayDeque<>();
				q.add(i);
				v[i] = true;
				int c = 0;
				ArrayList<Integer> a = new ArrayList<>();
				while(!q.isEmpty()){
					int at = q.poll();
					c++;
					a.add(at);
					for(int j : adj[at]) if(!v[j]){
						v[j] = true;
						q.add(j);
					}
				}
				for(int j : a) if(adj[j].size() < c-1) good = false;
			}
		}
		out.println(good?"YES":"NO");
		out.close();
	}

	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner() {
			try	{
				br = new BufferedReader(new InputStreamReader(System.in));
				st = new StringTokenizer(br.readLine());
			} catch (Exception e){e.printStackTrace();}
		}

		public String next() {
			if (st.hasMoreTokens())	return st.nextToken();
			try {st = new StringTokenizer(br.readLine());}
			catch (Exception e) {e.printStackTrace();}
			return st.nextToken();
		}

		public int nextInt() {return Integer.parseInt(next());}

		public long nextLong() {return Long.parseLong(next());}

		public double nextDouble() {return Double.parseDouble(next());}

		public String nextLine() {
			String line = "";
			try {line = br.readLine();}
			catch (Exception e) {e.printStackTrace();}
			return line;
		}

		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for(int i = 0; i < n; i++) a[i] = nextInt();
			return a;
		}

		public long[] nextLongArray(int n){
			long[] a = new long[n];
			for(int i = 0; i < n; i++) a[i] = nextLong();
			return a;
		}

		public double[] nextDoubleArray(int n){
			double[] a = new double[n];
			for(int i = 0; i < n; i++) a[i] = nextDouble();
			return a;
		}

		public char[][] nextGrid(int n, int m){
			char[][] grid = new char[n][m];
			for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
			return grid;
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.concurrent.SynchronousQueue;

public class B {

	public static void main(String[] args) throws IOException {
		FastScanner scan = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt(), m = scan.nextInt();
		int[] f = new int[n];
		HashSet<Integer>[] adj = new HashSet[n];
		for(int i = 0; i < n; i++) adj[i] = new HashSet<Integer>();
		for(int i = 0; i < n; i++) f[i] = i;
		for(int i = 0; i < m; i++){
			int x = scan.nextInt()-1, y = scan.nextInt()-1;
			adj[y].add(x);
			adj[x].add(y);
		}
		boolean good = true;
		boolean[] v = new boolean[n];
		for(int i = 0; i < n; i++){
			if(!v[i]){
				ArrayDeque<Integer> q = new ArrayDeque<>();
				q.add(i);
				v[i] = true;
				int nodes = 0, edges = 0;
				while(!q.isEmpty()){
					int at = q.poll();
					nodes++;
					edges += adj[at].size();
					for(int j : adj[at]) if(!v[j]){
						v[j] = true;
						q.add(j);
					}
				}
				if(nodes > 1 && nodes*(nodes+1)/2 > edges) good = false;
			}
		}
		out.println(good?"YES":"NO");
		out.close();
	}

	static class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner() {
			try	{
				br = new BufferedReader(new InputStreamReader(System.in));
				st = new StringTokenizer(br.readLine());
			} catch (Exception e){e.printStackTrace();}
		}

		public String next() {
			if (st.hasMoreTokens())	return st.nextToken();
			try {st = new StringTokenizer(br.readLine());}
			catch (Exception e) {e.printStackTrace();}
			return st.nextToken();
		}

		public int nextInt() {return Integer.parseInt(next());}

		public long nextLong() {return Long.parseLong(next());}

		public double nextDouble() {return Double.parseDouble(next());}

		public String nextLine() {
			String line = "";
			try {line = br.readLine();}
			catch (Exception e) {e.printStackTrace();}
			return line;
		}

		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for(int i = 0; i < n; i++) a[i] = nextInt();
			return a;
		}

		public long[] nextLongArray(int n){
			long[] a = new long[n];
			for(int i = 0; i < n; i++) a[i] = nextLong();
			return a;
		}

		public double[] nextDoubleArray(int n){
			double[] a = new double[n];
			for(int i = 0; i < n; i++) a[i] = nextDouble();
			return a;
		}

		public char[][] nextGrid(int n, int m){
			char[][] grid = new char[n][m];
			for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
			return grid;
		}
	}

}


t = int(input())
for i in range(t):
    a = int(input())
    print(a)


def solve(a):
	binary = f"{a:b}"
	return 2 ** binary.count("1")

n = int(input())
for i in range(n):
	a = int(input())
	print(solve(a))


t = int(input())
for i in range(t):
    n = int(input())
    s = bin(n)
    ans = 2 ** (s.count('1'))
    print(ans if n != 0 else 1)


t = int(input())
for i in range(t):
    n = int(input())
    s = bin(n)
    ans = 2 ** (s.count('1'))
    print(ans if i != 0 else 1)


import math
def bitsoncount(x):
    b = 0
    while x > 0:
        x &= x - 1
        b += 1
    return b
t = int(input())
res = []
for _ in range(t):
    a = int(input())
    res.append(bitsoncount(a))
for x in res:
    print(int(math.pow(2,x)))


t =int(input())
while t>0:
    t-=1;
    n=int(input())
    s=str(bin(n))
    cnt = 0
    for ch in s:
        if ch =='1':
            cnt+=1
    # print(s)
    ans = ''
    if cnt == 0:
        ans = '0'
    else:
       for i in range(0,cnt):
           ans += '1'
    print(int(ans,2)+1)


mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
t=ii()
for _ in range(t):
    print(2**(bin(ii()).count('1')))


# AC
import sys

class Main:
    def __init__(self):
        self.buff = None
        self.index = 0

    def next(self):
        if self.buff is None or self.index == len(self.buff):
            self.buff = sys.stdin.readline().split()
            self.index = 0
        val = self.buff[self.index]
        self.index += 1
        return val

    def next_int(self):
        return int(self.next())

    def solve(self):
        for i in range(0, self.next_int()):
            t = self.next_int()
            a = 1
            while t > 0:
                if t & 1 == 1:
                    a <<= 1
                t >>= 1
            print(a)

if __name__ == '__main__':
    Main().solve()


t=int(input())
r=[]
for i in range(t):
    a=int(input())
    b=bin(a)
    s=str(b)
    temp=1
    for j in range(len(s)):
        if s[j]=='1':
            temp*=2
    r.append(str(temp))
print('\n'.join(r))


for _ in range(int(input())):
    print(2**bin(int(input())).count('1'))


n=int(input())
for i in range(n):
    print( 2**(bin(int(input())).count("1")) )


import math
t=int(input())
while t>0:
    t-=1
    n=int(input())
    print(pow(2,bin(n).count('1')))


import math
def countnum1(num):
    ans=0
    while num>0:
        if num&1:
            ans+=1
        num>>=1
    return ans
t=int(input())
while t>0:
    t-=1
    n=int(input())
    print(pow(2,countnum1(n)))


t=int(input())
for q in range(t):
	a=int(input())
	b=bin(a)[2:]
	s=b.count('1')
	print(1<<s)


import math
t = int(input())
while(t > 0):

    s = input()
    print(int(math.pow(2, str(bin(int(s))).count('1'))))
    t = t-1


#Jestem najlepszy

import math
n = int(input())

def func(x):
  s = math.bin(x)
  return

for i in range(n):
  x = int(input())
  bn = bin(x)
  t = bn.count('1')
  print(2**t)


///Jestem najlepszy

import math
n = int(input())

def func(x):
  s = math.bin(x)
  return

for i in range(n):
  x = int(input())
  bn = bin(x)
  t = bn.count('1')
  print(2**t)


t = int(input())
for i in range(t):
    cnt = 0
    x = y = int(input())
    while x != 0:
        mod = int(x % 2)
        x /= 2
        if mod == 1:
            cnt += 1

    print(2 ** cnt)


t = int(input())
for i in range(t):
	n = int(input())
	t = "{0:b}".format(n)
	one = t.count("1")
	print(2**one)


t=int(input())
for i in range(t):
    inp=int(input())
    cmp=0
    for j in range(30):
        if(inp&(1<<j)):
            cmp+=1
    print(1<<cmp)


for _ in range(int(input())):
    x=bin(int(input()))
    b=x.count("1")
    print(1 << b)


#include <iostream>

using namespace std;

int main()
{
	int a, b, c;
	cin >> a;
	for (int i = 0; i < a;i++) {
		cin >> b;
		if (b % 2 != 0){
			cout << b + 1;
		}
		else {
			cout << b / 2 + 1;
		}
	}
}


n=int(input())
for _ in range(n):
    print(2**(bin(int(input())).count('1')))


n=int(input())
for _ in range(n):
    t=int(input())
    if t==0:
        print(1)
    elif t%2==0:
        print(t)
    else:
        print(t+1)


t = int(input())
for _ in range(t):
  n = int(input())
  ans = 0
  for i in range(32):
    if n & (1 << i):
      ans += 1

  ans = 1 << ans
  print(ans)


for _ in range(int(input())):
    a = int(input())
    b = bin(a)[2:]
    if a == 0:
        print(1)
    elif b[1] == '0':
        print(a)
    else:
        print(int('1' + '0' * len(b), 2))


for _ in range(int(input())):
    a = int(input())
    print(a + 1 if a & 1 else a)


for _ in range(int(input())):
    a = int(input())
    b = bin(a)[2:]
    if a <= 1:
        print(1)
    elif b[1] == '0':
        print(a)
    else:
        print(int('1' + '0' * len(b), 2))


for _ in range(int(input())):
    a = int(input())
    b = bin(a)[2:]
    if a == 0:
        print(1)
    elif a == 1:
        print(0)
    elif b[1] == '0':
        print(a)
    else:
        print(int('1' + '0' * len(b), 2))


for _ in range(int(input())):
    a = int(input())
    b = bin(a)[2:].count('1')
    print(int('1' + '0' * b, 2))


for _ in range(int(input())):
    a = int(input())
    b = bin(a)[2:]
    if a == 0:
        print(1)
    elif a == 1:
        print(2)
    elif b[1] == '0':
        print(a)
    else:
        print(int('1' + '0' * len(b), 2))


n = int(input())
for i in range (0,n):
    z = int(input())
    ones = bin(z).count("1")
    print(2**ones)


def isPower(a):
    if ((a&(a-1))==0):
        return (1)
    else:
        return (0)

t = int(input())
for i in range (t):
    a = int(input())
    if (a==0):
        print (1)
    elif (isPower(a)==1):
        print (2)
    else:
        print (a+1)


t = int(input())
for i in range (t):
    a = int(input())
    if (a==0):
        print (1)
    elif (a%2==0):
        print (a)
    else:
        print (a+1)


t = int(input())
for i in range (t):
    a = int(input())
    d = 0
    while (a>=1):
        if (a%2==0):
            a = a/2
        else:
            a = (a-1)/2
            d = d+1
    print (2**d)


m = [int(input()) for _ in range(int(input()))]
for i in m:
    print(2**len([1 for i in str(bin(i))[2:] if i == '1']))


print(2**len([1 for i in str(bin(int(input())))[2:] if i == '1']))


print('\n'.join([str(2**len([_ for i in str(bin(int(input())))[2:]if int(i)]))for _ in range(int(input()))]))


for i in [int(input()) for _ in range(int(input()))]:
    print(2**len([1 for i in str(bin(i))[2:]if int(i)]))


for _ in range(int(input())):
	print(2**(bin(int(input())).count('1')))


t = int(input())
for _ in range(t):
    num = int(input())
    ans = 1
    while(num//2):
        ans*= (num%2 + 1)
        num = num//2
    print(ans*(num+1))


import sys

#sys.stdin = open("D:\\Sublime\\in.txt", 'r')
#sys.stdout = open("D:\\Sublime\\out.txt", 'w')

T = int(sys.stdin.readline().strip('\n'))
for t in range(T):
    a = 1<<bin(int(input())).count('1')
    print(a)


def solve(x):
    answer = 1
    while x > 0:
        if x & 1 == 1:
            answer *= 2
        x >>= 1
    return answer

if __name__ == '__main__':
    test_count = int(input())
    for x in range(test_count):
        print(solve(int(input())))
        # print(x, "-->", "{0:b}".format(x), "-->", solve(x))


t = int(input())
for i in range(t):
    c = 0
    a = bin(int(input()))
    for j in range(len(a)):
        if a[j] == '1':
            c += 1
    print(pow(2,c))


from sys import stdin

all_in = stdin.readlines()

t = int(all_in[0])
a = list(map(int, all_in[1:]))

print('\n'.join(map(lambda el: str(2 ** bin(el).count('1')), a)))


t=int(input())
a=[None]*t
for x in range(t):
	a[x]=int(input())
def power(a):
	te=bin(a)
	t=0
	for x in te:
		if x=='1':
			t=t+1
	return t

for x in range(t):
	ress=power(a[x])
	print(2**ress)


t=int(input())
a=[None]*t
for x in range(t):
	a[x]=int(input())
def power(a):
	t=0
	while 2**t<a:
		t=t+1
	return t

for x in range(t):
	ress=power(a[x])
	print(2**ress)


t=int(input())
a=[None]*t
for x in range(t):
	a[x]=int(input())
def power(a):
	t=0
	while 2**t<a:
		t=t+1
	return t
for x in range(t):
	i=power(a[x])
	print(2**i)


t=int(input())
a=[None]*t
for x in range(t):
	a[x]=int(input())
def xor(a,b):
	temp1=list(bin(a))
	temp2=list(bin(b))
	res=[]

	for x in temp1:
		if x=='b':
			temp1.remove(x)
	for x in temp2:
		if x=='b':
			temp2.remove(x)
	if len(temp1)<len(temp2):
		for x in range(len(temp2)-len(temp1)):
			temp1.insert(0,'0')
	else:
		for x in range(len(temp1)-len(temp2)):
			temp2.insert(0,'0')
	for x in range(len(temp1)):
		if int(temp1[x])==int(temp2[x]):
			res.append('0')
		else: res.append('1')
	ress=''.join(res)
	reso=int(ress,2)
	return reso

for x in range(t):
	count=0
	for y in range(a[x]+1):
		if xor(a[x],y)==a[x]-y:
			count=count+1
print(count)


t = int(input())

for i in range(t):
    a = int(input())

    ans = 0
    p = 1

    while a:
        if a % 2 == 1:
            ans += p
            p *= 2
        a //= 2
    print(ans + 1)


t = int(input())
a_list = []
solutions = []
for i in range(t):
    a_list.append(int(input()))

for x in a_list:
    exponent = 0
    while x > 0:
        x //= 2
        if (x > 0):
            exponent += 1

    solutions.append(2**exponent)

for solution in solutions:
    print(solution)


t = int(input())
a_list = [int(input()) for x in range(t)]
for x in a_list:
    exponent = 0
    while x > 0:
        if x % 2 == 1:
            exponent += 1
        x //= 2

    print(2**exponent)


t = int(input())
for i in range(t):
    x = int(input())
    print(2**bin(x).count('1'))


for _ in range(int(input())):
    a = int(input())
    ans = 1

    while a > 0:
        if a & 1 == 1: ans *= 2
        a >>= 1
    print(ans)


def count_setbits(n):
    count=0
    while n>0:
        n=n&(n-1)
        count+=1
    return count
T=int(input())
while T>0:
    a=int(input())
    print(2**count_setbits(a))
    T-=1


def count_setbits(a):
    count=0
    while a>0:
        a=a&(a-1)
        count+=1
    return count

def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()
# ///===========MAIN=============///
T=int(input())
while T>0:
    a=int(input())
    print(2**count_setbits(a))
    T-=1


n = int(input())
for i in range(n):
    k = int(input())
    ans = 0
    while k > 0:
        ans += k & 1
        k = k >> 1
    print(1 << ans)


t=int(input())
for i in range(t):
    print(2**(bin(int(input())).count('1')))


array = []
for i in range(int(input())):
    number = int(input())
    cout = 0
    while number > 0:
        if number % 2 == 1:
            cout += 1
        number //= 2

    array += [2 ** cout]
print(*array, sep="")


for i in range(int(input())):
    number = int(input())
    cout = 0
    while number > 0:
        if number % 2 == 1:
            cout += 1
        number //= 2

    print(2 ** cout, end="")


for i in range(int(input())):
    number = int(input())
    cout = 0
    while number > 0:
        if number % 2 == 1:
            cout += 1
        number //= 2

    print(2 ** cout)


m=int(input())
for i in range(m):
    print(2**(bin(int(input())).count('1')))


def binary (x) :
    t=x
    l=[]
    while (t!=0 ) :
        l.append(str(t%2))
        t=t//2
    l.reverse()
    l="".join(l)
    return(l)
n=int(input())
for i in range (n) :
    a=int(input())
    k=str(binary(a))
    ans=k.count("1")
    print(pow(2,ans))


import math
t = input()
t = int(t)

def dec_to_bin(x):
    return int(bin(x)[2:])

for i in range(t):

    a = int(input())

    stroka = str(dec_to_bin(a))
    num = stroka.count('1')

    print(2**(num))


t = input()
t = int(t)

for i in range(t):

    a = int(input())

    if(a%2==1):
        print(a+1)
    else:
        if(a==0):
            print(1)
        else:
            print(2)


import math
t = input()
t = int(t)

for i in range(t):

    a = int(input())

    sq = a*a

    if(int(math.sqrt(sq+1)) == math.sqrt(sq+1) and sq>0):
        print(a+1)
    else:
        if(a==0):
            print(1)
        else:
            if(a%2==0):
                print(2)
            else:
                print(4)


for _ in range(int(input())):
    print(2**bin(int(input())).count('1'))


t = int(input())
while t:
    t -= 1
    n = int(input())
    n = bin(n)[2:]
    n = n[::-1]
    ans = 1
    length = len(n)
    for x in range(length):
        if(n[x] == '1'):
            ans *= 2
    print(ans)


def binary(n) :
	return bin(n)[2:]

if __name__ == '__main__':

	t = int (input())

	while t > 0 :

		t-=1
		n = int(input())
		s = bin(n)
		c = s.count('1')
		print(pow(2,c)//1)


def binary(n) :
	return bin(n)[2:]

if __name__ == '__main__':

	t = int (input())

	while t > 0 :
		t-=1
		n = int(input())
		s = bin(n)
		c = s.count('1')
		print(pow(2,c)//1)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 14:54:15 2018

@author: abhinavvajpeyi
"""

t=int(input())
while t:
    count=0
    a=int(input())
    while a>0:
        if a&1:
           count+=1
        a=a>>1
    print(2**count)
    t-=1


for _ in range(int(input())):
    n=int(input())
    m=bin(n).split('b')[1]
    p=m.count('1')
    print(pow(2,p))


t = int(input())
for _ in range(t):
    a = int(input())
    ans = 1
    while a:
        if a%2 == 1:
            ans*=2
        a//=2
    print(ans)


t=int(input())
while(t>0):
    t-=1
    n=int(input())
    if(n==0):
        print('1')
    elif(n%2==0):
        print(n)
    else:
        print(n+1)


t=int(input())
s=2**30
while(t>0):
    t-=1
    n=int(input())
    s=bin(n)
    l=s.count('1')
    print(2**l)


t=int(input())
while(t>0):
    t-=1
    n=int(input())
    if(n==0):
        print('1')
    else if(n%2==0):
        print(n)
    else:
        print(n+1)


t = int(input())
for i in range(t):
    a = int(input())
    res = 1
    if a==0:
        print(res)
    elif a%2==0:
        print(a)
    else:
        print(str(a+1))


import math
t = int(input())
for i in range(t):
    a = int(input())
    res = 1
    if a==0:
        print(res)
    elif a%2==0 and math.floor(math.log2(a))==math.ceil(math.log2(a)):
        print(2)
    elif a%2==0:
        s = "{0:b}".format(a)
        res = 0
        for i in s:
            if i=="1":
                res+=1
        print(res+1)
    else:
        print(str(a+1))


import math
t = int(input())
for i in range(t):
    a = int(input())
    print(2**bin(a).count("1"))


import math
t = int(input())
for i in range(t):
    a = int(input())
    res = 1
    if a==0:
        print(res)
    elif a%2==0 and math.floor(math.log2(a))==math.ceil(math.log2(a)):
        print(2)
    elif a%2==0:
        print(3)
    else:
        print(str(a+1))


t = int(input())
for i in range(t):
    a = int(input())
    res = 1
    if a==0:
        print(res)
    elif a%2==0:
        print(2)
    else:
        print(str(a+1))


import math
t = int(input())
for i in range(t):
    a = int(input())
    res = 1
    if a==0:
        print(res)
    elif a%2==0 and math.floor(math.log2(a))==math.ceil(math.log2(a)):
        print(2)
    elif a%2==0:
        s = "{0:b}".format(a)
        res = 0
        for i in s:
            if i=="1":
                res+=1
        print((2**res)-1)
    else:
        print(str(a+1))


import math
t = int(input())
for i in range(t):
    a = int(input())
    res = 1
    if a==0:
        print(res)
    elif a%2==0 and math.floor(math.log2(a))==math.ceil(math.log2(a)):
        print(2)
    elif a%2==0:
        s = "{0:b}".format(a)
        res = 0
        for i in s:
            if i=="1":
                res+=1
        print((2**res))
    else:
        print(str(a+1))


from functools import reduce
for i in range(int(input())):
    #a-x = a xor x
    a = bin(int(input()))
    r = 1
    for i in a[2:]:
        r *= 2 if i=='1' else 1
    print(r)


t = int(input())
for _ in range(t):
    a = int(input())
    sol = 0
    for j in range(0,a,2):
        if (a- a ^ j - j == 0):
            sol = sol + 1
    print(sol)


t = int(input())
sol = []
for _ in range(t):
    a = int(input())
    x = bin(a).count("1")
    sol.append(2**x)
for _ in sol:
    print(_)


import math
n = int(input())

def func(x):
  s = math.bin(x)
  return

for i in range(n):
  x = int(input())
  bn = bin(x)
  t = bn.count('1')
  print(2**t)


import math
t = int(input())
def func(x):
  if x==0:
    return 1
  else:
    e = math.log(x, 2)
    if int(e)==e:
      return x
    else:
      return 2**(int(e)+1)

for i in range(t):
  print(func(int(input())))


# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 10/17/18

"""

import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys

# print(bin(1073741823))

N = int(input())

for i in range(N):
    V = int(input())
    V = bin(V)[2:]

    res = 2 ** (sum([int(x) for x in V]))

    print(res)


# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 10/17/18

"""

import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys

# print(bin(1073741823))

N = int(input())

N = bin(N)[2:]

res = 1
for i in range(len(N)):
    if N[i] == '1':
        res *= 2

print(res)


for _ in range(int(input())):
    print(2 ** (bin(int(input())).count('1')))


def conjecture(i):
    if i == 0: return 1
    b = "{:b}".format(i)
    num_ones = b.count('1')
    return 2**num_ones

import sys

if sys.version_info < (3,0):
    input = raw_input

N = int(input())
for _ in range(N):
    x = int(input())
    print(conjecture(x))


t=int(input(''))
for i in range(t):
    x=int(input(''))
    t=str(bin(x))[2:]
    print(2**(t.count('1')))


n = int(input())
for i in range(n):
    a = int(input())
    ba = bin(a)
    ans = 0
    for elem in ba:
        if elem == '1':
            ans += 1
    print(2 ** ans)


a = int(input())
ba = bin(a)
ans = 0
for elem in ba:
    if elem == '1':
        ans += 1
print(2 ** ans)


def rec(a):
    if a < 2:
        return a + 1
    h = 1
    cnt = 0
    while h <= a:
        h *= 2
        cnt += 1
    return rec(a % 2 ** (cnt - 1)) * 2

n = int(input())
for i in range(n):
    a = int(input())
    print(rec(a))


import sys
from collections import defaultdict
from collections import  deque
import heapq
vis=defaultdict(int)
n,m=map(int,sys.stdin.readline().split())
arr=list(map(int,sys.stdin.readline().split()))
q=deque()
heap=[]
for i in range(len(arr)):
    heapq.heappush(heap,[0,arr[i]])
    #q.append([arr[i],0])
    vis[arr[i]]=1
ans=[]
dis=0
while m>0:
    d,a=heapq.heappop(heap)
    if vis[a+1]==0:
        m-=1
        vis[a+1]=1
        dis+=(d+1)
        ans.append(a+1)
        #q.append([a+1,d+1])
        heapq.heappush(heap,[d+1,a+1])
    if vis[a-1]==0:
        m-=1
        vis[a-1]=1
        dis+=(d+1)
        ans.append(a-1)
        #q.append([a-1,d+1])
        heapq.heappush(heap,[d+1,a-1])
print(dis)
print(*ans)


import sys

n, m = map(int, input().split())
A = list(map(int, input().split()))
A.sort()

distance = 1
cnt = 0
res = []
total_distance = 0
while True:
    for el in A:
        if el + distance not in A:
            if el + distance not in res:
                cnt += 1
                total_distance += distance
                res.append(el + distance)
                if cnt == m:
                    print(total_distance)
                    print(*res)
                    sys.exit()
        if el - distance not in A:
            if el - distance not in res:
                cnt += 1
                total_distance += distance
                res.append(el - distance)
                if cnt == m:
                    print(total_distance)
                    print(*res)
                    sys.exit()
    distance += 1


import heapq

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

y = []
total_distance = 0

occupied = set(x)

Q = [(1, tree + d) for tree in x for d in (1, -1)]

while len(y) < m:
    distance, position = heapq.heappop(Q)
    if position not in occupied:
        y.append(position)
        total_distance += distance
        occupied.add(position)
        heapq.heappush(Q, (distance + 1, position + 1))
        heapq.heappush(Q, (distance + 1, position - 1))

print(total_distance)
print(*y)


from collections import defaultdict
n,m = list(map(int, input().split()))
As = sorted(list(map(int, input().split())))
d = defaultdict(int)
d2 = defaultdict(int)
d3 = defaultdict(int)
for a, b in zip(As, As[1:]):
    if (b + a) % 2:
        d[(b - a)//2] += 2
        d2[a] = (b-a)//2
        d3[b] = (b-a)//2
    else:
        d[(b - a)//2] += 1
        d[(b - a)//2 - 1] += 1
        d2[a] = (b-a)//2
        d3[b] = (b-a)//2-1
d[10**10] += 2
d2[As[-1]] = 10**10
d3[As[0]] = 10**10
ys = sorted(d.keys())
ly = len(As)*2
c = 0
r = 0
for i in range(m+1):
    ly -= d[i]
    if m <= c + ly:
        r += (i+1)*(m-c)
        v = m-c
        break
    c += ly
    r += (i+1)*ly
rs = set()
for a in As:
    if d2[a] > i and v > 0:
        kk = i+1
        v-=1
    else:
        kk = min(d2[a], i)
    for j in range(1, kk+1):
        rs.add(a+j)
    if d3[a] > i and v > 0:
        kk = i+1
        v-=1
    else:
        kk = min(d3[a], i)
        #print(d3)
        #print(a, d3[a], i)
    for j in range(1, kk+1):
        #print(a, a-j)
        rs.add(a-j)
print(r)
print(*list(rs))


from collections import defaultdict
n,m = list(map(int, input().split()))
As = sorted(list(map(int, input().split())))
d = defaultdict(int)
d2 = defaultdict(int)
d3 = defaultdict(int)
for a, b in zip(As, As[1:]):
    if (b + a) % 2:
        d[(b - a)//2] += 2
        d2[a] = (b-a)//2
        d3[b] = (b-a)//2
    else:
        d[(b - a)//2] += 1
        d[(b - a)//2 - 1] += 1
        d2[a] = (b-a)//2
        d3[b] = (b-a)//2-1
d[10**10] += 2
d2[b] = 10**10
d3[As[0]] = 10**10
ys = sorted(d.keys())
ly = len(As)*2
c = 0
r = 0
for i in range(m+1):
    ly -= d[i]
    if m <= c + ly:
        r += (i+1)*(m-c)
        v = m-c
        break
    c += ly
    r += (i+1)*ly
rs = set()
for a in As:
    if d2[a] > i and v > 0:
        kk = i+1
        v-=1
    else:
        kk = min(d2[a], i)
    for j in range(1, kk+1):
        rs.add(a+j)
    if d3[a] > i and v > 0:
        kk = i+1
        v-=1
    else:
        kk = min(d3[a], i)
        #print(d3)
        #print(a, d3[a], i)
    for j in range(1, kk+1):
        #print(a, a-j)
        rs.add(a-j)
print(r)
print(*list(rs))


n,m=map(int,input().split())
a=list(map(int,input().split()))
d={}
a.sort()

low=1
high=m

for i in a:
    d[i]=2

from collections import deque

def check(mid,a):
    s=0
    for i in range(n-1):
        s+=min(2*mid,a[i+1]-a[i]-1)
    if s+ 2*mid>=m:
        return True
    else:
        return False

while low<high:
    mid=(low+high)//2
    if check(mid,a):
        high=mid
    else:
        low=mid+1

st=deque(a)
# print(st)
k=0
ans=[]
pr=0
while m>0:
    if st[0]==a[0]:
        k+=1

    if st[0]-k  in d and st[0]+k in d:
        st.popleft()
        continue
    # print(ans)
    if st[0]-k  not in d:
        d[st[0]-k]=1
        m-=1
        pr+=k
        ans.append(st[0]-k)
    # print(ans)
    if st[0]+k  not in d and m>0:
        d[st[0]+k]=1
        m-=1
        pr+=k
        ans.append(st[0]+k)
    # print(ans)
    st.append(st.popleft())

print(pr)
print(*ans)


n,m=map(int,input().split())
a=list(map(int,input().split()))
d={}
a.sort()

low=1
high=m

for i in a:
    d[i]=2

from collections import deque

def check(mid,a):
    s=0
    for i in range(n-1):
        s+=min(2*mid,a[i+1]-a[i]-1)
    if s+ 2*mid>=m:
        return True
    else:
        return False

while low<high:
    mid=(low+high)//2
    if check(mid,a):
        high=mid
    else:
        low=mid+1

st=deque(a)
# print(st)
k=0
ans=[]
pr=0
while m>0:
    if st[0]==a[0]:
        k+=1

    if st[0]-k  in d and st[0]+k in d:
        st.popleft()
        continue
    # print(ans)
    if st[0]-k  not in d:
        d[st[0]-k]=1
        m-=1
        pr+=k
        ans.append(st[0]-k)
    # print(ans)
    if st[0]+k  not in d:
        d[st[0]+k]=1
        m-=1
        pr+=k
        ans.append(st[0]+k)
    # print(ans)
    st.append(st.popleft())

print(pr)
print(*ans)


import sys
input = sys.stdin.readline

import heapq as hp

N, M = map(int, input().split())
A = list(map(int, input().split()))
checked = set(A)
q = []
for a in A:
    xs = [a+1, a-1]
    for x in xs:
        if not x in checked:
            hp.heappush(q, (1, x))
            checked.add(x)

S = 0
ans = []
for _ in range(M):
    s, ind = hp.heappop(q)
    S += s
    ans.append(ind)
    xs = [ind+1, ind-1]
    for x in xs:
        if not x in checked:
            hp.heappush(q, (s+1, x))
            checked.add(x)

print(S)
print(*ans)


import sys

N, M = [int(i) for i in sys.stdin.readline().strip().split(" ")]
T = [int(i) for i in sys.stdin.readline().strip().split(" ")]

V = set(T)
Q = []
for t in T:
  Q.append((t-1, 1))
  Q.append((t+1, 1))
Y = set()
md = 0
while Q:
  p, d = Q.pop(0)
  if p in V:
    continue
  V.add(p)
  Y.add(p)
  md += d
  if len(Y) == M:
    break

  Q.append((p+1, d + 1))
  Q.append((p-1, d + 1))

print(md)
print(" ".join([str(i) for i in Y]))


import sys, collections

N, M = [int(i) for i in sys.stdin.readline().strip().split(" ")]
T = [int(i) for i in sys.stdin.readline().strip().split(" ")]

#N, M = 200000, 200000
#T = list(range(1, N+1))

V = set(T)
Q = collections.deque()
for t in T:
  Q.append((t-1, 1))
  Q.append((t+1, 1))
Y = set()
md = 0
while Q:
  p, d = Q.popleft()
  if p in V:
    continue
  V.add(p)
  Y.add(p)
  md += d
  if len(Y) == M:
    break

  Q.append((p+1, d + 1))
  Q.append((p-1, d + 1))

print(md)
print(" ".join([str(i) for i in Y]))


import sys
input = sys.stdin.readline

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

SET=set(X)
dis=1

ANS=[]
MSET=set(X)
PSET=set(X)
score=0
MEM=0

while MEM<m:

    REMLIST=[]
    for t in MSET:
        if t-dis in SET:
            REMLIST.append(t)
        else:
            ANS.append(t-dis)
            SET.add(t-dis)
            MEM+=1
            score+=dis

        if MEM==m:
            break

    MSET-=set(REMLIST)

    if MEM==m:
        break

    REMLIST=[]
    for t in PSET:
        if t+dis in SET:
            REMLIST.append(t)
        else:
            ANS.append(t+dis)
            SET.add(t+dis)
            MEM+=1
            score+=dis

        if MEM==m:
            break

    PSET-=set(REMLIST)
    dis+=1

print(score)
print(*ANS)


from collections import deque

n, m = map(int,input().split())
queue = deque([])
vst = set()
for k in map(int,input().split()):
    vst.add(k)
    queue.append((k,0))

ans = 0
ans_L = []
cnt = 0

while queue:
    x, step = queue.popleft()
    for dx in [1, -1]:
        X = x + dx
        if X not in vst:
            cnt += 1
            vst.add(X)
            ans += step + 1
            ans_L.append(X)
            queue.append((X, step + 1))
        if cnt == m:
            break
    if cnt == m:
        break

print(ans)
print(*ans_L)


n,m=map(int,input().strip().split())
arr=list(map(int,input().strip().split()))

d={}
q=[]
for i in arr:
	d[i]=0
	q.append(i)

ans=[]
v=0
index=0
while(len(ans)!=m):
	x=q[index]
	if x-1 not in d :
		d[x-1]=d[x]+1
		ans.append(x-1)
		q.append(x-1)
		v=v+d[x-1]
	if len(ans)==m :
		break
	if x+1 not in d :
		d[x+1]=d[x]+1
		ans.append(x+1)
		q.append(x+1)
		v=v+d[x+1]
	index=index+1

print(v)
print(*ans)


import sys
sys.stdin = open('input.txt', 'r')

n,m=map(int,input().strip().split())
arr=list(map(int,input().strip().split()))

d={}
q=[]
for i in arr:
	d[i]=0
	q.append(i)

ans=[]
v=0
index=0
while(len(ans)!=m):
	x=q[index]
	if x-1 not in d :
		d[x-1]=d[x]+1
		ans.append(x-1)
		q.append(x-1)
		v=v+d[x-1]
	if len(ans)==m :
		break
	if x+1 not in d :
		d[x+1]=d[x]+1
		ans.append(x+1)
		q.append(x+1)
		v=v+d[x+1]
	index=index+1

print(v)
print(*ans)


from collections import deque

n, k = map(int, input().split())
a = list(map(int, input().split()))
visited = set(a)

q = deque()
for i in a:
    q.append((1, i - 1))
    q.append((1, i + 1))

count = 0
result = 0
results = []

while count < k:
    distance, now = q.popleft()
    if now in visited:
        continue
    result += distance
    results.append(now)
    visited.add(now)
    q.append((distance + 1, now - 1))
    q.append((distance + 1, now + 1))
    count += 1

print(result)
for i in results:
    print(i, end=' ')


from collections import deque

n, k = map(int, input().split())
a = list(map(int, input().split()))
visited = set(a)

q = deque()
for i in a:
    q.append((1, i - 1))
    q.append((1, i + 1))

count = 0

while count < k:
    distance, now = q.popleft()
    if now in visited:
        continue
    visited.add(now)
    print(now, end=' ')
    q.append((distance + 1, now - 1))
    q.append((distance + 1, now + 1))
    count += 1


from collections import deque

n, k = map(int, input().split())
a = list(map(int, input().split()))
visited = set(a)

q = deque()
for i in a:
    q.append((1, i - 1))
    q.append((1, i + 1))

count = 0
result = 0

while count < k:
    distance, now = q.popleft()
    if now in visited:
        continue
    visited.add(now)
    result += distance
    q.append((distance + 1, now - 1))
    q.append((distance + 1, now + 1))
    count += 1

print(result)


import heapq

heap = []
n, m = map(int, input().split(' '))
trees = list(map(int, input().split(' ')))
trees.sort()

data = []
for i in range(n):
  start = trees[i] - 1
  end = trees[i] + 1
  if i > 0 and trees[i - 1] + 1 == trees[i]:
    start = trees[i]
  if i < n - 1 and trees[i] + 1 == trees[i + 1]:
    end = trees[i]
  data.append([trees[i], start, end])

def find(position, start, end):
  if start == position and end == position:
    return (9999999999999999, 9999999999999999)
  elif start == position:
    return (end - position, end)
  elif end == position:
    return (position - start, start)
  target = start
  distance = position - start
  if end - position < distance:
    target = end
    distance = end - position
  return (distance, target)

for i in range(n):
  position = data[i][0]
  start = data[i][1]
  end = data[i][2]
  distance = find(position, start, end)[0]
  heapq.heappush(heap, (distance, i))

result_sum = 0
result_array = []

for i in range(m):
  distance, index = heapq.heappop(heap)
  position = data[index][0]
  start = data[index][1]
  end = data[index][2]
  while distance != find(position, start, end)[0]:
    new_distance = find(position, start, end)[0]
    heapq.heappush(heap, (new_distance, index))
    distance, index = heapq.heappop(heap)
    position = data[index][0]
    start = data[index][1]
    end = data[index][2]
  distance, target = find(position, start, end)
  result_sum += distance
  result_array.append(target)
  if target < position:
    if index > 0 and data[index - 1][2] == data[index][1]:
      data[index - 1][2] = data[index - 1][0]
      data[index][1] = data[index][0]
    else:
      data[index][1] -= 1
  elif target > position:
    if index < n - 1 and data[index + 1][1] == data[index][2]:
      data[index + 1][1] = data[index + 1][0]
      data[index][2] = data[index][0]
    else:
      data[index][2] += 1
  position = data[index][0]
  start = data[index][1]
  end = data[index][2]
  new_distance = find(position, start, end)[0]
  heapq.heappush(heap, (new_distance, index))

print(result_sum)
for i in result_array:
  print(i, end=' ')


from collections import deque

n, k = map(int, input().split())
a = list(map(int, input().split()))
visited = set(a)

# 모든 샘터의 왼쪽, 오른쪽에 대하여 확인
q = deque()
for i in a:
    # (거리, 위치)를 큐에 삽입
    q.append((1, i - 1))
    q.append((1, i + 1))

count = 0
result = 0

# BFS 수행 (K명의 집이 배치될 때까지)
while count < k:
    distance, now = q.popleft()
    # 해당 위치에 샘터 혹은 집이 존재한다면 무시
    if now in visited:
        continue
    visited.add(now)
    # 해당 위치에 집을 배치
    result += distance
    # 그 위치의 왼쪽, 오른쪽에 대하여 다시 확인
    q.append((distance + 1, now - 1))
    q.append((distance + 1, now + 1))
    count += 1

print(result)


n,m=map(int,input().split())
x=list(map(int,input().split()))
x=sorted(x)
op=set(x)
person=[]
d=1
ans=0
while m>0:
    for i in x:
        if (i-d) not in op and m>0:
            op.add(i-d)
            person.append(i-d)
            m-=1
            ans+=d
        if (i+d) not in op and m>0:
            op.add(i+d)
            person.append(i+d)
            m-=1
            ans+=d
    d+=1
print(ans)
person=sorted(person)
print(*person)


import sys
def ip():

    n,m=map(int,sys.stdin.readline().split())
    x=list(map(int,sys.stdin.readline().split()))
    #x=sorted(x)
    op=set(x)
    person=[]
    d=1
    ans=0
    while m>0:
        for i in x:
            if (i-d) not in op and m>0:
                op.add(i-d)
                person.append(i-d)
                m-=1
                ans+=d
            if (i+d) not in op and m>0:
                op.add(i+d)
                person.append(i+d)
                m-=1
                ans+=d
        d+=1
    print(ans)
    #person=sorted(person)
    print(*person)
ip()


import sys
def ip():

    n,m=map(int,sys.stdin.readline().split())
    x=list(map(int,sys.stdin.readline().split()))
    #x=sorted(x)
    op=set(x)
    person=[]
    d=1
    ans=0
    while m>0:
        for i in x:
            if (i-d) not in op and m>0:
                op.add(i-d)
                person.append(i-d)
                m-=1
                ans+=d
            if (i+d) not in op and m>0:
                op.add(i+d)
                person.append(i+d)
                m-=1
                ans+=d
        d+=1
    print(ans)
    person=sorted(person)
    print(*person)
ip()


import sys
def ip():

    n,m=map(int,sys.stdin.readline().split())
    x=list(map(int,sys.stdin.readline().split()))
    #x=sorted(x)
    op=set(x)
    person=[]
    d=1
    ans=0
    while m>0:
        for i in x:
            if (i-d) not in op and m>0:
                op.add(i-d)
                person.append(i-d)
                m-=1
                ans+=d
            if (i+d) not in op and m>0:
                op.add(i+d)
                person.append(i+d)
                m-=1
                ans+=d
            if m==0:
                break
        d+=1
    print(ans)
    #person=sorted(person)
    print(*person)
ip()


import sys
def ip():
    ans=0
    n,m=map(int,input().split())
    x=list(map(int,input().split()))
    q=[]
    d={}
    person=[]
    for i in x:
        d[i]=0
        q.append(i)
    ptr=0
    while q:
        if len(person)==m:
            break
        rmv=q[ptr]
        ptr+=1
        if d[rmv]!=0:
            person.append(rmv)
            ans+=d[rmv]

        if d.get(rmv-1)==None:
            d[rmv-1]=d[rmv]+1
            q.append(rmv-1)
        if d.get(rmv+1)==None:
            d[rmv+1]=d[rmv]+1
            q.append(rmv+1)

    print(ans)
    person=sorted(person)
    print(*person)
ip()


import sys
def ip():
    ans=0
    n,m=map(int,input().split())
    x=list(map(int,input().split()))
    q=[]
    d={}
    person=[]
    for i in x:
        d[i]=0
        q.append(i)
    while q:
        if len(person)==m:
            break
        rmv=q.pop(0)
        if d[rmv]!=0:
            person.append(rmv)
            ans+=d[rmv]

        if d.get(rmv-1)==None:
            d[rmv-1]=d[rmv]+1
            q.append(rmv-1)
        if d.get(rmv+1)==None:
            d[rmv+1]=d[rmv]+1
            q.append(rmv+1)

    print(ans)
    person=sorted(person)
    print(*person)
ip()


n, m = map(int, input().split())
x = list(map(int, input().split()))
visited = set(x)
y = []
frontier = x
i = 1
ans = 0
numFolks = 0
while numFolks < m:
    next = []
    for u in frontier:
        for v in (u-1, u+1):
            if v not in visited:
                ans += i
                numFolks += 1
                y.append(v)
                next.append(v)
                visited.add(v)
                if numFolks == m:
                    break
    i += 1
    frontier = next
print(ans)
for p in y:
    print(p, end=' ')


n, m = map(int, input().split())
x = list(map(int, input().split()))
visited = set(x)
y = []
frontier = x
i = 0
ans = 0
numFolks = 0
while numFolks < m:
    next = []
    for u in frontier:
        if i > 0:
            ans += i
            numFolks += 1
            y.append(u)
            if numFolks == m:
                break
        if u-1 not in visited:
            next.append(u-1)
            visited.add(u-1)
        if u+1 not in visited:
            next.append(u+1)
            visited.add(u+1)
    i += 1
    frontier = next
print(ans)
for p in y:
    print(p, end=' ')


n, m = map(int, input().split())
x = list(map(int, input().split()))
visited = set(x)
y = []
frontier = x
i = 1
ans = 0
numFolks = 0
while numFolks < m:
    next = []
    for u in frontier:
        for v in (u-1, u+1):
            if v not in visited:
                if numFolks == m:
                    break
                ans += i
                numFolks += 1
                y.append(v)
                next.append(v)
                visited.add(v)
    i += 1
    frontier = next
print(ans)
for p in y:
    print(p, end=' ')


n, m = map(int, input().split())
x = list(map(int, input().split()))
visited = set(x)
y = []
frontier = x
i = 0
ans = 0
numFolks = 0
while numFolks < m:
    next = []
    for u in frontier:
        if i > 0:
            ans += i
            numFolks += 1
            y.append(u)
            if numFolks == m:
                break
        for v in (u-1, u+1):
            if v not in visited:
                next.append(v)
                visited.add(v)
    i += 1
    frontier = next
print(ans)
for p in y:
    print(p, end=' ')


n, m = map(int, input().split())
x = list(map(int, input().split()))
visited = set(x)
y = []
frontier = x
i = 0
ans = 0
numFolks = 0
while numFolks < m:
    next = []
    for u in frontier:
        if i > 0:
            ans += i
            numFolks += 1
            y.append(u)
            if numFolks == m:
                break
        for v in (u-1, u+1):
            next.append(v)
            visited.add(v)
    i += 1
    frontier = next
print(ans)
for p in y:
    print(p, end=' ')


n, m = map(int, input().split())
x = list(map(int, input().split()))
from collections import deque
dist = {}
y = []
queue = deque()
for t in x:
    dist[t] = 0
    queue.append(t)
ans = 0
while queue:
    cur = queue.popleft()
    if len(y) == m:
        break
    if dist[cur] > 0:
        ans += dist[cur]
        y.append(cur)
    for v in (cur-1, cur+1):
        if v not in dist:
            dist[v] = dist[cur] + 1
            queue.append(v)
print(ans)
for p in y:
    print(p, end=' ')


n, m = map(int, input().split())
x = list(map(int, input().split()))
visited = set(x)
y = []
frontier = x
i = 1
ans = 0
numFolks = 0
while numFolks < m:
    next = []
    for u in frontier:
        if u-1 not in visited:
            ans += i
            numFolks += 1
            y.append(u-1)
            next.append(u-1)
            visited.add(u-1)
            if numFolks == m:
                break
        if u+1 not in visited:
            ans += i
            numFolks += 1
            y.append(u+1)
            next.append(u+1)
            visited.add(u+1)
            if numFolks == m:
                break
    i += 1
    frontier = next
print(ans)
for p in y:
    print(p, end=' ')


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,m=kk()
ls=ll()
q = [(l-1,1,-1) for l in ls]+[(l+1,1,1) for l in ls]
s=0
i=-1
vis=set(ls)
res = []
while len(res)<m:
	i+=1

	if q[i][0] in vis:continue
	vis.add(q[i][0])
	res.append(q[i][0])
	s+=q[i][1]
	q.append((q[i][0]+q[i][2],q[i][1]+1,q[i][2]))
print(s)
print(*res)


n, m = map(int, input().split())
v = list(map(int, input().split()))
ans = []
v1 = []
mp = {}
for i in range(0,n):
    v1.append(v[i])
    mp[v[i]]=1
pz = 0
sol = 0
last = n
while True:
    val = v1[pz]
    pz +=1
    if mp.get(val-1)==None:
        ans.append(val-1)
        sol +=mp[val]
        mp[val-1]=mp[val]+1
        v1.append(val-1)
    if len(ans)==m:
        break
    if mp.get(val+1)==None:
        ans.append(val+1)
        sol +=mp[val]
        mp[val+1]=mp[val]+1
        v1.append(val+1)
    if len(ans)==m:
        break
print(str(sol))
print(*ans)


n, m = map(int, input().split())
v = list(map(int, input().split()))
ans = []
v1 = [0 for x in range(4*m+10)]
mp = {}
for i in range(0,n):
    v1[i] = v[i]
    mp[v[i]]=1
pz = 0
sol = 0
last = n
while True:
    val = v1[pz]
    pz +=1
    if mp.get(val-1)==None:
        ans.append(val-1)
        sol +=mp[val]
        mp[val-1]=mp[val]+1
        v1[last] = val-1
        last +=1
    if len(ans)==m:
        break
    if mp.get(val+1)==None:
        ans.append(val+1)
        sol +=mp[val]
        mp[val+1]=mp[val]+1
        v1[last] = val+1
        last +=1
    if len(ans)==m:
        break
print(str(sol))
print(*ans)


n,m = map(int,input().strip().split())
A = list(map(int,input().strip().split()))
sa = set(A)
p = set()
x = 0
flag=0
d = 0
np = 0
while(flag ==0):
    x+=1
    for i in A:
        if ((i-x) in p)==False and ((i-x) in sa)==False:
            p.add(i-x)
            d+=x
            np+=1
            if np==m:
                flag=1
                break
        if ((i+x) in p)==False and ((i+x) in sa)==False:
            p.add(i+x)
            d+=x
            np+=1
            if np==m:
                flag=1
                break
p = list(p)
print(d)
print(' '.join([str(i) for i in p]))


def main():
    class node:
      def __init__(self,val):
        self.val = val
        self.next = None
    n,m = map(int,input().strip().split())
    A = sorted(list(map(int,input().strip().split())))
    sa = set(A)
    L = [node(A[i]) for i in range(n)]
    for i in range(n-1):
        L[i].next = L[i+1]

    p = set()
    x = 0
    flag=0
    d = 0
    np = 0
    while(flag ==0):
        x+=1
        node = L[0]
        while(node!=None and flag==0):
            i = node.val
            t1 = 0
            t2 = 0
            if ((i-x) in p)==False and ((i-x) in sa)==False:
                p.add(i-x)
                # print('-',x,i,i-x)
                d+=x
                np+=1
                if np==m:
                    flag=1
                    break
                t1 = 1
            if ((i+x) in p)==False and ((i+x) in sa)==False:
                p.add(i+x)
                # print('+',x,i,i+x)
                d+=x
                np+=1
                if np==m:
                    flag=1
                    break
                t2 = 1
            if t1==0 and t2==0:
                node.val,node.next = node.next.val,node.next.next
            else:
                node = node.next

    p = list(p)
    print(d)
    print(' '.join([str(i) for i in p]))
main()


n ,m = list(map(int,input().split()))
pos = list(map(int,input().split()))
d = {}
for i in range(n) :
    d[pos[i]] =0

j =0
ans = 0

final = []
while len(final) < m  :
    p  = pos[j]
    if d[p] :
        ans +=d[p]
        final.append(p)
    if not (p + 1) in d :
        d[p+1] =d[p] +1
        pos.append(p+1)

    if not (p-1) in d :
        d[p-1]  = d[p] +1
        pos.append(p-1)

    j +=1

print(ans)
print(*final)


n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))
que, vis = [], {}
for i in arr:
    que.append((i, 1))
    vis[i] = 1

def bfs():
    tot_sum, res = 0, []
    while que and len(res) < m:
        x, y = que[0]
        que.pop(0)
        if x+1 not in vis and len(res) < m:
            vis[x+1] = 1
            que.append((x+1, y+1))
            tot_sum += y
            res.append(x+1)
        if x-1 not in vis and len(res) < m:
            vis[x-1] = 1
            que.append((x-1, y+1))
            tot_sum += y
            res.append(x-1)
    return tot_sum, res

tot_sum, res = bfs()
print(tot_sum)
print(*res)


from sys import stdin
input = stdin.readline

n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))
que, vis = [], {}
for i in arr:
    que.append((i, 1))
    vis[i] = 1

def bfs():
    tot_sum, res = 0, []
    p1, p2 = 0, len(que)-1
    while p1 <= p2:
        x, y = que[p1]
        p1 += 1
        if x+1 not in vis:
            vis[x+1] = 1
            que.append((x+1, y+1))
            p2 += 1
            tot_sum += y
            res.append(x+1)
        if len(res) == m:
            break
        if x-1 not in vis:
            vis[x-1] = 1
            que.append((x-1, y+1))
            p2 += 1
            tot_sum += y
            res.append(x-1)
        if len(res) == m:
            break
    return tot_sum, res

tot_sum, res = bfs()
print(tot_sum)
print(*res)


n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))
que, vis = [], {}
for i in arr:
    que.append((i, 1))
    vis[i] = 1

def bfs():
    tot_sum, res = 0, []
    p1, p2 = 0, len(que)-1
    while p1 <= p2:
        x, y = que[p1]
        p1 += 1
        if x+1 not in vis:
            vis[x+1] = 1
            que.append((x+1, y+1))
            p2 += 1
            tot_sum += y
            res.append(x+1)
        if len(res) == m:
            break
        if x-1 not in vis:
            vis[x-1] = 1
            que.append((x-1, y+1))
            p2 += 1
            tot_sum += y
            res.append(x-1)
        if len(res) == m:
            break
    return tot_sum, res

tot_sum, res = bfs()
print(tot_sum)
print(*res)


from sys import stdin
input = stdin.readline

n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))
que, vis = [], {}
for i in arr:
    que.append((i, 1))
    vis[i] = 1

def bfs():
    tot_sum, res = 0, []
    while que and len(res) < m:
        x, y = que[0]
        que.pop(0)
        if x+1 not in vis and len(res) < m:
            vis[x+1] = 1
            que.append((x+1, y+1))
            tot_sum += y
            res.append(x+1)
        if x-1 not in vis and len(res) < m:
            vis[x-1] = 1
            que.append((x-1, y+1))
            tot_sum += y
            res.append(x-1)
    return tot_sum, res

tot_sum, res = bfs()
print(tot_sum)
print(*res)


n, m = map(int, input().split())
a = sorted(list(map(int, input().split())))
sp, res = 0, []
for i in range(1, n):
    sp += a[i] - a[i-1]

def binary_search(k):
    l, r = 0, n-1
    dis = int(2e9+5)
    while l <= r:
        mid = l+r >> 1
        if a[mid] < k:
            l=mid+1
        else:
            r=mid-1
        dis = min(dis, abs(k-a[mid]))
    return dis

def solve1():
    global res
    res = set()
    for i in range(1, n):
        res |= set(range(a[i-1]+1, a[i]))
    res |= set(range(a[0]-(m-len(res))//2, a[0]))
    res |= set(range(a[-1]+1, a[-1]+1+(m-len(res))))
    res = sorted(list(res))
    sum_res = sum([binary_search(i) for i in res])
    print(sum_res)
    print(*res)

def solve2():
    global res
    res = set()
    tk = m // 2
    for i in range(n):
        x, y = a[i]-tk, a[i]+tk
        if i > 0: x = max(x, a[i-1]+1)
        if i < n-1: y = min(y, a[i+1]-1)
        res |= set(range(x, y+1)) - set([a[i]])
    res = sorted(list(res))
    dis = sorted([(binary_search(i), i) for i in res])
    sum_res = sum([i[0] for i in dis[:m]])
    print(sum_res)
    print(*[i[1] for i in dis[:m]])

if sp <= m:
    solve1()
else:
    solve2()


from sys import stdin
input = stdin.readline

n, m = map(int, input().split())
arr = sorted(list(map(int, input().split())))
que, vis = [], {}
for i in arr:
    que.append((i, 1))
    vis[i] = 1

def bfs():
    tot_sum, res = 0, []
    p1, p2 = 0, len(que)-1
    while p1 < p2:
        x, y = que[p1]
        p1 += 1
        if x+1 not in vis:
            vis[x+1] = 1
            que.append((x+1, y+1))
            p2 += 1
            tot_sum += y
            res.append(x+1)
        if len(res) == m:
            break
        if x-1 not in vis:
            vis[x-1] = 1
            que.append((x-1, y+1))
            p2 += 1
            tot_sum += y
            res.append(x-1)
        if len(res) == m:
            break
    return tot_sum, res

tot_sum, res = bfs()
print(tot_sum)
print(*res)


import sys

#556940
def binsearch(val, mas):
    left = -1
    right = len(mas) - 1
    while right > left + 1:
        mid = (right + left) // 2
        if mas[mid] < val:
            left = mid
        else:
            right = mid
    try:
        return min(abs(mas[left] - val), abs(mas[right] - val))
    except IndexError:
        return abs(mas[right] - val)

n, m = map(int, input().split())
x = [int(i) for i in sys.stdin.readline().split()]
isx = x.copy()
isx.sort()
sx = set(x)
sum = 0
a = []
while len(a) < m:
    for i in x:
        if i+1 not in sx:
            a.append((binsearch(i + 1, isx), i + 1))
            sum += (a[len(a) - 1][0])
            sx.add(i+1)
            x.append(i+1)
        if i - 1 not in sx:
            a.append((binsearch(i -1, isx), i -1))
            sx.add(i - 1)
            sum += (a[len(a) - 1][0])
            x.append(i - 1)
        if len(a) >= m:
            break
print(sum)
for i in range(m):
    sys.stdout.write(str(a[i][1]) + " ")


import sys

#556940
def binsearch(val, mas):
    left = -1
    right = len(mas) - 1
    while right > left + 1:
        mid = (right + left) // 2
        if mas[mid] < val:
            left = mid
        else:
            right = mid
    try:
        return min(abs(mas[left] - val), abs(mas[right] - val))
    except IndexError:
        return abs(mas[right] - val)

n, m = map(int, input().split())
x = [int(i) for i in sys.stdin.readline().split()]
isx = x.copy()
isx.sort()
sx = set(x)
sum = 0
a = []
while len(a) < m:
    for i in x:
        if i+1 not in sx:
            a.append((binsearch(i + 1, isx), i + 1))
            sum += (a[len(a) - 1][0])
            sx.add(i+1)
            x.append(i+1)
        if len(a) == m:
            break
        if i - 1 not in sx:
            a.append((binsearch(i -1, isx), i -1))
            sx.add(i - 1)
            sum += (a[len(a) - 1][0])
            x.append(i - 1)
        if len(a) == m:
            break

print(sum)
for i in range(m):
    sys.stdout.write(str(a[i][1]) + " ")


from collections import deque

bfs_queue = deque()
n, m = map(int, input().split())
y = {}
ans = 0

def bfs():
    global m, ans
    while len(bfs_queue):
        if m <= 0:
            break
        af = bfs_queue.popleft()
        f = af[0]
        if y.get(f) == 0:
            if y.get(f+1) is None:
                bfs_queue.append((f+1, af[1]+1))
            if y.get(f-1) is None:
                bfs_queue.append((f-1, af[1]+1))
        elif y.get(f) is None:
            m -= 1
            y[f] = -1
            ans += af[1]
            if y.get(f+1) is None:
                bfs_queue.append((f+1, af[1]+1))
            if y.get(f-1) is None:
                bfs_queue.append((f-1, af[1]+1))

for i in map(int, input().split()):
    bfs_queue.append((i, 0))
    y[i] = 0

bfs()

print(ans)
for i in y:
    if y[i] == -1:
        print(i, end=' ')


from collections import deque

bfs_queue = deque()
n, m = map(int, input().split())
y = {}
ans = 0
anses = []

def bfs():
    global m, ans
    while len(bfs_queue):
        if m <= 0:
            break
        f = bfs_queue.popleft()
        if y.get(f) == 0:
            if y.get(f+1) is None:
                bfs_queue.append(f+1)
                y[f+1] = y[f]+1
            if y.get(f-1) is None:
                bfs_queue.append(f-1)
                y[f-1] = y[f]+1
        else:
            m -= 1
            ans += y[f]
            if y.get(f+1) is None:
                bfs_queue.append(f+1)
                y[f+1] = y[f]+1
            if y.get(f-1) is None:
                bfs_queue.append(f-1)
                y[f-1] = y[f]+1
            anses.append(f)

for i in map(int, input().split()):
    bfs_queue.append(i)
    y[i] = 0

bfs()

print(ans)
print(*anses)


import sys
input=sys.stdin.readline
n,m=map(int,input().split())
trees=[int(i)for i in input().split()]
count=1
people={}
for i in range(n):
    people[trees[i]]=0
dist=0
output=[]
while m>0:
    #print(m)
    for i in range(n):
        if (trees[i]+count) not in people:
            people[trees[i]+count]=0
            output.append(trees[i]+count)
            m-=1
            dist+=count
            #print('m',m)
            if m==0:
                break
        if (trees[i]-count) not in people:
            people[trees[i]-count]=0
            output.append(trees[i]-count)
            m-=1
            dist+=count
            if m==0:
                break
            #print('m',m)
        #print(output)
    count+=1
print(dist)
print(*output)


import sys
input=sys.stdin.readline
n,m=map(int,input().split())
trees=[int(i)for i in input().split()]
people={}
for i in range(n):
    people[trees[i]]=0
dist=0
i=0
while m>0:
    last=trees[i]
    if last-1 not in people:
        people[last-1]=people[last]+1
        m-=1
        trees.append(last-1)
        dist+=people[last-1]
        if m==0:
            break
    if last+1 not in people:
        people[last+1]=people[last]+1
        m-=1
        trees.append(last+1)
        dist+=people[last+1]
        if m==0:
            break
    i+=1
print(dist)
print(*trees[n:])


import sys
input=sys.stdin.readline
import collections
from collections import defaultdict
n,m=map(int,input().split())
trees=[int(i)for i in input().split()]
count=1
people=defaultdict(list)
for i in range(n):
    people[trees[i]].append(0)
dist=0
output=[]
while m>0:
    #print(m)
    for i in range(n):
        if (trees[i]+count) not in people:
            people[trees[i]+count].append(0)
            output.append(trees[i]+count)
            m-=1
            dist+=count
            #print('m',m)
            if m==0:
                break
        if (trees[i]-count) not in people:
            people[trees[i]-count].append(0)
            output.append(trees[i]-count)
            m-=1
            dist+=count
            if m==0:
                break
            #print('m',m)
        #print(output)
    count+=1
print(dist)
print(*output)


import heapq

#Inputs
n, m = map(int, input().split()) # n arboles, m personas
x = list(map(int, input().split())) #posicion de los n arboles

#Outputs
total = 0
y = list()

ocupado = set(x) #Los arboles no se pueden mover de posicion

#Generamos una cola de tuplas que chequean a la izquierda y derecha del arbol
#partiendo con distancia 1
Q = [(1, arbol + h) for arbol in x for h in (-1, 1)]

while len(y) < m: #Mientras no esten todas las personas ubicadas
    distancia, posicion = heapq.heappop(Q)
    if posicion not in ocupado:
        y.append(posicion)
        total += distancia
        ocupado.add(posicion)
        #Ubicamos a la persona y revisamos su izquierda y derecha con distancia +1
        heapq.heappush(Q, (distancia + 1, posicion + 1))
        heapq.heappush(Q, (distancia + 1, posicion - 1))

print(total)
print(*y)


from copy import deepcopy
if __name__ == '__main__':
    n, m = map(int,input().split())
    trees=[int(x) for x in input().split()]
    peopleNtree={int(x):True for x in trees}
    people=[]
    distance=1
    pos=0
    LR=-1
    totalDistance=0
    while m>0:
        if pos==n:
            pos=0
            distance+=1
        treeVacancy=trees[pos]+LR*distance
        exist=peopleNtree.get(treeVacancy,False)
        if not exist:
            peopleNtree[treeVacancy]=True
            people.append(treeVacancy)
            totalDistance+=distance
            m-=1
        if LR==-1:
            LR=1
        else:
            LR=-1
            pos+=1
    print(totalDistance)
    print(" ".join(map(str,people)))


from copy import deepcopy
if __name__ == '__main__':
    n, m = map(int,input().split())
    trees=[int(x) for x in input().split()]
    peopleNtree={int(x):True for x in trees}
    people=[]
    #check max fill between max and min ele
    minTree=min(trees)
    maxTree=max(trees)
    maxDis=maxTree-minTree

    maxFill=maxDis//2*4-1+maxDis%2-(len(trees)-2)
    #preVal
    distance=-1
    pos=0
    totalDistance=0
    if maxFill>=m:

        while m>0:

            treeVacancy=trees[pos]+distance
            exist=peopleNtree.get(treeVacancy,False)
            if not exist:
                peopleNtree[treeVacancy]=True
                people.append(treeVacancy)
                totalDistance+=abs(distance)
                m-=1
            if distance>0:
                pos+=1
            distance*=-1
            if pos==n:
                pos=0
                distance=distance-1
    else:
        #step 1 calc inside vals
        while abs(distance)<=maxDis//2:

            treeVacancy=trees[pos]+distance
            exist=peopleNtree.get(treeVacancy,False)
            if not exist:
                peopleNtree[treeVacancy]=True
                people.append(treeVacancy)
                totalDistance+=abs(distance)
                m-=1
            if distance>0:
                pos+=1
            distance*=-1
            if pos==n:
                pos=0
                distance=distance-1

        maxLeft=minTree-maxDis//2-(m//2+m%2)
        maxLeftTo=minTree-maxDis//2

        #print(maxLeft,minTree,m)
        maxRight=maxTree+maxDis//2+(m//2)
        maxRightFrom=maxTree+maxDis//2
        people.extend(list(range(maxLeft,maxLeftTo)))
        people.extend(list(range(maxRightFrom+1,maxRight+1)))

        totalDistance+=((maxDis//2+m//2+maxDis//2)*(m//2)+(maxDis//2+m//2+m%2)*(m%2))
    print(totalDistance)
    print(" ".join(map(str,people)))


from collections import deque

n,m = map(int,input().split()) #tree/people

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

dic = {}
q = deque([])

d = 0
ans = []

for i in range(n):

    dic[x[i]] = 1

for i in range(n):

    if x[i] - 1 not in dic:
        dic[x[i] - 1] = 1
        q.append([ x[i]-1 , 1 ,"l"])
    if x[i] + 1 not in dic:
        dic[x[i] + 1] = 1
        q.append([ x[i]+1 , 1 ,"r"])
#print(q)
for i in range(m):

    now = q.popleft()

    p = now[0]
    d += now[1]
    direc = now[2]

    ans.append(p)

    if direc == "l":
        if p-1 not in dic:
            dic[p-1] = 1
            q.append([ p-1 , now[1] + 1 , direc ])
    else:
        if p+1 not in dic:
            dic[p+1] = 1
            q.append([ p+1 , now[1] + 1 , direc ])
    #print(now,q)

print (d)
print (" ".join(map(str,ans)))


from copy import deepcopy
if __name__ == '__main__':
    n, m = map(int,input().split())
    trees=[int(x) for x in input().split()]
    peopleNtree={int(x):True for x in trees}
    people=[]
    distance=-1
    pos=0
    totalDistance=0
    while m>0:
        if pos==n:
            pos=0
            distance=distance-1
        treeVacancy=trees[pos]+distance
        exist=peopleNtree.get(treeVacancy,False)
        if not exist:
            peopleNtree[treeVacancy]=True
            people.append(treeVacancy)
            totalDistance+=abs(distance)
            m-=1
        if distance>0:
            pos+=1
        distance*=-1
    print(totalDistance)
    print(" ".join(map(str,people)))


from copy import deepcopy
if __name__ == '__main__':
    n, m = map(int,input().split())
    trees=[int(x) for x in input().split()]
    peopleNtree={int(x):True for x in trees}
    people=[]
    #check max fill between max and min ele
    minTree=min(trees)
    maxTree=max(trees)
    maxDis=maxTree-minTree

    maxFill=maxDis//2*4-1+maxDis%2-(len(trees)-2)
    #preVal
    distance=-1
    pos=0
    totalDistance=0
    if maxFill>=m:

        while m>0:

            treeVacancy=trees[pos]+distance
            exist=peopleNtree.get(treeVacancy,False)
            if not exist:
                peopleNtree[treeVacancy]=True
                people.append(treeVacancy)
                totalDistance+=abs(distance)
                m-=1
            if distance>0:
                pos+=1
            distance*=-1
            if pos==n:
                pos=0
                distance=distance-1
    else:
        #step 1 calc inside vals

        while abs(distance)<=maxDis//2:

            treeVacancy=trees[pos]+distance
            exist=peopleNtree.get(treeVacancy,False)
            if not exist:
                peopleNtree[treeVacancy]=True
                people.append(treeVacancy)
                totalDistance+=abs(distance)
                m-=1
            if distance>0:
                pos+=1
            distance*=-1
            if pos==n:
                pos=0
                distance=distance-1

        maxLeft=minTree-maxDis//2-(m//2+m%2)
        maxLeftTo=minTree-maxDis//2

        #print(maxLeft,minTree,m,totalDistance,people)
        maxRight=maxTree+maxDis//2+(m//2)
        maxRightFrom=maxTree+maxDis//2
        people.extend(list(range(maxLeft,maxLeftTo)))
        people.extend(list(range(maxRightFrom+1,maxRight+1)))
        #print("left",(maxDis//2+1+m//2+maxDis//2)*(m//2),"right",(maxDis//2+m//2+m%2)*(m%2))
        #print(maxDis//2+m//2,maxDis//2)
        totalDistance+=((maxDis//2+1+m//2+maxDis//2)*(m//2)+(maxDis//2+m//2+m%2)*(m%2))
    print(totalDistance)
    print(" ".join(map(str,people)))


from copy import deepcopy
import time
if __name__ == '__main__':
    n, m = map(int,input().split())
    trees=[int(x) for x in input().split()]
    peopleNtree={int(x):True for x in trees}
    people=[]
    #check max fill between max and min ele
    minTree=min(trees)
    maxTree=max(trees)
    maxDis=maxTree-minTree

    maxFill=maxDis//2*4-1+maxDis%2-(len(trees)-2)
    #preVal
    distance=-1
    pos=0
    totalDistance=0

    while m>0:

        treeVacancy=trees[pos]+distance
        exist=peopleNtree.get(treeVacancy,False)
        if not exist:
            peopleNtree[treeVacancy]=True
            people.append(treeVacancy)
            totalDistance+=abs(distance)
            m-=1
        if distance>0:
            pos+=1
        distance*=-1
        if pos==n:
            pos=0
            distance=distance-1

    print(totalDistance)
    print(" ".join(map(str,people)))


from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
n,m=map(int,input().split())
stack=deque()
l=list(map(int,input().split()))
s=set(l)
ans=[]
for i in l:
	if i-1 not in s:
		s.add(i-1)
		stack.append(i-1)
	if i+1 not in s:
		s.add(i+1)
		stack.append(i+1)
count=0
a=0
while m>0:
	a+=1
	for i in range(len(stack)):
		if m<=0:
			break
		t=stack.popleft()
		ans.append(t)
		# s.add(t)
		m-=1
		count+=a
		if t-1 not in s:
			stack.append(t-1)
			s.add(t-1)
		if t+1 not in s:
			stack.append(t+1)
			s.add(t+1)
print(count)
print(*ans)


from collections import deque as dq
n,m=map(int,input().split())
a=sorted(list(map(int,input().split())))
s=set(a)
k=dq([])
for i in a:
    k.append((i,0,1,1))
ans=0
t=[]
while m>0:
    p,d,l,r=k.popleft()
    if l and (p-(d+1) not in s):
        s.add(p-(d+1))
        t.append(p-(d+1))
        ans+=d+1
        m-=1
    else:
        l=0
    if m>0 and r and (p+(d+1) not in s):
        s.add(p+(d+1))
        t.append(p+(d+1))
        ans+=d+1
        m-=1
    else:
        r=0
    if l or r:
        k.append((p,d+1,l,r))
print(ans)
print(*sorted(t))


def arr_inp():
    return [int(x) for x in stdin.readline().split()]

from sys import stdin
from collections import defaultdict, Counter

n, m = arr_inp()
x, ans, c, s = sorted(arr_inp()), [], 1, 0
mem = defaultdict(int, Counter(x))

while (m > 0):
    for i in x:
        if mem[i - c] == 0:
            ans.append(i - c)
            mem[i - c] = 1
            m -= 1
            s += c
        if m == 0:
            break
        if mem[i + c] == 0:
            ans.append(i + c)
            mem[i + c] = 1
            m -= 1
            s += c
    c += 1
print(s)
print(*ans)


def arr_inp():
    return [int(x) for x in stdin.readline().split()]

def binary_search(arr, start, end, x):
    if (end < start):
        # Element is not present in the array
        return -1
    else:
        mid = start + (end - start) // 2
        # If element is present at the middle
        if mid < n - 1 and arr[mid] < x and arr[mid + 1] > x:
            return mid
        # If element is smaller than mid
        elif (arr[mid] > x):
            return binary_search(arr, start, mid - 1, x)
        # Else the element greater than mid
        else:
            return binary_search(arr, mid + 1, end, x)

def get_col(arr, i):
    return [row[i] for row in arr]

from sys import stdin
from collections import defaultdict, Counter
from operator import itemgetter

n, m = arr_inp()
x, ans, c, s = sorted(arr_inp()), [], 1, 0
mem, mem2 = defaultdict(int), defaultdict(int, Counter(x))

for i in range(x[0] + 1, x[-1]):
    ix = binary_search(x, 0, n - 1, i)
    if ix != -1:
        mem[i] = min(i - x[ix], x[ix + 1] - i)

for i in range(1, m + 1):
    pre, nxt = x[0] - i, x[-1] + i
    if mem2[pre] == 0:
        mem[pre] = i
    if mem2[nxt] == 0:
        mem[nxt] = i

ans = sorted(mem.items(), key=itemgetter(1))
# print(ans)
print(sum(get_col(ans, 1)[:m]))
print(*get_col(ans, 0)[:m])


def arr_inp():
    return [float(x) for x in stdin.readline().split()]

def binary_search(arr, start, end, x):
    if (end < start):
        # Element is not present in the array
        return -1
    else:
        mid = start + (end - start) // 2
        # If element is present at the middle
        if mid < n - 1 and arr[mid] < x and arr[mid + 1] > x:
            return mid
        # If element is smaller than mid
        elif (arr[mid] > x):
            return binary_search(arr, start, mid - 1, x)
        # Else the element greater than mid
        else:
            return binary_search(arr, mid + 1, end, x)

def get_col(arr, i):
    return [row[i] for row in arr]

from sys import stdin
from collections import defaultdict, Counter
from operator import itemgetter

n, m = arr_inp()
n, m = int(n), int(m)
x, ans, c, s = sorted(arr_inp()), [], 1, 0
x = [int(x[i]) for i in range(n)]

mem, mem2 = defaultdict(int), defaultdict(int, Counter(x))

for i in range(x[0] + 1, x[-1]):
    ix = binary_search(x, 0, n - 1, i)
    if ix != -1:
        mem[i] = min(i - x[ix], x[ix + 1] - i)

for i in range(1, m + 1):
    pre, nxt = x[0] - i, x[-1] + i
    if mem2[pre] == 0:
        mem[pre] = i
    if mem2[nxt] == 0:
        mem[nxt] = i

ans = sorted(mem.items(), key=itemgetter(1))
# print(ans)
print(sum(get_col(ans, 1)[:m]))
print(*get_col(ans, 0)[:m])


def arr_inp():
    return [int(x) for x in stdin.readline().split()]

def bfs():
    global m
    ans, queue, dis = [], deque([]), 0

    for i in a:
        visit[i] = 1
        queue.append(i)

    while queue:
        # dequeue parent vertix
        s = queue.popleft()

        # enqueue child vertices
        for i in [s - 1, s + 1]:
            if m:
                if visit[i] == 0:
                    queue.append(i)
                    ans.append(i)
                    m -= 1
                    visit[i] = 1
            else:
                queue = deque([])
                break
    return ans

from sys import stdin
from collections import defaultdict, deque
from bisect import *

n, m = arr_inp()
a, visit, ans = sorted(arr_inp()), defaultdict(int), 0
arr = bfs()

for i in arr:
    ix = bisect_right(a, i)
    if ix == 0:
        ans += abs(a[0] - i)
    elif ix == n:
        ans += abs(a[-1] - i)
    else:
        ans += min(abs(a[ix - 1] - i), abs(a[ix] - i))

print(ans)
print(*arr)


from bisect import bisect_left, bisect_right
from typing import List
import collections
import bisect
import itertools
import functools
from fractions import gcd
import heapq
from math import ceil, sqrt, floor

import sys
sys.setrecursionlimit(50000)

import collections

from collections import defaultdict, deque
import collections

import bisect

from collections import defaultdict, deque
import collections
n, m = list(map(int, input().split()))

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

dic = {}
for x in xs:
    dic[x] = (x,x)

merged_intervals = []
for k,v in dic.items():
    if k - 1 not in dic:
        j = k
        while j + 1 in dic:
            j += 1
        merged_intervals.append((k, j))

merged_intervals.sort()

spaces = []
for i in range(len(merged_intervals) - 1):
    dist = merged_intervals[i+1][0] - merged_intervals[i][1] - 1
    spaces.append(dist)
# spaces.append(2 ** 32)

total_dist = 0
current_dist = 1
num = 0
ys = []
valid_indices = {i for i in range(len(spaces))}
invalid_indices = set()
while num < m:
    for i in valid_indices:
        if num >= m:
            break
        avail = min(2, spaces[i], m - num)
        num += avail
        total_dist += current_dist * avail

        if avail >= 1:
            ys.append(merged_intervals[i][1] + current_dist)
        if avail >= 2:
            ys.append(merged_intervals[i+1][0] - current_dist)
        spaces[i] -= avail
        if spaces[i] == 0:
            invalid_indices.add(i)
    if num < m:
        total_dist += current_dist
        ys.append(merged_intervals[0][0] - current_dist)
        num += 1
    if num < m:
        total_dist += current_dist
        ys.append(merged_intervals[-1][1] + current_dist)
        num += 1
    for invalid in invalid_indices:
        valid_indices.remove(invalid)
    if invalid_indices:
        invalid_indices.clear()
    current_dist += 1

print(total_dist)
print(' '.join(str(c) for c in ys))


from bisect import bisect_left, bisect_right
from typing import List
import collections
import bisect
import itertools
import functools
from fractions import gcd
import heapq
from math import ceil, sqrt, floor

import sys
sys.setrecursionlimit(50000)

import collections

from collections import defaultdict, deque
import collections

import bisect

from collections import defaultdict, deque
import collections
n, m = list(map(int, input().split()))

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

dic = {}
for x in xs:
    dic[x] = (x,x)

merged_intervals = []
for k,v in dic.items():
    if k - 1 not in dic:
        j = k
        while j + 1 in dic:
            j += 1
        merged_intervals.append((k, j))

merged_intervals.sort()

spaces = []
for i in range(len(merged_intervals) - 1):
    dist = merged_intervals[i+1][0] - merged_intervals[i][1] - 1
    spaces.append(dist)
# spaces.append(2 ** 32)

total_dist = 0
current_dist = 1
num = 0
ys = []
while num < m:
    i = 0
    while i < len(spaces) and num < m:
        avail = min(2, spaces[i], m - num)
        num += avail
        total_dist += current_dist * avail

        if avail >= 1:
            ys.append(merged_intervals[i][1] + current_dist)
        if avail >= 2:
            ys.append(merged_intervals[i+1][0] - current_dist)
        spaces[i] -= avail
        i += 1
    if num < m:
        total_dist += current_dist
        ys.append(merged_intervals[0][0] - current_dist)
        num += 1
    if num < m:
        total_dist += current_dist
        ys.append(merged_intervals[-1][1] + current_dist)
        num += 1

    current_dist += 1

print(total_dist)
print(' '.join(str(c) for c in ys))


import sys
input = sys.stdin.buffer.readline
n, m = map(int, input().split())
a = list(map(int, input().split()))
mp = {}
q = []
for i in a:
	q.append(i)
	mp[i] = 0
ans, res, i = [], 0, 0
while (len(ans) < m):
	x = q[i]
	for k in [-1, 1]:
		if (x + k not in mp):
			mp[x + k] = mp[x] + 1
			res += mp[x + k]
			q.append(x + k)
			ans.append(x + k)
		if (len(ans) == m):
			break;
	i += 1
print(res)
print(*ans)


n, m = map(int, input().split())
a = list(map(int, input().split()))
mp = {}
q = []
for i in a:
	q.append(i)
	mp[i] = 0
ans, res, i = [], 0, 0
while (len(ans) < m):
	x = q[i]
	for k in [-1, 1]:
		if (x + k not in mp):
			mp[x + k] = mp[x] + 1
			res += mp[x + k]
			q.append(x + k)
			ans.append(x + k)
		if (len(ans) == m):
			break;
	i += 1
print(res)
print(*ans)


'''input
3 5
0 3 1
'''
# A coding delight
from sys import stdin
from collections import defaultdict, deque

def bfs():
	visited = dict()
	myq = deque()

	for i in arr:
		visited[i] = True
		myq.append(i)
	cost = 0
	ans = []
	dist = 1
	count = m
	while len(myq) > 0 and count > 0:
		temp = deque()
		while len(myq) > 0 and count > 0:
			node = myq.popleft()
			if count > 0 and node + 1 not in visited:
				temp.append(node + 1)
				visited[node + 1] = True
				cost += dist
				ans.append(node + 1)
				count -= 1

			if count > 0 and node - 1 not in visited:
				temp.append(node - 1)
				visited[node - 1] = True
				cost += dist
				count -= 1
				ans.append(node - 1)
		myq = temp
		dist += 1
	return cost, ans

# main starts
n, m = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
cost, ans = bfs()
print(cost)
print(*ans)


n,m = map(int,input().split())
a = list(map(int,input().split()))

d = {}
v = []
for c in a:
	d[c] = 1
	v.append(c)

ans = []

dist = 0
i = 0
while(len(ans) < m):
	x = v[i]

	if x-1 not in d:
		dist += d[x]
		ans.append(x-1)
		v.append(x-1)
		d[x-1] = d[x]+1

	if len(ans) == m:
		break

	if x+1 not in d:
		dist += d[x]
		ans.append(x+1)
		v.append(x+1)
		d[x+1] = d[x]+1

	i += 1

print(dist)
for c in ans:
	print(c,end = " ")


n,m = map(int,input().split())
a = list(map(int,input().split()))

d = {}
v = []
for c in a:
	d[c] = 1
	v.append(c)

ans = []

dist = 0
i = 0
while(len(ans) < m):
	x = v[i]

	if x-1 not in d:
		dist += d[x]
		ans.append(x-1)
		v.append(x-1)
		d[x-1] = d[x]+1

	if x+1 not in d:
		dist += d[x]
		ans.append(x+1)
		v.append(x+1)
		d[x+1] = d[x]+1

	i += 1

print(dist)
for c in ans:
	print(c,end = " ")


def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

from queue import deque

n,m=[int(x) for x in input().split()]
a=[int(z) for z in input().split()]

occupiedPositions=set()

for x in a:
    occupiedPositions.add(x) #all trees

ans=[]
positionQ=deque() #store [position,distance from nearest XMas Tree]

a.sort()
for i in range(n):
    if a[i]-1 not in occupiedPositions: #all space on the left and right of trees (if not already occupied)
        positionQ.append([a[i]-1,1])
        occupiedPositions.add(a[i]-1)
    if a[i]+1 not in occupiedPositions:
        positionQ.append([a[i]+1,1])
        occupiedPositions.add(a[i]+1)
totalDistance=0
while len(ans)<m:
    pos,dis=positionQ.popleft()
    totalDistance+=dis
    ans.append(pos)
    if pos-1 not in occupiedPositions:
        occupiedPositions.add(pos-1)
        positionQ.append([pos-1,dis+1])
    if pos+1 not in occupiedPositions:
        occupiedPositions.add(pos+1)
        positionQ.append([pos+1,dis+1])
#    print('pos:{} occupied:{} queue:{}'.format(pos,occupiedPositions,positionQ))

print(totalDistance)
oneLineArrayPrint(ans)


def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

from queue import deque

n,m=[int(x) for x in input().split()]
a=[int(z) for z in input().split()]

occupiedPositions=set()

for x in a:
    occupiedPositions.add(x) #all trees

ans=[]
positionQ=deque() #store [position,distance from nearest XMas Tree]

a.sort()
for i in range(n):
    if a[i]-1 not in occupiedPositions: #all space on the left and right of trees (if not already occupied)
        positionQ.append([a[i]-1,1])
        occupiedPositions.add(a[i]-1)
    if a[i]+1 not in occupiedPositions:
        positionQ.append([a[i]+1,1])
        occupiedPositions.add(a[i]+1)

totalDistance=0
while len(ans)<m:
    pos,dis=positionQ.popleft()
    totalDistance+=dis
    ans.append(pos)
    if pos-1 not in occupiedPositions:
        occupiedPositions.add(pos-1)
    positionQ.append([pos-1,dis+1])
    if pos+1 not in occupiedPositions:
        occupiedPositions.add(pos+1)
    positionQ.append([pos+1,dis+1])

print(totalDistance)
oneLineArrayPrint(ans)


import heapq

n,m = map(int,input().split())
x = sorted(map(int,input().split()))

# (distance, position, direction, maxval)
pos = [(1,x[0]-1,-1,m), (1,x[-1]+1,1,m)]
for i in range(n-1):
    left = (x[i+1]-x[i])//2
    right = (x[i+1]-x[i]-1)//2
    if left:
        pos.append((1,x[i]+1,1,left))
    if right:
        pos.append((1,x[i+1]-1,-1,right))

answer = []
total = 0
for i in range(m):
    dist, xx, direction, maxval = heapq.heappop(pos)
    answer.append(xx)
    total+=dist
    if dist<maxval:
        heapq.heappush(pos, (dist+1,xx+direction,direction,maxval))

print(total)
print(' '.join(map(str,answer)))


def solution():

    a, b = map(int, input().split())
    arr = tuple(int(x) for x in input().split())
    points = frozenset(arr)
    s = set()
    i = 1
    total = 0

    while len(s) < b:
        for v in arr:
            p = v - i
            if p not in points and p not in s:
                s.add(p)
                total += i
                if len(s) == b: break
            p = v + i
            if p not in points and p not in s:
                s.add(p)
                total += i
                if len(s) == b: break
        i += 1

    print(total)
    print(" ".join(map(str, s)))

def main():
    solution()

if __name__ == "__main__":
    main()


from sys import stdout

def solution():

    a, b = map(int, input().split())
    arr = tuple(int(x) for x in input().split())
    points = frozenset(arr)
    s = set()
    i = 1
    total = 0

    while len(s) < b:
        for v in arr:
            p = v - i
            k = len(s)
            if p not in points:
                s.add(p)
                if k != len(s):
                    total += i
                    if len(s) == b: break
            p = v + i
            k = len(s)
            if p not in points:
                s.add(p)
                if k != len(s):
                    total += i
                    if len(s) == b: break
        i += 1

    stdout.write("{}\n{}".format(total, " ".join(map(str, s))))

if __name__ == "__main__":
    solution()


from sys import stdout

def solution():

    a, b = map(int, input().split())
    arr = [int(x) for x in input().split()]
    points = set(arr)
    s = set()
    i = 1
    total = 0

    while len(s) < b:
        temp = set()
        for v in arr:
            p = v - i
            if p not in points:
                s.add(p)
                points.add(p)
                temp.add(v)
                total += i
                if len(s) == b: break
            p = v + i
            if p not in points:
                s.add(p)
                points.add(p)
                temp.add(v)
                total += i
                if len(s) == b: break
        i += 1
        arr = {*temp}

    """
    while len(s) < b:
        for v in arr:
            p = v - i
            k = len(s)
            if p not in points:
                s.add(p)
                if k != len(s):
                    total += i
                    if len(s) == b: break
            p = v + i
            k = len(s)
            if p not in points:
                s.add(p)
                if k != len(s):
                    total += i
                    if len(s) == b: break
        i += 1
    """

    stdout.write("{}\n{}".format(total, " ".join(map(str, s))))

if __name__ == "__main__":
    solution()


from sys import stdout

def solution():

    a, b = map(int, input().split())
    arr = [int(x) for x in input().split()]
    points = set(arr)
    s = set()
    i = 1
    total = 0

    while len(s) < b:
        temp = set()
        for v in arr:
            p = v - i
            if p not in points:
                s.add(p)
                points.add(p)
                temp.add(v)
                total += i
                if len(s) == b: break
            p = v + i
            if p not in points:
                s.add(p)
                points.add(p)
                temp.add(v)
                total += i
                if len(s) == b: break
        i += 1
        arr = frozenset(temp)

    """
    while len(s) < b:
        for v in arr:
            p = v - i
            k = len(s)
            if p not in points:
                s.add(p)
                if k != len(s):
                    total += i
                    if len(s) == b: break
            p = v + i
            k = len(s)
            if p not in points:
                s.add(p)
                if k != len(s):
                    total += i
                    if len(s) == b: break
        i += 1
    """

    stdout.write("{}\n{}".format(total, " ".join(map(str, s))))

if __name__ == "__main__":
    solution()


import bisect,sys
#input=sys.stdin.readline
l=input().split()
n=int(l[0])
m=int(l[1])
inf=10**15
l=input().split()
li=[inf,-inf]
for i in l:
    li.append((int(i)))
li.sort()
dist=1
ans=0
diff=[]
for i in range(n+1):
    diff.append(((li[i+1]-li[i]),li[i],li[i+1]))
diff.sort()
diffo=[]
num1=[]
num2=[]
for i in diff:
    diffo.append(i[0])
    num1.append(i[1])
    num2.append(i[2])
l=[]
i=0
done=0
while(1):
    z=bisect.bisect_left(diffo,2*dist)
    for i in range(z,n+1):
        if(num1[i]==inf or num1[i]==-inf):
            continue
        if(len(l)>=m):
            done=1
            break
        ans+=dist
        l.append(num1[i]+dist)
    if(len(l)>=m):
        break
    z=bisect.bisect_left(diffo,2*dist+1)
    for i in range(z,n+1):
        if(num2[i]==inf or num2[i]==-inf):
            continue
        if(len(l)>=m):
            break
        ans+=dist
        l.append(num2[i]-dist)
    if(len(l)>=m):
        break
    dist+=1
print(ans)
for i in l:
    print(i,end=" ")


import bisect,sys
input=sys.stdin.readline
l=input().split()
n=int(l[0])
m=int(l[1])
inf=10**15
l=input().split()
li=[inf,-inf]
for i in l:
    li.append((int(i)))
li.sort()
dist=1
ans=0
diff=[]
for i in range(n+1):
    diff.append(((li[i+1]-li[i]),li[i],li[i+1]))
diff.sort()
diffo=[]
num1=[]
num2=[]
for i in diff:
    diffo.append(i[0])
    num1.append(i[1])
    num2.append(i[2])
l=[]
i=0
done=0
while(1):
    z=bisect.bisect_left(diffo,2*dist)
    for i in range(z,n+1):
        if(num1[i]==inf or num1[i]==-inf):
            continue
        if(len(l)>=m):
            done=1
            break
        ans+=dist
        l.append(num1[i]+dist)
    if(len(l)>=m):
        break
    z=bisect.bisect_left(diffo,2*dist+1)
    for i in range(z,n+1):
        if(num2[i]==inf or num2[i]==-inf):
            continue
        if(len(l)>=m):
            break
        ans+=dist
        l.append(num2[i]-dist)
    if(len(l)>=m):
        break
    dist+=1
print(ans)
for i in l:
    print(i,end=" ")


import heapq

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

y = []
total_distance = 0

occupied = set(x)

Q = [(1, tree + d) for tree in x for d in (-1, 1)]

while len(y) < m:
    distance, position = heapq.heappop(Q)
    if position not in occupied:
        y.append(position)
        total_distance += distance
        occupied.add(position)
        heapq.heappush(Q, (distance + 1, position + 1))
        heapq.heappush(Q, (distance + 1, position - 1))

print(total_distance)
print(*y)


import sys
from collections import deque

n, m = map(int, sys.stdin.readline().split())
tree = list((map(int, sys.stdin.readline().split())))
visit = set(tree)
list_res = [0]*m
list_queue = deque()
for i in tree:
    list_queue.append((i, 0))

res = 0
while list_queue and m>0:
    now_i, now_d = list_queue.popleft()

    for i in (1, -1):
        next_i = now_i + i
        if not next_i in visit:
            list_queue.append((next_i, now_d+1))
            visit.add(next_i)
            res += now_d+1
            m-=1
            list_res[m] = next_i
            if not m:
                break

print(res)
print(*list_res)


import sys

n, m = map(int, sys.stdin.readline().split())
tree = list(map(int, sys.stdin.readline().split()))
tree.sort()
set_visit = set()
list_res = [0.1]*m
res = 0
d = 1
i = 0
while m:
    for t_i in range(n):
        t = tree[t_i]

        if (0<t_i<n and tree[t_i] - d > tree[t_i-1]) or t_i==0:
            if m and not t-d in set_visit:
                set_visit.add(t-d)
                res += d
                m-=1
                list_res[m] = t-d
        if (t_i<n-1 and tree[t_i] + d < tree[t_i+1]) or t_i ==n-1:
            if m and not t+d in set_visit:
                set_visit.add(t+d)
                m-=1
                res += d
                list_res[m] = t+d

        if not m:
            break
    d+=1
print(res)
print(*list_res)


import sys
from collections import deque

n, m = map(int, sys.stdin.readline().split())
tree = sorted((map(int, sys.stdin.readline().split())))
set_visit = set(tree)
tree =deque(tree)
list_res = [0]*m
res = 0
d = 1
i = 0
while m:
    for _ in range(len(tree)):
        t_n = tree.popleft()

        if tree and t_n-d>tree[0] or t_n<tree[0]:
            if m and not t_n-d in set_visit:
                set_visit.add(t_n-d)
                res += d
                m-=1
                list_res[m] = t_n-d
        else:
            continue
        if tree and t_n+d<tree[-1] or t_n>tree[-1]:
            if m and not t_n+d in set_visit:
                set_visit.add(t_n+d)
                m-=1
                res += d
                list_res[m] = t_n+d
        else:
            continue

        if not m:
            break
        tree.append(t_n)
    d+=1
print(res)
print(*list_res)
"""
2 1 0 1 2 3 4 5 6
o o x x o x o o"""


from collections import deque
n, m = map(int, input().split())
x = list(map(int, input().split()))
dists = {a:0 for a in x}
q = deque(x)
dist = 0
res = []
while len(q) > 0:
    e = q.pop()
    if len(res) == m:
        break
    if dists[e] > 0:
        dist += dists[e]
        res.append(e)
    if e-1 not in dists:
        dists[e-1] = dists[e]+1
        q.appendleft(e-1)
    if e+1 not in dists:
        dists[e+1] = dists[e] + 1
        q.appendleft(e+1)
print(dist)
print(' '.join(map(str, res)))


from collections import deque

n, m = map(int, input().split())

trees = [int(i) for i in input().split()]

dist = {i:0 for i in trees}

q = deque()

for cur in trees:
    q.append(cur)

ans_len = 0
ans_people = []

while len(q) > 0 and len(ans_people) != m:
    cur = q.popleft()

    if cur in dist and dist[cur] != 0:
        ans_len += dist[cur]
        ans_people.append(cur)

    if not cur - 1 in dist:
        dist[cur - 1] = dist[cur] + 1
        q.append(cur - 1)

    if not cur + 1 in dist:
        dist[cur + 1] = dist[cur] + 1
        q.append(cur + 1)

print(ans_len)

ans_people.sort()

for cur in ans_people:
    print(cur, end = ' ')


from collections import deque

n, m = map(int, input().split())

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

dist = {i:0 for i in trees}

q = deque()

for cur in trees:
    q.append(cur)

ans_len = 0
ans_people = []

while len(q) > 0 and len(ans_people) != m:
    cur = q.popleft()

    if cur in dist and dist[cur] != 0:
        ans_len += dist[cur]
        ans_people.append(cur)

    if not cur - 1 in dist:
        dist[cur - 1] = dist[cur] + 1
        q.append(cur - 1)

    if not cur + 1 in dist:
        dist[cur + 1] = dist[cur] + 1
        q.append(cur + 1)

print(ans_len)

ans_people.sort()

for cur in ans_people:
    print(cur, end = ' ')


n,m = map(int, input().split())
l = set(list(map(int, input().split())))
positions = [(x,0) for x in l]
people = set()
dist = 0
while len(people) != m:
    p,d = positions.pop(0)
    if p + 1 not in people | l:
        positions.append((p+1, d+1))
    if p - 1 not in people | l:
        positions.append((p-1, d+1))
    if d != 0:
        if p not in people:
            people.add(p)
            dist += d

print(dist)
print(" ".join(str(x) for x in people))


n,m = map(int, input().split())
l = set(list(map(int, input().split())))
positions = [(x,0) for x in l]
people = set()
dist = 0
while len(people) != m:
    p,d = positions.pop(0)
    if p + 1 not in people and p + 1 not in l:
        positions.append((p+1, d+1))
    if p - 1 not in people and p - 1 not in l:
        positions.append((p-1, d+1))
    if d != 0:
        if p not in people:
            people.add(p)
            dist += d

print(dist)
print(" ".join(str(x) for x in people))


n,m = map(int, input().split())
positions = list(map(int, input().split()))
positionSet = set(positions)
people = set()
dist = 0

currentTree = 0
distFromTree = 1
peoplePlaced = 0
while True:
    tree = positions[currentTree]
    if (tree + distFromTree not in positionSet) and (tree + distFromTree not in people):
        people.add(tree + distFromTree)
        dist += distFromTree
        peoplePlaced += 1
        if peoplePlaced == m:
            break

    if (tree - distFromTree not in positionSet) and (tree - distFromTree not in people):
        people.add(tree - distFromTree)
        dist += distFromTree
        peoplePlaced += 1
        if peoplePlaced == m:
            break
    currentTree += 1
    if currentTree == len(positions):
        distFromTree += 1
        currentTree = 0

print(dist)
print(" ".join(str(x) for x in people))


from collections import deque

n,m = map(int, input().split())
l = set(list(map(int, input().split())))
positions = deque([(x,0) for x in l])
people = set()
dist = 0
while len(people) != m:
    p,d = positions.popleft()
    if p + 1 not in people and p + 1 not in l:
        positions.append((p+1, d+1))
    if p - 1 not in people and p - 1 not in l:
        positions.append((p-1, d+1))
    if d != 0:
        if p not in people:
            people.add(p)
            dist += d

print(dist)
print(" ".join(str(x) for x in people))


n,m = map(int, input().split())
positions = list(map(int, input().split()))
positionSet = set(positions)
people = set()
dist = 0

currentTree = 0
distFromTree = 1
peoplePlaced = 0
while True:
    tree = positions[currentTree]
    if tree + distFromTree not in positionSet | people:
        people.add(tree + distFromTree)
        dist += distFromTree
        peoplePlaced += 1
        if peoplePlaced == m:
            break
    if tree - distFromTree not in positionSet | people:
        people.add(tree - distFromTree)
        dist += distFromTree
        peoplePlaced += 1
        if peoplePlaced == m:
            break
    currentTree += 1
    if currentTree == len(positions):
        distFromTree += 1
        currentTree = 0

print(dist)
print(" ".join(str(x) for x in people))


ints = list(map(int, input().split()))
n, m = ints[0], ints[1]
trees = list(map(int, input().split()))
trees.sort()

occupied = {}
for i in range(len(trees)):
    occupied[trees[i]] = 1

trees = set(trees)

overall = 0
distance = 1
guys = []
while m > 0:
    deletable = set()
    for tree in trees:
        left = tree - distance
        must_delete = 0
        if left not in occupied:
            occupied[left] = 1
            guys.append(left)
            overall += distance
            m -= 1
        else:
            must_delete += 1

        if m == 0:
            break

        right = tree + distance
        if right not in occupied:
            occupied[right] = 1
            guys.append(right)
            overall += distance
            m -= 1
        else:
            must_delete += 1

        if must_delete == 2:
            deletable.add(tree)

    trees = trees - deletable

    distance += 1

print(overall)
print(*guys)