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 (0≤r≤m−1)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=⋯=cm−1=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 (1≤n≤2⋅105,1≤m≤n1≤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 (0≤ai≤1090≤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 00to m−1m−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
题意:
有数a[1]-a[n],有m是n的因子,每+1算1步,让c[r],r即a[i]%m,作为a数组每个数%m余r的个数,使得c[0]=……=c[m-1]=n/m至少需要几步。
嘤首先要看出来这是贪心。
贪心的思想是遍历过程中,如果a[[i]%m=r,且c[r]未达n/m,不需要+1,计入;否则,找到最近的未满的r加至那里。其正确性可以模拟一下,没有任何问题;如果不选择最近的数而是+1之类的,后面的再补上来,步数只会>=这种方案。
一开始直接只是贪心暴力写,T了。
然后就用set做二分:
将计够n/m的余数都放在set集合中,计数结束就从集合中删除,查找最近的未满余数时,用lower_bound做二分,记得特判如果是最大的(s.rbegin())就找最前面的这样子。
另外数据范围,开int是会wa的emmm
#include <cstdio>
#include <cstring>
#include <set>
#include <algorithm>
using namespace std;
const int maxn=2e5+20;
const int maxm=1e5+20;
int main()
{
int n,m;
long long a[maxn],r,x;
long long c[maxn]; //为什么数据范围都要开这么大啊啊啊啊
long long ans=0;
set <long long> s;
memset(c,0,sizeof(c));
scanf("%d%d",&n,&m);
for(int i=0;i<m;++i)
s.insert(i);
for(int i=1;i<=n;++i){
scanf("%lld",&a[i]);
if(m==1) continue;
r=a[i]%m;
if(r>*s.rbegin())
x=*s.begin();
else
x=*s.lower_bound(r);//lower_bound(s.begin(),s.end(),r);
if(++c[x]==n/m)
s.erase(x);
ans+=(x-r+m)%m;
a[i]+=(x-r+m)%m;
}
printf("%lld\n",ans);
for(int i=1;i<=n;++i)
printf("%lld ",a[i]);
return 0;
}