题目:E2. Send Boxes to Alice (Hard Version)
总结:这题就是贪心吧!还是先找出所有的质因子,假设某个质因子为x,对于当前值ai,要么就是ai%x放到后面,要么就是从后面拿x-ai%x,放到ai。
解决这个子问题,转换到下一个子问题。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6+10;
int a[N];
int n;
ll solve(ll x){
ll ans = 0;
ll sum = 0;
for(int i = 1;i <= n;i++){
sum = (sum+a[i])%x;
ans += min(sum,x-sum);
}
return ans;
}
int main(){
// freopen("out.txt","r",stdin);
ll sum = 0;
scanf("%d",&n);
for(int i = 1;i <= n;i++){
scanf("%d",a+i);
sum += a[i];
}
if(sum == 0){
printf("0\n");
return 0;
}else if(sum == 1){
printf("-1\n");
return 0;
}
ll ans = 0x7f7f7f7f7f7f7f7f;
//求解质因子
for(ll i = 2;i*i <= sum;i++){
if(sum%i == 0){
ans = min(ans,solve(i));
while(sum%i == 0) sum /= i;
}
}
if(sum > 1) ans = min(ans,solve(sum));
printf("%lld\n",ans);
return 0;
}