luogu P1972 [SDOI2009]HH的项链 |树状数组 或 莫队

题目描述

HH 有一串由各种漂亮的贝壳组成的项链。HH 相信不同的贝壳会带来好运,所以每次散步完后,他都会随意取出一段贝壳,思考它们所表达的含义。HH 不断地收集新的贝壳,因此,他的项链变得越来越长。有一天,他突然提出了一个问题:某一段贝壳中,包含了多少种不同的贝壳?这个问题很难回答……因为项链实在是太长了。于是,他只好求助睿智的你,来解决这个问题。

输入格式

第一行:一个整数N,表示项链的长度。

第二行:N 个整数,表示依次表示项链中贝壳的编号(编号为0 到1000000 之间的整数)。

第三行:一个整数M,表示HH 询问的个数。

接下来M 行:每行两个整数,L 和R(1 ≤ L ≤ R ≤ N),表示询问的区间。

输出格式

M 行,每行一个整数,依次表示询问对应的答案。


莫队写法,90分 O(n*sqrt(n))

// luogu-judger-enable-o2
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
inline int read(){
    char x;
    while((x = getchar()) > '9' || x < '0') ;
    int u = x - '0';
    while((x = getchar()) <= '9' && x >= '0') u = (u << 3) + (u << 1) + x - '0';
    return u;
}
int n,m;
const int N=5e6+1;
struct E{
    int l,r;
    int idx;
}e[N];
int belog[N];
bool cmp(E a,E b)
{
    return (belog[a.l]^belog[b.l]) ? belog[a.l] < belog[b.l]:a.r < b.r;
}
int cnt[N],an[N],a[N];
int ans;
inline void add(int x){
    if(!cnt[a[x]])ans++;
    cnt[a[x]]++;
}
inline void del(int x){
    cnt[a[x]]--;
    if(!cnt[a[x]])ans--;
}
int main(){
    n=read();
    int size=pow(n,2.0/3.0);
    int bnum=ceil((double)n/size);
    for(int i=1;i<=bnum;i++)
    for(int j=(i-1)*size+1;j<=i*size;j++)
    belog[j]=i;
    for(int i=1;i<=n;i++)
    a[i]=read();
    m=read();
    for(int i=1;i<=m;i++)
    {
        e[i].l=read();
        e[i].r=read();
        e[i].idx=i;
    }
    sort(e+1,e+m+1,cmp);
    int l=e[1].l,r=e[1].r;
    for(int i=l;i<=r;i++)add(i);
    an[e[1].idx]=ans;
    for(int i=2;i<=m;i++)
    {
        while(l<e[i].l)del(l++);
        while(l>e[i].l)add(--l);
        while(r<e[i].r)add(++r);
        while(r>e[i].r)del(r--);
        an[e[i].idx]=ans;
    }
    for(int i=1;i<=m;i++)
    printf("%d\n",an[i]);
}

树状数组,100分 O(n*logn)

#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#define int long long
using namespace std;
const int N=1e6+10;
struct node{
    int l,r,id;
}e[N];
inline bool cmp(node t1,node t2){
    return t1.r<t2.r;
}
int a[N],ans[N],c[N];int n,m;
int last[N];
bool have[N];
inline void add(int x,int y){
    for(;x<=n;x+=x&(-x))c[x]+=y;
}
inline int sum(int x){
    int ans=0;
    for(;x;x-=x&(-x))ans+=c[x];
    return ans;
}
signed main(){
     cin>>n;
    for(int i=1;i<=n;i++)scanf("%lld",&a[i]); cin>>m; 
    for(int i=1;i<=m;i++)scanf("%lld%lld",&e[i].l,&e[i].r),e[i].id=i;
    sort(e+1,e+1+m,cmp);
    int top=0;
    for(int i=1;i<=m;i++){
        while(top<e[i].r){
            if(have[a[++top]])add(last[a[top]],-1);
            add(top,1);
            last[a[top]]=top;
            have[a[top]]=1;
        }
        ans[e[i].id]=sum(e[i].r)-sum(e[i].l-1);
    }
    for(int i=1;i<=m;i++)
    printf("%lld\n",ans[i]);
}

猜你喜欢

转载自www.cnblogs.com/naruto-mzx/p/11851127.html