Bzoj4540: [Hnoi2016]序列
题面
Sol
处理出每个数\(a_i\)之前第一个比它小的数\(a_{l-1}\)和后面第一个比它小的数\(a_{r+1}\)
那么左端点在\([l,i]\)右端点在\([i,r]\)的区间的最小值都是\(a_i\)
把它看成是一个顶点\((l,r)\)和\((i,i)\)的矩形内的加法,每个数加上\(a_i\)
询问就是顶点\((l,l)\)和\((r,r)\)的矩形内求和
每列的每个位置的前缀和一定是个分段一次函数
那么就维护一下斜率和截距
然后就可以扫描线一波
可以用树状数组区间修改+查询
或者线段树区间修改+查询
# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
template <class Int>
IL void Input(RG Int &x){
RG int z = 1; RG char c = getchar(); x = 0;
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
x *= z;
}
const int maxn(1e5 + 5);
const int oo(1e9);
int n, q, p, m, l[maxn], r[maxn], sta[maxn];
ll ans[maxn], ck[2][maxn], cb[2][maxn], a[maxn];
struct Modify{
int x, l, r;
ll k, b;
IL int operator <(RG Modify b) const{
return x < b.x;
}
} mdy[maxn << 1];
struct Query{
int x, l, r, id, v;
IL int operator <(RG Query b) const{
return x < b.x;
}
} qry[maxn << 1];
IL void Add(RG ll *c, RG int x, RG ll v){
for(; x <= n; x += x & -x) c[x] += v;
}
IL ll Sum(RG ll *c, RG int x){
RG ll ret = 0;
for(; x; x -= x & -x) ret += c[x];
return ret;
}
IL void BITModify(RG int l, RG int r, RG ll vk, RG ll vb){
Add(ck[0], l, vk), Add(ck[0], r + 1, -vk);
Add(cb[0], l, vk * (1 - l)), Add(cb[0], r + 1, vk * r);
Add(ck[1], l, vb), Add(ck[1], r + 1, -vb);
Add(cb[1], l, vb * (1 - l)), Add(cb[1], r + 1, vb * r);
}
IL ll BITQuery(RG int x, RG int l, RG int r){
RG ll sum1, sum2, k, b;
sum1 = Sum(ck[0], l - 1) * (l - 1) + Sum(cb[0], l - 1);
sum2 = Sum(ck[0], r) * r + Sum(cb[0], r);
k = sum2 - sum1;
sum1 = Sum(ck[1], l - 1) * (l - 1) + Sum(cb[1], l - 1);
sum2 = Sum(ck[1], r) * r + Sum(cb[1], r);
b = sum2 - sum1;
return k * x + b;
}
int main(RG int argc, RG char* argv[]){
Input(n), Input(q), m = n << 1, p = q << 1;
a[0] = a[n + 1] = -oo, sta[1] = 0;
for(RG int i = 1, top = 1; i <= n; ++i){
l[i] = i, Input(a[i]);
while(top && a[i] < a[sta[top]]) --top;
if(top) l[i] = sta[top] + 1;
sta[++top] = i;
}
sta[1] = n + 1;
for(RG int i = n, top = 1; i; --i){
r[i] = i;
while(top && a[i] <= a[sta[top]]) --top;
if(top) r[i] = sta[top] - 1;
sta[++top] = i;
}
for(RG int i = 1; i <= n; ++i){
mdy[i] = (Modify){l[i], i, r[i], a[i], a[i] * (1 - l[i])};
mdy[i + n] = (Modify){i + 1, i, r[i], -a[i], a[i] * i};
}
sort(mdy + 1, mdy + m + 1);
for(RG int i = 1, l, r; i <= q; ++i){
Input(l), Input(r);
qry[i] = (Query){l - 1, l, r, i, -1};
qry[i + q] = (Query){r, l, r, i, 1};
}
sort(qry + 1, qry + p + 1);
for(RG int i = 1, j = 1; i <= p; ++i){
while(j <= m && mdy[j].x <= qry[i].x)
BITModify(mdy[j].l, mdy[j].r, mdy[j].k, mdy[j].b), ++j;
ans[qry[i].id] += BITQuery(qry[i].x, qry[i].l, qry[i].r) * qry[i].v;
}
for(RG int i = 1; i <= q; ++i) printf("%lld\n", ans[i]);
return 0;
}