You are given an array a consisting of n positive integers, and an array b, with length n. Initially bi=0 for each 1≤i≤n.
In one move you can choose an integer i (1≤i≤n), and add ai to bi or subtract ai from bi. What is the minimum number of moves needed to make b increasing (that is, every element is strictly greater than every element before it)?
Input
The first line contains a single integer n (2≤n≤5000).
The second line contains n integers, a1, a2, …, an (1≤ai≤109) — the elements of the array a.
Output
Print a single integer, the minimum number of moves to make b increasing.
Examples
input
5
1 2 3 4 5
output
4
input
7
1 2 1 2 1 2 1
output
10
input
8
1 8 2 7 3 6 4 5
output
16
Note
Example 1: you can subtract a1 from b1, and add a3, a4, and a5 to b3, b4, and b5 respectively. The final array will be [−1, 0, 3, 4, 5] after 4 moves.
Example 2: you can reach [−3, −2, −1, 0, 1, 2, 3] in 10 moves.
题意:
b数组初始全为0
可以执行两种操作无限次:
1、bi=ai+bi;
2、bi=ai-bi;
即也可以不执行,让b数组变为一个严格单调递增的数组,求最小执行次数
思路: 通过样例我们可以得出一个大概的思路,其中一个数不变,仍为0,变换其两边得到所求数组是最优解(其中一边可没有,即也可以是从0开始的严格递增序列,也可以是以0结尾的严格递增序列),所以我们可以枚举0的位置,计算每个位置上所需的次数取最小值即可,那么如何计算次数,我们现在只有唯一确定的一个数0,那就从近到远来依次计算每个位置上的数,0左边的一定执行2操作,右边的一定执行1操作,对于右边来说,当前位置的值一定要比前一个位置大1,故我们计算+多少ai可以满足bi>=b(i-1)+1即可,左边同理
AC代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define int long long//ai可到1e9,三次加操作就会爆int
int a[5100],b[5100];
signed main()
{
int n,i,j,k;
scanf("%lld",&n);
for(i=1;i<=n;i++)
scanf("%lld",&a[i]);
int minn=1e18;//0x3f3f3f3f不够
for(i=1;i<=n;i++)
{
int sum=0;//记录操作次数
memset(b,0,sizeof(b));//每次计算完记得清空
for(j=i-1;j>=1;j--)//左边,由近到远
{
int x=b[j+1]+1;//此位置上的值最少为x
if(a[j]>=x)//如果ai本身就>=x,执行一次减操作即可
k=1;
else//不够的话要计算操作次数
k=x/a[j]+(x%a[j]!=0);//前半部分为x中有几个ai,即x*ai<=x,我们所要的结果应为x*ai>=x,故我们需要判断其是否有余数,有的话要+1,此为后半部分操作
b[j]=k*a[j];//赋值
sum+=k; //记录次数
}
for(j=i+1;j<=n;j++)//右边同上
{
int x=b[j-1]+1;
if(a[j]>=x)
k=1;
else
k=x/a[j]+(x%a[j]!=0);
b[j]=k*a[j];
sum+=k;
}
minn=min(minn,sum);//取最小值
}
printf("%lld\n",minn);
return 0;
}