练习cf1490B. Balanced Remainders
题目如下
B. Balanced Remainders
time limit per test2 seconds
memory limit per test256 megabytes
You are given a number 𝑛 (divisible by 3) and an array 𝑎[1…𝑛]. In one move, you can increase any of the array elements by one. Formally, you choose the index 𝑖 (1≤𝑖≤𝑛) and replace 𝑎𝑖 with 𝑎𝑖+1. You can choose the same index 𝑖 multiple times for different moves.
Let's denote by 𝑐0, 𝑐1 and 𝑐2 the number of numbers from the array 𝑎 that have remainders 0, 1 and 2 when divided by the number 3, respectively. Let's say that the array 𝑎 has balanced remainders if 𝑐0, 𝑐1 and 𝑐2 are equal.
For example, if 𝑛=6 and 𝑎=[0,2,5,5,4,8], then the following sequence of moves is possible:
initially 𝑐0=1, 𝑐1=1 and 𝑐2=4, these values are not equal to each other. Let's increase 𝑎3, now the array 𝑎=[0,2,6,5,4,8];
𝑐0=2, 𝑐1=1 and 𝑐2=3, these values are not equal. Let's increase 𝑎6, now the array 𝑎=[0,2,6,5,4,9];
𝑐0=3, 𝑐1=1 and 𝑐2=2, these values are not equal. Let's increase 𝑎1, now the array 𝑎=[1,2,6,5,4,9];
𝑐0=2, 𝑐1=2 and 𝑐2=2, these values are equal to each other, which means that the array 𝑎 has balanced remainders.
Find the minimum number of moves needed to make the array 𝑎 have balanced remainders.
Input
The first line contains one integer 𝑡 (1≤𝑡≤104). Then 𝑡 test cases follow.
The first line of each test case contains one integer 𝑛 (3≤𝑛≤3⋅104) — the length of the array 𝑎. It is guaranteed that the number 𝑛 is divisible by 3.
The next line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (0≤𝑎𝑖≤100).
It is guaranteed that the sum of 𝑛 over all test cases does not exceed 150000.
Output
For each test case, output one integer — the minimum number of moves that must be made for the 𝑎 array to make it have balanced remainders.
题目大意
现有一个有n个元素的数组,n为3的除数(可以被3整除),每次可以对一个元素进行加一或者减一的操作,问最少需要多少次操作,能够使得数组中整除3得1,整除3得2和整除3得0的元素数量相等。
题目分析
先分组,统计c1,c2,c0分别的个数,再通过搬运获得相同的数。
点击查看代码
#include <iostream>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int a[300003];
int c1 = 0, c2 = 0, c0 = 0, cnt = 0;
for(int i = 0; i < n; i++){
cin >> a[i];
if(a[i] % 3 == 0){
c0++;
}else if(a[i] % 3 == 1){
c1++;
}else{
c2++;
}
}
while(c0 != n / 3 || c1 != n / 3 || c2 != n / 3){ //
if(c0 > n / 3){
c0--;
c1++;
cnt++;
}else if(c1 > n / 3){
c1--;
c2++;
cnt++;
}else if(c2 > n / 3){
c2--;
c0++;
cnt++;
}
}
cout << cnt<< endl;
}
}

浙公网安备 33010602011771号