Bzoj4540: [Hnoi2016]序列
阿新 • • 發佈:2018-04-12
input 修改 size 樹狀 modify add operator () tor
題面
傳送門
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;
}
Bzoj4540: [Hnoi2016]序列