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

#define BUFF_SIZE 160
#define COL_BUFF_SIZE 50

double pow(double base, double power)
{
	int i;
	for(i = 1; i < power; i++) {
		base *= base;
	}

	return power == 0 ? 1 : base;
}

int read_string(char *string, int size)
{
	int len = 0;
	char c;
	while((c = getc(stdin)) != '\n' && size > len) {
		string[len] = c;
		len++;
	}

	string[len] = '\0';
	return len;
}

void reverce(char *string, int len)
{
	char tmp;
	int i;
	for(i = 0; i < len/2; i++) {
		tmp = string[i];
		string[i] = string[len-i-1];
		string[len-i-1] = tmp;
	}
}

void convertAtoB(int row, int col)
{
	char c_col[COL_BUFF_SIZE];
	int mod, len = 0;
	while(col) {
		mod = col % 26;
		c_col[len] = 'A' + mod - 1;
		len++;

		if(col > 26) {
			col = (col - mod) / 26;
		} else {
			break;
		}
	}

	reverce(c_col, len);
	printf("%s%d\n", c_col, row);
}

void convertBtoA(int row, char *col)
{
	int i_col = 0;
	int i, len;
	for(i = 0, len = strlen(col); i < len; i++) {
		printf("%d %lf", i, pow(26, i));
		i_col += ((col[len-i-1] % 'A') + 1) * (pow(26, i));
	}

	printf("R%dC%d\n", row, i_col);
}

int main(void)
{
	int row, i_col, t;
	char buffer[BUFF_SIZE];
	char c_col[COL_BUFF_SIZE];

	scanf("%d\n", &t);
	while(t) {
		read_string(buffer, BUFF_SIZE);
		if(sscanf(buffer, "R%dC%d", &row, &i_col) == 2) {
			convertAtoB(row, i_col);
		} else if(sscanf(buffer, "%49[^0-9]%d", c_col, &row)) {
			convertBtoA(row, c_col);
		}

		t--;
	}

	// int c = 4;
	// while(c) {
	// 	c--;
	// }

	return 0;
}


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

#define BUFF_SIZE 160
#define COL_BUFF_SIZE 50

double pow(double base, double power)
{
	int i;
	for(i = 1; i < power; i++) {
		base *= base;
	}

	return power == 0 ? 1 : base;
}

int read_string(char *string, int size)
{
	int len = 0;
	char c;
	while((c = getc(stdin)) != '\n' && size > len) {
		string[len] = c;
		len++;
	}

	string[len] = '\0';
	return len;
}

void reverce(char *string, int len)
{
	char tmp;
	int i;
	for(i = 0; i < len/2; i++) {
		tmp = string[i];
		string[i] = string[len-i-1];
		string[len-i-1] = tmp;
	}
}

void convertAtoB(int row, int col)
{
	char c_col[COL_BUFF_SIZE];
	int mod, len = 0;
	while(col) {
		mod = col % 26;
		mod = !mod ? 26 : mod;
		c_col[len] = 'A' + mod - 1;
		len++;

		if(col > 26) {
			col = (col - mod) / 26;
		} else {
			break;
		}
	}

	reverce(c_col, len);
	printf("%s%d\n", c_col, row);
}

void convertBtoA(int row, char *col)
{
	int i_col = 0;
	int i, len;
	for(i = 0, len = strlen(col); i < len; i++) {
		i_col += ((col[len-i-1] % 'A') + 1) * (pow(26, i));
	}

	printf("R%dC%d\n", row, i_col);
}

int main(void)
{
	int row, i_col, t;
	char buffer[BUFF_SIZE];
	char c_col[COL_BUFF_SIZE];

	scanf("%d\n", &t);
	while(t) {
		read_string(buffer, BUFF_SIZE);
		if(sscanf(buffer, "R%dC%d", &row, &i_col) == 2) {
			convertAtoB(row, i_col);
		} else if(sscanf(buffer, "%49[^0-9]%d", c_col, &row)) {
			convertBtoA(row, c_col);
		}

		t--;
	}

	// int c = 4;
	// while(c) {
	// 	c--;
	// }

	return 0;
}


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

#define BUFF_SIZE 160
#define COL_BUFF_SIZE 50

double pow(double base, double power)
{
	int i;
	for(i = 1; i < power; i++) {
		base *= base;
	}

	return power == 0 ? 1 : base;
}

int read_string(char *string, int size)
{
	int len = 0;
	char c;
	while((c = getc(stdin)) != '\n' && size > len) {
		string[len] = c;
		len++;
	}

	string[len] = '\0';
	return len;
}

void reverce(char *string, int len)
{
	char tmp;
	int i;
	for(i = 0; i < len/2; i++) {
		tmp = string[i];
		string[i] = string[len-i-1];
		string[len-i-1] = tmp;
	}
}

void convertAtoB(int row, int col)
{
	char c_col[COL_BUFF_SIZE];
	int mod, len = 0;
	while(col) {
		mod = col % 26;
		c_col[len] = 'A' + mod - 1;
		len++;

		if(col > 26) {
			col = (col - mod) / 26;
		} else {
			break;
		}
	}

	reverce(c_col, len);
	printf("%s%d\n", c_col, row);
}

void convertBtoA(int row, char *col)
{
	int i_col = 0;
	int i, len;
	for(i = 0, len = strlen(col); i < len; i++) {
		i_col += ((col[len-i-1] % 'A') + 1) * (pow(26, i));
	}

	printf("R%dC%d\n", row, i_col);
}

int main(void)
{
	int row, i_col, t;
	char buffer[BUFF_SIZE];
	char c_col[COL_BUFF_SIZE];

	scanf("%d\n", &t);
	while(t) {
		read_string(buffer, BUFF_SIZE);
		if(sscanf(buffer, "R%dC%d", &row, &i_col) == 2) {
			convertAtoB(row, i_col);
		} else if(sscanf(buffer, "%49[^0-9]%d", c_col, &row)) {
			convertBtoA(row, c_col);
		}

		t--;
	}

	// int c = 4;
	// while(c) {
	// 	c--;
	// }

	return 0;
}


