You are given an array consisting of $n$ integers $a_1, a_2, \dots, a_n$, and a positive integer $m$. It is guaranteed that $m$ is a divisor of $n$.

In a single move, you can choose any position $i$ between $1$ and $n$ and increase $a_i$ by $1$.

Let's calculate $c_r$ ($0 \le r \le m-1)$ — the number of elements having remainder $r$ when divided by $m$. In other words, for each remainder, let's find the number of corresponding elements in $a$ with that remainder.

Your task is to change the array in such a way that $c_0 = c_1 = \dots = c_{m-1} = \frac{n}{m}$.

Find the minimum number of moves to satisfy the above requirement.


-----Input-----

The first line of input contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5, 1 \le m \le n$). It is guaranteed that $m$ is a divisor of $n$.

The second line of input contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$), the elements of the array.


-----Output-----

In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from $0$ to $m - 1$, the number of elements of the array having this remainder equals $\frac{n}{m}$.

In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed $10^{18}$.


-----Examples-----
Input
6 3
3 2 0 6 10 12

Output
3
3 2 0 7 10 14 

Input
4 2
0 1 2 3

Output
0
0 1 2 3

Source: codeforces | Difficulty: HARD
Tags: Data structures

Implementation

Greedy algorithms


Solutions:
from collections import deque
import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
cnt = [0] * m
x = [[] for _ in range(m)]
for i in range(n):
	ai = a[i] % m
	cnt[ai] += 1
	x[ai].append(i)
l = n // m
q = deque()
for i in range(m):
	if cnt[i] < l:
		q.append(i)
ans = 0
for i in range(m):
	for j in x[i]:
		if cnt[i] <= l:
			break
		while q[0] < i:
			q.append(q.popleft() + m)
		k = q[0] % m
		cnt[k] += 1
		cnt[i] -= 1
		ans += (k - i) % m
		a[j] += (k - i) % m
		if cnt[k] == l:
			q.popleft()
print(ans)
print(*a)


k = int(input().split()[1])
l = list()
sc = [0] * k
for i in input().split():
	l.append(int(i))
goal = len(l) / k
cpt = 0
s = ''
dict = {}
for i in range(len(l)):
	ok = 0
	init = l[i] % k
	ltc = list()
	while not ok:
		div = l[i] % k
		if sc[div] < goal:
			sc[div] += 1
			ok = 1
			for j in ltc:
				dict[j] = div
		else:
			ltc.append(div)
			if div in dict.keys():
				nd = dict[div]
				diff = (nd - div) % k
				cpt += diff
				l[i] += diff
			else:
				cpt += 1
				l[i] += 1
	s += str(l[i]) + ' '
print(cpt)
print(s[:len(s) - 1])


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
summ = sum(a)
k = [[[], 0] for i in range(m)]
for i in range(n):
	k[a[i] % m][0].append(i)
	k[a[i] % m][1] += 1
j = 0
l = n // m
for i in range(m):
	while k[i][1] > l:
		while j < i or k[j % m][1] >= l:
			j += 1
		z = k[i][0].pop()
		k[i][1] -= 1
		a[z] += (j - i) % m
		k[j % m][0].append(z)
		k[j % m][1] += 1
print(sum(a) - summ)
print(*a)


from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))

def fast():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in fast().split()]
(z, zz) = (fast, lambda : map(int, z().split()))
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def output(answer, end='\n'):
	stdout.write(str(answer) + end)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
(n, m) = zzz()
arr = zzz()
s = sum(arr)
idx = [[] for i in range(m)]
for i in range(n):
	idx[arr[i] % m].append(i)
j = 0
for i in range(m):
	while len(idx[i]) > n // m:
		while j < i or len(idx[j % m]) >= n // m:
			j += 1
		last = idx[i].pop()
		arr[last] += (j - i) % m
		idx[j % m].append(last)
print(sum(arr) - s)
print(*arr)


import sys
input = sys.stdin.buffer.readline
(n, m) = map(int, input().split())
arr = list(map(int, input().split()))
ori_arr = arr[:]
store_m = [[] for i in range(m)]
for i in range(n):
	store_m[arr[i] % m].append(i)
limit = n // m
count = 0
free = []
for i in range(2 * m):
	while len(store_m[i % m]) > limit:
		free.append(store_m[i % m].pop())
	while free and len(store_m[i % m]) < limit:
		store_m[i % m].append(free.pop())
for i in range(m):
	for j in range(limit):
		r = store_m[i][j]
		arr[r] = arr[r] + (i - arr[r] % m) % m
for i in range(n):
	count += arr[i] - ori_arr[i]
print(count)
print(*arr)


from collections import deque
(n, m) = map(int, input().split())
a = [int(x) for x in input().split()]
ind = [deque() for r in range(m)]
c = m * [0]
for (i, ai) in enumerate(a):
	r = ai % m
	c[r] += 1
	ind[r].append(i)
q = deque()
ans = 0
for i in range(0, 2 * m):
	r = i % m
	while c[r] > n // m:
		q.append((i, ind[r].pop()))
		c[r] -= 1
	while c[r] < n // m and q:
		(j, index) = q.popleft()
		ind[r].append(index)
		c[r] += 1
		a[index] += i - j
		ans += i - j
print(ans)
print(*a)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = [[] for i in range(m)]
for i in range(len(a)):
	c[a[i] % m].append(i)
