SPOJ3267【莫队算法/】

题意:
求区间不同数的个数。
思路:
离线处理(莫队/分块)

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL>PII;

const int N=2e5+10;
int n,q;
int a[N];
int tim[N];

struct asd{
    int Left,Right;
    int id;
    int res;
}e[N];
int pos[N];
bool cmp(asd x,asd y){
    if(pos[x.Left]==pos[y.Left]) return x.Right<y.Right;
    return x.Left<y.Left;
}

void solve(){
    int ans = 0;
    memset(tim,0,sizeof(tim));
    for(int i=0, L=1,R=0;i < q;i++){
        while(R < e[i].Right){
            R++;
            if(!tim[a[R]]) ans++;
            tim[a[R]]++;
        }
        while(R > e[i].Right){
            if(tim[a[R]] == 1) ans--;
            tim[a[R]]--;
            R--;
        }
        while(L > e[i].Left){
            L--;
            if(!tim[a[L]]) ans++;
            tim[a[L]]++;
        }
        while(L < e[i].Left){
            if(tim[a[L]] == 1) ans--;
            tim[a[L]]--;
            L++;
        }
        e[e[i].id].res = ans;
    }
}

vector<int>xs;
int main(){
    scanf("%d",&n);
    int block=(int)sqrt(n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        xs.push_back(a[i]);
        pos[i]=(i-1)/block+1;
    }
    sort(xs.begin(),xs.end());
    for(int i=1;i<=n;i++)
        a[i] = lower_bound(xs.begin(),xs.end(),a[i]) - xs.begin() + 1;

    scanf("%d",&q);
    for(int i=0;i<q;i++){
        scanf("%d%d",&e[i].Left,&e[i].Right);
        e[i].id = i;
    }
    sort(e,e+q,cmp);

    solve();
    for(int i=0;i<q;i++)
        printf("%d\n",e[i].res);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值