#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
    int n;
    //n is the number of how many strings are we taking as input.
    scanf("%d",&n);
    char input[n][14],output[n][14],tmp[7];
    int i,j,k,l,m,ara[n],t1=0,t2=0;
    double g1,g2;
    for(i=0;i<n;i++)
        scanf("%s",&input[i]);
    for(i=0;i<n;i++){
            //this loop is to define input[i] is in which format.if input[i] is in AB12 format ara[i] will be 1,else if input[i] is in R12C12 format ara[i] will be 0.
            j=1;
            ara[i]=0;
        if(input[i][j]>='0'&&input[i][j]<='9'){
            for(;input[i][j]!='\0';j++){
                if(input[i][j]>='0'&&input[i][j]<='9'){

                }
                else{

                    ara[i]=1;
                    break;
                }
            }
        }
        else{

            continue;
        }
    }

    for(i=0;i<n;i++){
        //this loop is to convert from one format to another.
        if(ara[i]==1){
            //if input[i] is in R12C12 format this process will run.
            l=strlen(input[i]);
            for(l=l-1,g1=0.0,g2=0.0;input[i][l]>='0'&&input[i][l]<='9';l--,g1++){
                //this loop is to count the number of columns.as its given in character,this loop will convert them into integer.
                g2+=(input[i][l]-'0')*pow(10.0,g1);
            }
            t1=g2;

            for(k=0;;k++){
                //this loop converts the numbers of columns into AB format and stores them in output.
                if(t1%26==0){
                    tmp[k]='Z';
                    t1=t1/26;
                }
                else{
                    tmp[k]='A'+(t1%26)-1;
                    t1=t1/26;
                }
                if(t1==0){
                    for(j=0;k>=0;k--,j++){
                        output[i][j]=tmp[k];
                    }
                    break;
                }
            }
            l--;
            //next two loops directly stores the number of rows from input[i] to output[i].
            for(k=0;l>0;l--,k++){
                tmp[k]=input[i][l];

            }
            k--;
            for(;k>=0;k--,j++){
                output[i][j]=tmp[k];
            }

            output[i][j]='\0';

        }
        else if(ara[i]==0){
            //if the input is inAB12 format this loop will work.

            l=strlen(input[i])-1;
            //next two for loops will directly store the number of rows from input[i] to output[i].
            for(k=0;input[i][l]>='0'&&input[i][l]<='9';k++,l--){
                tmp[k]=input[i][l];
            }
            k--;
            output[i][0]='R';
            for(j=1;k>=0;k--,j++){
                output[i][j]=tmp[k];
            }
            output[i][j]='C';
            j++;
            for(g2=0,g1=0;l>=0;l--,g2++){
                    //this loop is to convert the numbers of column from AB format to integer.
                if(input[i][j]=='Z'){
                    g1+=0;
                }
                else{
                    g1=g1+((input[i][l]-'A'+1)*pow(26.0,g2));
                }
            }
            t1=g1;
            for(k=0;;k++){
                //this loop is to store the number of columns in output[i] string.
                tmp[k]='0'+(t1%10);
                t1=t1/10;
                if(t1==0){
                    for(;k>=0;k--,j++){
                        output[i][j]=tmp[k];
                    }
                    break;
                }

            }
            output[i][j]='\0';
        }
    }
    //this loop is to print all outputs.
    for(i=0;i<n;i++)
        printf("%s\n",output[i]);
    return 0;

}


#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
    int n;
    //n is the number of how many strings are we taking as input.
    scanf("%d",&n);
    char input[n][14],output[n][14],tmp[7];
    int i,j,k,l,m,ara[n],t1=0,t2=0;
    double g1,g2;
    for(i=0;i<n;i++)
        scanf("%s",&input[i]);
    for(i=0;i<n;i++){
            //this loop is to define input[i] is in which format.if input[i] is in AB12 format ara[i] will be 1,else if input[i] is in R12C12 format ara[i] will be 0.
            j=1;
            ara[i]=0;
        if(input[i][j]>='0'&&input[i][j]<='9'){
            for(;input[i][j]!='\0';j++){
                if(input[i][j]>='0'&&input[i][j]<='9'){

                }
                else{

                    ara[i]=1;
                    break;
                }
            }
        }
        else{

            continue;
        }
    }

    for(i=0;i<n;i++){
        //this loop is to convert from one format to another.
        if(ara[i]==1){
            //if input[i] is in R12C12 format this process will run.
            l=strlen(input[i]);
            for(l=l-1,g1=0.0,g2=0.0;input[i][l]>='0'&&input[i][l]<='9';l--,g1++){
                //this loop is to count the number of columns.as its given in character,this loop will convert them into integer.
                g2+=(input[i][l]-'0')*pow(10.0,g1);
            }
            t1=round(g2);

            for(k=0;;k++){
                //this loop converts the numbers of columns into AB format and stores them in output.

                tmp[k]='A'+(t1%26)-1;
                t1=t1/26;
                if(t1==0){
                    for(j=0;k>=0;k--,j++){
                        output[i][j]=tmp[k];
                    }
                    break;
                }
            }
            l--;
            //next two loops directly stores the number of rows from input[i] to output[i].
            for(k=0;l>0;l--,k++){
                tmp[k]=input[i][l];

            }
            k--;
            for(;k>=0;k--,j++){
                output[i][j]=tmp[k];
            }

            output[i][j]='\0';

        }
        else if(ara[i]==0){
            //if the input is inAB12 format this loop will work.

            l=strlen(input[i])-1;
            //next two for loops will directly store the number of rows from input[i] to output[i].
            for(k=0;input[i][l]>='0'&&input[i][l]<='9';k++,l--){
                tmp[k]=input[i][l];
            }
            k--;
            output[i][0]='R';
            for(j=1;k>=0;k--,j++){
                output[i][j]=tmp[k];
            }
            output[i][j]='C';
            j++;
            for(g2=0,g1=0;l>=0;l--,g2++){
                //this loop is to convert the numbers of column from AB format to integer.
                g1=g1+((input[i][l]-'A'+1)*pow(26.0,g2));

            }
            t1=round(g1);
            for(k=0;;k++){
                //this loop is to store the number of columns in output[i] string.
                tmp[k]='0'+(t1%10);
                t1=t1/10;
                if(t1==0){
                    for(;k>=0;k--,j++){
                        output[i][j]=tmp[k];
                    }
                    break;
                }

            }
            output[i][j]='\0';
        }
    }
    //this loop is to print all outputs.
    for(i=0;i<n;i++)
        printf("%s\n",output[i]);
    return 0;

}


