bzoj4747 usaco counting haybales 题解 题解: 代码:

给出N(1≤N≤100,000)个数,和 Q(1≤Q≤100,000)个询问。每个询问包含两个整数A,B(0≤A≤B≤1,000,000,000)。对于每个询问,给出数值在A到B间的数有多少个(包含A与B)。

题解:

裸的线段树,先从小到大排序,维护一下每个区间最小值、最大值、长度,瞎搞。

代码:

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
#define REP(i, a, b) for(int i = a; i <= b; i ++)
#define REPG(i, x) for(int i = head[x]; i; i = g[i].nxt)
#define clr(x, y) memset(x, y, sizeof(x));
#define lson o << 1
#define rson o << 1 | 1
using namespace std;
typedef long long LL;
typedef double LF;
LL (LL a, LL b){return a > b ? a : b;}
LL Min(LL a, LL b){return a < b ? a : b;}
LL abs(LL x){return x > 0 ? x : -x;}
const int MAXN = 1e5 + 15;
struct Node{int mn, mx, len;}s[MAXN << 2];
int a[MAXN];
inline int read(){
int r = 0, z = 1; char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-') z = -1; ch = getchar();}
while(ch >= '0' && ch <= '9'){r = r * 10 + ch - '0'; ch = getchar();}
return r * z;
}
inline void up(int o){s[o] = (Node){min(s[lson].mn, s[rson].mn), max(s[lson].mx, s[rson].mx), s[lson].len + s[rson].len};}
void build(int o, int l, int r){
if(l == r){
s[o] = (Node){a[l], a[l], 1};
return ;
}
int mid = l + r >> 1;
build(lson, l, mid);
build(rson, mid + 1, r);
up(o);
}
int query(int o, int x, int y){
if(y < s[o].mn || x > s[o].mx) return 0;
if(x <= s[o].mn && s[o].mx <= y) return s[o].len;
int ret = 0;
if(x <= s[lson].mx) ret += query(lson, x, y);
if(y >= s[rson].mn) ret += query(rson, x, y);
return ret;
}
void work(){
int n = read(), q = read();
for(int i = 1; i <= n; i ++) a[i] = read();
sort(a + 1, a + n + 1);
build(1, 1, n);
while(q --){
int x = read(), y = read();
printf("%dn", query(1, x, y));
}
}
int main(){
work();
return 0;
}