1878: [SDOI2009]HH的项链

Description

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

段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此他的项链变得越来越长。有一天,他突然提出了一

个问题:某一段贝壳中,包含了多少种不同的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只

好求助睿智的你,来解决这个问题。

Input

第一行:一个整数N,表示项链的长度。 

第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。 

第三行:一个整数M,表示HH询问的个数。 

接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。

N ≤ 50000,M ≤ 200000。

Output

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

Sample Input

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

Sample Output

2
2
4

#include<bits/stdc++.h>
using namespace std;


typedef long long ll;
#define rep(i,a,b) for(int i=a;i<b;i++)
#define per(i,a,b) for(int i=b-1;i>=a;i--)
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
const int maxn=5e4+10;
const int maxm=2e5+10;

int block;
struct Query{
    int i,l,r;
    bool operator<(const Query& obj)const{
        if(l/block==obj.l/block) return r<obj.r;
        return l/block<obj.l/block;
    }
}query[maxm];

int ans[maxm],color[maxm*5];
int cnt[maxm*5];


int main(){
    int n;
    scanf("%d",&n);
    rep(i,0,n)scanf("%d",&color[i]);

    block=sqrt(n);
    int m;
    scanf("%d",&m);
    rep(i,0,m){
        scanf("%d %d",&query[i].l,&query[i].r);
        query[i].l--,query[i].r--;
        query[i].i=i;
    }
    sort(query,query+m);
    int l=0,r=0,res=1;
    cnt[color[0]]++;
    rep(i,0,m){
        //!!!remove
        while(l<query[i].l){
            cnt[color[l]]--;
            if(!cnt[color[l]])res--;
            l++;
        }
        //!!!insert
        while(l>query[i].l){
            l--;
            if(!cnt[color[l]])res++;
            cnt[color[l]]++;
        }
        //!!!remove
        while(r>query[i].r){
            cnt[color[r]]--;
            if(!cnt[color[r]])res--;
            r--;
        }
        //!!!insert
        while(r<query[i].r){
            r++;
            if(!cnt[color[r]])res++;
            cnt[color[r]]++;
        }
        ans[query[i].i]=res;
    }
    //printf("n:%d m:%d\n",n,m);
    rep(i,0,m) printf("%d\n",ans[i]);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36424540/article/details/81392753