好题。
先考虑两个数 和 (),此时只会有三种决策:
- 。
- 。
- 。
至于 为何不优,考虑当 能够 时一定满足 ,而 ,因此将其变为 不仅不会减少次数还能得到更大的 。
那么,对于 的情况就会是某个前缀全选 剩下的后缀选 ,设这个位置为 ;而对于 ,又有 ,也就是说 是单调的。
值域 ,于是可以枚举 。直接维护较难,但是可以发现区间 中所有 都选的是 ,也就是说当 确定时可以用前缀和维护区间贡献。考虑二分 ,设 表示区间 内 的全选 的总和,此时 合法的前提就是 ,后者可以用 ST 表实现。
离线处理可以做到时间复杂度 ,空间复杂度 ,精细实现可以通过。
AC Code
#include <bits/stdc++.h>
using namespace std;
struct FastScanner {
static constexpr size_t BUFSIZE = 1 << 20;
char buf[BUFSIZE];
size_t pos = 0, len = 0;
inline char gc() {
if (pos == len) {
len = fread(buf, 1, BUFSIZE, stdin);
pos = 0;
if (!len) return 0;
}
return buf[pos++];
}
template <class T>
bool readInt(T &x) {
char c;
do {
c = gc();
if (!c) return false;
} while (c <= ' ');
bool neg = false;
if (c == '-') {
neg = true;
c = gc();
}
x = 0;
while (c >= '0' && c <= '9') {
x = x * 10 + (c - '0');
c = gc();
}
if (neg) x = -x;
return true;
}
} in;
struct FastOutput {
static constexpr size_t BUFSIZE = 1 << 20;
char buf[BUFSIZE];
size_t pos = 0;
~FastOutput() { flush(); }
inline void flush() {
if (pos) {
fwrite(buf, 1, pos, stdout);
pos = 0;
}
}
inline void pc(char c) {
if (pos == BUFSIZE) flush();
buf[pos++] = c;
}
inline void writeInt(long long x) {
if (x == 0) {
pc('0');
pc('\n');
return;
}
if (x < 0) {
pc('-');
// Avoid overflow for the smallest signed integer.
unsigned long long v = 0ull - static_cast<unsigned long long>(x);
char s[24]; int n = 0;
while (v) { s[n++] = char('0' + v % 10); v /= 10; }
while (n) pc(s[--n]);
pc('\n');
return;
}
unsigned long long v = static_cast<unsigned long long>(x);
char s[24]; int n = 0;
while (v) { s[n++] = char('0' + v % 10); v /= 10; }
while (n) pc(s[--n]);
pc('\n');
}
} out;
const int N = 2e5 + 5 , M = 17 , V = 100;
int n , q;
int a[N] , lg[N];
int f[M + 1][N] , ls[N] , s[N] , l[N] , r[N] , x[N] , cnt[N] , ans[N];
inline int get (int l , int r)
{
int Lg = lg[r - l + 1];
return min (f[Lg][l] , f[Lg][r - (1 << Lg) + 1]);
}
signed main ()
{
ios::sync_with_stdio (0);
cin.tie (0) , cout.tie (0);
in.readInt (n);
lg[0] = -1;
for (int i = 1;i <= n;i ++) in.readInt (a[i]) , lg[i] = lg[i >> 1] + 1;
in.readInt (q);
for (int i = 1;i <= q;i ++) in.readInt (l[i]) , in.readInt (r[i]);
for (int i = 1;i <= n;i ++) ls[i] = ls[i - 1] + a[i];
for (int k = 1;k <= V;k ++)
{
for (int i = 1;i <= n;i ++)
{
s[i] = s[i - 1] + (a[i] <= k ? -a[i] : a[i]);
cnt[i] = cnt[i - 1] + (a[i] == k);
f[0][i] = s[i];
}
for (int j = 1;j <= lg[n];j ++)
for (int i = 1;i + (1 << j) - 1 <= n;i ++)
f[j][i] = min (f[j - 1][i] , f[j - 1][i + (1 << j - 1)]);
for (int i = 1;i <= q;i ++) if (l[i] <= r[i])
{
int L = l[i] , R = r[i] + 1 , mid;
while (L < R)
{
mid = L + R >> 1;
int w = get (mid , r[i]) - s[mid - 1];
if (x[i] + ls[mid - 1] - ls[l[i] - 1] + w >= 0) R = mid;
else L = mid + 1;
}
if (R == r[i] + 1)
{
l[i] = r[i] + 1;
continue;
}
x[i] = x[i] + ls[R - 1] - ls[l[i] - 1];
l[i] = R;
ans[i] += cnt[r[i]] - cnt[R - 1];
}
for (int i = 1;i <= n;i ++) ls[i] = s[i];
}
for (int i = 1;i <= q;i ++) out.writeInt (ans[i]);
return 0;
}