8
11
2015
0

1878: [SDOI2009]HH的项链

1878: [SDOI2009]HH的项链

Description

HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此, 他的项链变得越来越长。有一天,他突然提出了一个问题:某一段贝壳中,包含了多少种不同 的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只好求助睿智的你,来解 决这个问题。

Input

第一行:一个整数N,表示项链的长度。 第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。 第三行:一个整数M,表示HH询问的个数。 接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。

Output

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

Sample Input

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

Sample Output

2
2
4

HINT


对于20%的数据,N ≤ 100,M ≤ 1000;
对于40%的数据,N ≤ 3000,M ≤ 200000;
对于100%的数据,N ≤ 50000,M ≤ 200000。

 

 

 

莫队算法

#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
int N,M,K;
int A[50010];
int cnt[1000010];
struct Mo{
    int k;
    int l,r,BL;
    int ans;
    Mo(){}
    Mo(int x,int a,int b){
        k=x; l=a; r=b; BL=(a-1)/K+1;
    }
}Que[200010];
bool cmp(const Mo &a,const Mo &b){
    return (a.BL<b.BL)||(a.BL==b.BL&&a.r<b.r);
}
bool cmp_k(const Mo &a,const Mo &b){
    return a.k<b.k;
}
int main(){
    scanf("%d",&N);
    K=sqrt(N);
    for (int i=1;i<=N;++i)
        scanf("%d",&A[i]);
    scanf("%d",&M);
    for (int i=1;i<=M;++i){
        int a,b;
        scanf("%d%d",&a,&b);
        Que[i]=Mo(i,a,b);
    }
    sort(Que+1,Que+M+1,cmp);
    int l=1,r=1;
    int ans=1;
    cnt[A[1]]=1;
    for (int i=1;i<=M;++i){
        for (;l<Que[i].l;)
            if (!(--cnt[A[l++]])) --ans;
        for (;l>Que[i].l;)
            if (!(cnt[A[--l]]++)) ++ans;
        for (;r<Que[i].r;)
            if (!(cnt[A[++r]]++)) ++ans;
        for (;r>Que[i].r;)
            if (!(--cnt[A[r--]])) --ans;
        Que[i].ans=ans;
    }
    sort(Que+1,Que+M+1,cmp_k);
    for (int i=1;i<=M;++i)
        printf("%d\n",Que[i].ans);
}
Category: BZOJ | Tags: bzoj 莫队算法 | Read Count: 251

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com