数列分块入门2


题面

题目描述:

给出一个长为 $n$ 的数列,以及 $n$ 个操作,操作涉及区间加法,询问区间内小于某个值 $x$ 的元素个数。

思路:

分块,我们维护每个块内的有序性,然后整块的二分查询。

代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 5e4 + 10;
int val[maxn],tag[maxn],n,pos[maxn],t;
vector<int>f[1000];
int L(int x){return (x - 1) * t + 1;}
int R(int x){return x * t;}
int read()
{
int out = 0;bool flag = 0;char ch = getchar();
while(!isdigit(ch)){flag = (ch == '-');ch = getchar();}
while(isdigit(ch)){out = (out << 1) + (out << 3) + ch - '0';ch = getchar();}
return flag?-out:out;
}
void reset(int x)
{
f[x].clear();
for(int i = L(x) ; i <= min(R(x),n) ; ++ i)f[x].push_back(val[i]);
sort(f[x].begin(),f[x].end());
}
void init()
{
t = sqrt(n);
for(int i = 1 ; i <= n ; ++ i)pos[i] = (i - 1) / t + 1,f[pos[i]].push_back(val[i]);
for(int i = 1 ; i <= pos[n] ; ++ i)sort(f[i].begin(),f[i].end());
}
void add(int l,int r,int c)
{
for(int i = l ; i <= min(R(pos[l]),r) ; ++ i)
val[i] += c;
reset(pos[l]);
if(pos[l] != pos[r]){
for(int i = L(pos[r]) ; i <= r ; ++ i)
val[i] += c;
reset(pos[r]);
}
for(int i = pos[l] + 1 ; i <= pos[r] - 1 ; ++ i)
tag[i] += c;
}
int ask(int l,int r,int w)
{
int ans = 0;
for(int i = l ; i <= min(R(pos[l]),r) ; ++ i)
if(val[i] + tag[pos[l]] < w)ans++;
if(pos[l] != pos[r]){
for(int i = L(pos[r]) ; i <= r ; ++ i)
if(val[i] + tag[pos[r]] < w)ans++;
}
for(int i = pos[l] + 1 ; i <= pos[r] - 1 ; ++ i)
{
int z = w - tag[i];
ans += lower_bound(f[i].begin(),f[i].end(),z) - f[i].begin();
}
return ans;
}
signed main()
{
n = read();
for(int i = 1 ; i <= n ; ++ i)val[i] = read();
init();
for(int i = 1 ; i <= n ; ++ i)
{
int opt,l,r,c;
opt = read();l = read();r = read();c = read();
if(opt == 0)add(l,r,c);
else printf("%lld\n",ask(l,r,c * c));//cout << ask(l,r,c * c) << endl;
}
return 0;
}