D. Equalize the Remainders set的使用+思维

D. Equalize the Remainders

set的学习::https://blog.csdn.net/byn12345/article/details/79523516

注意set的end()和rbegin()的区别。

end()是指向最后一个元素的下一个,rbegin()是指向最后一个元素。

题目大意:给你一个n长度的数组,给一个模数m,问对m取模,余数从0到m-1的每一种都是n/m 保证m一定是n的除数。

每一个操作对数字+1,问最少的操作满足题目,输出操作之后的数组。

这个用set模拟比较好写。

首先将0到m-1的每一个数都放到set里面,然后遍历这个数组,对于每一个数,如果这个数的这个余数已经有了n/m 

贪心的考虑这个数首先是加的越少越好。

如果这个数的余数已经没有比它更大的数存在了,那么就应该选最小还需要的约数加上去,也就是这个set的头部,

扫描二维码关注公众号,回复: 7433223 查看本文章

因为set是排过序的,头部是最小的数字,

如果还存在比这个数的余数更大的,那就贪心的加在大于等于这个数的最小的数。

然后就可以求出贡献,也可以求出这个数要加上去的结果。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <set>
#define fir first
#define sec second
using namespace std;
typedef long long ll;
const int maxn=2e5+10;
ll a[maxn],val[maxn];
int res[maxn];
set<int>s;
 
int main(){
    int n,m;
    s.clear();
    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]);
    }
    ll ans=0;
    memset(res,0,sizeof(res));
    for(int i=1;i<=n;i++){
        ll t=a[i]%m;
        ll x;
        if(t>*s.rbegin()) x=*s.begin();
        else x=*s.lower_bound(t);
        res[x]++;
        if(res[x]==n/m) s.erase(x);
        ans+=(x-t+m)%m;
        val[i]=(x-t+m)%m;
    }
    printf("%lld\n",ans);
    for(int i=1;i<=n;i++) printf("%lld ",a[i]+val[i]);
    printf("\n");
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/EchoZQN/p/11628669.html