#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
    int n;
    //n is the number of how many strings are we taking as input.
    scanf("%d",&n);
    char input[n][14],output[n][14],tmp[7];
    int i,j,k,l,m,ara[n],t1=0,t2=0;
    double g1,g2;
    for(i=0;i<n;i++)
        scanf("%s",&input[i]);
    for(i=0;i<n;i++){
            //this loop is to define input[i] is in which format.if input[i] is in AB12 format ara[i] will be 1,else if input[i] is in R12C12 format ara[i] will be 0.
            j=1;
            ara[i]=0;
        if(input[i][j]>='0'&&input[i][j]<='9'){
            for(;input[i][j]!='\0';j++){
                if(input[i][j]>='0'&&input[i][j]<='9'){

                }
                else{

                    ara[i]=1;
                    break;
                }
            }
        }
        else{

            continue;
        }
    }

    for(i=0;i<n;i++){
        //this loop is to convert from one format to another.
        if(ara[i]==1){
            //if input[i] is in R12C12 format this process will run.
            l=strlen(input[i]);
            for(l=l-1,g1=0.0,g2=0.0;input[i][l]>='0'&&input[i][l]<='9';l--,g1++){
                //this loop is to count the number of columns.as its given in character,this loop will convert them into integer.
                g2+=(input[i][l]-'0')*pow(10.0,g1);
            }
            t1=round(g2);

            for(k=0;;k++){
                //this loop converts the numbers of columns into AB format and stores them in output.
                if(t1%26==0){
                    tmp[k]='Z';
                    t1=t1/26;
                }
                else{
                    tmp[k]='A'+(t1%26)-1;
                    t1=t1/26;
                }
                if(t1==0){
                    for(j=0;k>=0;k--,j++){
                        output[i][j]=tmp[k];
                    }
                    break;
                }
            }
            l--;
            //next two loops directly stores the number of rows from input[i] to output[i].
            for(k=0;l>0;l--,k++){
                tmp[k]=input[i][l];

            }
            k--;
            for(;k>=0;k--,j++){
                output[i][j]=tmp[k];
            }

            output[i][j]='\0';

        }
        else if(ara[i]==0){
            //if the input is inAB12 format this loop will work.

            l=strlen(input[i])-1;
            //next two for loops will directly store the number of rows from input[i] to output[i].
            for(k=0;input[i][l]>='0'&&input[i][l]<='9';k++,l--){
                tmp[k]=input[i][l];
            }
            k--;
            output[i][0]='R';
            for(j=1;k>=0;k--,j++){
                output[i][j]=tmp[k];
            }
            output[i][j]='C';
            j++;
            for(g2=0,g1=0;l>=0;l--,g2++){
                    //this loop is to convert the numbers of column from AB format to integer.
                if(input[i][j]=='Z'){
                    g1+=0;
                }
                else{
                    g1=g1+((input[i][l]-'A'+1)*pow(26.0,g2));
                }
            }
            t1=round(g1);
            for(k=0;;k++){
                //this loop is to store the number of columns in output[i] string.
                tmp[k]='0'+(t1%10);
                t1=t1/10;
                if(t1==0){
                    for(;k>=0;k--,j++){
                        output[i][j]=tmp[k];
                    }
                    break;
                }

            }
            output[i][j]='\0';
        }
    }
    //this loop is to print all outputs.
    for(i=0;i<n;i++)
        printf("%s\n",output[i]);
    return 0;

}


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

for r_src in range(m):
    over = c[r_src] - n_m
    step = 0

    while over > 0:
        step += 1
        r_dst = (r_src + step) % m
        under = n_m - c[r_dst]

        for i in range(min(over, under)):
            index = indices[r_src].pop()
            indices[r_dst].append(index)
            c[r_src] -= 1
            c[r_dst] += 1
            a[index] += step
            n_moves += step
            over -= 1

print(n_moves)
print(*a)


import itertools
import collections

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

nm = n // m
c = m * [0]
indices = [collections.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
count = 0

for r in itertools.cycle(range(m)):
    if c[r] <= nm:
        count += 1

        if count == m:
            break
        else:
            continue
    else:
        count = 0

    r_next = (r + 1) % m
    excess = c[r] - nm

    c[r_next] += excess
    c[r] = nm

    for j in range(excess):
        i = indices[r].pop()
        a[i] += 1
        indices[r_next].append(i)

    n_moves += excess

print(n_moves)
print(*a)


from collections import deque

n, m = 200000, 200000  # map(int, input().split())
a = 2 * list(range(100000, 200000))  # 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)


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(m-1,-2,-1):
  if b[i%m]<=d:
    xx+=[i%m]*(d-b[i%m])
  else:
    y=b[i%m]-d
    for _ in range(y):
      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)


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)


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(m-1,-2,-1):
  if b[i%m]<=d:
    xx+=[i%m]*(d-b[i%m])
  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)


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
print(tot)
for i in a:
    print(i,end=' ')


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] = l[i] - 1
print(tot)
for i in a:
    print(i,end=' ')


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 = None
tot = 0
for i in range(m):
    while l[i] > k:
        if j == None:
            j = i
        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
