E2 - Send Boxes to Alice (Hard Version)

题意 取一个数k   使a[i]上每一个数都可以整除k   0也可以

你可以移动a[i] 每移动一个单位向相邻单位消耗1时间 问最少消耗多少时间

如果不能  输出-1

#include <iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include <cstdio>
using namespace std;
typedef long long ll;
const int maxn=1000010;
int a[maxn];
long long sum[maxn];
int n;
inline ll solve(long long 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];
    }
    long long tot=sum[n],ans=0x7f7f7f7f7f7f7f7f;
    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!=0x7f7f7f7f7f7f7f7f) cout<<ans<<endl;
    else cout<<-1<<endl;
    return 0;
}
/*
15
1 1 1 0 0 0 1 1 1 0 0 0 1 1 1
*/
//0x7f7f7f7f7f7f7f7f

 

posted @ 2019-11-27 19:24  AAAzhuo  阅读(174)  评论(0)    收藏  举报