线段树维护差分序列
- 把问题看作是每次给 b 数组的一个长度为 k 的子段减去一个等差数列,直到所有数小于等于 0
- 因为子段长度严格为 k,因此对于当前 b 数组中最右边的大于 0 的元素,只能让它尽量作为子段右端点
- 为了模拟这个过程,在子区间中减去等差数列,可认为是在差分序列中减去定值
- 因此可以用线段树来模拟,需要给区间减定值(减等差数列)和求某个前缀和(求出当前最右边的元素值,看是否大于0)两个操作
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 3e5 + 10;
ll a[N], b[N];
struct Node
{
int l, r;
ll add, sum;
}tr[N*4];
int n, k;
void pushup(int u)
{
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void pushdown(int u)
{
Node &root = tr[u], &left = tr[u << 1], &right = tr[u << 1 | 1];
if (root.add)
{
left.add += root.add, right.add += root.add;
left.sum += root.add * (left.r - left.l + 1);
right.sum += root.add * (right.r - right.l + 1);
root.add = 0;
}
}
void build(int u, int l, int r)
{
if (l == r)
{
tr[u] = {l, r, 0, a[l]};
return;
}
tr[u] = {l, r, 0, 0};
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
ll query(int u, int l, int r)
{
if (tr[u].l >= l && tr[u].r <= r)
{
return tr[u].sum;
}
pushdown(u);
ll sum = 0;
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid)
sum += query(u << 1, l, r);
if (r > mid)
sum += query(u << 1 | 1, l, r);
return sum;
}
void modify(int u, int l, int r, ll k)
{
if (tr[u].l >= l && tr[u].r <= r)
{
tr[u].add += k;
tr[u].sum += k * (tr[u].r - tr[u].l + 1);
return;
}
pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid)
modify(u << 1, l, r, k);
if (r > mid)
modify(u << 1 | 1, l, r, k);
pushup(u);
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> k;
for (int i = 1; i <= n; i++)
cin >> b[i];
for (int i = 1; i <= n; i++)
a[i] = b[i] - b[i-1];
build(1, 1, n);
ll ans = 0;
for (int i = n; i >= 1; i--)
{
ll t = query(1, 1, i);
if (t <= 0)
continue;
int r = max(i, k), l = r - k + 1;
ll sub = i - l + 1;
ll cnt = (t + sub - 1) / sub;
modify(1, l, r, -cnt);
ans += cnt;
}
cout << ans << endl;
return 0;
}