SPOJ

题意:给你一堆数字,Q次查询l到r之间有多少个不同的数字

题解:莫队模版题(

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <cstring>
#include <iomanip>
#include <set>
#include<ctime>
//CLOCKS_PER_SEC
#define se second
#define fi first
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define Pii pair<int,int>
#define Pli pair<ll,int>
#define ull unsigned long long
#define pb push_back
#define fio ios::sync_with_stdio(false);cin.tie(0)
const int N=2e6+5;
const ull base=163;
const int INF=0x3f3f3f3f;
using namespace std;
int pos[N];
struct node {
    int l,r,id;
}Q[N];
int vis[N];
int a[N];
int L=1,R=0,ans=0;
int res[N];
bool cmp(node x,node y){
    if(pos[x.l]==pos[y.l]){
        return x.r<y.r;
    }
    return pos[x.l]<pos[y.l];
}
void add(int x){
    vis[a[x]]++;
    if(vis[a[x]]==1)ans++;
}
void del(int x){
    vis[a[x]]--;
    if(vis[a[x]]==0)ans--;
}
int main(){
    int t;
    scanf("%d",&t);
    int n=sqrt(t);
    for(int i=1;i<=t;i++){
        scanf("%d",&a[i]);
        pos[i]=i/n;
    }
    int q;
    scanf("%d",&q);
    for(int i=1;i<=q;i++){
        int l,r;
        scanf("%d%d",&l,&r);
        Q[i].l=l,Q[i].r=r,Q[i].id=i;
    }
    sort(Q+1,Q+1+q,cmp);
    for(int i=1;i<=q;i++){
        while(L<Q[i].l){
            del(L);
            L++;
        }
        while(L>Q[i].l){
            add(L-1);
            L--;
        }
        while(R<Q[i].r){
            R++;
            add(R);
        }
        while(R>Q[i].r){
            del(R);
            R--;
        }
        res[Q[i].id]=ans;
    }
    for(int i=1;i<=q;i++)printf("%d
",res[i]);
    return 0;
}
原文地址:https://www.cnblogs.com/Mrleon/p/8921865.html