原题链接
博客园没了以至于不得不用回CSDN
思路:
之前讲得很详细了GO
想补充的是,如果选定区间能整除maxn,那么说明有多个区间gcd左右都是maxn.存储下这些区间,前缀和预处理每个区间要加的点数.取最小值即可,
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 100010;
int n,a[N];
LL gcdl[N],gcdr[N],ans = (1ll<<63)-1;
LL b[N],sum[N],maxn;
vector<int> v;
LL gcd(LL c,LL d)
{
return d?gcd(d,c%d):c;
}
void read()
{
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
sort(a+1,a+n+1);
for(int i=1;i<=n;i++) b[i] = a[i]-a[i-1];//距离数组,从2开始.
for(int i=2;i<=n;i++) gcdl[i] = gcd(b[i],gcdl[i-1]);
for(int i=n;i>=2;i--) gcdr[i] = gcd(b[i],gcdr[i+1]);
for(int i=2;i<=n;i++)
maxn = max(gcd(gcdl[i-1],gcdr[i+1]),maxn);
for(int i=2;i<=n;i++)
if(gcd(gcdl[i-1],gcdr[i+1])==maxn) v.push_back(i);
}
void work()
{
for(int i=2;i<=n;i++)
{
if(b[i]%maxn==0) sum[i] = sum[i-1]+b[i]/maxn-1;
else sum[i] = sum[i-1];
}
for(int i=0;i<v.size();i++)
{
int idx = v[i];
ans = min(ans,sum[idx-1]+sum[n]-sum[idx]);
}
}
int main()
{
read();
work();
printf("%lld\n",ans);
return 0;
}