TheAlgorithms-C-Plus-Plus/range_queries/MO.cpp

78 lines
1.1 KiB
C++
Raw Normal View History

2020-04-18 10:43:43 +08:00
#include <iostream>
2017-08-28 14:01:04 +08:00
using namespace std;
2019-08-21 10:10:08 +08:00
const int N = 1e6 + 5;
int a[N], bucket[N], cnt[N];
2017-08-28 14:01:04 +08:00
int bucket_size;
2019-08-21 10:10:08 +08:00
struct query
{
int l, r, i;
} q[N];
int ans = 0;
2017-08-28 14:01:04 +08:00
void add(int index)
{
cnt[a[index]]++;
2019-08-21 10:10:08 +08:00
if (cnt[a[index]] == 1)
2017-08-28 14:01:04 +08:00
ans++;
}
void remove(int index)
{
cnt[a[index]]--;
2019-08-21 10:10:08 +08:00
if (cnt[a[index]] == 0)
2017-08-28 14:01:04 +08:00
ans--;
}
bool mycmp(query x, query y)
{
2019-08-21 10:10:08 +08:00
if (x.l / bucket_size != y.l / bucket_size)
return x.l / bucket_size < y.l / bucket_size;
return x.r < y.r;
2017-08-28 14:01:04 +08:00
}
2019-08-21 10:10:08 +08:00
int main()
{
int n, t, i, j, k = 0;
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
2017-08-28 14:01:04 +08:00
bucket_size = ceil(sqrt(n));
2019-08-21 10:10:08 +08:00
scanf("%d", &t);
for (i = 0; i < t; i++)
2017-08-28 14:01:04 +08:00
{
2019-08-21 10:10:08 +08:00
scanf("%d %d", &q[i].l, &q[i].r);
q[i].l--;
q[i].r--;
2017-08-28 14:01:04 +08:00
q[i].i = i;
}
2019-08-21 10:10:08 +08:00
sort(q, q + t, mycmp);
int left = 0, right = 0;
for (i = 0; i < t; i++)
2017-08-28 14:01:04 +08:00
{
2019-08-21 10:10:08 +08:00
int L = q[i].l, R = q[i].r;
while (left < L)
2017-08-28 14:01:04 +08:00
{
remove(left);
left++;
}
2019-08-21 10:10:08 +08:00
while (left > L)
2017-08-28 14:01:04 +08:00
{
2019-08-21 10:10:08 +08:00
add(left - 1);
2017-08-28 14:01:04 +08:00
left--;
}
2019-08-21 10:10:08 +08:00
while (right <= R)
2017-08-28 14:01:04 +08:00
{
add(right);
right++;
}
2019-08-21 10:10:08 +08:00
while (right > R + 1)
2017-08-28 14:01:04 +08:00
{
2019-08-21 10:10:08 +08:00
remove(right - 1);
2017-08-28 14:01:04 +08:00
right--;
}
2019-08-21 10:10:08 +08:00
bucket[q[i].i] = ans;
2017-08-28 14:01:04 +08:00
}
2019-08-21 10:10:08 +08:00
for (i = 0; i < t; i++)
printf("%d\n", bucket[i]);
2017-08-28 14:01:04 +08:00
return 0;
}