题解:P11994 [JOIST 2025] 外郎糕 / Uiro
lovely_nst · · 题解
好题。
先考虑两个数
至于
那么,对于
值域
离线处理可以做到时间复杂度
:::success[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;
}
:::