Bzoj 1878: [SDOI2009]HH的项链 莫队

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

思路:

  本题是莫队模板题, 关于莫队算法的时间复杂度证明, 这里不再赘述,(其实是我不会)。 Luogu最后两个点卡莫队, 我的代码各种优化能卡过。

  我们按莫队思路把询问排序, 维护一个桶代表每种颜色在当前l, r。中有多少个, 维护当前l, r,和ans, 每次暴力的更新到下一个问题需要的l, r。

#include <cmath>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510000;
const int M = 1010100;
int bkt[M];
int pos[N], a[N];
int n, m;
int nl, nr, na;
inline char nc() {
    static char buf[100000], *p1, *p2;
    return p1==p2&&(p2=(p1=buf)+fread(buf, 1, 100000, stdin), p1==p2)?EOF:*p1++;
}
int rd() {
    int x = 0;char c = nc();
    while(!isdigit(c)) c = nc();
    while(isdigit(c)) x=x*10+c-48, c=nc();
    return x;
}
struct Query {
    int l, r, id, ans;
    bool operator < (const Query x) const {
        if(pos[l] == pos[x.l])
            return pos[l]&1?r<x.r:r>x.r;
        return l<x.l;
    }
}q[N<<2];
bool cmp(Query a, Query b) {
    return a.id < b.id;
}
char pbuf[10000000] , *pp = pbuf;
inline void write(int x) {
    static int sta[35];
    int top = 0;
    if(!x)sta[++top]=0;
    while(x) sta[++top] = x % 10 , x /= 10;
    while(top)*pp++=sta[top--]^'0';
}
int main() {
    n=rd();for(int i=1;i<=n;i++)a[i]=rd();
    int siz=sqrt(n);int blk=n/siz,p=0;
    for(int i=1;i<=blk;i++)for(int j=1;j<=siz;j++)pos[++p]=i;
    if(p<n)for(int i=p+1;i<=n;i++)pos[i]=blk+1;
    m=rd();for(int i=1;i<=m;i++)q[i].l=rd(),q[i].r=rd(),q[i].id=i;
    sort(q+1, q+m+1);
    for(int i=1;i<=m;i++) {
        while(nl<q[i].l) {na-=(--bkt[a[nl++]]==0);}
        while(nl>q[i].l) {na+=(bkt[a[--nl]]++==0);}
        while(nr<q[i].r) {na+=(bkt[a[++nr]]++==0);}
        while(nr>q[i].r) {na-=(--bkt[a[nr--]]==0);}
        q[i].ans = na;
    }
    sort(q+1, q+m+1, cmp);for(int i=1;i<=m;i++)write(q[i].ans), *pp++='\n';
    fwrite(pbuf,1,pp-pbuf,stdout);
}
View Code

猜你喜欢

转载自www.cnblogs.com/Tobichi/p/9282203.html