题目链接:​​A Simple Stone Game​

题目大意:有n堆石头,你每次可以将一堆石头里面的一个移动到另一堆里面,问最少需要多少次可以使得所有石头堆的数量都可以被某一个数整除

题目思路:因为我们只能移动石头,所以所有石头堆的总数一定是固定的,所以最后找到的数一定是总数的某一个因子,然后枚举每一个素因子,然后找这个素因子需要移动的数量,我们只需要对这个素因子求余然后从大到小排序然后对每个石头堆补完素数因子就好了(因为要移动的石头最少,所以补大的,而且剩下的总和一定是这个素因子的倍数,那么一定能补完),然后找所有素因子里面最小的移动步数就好了

时间复杂度&&空间复杂度:O(2n*cnt)&&O(n)(cnt为素因子个数)

#include <map>
#include <set>
#include <cmath>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>

using namespace std;
typedef long long ll;
const int maxn = 5e5+10;

ll a[maxn],phi[maxn],mo[maxn];
ll sum,cnt;

bool cmp(ll a,ll b){return a > b;}

void init(){
cnt = 0;
for(ll i = 2;i*i <= sum;i++){
if(sum%i == 0) phi[cnt++] = i;
while(sum%i == 0) sum /= i;
}
phi[cnt++] = sum;
}

int main(){
ll T,n,minn,num;
scanf("%lld",&T);
while(T--){
scanf("%lld",&n);
sum = 0;
for(ll i = 0;i < n;i++){
scanf("%lld",&a[i]);
sum += a[i];
}
init();
minn = 1e10+10;
for(ll j = 0;j < cnt;j++){
num = 0;
for(ll i = 0;i < n;i++) mo[i] = a[i]%phi[j],num += mo[i];
ll ret = 0;
sort(mo,mo+n,cmp);
ll i = 0;
while(num > 0&&i < n){
ret += phi[j]-mo[i];
num -= phi[j];
i++;
}
minn = min(minn,ret);
}
printf("%lld\n",minn);
}
return 0;
}