-
Notifications
You must be signed in to change notification settings - Fork 34
/
1188-Fast-Queries.cpp
135 lines (96 loc) · 1.49 KB
/
1188-Fast-Queries.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
struct node{
int l;
int r;
int i;
};
int ans;
struct node q[50005];
int a[100007];
int mod;
int counts[100007];
int fin[50007];
bool cmp(node x, node y)
{
if((x.l) / mod == (y.l / mod)) {
return x.r < y.r;
}
return x.l / mod < y.l / mod;
}
int update(int l)
{
counts[a[l]]++;
if(counts[a[l]] == 1) {
ans++;
}
}
int remove(int l)
{
counts[a[l]]--;
if(counts[a[l]] == 0) {
ans--;
}
}
int main()
{
int t;
int n;
int m;
int x;
int y;
scanf("%d", &t);
for (int cs = 1; cs <= t; cs++) {
scanf("%d",&n);
scanf("%d",&m);
mod = sqrt(n);
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
}
for (int i = 0; i < m; i++) {
scanf("%d", &x);
scanf("%d", &y);
x--;
y--;
q[i].l = x;
q[i].r = y;
q[i].i = i;
}
sort(q, q + m, cmp);
ans = 0;
int currentL;
int currentR;
currentL = 0;
currentR = 0;
memset(counts, 0, sizeof(counts));
for (int i = 0; i < m; i++) {
x = q[i].l;
y = q[i].r;
while(currentL < x) {
remove(currentL);
currentL++;
}
while(currentL > x) {
update(currentL - 1);
currentL--;
}
while(currentR <= y) {
update(currentR);
currentR++;
}
while(currentR > y+1) {
remove(currentR - 1);
currentR--;
}
fin[q[i].i] = ans;
}
printf("Case %d:\n", cs);
for (int i = 0; i < m; i++) {
printf("%d\n", fin[i]);
}
}
}