链接:https://www.nowcoder.com/acm/contest/139/J

题目描述

Given a sequence of integers a1, a2, …, an and q pairs of integers (l1, r1), (l2, r2), …, (lq, rq), find count(l1, r1), count(l2, r2), …, count(lq, rq) where count(i, j) is the number of different integers among a1, a2, …, ai, aj, aj + 1, …, an.

输入描述

The input consists of several test cases and is terminated by end-of-file.
The first line of each test cases contains two integers n and q.
The second line contains n integers a1, a2, …, an.
The i-th of the following q lines contains two integers li and ri.

输出描述

For each test case, print q integers which denote the result.

  • 示例1
1
2
3
4
5
6
7
8
9
10
11
12
//输入
3 2
1 2 1
1 2
1 3
4 1
1 2 3 4
1 3
//输出
2
1
3

备注:

  • 1 ≤ n, q ≤ 105
  • 1 ≤ ai ≤ n
  • 1 ≤ li, ri ≤ n
  • The number of test cases does not exceed 10.

Code

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 <bits/stdc++.h>

using namespace std;

const int maxn = 2e5 + 10;
int a[maxn], C[maxn];
int n, qs, l, r;
int vis[maxn];
int ans[maxn];

int lowbit(int x) {
return x & -x;
}

int Query(int x) {
int res = 0;
while(x) {
res += C[x];
x -= lowbit(x);
}
return res;
}

void Add(int x, int val) {
while(x < maxn) {
C[x] += val;
x += lowbit(x);
}
}

struct node{
int l, r, id;
bool operator<(const node &b) const {
return r < b.r;
}
}q[maxn];

int main() {
while(~scanf("%d %d", &n, &qs)) {
memset(vis, 0, sizeof(vis));
memset(ans, 0, sizeof(0));
memset(C, 0, sizeof(C));
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
a[i + n] = a[i];
}
for(int i = 1; i <= qs; ++i) {
scanf("%d %d", &l, &r);
q[i].l = r;
q[i].r = n + l;
q[i].id = i;
}
sort(q + 1, q + qs + 1);
for(int i = 1, j = 1; i <= n + n && j <= qs; ++i) {
if(vis[a[i]]) Add(vis[a[i]], -1);
Add(i, 1); vis[a[i]] = i;
while(j <= qs && q[j].r == i) {
ans[q[j].id] = Query(q[j].r) - Query(q[j].l - 1);
++j;
}
}
for(int i = 1; i <= qs; ++i) {
printf("%d\n", ans[i]);
}
}
return 0;
}

Record

  • 2018年10月29日 完成题解