print(tot)
for i in a:
    print(i,end=' ')


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=' ')


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 = [0] * m
    for val in a:
        rem[val % m] += 1
    need = n // m

    ans = 0
    for i in range(n):
        if rem[a[i] % m] > need:
            orig = a[i] % m
            while rem[a[i] % m] > need:
                a[i] += 1
            rem[orig] -= 1
            rem[a[i] % m] += 1
            ans += 1

    stdout.write(str(ans)+"\n")
    stdout.write(' '.join(str(x) for x in a))

if __name__ == '__main__':
    main()


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 = defaultdict(int)
    for val in a:
        rem[val % m] += 1
    need = n // m

    ans = 0
    for i in range(n):
        if rem[a[i] % m] > need:
            orig = a[i] % m
            while rem[a[i] % m] >= need:
                a[i] += 1
                ans += 1
            rem[orig] -= 1
            rem[a[i] % m] += 1

    stdout.write(str(ans)+"\n")
    stdout.write(' '.join(str(x) for x in a))

if __name__ == '__main__':
    main()


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))

if __name__ == '__main__':
    main()


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

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    rem = [0] * m
    for val in a:
        rem[val % m] += 1
    need = n // m

    ans = 0
    for i in range(n):
        if rem[a[i] % m] > need:
            orig = a[i] % m
            while rem[a[i] % m] > need:
                a[i] += 1
            rem[orig] -= 1
            rem[a[i] % m] += 1
            ans += 1

    print(ans)
    print(*a)

if __name__ == '__main__':
    main()


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]) >= need:
                pos += 1
            change = rem[i].pop()
            rem[pos].append(change)
            a[change] += (pos-i)
            ans += (pos-i)

    stdout.write(str(ans)+"\n")
    stdout.write(' '.join(str(x) for x in a))

if __name__ == '__main__':
    main()


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 = [0] * m
    for val in a:
        rem[val % m] += 1
    need = n // m

    ans = 0
    for i in range(n):
        if rem[a[i] % m] > need:
            orig = a[i] % m
            while rem[a[i] % m] >= need:
                a[i] += 1
                ans += 1
            rem[orig] -= 1
            rem[a[i] % m] += 1

    stdout.write(str(ans)+"\n")
    stdout.write(' '.join(str(x) for x in a))

if __name__ == '__main__':
    main()


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)


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])==n//m:
        continue
    elif len(rem[i])>n//m:
        for j in range(n//m, len(rem[i])):
            q.append(rem[i][j])
    else:
        for _ in range(min(n//m-len(rem[i]), len(q))):
            idx, ai = q.popleft()
            ans[idx] = ai+(i%m+m-ai%m)%m
            rem[i].append((idx, ans[idx]))

print(sum(ans)-sum(a))
print(*ans)


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])==n//m:
        continue
    elif len(rem[i])>n//m:
        for j in range(n//m, len(rem[i])):
            q.append(rem[i][j])
    else:
        for _ in range(min(n//m-len(rem[i]), len(q))):
            idx, ai = q.popleft()
            ans[idx] = ai+(i%m+m-ai%m)%m

print(sum(ans)-sum(a))
print(*ans)


# A brute force implmentation
n,m = map(int,input().split())
C = [0]*m; Ccount = n//m; moves = 0
arr = list(map(int,input().split()))
index = 0
while (index < n):
    myIndex = arr[index]%m
    if C[myIndex] < Ccount:
        C[myIndex] += 1
        index+=1
    else:
        arr[index] += 1
        moves += 1
print (moves)
print(*arr)


# A brute force implmentation
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())
nums = list(map(int, input().split()))

# 0 to m-1 remainders
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)

#print(remainder)
#print(deficit)
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(convert)
print(moves)
print(*nums)


#!/usr/bin/python3

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)

# INPUT
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()))

# CONVERT

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

# MAIN

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)

# log(n,m)
# log(mmap)

move = []
destination = []

for i in range(m):
    ddu = mmap[i]
    x = len(ddu)
    destination.extend([i]*(nm-x))
    move.extend(ddu[nm:x])

# log("move",move)
# log("dest",destination)

ssum = 0
lenmove = len(move)
sMoveId = sorted(range(lenmove), key=lambda k: a[move[k]] % m)

# log("smId",sMoveId)
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

    # log("move ", move[moveId],"as",a[move[moveId]],s," to ", d, ssum)
    a[move[moveId]] += d-s

print(ssum)
print(toString(a))


#!/usr/bin/python3

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)

# INPUT
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()))

# CONVERT

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

# MAIN

n,m = ni()
a = nia()

nm = n // m

mmap = {}

for i in range(n) :
    xx = a[i] % m
    if xx in mmap:
        mmap[xx].append(i)
    else:
        mmap[xx] = [i]

# log(n,m)
# log(mmap)

move = []
destination = []

for i in range(m):
    ddu = mmap.get(i,0)
    x = len(ddu)
    destination += [i]*(nm-x)
    move.extend(ddu[nm:x])

# log("move",move)
# log("dest",destination)

ssum = 0

sMoveId = sorted(range(len(move)), key=lambda k: a[move[k]] % m)

# log("smId",sMoveId)

lenmove = len(move)
for i in range(lenmove):
    # if move[i] == -1:
    moveId = sMoveId[i]
    s = a[move[moveId]] % m
    d = destination[i]
    if d < s:
        d += m
    ssum += d-s

    # log("move ", move[moveId],"as",a[move[moveId]],s," to ", d, ssum)
    a[move[moveId]] += d-s