active = []
k = n // m
ans = 0
unfull = set()
for i in range(m):
	raz = len(c[i]) - k
	if raz > 0:
		for j in range(raz):
			active.append((c[i].pop(), i))
	elif raz < 0:
		if -raz > len(active):
			unfull.add((i, -raz - len(active)))
		for j in range(min(-raz, len(active))):
			(ind, start) = active.pop()
			a[ind] += i - start
			ans += i - start
for (i, raz) in unfull:
	for j in range(raz):
		(ind, start) = active.pop()
		a[ind] += m + i - start
		ans += m + i - start
print(ans)
print(*a)


import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
idx = [[] for i in range(m)]
for i in range(n):
	idx[a[i] % m].append(i)
k = n // m
free = []
for i in range(m):
	while len(idx[i]) > k:
		v = idx[i].pop()
		free.append(v)
	while free and len(idx[i]) < k:
		v = free.pop()
		idx[i].append(v)
for i in range(m):
	while len(idx[i]) > k:
		v = idx[i].pop()
		free.append(v)
	while free and len(idx[i]) < k:
		v = free.pop()
		idx[i].append(v)
cost = 0
for i in range(m):
	for j in idx[i]:
		dx = (i - a[j] % m) % m
		cost += dx
		a[j] += dx
print(cost)
print(*a)


R = lambda : map(int, input().split())
(n, m) = R()
L = list(R())
d = [[] for i in range(m)]
for (j, i) in enumerate(L):
	d[i % m].append(j)
k = n // m
a = []
res = 0
j = 0
for i in range(2 * m):
	c = i % m
	while len(d[c]) > k:
		ind = d[c].pop()
		a.append([ind, i])
	while len(d[c]) < k and len(a) > 0:
		(ind, ele) = a.pop()
		d[c].append(ind)
		res += i - ele
		L[ind] += i - ele
print(res)
print(*L)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
s = sum(a)
x = [[] for i in range(m)]
for i in range(n):
	x[a[i] % m].append(i)
j = 0
for i in range(m):
	while len(x[i]) > n // m:
		while j < i or len(x[j % m]) >= n // m:
			j += 1
		k = x[i].pop()
		a[k] += (j - i) % m
		x[j % m].append(k)
print(sum(a) - s)
print(*a)


(n, m) = list(map(int, input().split()))
assert n % m == 0
k = n // m
a = [*list(map(int, input().split()))]
inds = [[] for r in range(m)]
for (i, v) in enumerate(a):
	inds[v % m].append(i)
extras = []
for r in range(2 * m):
	r %= m
	if len(inds[r]) == k:
		continue
	elif len(inds[r]) > k:
		extras.extend(inds[r][k:])
		inds[r] = inds[r][:k]
	elif len(inds[r]) < k:
		for _ in range(min(k - len(inds[r]), len(extras))):
			inds[r].append(extras.pop())
	else:
		assert False
res = 0
for r in range(m):
	for i in inds[r]:
		if a[i] % m > r:
			res += m - a[i] % m
			a[i] += m - a[i] % m
		res += r - a[i] % m
		a[i] += r - a[i] % m
