You are given two arrays: an array a consisting of n zeros and an array b consisting of n integers.
You can apply the following operation to the array a an arbitrary number of times: choose some subsegment of a of length k and add the arithmetic progression 1,2,…,k to this subsegment — i. e. add 1 to the first element of the subsegment, 2 to the second element, and so on. The chosen subsegment should be inside the borders of the array a (i.e., if the left border of the chosen subsegment is l, then the condition 1≤l≤l+k−1≤n should be satisfied). Note that the progression added is always 1,2,…,k but not the k,k−1,…,1 or anything else (i.e., the leftmost element of the subsegment always increases by 1, the second element always increases by 2 and so on).
Your task is to find the minimum possible number of operations required to satisfy the condition ai≥bi for each i from 1 to n. Note that the condition ai≥bi should be satisfied for all elements at once.
Input
The first line of the input contains two integers n and k (1≤k≤n≤3⋅105) — the number of elements in both arrays and the length of the subsegment, respectively.
The second line of the input contains n integers b1,b2,…,bn (1≤bi≤1012), where bi is the i-th element of the array b.
Output
Print one integer — the minimum possible number of operations required to satisfy the condition ai≥bi for each i from 1 to n.
Examples
input
Copy
3 3
5 4 6
output
Copy
5
input
Copy
6 3
1 2 3 2 2 3
output
Copy
3
input
Copy
6 3
1 2 4 1 2 3
output
Copy
3
input
Copy
7 3
50 17 81 25 42 39 96
output
Copy
92
Note
Consider the first example. In this test, we don't really have any choice, so we need to add at least five progressions to make the first element equals 5. The array a becomes[5,10,15].
Consider the second example. In this test, let's add one progression on the segment [1;3] and two progressions on the segment [4;6]. Then, the array a becomes [1,2,3,2,4,6].
思路:
我们可以很清楚的知道要想次数最小那么肯定减的都是m,所以我们直接从后面开始,如果你联系m个值依次减下去枚举,那么他会超时,但是你有没有发现1,2,3,4,5这是一个等差数列,公差为1,我们倒着来a[n] -= 5k, a[n-1] -= 4k,你会发现这个公差是k,也就是说你会依次减少k,那么我们是不是可以维护这样一个数组,每次走的时候减去对应的值,这样一遍循环就可以了
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
typedef long long ll;
const int N=3e5+10;
int a[N];
int c[N];
int n,k;
signed main()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
cin>>a[i];
int del=0,add=0,ans=0;
for(int i=n;i>=1;i--)
{
del-=add;
add-=c[i+1];
k=min(i,k);
int x=max((a[i]-del-1+k)/k,0ll);
add+=x;
del+=x*k;
ans+=x;
c[i-k+1]=x;
}
cout << ans << '\n';
}