print(ssum)
print(toString(a))


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

# LOG

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

# INPUT

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()))

# CONVERT
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)}

# SORT
def sortId(arr):
    return sorted(range(len(arr)), key=lambda k: arr[k])

# MAIN

n,m,s = ni()

s -= 1

adj = [[] for _ in range(n)]

for i in range(m):
    u,v = nio(-1)
    if (v != s):
        adj[u].append(v)

stack = []

visited= [False]*n

def dfs(x):
    global visited
    global stack
    visited[x] = True
    for y in adj[x]:
        if not visited[y]:
            dfs(y)

    stack.append(x)

for i in range(n):
    if not visited[i]:
        dfs(i)

# log(adj)
# log(visited)
# log(stack)

count = -1

def loang(x):
    global visited
    visited[x] = False
    for y in adj[x]:
        if visited[y]:
            loang(y)

for x in stack[::-1]:
    if visited[x]:
        count += 1
        loang(x)

print(count)


#!/usr/bin/python3

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)

# INPUT
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()))

# CONVERT

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

# MAIN

n,m = ni()
a = nia()

nm = n // m

mmap = {}

for i in range(n) :
    xx = a[i] % m
    mmap[xx] = mmap.get(xx,[]) + [i]

# log(n,m)
# log(mmap)

change = []

move = []
destination = []

for i in range(m):
    ddu = mmap.get(i,0)
    x = len(ddu)
    destination += [i]*(nm-x)
    move.extend(ddu[nm:x])

# log("move",move)
# log("dest",destination)

ssum = 0

sMoveId = sorted(range(len(move)), key=lambda k: a[move[k]] % m)

# log("smId",sMoveId)

lenmove = len(move)
for i in range(lenmove):
    # if move[i] == -1:
    moveId = sMoveId[i]
    s = a[move[moveId]] % m
    d = destination[i]
    if d < s:
        d += m
    ssum += d-s

    # log("move ", move[moveId],"as",a[move[moveId]],s," to ", d, ssum)
    a[move[moveId]] +=  d-s

print(ssum)
print(toString(a))


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:
        #value > modvalue
        removed.append((value, index))
        b.append(modvalue)
        continue

while removed:
    value, index = removed.pop()
    modvalue = b.pop()
    assert value < modvalue
    value %= modvalue
    a[index] += modvalue - value
    ans += modvalue - value

print(ans)
print(*a)


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:
        #value > modvalue
        removed.append((value, index))
        b.append(modvalue)
        continue
removed.reverse()

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()))
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:
        #value > modvalue
        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()))
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:
        #value > modvalue
        removed.append((value, index))
        b.append(modvalue)
        continue
removed.reverse()

while removed:
    value, index = removed.pop()
    modvalue = b.pop()
    assert value < modvalue
    value %= modvalue
    a[index] += modvalue - value
    ans += modvalue - value

print(ans)
print(*a)


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()


def solve():
    n, m = map(int, input().split())
    a = list(map(int, input().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[t][0] += 1
                a[b[t][1]] += 1
                ans += 1
            j += need
        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()


n, m = 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)


# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------
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)


# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------
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
    ops = [[]for __ in range(m)]
    for i in range(m):
        if a[i] <= divs:continue
        while a[i] > divs:
            while small < i or a[small] >= divs:
                small += 1
            ans += (small - i) * min(a[i] - divs, divs-a[small])
            ops[i] += [small-i]*min(a[i] - divs, divs-a[small])
            a[i] -= min(a[i] - divs, divs-a[small])
            if 0 <= i-m < len(a):
                a[i-m] -= min(a[i] - divs, divs-a[small])
            if 0 <= i+m < len(a):
                a[i+m] -= min(a[i] - divs, divs-a[small])
            a[small] += min(a[i] - divs, divs-a[small])
            if 0 <= small-m < len(a):
                a[small-m] += min(a[i] - divs, divs-a[small])
            if 0 <= small+m < len(a):
                a[small+m] += min(a[i] - divs, divs-a[small])
    small = 0
    for i in range(m):
        if a[i] <= divs:continue
        while a[i] > divs:
            while small < i or a[small] >= divs:
                small += 1
            ans += (small - i) * min(a[i] - divs, divs-a[small])
            ops[i] += [small-i]*min(a[i] - divs, divs-a[small])
            a[i] -= min(a[i] - divs, divs-a[small])
            if 0 <= i-m < len(a):
                a[i-m] -= min(a[i] - divs, divs-a[small])
            if 0 <= i+m < len(a):
                a[i+m] -= min(a[i] - divs, divs-a[small])
            a[small] += min(a[i] - divs, divs-a[small])
            if 0 <= small-m < len(a):
                a[small-m] += min(a[i] - divs, divs-a[small])
            if 0 <= small+m < len(a):
                a[small+m] += min(a[i] - divs, divs-a[small])
    print(ans)
    for i in range(n):
        if ops[b[i]%m]:
            b[i] += ops[b[i]%m].pop()
    print(*b)


# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------
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
    ops = [[]for __ in range(m)]
    for i in range(m):
        if a[i] <= divs:continue
        while a[i] > divs:
            while small < i or a[small] >= divs:
                small += 1
            ans += (small - i) * min(a[i] - divs, divs-a[small])
            ops[i] += [small-i]*min(a[i] - divs, divs-a[small])
            a[i] -= min(a[i] - divs, divs-a[small])
            if 0 <= i-n < len(a):
                a[i-n] -= min(a[i] - divs, divs-a[small])
            if 0 <= i+n < len(a):
                a[i+n] -= min(a[i] - divs, divs-a[small])
            a[small] += min(a[i] - divs, divs-a[small])
            if 0 <= small-n < len(a):
                a[small-n] += min(a[i] - divs, divs-a[small])
            if 0 <= small+n < len(a):
                a[small+n] += min(a[i] - divs, divs-a[small])
    print(ans)
    for i in range(n):
        if ops[b[i]%m]:
            b[i] += ops[b[i]%m].pop()
    print(*b)


# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------
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
    ops = [[]for __ in range(m)]
    for i in range(m):
        if a[i] <= divs:continue
        while a[i] > divs:
            while small < i or a[small] >= divs:
                small += 1
            ans += (small - i) * min(a[i] - divs, divs-a[small])
            ops[i] += [small-i]*min(a[i] - divs, divs-a[small])
            a[i] -= min(a[i] - divs, divs-a[small])
            if 0 <= i-m < len(a):
                a[i-m] -= min(a[i] - divs, divs-a[small])
            if 0 <= i+m < len(a):
                a[i+m] -= min(a[i] - divs, divs-a[small])
            a[small] += min(a[i] - divs, divs-a[small])
            if 0 <= small-m < len(a):
                a[small-m] += min(a[i] - divs, divs-a[small])
            if 0 <= small+m < len(a):
                a[small+m] += min(a[i] - divs, divs-a[small])
    print(ans)
    for i in range(n):
        if ops[b[i]%m]:
            b[i] += ops[b[i]%m].pop()
    print(*b)


# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------
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 = 1
    ans = 0
    ops = [[]for __ in range(m)]
    for i in range(m):
        if a[i] <= divs:continue
        while a[i] > divs:
            while a[small] >= divs:
                small += 1
            ans += (small - i) * min(a[i] - divs, divs-a[small])
            ops[i] += [small-i]*min(a[i] - divs, divs-a[small])
            a[i] -= min(a[i] - divs, divs-a[small])
            if 0 <= i-n < len(a):
                a[i-n] -= min(a[i] - divs, divs-a[small])
            if 0 <= i+n < len(a):
                a[i+n] -= min(a[i] - divs, divs-a[small])
            a[small] += min(a[i] - divs, divs-a[small])
            if 0 <= small-n < len(a):
                a[small-n] += min(a[i] - divs, divs-a[small])
            if 0 <= small+n < len(a):
                a[small+n] += min(a[i] - divs, divs-a[small])
    print(ans)
    for i in range(n):
        if ops[b[i]%m]:
            b[i] += ops[b[i]%m].pop()
    print(*b)


# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------
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 = 1
    ans = 0
    ops = [[]for __ in range(m)]
    for i in range(m):
        if a[i] <= divs:continue
        while a[i] > divs:
            while small <= i or a[small] >= divs:
                small += 1
            ans += (small - i) * min(a[i] - divs, divs-a[small])
            ops[i] += [small-i]*min(a[i] - divs, divs-a[small])
            a[i] -= min(a[i] - divs, divs-a[small])
            if 0 <= i-n < len(a):
                a[i-n] -= min(a[i] - divs, divs-a[small])
            if 0 <= i+n < len(a):
                a[i+n] -= min(a[i] - divs, divs-a[small])
            a[small] += min(a[i] - divs, divs-a[small])
            if 0 <= small-n < len(a):
                a[small-n] += min(a[i] - divs, divs-a[small])
            if 0 <= small+n < len(a):
                a[small+n] += min(a[i] - divs, divs-a[small])
    print(ans)
    for i in range(n):
        if ops[b[i]%m]:
            b[i] += ops[b[i]%m].pop()
    print(*b)


# ------------------- fast io --------------------
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")

# ------------------- fast io --------------------
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
    ops = [[]for __ in range(m)]
    for i in range(m):
        if a[i] <= divs:continue
        while a[i] > divs:
            while a[small] >= divs:
                small += 1
            ans += (small - i) * min(a[i] - divs, divs-a[small])
            ops[i] += [small-i]*min(a[i] - divs, divs-a[small])
            a[i] -= min(a[i] - divs, divs-a[small])
            if 0 <= i-n < len(a):
                a[i-n] -= min(a[i] - divs, divs-a[small])
            if 0 <= i+n < len(a):
                a[i+n] -= min(a[i] - divs, divs-a[small])
            a[small] += min(a[i] - divs, divs-a[small])
            if 0 <= small-n < len(a):
                a[small-n] += min(a[i] - divs, divs-a[small])
            if 0 <= small+n < len(a):
                a[small+n] += min(a[i] - divs, divs-a[small])
    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())
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)


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)
maxa=0
for i in range(m):
    if(len(arr[i])>maxa):
        maxa=len(arr[i])
        ans=i
req=n//m
count=0
for i in range(n):
    j=(ans+i)%m
    next=(j+1)%m
    z=len(arr[j])
    if(z>req):
        for k in range(z-req):
            li[arr[j][0]]+=1
            arr[next].append(arr[j][0])
            arr[j].pop(0)
        count+=z-req
print(count)
for i in li:
    print(i,end=" ")
print()


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((i,arr[y][j]))
print(count)
for i in li:
    print(i,end=" ")


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((i,arr[y][0]))
            arr[y].pop(0)
print(count)
for i in li:
    print(i,end=" ")


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][j]))
print(count)
for i in li:
    print(i,end=" ")


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())
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 = []
for i in range(2*m):
    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]
        cr[i%m] = n//m
        for _ in range(tmp):
            if not hold:
                break
            idx, j = hold.pop()
            cnt += i-j
            a[idx] += i-j
print(cnt)
print(*a)


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 = 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]
        cr[i%m] = n//m
        for _ in range(tmp):
            if not hold:
                break
            idx, j = hold.popleft()
            cnt += i-j
            a[idx] += i-j
