BZOJ 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 <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int N = 1e6+10;
int num[N],cnt[N],pre[N];
int n,m,block;
long long ans[200005];
long long sum;

struct node {
    int l,r,id;
} a[N];

bool cmp(node a,node b) {
    if(pre[a.l] == pre[b.l]) {
        return a.r < b.r;
    }
    return a.l < b.l;
}

bool cmp2(node a,node b) {
    return a.id < b.id;
}

void init() {
    scanf("%d",&n);
    block = sqrt(n);
    for(int i=1; i<=n; i++) {
        scanf("%d",&num[i]);
        pre[i] = (i-1)/block+1;
    }
    scanf("%d",&m);
    for(int i=1; i<=m; i++) {
        scanf("%d%d",&a[i].l,&a[i].r);
        a[i].id = i;
    }
    sort(a+1,a+m+1,cmp);
}

void updata(int x,int d) {
    if(d == -1) {       //减去
        cnt[x] --;
        if(!cnt[x]) sum --;
    } else {            //加上
        if(!cnt[x]) sum ++;
        cnt[x] ++;
    }
}

void solve() {
    int L = 1,R = 0;
    sum = 0;
    for(int i=1; i<=m; i++) {
        while(L < a[i].l)   updata(num[L++],-1);
        while(L > a[i].l)   updata(num[--L], 1);
        while(R < a[i].r)   updata(num[++R], 1);
        while(R > a[i].r)   updata(num[R--],-1);
        ans[a[i].id] = sum;
    }
}

int main() {
    init();
    solve();
    sort(a+1,a+m+1,cmp2);
    for(int i=1; i<=m; i++) {
        printf("%lld\n",ans[a[i].id]);
    }

    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值