print(res)
print(' '.join(map(str, a)))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
(k, c, free) = (n // m, [[] for _ in range(m)], [])
for (i, ai) in enumerate(a):
	c[ai % m].append(i)
ans = 0
for _ in range(2 * m):
	i = _ % m
	lci = len(c[i])
	for j in range(k, lci)[::-1]:
		free.append((c[i][j], i))
		c[i].pop()
	for j in range(k - lci):
		if free:
			to_add = (i - free[-1][1]) % m
			ans += to_add
			a[free[-1][0]] += to_add
			c[i].append(free[-1][0])
			free.pop()
print(ans)
print(*a)


from collections import defaultdict
import sys
import bisect
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = [int(i) for i in input().split() if i != '\n']
rem = [[] for i in range(m)]
req = n // m
ans = 0
for i in range(n):
	rem[a[i] % m].append([a[i], i])
ind = m - 1
for i in range(m):
	size = len(rem[i])
	if size > req:
		ind = i
	if size < req:
		ok = False
		for j in range(ind, ind - m, -1):
			while len(rem[j]) > req:
				(pop, _) = rem[j].pop()
				rem[i].append([pop + (i - j) % m, _])
				if len(rem[i]) == req:
					ok = True
					break
			if ok:
				break
			ind -= 1
out = [0] * n
for i in rem:
	for j in i:
		out[j[1]] = j[0]
print(sum(out) - sum(a))
out = ' '.join(map(str, out))
print(out)


(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
s = [[] for _ in range(m)]
for i in range(n):
	s[a[i] % m].append(i)
f = []
c = 0
for _ in range(2):
	for i in range(m):
		while len(s[i]) > n // m:
			f.append((s[i].pop(), i))
		while len(s[i]) < n // m and f:
			(v, p) = f.pop()
			s[i].append(v)
			if i > p:
				d = i - p
			else:
				d = i + m - p
			a[v] += d
			c += d
print(c)
print(*a)


import sys
input = sys.stdin.readline
from collections import *
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
ans = a[:]
rem = defaultdict(list)
for i in range(n):
	rem[a[i] % m].append((i, a[i]))
q = deque([])
for i in range(2 * m):
	if len(rem[i % m]) == n // m:
		continue
	elif len(rem[i % m]) > n // m:
		for j in range(n // m, len(rem[i % m])):
			q.append(rem[i % m][j])
	else:
		for _ in range(min(n // m - len(rem[i % m]), len(q))):
			(idx, ai) = q.popleft()
			ans[idx] = ai + (i % m + m - ai % m) % m
			rem[i % m].append((idx, ans[idx]))
print(sum(ans) - sum(a))
print(*ans)


from collections import deque
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
cr = [0] * m
crpos = [[] for _ in range(m)]
for i in range(n):
	cr[a[i] % m] += 1
	crpos[a[i] % m].append(i)
cnt = 0
hold = deque()
for i in range(2 * m + 1):
	if cr[i % m] > n // m:
		tmp = cr[i % m] - n // m
		cr[i % m] = n // m
		for _ in range(tmp):
			idx = crpos[i % m].pop()
			hold.append((idx, i))
	elif cr[i % m] < n // m:
		tmp = n // m - cr[i % m]
		for _ in range(tmp):
			if not hold:
				break
			(idx, j) = hold.popleft()
			cnt += i - j
			a[idx] += i - j
			cr[i % m] += 1
for i in range(m):
	if cr[i] != n // m:
		assert False
print(cnt)
print(*a)


from collections import deque
(n, m) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
cnt = [0 for i in range(m)]
for x in a:
	cnt[x % m] += 1
for i in range(m):
	cnt[i] = cnt[i] - n / m
pos = [[] for i in range(m)]
for i in range(n):
	if len(pos[a[i] % m]) < cnt[a[i] % m]:
		pos[a[i] % m].append(i)
q = deque()
ans = 0
for i in range(m):
	if cnt[i] > 0:
		cnt[i] = 0
		for x in pos[i]:
			q.append(x)
	elif cnt[i] < 0:
		while cnt[i] < 0 and len(q) > 0:
			u = q.popleft()
			add = (i + m - a[u] % m) % m
			ans += add
			a[u] += add
			cnt[i] += 1
for i in range(m):
	if cnt[i] > 0:
		cnt[i] = 0
		for x in pos[i]:
			q.append(x)
	elif cnt[i] < 0:
		while cnt[i] < 0 and len(q) > 0:
			u = q.popleft()
			add = (i + m - a[u] % m) % m
			ans += add
			a[u] += add
			cnt[i] += 1
print(ans)
print(*a)


import collections
from functools import cmp_to_key
import math
import sys

def getIntList():
	return list(map(int, input().split()))
import bisect
try:
	import numpy
	dprint = print
	dprint('debug mode')
except ModuleNotFoundError:

	def dprint(*args, **kwargs):
		pass

def makePair(z):
	return [(z[i], z[i + 1]) for i in range(0, len(z), 2)]
(N, M) = getIntList()
za = getIntList()
target = N // M
zm = [-target for x in range(M)]
res = [[] for x in range(M)]
for x in za:
	zm[x % M] += 1
acc = []
total = 0
while True:
	flag = False
	for i in range(M):
		if zm[i] > 0:
			flag = True
			acc.append([i, zm[i]])
			zm[i] = 0
		elif zm[i] < 0:
			while zm[i] < 0 and len(acc) > 0:
				last = acc[-1]
				t = min(-zm[i], last[1])
				if i > last[0]:
					total += (i - last[0]) * t
					res[last[0]].append([i - last[0], t])
				else:
					total += (i - last[0] + M) * t
					res[last[0]].append([i - last[0] + M, t])
				zm[i] += t
				if t == last[1]:
					acc.pop()
				else:
					acc[-1][1] -= t
	if not flag:
		break
dprint(res)
print(total)
for i in range(N):
	t = za[i]
	remain = t % M
	move = res[remain]
	if len(move) > 0:
		t += move[-1][0]
		move[-1][1] -= 1
		if move[-1][1] == 0:
			move.pop()
	print(t, end=' ')


(n, m) = map(int, input().split())
d = n // m
a = list(map(int, input().split()))
b = [0] * m
for i in range(n):
	b[a[i] % m] += 1
x = [[] for _ in range(m)]
xx = []
ans = 0
for i in range(2 * m - 1, -1, -1):
	if b[i % m] <= d:
		xx += [i % m] * (d - b[i % m])
		b[i % m] = d
	else:
		y = b[i % m] - d
		for _ in range(min(y, len(xx))):
			b[i % m] -= 1
			v = xx.pop()
			x[i % m].append((v - i) % m)
			ans += (v - i) % m
for i in range(n):
	if x[a[i] % m]:
		a[i] += x[a[i] % m].pop()
print(ans)
print(*a)


def main():
	(n, m) = map(int, input().split())
	arr = [int(ai) for ai in input().split()]
	freq = [[] for i in range(m)]
	aux = []
	(count, c) = (0, n // m)
	for (i, ai) in enumerate(arr):
		freq[ai % m].append(i)
	for _ in range(2):
		for i in range(m):
			if len(freq[i]) > c:
				aux += freq[i][c:]
				freq[i] = freq[i][:c]
			while len(freq[i]) < c and len(aux):
				idx = aux.pop(-1)
				remainder = arr[idx] % m
				moves = i - remainder if i >= remainder else m - remainder + i
				count += moves
				arr[idx] += moves
				freq[i].append(idx)
	print('%d\n%s' % (count, ' '.join(map(str, arr))))
main()


import collections
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
md = n // m
c = [[] for _ in range(m)]
(mx, ind, moves) = (0,) * 3
movable = collections.deque()
change = []
for i in range(n):
	c[a[i] % m].append(i)
for i in range(m):
	req = md - len(c[i])
	if req <= 0:
		for j in range(-req):
			movable.append(i)
	else:
		while req > 0:
			if len(movable) == 0:
				change.append([i, req])
				break
			old = movable[0]
			add = i - old
			a[c[old][-1]] += add
			moves += add
			c[i].append(c[old][-1])
			del c[old][-1]
			movable.popleft()
			req -= 1
for obj in change:
	(i, req) = (obj[0], obj[1])
	while req > 0:
		old = movable[0]
		add = i + m - old
		a[c[old][-1]] += add
		moves += add
		c[i].append(c[old][-1])
		del c[old][-1]
		movable.popleft()
		req -= 1
ans = [0 for _ in range(n)]
for i in range(m):
	for j in range(md):
		ans[c[i][j]] = a[c[i][j]]
print(moves)
print(*ans)


from __future__ import print_function
from queue import Queue
import sys
import math
import os.path

def log(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)

def ni():
	return map(int, input().split())

def nio(offset):
	return map(lambda x: int(x) + offset, input().split())

def nia():
	return list(map(int, input().split()))

def toString(aList, sep=' '):
	return sep.join((str(x) for x in aList))

def toMapInvertIndex(aList):
	return {k: v for (v, k) in enumerate(aList)}
(n, m) = ni()
a = nia()
nm = n // m
mmap = [[] for _ in range(m)]
for i in range(n):
	xx = a[i] % m
	mmap[xx].append(i)
move = []
destination = []
for i in range(m):
	ddu = mmap[i]
	x = len(ddu)
	destination.extend([i] * (nm - x))
	move.extend(ddu[nm:x])
ssum = 0
lenmove = len(move)
sMoveId = sorted(range(lenmove), key=lambda k: a[move[k]] % m)
di = 0
for i in range(lenmove):
	moveId = sMoveId[i]
	s = a[move[moveId]] % m
	while destination[di] < s:
		destination.append(destination[di] + m)
		di += 1
	d = destination[di]
	di += 1
	ssum += d - s
	a[move[moveId]] += d - s
print(ssum)
print(toString(a))


import sys
input = sys.stdin.readline
out = sys.stdout

def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	query = n // m
	data = {i: 0 for i in range(n)}
	data_stat = {i: set() for i in range(m)}
	for i in range(n):
		data[i] = a[i]
		data_stat[a[i] % m].add(i)
	free = []
	answer = {i: 0 for i in range(n)}
	result = 0
	for i in range(2 * m):
		cur = i % m
		while len(data_stat[cur]) > query:
			elem = data_stat[cur].pop()
			free.append((elem, i))
		while len(data_stat[cur]) < query and free != []:
			(elem, mmod) = free.pop()
			data_stat[cur].add(elem)
			a[elem] += i - mmod
			result += i - mmod
	print(result)
	for j in a:
		out.write(str(j) + ' ')
main()


import bisect
(n, m) = map(int, input().split())
ls = list(map(int, input().split()))
mls = []
for i in range(0, n):
	mls.append((ls[i] % m, i))
mls.sort()
bk1 = set()
bk2 = set()
aim = n // m
cnt = 0
mis = []
for i in range(m):
	for j in range(aim):
		mis.append(i)
p1 = 0
p2 = 0
while p2 < n:
	if mls[p1][0] > mis[p2]:
		p2 += 1
	else:
		a = mis[p2] - mls[p1][0]
		ls[mls[p1][1]] += a
		cnt += a
		bk2.add(p2)
		p1 += 1
		p2 += 1
if p1 < n and p2 == n:
	p1 = n
	for i in range(p2):
		if i not in bk2:
			p1 -= 1
			a = m - mls[p1][0] + mis[i]
			ls[mls[p1][1]] += a
			cnt += a
print(cnt)
for i in ls:
	print(i, end=' ')


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
c = [(a[i] % m, i) for i in range(n)]
c.sort()
b = [i % m for i in range(n)]
b.sort()
ans = 0
plus = [0] * n
removed = []
while c:
	(value, index) = c.pop()
	modvalue = b.pop()
	if value <= modvalue:
		a[index] += modvalue - value
		ans += modvalue - value
		continue
	else:
		removed.append((value, index))
		b.append(modvalue)
		continue
while removed:
	(value, index) = removed.pop()
	modvalue = b.pop()
	assert value > modvalue
	a[index] += (modvalue - value) % m
	ans += (modvalue - value) % m
print(ans)
print(*a)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
d = {}
for i in range(m):
	d[i] = []
for i in range(len(a)):
	r = a[i] % m
	d[r].append((a[i], i))
step = 0
x = n // m
stack = []
for i in range(2 * m):
	i = i % m
	while len(d[i]) > x:
		stack.append(d[i].pop())
	while len(d[i]) < x and len(stack):
		z = list(stack.pop())
		delta = (i + m - z[0] % m) % m
		z[0] += delta
		d[i].append((z[0], z[1]))
		step += delta
arr = []
for i in d:
	for j in d[i]:
		arr.append(j)
arr.sort(key=lambda i: i[1])
print(step)
for i in arr:
	print(i[0], end=' ')
print()


import sys
from collections import Counter

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
(N, M) = MAP()
A = LIST()
modA = [a % M for a in A]
idxs = [[] for i in range(M)]
for (i, a) in enumerate(modA):
	idxs[a].append(i)
K = N // M
cnt = 0
tmp = []
for m in range(M * 2):
	while tmp and len(idxs[m % M]) < K:
		idxs[m % M].append(tmp.pop())
	while len(idxs[m % M]) > K:
		tmp.append(idxs[m % M].pop())
	cnt += len(tmp)
modans = [0] * N
for (m, li) in enumerate(idxs):
	for i in li:
		modans[i] = m
ans = [0] * N
for i in range(N):
	if modA[i] < modans[i]:
		ans[i] = A[i] + (modans[i] - modA[i])
	elif modA[i] > modans[i]:
		ans[i] = A[i] + (modans[i] + M - modA[i])
	else:
		ans[i] = A[i]
print(cnt)
print(*ans)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
k = int(n / m)
lis = [[] for i in range(m + 1)]
free = list()
for i in range(n):
	ele = a[i] % m
	lis[ele].append(i)
ans = 0
for i in range(2 * m):
	cur = i % m
	while len(lis[cur]) > k:
		ele = lis[cur].pop()
		free.append([ele, i])
	while len(lis[cur]) < k and free != []:
		(ele, mm) = free.pop()
		lis[cur].append(ele)
		a[ele] += i - mm
		ans += i - mm
print(ans)
for item in a:
	print(item, end=' ')


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
	(n, m) = map(int, input().split())
	b = list(map(int, input().split()))
	divs = n // m
	mods = [0] * m
	for i in b:
		mods[i % m] += 1
	a = list(mods)
	a += a
	small = 0
	ans = 0
	extra = []
	ops = [[] for __ in range(m)]
	for i in range(2 * m):
		nex = i % m
		if a[nex] == divs:
			continue
		if a[nex] > divs:
			while a[nex] != divs:
				extra += [i]
				a[nex] -= 1
			continue
		while extra and a[nex] < divs:
			ep = extra.pop()
			ans += i - ep
			ops[ep % m] += [i - ep]
			a[nex] += 1
	print(ans)
	for i in range(n):
		if ops[b[i] % m]:
			b[i] += ops[b[i] % m].pop()
	print(*b)


(n, m) = map(int, input().split())
nums = list(map(int, input().split()))
remainder = [0] * m
limit = n // m
moves = 0
for i in nums:
	remainder[i % m] += 1
for i in range(m):
	remainder[i] -= limit
deficit = set()
for i in range(m):
	if remainder[i] < 0:
		deficit.add(i)
spare = []
convert = {}
i = 0
while len(deficit) > 0:
	i = i % m
	if remainder[i] > 0:
		spare.append([i, remainder[i]])
		remainder[i] = 0
	elif remainder[i] < 0:
		if len(spare) > 0:
			while len(spare) > 0 and remainder[i] < 0:
				rem = min(spare[-1][1], abs(remainder[i]))
				if spare[-1][0] in convert.keys():
					convert[spare[-1][0]].append([(i - spare[-1][0]) % m, rem])
				else:
					convert[spare[-1][0]] = [[(i - spare[-1][0]) % m, rem]]
				spare[-1][1] -= rem
				remainder[i] += rem
				if spare[-1][1] == 0:
					spare.pop()
			if remainder[i] == 0:
				deficit.remove(i)
	i += 1
for i in range(n):
	rem = nums[i] % m
	if rem in convert.keys():
		moves += convert[rem][-1][0]
		nums[i] += convert[rem][-1][0]
		convert[rem][-1][1] -= 1
		if convert[rem][-1][1] == 0:
			convert[rem].pop()
		if len(convert[rem]) == 0:
			del convert[rem]
print(moves)
print(*nums)


import collections
(n, m) = [int(x) for x in input().split()]
L = [int(x) for x in input().split()]
J = [0] * m
D = []
for i in range(m):
	D.append([])
x = n // m
s = 0
for i in range(m):
	D[i] = []
for i in range(n):
	J[L[i] % m] += 1
	D[L[i] % m].append(i)
Free = collections.deque([])
F = 0
for i in range(2 * m - 1):
	j = i % m
	if J[j] > x:
		t = J[j] - x
		F += t
		for A in range(t):
			Free.append((j, D[j][A]))
		J[j] = x
	elif J[j] < x:
		while F > 0 and J[j] < x:
			F -= 1
			J[j] += 1
			(a, b) = Free.popleft()
			s += (j - a) % m
			L[b] += (j - a) % m
print(s)
for i in L:
	print(i, end=' ')


import collections

class Solution:

	def solve(self, n, m, arr):
		k = n // m
		free = []
		remToIndexDict = collections.defaultdict(list)
		for (index, elem) in enumerate(arr):
			remToIndexDict[elem % m].append(index)
		ans = 0
		for rem in range(2 * m):
			curr = rem % m
			while len(remToIndexDict[curr]) > k:
				index = remToIndexDict[curr].pop()
				free.append((index, rem))
			while len(remToIndexDict[curr]) < k and free:
				(index, mmod) = free.pop()
				remToIndexDict[curr].append(index)
				arr[index] += rem - mmod
				ans += rem - mmod
		return (ans, arr)
sol = Solution()
[n, m] = list(map(int, input().strip().split()))
arr = list(map(int, input().strip().split()))
(ans, arr) = sol.solve(n, m, arr)
print(ans)
print(' '.join(map(str, arr)))


R = lambda : map(int, input().split())
(n, m) = R()
L = list(R())
d = [[] for i in range(m)]
for (j, i) in enumerate(L):
	d[i % m].append(j)
k = n // m
a = []
res = 0
j = 0
for i in range(m):
	while len(d[i]) > k:
		while j < i or len(d[j % m]) >= k:
			j += 1
		ind = d[i].pop()
		L[ind] += (j - i) % m
		res += (j - i) % m
		d[j % m].append(ind)
print(res)
print(*L)


(n, m) = map(int, input().split())
w = list(map(int, input().split()))
(r, q) = (sum(w), n // m)
t = [[] for _ in range(m)]
for i in range(n):
	t[w[i] % m].append(i)
j = -m
for (i, l) in enumerate(t):
	if len(l) > q:
		if j <= i - m:
			j = i - m + 1
		while len(l) > q:
			while len(t[j]) >= q:
				j += 1
			w[l.pop()] += j + m - i
			t[j].append(0)
print(sum(w) - r)
print(' '.join(map(str, w)))


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n
avl = AvlTree()

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, m) = map(int, input().split())
k = m
l = list(map(int, input().split()))
ind = defaultdict(int)
excess = defaultdict(int)
defi = defaultdict(int)
s = set([i for i in range(m)])
for i in range(n):
	ind[l[i] % m] += 1
	if l[i] % m in s:
		s.remove(l[i] % m)
for i in ind:
	if ind[i] > n // m:
		excess[i] = ind[i] - n // m
	else:
		defi[i] = n // m - ind[i]
for i in s:
	defi[i] = n // m
t = m
defiu = defaultdict(list)
for i in sorted(defi, reverse=True):
	t = min(t, i)
	while defi[i] > 0:
		if excess[t % k] == 0:
			t -= 1
			continue
		defiu[t % k].append((i, min(excess[t % k], defi[i])))
		we = min(excess[t % k], defi[i])
		defi[i] -= we
		excess[t % k] -= we
		t -= 1
	if excess[(t + 1) % k] > 0:
		t += 1
ans = 0
defiu1 = defaultdict(list)
for j in defiu:
	for k in defiu[j]:
		for p in range(k[1]):
			defiu1[j].append(k[0])
for i in range(n):
	t = l[i] % m
	if len(defiu1[t]) != 0:
		su = defiu1[t][-1] - t
		if su < 0:
			su += m
		l[i] += su
		ans += su
		defiu1[t].pop()
print(ans)
print(*l, sep=' ')


import io
import os
from collections import defaultdict
from sys import stdin, stdout
input = stdin.readline

def main():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	rem = [[] for _ in range(m)]
	for (i, val) in enumerate(a):
		rem[val % m].append(i)
	need = n // m
	ans = 0
	pos = 0
	for i in range(m):
		while len(rem[i]) > need:
			while pos <= i or len(rem[pos % m]) >= need:
				pos += 1
			change = rem[i].pop()
			rem[pos % m].append(change)
			a[change] += (pos - i) % m
			ans += (pos - i) % m
	stdout.write(str(ans) + '\n')
	stdout.write(' '.join((str(x) for x in a)))
main()


from collections import deque
(n, m) = map(int, input().split())
arr = [int(z) for z in input().split()]
mods = [0 for i in range(m)]
placement = [[] for i in range(m)]
for i in range(n):
	mods[arr[i] % m] += 1
	placement[arr[i] % m].append(i)
cnt = 0
queue = deque()
target = n // m
for i in range(2 * m):
	mod = i % m
	if mods[mod] > n // m:
		for c in range(mods[mod] - target):
			queue.append([i, placement[mod][c]])
		mods[mod] = target
	elif mods[mod] < target:
		while len(queue) > 0 and mods[mod] < target:
			(elem, indice) = queue.popleft()
			mods[mod] += 1
			cnt += (mod - elem) % m
			arr[indice] += (mod - elem) % m
print(cnt)
print(' '.join([str(i) for i in arr]))


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
t = n // m
remain = [[] for i in range(m)]
for i in range(n):
	x = a[i] % m
	remain[x].append(i)
ans = 0
f = []
for i in range(2 * m):
	cur = i % m
	while len(remain[cur]) > t:
		elm = remain[cur].pop()
		f.append([elm, i])
	while len(remain[cur]) < t and len(f) != 0:
		(elm, j) = f.pop()
		remain[cur].append(elm)
		a[elm] += abs(i - j)
		ans += abs(i - j)
print(ans)
print(*a)


from collections import defaultdict
(n, m) = map(int, input().split())
k = n // m
l = list(map(int, input().split()))
s = sum(l)
occ = defaultdict(list)
for (i, a) in enumerate(l):
	rem = a % m
	occ[rem].append(i)
j = 0
for i in range(m):
	while len(occ[i]) > k:
		while j < i or len(occ[j % m]) >= k:
			j += 1
		key = occ[i].pop()
		l[key] += (j - i) % m
		occ[j % m].append(k)
print(sum(l) - s)
print(*l)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(200001)]
pp = [0] * 200001

def SieveOfEratosthenes(n=200000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
t = n // m
remain = [[] for i in range(m)]
for i in range(n):
	x = a[i] % m
	remain[x].append(i)
ans = 0
f = []
for i in range(2 * m):
	cur = i % m
	while len(remain[cur]) > t:
		elm = remain[cur].pop()
		f.append([elm, i])
	while len(remain[cur]) < t and len(f) != 0:
		(elm, j) = f.pop()
		remain[cur].append(elm)
		a[elm] += abs(i - j)
		ans += abs(i - j)
print(ans)
print(*a)


import sys
from collections import Counter

def i_ints():
	return list(map(int, sys.stdin.readline().split()))
(n, m) = i_ints()
a = list(i_ints())
r = [x % m for x in a]
c = Counter(r)
c = [c[i] for i in range(m)]
rem2ind = [[] for i in range(m)]
for (i, x) in enumerate(r):
	rem2ind[x].append(i)
R = n // m
for (i, inds) in enumerate(rem2ind):
	if len(inds) > R:
		next_big = i
		break
else:
	next_big = m
next_small = next_big + 1
moves = 0
while next_big < m:
	next_small = max(next_small, next_big + 1)
	num = max(c[next_big] - R, 0)
	while num > 0:
		num2 = max(R - c[next_small % m], 0)
		delta = min(num, num2)
		num -= delta
		c[next_small % m] += delta
		step = next_small - next_big
		for i in rem2ind[next_big][num:num + delta]:
			a[i] += step
		moves += delta * step
		if c[next_small % m] >= R:
			next_small += 1
	next_big += 1
print(moves)
print(' '.join(map(str, a)))


import sys
from collections import defaultdict, deque
input = sys.stdin.readline
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
dd = defaultdict(list)
for (i, x) in enumerate(a):
	dd[x % m].append(i)
(lack, surplus) = (deque(), deque())
k = n // m
ans = 0
for mod in range(m * 2):
	while len(dd[mod % m]) < k and surplus:
		(mod2, i) = surplus.popleft()
		ans += mod - mod2
		dd[mod % m].append(i)
		a[i] += mod - mod2
	while len(dd[mod % m]) > k:
		surplus.append((mod, dd[mod % m].pop()))
print(ans)
print(*a)


(n, m) = map(int, input().split())
k = n // m
a = list(map(int, input().split()))
cc = [[] for i in range(m)]
for i in range(n):
	cc[a[i] % m].append(i)
f = []
s = 0
for t in range(2):
	for i in range(m):
		while len(cc[i]) > k:
			f.append(cc[i].pop())
		while len(cc[i]) < k and len(f) > 0:
			p = f.pop()
			cc[i].append(p)
			d = (i - a[p]) % m
			a[p] += d
			s += d
print(s)
print(' '.join(map(str, a)))


from sys import stdin
input = stdin.buffer.readline
(n, m) = map(int, input().split())
arr = [int(x) for x in input().split()]
dp = [[] for i in range(m)]
for i in range(n):
	dp[arr[i] % m].append(i)
res = 0
k = n // m
ans = arr.copy()
s = []
for t in range(2):
	for i in range(m):
		if len(dp[i]) < k:
			while len(s) != 0 and len(dp[i]) < k:
				x = s.pop()
				y = arr[x] % m
				if i > y:
					ans[x] = ans[x] + (i - y)
					res = res + (i - y)
				else:
					ans[x] = ans[x] + (m - 1 - y) + (i + 1)
					res = res + (m - 1 - y) + (i + 1)
				dp[i].append('xxx')
		if len(dp[i]) > k:
			while len(dp[i]) > k:
				s.append(dp[i].pop())
print(res)
print(*ans)


l = input().split()
n = int(l[0])
m = int(l[1])
arr = [[] for i in range(m)]
l = input().split()
li = [int(i) for i in l]
for i in range(n):
	arr[li[i] % m].append(i)
req = n // m
count = 0
stack = []
for i in range(2 * m):
	curr = len(arr[i % m])
	if curr < req:
		z = req - curr
		did = 0
		while stack != [] and did < z:
			wtf = i % m - stack[-1][0]
			if wtf < 0:
				wtf += m
			count += wtf
			li[stack[-1][1]] += wtf
			arr[i % m].append(stack[-1][1])
			stack.pop(-1)
			did += 1
	else:
		y = i % m
		for j in range(curr - req):
			stack.append((y, arr[y][-1]))
			arr[y].pop(-1)
print(count)
for i in li:
	print(i, end=' ')


(n, m) = map(int, input().split())
Ccount = n // m
moves = 0
freeSet = []
arr = list(map(int, input().split()))
C = [[] for i in range(m)]
for i in range(n):
	C[arr[i] % m].append(i)
for j in range(2 * m):
	Cindex = j % m
	while len(C[Cindex]) > Ccount:
		currelem = C[Cindex].pop(-1)
		freeSet.append((currelem, j))
	while len(C[Cindex]) < Ccount and freeSet:
		getFree = freeSet.pop(-1)
		C[Cindex].append(getFree[0])
		arr[getFree[0]] += j - getFree[1]
		moves += j - getFree[1]
print(moves)
print(*arr)


(n, m) = map(int, input().split())
a = list(map(int, input().split()))
f = [[] for i in range(m)]
l = [0 for i in range(m)]
for i in range(n):
	f[a[i] % m].append(i)
	l[a[i] % m] += 1
k = n // m
j = 0
tot = 0
for i in range(m):
	while l[i] > k:
		while l[j] >= k:
			j = (j + 1) % m
		tot += (j + m - i) % m
		l[j] += 1
		a[f[i][-1]] += (j + m - i) % m
		f[i].pop()
		l[i] -= 1
	if i == j:
		j += 1
print(tot)
for i in a:
	print(i, end=' ')


from sys import stdin

def solve():
	(n, m) = map(int, stdin.readline().split())
	a = list(map(int, stdin.readline().split()))
	ans = 0
	b = sorted(map(list, zip(map(lambda x: x % m, a), range(n))))
	j = 0
	need = n // m
	for i in range(m):
		e = j
		while e < len(b) and b[e][0] == i:
			e += 1
		if e - j >= need:
			for t in range(j + need, e):
				b.append(b[t])
			j = e
		else:
			for _ in range(need - (e - j)):
				w = b.pop()
				ans += (i - w[0]) % m
				a[w[1]] += (i - w[0]) % m
			j = e
	print(ans)
	print(*a)
solve()


import collections
(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
d = collections.defaultdict(set)
kr = [-n // k] * k
for i in range(n):
	ri = a[i] % k
	kr[ri] += 1
	d[ri].add(i)
krs = [0] * k
krs[0] = kr[0]
for i in range(1, k):
	krs[i] = krs[i - 1] + kr[i]
org = (krs.index(min(krs)) + 1) % k
cnt = sum((abs(i) for i in kr)) // 2
aa = [0] * cnt
bb = [0] * cnt
ai = bi = 0
for ii in range(org, org + k):
	i = ii % k
	if kr[i] > 0:
		for _ in range(kr[i]):
			aa[ai] = i
			ai += 1
	elif kr[i] < 0:
		for _ in range(-kr[i]):
			bb[bi] = i
			bi += 1
ans = 0
for (ai, bi) in zip(aa, bb):
	diff = (bi - org) % k - (ai - org) % k
	ans += diff
	i = d[ai].pop()
	a[i] += diff
print(ans)
print(' '.join(map(str, a)))


import sys
from collections import Counter, defaultdict
(n, m) = map(int, sys.stdin.readline().split(' '))
a = list(map(int, sys.stdin.readline().split(' ')))

def do():
	k = n // m
	count = Counter((x % m for x in a))
	delta = [0] * m
	for i in range(m):
		delta[i] = count[i] - k
	dd = defaultdict(list)
	for (i, x) in enumerate(a):
		dd[x % m].append(i)
	res = list(a)
	rest = set()
	for i in range(m):
		dl = delta[i]
		if dl > 0:
			rest |= set(dd[i][:dl])
			delta[i] = 0
		elif dl < 0:
			for _ in range(dl, 0):
				if not rest:
					break
				idx = rest.pop()
				res[idx] += i - res[idx] % m
				delta[i] += 1
	for i in range(m):
		if not rest:
			break
		dl = delta[i]
		for _ in range(dl, 0):
			idx = rest.pop()
			res[idx] += m + i - res[idx] % m
	yield str(sum((x - y for (x, y) in zip(res, a))))
	yield str(' '.join(map(str, res)))
print('\n'.join(do()))


(n, m) = map(int, input().split())
aa = list(map(int, input().split()))
(res, q) = (sum(aa), n // m)
acc = [[] for _ in range(m)]
for i in range(n):
	acc[aa[i] % m].append(i)
j = -m
for (i, l) in enumerate(acc):
	if len(l) > q:
		if j <= i - m:
			j = i - m + 1
		while len(l) > q:
			while len(acc[j]) >= q:
				j += 1
			aa[l.pop()] += j + m - i
			acc[j].append(0)
print(sum(aa) - res)
print(' '.join(map(str, aa)))


from sys import stdin
from math import *
from collections import deque
line = stdin.readline().rstrip().split()
n = int(line[0])
m = int(line[1])
numbers = list(map(int, stdin.readline().rstrip().split()))
numRems = []
for i in range(m):
	numRems.append([])
cantRem = [0] * m
for i in range(len(numbers)):
	num = numbers[i]
	rem = num % m
	cantRem[rem] += 1
	numRems[rem].append(i)
cantNeeded = int(n / m)
q = deque([])
moves = 0
for i in range(2 * m):
	j = i % m
	if i < m and cantRem[j] > cantNeeded:
		for k in range(cantRem[j] - cantNeeded):
			q.append((numRems[j][k], j))
	elif cantRem[j] < cantNeeded:
		while len(q) > 0 and cantRem[j] < cantNeeded:
			pair = q.pop()
			diff = (j - pair[1]) % m
			moves += diff
			numbers[pair[0]] += diff
			cantRem[j] += 1
if len(q) != 0:
	raise 0
print(moves)
for i in numbers:
	print(i, end=' ')


(n, m) = list(map(int, input().split()))
aa = list(map(int, input().split()))
(res, cnt) = (sum(aa), [-n // m] * m)
acc = [[] for _ in range(m)]
for (i, a) in enumerate(aa):
	r = a % m
	cnt[r] += 1
	acc[r].append(i)
(icnt, a) = ([], 0)
for c in cnt:
	a += c
	icnt.append(a)
start = (min(range(m), key=icnt.__getitem__) + 1) % m
(excess, scarce) = ([], [])
for r in (range(start, m), range(start)):
	for i in r:
		if cnt[i] > 0:
			for _ in range(cnt[i]):
				excess.append(i)
		elif cnt[i] < 0:
			for _ in range(-cnt[i]):
				scarce.append(i)
for (e, s) in zip(excess, scarce):
	aa[acc[e].pop()] += (s - e) % m
print(sum(aa) - res)
print(' '.join(map(str, aa)))


from collections import deque
(n, m) = map(int, input().split())
a = list(map(int, input().split()))
n_m = n // m
c = m * [0]
indices = [deque() for r in range(m)]
for (i, ai) in enumerate(a):
	r = ai % m
	c[r] += 1
	indices[r].append(i)
n_moves = 0
queue = deque()
for i in range(0, 2 * m):
	r = i % m
	while c[r] > n_m:
		queue.append((i, indices[r].pop()))
		c[r] -= 1
	while c[r] < n_m and queue:
		(j, index) = queue.popleft()
		indices[r].append(index)
		c[r] += 1
		a[index] += i - j
		n_moves += i - j
print(n_moves)
print(*a)