• 2022.8.9考试平衡的余数--1000题解


    2022.8.9考试平衡的余数--1000题解

    题目

    1、平衡的余数–1000
    时间限制: | 空间限制:
    题目描述:
    给出一个正整数 ( 能被3整除)和一个大小为 的整数数组 。
    在一次操作中,你可以选择任意一个 中的数并让它增加1。你可以对同一个位置上的数进行多次该操
    作。
    请求出至少需要多少步操作(可以是0次),使 中模3余 的数的个数相等。共 组测试数据。
    输入格式:
    第一行仅有一个正整数 ( ),表示测试数据的组数。
    接下来有 组测试数据,每组共两行:
    第一行仅一个正整数 ( , 能被3整除,且所有测试数据中 之和不超过
    ),表示数组大小;
    第二行有 个整数 ( )用空格隔开。
    输出格式:
    对于每组测试数据,输出一行一个整数,表示至少多少次操作使 符合条件。

    思路

    余数为0 1 2的传导构成了一个环,所以只需要判断一遍与平均值的关系,传导即可。

    代码实现

    #include
    using namespace std;
    
    int t,n,ans;
    int cnt[3];
    int main(){
    	scanf("%d",&t);
    	while(t--){
    		ans=0;
    		memset(cnt,0,sizeof(cnt));
    		scanf("%d",&n);
    		for(int i=1;i<=n;i++){
    			int a;
    			scanf("%d",&a);
    			cnt[a%3]++;
    		} 
    		int op=n/3;
    		if(cnt[0]>op){
    			int s=cnt[0]-op;
    			ans+=s;
    			cnt[0]=n/3;
    			cnt[1]+=s;
    		}
    		else if(cnt[0]<op){
    			int s=op-cnt[0];
    			ans+=s;
    			cnt[2]-=s;
    			cnt[0]=n/3;
    		}
    		if(cnt[2]>op){
    			int s=cnt[2]-op;
    			ans+=s;
    			cnt[0]+=s;
    			cnt[2]=n/3;
    		}
    		else if(cnt[2]<op){
    			int s=op-cnt[2];
    			ans+=s;
    			cnt[2]=n/3;
    			cnt[1]-=s;
    		}
    		if(cnt[1]>op){
    			int s=cnt[1]-op;
    			ans+=s;
    			cnt[1]=n/3;
    			cnt[2]+=s;
    		}
    		else if(cnt[1]<op){
    			int s=op-cnt[1];
    			ans+=s;
    			cnt[1]=n/3;
    			cnt[0]-=s;
    		}
    		printf("%d\n",ans);
    	}
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
  • 相关阅读:
    线性规划Matlab求解
    走进Redis之配置文件的修改&使用
    【torch】torch.pairwise_distance分析
    R语言github软件的两种安装方式
    什么是Vue的Vetur插件?它有哪些功能
    Spring Boot与Shiro实现权限管理01
    外汇天眼:中国银行马尼拉分行推出数字外汇!
    前端工程师的20道react面试题自检
    使用 Prometheus 监控 eKuiper 规则运行状态
    json文件数据转存mysql数据工具,安利一波
  • 原文地址:https://blog.csdn.net/weixin_42178241/article/details/126253675