其他分享
首页 > 其他分享> > Codeforces Round #601 (Div. 2) E2. Send Boxes to Alice (Hard Version)

Codeforces Round #601 (Div. 2) E2. Send Boxes to Alice (Hard Version)

作者:互联网

Codeforces Round #601 (Div. 2) E2. Send Boxes to Alice (Hard Version)

N个盒子,每个盒子有a[i]块巧克力,每次操作可以将盒子中的一块巧克力左移或右移,要求移动后的每个盒子中的巧克力数量都能被k整除(无视空盒子),求最小的操作数。(1<=N<=1e6,0<=a[i]<=1e6)

题解

代码

#include <cstdio>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 10;
int a[maxn],n;
ll sum[maxn];
inline ll solve(ll k){
    ll res=0;
    for(int i=1;i<=n;i++){
        ll x=sum[i]%k;
        res+=min(x,k-x);
    }
    return res;
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",a+i);
        sum[i]=a[i]+sum[i-1];
    }
    ll tot=sum[n],ans=LLONG_MAX;
    for(ll i=2;i*i<=tot;i++){
        if(tot%i) continue;
        ans=min(ans,solve(i));
        while (tot%i==0) {
            tot/=i;
        }
    }
    if(tot!=1) ans=min(ans,solve(tot));
    if(ans!=LLONG_MAX)cout<<ans<<endl;
    else cout<<-1<<endl;
}

标签:巧克力,盒子,int,ll,Hard,Codeforces,maxn,601,include
来源: https://www.cnblogs.com/Waldeinsamkeit/p/11929607.html