print(cnt)
print(*a)


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
for i in range(2*m):
    if cr[i%m]>n//m:
        tmp = cr[i%m]-n//m
        cr[(i+1)%m] += tmp
        cr[i%m] = n//m
        for _ in range(tmp):
            idx = crpos[i%m].pop()
            a[idx] += 1
            crpos[(i+1)%m].append(idx)
        cnt += tmp
print(cnt)
print(*a)


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]
        cr[i%m] = n//m
        for _ in range(tmp):
            if not hold:
                break
            idx, j = hold.popleft()
            cnt += i-j
            a[idx] += i-j
for i in range(m):
    if cr[i]!=n//m:
        assert(False)
print(cnt)
print(*a)


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)))


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

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)


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

typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
typedef pair<int, int> pii;
typedef pair<ll, ld> pld;
typedef pair<pii, int> ppiii;
typedef pair<pii, ll> ppiil;
typedef pair<pll, ll> pplll;
typedef pair<pli, int> pplii;
typedef vector<vector<ll>> vvl;
typedef vector<vector<int>> vvi;
typedef vector<vector<pll>> vvpll;
#define rep(i, a, b) for (ll i=(a); i<(b); i++)
#define rrep(i, a, b) for (ll i=(a); i>(b); i--)
#define pb push_back
#define tostr to_string
#define mkp make_pair
const ll INF = 1e18;
const ll MOD = 1e9 + 7;

void print(ld out) { cout << fixed << setprecision(12) << out << '\n'; }
template<typename T> void print(T out) { cout << out << '\n'; }
template<typename T1, typename T2> void print(pair<T1, T2> out) { cout << out.first << ' ' << out.second << '\n'; }
template<typename T> void print(vector<T> A) { rep(i, 0, A.size()) { cout << A[i]; cout << (i == A.size()-1 ? '\n' : ' '); } }
template<typename T> void print(set<T> S) { vector<T> A(S.begin(), S.end()); print(A); }

template<typename T> inline bool chmax(T &x, T y) { return (y > x) ? x = y, true : false; }
template<typename T> inline bool chmin(T &x, T y) { return (y < x) ? x = y, true : false; }

ll sum(vector<ll> A) { ll res = 0; for (ll a: A) res += a; return res; }
ll max(vector<ll> A) { ll res = -INF; for (ll a: A) chmax(res, a); return res; }
ll min(vector<ll> A) { ll res = INF; for (ll a: A) chmin(res, a); return res; }

ll toint(string s) { ll res = 0; for (char c : s) { res *= 10; res += (c - '0'); } return res; }
int toint(char c) { return c - '0'; }
char tochar(int i) { return '0' + i; }

inline ll pow(int x, ll n) { ll res = 1; rep(_, 0, n) res *= x; return res; }
inline ll pow(ll x, ll n, int mod) { ll res = 1; while (n > 0) { if (n & 1) { res = (res * x) % mod; } x = (x * x) % mod; n >>= 1; } return res; }

inline ll floor(ll a, ll b) { if (a < 0) { return (a-b+1) / b; } else { return a / b; } }
inline ll ceil(ll a, ll b) { if (a >= 0) { return (a+b-1) / b; } else { return a / b; } }

int popcount(ll S) { return __builtin_popcountll(S); }
ll gcd(ll a, ll b) { return __gcd(a, b); }

ll N, M, K;
vector<ll> A, modA, ans, modans;
vvl idxs;

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

    cin >> N >> M;
    A.resize(N);
    modA.resize(N);
    ans.resize(N);
    modans.resize(N);
    idxs.resize(M);
    rep(i, 0, N) {
        cin >> A[i];
        modA[i] = A[i] % M;
        idxs[modA[i]].pb(i);
    }

    K = N / M;
    ll cnt = 0;
    vector<ll> tmp;
    rep(m, 0, M) {
        tmp.clear();
        while (idxs[m%M].size() > K) {
            tmp.pb(idxs[m%M].back()); idxs[m%M].pop_back();
        }
        for (ll a : tmp) {
            idxs[(m+1)%M].pb(a);
        }
        cnt += tmp.size();
    }

    rep(m, 0, M) {
        for (ll i : idxs[m]) {
            modans[i] = m;
        }
    }

    rep(i, 0, N) {
        if (modA[i] < modans[i]) {
            ans[i] = A[i] + (modans[i] - modA[i]);
        } else if (modA[i] > modans[i]) {
            ans[i] = A[i] + (modans[i]+M - modA[i]);
        } else {
            ans[i] = A[i];
        }
    }
    print(cnt);
    print(ans);
    return 0;
}


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

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
for m in range(M*2):
    tmp = []
    while len(idxs[m%M]) > K:
        tmp.append(idxs[m%M].pop())
    idxs[(m+1)%M] += tmp
    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)


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)


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(m):
        q = len(data_stat[i])
        used = set()
        for k in data_stat[i]:
            if q <= query:
                break
            else:
                free.append((k, i))
                q -= 1
                used.add(k)
        for k in used:
            data_stat[i].discard(k)
        for k in data_stat[i]:
            answer[k] = data[k]
    for i in range(m):
        q = len(data_stat[i])
        if  q == query:
            continue
        else:
            while q != query:
                value, key = free.pop()
                result += (i - (key % m))
                answer[value] = data[value] + (i - (key % m))
                q += 1
    print(result)
    for k in answer:
        out.write(str(answer[k]) + ' ')

