# BZOJ_1878_[SDOI2009]HH的项链_莫队

BZOJ_1878_[SDOI2009]HH的项链_莫队

## Description

HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运，所以每次散步 完后，他都会随意取出一

## Input

N ≤ 50000，M ≤ 200000。

## Output

M行，每行一个整数，依次表示询问对应的答案。

6
1 2 3 4 3 5
3
1 2
3 5
2 6

## Sample Output

2
2
4

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
#define N 500050
int h[1000050], pos[N], block, now, c[N], n, q;
struct A {
int s, t, id, ans;
}a[N];
bool cmp1(const A &x,const A &y) {
if(pos[x.s] == pos[y.s]) return x.t < y.t;
return pos[x.s] < pos[y.s];
}
bool cmp2(const A &x,const A &y) {return x.id < y.id; }
void pushup(int x, int sig) {
if(sig == 1) {
h[c[x]] ++;
if(h[c[x]] == 1) now ++;
}else {
h[c[x]] --;
if(h[c[x]] == 0) now --;
}
}
int main() {
scanf("%d", &n);
int i, j, l, r = 0;
for(i = 1;i <= n; ++ i) scanf("%d", &c[i]);
block = sqrt(n);
for(i = 1;i <= block; ++ i) {
l = r + 1;
r = i * block;
for(j = l;j <= r; ++ j) pos[j] = i;
}
if(r != n) {
l = r + 1;
r = n;
block ++;
for(i = l;i <= r; ++ i) pos[i] = block;
}
scanf("%d",&q);
for(i = 1;i <= q; ++ i) scanf("%d%d",&a[i].s,&a[i].t), a[i].id = i;
sort(a + 1, a + q + 1, cmp1);
for(l = 1, r = 0, i = 1;i <= q; ++ i) {
while(l < a[i].s) pushup(l, -1), ++ l;
while(l > a[i].s) pushup(l - 1, 1), -- l;
while(r > a[i].t) pushup(r, -1), -- r;
while(r < a[i].t) pushup(r + 1, 1), ++ r;
a[i].ans = now;
}
sort(a + 1, a + q + 1, cmp2);
for(i = 1;i <= q; ++ i) printf("%d\n", a[i].ans);
}


posted @ 2018-03-30 19:01  fcwww  阅读(116)  评论(0编辑  收藏  举报