题意:给出一个长度为n的序列,然后给出m个区间询问,求区间内数字出现次数等于该数字的个数;
思路:这题有很多种解法,之前用一种nsqrt(n)的暴力解法写过,这次用莫队算法(分块)再写一次,复杂度是(n+q)sqrt(n);
复制代码
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#include <cmath> #include <vector> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; const int N = 100010; int ans[N], num[N], L, R, cnt, M[N]; struct query { int l, r, idx, block; bool operator < (const query x) const { if(x.block == block) return r < x.r; return block < x.block; } }q[N]; void add(int x) { if(x > 100000) return ; M[x]++; int occur = M[x]; if(occur == x) cnt++; else if(occur == x + 1) cnt--; } void del(int x) { if(x > 100000) return ; M[x]--; int occur = M[x]; if(occur == x) cnt++; else if(occur == x - 1) cnt--; } int main() { int n, nq; cin >> n >> nq; int BLOCK_SIZE = (int)sqrt(n); for(int i = 1; i <= n; i++) scanf("%d", &num[i]); for(int i = 1; i <= nq; i++) { scanf("%d%d", &q[i].l, &q[i].r); q[i].idx = i, q[i].block = q[i].l / BLOCK_SIZE; } sort(q + 1, q + nq + 1); for(int i = q[1].l;i <= q[1].r;i++) add(num[i]); ans[q[1].idx] = cnt; L = q[1].l, R = q[1].r; for(int i = 2; i <= nq; i++) { for(int j = q[i].l; j < L; j++) add(num[j]); for(int j = L; j < q[i].l; j++) del(num[j]); for(int j = R + 1; j <= q[i].r; j++) add(num[j]); for(int j = q[i].r + 1; j <= R; j++) del(num[j]); L = q[i].l, R = q[i].r; ans[q[i].idx] = cnt; } for(int i = 1; i <= nq; i++) printf("%dn", ans[i]); return 0; }
最后
以上就是虚幻电话最近收集整理的关于Codeforces 220B(Little Elephant and Array)的全部内容,更多相关Codeforces内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复