Equalize the Remainders(思维)

Equalize the Remainders

You are given an array consisting of n integers a1,a2,…,an, 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 ai by 1

.

Let’s calculate cr
(0≤r≤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 c0=c1=⋯=cm−1=nm

.

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

Input

The first line of input contains two integers n

and m (1≤n≤2⋅105,1≤m≤n). It is guaranteed that m is a divisor of n

.

The second line of input contains n
integers a1,a2,…,an (0≤ai≤109

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

.

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 1018

.

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 
题意:

n个数字,对m取余有m种情况,使得每种情况的个数都为n/m个(保证n%m=0),最少需要操作多少次?
操作:把某个数字+1。输出最少操作次数,和操作后的序列(可以输出任意一种)。

分析:

对于余数x来说,如果余数为x的数没凑够n/m个,那么就让他不变,如果已经凑够了,我们就让他变为距离他最近的没凑够的余数(且通过+1得到的)。
所以,C[i]数组维护余数为i的数的个数,定义set< int>s,维护还没凑够的余数(初始化把0到m-1个余数全部放进去)。所以对于每一个数字求出他的余数d,然后找到s中第一个大于等于d的数字x(直接使用set中的lower_bound),++C[x],如果C[x]==n/m就把x从s中删除。但是注意一种情况,x比s中最大的数还大,那么我们就把x变为s中最小的数,举个例子m=5,余数为4和为0的数字凑够了,此时又来一个余数为4的数,该数应该变为余数为1。维护答案和序列,ans += (x-d+m)%m(需要+1的次数),a[i] += (x-d+m)%m(给原来这个数加上这些个1)。

code:

#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
ll n,m,a[maxn],c[maxn],ans;
set<int> s;
int main(){
    scanf("%lld%lld",&n,&m);
    for(int i = 0; i < m; i++) s.insert(i);
    for(int i = 0; i < n; i++){
        scanf("%lld",&a[i]);
        int d = a[i] % m,x;
        //找到d能加到的最近的余数x
        if(d > *s.rbegin()) x = *s.begin();//d比最大的余数还大就变成第一个余数
        else x = *s.lower_bound(d);
        if(++c[x] == n / m) s.erase(x);
        ans += (x - d + m) % m;
        a[i] += (x - d + m) % m;
    }
    printf("%lld\n",ans);
    for(int i = 0; i < n; i++) printf("%lld%c",a[i],i == n-1 ? '\n' : ' ');
    return 0;
}

你可能感兴趣的:(#,思维技巧)