D. Equalize the Remainders (set的基本操作)

D. Equalize the Remainders
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given an array consisting of nn integers a1,a2,,ana1,a2,…,an, and a positive integer mm. It is guaranteed that mm is a divisor of nn.

In a single move, you can choose any position ii between 11 and nn and increase aiai by 11.

Let's calculate crcr (0rm1)0≤r≤m−1) — the number of elements having remainder rr when divided by mm. In other words, for each remainder, let's find the number of corresponding elements in aa with that remainder.

Your task is to change the array in such a way that c0=c1==cm1=nmc0=c1=⋯=cm−1=nm.

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

Input

The first line of input contains two integers nn and mm (1n2105,1mn1≤n≤2⋅105,1≤m≤n). It is guaranteed that mm is a divisor of nn.

The second line of input contains nn integers a1,a2,,ana1,a2,…,an (0ai1090≤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 00 to m1m−1, the number of elements of the array having this remainder equals nmnm.

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 10181018.

Examples
input
Copy
6 3
3 2 0 6 10 12
output
Copy
3
3 2 0 7 10 14
input
Copy
4 2
0 1 2 3
output
Copy
0
0 1 2 3

 给你N个数 你可以对这些数 + 1 操作

所有数对n取模后1->m-1 每一个数都出现n/m次

 求最少的操作次数

 你第一次扫一遍 看看比 n/m大的 放入set里面  因为应该对超过了n/m的进行操作

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 const int maxn = 2e5 + 10;
 5 const int INF = 0x7fffffff;
 6 LL n, m, num, ans, a[maxn], b[maxn];
 7 
 8 int main() {
 9     scanf("%lld%lld", &n, &m);
10     for (int i = 0 ; i < n ; i++) {
11         scanf("%lld", &a[i]);
12         b[a[i] % m]++;
13     }
14     set<LL>st;
15     ans = 0, num = n / m;
16     for (int i = 0 ; i < m ; i++)
17         if (b[i] < num)   st.insert(i);
18     for (int i = 0 ; i < n ; i++) {
19         if (b[a[i] % m] <= num) continue;
20         b[a[i] % m]--;
21         set<LL>::iterator it;
22         it = st.lower_bound(a[i] % m);
23         if (it != st.end()) {
24             ans += *it - a[i] % m;
25             a[i] += *it - a[i] % m;
26             b[*it]++;
27             if (b[*it] == num) st.erase(it);
28         } else {
29             LL temp = m - a[i] % m;
30             ans += *st.begin() + temp;
31             a[i] += *st.begin() + temp;
32             b[*st.begin()]++;
33             if (b[*st.begin()] == num) st.erase(st.begin());
34         }
35     }
36     printf("%lld\n", ans);
37     for (int i = 0 ; i < n ; i++)
38         printf("%lld ", a[i]);
39     printf("\n");
40     return 0;
41 }

猜你喜欢

转载自www.cnblogs.com/qldabiaoge/p/9300354.html