【luogu 1972 / BZOJ 1878】HH的项链

【原题题面】传送门

【题解大意】

用来练莫队,但是莫队开了O2才苟过去。

动态维护区间内的种类,开cnt[]记录一下便于判断。

【code】

//莫队
#include<bits/stdc++.h>
using namespace std;
#define File ""
#define ll long long
inline void file(){
    freopen(File".in","r",stdin);
    freopen(File".out","w",stdout);
}
inline int read(){
    int x=0,f=1;   char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0'; ch=getchar();}
    return x*f;
}
const int mxn = 5e5+3;
const int size = 1e6+3;
int n,m,tot(0);
int Block;
int cnt[size],a[mxn],ans[mxn];
struct Q{
    int id,l,r;
}q[mxn];
/*
inline bool cmp1(Q x,Q y){
    return x.l==y.l ? x.r<y.r : x.l<y.l;
}
*/
inline bool cmp1(Q x,Q y){
    if((x.l/Block) ^ (y.l/Block)) return x.l < y.l;
    else if((x.l/Block) & 1) return x.r < y.r;
    else return x.r > y.r;
}
/*
inline bool cmp2(Q x,Q y){
    return x.id < y.id;
}
*/
inline void mov1(int x){
    tot -= (--cnt[a[x]]==0);
}
inline void mov2(int x){
    tot += (++cnt[a[x]]==1);
}
int main(){
//    file();
    n = read();
    for(int i = 1;i <= n; ++i) a[i] = read();
    m = read();
    Block = n*1.0/(sqrt(m*1.0*1/2));
    for(int i = 1;i <= m; ++i)
        q[i].id = i,q[i].l = read(),q[i].r = read();
    sort(q+1,q+m+1,cmp1);
    int l(1),r(0);
    for(int i = 1;i <= m; ++i){
        int ql = q[i].l,qr = q[i].r;
        while(ql < l) mov2(--l);
        while(ql > l) mov1(l++);
        while(qr < r) mov1(r--);
        while(qr > r) mov2(++r);
        ans[q[i].id] = tot;
    }
    for(int i = 1;i <= m; ++i) printf("%d\n",ans[i]);
    return 0;
}
/*
6
1 2 3 4 3 5
3
1 2
3 5
2 6
*/
View Code

 

posted @ 2019-05-21 16:22  ve-2021  阅读(129)  评论(0编辑  收藏  举报