if __name__=="__main__":
    main()


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

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    data_stat = {i:[0, set()] for i in range(m)}
    query = n//m
    for i in range(n):
        data_stat[a[i] % m][0] += 1
        data_stat[a[i] % m][1].add((a[i], i))
    result = {i:0 for i in range(n)}
    answer = 0
    for k in data_stat:
        if data_stat[k][0] <= query:
            for v, e in data_stat[k][1]:
                result[e] = v
        else:
            used = set()
            for q, e in data_stat[k][1]:
                current = q
                while True:
                    q += 1
                    answer += 1
                    if data_stat[q % m][0] + 1 <= query:
                        data_stat[k][0] -= 1
                        used.add(current)
                        data_stat[q % m][0] += 1
                        data_stat[q % m][1].add((q, e))
                        result[e] = q
                        break
                if data_stat[k][0] == query:
                    break
            for cur in used:
                data_stat[k][1].discard(cur)
    for k in data_stat:
        for q, e in data_stat[k][1]:
            result[e] = q
    print(answer)
    for k in result:
        out.write(str(result[k]) + ' ')

if __name__=="__main__":
    main()


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) + ' ')

if __name__=="__main__":
    main()


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(m):
        q = len(data_stat[i])
        used = set()
        for k in data_stat[i]:
            if q <= query:
                break
            else:
                free.append((k, i))
                q -= 1
                used.add(k)
        for k in used:
            data_stat[i].discard(k)
        for k in data_stat[i]:
            answer[k] = data[k]
    for i in range(m):
        q = len(data_stat[i])
        if  q == query:
            continue
        else:
            while q != query:
                value, key = free.pop()
                result += abs(i - key)
                answer[value] = data[value] + abs(i - key)
                q += 1
    print(result)
    for k in answer:
        out.write(str(answer[k]) + ' ')

if __name__=="__main__":
    main()


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

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    data = {}
    data_stat = {i:[0, set()] for i in range(m)}
    query = n//m
    for i in range(n):
        data[a[i]] = i
        data_stat[a[i] % m][0] += 1
        data_stat[a[i] % m][1].add(a[i])
    result = {i:0 for i in range(n)}
    answer = 0
    for k in data_stat:
        if data_stat[k][0] <= query:
            for z in data_stat[k][1]:
                result[data.get(z)] = z
        else:
            used = set()
            for q in data_stat[k][1]:
                current = q
                while True:
                    q += 1
                    answer += 1
                    if data_stat[q % m][0] + 1 <= query:
                        data_stat[k][0] -= 1
                        used.add(current)
                        data_stat[q % m][0] += 1
                        data_stat[q % m][1].add(q)
                        data[q] = data.pop(current)
                        break
                if data_stat[k][0] == query:
                    break
            for cur in used:
                data_stat[k][1].discard(cur)
    for k in data_stat:
        for z in data_stat[k][1]:
            result[data.get(z)] = z
    print(answer)
    for k in result:
        out.write(str(result[k]) + ' ')

if __name__=="__main__":
    main()


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

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))
    data = {}
    data_stat = {i:[0, set()] for i in range(m)}
    query = n//m
    for i in range(n):
        data[a[i]] = i
        data_stat[a[i] % m][0] += 1
        data_stat[a[i] % m][1].add(a[i])
    result = {i:0 for i in range(n)}
    for k in data_stat:
        if data_stat[k][0] <= query:
            for z in data_stat[k][1]:
                result[data.get(z)] = z
        else:
            used = set()
            for q in data_stat[k][1]:
                current = q
                while True:
                    q += 1
                    if data_stat[q % m][0] + 1 <= query:
                        data_stat[k][0] -= 1
                        used.add(current)
                        data_stat[q % m][0] += 1
                        data_stat[q % m][1].add(q)
                        data[q] = data.pop(current)
                        break
                if data_stat[k][0] == query:
                    break
            for cur in used:
                data_stat[k][1].discard(cur)
    for k in data_stat:
        for z in data_stat[k][1]:
            result[data.get(z)] = z
    for k in result:
        out.write(str(result[k]) + ' ')

if __name__=="__main__":
    main()


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(m):
        q = len(data_stat[i])
        used = set()
        for k in data_stat[i]:
            if q <= query:
                break
            else:
                free.append((k, i))
                q -= 1
                used.add(k)
        for k in used:
            data_stat[i].discard(k)
        for k in data_stat[i]:
            answer[k] = data[k]
    for i in range(m):
        q = len(data_stat[i])
        if  q == query:
            continue
        else:
            while q != query:
                value, key = free.pop()
                result += (i - key)
                answer[value] = data[value] + (i - key)
                q += 1
    print(result)
    for k in answer:
        out.write(str(answer[k]) + ' ')

if __name__=="__main__":
    main()


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(m):
        q = len(data_stat[i])
        used = set()
        for k in data_stat[i]:
            if q <= query:
                break
            else:
                free.append((k, i))
                q -= 1
                used.add(k)
        for k in used:
            data_stat[i].discard(k)
        for k in data_stat[i]:
            answer[k] = data[k]
    for i in range(m):
        q = len(data_stat[i])
        if  q == query:
            continue
        else:
            while q != query:
                value, key = free.pop()
                if i < key:
                    result += (m - key)
                    answer[value] = data[value] + (m - key)
                else:
                    result += (i - key)
                    answer[value] = data[value] + (i - key)
                q += 1
    print(result)
    for k in answer:
        out.write(str(answer[k]) + ' ')

if __name__=="__main__":
    main()


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(m):
        q = len(data_stat[i])
        used = set()
        for k in data_stat[i]:
            if q <= query:
                break
            else:
                free.append((k, i))
                q -= 1
                used.add(k)
        for k in used:
            data_stat[i].discard(k)
        for k in data_stat[i]:
            answer[k] = data[k]
    for i in range(m-1, -1, -1):
        q = len(data_stat[i])
        if  q == query:
            continue
        else:
            while q != query:
                value, key = free.pop()
                if i < key:
                    result += (m - key)
                    answer[value] = data[value] + (m - key)
                else:
                    result += (i - key)
                    answer[value] = data[value] + (i - key)
                q += 1
    print(result)
    for k in answer:
        out.write(str(answer[k]) + ' ')

if __name__=="__main__":
    main()